theme.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251
  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.2.0 (2020-02-13)
  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 () {
  51. var args = [];
  52. for (var _i = 0; _i < arguments.length; _i++) {
  53. args[_i] = arguments[_i];
  54. }
  55. return !f.apply(null, args);
  56. };
  57. };
  58. var die = function (msg) {
  59. return function () {
  60. throw new Error(msg);
  61. };
  62. };
  63. var never = constant(false);
  64. var always = constant(true);
  65. var global$1 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  66. var __assign = function () {
  67. __assign = Object.assign || function __assign(t) {
  68. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69. s = arguments[i];
  70. for (var p in s)
  71. if (Object.prototype.hasOwnProperty.call(s, p))
  72. t[p] = s[p];
  73. }
  74. return t;
  75. };
  76. return __assign.apply(this, arguments);
  77. };
  78. function __rest(s, e) {
  79. var t = {};
  80. for (var p in s)
  81. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  82. t[p] = s[p];
  83. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  84. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  85. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  86. t[p[i]] = s[p[i]];
  87. }
  88. return t;
  89. }
  90. function __spreadArrays() {
  91. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  92. s += arguments[i].length;
  93. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  94. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  95. r[k] = a[j];
  96. return r;
  97. }
  98. var none = function () {
  99. return NONE;
  100. };
  101. var NONE = function () {
  102. var eq = function (o) {
  103. return o.isNone();
  104. };
  105. var call = function (thunk) {
  106. return thunk();
  107. };
  108. var id = function (n) {
  109. return n;
  110. };
  111. var me = {
  112. fold: function (n, s) {
  113. return n();
  114. },
  115. is: never,
  116. isSome: never,
  117. isNone: always,
  118. getOr: id,
  119. getOrThunk: call,
  120. getOrDie: function (msg) {
  121. throw new Error(msg || 'error: getOrDie called on none.');
  122. },
  123. getOrNull: constant(null),
  124. getOrUndefined: constant(undefined),
  125. or: id,
  126. orThunk: call,
  127. map: none,
  128. each: noop,
  129. bind: none,
  130. exists: never,
  131. forall: always,
  132. filter: none,
  133. equals: eq,
  134. equals_: eq,
  135. toArray: function () {
  136. return [];
  137. },
  138. toString: constant('none()')
  139. };
  140. if (Object.freeze) {
  141. Object.freeze(me);
  142. }
  143. return me;
  144. }();
  145. var some = function (a) {
  146. var constant_a = constant(a);
  147. var self = function () {
  148. return me;
  149. };
  150. var bind = function (f) {
  151. return f(a);
  152. };
  153. var me = {
  154. fold: function (n, s) {
  155. return s(a);
  156. },
  157. is: function (v) {
  158. return a === v;
  159. },
  160. isSome: always,
  161. isNone: never,
  162. getOr: constant_a,
  163. getOrThunk: constant_a,
  164. getOrDie: constant_a,
  165. getOrNull: constant_a,
  166. getOrUndefined: constant_a,
  167. or: self,
  168. orThunk: self,
  169. map: function (f) {
  170. return some(f(a));
  171. },
  172. each: function (f) {
  173. f(a);
  174. },
  175. bind: bind,
  176. exists: bind,
  177. forall: bind,
  178. filter: function (f) {
  179. return f(a) ? me : NONE;
  180. },
  181. toArray: function () {
  182. return [a];
  183. },
  184. toString: function () {
  185. return 'some(' + a + ')';
  186. },
  187. equals: function (o) {
  188. return o.is(a);
  189. },
  190. equals_: function (o, elementEq) {
  191. return o.fold(never, function (b) {
  192. return elementEq(a, b);
  193. });
  194. }
  195. };
  196. return me;
  197. };
  198. var from = function (value) {
  199. return value === null || value === undefined ? NONE : some(value);
  200. };
  201. var Option = {
  202. some: some,
  203. none: none,
  204. from: from
  205. };
  206. var value = function (o) {
  207. var is = function (v) {
  208. return o === v;
  209. };
  210. var or = function (opt) {
  211. return value(o);
  212. };
  213. var orThunk = function (f) {
  214. return value(o);
  215. };
  216. var map = function (f) {
  217. return value(f(o));
  218. };
  219. var mapError = function (f) {
  220. return value(o);
  221. };
  222. var each = function (f) {
  223. f(o);
  224. };
  225. var bind = function (f) {
  226. return f(o);
  227. };
  228. var fold = function (_, onValue) {
  229. return onValue(o);
  230. };
  231. var exists = function (f) {
  232. return f(o);
  233. };
  234. var forall = function (f) {
  235. return f(o);
  236. };
  237. var toOption = function () {
  238. return Option.some(o);
  239. };
  240. return {
  241. is: is,
  242. isValue: always,
  243. isError: never,
  244. getOr: constant(o),
  245. getOrThunk: constant(o),
  246. getOrDie: constant(o),
  247. or: or,
  248. orThunk: orThunk,
  249. fold: fold,
  250. map: map,
  251. mapError: mapError,
  252. each: each,
  253. bind: bind,
  254. exists: exists,
  255. forall: forall,
  256. toOption: toOption
  257. };
  258. };
  259. var error = function (message) {
  260. var getOrThunk = function (f) {
  261. return f();
  262. };
  263. var getOrDie = function () {
  264. return die(String(message))();
  265. };
  266. var or = function (opt) {
  267. return opt;
  268. };
  269. var orThunk = function (f) {
  270. return f();
  271. };
  272. var map = function (f) {
  273. return error(message);
  274. };
  275. var mapError = function (f) {
  276. return error(f(message));
  277. };
  278. var bind = function (f) {
  279. return error(message);
  280. };
  281. var fold = function (onError, _) {
  282. return onError(message);
  283. };
  284. return {
  285. is: never,
  286. isValue: never,
  287. isError: always,
  288. getOr: identity,
  289. getOrThunk: getOrThunk,
  290. getOrDie: getOrDie,
  291. or: or,
  292. orThunk: orThunk,
  293. fold: fold,
  294. map: map,
  295. mapError: mapError,
  296. each: noop,
  297. bind: bind,
  298. exists: never,
  299. forall: always,
  300. toOption: Option.none
  301. };
  302. };
  303. var fromOption = function (opt, err) {
  304. return opt.fold(function () {
  305. return error(err);
  306. }, value);
  307. };
  308. var Result = {
  309. value: value,
  310. error: error,
  311. fromOption: fromOption
  312. };
  313. var typeOf = function (x) {
  314. if (x === null) {
  315. return 'null';
  316. }
  317. var t = typeof x;
  318. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  319. return 'array';
  320. }
  321. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  322. return 'string';
  323. }
  324. return t;
  325. };
  326. var isType = function (type) {
  327. return function (value) {
  328. return typeOf(value) === type;
  329. };
  330. };
  331. var isString = isType('string');
  332. var isObject = isType('object');
  333. var isArray = isType('array');
  334. var isBoolean = isType('boolean');
  335. var isFunction = isType('function');
  336. var isNumber = isType('number');
  337. var isArrayOf = function (value, pred) {
  338. if (isArray(value)) {
  339. for (var i = 0, len = value.length; i < len; ++i) {
  340. if (pred(value[i]) !== true) {
  341. return false;
  342. }
  343. }
  344. return true;
  345. }
  346. return false;
  347. };
  348. var nativeSlice = Array.prototype.slice;
  349. var nativeIndexOf = Array.prototype.indexOf;
  350. var nativePush = Array.prototype.push;
  351. var rawIndexOf = function (ts, t) {
  352. return nativeIndexOf.call(ts, t);
  353. };
  354. var indexOf = function (xs, x) {
  355. var r = rawIndexOf(xs, x);
  356. return r === -1 ? Option.none() : Option.some(r);
  357. };
  358. var contains = function (xs, x) {
  359. return rawIndexOf(xs, x) > -1;
  360. };
  361. var exists = function (xs, pred) {
  362. for (var i = 0, len = xs.length; i < len; i++) {
  363. var x = xs[i];
  364. if (pred(x, i)) {
  365. return true;
  366. }
  367. }
  368. return false;
  369. };
  370. var range = function (num, f) {
  371. var r = [];
  372. for (var i = 0; i < num; i++) {
  373. r.push(f(i));
  374. }
  375. return r;
  376. };
  377. var chunk = function (array, size) {
  378. var r = [];
  379. for (var i = 0; i < array.length; i += size) {
  380. var s = nativeSlice.call(array, i, i + size);
  381. r.push(s);
  382. }
  383. return r;
  384. };
  385. var map = function (xs, f) {
  386. var len = xs.length;
  387. var r = new Array(len);
  388. for (var i = 0; i < len; i++) {
  389. var x = xs[i];
  390. r[i] = f(x, i);
  391. }
  392. return r;
  393. };
  394. var each = function (xs, f) {
  395. for (var i = 0, len = xs.length; i < len; i++) {
  396. var x = xs[i];
  397. f(x, i);
  398. }
  399. };
  400. var eachr = function (xs, f) {
  401. for (var i = xs.length - 1; i >= 0; i--) {
  402. var x = xs[i];
  403. f(x, i);
  404. }
  405. };
  406. var partition = function (xs, pred) {
  407. var pass = [];
  408. var fail = [];
  409. for (var i = 0, len = xs.length; i < len; i++) {
  410. var x = xs[i];
  411. var arr = pred(x, i) ? pass : fail;
  412. arr.push(x);
  413. }
  414. return {
  415. pass: pass,
  416. fail: fail
  417. };
  418. };
  419. var filter = function (xs, pred) {
  420. var r = [];
  421. for (var i = 0, len = xs.length; i < len; i++) {
  422. var x = xs[i];
  423. if (pred(x, i)) {
  424. r.push(x);
  425. }
  426. }
  427. return r;
  428. };
  429. var foldr = function (xs, f, acc) {
  430. eachr(xs, function (x) {
  431. acc = f(acc, x);
  432. });
  433. return acc;
  434. };
  435. var foldl = function (xs, f, acc) {
  436. each(xs, function (x) {
  437. acc = f(acc, x);
  438. });
  439. return acc;
  440. };
  441. var find = function (xs, pred) {
  442. for (var i = 0, len = xs.length; i < len; i++) {
  443. var x = xs[i];
  444. if (pred(x, i)) {
  445. return Option.some(x);
  446. }
  447. }
  448. return Option.none();
  449. };
  450. var findIndex = function (xs, pred) {
  451. for (var i = 0, len = xs.length; i < len; i++) {
  452. var x = xs[i];
  453. if (pred(x, i)) {
  454. return Option.some(i);
  455. }
  456. }
  457. return Option.none();
  458. };
  459. var flatten = function (xs) {
  460. var r = [];
  461. for (var i = 0, len = xs.length; i < len; ++i) {
  462. if (!isArray(xs[i])) {
  463. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  464. }
  465. nativePush.apply(r, xs[i]);
  466. }
  467. return r;
  468. };
  469. var bind = function (xs, f) {
  470. return flatten(map(xs, f));
  471. };
  472. var forall = function (xs, pred) {
  473. for (var i = 0, len = xs.length; i < len; ++i) {
  474. var x = xs[i];
  475. if (pred(x, i) !== true) {
  476. return false;
  477. }
  478. }
  479. return true;
  480. };
  481. var reverse = function (xs) {
  482. var r = nativeSlice.call(xs, 0);
  483. r.reverse();
  484. return r;
  485. };
  486. var difference = function (a1, a2) {
  487. return filter(a1, function (x) {
  488. return !contains(a2, x);
  489. });
  490. };
  491. var pure = function (x) {
  492. return [x];
  493. };
  494. var sort = function (xs, comparator) {
  495. var copy = nativeSlice.call(xs, 0);
  496. copy.sort(comparator);
  497. return copy;
  498. };
  499. var head = function (xs) {
  500. return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  501. };
  502. var last = function (xs) {
  503. return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  504. };
  505. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  506. return nativeSlice.call(x);
  507. };
  508. var findMap = function (arr, f) {
  509. for (var i = 0; i < arr.length; i++) {
  510. var r = f(arr[i], i);
  511. if (r.isSome()) {
  512. return r;
  513. }
  514. }
  515. return Option.none();
  516. };
  517. var keys = Object.keys;
  518. var hasOwnProperty = Object.hasOwnProperty;
  519. var each$1 = function (obj, f) {
  520. var props = keys(obj);
  521. for (var k = 0, len = props.length; k < len; k++) {
  522. var i = props[k];
  523. var x = obj[i];
  524. f(x, i);
  525. }
  526. };
  527. var map$1 = function (obj, f) {
  528. return tupleMap(obj, function (x, i) {
  529. return {
  530. k: i,
  531. v: f(x, i)
  532. };
  533. });
  534. };
  535. var tupleMap = function (obj, f) {
  536. var r = {};
  537. each$1(obj, function (x, i) {
  538. var tuple = f(x, i);
  539. r[tuple.k] = tuple.v;
  540. });
  541. return r;
  542. };
  543. var mapToArray = function (obj, f) {
  544. var r = [];
  545. each$1(obj, function (value, name) {
  546. r.push(f(value, name));
  547. });
  548. return r;
  549. };
  550. var find$1 = function (obj, pred) {
  551. var props = keys(obj);
  552. for (var k = 0, len = props.length; k < len; k++) {
  553. var i = props[k];
  554. var x = obj[i];
  555. if (pred(x, i, obj)) {
  556. return Option.some(x);
  557. }
  558. }
  559. return Option.none();
  560. };
  561. var values = function (obj) {
  562. return mapToArray(obj, function (v) {
  563. return v;
  564. });
  565. };
  566. var get = function (obj, key) {
  567. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  568. };
  569. var has = function (obj, key) {
  570. return hasOwnProperty.call(obj, key);
  571. };
  572. var hasNonNullableKey = function (obj, key) {
  573. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  574. };
  575. var generate = function (cases) {
  576. if (!isArray(cases)) {
  577. throw new Error('cases must be an array');
  578. }
  579. if (cases.length === 0) {
  580. throw new Error('there must be at least one case');
  581. }
  582. var constructors = [];
  583. var adt = {};
  584. each(cases, function (acase, count) {
  585. var keys$1 = keys(acase);
  586. if (keys$1.length !== 1) {
  587. throw new Error('one and only one name per case');
  588. }
  589. var key = keys$1[0];
  590. var value = acase[key];
  591. if (adt[key] !== undefined) {
  592. throw new Error('duplicate key detected:' + key);
  593. } else if (key === 'cata') {
  594. throw new Error('cannot have a case named cata (sorry)');
  595. } else if (!isArray(value)) {
  596. throw new Error('case arguments must be an array');
  597. }
  598. constructors.push(key);
  599. adt[key] = function () {
  600. var argLength = arguments.length;
  601. if (argLength !== value.length) {
  602. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  603. }
  604. var args = new Array(argLength);
  605. for (var i = 0; i < args.length; i++) {
  606. args[i] = arguments[i];
  607. }
  608. var match = function (branches) {
  609. var branchKeys = keys(branches);
  610. if (constructors.length !== branchKeys.length) {
  611. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  612. }
  613. var allReqd = forall(constructors, function (reqKey) {
  614. return contains(branchKeys, reqKey);
  615. });
  616. if (!allReqd) {
  617. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  618. }
  619. return branches[key].apply(null, args);
  620. };
  621. return {
  622. fold: function () {
  623. if (arguments.length !== cases.length) {
  624. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  625. }
  626. var target = arguments[count];
  627. return target.apply(null, args);
  628. },
  629. match: match,
  630. log: function (label) {
  631. domGlobals.console.log(label, {
  632. constructors: constructors,
  633. constructor: key,
  634. params: args
  635. });
  636. }
  637. };
  638. };
  639. });
  640. return adt;
  641. };
  642. var Adt = { generate: generate };
  643. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  644. var shallow = function (old, nu) {
  645. return nu;
  646. };
  647. var deep = function (old, nu) {
  648. var bothObjects = isObject(old) && isObject(nu);
  649. return bothObjects ? deepMerge(old, nu) : nu;
  650. };
  651. var baseMerge = function (merger) {
  652. return function () {
  653. var objects = new Array(arguments.length);
  654. for (var i = 0; i < objects.length; i++) {
  655. objects[i] = arguments[i];
  656. }
  657. if (objects.length === 0) {
  658. throw new Error('Can\'t merge zero objects');
  659. }
  660. var ret = {};
  661. for (var j = 0; j < objects.length; j++) {
  662. var curObject = objects[j];
  663. for (var key in curObject) {
  664. if (hasOwnProperty$1.call(curObject, key)) {
  665. ret[key] = merger(ret[key], curObject[key]);
  666. }
  667. }
  668. }
  669. return ret;
  670. };
  671. };
  672. var deepMerge = baseMerge(deep);
  673. var merge = baseMerge(shallow);
  674. var cached = function (f) {
  675. var called = false;
  676. var r;
  677. return function () {
  678. var args = [];
  679. for (var _i = 0; _i < arguments.length; _i++) {
  680. args[_i] = arguments[_i];
  681. }
  682. if (!called) {
  683. called = true;
  684. r = f.apply(null, args);
  685. }
  686. return r;
  687. };
  688. };
  689. var SimpleResultType;
  690. (function (SimpleResultType) {
  691. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  692. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  693. }(SimpleResultType || (SimpleResultType = {})));
  694. var fold = function (res, onError, onValue) {
  695. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  696. };
  697. var partition$1 = function (results) {
  698. var values = [];
  699. var errors = [];
  700. each(results, function (obj) {
  701. fold(obj, function (err) {
  702. return errors.push(err);
  703. }, function (val) {
  704. return values.push(val);
  705. });
  706. });
  707. return {
  708. values: values,
  709. errors: errors
  710. };
  711. };
  712. var mapError = function (res, f) {
  713. if (res.stype === SimpleResultType.Error) {
  714. return {
  715. stype: SimpleResultType.Error,
  716. serror: f(res.serror)
  717. };
  718. } else {
  719. return res;
  720. }
  721. };
  722. var map$2 = function (res, f) {
  723. if (res.stype === SimpleResultType.Value) {
  724. return {
  725. stype: SimpleResultType.Value,
  726. svalue: f(res.svalue)
  727. };
  728. } else {
  729. return res;
  730. }
  731. };
  732. var bind$1 = function (res, f) {
  733. if (res.stype === SimpleResultType.Value) {
  734. return f(res.svalue);
  735. } else {
  736. return res;
  737. }
  738. };
  739. var bindError = function (res, f) {
  740. if (res.stype === SimpleResultType.Error) {
  741. return f(res.serror);
  742. } else {
  743. return res;
  744. }
  745. };
  746. var svalue = function (v) {
  747. return {
  748. stype: SimpleResultType.Value,
  749. svalue: v
  750. };
  751. };
  752. var serror = function (e) {
  753. return {
  754. stype: SimpleResultType.Error,
  755. serror: e
  756. };
  757. };
  758. var toResult = function (res) {
  759. return fold(res, Result.error, Result.value);
  760. };
  761. var fromResult = function (res) {
  762. return res.fold(serror, svalue);
  763. };
  764. var SimpleResult = {
  765. fromResult: fromResult,
  766. toResult: toResult,
  767. svalue: svalue,
  768. partition: partition$1,
  769. serror: serror,
  770. bind: bind$1,
  771. bindError: bindError,
  772. map: map$2,
  773. mapError: mapError,
  774. fold: fold
  775. };
  776. var adt = Adt.generate([
  777. { strict: [] },
  778. { defaultedThunk: ['fallbackThunk'] },
  779. { asOption: [] },
  780. { asDefaultedOptionThunk: ['fallbackThunk'] },
  781. { mergeWithThunk: ['baseThunk'] }
  782. ]);
  783. var defaulted = function (fallback) {
  784. return adt.defaultedThunk(constant(fallback));
  785. };
  786. var mergeWith = function (base) {
  787. return adt.mergeWithThunk(constant(base));
  788. };
  789. var strict = adt.strict;
  790. var asOption = adt.asOption;
  791. var defaultedThunk = adt.defaultedThunk;
  792. var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
  793. var mergeWithThunk = adt.mergeWithThunk;
  794. var exclude = function (obj, fields) {
  795. var r = {};
  796. each$1(obj, function (v, k) {
  797. if (!contains(fields, k)) {
  798. r[k] = v;
  799. }
  800. });
  801. return r;
  802. };
  803. var wrap = function (key, value) {
  804. var _a;
  805. return _a = {}, _a[key] = value, _a;
  806. };
  807. var wrapAll = function (keyvalues) {
  808. var r = {};
  809. each(keyvalues, function (kv) {
  810. r[kv.key] = kv.value;
  811. });
  812. return r;
  813. };
  814. var comparison = Adt.generate([
  815. {
  816. bothErrors: [
  817. 'error1',
  818. 'error2'
  819. ]
  820. },
  821. {
  822. firstError: [
  823. 'error1',
  824. 'value2'
  825. ]
  826. },
  827. {
  828. secondError: [
  829. 'value1',
  830. 'error2'
  831. ]
  832. },
  833. {
  834. bothValues: [
  835. 'value1',
  836. 'value2'
  837. ]
  838. }
  839. ]);
  840. var partition$2 = function (results) {
  841. var errors = [];
  842. var values = [];
  843. each(results, function (result) {
  844. result.fold(function (err) {
  845. errors.push(err);
  846. }, function (value) {
  847. values.push(value);
  848. });
  849. });
  850. return {
  851. errors: errors,
  852. values: values
  853. };
  854. };
  855. var exclude$1 = function (obj, fields) {
  856. return exclude(obj, fields);
  857. };
  858. var wrap$1 = function (key, value) {
  859. return wrap(key, value);
  860. };
  861. var wrapAll$1 = function (keyvalues) {
  862. return wrapAll(keyvalues);
  863. };
  864. var mergeValues = function (values, base) {
  865. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  866. };
  867. var mergeErrors = function (errors) {
  868. return Result.error(flatten(errors));
  869. };
  870. var consolidate = function (objs, base) {
  871. var partitions = partition$2(objs);
  872. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  873. };
  874. var mergeValues$1 = function (values, base) {
  875. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  876. };
  877. var mergeErrors$1 = function (errors) {
  878. return compose(SimpleResult.serror, flatten)(errors);
  879. };
  880. var consolidateObj = function (objects, base) {
  881. var partition = SimpleResult.partition(objects);
  882. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  883. };
  884. var consolidateArr = function (objects) {
  885. var partitions = SimpleResult.partition(objects);
  886. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  887. };
  888. var ResultCombine = {
  889. consolidateObj: consolidateObj,
  890. consolidateArr: consolidateArr
  891. };
  892. var formatObj = function (input) {
  893. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  894. };
  895. var formatErrors = function (errors) {
  896. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  897. path: [],
  898. getErrorInfo: function () {
  899. return '... (only showing first ten failures)';
  900. }
  901. }]) : errors;
  902. return map(es, function (e) {
  903. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  904. });
  905. };
  906. var nu = function (path, getErrorInfo) {
  907. return SimpleResult.serror([{
  908. path: path,
  909. getErrorInfo: getErrorInfo
  910. }]);
  911. };
  912. var missingStrict = function (path, key, obj) {
  913. return nu(path, function () {
  914. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  915. });
  916. };
  917. var missingKey = function (path, key) {
  918. return nu(path, function () {
  919. return 'Choice schema did not contain choice key: "' + key + '"';
  920. });
  921. };
  922. var missingBranch = function (path, branches, branch) {
  923. return nu(path, function () {
  924. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  925. });
  926. };
  927. var unsupportedFields = function (path, unsupported) {
  928. return nu(path, function () {
  929. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  930. });
  931. };
  932. var custom = function (path, err) {
  933. return nu(path, function () {
  934. return err;
  935. });
  936. };
  937. var adt$1 = Adt.generate([
  938. {
  939. field: [
  940. 'key',
  941. 'okey',
  942. 'presence',
  943. 'prop'
  944. ]
  945. },
  946. {
  947. state: [
  948. 'okey',
  949. 'instantiator'
  950. ]
  951. }
  952. ]);
  953. var strictAccess = function (path, obj, key) {
  954. return get(obj, key).fold(function () {
  955. return missingStrict(path, key, obj);
  956. }, SimpleResult.svalue);
  957. };
  958. var fallbackAccess = function (obj, key, fallbackThunk) {
  959. var v = get(obj, key).fold(function () {
  960. return fallbackThunk(obj);
  961. }, identity);
  962. return SimpleResult.svalue(v);
  963. };
  964. var optionAccess = function (obj, key) {
  965. return SimpleResult.svalue(get(obj, key));
  966. };
  967. var optionDefaultedAccess = function (obj, key, fallback) {
  968. var opt = get(obj, key).map(function (val) {
  969. return val === true ? fallback(obj) : val;
  970. });
  971. return SimpleResult.svalue(opt);
  972. };
  973. var cExtractOne = function (path, obj, field, strength) {
  974. return field.fold(function (key, okey, presence, prop) {
  975. var bundle = function (av) {
  976. var result = prop.extract(path.concat([key]), strength, av);
  977. return SimpleResult.map(result, function (res) {
  978. return wrap(okey, strength(res));
  979. });
  980. };
  981. var bundleAsOption = function (optValue) {
  982. return optValue.fold(function () {
  983. var outcome = wrap(okey, strength(Option.none()));
  984. return SimpleResult.svalue(outcome);
  985. }, function (ov) {
  986. var result = prop.extract(path.concat([key]), strength, ov);
  987. return SimpleResult.map(result, function (res) {
  988. return wrap(okey, strength(Option.some(res)));
  989. });
  990. });
  991. };
  992. return function () {
  993. return presence.fold(function () {
  994. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  995. }, function (fallbackThunk) {
  996. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  997. }, function () {
  998. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  999. }, function (fallbackThunk) {
  1000. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1001. }, function (baseThunk) {
  1002. var base = baseThunk(obj);
  1003. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1004. return deepMerge(base, v);
  1005. });
  1006. return SimpleResult.bind(result, bundle);
  1007. });
  1008. }();
  1009. }, function (okey, instantiator) {
  1010. var state = instantiator(obj);
  1011. return SimpleResult.svalue(wrap(okey, strength(state)));
  1012. });
  1013. };
  1014. var cExtract = function (path, obj, fields, strength) {
  1015. var results = map(fields, function (field) {
  1016. return cExtractOne(path, obj, field, strength);
  1017. });
  1018. return ResultCombine.consolidateObj(results, {});
  1019. };
  1020. var valueThunk = function (getDelegate) {
  1021. var extract = function (path, strength, val) {
  1022. return getDelegate().extract(path, strength, val);
  1023. };
  1024. var toString = function () {
  1025. return getDelegate().toString();
  1026. };
  1027. return {
  1028. extract: extract,
  1029. toString: toString
  1030. };
  1031. };
  1032. var value$1 = function (validator) {
  1033. var extract = function (path, strength, val) {
  1034. return SimpleResult.bindError(validator(val, strength), function (err) {
  1035. return custom(path, err);
  1036. });
  1037. };
  1038. var toString = function () {
  1039. return 'val';
  1040. };
  1041. return {
  1042. extract: extract,
  1043. toString: toString
  1044. };
  1045. };
  1046. var getSetKeys = function (obj) {
  1047. var keys$1 = keys(obj);
  1048. return filter(keys$1, function (k) {
  1049. return hasNonNullableKey(obj, k);
  1050. });
  1051. };
  1052. var objOfOnly = function (fields) {
  1053. var delegate = objOf(fields);
  1054. var fieldNames = foldr(fields, function (acc, f) {
  1055. return f.fold(function (key) {
  1056. return deepMerge(acc, wrap$1(key, true));
  1057. }, constant(acc));
  1058. }, {});
  1059. var extract = function (path, strength, o) {
  1060. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1061. var extra = filter(keys, function (k) {
  1062. return !hasNonNullableKey(fieldNames, k);
  1063. });
  1064. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1065. };
  1066. return {
  1067. extract: extract,
  1068. toString: delegate.toString
  1069. };
  1070. };
  1071. var objOf = function (fields) {
  1072. var extract = function (path, strength, o) {
  1073. return cExtract(path, o, fields, strength);
  1074. };
  1075. var toString = function () {
  1076. var fieldStrings = map(fields, function (field) {
  1077. return field.fold(function (key, okey, presence, prop) {
  1078. return key + ' -> ' + prop.toString();
  1079. }, function (okey, instantiator) {
  1080. return 'state(' + okey + ')';
  1081. });
  1082. });
  1083. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1084. };
  1085. return {
  1086. extract: extract,
  1087. toString: toString
  1088. };
  1089. };
  1090. var arrOf = function (prop) {
  1091. var extract = function (path, strength, array) {
  1092. var results = map(array, function (a, i) {
  1093. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1094. });
  1095. return ResultCombine.consolidateArr(results);
  1096. };
  1097. var toString = function () {
  1098. return 'array(' + prop.toString() + ')';
  1099. };
  1100. return {
  1101. extract: extract,
  1102. toString: toString
  1103. };
  1104. };
  1105. var oneOf = function (props) {
  1106. var extract = function (path, strength, val) {
  1107. var errors = [];
  1108. for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
  1109. var prop = props_1[_i];
  1110. var res = prop.extract(path, strength, val);
  1111. if (res.stype === SimpleResultType.Value) {
  1112. return res;
  1113. }
  1114. errors.push(res);
  1115. }
  1116. return ResultCombine.consolidateArr(errors);
  1117. };
  1118. var toString = function () {
  1119. return 'oneOf(' + map(props, function (prop) {
  1120. return prop.toString();
  1121. }).join(', ') + ')';
  1122. };
  1123. return {
  1124. extract: extract,
  1125. toString: toString
  1126. };
  1127. };
  1128. var setOf = function (validator, prop) {
  1129. var validateKeys = function (path, keys) {
  1130. return arrOf(value$1(validator)).extract(path, identity, keys);
  1131. };
  1132. var extract = function (path, strength, o) {
  1133. var keys$1 = keys(o);
  1134. var validatedKeys = validateKeys(path, keys$1);
  1135. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1136. var schema = map(validKeys, function (vk) {
  1137. return adt$1.field(vk, vk, strict(), prop);
  1138. });
  1139. return objOf(schema).extract(path, strength, o);
  1140. });
  1141. };
  1142. var toString = function () {
  1143. return 'setOf(' + prop.toString() + ')';
  1144. };
  1145. return {
  1146. extract: extract,
  1147. toString: toString
  1148. };
  1149. };
  1150. var anyValue = constant(value$1(SimpleResult.svalue));
  1151. var arrOfObj = compose(arrOf, objOf);
  1152. var state = adt$1.state;
  1153. var field = adt$1.field;
  1154. var chooseFrom = function (path, strength, input, branches, ch) {
  1155. var fields = get(branches, ch);
  1156. return fields.fold(function () {
  1157. return missingBranch(path, branches, ch);
  1158. }, function (vp) {
  1159. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1160. });
  1161. };
  1162. var choose = function (key, branches) {
  1163. var extract = function (path, strength, input) {
  1164. var choice = get(input, key);
  1165. return choice.fold(function () {
  1166. return missingKey(path, key);
  1167. }, function (chosen) {
  1168. return chooseFrom(path, strength, input, branches, chosen);
  1169. });
  1170. };
  1171. var toString = function () {
  1172. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1173. };
  1174. return {
  1175. extract: extract,
  1176. toString: toString
  1177. };
  1178. };
  1179. var _anyValue = value$1(SimpleResult.svalue);
  1180. var arrOfObj$1 = function (objFields) {
  1181. return arrOfObj(objFields);
  1182. };
  1183. var arrOfVal = function () {
  1184. return arrOf(_anyValue);
  1185. };
  1186. var valueThunkOf = valueThunk;
  1187. var valueOf = function (validator) {
  1188. return value$1(function (v) {
  1189. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1190. });
  1191. };
  1192. var setOf$1 = function (validator, prop) {
  1193. return setOf(function (v) {
  1194. return SimpleResult.fromResult(validator(v));
  1195. }, prop);
  1196. };
  1197. var extract = function (label, prop, strength, obj) {
  1198. var res = prop.extract([label], strength, obj);
  1199. return SimpleResult.mapError(res, function (errs) {
  1200. return {
  1201. input: obj,
  1202. errors: errs
  1203. };
  1204. });
  1205. };
  1206. var asRaw = function (label, prop, obj) {
  1207. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1208. };
  1209. var getOrDie = function (extraction) {
  1210. return extraction.fold(function (errInfo) {
  1211. throw new Error(formatError(errInfo));
  1212. }, identity);
  1213. };
  1214. var asRawOrDie = function (label, prop, obj) {
  1215. return getOrDie(asRaw(label, prop, obj));
  1216. };
  1217. var formatError = function (errInfo) {
  1218. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1219. };
  1220. var chooseProcessor = function (key, branches) {
  1221. return choose(key, branches);
  1222. };
  1223. var choose$1 = function (key, branches) {
  1224. return choose(key, map$1(branches, objOf));
  1225. };
  1226. var anyValue$1 = constant(_anyValue);
  1227. var typedValue = function (validator, expectedType) {
  1228. return value$1(function (a) {
  1229. var actualType = typeof a;
  1230. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1231. });
  1232. };
  1233. var number = typedValue(isNumber, 'number');
  1234. var string = typedValue(isString, 'string');
  1235. var boolean = typedValue(isBoolean, 'boolean');
  1236. var functionProcessor = typedValue(isFunction, 'function');
  1237. var isPostMessageable = function (val) {
  1238. var every = function (iter, callbackFn) {
  1239. var result = iter.next();
  1240. while (!result.done) {
  1241. if (!callbackFn(result.value)) {
  1242. return false;
  1243. }
  1244. result = iter.next();
  1245. }
  1246. return true;
  1247. };
  1248. if (Object(val) !== val) {
  1249. return true;
  1250. }
  1251. switch ({}.toString.call(val).slice(8, -1)) {
  1252. case 'Boolean':
  1253. case 'Number':
  1254. case 'String':
  1255. case 'Date':
  1256. case 'RegExp':
  1257. case 'Blob':
  1258. case 'FileList':
  1259. case 'ImageData':
  1260. case 'ImageBitmap':
  1261. case 'ArrayBuffer':
  1262. return true;
  1263. case 'Array':
  1264. case 'Object':
  1265. return Object.keys(val).every(function (prop) {
  1266. return isPostMessageable(val[prop]);
  1267. });
  1268. case 'Map':
  1269. return every(val.keys(), isPostMessageable) && every(val.values(), isPostMessageable);
  1270. case 'Set':
  1271. return every(val.keys(), isPostMessageable);
  1272. default:
  1273. return false;
  1274. }
  1275. };
  1276. var postMessageable = value$1(function (a) {
  1277. return isPostMessageable(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  1278. });
  1279. var validateEnum = function (values) {
  1280. return valueOf(function (value) {
  1281. return contains(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  1282. });
  1283. };
  1284. var strict$1 = function (key) {
  1285. return field(key, key, strict(), anyValue());
  1286. };
  1287. var strictOf = function (key, schema) {
  1288. return field(key, key, strict(), schema);
  1289. };
  1290. var strictNumber = function (key) {
  1291. return strictOf(key, number);
  1292. };
  1293. var strictString = function (key) {
  1294. return strictOf(key, string);
  1295. };
  1296. var strictStringEnum = function (key, values) {
  1297. return field(key, key, strict(), validateEnum(values));
  1298. };
  1299. var strictBoolean = function (key) {
  1300. return strictOf(key, boolean);
  1301. };
  1302. var strictFunction = function (key) {
  1303. return strictOf(key, functionProcessor);
  1304. };
  1305. var forbid = function (key, message) {
  1306. return field(key, key, asOption(), value$1(function (v) {
  1307. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1308. }));
  1309. };
  1310. var strictObjOf = function (key, objSchema) {
  1311. return field(key, key, strict(), objOf(objSchema));
  1312. };
  1313. var strictArrayOfObj = function (key, objFields) {
  1314. return field(key, key, strict(), arrOfObj(objFields));
  1315. };
  1316. var strictArrayOf = function (key, schema) {
  1317. return field(key, key, strict(), arrOf(schema));
  1318. };
  1319. var option = function (key) {
  1320. return field(key, key, asOption(), anyValue());
  1321. };
  1322. var optionOf = function (key, schema) {
  1323. return field(key, key, asOption(), schema);
  1324. };
  1325. var optionNumber = function (key) {
  1326. return optionOf(key, number);
  1327. };
  1328. var optionString = function (key) {
  1329. return optionOf(key, string);
  1330. };
  1331. var optionFunction = function (key) {
  1332. return optionOf(key, functionProcessor);
  1333. };
  1334. var optionArrayOf = function (key, schema) {
  1335. return optionOf(key, arrOf(schema));
  1336. };
  1337. var optionObjOf = function (key, objSchema) {
  1338. return optionOf(key, objOf(objSchema));
  1339. };
  1340. var optionObjOfOnly = function (key, objSchema) {
  1341. return optionOf(key, objOfOnly(objSchema));
  1342. };
  1343. var defaulted$1 = function (key, fallback) {
  1344. return field(key, key, defaulted(fallback), anyValue());
  1345. };
  1346. var defaultedOf = function (key, fallback, schema) {
  1347. return field(key, key, defaulted(fallback), schema);
  1348. };
  1349. var defaultedNumber = function (key, fallback) {
  1350. return defaultedOf(key, fallback, number);
  1351. };
  1352. var defaultedString = function (key, fallback) {
  1353. return defaultedOf(key, fallback, string);
  1354. };
  1355. var defaultedStringEnum = function (key, fallback, values) {
  1356. return defaultedOf(key, fallback, validateEnum(values));
  1357. };
  1358. var defaultedBoolean = function (key, fallback) {
  1359. return defaultedOf(key, fallback, boolean);
  1360. };
  1361. var defaultedFunction = function (key, fallback) {
  1362. return defaultedOf(key, fallback, functionProcessor);
  1363. };
  1364. var defaultedPostMsg = function (key, fallback) {
  1365. return defaultedOf(key, fallback, postMessageable);
  1366. };
  1367. var defaultedArrayOf = function (key, fallback, schema) {
  1368. return defaultedOf(key, fallback, arrOf(schema));
  1369. };
  1370. var defaultedObjOf = function (key, fallback, objSchema) {
  1371. return defaultedOf(key, fallback, objOf(objSchema));
  1372. };
  1373. var state$1 = function (okey, instantiator) {
  1374. return state(okey, instantiator);
  1375. };
  1376. var Cell = function (initial) {
  1377. var value = initial;
  1378. var get = function () {
  1379. return value;
  1380. };
  1381. var set = function (v) {
  1382. value = v;
  1383. };
  1384. var clone = function () {
  1385. return Cell(get());
  1386. };
  1387. return {
  1388. get: get,
  1389. set: set,
  1390. clone: clone
  1391. };
  1392. };
  1393. var fromHtml = function (html, scope) {
  1394. var doc = scope || domGlobals.document;
  1395. var div = doc.createElement('div');
  1396. div.innerHTML = html;
  1397. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1398. domGlobals.console.error('HTML does not have a single root node', html);
  1399. throw new Error('HTML must have a single root node');
  1400. }
  1401. return fromDom(div.childNodes[0]);
  1402. };
  1403. var fromTag = function (tag, scope) {
  1404. var doc = scope || domGlobals.document;
  1405. var node = doc.createElement(tag);
  1406. return fromDom(node);
  1407. };
  1408. var fromText = function (text, scope) {
  1409. var doc = scope || domGlobals.document;
  1410. var node = doc.createTextNode(text);
  1411. return fromDom(node);
  1412. };
  1413. var fromDom = function (node) {
  1414. if (node === null || node === undefined) {
  1415. throw new Error('Node cannot be null or undefined');
  1416. }
  1417. return { dom: constant(node) };
  1418. };
  1419. var fromPoint = function (docElm, x, y) {
  1420. var doc = docElm.dom();
  1421. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  1422. };
  1423. var Element = {
  1424. fromHtml: fromHtml,
  1425. fromTag: fromTag,
  1426. fromText: fromText,
  1427. fromDom: fromDom,
  1428. fromPoint: fromPoint
  1429. };
  1430. var compareDocumentPosition = function (a, b, match) {
  1431. return (a.compareDocumentPosition(b) & match) !== 0;
  1432. };
  1433. var documentPositionPreceding = function (a, b) {
  1434. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_PRECEDING);
  1435. };
  1436. var documentPositionContainedBy = function (a, b) {
  1437. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY);
  1438. };
  1439. var Node = {
  1440. documentPositionPreceding: documentPositionPreceding,
  1441. documentPositionContainedBy: documentPositionContainedBy
  1442. };
  1443. var firstMatch = function (regexes, s) {
  1444. for (var i = 0; i < regexes.length; i++) {
  1445. var x = regexes[i];
  1446. if (x.test(s)) {
  1447. return x;
  1448. }
  1449. }
  1450. return undefined;
  1451. };
  1452. var find$2 = function (regexes, agent) {
  1453. var r = firstMatch(regexes, agent);
  1454. if (!r) {
  1455. return {
  1456. major: 0,
  1457. minor: 0
  1458. };
  1459. }
  1460. var group = function (i) {
  1461. return Number(agent.replace(r, '$' + i));
  1462. };
  1463. return nu$1(group(1), group(2));
  1464. };
  1465. var detect = function (versionRegexes, agent) {
  1466. var cleanedAgent = String(agent).toLowerCase();
  1467. if (versionRegexes.length === 0) {
  1468. return unknown();
  1469. }
  1470. return find$2(versionRegexes, cleanedAgent);
  1471. };
  1472. var unknown = function () {
  1473. return nu$1(0, 0);
  1474. };
  1475. var nu$1 = function (major, minor) {
  1476. return {
  1477. major: major,
  1478. minor: minor
  1479. };
  1480. };
  1481. var Version = {
  1482. nu: nu$1,
  1483. detect: detect,
  1484. unknown: unknown
  1485. };
  1486. var edge = 'Edge';
  1487. var chrome = 'Chrome';
  1488. var ie = 'IE';
  1489. var opera = 'Opera';
  1490. var firefox = 'Firefox';
  1491. var safari = 'Safari';
  1492. var isBrowser = function (name, current) {
  1493. return function () {
  1494. return current === name;
  1495. };
  1496. };
  1497. var unknown$1 = function () {
  1498. return nu$2({
  1499. current: undefined,
  1500. version: Version.unknown()
  1501. });
  1502. };
  1503. var nu$2 = function (info) {
  1504. var current = info.current;
  1505. var version = info.version;
  1506. return {
  1507. current: current,
  1508. version: version,
  1509. isEdge: isBrowser(edge, current),
  1510. isChrome: isBrowser(chrome, current),
  1511. isIE: isBrowser(ie, current),
  1512. isOpera: isBrowser(opera, current),
  1513. isFirefox: isBrowser(firefox, current),
  1514. isSafari: isBrowser(safari, current)
  1515. };
  1516. };
  1517. var Browser = {
  1518. unknown: unknown$1,
  1519. nu: nu$2,
  1520. edge: constant(edge),
  1521. chrome: constant(chrome),
  1522. ie: constant(ie),
  1523. opera: constant(opera),
  1524. firefox: constant(firefox),
  1525. safari: constant(safari)
  1526. };
  1527. var windows = 'Windows';
  1528. var ios = 'iOS';
  1529. var android = 'Android';
  1530. var linux = 'Linux';
  1531. var osx = 'OSX';
  1532. var solaris = 'Solaris';
  1533. var freebsd = 'FreeBSD';
  1534. var chromeos = 'ChromeOS';
  1535. var isOS = function (name, current) {
  1536. return function () {
  1537. return current === name;
  1538. };
  1539. };
  1540. var unknown$2 = function () {
  1541. return nu$3({
  1542. current: undefined,
  1543. version: Version.unknown()
  1544. });
  1545. };
  1546. var nu$3 = function (info) {
  1547. var current = info.current;
  1548. var version = info.version;
  1549. return {
  1550. current: current,
  1551. version: version,
  1552. isWindows: isOS(windows, current),
  1553. isiOS: isOS(ios, current),
  1554. isAndroid: isOS(android, current),
  1555. isOSX: isOS(osx, current),
  1556. isLinux: isOS(linux, current),
  1557. isSolaris: isOS(solaris, current),
  1558. isFreeBSD: isOS(freebsd, current),
  1559. isChromeOS: isOS(chromeos, current)
  1560. };
  1561. };
  1562. var OperatingSystem = {
  1563. unknown: unknown$2,
  1564. nu: nu$3,
  1565. windows: constant(windows),
  1566. ios: constant(ios),
  1567. android: constant(android),
  1568. linux: constant(linux),
  1569. osx: constant(osx),
  1570. solaris: constant(solaris),
  1571. freebsd: constant(freebsd),
  1572. chromeos: constant(chromeos)
  1573. };
  1574. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  1575. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  1576. var isiPhone = os.isiOS() && !isiPad;
  1577. var isMobile = os.isiOS() || os.isAndroid();
  1578. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  1579. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  1580. var isPhone = isiPhone || isMobile && !isTablet;
  1581. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  1582. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  1583. return {
  1584. isiPad: constant(isiPad),
  1585. isiPhone: constant(isiPhone),
  1586. isTablet: constant(isTablet),
  1587. isPhone: constant(isPhone),
  1588. isTouch: constant(isTouch),
  1589. isAndroid: os.isAndroid,
  1590. isiOS: os.isiOS,
  1591. isWebView: constant(iOSwebview),
  1592. isDesktop: constant(isDesktop)
  1593. };
  1594. };
  1595. var detect$1 = function (candidates, userAgent) {
  1596. var agent = String(userAgent).toLowerCase();
  1597. return find(candidates, function (candidate) {
  1598. return candidate.search(agent);
  1599. });
  1600. };
  1601. var detectBrowser = function (browsers, userAgent) {
  1602. return detect$1(browsers, userAgent).map(function (browser) {
  1603. var version = Version.detect(browser.versionRegexes, userAgent);
  1604. return {
  1605. current: browser.name,
  1606. version: version
  1607. };
  1608. });
  1609. };
  1610. var detectOs = function (oses, userAgent) {
  1611. return detect$1(oses, userAgent).map(function (os) {
  1612. var version = Version.detect(os.versionRegexes, userAgent);
  1613. return {
  1614. current: os.name,
  1615. version: version
  1616. };
  1617. });
  1618. };
  1619. var UaString = {
  1620. detectBrowser: detectBrowser,
  1621. detectOs: detectOs
  1622. };
  1623. var checkRange = function (str, substr, start) {
  1624. if (substr === '') {
  1625. return true;
  1626. }
  1627. if (str.length < substr.length) {
  1628. return false;
  1629. }
  1630. var x = str.substr(start, start + substr.length);
  1631. return x === substr;
  1632. };
  1633. var contains$1 = function (str, substr) {
  1634. return str.indexOf(substr) !== -1;
  1635. };
  1636. var endsWith = function (str, suffix) {
  1637. return checkRange(str, suffix, str.length - suffix.length);
  1638. };
  1639. var trim = function (str) {
  1640. return str.replace(/^\s+|\s+$/g, '');
  1641. };
  1642. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  1643. var checkContains = function (target) {
  1644. return function (uastring) {
  1645. return contains$1(uastring, target);
  1646. };
  1647. };
  1648. var browsers = [
  1649. {
  1650. name: 'Edge',
  1651. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  1652. search: function (uastring) {
  1653. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  1654. }
  1655. },
  1656. {
  1657. name: 'Chrome',
  1658. versionRegexes: [
  1659. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  1660. normalVersionRegex
  1661. ],
  1662. search: function (uastring) {
  1663. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  1664. }
  1665. },
  1666. {
  1667. name: 'IE',
  1668. versionRegexes: [
  1669. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  1670. /.*?rv:([0-9]+)\.([0-9]+).*/
  1671. ],
  1672. search: function (uastring) {
  1673. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  1674. }
  1675. },
  1676. {
  1677. name: 'Opera',
  1678. versionRegexes: [
  1679. normalVersionRegex,
  1680. /.*?opera\/([0-9]+)\.([0-9]+).*/
  1681. ],
  1682. search: checkContains('opera')
  1683. },
  1684. {
  1685. name: 'Firefox',
  1686. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1687. search: checkContains('firefox')
  1688. },
  1689. {
  1690. name: 'Safari',
  1691. versionRegexes: [
  1692. normalVersionRegex,
  1693. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1694. ],
  1695. search: function (uastring) {
  1696. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1697. }
  1698. }
  1699. ];
  1700. var oses = [
  1701. {
  1702. name: 'Windows',
  1703. search: checkContains('win'),
  1704. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1705. },
  1706. {
  1707. name: 'iOS',
  1708. search: function (uastring) {
  1709. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1710. },
  1711. versionRegexes: [
  1712. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1713. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1714. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1715. ]
  1716. },
  1717. {
  1718. name: 'Android',
  1719. search: checkContains('android'),
  1720. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1721. },
  1722. {
  1723. name: 'OSX',
  1724. search: checkContains('mac os x'),
  1725. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  1726. },
  1727. {
  1728. name: 'Linux',
  1729. search: checkContains('linux'),
  1730. versionRegexes: []
  1731. },
  1732. {
  1733. name: 'Solaris',
  1734. search: checkContains('sunos'),
  1735. versionRegexes: []
  1736. },
  1737. {
  1738. name: 'FreeBSD',
  1739. search: checkContains('freebsd'),
  1740. versionRegexes: []
  1741. },
  1742. {
  1743. name: 'ChromeOS',
  1744. search: checkContains('cros'),
  1745. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  1746. }
  1747. ];
  1748. var PlatformInfo = {
  1749. browsers: constant(browsers),
  1750. oses: constant(oses)
  1751. };
  1752. var detect$2 = function (userAgent, mediaMatch) {
  1753. var browsers = PlatformInfo.browsers();
  1754. var oses = PlatformInfo.oses();
  1755. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  1756. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1757. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1758. return {
  1759. browser: browser,
  1760. os: os,
  1761. deviceType: deviceType
  1762. };
  1763. };
  1764. var PlatformDetection = { detect: detect$2 };
  1765. var mediaMatch = function (query) {
  1766. return domGlobals.window.matchMedia(query).matches;
  1767. };
  1768. var platform = Cell(PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch));
  1769. var detect$3 = function () {
  1770. return platform.get();
  1771. };
  1772. var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE;
  1773. var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE;
  1774. var COMMENT = domGlobals.Node.COMMENT_NODE;
  1775. var DOCUMENT = domGlobals.Node.DOCUMENT_NODE;
  1776. var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE;
  1777. var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE;
  1778. var ELEMENT = domGlobals.Node.ELEMENT_NODE;
  1779. var TEXT = domGlobals.Node.TEXT_NODE;
  1780. var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE;
  1781. var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE;
  1782. var ENTITY = domGlobals.Node.ENTITY_NODE;
  1783. var NOTATION = domGlobals.Node.NOTATION_NODE;
  1784. var ELEMENT$1 = ELEMENT;
  1785. var DOCUMENT$1 = DOCUMENT;
  1786. var is = function (element, selector) {
  1787. var dom = element.dom();
  1788. if (dom.nodeType !== ELEMENT$1) {
  1789. return false;
  1790. } else {
  1791. var elem = dom;
  1792. if (elem.matches !== undefined) {
  1793. return elem.matches(selector);
  1794. } else if (elem.msMatchesSelector !== undefined) {
  1795. return elem.msMatchesSelector(selector);
  1796. } else if (elem.webkitMatchesSelector !== undefined) {
  1797. return elem.webkitMatchesSelector(selector);
  1798. } else if (elem.mozMatchesSelector !== undefined) {
  1799. return elem.mozMatchesSelector(selector);
  1800. } else {
  1801. throw new Error('Browser lacks native selectors');
  1802. }
  1803. }
  1804. };
  1805. var bypassSelector = function (dom) {
  1806. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  1807. };
  1808. var all = function (selector, scope) {
  1809. var base = scope === undefined ? domGlobals.document : scope.dom();
  1810. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), Element.fromDom);
  1811. };
  1812. var one = function (selector, scope) {
  1813. var base = scope === undefined ? domGlobals.document : scope.dom();
  1814. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1815. };
  1816. var eq = function (e1, e2) {
  1817. return e1.dom() === e2.dom();
  1818. };
  1819. var regularContains = function (e1, e2) {
  1820. var d1 = e1.dom();
  1821. var d2 = e2.dom();
  1822. return d1 === d2 ? false : d1.contains(d2);
  1823. };
  1824. var ieContains = function (e1, e2) {
  1825. return Node.documentPositionContainedBy(e1.dom(), e2.dom());
  1826. };
  1827. var browser = detect$3().browser;
  1828. var contains$2 = browser.isIE() ? ieContains : regularContains;
  1829. var ancestor = function (scope, transform, isRoot) {
  1830. var element = scope.dom();
  1831. var stop = isFunction(isRoot) ? isRoot : constant(false);
  1832. while (element.parentNode) {
  1833. element = element.parentNode;
  1834. var el = Element.fromDom(element);
  1835. var transformed = transform(el);
  1836. if (transformed.isSome()) {
  1837. return transformed;
  1838. } else if (stop(el)) {
  1839. break;
  1840. }
  1841. }
  1842. return Option.none();
  1843. };
  1844. var closest = function (scope, transform, isRoot) {
  1845. var current = transform(scope);
  1846. return current.orThunk(function () {
  1847. return isRoot(scope) ? Option.none() : ancestor(scope, transform, isRoot);
  1848. });
  1849. };
  1850. var isSource = function (component, simulatedEvent) {
  1851. return eq(component.element(), simulatedEvent.event().target());
  1852. };
  1853. var nu$4 = function (parts) {
  1854. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  1855. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  1856. }
  1857. return asRawOrDie('Extracting event.handler', objOfOnly([
  1858. defaulted$1('can', constant(true)),
  1859. defaulted$1('abort', constant(false)),
  1860. defaulted$1('run', noop)
  1861. ]), parts);
  1862. };
  1863. var all$1 = function (handlers, f) {
  1864. return function () {
  1865. var args = [];
  1866. for (var _i = 0; _i < arguments.length; _i++) {
  1867. args[_i] = arguments[_i];
  1868. }
  1869. return foldl(handlers, function (acc, handler) {
  1870. return acc && f(handler).apply(undefined, args);
  1871. }, true);
  1872. };
  1873. };
  1874. var any = function (handlers, f) {
  1875. return function () {
  1876. var args = [];
  1877. for (var _i = 0; _i < arguments.length; _i++) {
  1878. args[_i] = arguments[_i];
  1879. }
  1880. return foldl(handlers, function (acc, handler) {
  1881. return acc || f(handler).apply(undefined, args);
  1882. }, false);
  1883. };
  1884. };
  1885. var read = function (handler) {
  1886. return isFunction(handler) ? {
  1887. can: constant(true),
  1888. abort: constant(false),
  1889. run: handler
  1890. } : handler;
  1891. };
  1892. var fuse = function (handlers) {
  1893. var can = all$1(handlers, function (handler) {
  1894. return handler.can;
  1895. });
  1896. var abort = any(handlers, function (handler) {
  1897. return handler.abort;
  1898. });
  1899. var run = function () {
  1900. var args = [];
  1901. for (var _i = 0; _i < arguments.length; _i++) {
  1902. args[_i] = arguments[_i];
  1903. }
  1904. each(handlers, function (handler) {
  1905. handler.run.apply(undefined, args);
  1906. });
  1907. };
  1908. return nu$4({
  1909. can: can,
  1910. abort: abort,
  1911. run: run
  1912. });
  1913. };
  1914. var touchstart = constant('touchstart');
  1915. var touchmove = constant('touchmove');
  1916. var touchend = constant('touchend');
  1917. var touchcancel = constant('touchcancel');
  1918. var mousedown = constant('mousedown');
  1919. var mousemove = constant('mousemove');
  1920. var mouseout = constant('mouseout');
  1921. var mouseup = constant('mouseup');
  1922. var mouseover = constant('mouseover');
  1923. var focusin = constant('focusin');
  1924. var focusout = constant('focusout');
  1925. var keydown = constant('keydown');
  1926. var keyup = constant('keyup');
  1927. var input = constant('input');
  1928. var change = constant('change');
  1929. var click = constant('click');
  1930. var transitionend = constant('transitionend');
  1931. var selectstart = constant('selectstart');
  1932. var alloy = { tap: constant('alloy.tap') };
  1933. var focus = constant('alloy.focus');
  1934. var postBlur = constant('alloy.blur.post');
  1935. var postPaste = constant('alloy.paste.post');
  1936. var receive = constant('alloy.receive');
  1937. var execute = constant('alloy.execute');
  1938. var focusItem = constant('alloy.focus.item');
  1939. var tap = alloy.tap;
  1940. var longpress = constant('alloy.longpress');
  1941. var sandboxClose = constant('alloy.sandbox.close');
  1942. var typeaheadCancel = constant('alloy.typeahead.cancel');
  1943. var systemInit = constant('alloy.system.init');
  1944. var documentTouchmove = constant('alloy.system.touchmove');
  1945. var documentTouchend = constant('alloy.system.touchend');
  1946. var windowScroll = constant('alloy.system.scroll');
  1947. var windowResize = constant('alloy.system.resize');
  1948. var attachedToDom = constant('alloy.system.attached');
  1949. var detachedFromDom = constant('alloy.system.detached');
  1950. var dismissRequested = constant('alloy.system.dismissRequested');
  1951. var repositionRequested = constant('alloy.system.repositionRequested');
  1952. var focusShifted = constant('alloy.focusmanager.shifted');
  1953. var slotVisibility = constant('alloy.slotcontainer.visibility');
  1954. var changeTab = constant('alloy.change.tab');
  1955. var dismissTab = constant('alloy.dismiss.tab');
  1956. var highlight = constant('alloy.highlight');
  1957. var dehighlight = constant('alloy.dehighlight');
  1958. var emit = function (component, event) {
  1959. dispatchWith(component, component.element(), event, {});
  1960. };
  1961. var emitWith = function (component, event, properties) {
  1962. dispatchWith(component, component.element(), event, properties);
  1963. };
  1964. var emitExecute = function (component) {
  1965. emit(component, execute());
  1966. };
  1967. var dispatch = function (component, target, event) {
  1968. dispatchWith(component, target, event, {});
  1969. };
  1970. var dispatchWith = function (component, target, event, properties) {
  1971. var data = __assign({ target: target }, properties);
  1972. component.getSystem().triggerEvent(event, target, map$1(data, constant));
  1973. };
  1974. var dispatchEvent = function (component, target, event, simulatedEvent) {
  1975. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  1976. };
  1977. var derive = function (configs) {
  1978. return wrapAll$1(configs);
  1979. };
  1980. var abort = function (name, predicate) {
  1981. return {
  1982. key: name,
  1983. value: nu$4({ abort: predicate })
  1984. };
  1985. };
  1986. var can = function (name, predicate) {
  1987. return {
  1988. key: name,
  1989. value: nu$4({ can: predicate })
  1990. };
  1991. };
  1992. var preventDefault = function (name) {
  1993. return {
  1994. key: name,
  1995. value: nu$4({
  1996. run: function (component, simulatedEvent) {
  1997. simulatedEvent.event().prevent();
  1998. }
  1999. })
  2000. };
  2001. };
  2002. var run = function (name, handler) {
  2003. return {
  2004. key: name,
  2005. value: nu$4({ run: handler })
  2006. };
  2007. };
  2008. var runActionExtra = function (name, action, extra) {
  2009. return {
  2010. key: name,
  2011. value: nu$4({
  2012. run: function (component, simulatedEvent) {
  2013. action.apply(undefined, [
  2014. component,
  2015. simulatedEvent
  2016. ].concat(extra));
  2017. }
  2018. })
  2019. };
  2020. };
  2021. var runOnName = function (name) {
  2022. return function (handler) {
  2023. return run(name, handler);
  2024. };
  2025. };
  2026. var runOnSourceName = function (name) {
  2027. return function (handler) {
  2028. return {
  2029. key: name,
  2030. value: nu$4({
  2031. run: function (component, simulatedEvent) {
  2032. if (isSource(component, simulatedEvent)) {
  2033. handler(component, simulatedEvent);
  2034. }
  2035. }
  2036. })
  2037. };
  2038. };
  2039. };
  2040. var redirectToUid = function (name, uid) {
  2041. return run(name, function (component, simulatedEvent) {
  2042. component.getSystem().getByUid(uid).each(function (redirectee) {
  2043. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2044. });
  2045. });
  2046. };
  2047. var redirectToPart = function (name, detail, partName) {
  2048. var uid = detail.partUids[partName];
  2049. return redirectToUid(name, uid);
  2050. };
  2051. var runWithTarget = function (name, f) {
  2052. return run(name, function (component, simulatedEvent) {
  2053. var ev = simulatedEvent.event();
  2054. var target = component.getSystem().getByDom(ev.target()).fold(function () {
  2055. var closest$1 = closest(ev.target(), function (el) {
  2056. return component.getSystem().getByDom(el).toOption();
  2057. }, constant(false));
  2058. return closest$1.getOr(component);
  2059. }, function (c) {
  2060. return c;
  2061. });
  2062. f(component, target, simulatedEvent);
  2063. });
  2064. };
  2065. var cutter = function (name) {
  2066. return run(name, function (component, simulatedEvent) {
  2067. simulatedEvent.cut();
  2068. });
  2069. };
  2070. var stopper = function (name) {
  2071. return run(name, function (component, simulatedEvent) {
  2072. simulatedEvent.stop();
  2073. });
  2074. };
  2075. var runOnSource = function (name, f) {
  2076. return runOnSourceName(name)(f);
  2077. };
  2078. var runOnAttached = runOnSourceName(attachedToDom());
  2079. var runOnDetached = runOnSourceName(detachedFromDom());
  2080. var runOnInit = runOnSourceName(systemInit());
  2081. var runOnExecute = runOnName(execute());
  2082. var Immutable = function () {
  2083. var fields = [];
  2084. for (var _i = 0; _i < arguments.length; _i++) {
  2085. fields[_i] = arguments[_i];
  2086. }
  2087. return function () {
  2088. var values = [];
  2089. for (var _i = 0; _i < arguments.length; _i++) {
  2090. values[_i] = arguments[_i];
  2091. }
  2092. if (fields.length !== values.length) {
  2093. throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
  2094. }
  2095. var struct = {};
  2096. each(fields, function (name, i) {
  2097. struct[name] = constant(values[i]);
  2098. });
  2099. return struct;
  2100. };
  2101. };
  2102. var sort$1 = function (arr) {
  2103. return arr.slice(0).sort();
  2104. };
  2105. var reqMessage = function (required, keys) {
  2106. throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  2107. };
  2108. var unsuppMessage = function (unsupported) {
  2109. throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  2110. };
  2111. var validateStrArr = function (label, array) {
  2112. if (!isArray(array)) {
  2113. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  2114. }
  2115. each(array, function (a) {
  2116. if (!isString(a)) {
  2117. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  2118. }
  2119. });
  2120. };
  2121. var checkDupes = function (everything) {
  2122. var sorted = sort$1(everything);
  2123. var dupe = find(sorted, function (s, i) {
  2124. return i < sorted.length - 1 && s === sorted[i + 1];
  2125. });
  2126. dupe.each(function (d) {
  2127. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  2128. });
  2129. };
  2130. var MixedBag = function (required, optional) {
  2131. var everything = required.concat(optional);
  2132. if (everything.length === 0) {
  2133. throw new Error('You must specify at least one required or optional field.');
  2134. }
  2135. validateStrArr('required', required);
  2136. validateStrArr('optional', optional);
  2137. checkDupes(everything);
  2138. return function (obj) {
  2139. var keys$1 = keys(obj);
  2140. var allReqd = forall(required, function (req) {
  2141. return contains(keys$1, req);
  2142. });
  2143. if (!allReqd) {
  2144. reqMessage(required, keys$1);
  2145. }
  2146. var unsupported = filter(keys$1, function (key) {
  2147. return !contains(everything, key);
  2148. });
  2149. if (unsupported.length > 0) {
  2150. unsuppMessage(unsupported);
  2151. }
  2152. var r = {};
  2153. each(required, function (req) {
  2154. r[req] = constant(obj[req]);
  2155. });
  2156. each(optional, function (opt) {
  2157. r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
  2158. });
  2159. return r;
  2160. };
  2161. };
  2162. var owner = function (element) {
  2163. return Element.fromDom(element.dom().ownerDocument);
  2164. };
  2165. var documentElement = function (element) {
  2166. return Element.fromDom(element.dom().ownerDocument.documentElement);
  2167. };
  2168. var defaultView = function (element) {
  2169. return Element.fromDom(element.dom().ownerDocument.defaultView);
  2170. };
  2171. var parent = function (element) {
  2172. return Option.from(element.dom().parentNode).map(Element.fromDom);
  2173. };
  2174. var offsetParent = function (element) {
  2175. return Option.from(element.dom().offsetParent).map(Element.fromDom);
  2176. };
  2177. var nextSibling = function (element) {
  2178. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  2179. };
  2180. var children = function (element) {
  2181. return map(element.dom().childNodes, Element.fromDom);
  2182. };
  2183. var child = function (element, index) {
  2184. var cs = element.dom().childNodes;
  2185. return Option.from(cs[index]).map(Element.fromDom);
  2186. };
  2187. var firstChild = function (element) {
  2188. return child(element, 0);
  2189. };
  2190. var spot = Immutable('element', 'offset');
  2191. var fromHtml$1 = function (html, scope) {
  2192. var doc = scope || domGlobals.document;
  2193. var div = doc.createElement('div');
  2194. div.innerHTML = html;
  2195. return children(Element.fromDom(div));
  2196. };
  2197. var before = function (marker, element) {
  2198. var parent$1 = parent(marker);
  2199. parent$1.each(function (v) {
  2200. v.dom().insertBefore(element.dom(), marker.dom());
  2201. });
  2202. };
  2203. var after = function (marker, element) {
  2204. var sibling = nextSibling(marker);
  2205. sibling.fold(function () {
  2206. var parent$1 = parent(marker);
  2207. parent$1.each(function (v) {
  2208. append(v, element);
  2209. });
  2210. }, function (v) {
  2211. before(v, element);
  2212. });
  2213. };
  2214. var prepend = function (parent, element) {
  2215. var firstChild$1 = firstChild(parent);
  2216. firstChild$1.fold(function () {
  2217. append(parent, element);
  2218. }, function (v) {
  2219. parent.dom().insertBefore(element.dom(), v.dom());
  2220. });
  2221. };
  2222. var append = function (parent, element) {
  2223. parent.dom().appendChild(element.dom());
  2224. };
  2225. var appendAt = function (parent, element, index) {
  2226. child(parent, index).fold(function () {
  2227. append(parent, element);
  2228. }, function (v) {
  2229. before(v, element);
  2230. });
  2231. };
  2232. var before$1 = function (marker, elements) {
  2233. each(elements, function (x) {
  2234. before(marker, x);
  2235. });
  2236. };
  2237. var append$1 = function (parent, elements) {
  2238. each(elements, function (x) {
  2239. append(parent, x);
  2240. });
  2241. };
  2242. var empty = function (element) {
  2243. element.dom().textContent = '';
  2244. each(children(element), function (rogue) {
  2245. remove(rogue);
  2246. });
  2247. };
  2248. var remove = function (element) {
  2249. var dom = element.dom();
  2250. if (dom.parentNode !== null) {
  2251. dom.parentNode.removeChild(dom);
  2252. }
  2253. };
  2254. var unwrap = function (wrapper) {
  2255. var children$1 = children(wrapper);
  2256. if (children$1.length > 0) {
  2257. before$1(wrapper, children$1);
  2258. }
  2259. remove(wrapper);
  2260. };
  2261. var get$1 = function (element) {
  2262. return element.dom().innerHTML;
  2263. };
  2264. var set = function (element, content) {
  2265. var owner$1 = owner(element);
  2266. var docDom = owner$1.dom();
  2267. var fragment = Element.fromDom(docDom.createDocumentFragment());
  2268. var contentElements = fromHtml$1(content, docDom);
  2269. append$1(fragment, contentElements);
  2270. empty(element);
  2271. append(element, fragment);
  2272. };
  2273. var getOuter = function (element) {
  2274. var container = Element.fromTag('div');
  2275. var clone = Element.fromDom(element.dom().cloneNode(true));
  2276. append(container, clone);
  2277. return get$1(container);
  2278. };
  2279. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  2280. var name = function (element) {
  2281. var r = element.dom().nodeName;
  2282. return r.toLowerCase();
  2283. };
  2284. var type = function (element) {
  2285. return element.dom().nodeType;
  2286. };
  2287. var isType$1 = function (t) {
  2288. return function (element) {
  2289. return type(element) === t;
  2290. };
  2291. };
  2292. var isElement = isType$1(ELEMENT);
  2293. var isText = isType$1(TEXT);
  2294. var rawSet = function (dom, key, value) {
  2295. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2296. dom.setAttribute(key, value + '');
  2297. } else {
  2298. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2299. throw new Error('Attribute value was not simple');
  2300. }
  2301. };
  2302. var set$1 = function (element, key, value) {
  2303. rawSet(element.dom(), key, value);
  2304. };
  2305. var setAll = function (element, attrs) {
  2306. var dom = element.dom();
  2307. each$1(attrs, function (v, k) {
  2308. rawSet(dom, k, v);
  2309. });
  2310. };
  2311. var get$2 = function (element, key) {
  2312. var v = element.dom().getAttribute(key);
  2313. return v === null ? undefined : v;
  2314. };
  2315. var getOpt = function (element, key) {
  2316. return Option.from(get$2(element, key));
  2317. };
  2318. var has$1 = function (element, key) {
  2319. var dom = element.dom();
  2320. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2321. };
  2322. var remove$1 = function (element, key) {
  2323. element.dom().removeAttribute(key);
  2324. };
  2325. var clone = function (original, isDeep) {
  2326. return Element.fromDom(original.dom().cloneNode(isDeep));
  2327. };
  2328. var shallow$1 = function (original) {
  2329. return clone(original, false);
  2330. };
  2331. var getHtml = function (element) {
  2332. var clone = shallow$1(element);
  2333. return getOuter(clone);
  2334. };
  2335. var element = function (elem) {
  2336. return getHtml(elem);
  2337. };
  2338. var isRecursive = function (component, originator, target) {
  2339. return eq(originator, component.element()) && !eq(originator, target);
  2340. };
  2341. var events = derive([can(focus(), function (component, simulatedEvent) {
  2342. var originator = simulatedEvent.event().originator();
  2343. var target = simulatedEvent.event().target();
  2344. if (isRecursive(component, originator, target)) {
  2345. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  2346. return false;
  2347. } else {
  2348. return true;
  2349. }
  2350. })]);
  2351. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2352. __proto__: null,
  2353. events: events
  2354. });
  2355. var unique = 0;
  2356. var generate$1 = function (prefix) {
  2357. var date = new Date();
  2358. var time = date.getTime();
  2359. var random = Math.floor(Math.random() * 1000000000);
  2360. unique++;
  2361. return prefix + '_' + random + unique + String(time);
  2362. };
  2363. var prefix = constant('alloy-id-');
  2364. var idAttr = constant('data-alloy-id');
  2365. var prefix$1 = prefix();
  2366. var idAttr$1 = idAttr();
  2367. var write = function (label, elem) {
  2368. var id = generate$1(prefix$1 + label);
  2369. writeOnly(elem, id);
  2370. return id;
  2371. };
  2372. var writeOnly = function (elem, uid) {
  2373. Object.defineProperty(elem.dom(), idAttr$1, {
  2374. value: uid,
  2375. writable: true
  2376. });
  2377. };
  2378. var read$1 = function (elem) {
  2379. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  2380. return Option.from(id);
  2381. };
  2382. var generate$2 = function (prefix) {
  2383. return generate$1(prefix);
  2384. };
  2385. var make = identity;
  2386. var NoContextApi = function (getComp) {
  2387. var fail = function (event) {
  2388. return function () {
  2389. throw new Error('The component must be in a context to send: ' + event + (getComp ? '\n' + element(getComp().element()) + ' is not in context.' : ''));
  2390. };
  2391. };
  2392. return {
  2393. debugInfo: constant('fake'),
  2394. triggerEvent: fail('triggerEvent'),
  2395. triggerFocus: fail('triggerFocus'),
  2396. triggerEscape: fail('triggerEscape'),
  2397. build: fail('build'),
  2398. addToWorld: fail('addToWorld'),
  2399. removeFromWorld: fail('removeFromWorld'),
  2400. addToGui: fail('addToGui'),
  2401. removeFromGui: fail('removeFromGui'),
  2402. getByUid: fail('getByUid'),
  2403. getByDom: fail('getByDom'),
  2404. broadcast: fail('broadcast'),
  2405. broadcastOn: fail('broadcastOn'),
  2406. broadcastEvent: fail('broadcastEvent'),
  2407. isConnected: constant(false)
  2408. };
  2409. };
  2410. var singleton = NoContextApi();
  2411. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2412. var delegate = apiFunction.toString();
  2413. var endIndex = delegate.indexOf(')') + 1;
  2414. var openBracketIndex = delegate.indexOf('(');
  2415. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2416. f.toFunctionAnnotation = function () {
  2417. return {
  2418. name: apiName,
  2419. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2420. };
  2421. };
  2422. return f;
  2423. };
  2424. var cleanParameters = function (parameters) {
  2425. return map(parameters, function (p) {
  2426. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2427. });
  2428. };
  2429. var markAsExtraApi = function (f, extraName) {
  2430. var delegate = f.toString();
  2431. var endIndex = delegate.indexOf(')') + 1;
  2432. var openBracketIndex = delegate.indexOf('(');
  2433. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2434. f.toFunctionAnnotation = function () {
  2435. return {
  2436. name: extraName,
  2437. parameters: cleanParameters(parameters)
  2438. };
  2439. };
  2440. return f;
  2441. };
  2442. var markAsSketchApi = function (f, apiFunction) {
  2443. var delegate = apiFunction.toString();
  2444. var endIndex = delegate.indexOf(')') + 1;
  2445. var openBracketIndex = delegate.indexOf('(');
  2446. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2447. f.toFunctionAnnotation = function () {
  2448. return {
  2449. name: 'OVERRIDE',
  2450. parameters: cleanParameters(parameters.slice(1))
  2451. };
  2452. };
  2453. return f;
  2454. };
  2455. var premadeTag = generate$1('alloy-premade');
  2456. var premade = function (comp) {
  2457. return wrap$1(premadeTag, comp);
  2458. };
  2459. var getPremade = function (spec) {
  2460. return get(spec, premadeTag);
  2461. };
  2462. var makeApi = function (f) {
  2463. return markAsSketchApi(function (component) {
  2464. var rest = [];
  2465. for (var _i = 1; _i < arguments.length; _i++) {
  2466. rest[_i - 1] = arguments[_i];
  2467. }
  2468. return f.apply(undefined, [component.getApis()].concat([component].concat(rest)));
  2469. }, f);
  2470. };
  2471. var NoState = {
  2472. init: function () {
  2473. return nu$5({
  2474. readState: function () {
  2475. return 'No State required';
  2476. }
  2477. });
  2478. }
  2479. };
  2480. var nu$5 = function (spec) {
  2481. return spec;
  2482. };
  2483. var generateFrom = function (spec, all) {
  2484. var schema = map(all, function (a) {
  2485. return optionObjOf(a.name(), [
  2486. strict$1('config'),
  2487. defaulted$1('state', NoState)
  2488. ]);
  2489. });
  2490. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  2491. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2492. }, function (v) {
  2493. return v;
  2494. });
  2495. return {
  2496. list: all,
  2497. data: map$1(validated, function (optBlobThunk) {
  2498. var output = optBlobThunk.map(function (blob) {
  2499. return {
  2500. config: blob.config,
  2501. state: blob.state.init(blob.config)
  2502. };
  2503. });
  2504. return function () {
  2505. return output;
  2506. };
  2507. })
  2508. };
  2509. };
  2510. var getBehaviours = function (bData) {
  2511. return bData.list;
  2512. };
  2513. var getData = function (bData) {
  2514. return bData.data;
  2515. };
  2516. var byInnerKey = function (data, tuple) {
  2517. var r = {};
  2518. each$1(data, function (detail, key) {
  2519. each$1(detail, function (value, indexKey) {
  2520. var chain = get(r, indexKey).getOr([]);
  2521. r[indexKey] = chain.concat([tuple(key, value)]);
  2522. });
  2523. });
  2524. return r;
  2525. };
  2526. var nu$6 = function (s) {
  2527. return {
  2528. classes: s.classes !== undefined ? s.classes : [],
  2529. attributes: s.attributes !== undefined ? s.attributes : {},
  2530. styles: s.styles !== undefined ? s.styles : {}
  2531. };
  2532. };
  2533. var merge$1 = function (defnA, mod) {
  2534. return __assign(__assign({}, defnA), {
  2535. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2536. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2537. classes: defnA.classes.concat(mod.classes)
  2538. });
  2539. };
  2540. var combine = function (info, baseMod, behaviours, base) {
  2541. var modsByBehaviour = __assign({}, baseMod);
  2542. each(behaviours, function (behaviour) {
  2543. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  2544. });
  2545. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  2546. return {
  2547. name: name,
  2548. modification: modification
  2549. };
  2550. });
  2551. var combineObjects = function (objects) {
  2552. return foldr(objects, function (b, a) {
  2553. return __assign(__assign({}, a.modification), b);
  2554. }, {});
  2555. };
  2556. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  2557. return a.modification.concat(b);
  2558. }, []);
  2559. var combinedAttributes = combineObjects(byAspect.attributes);
  2560. var combinedStyles = combineObjects(byAspect.styles);
  2561. return nu$6({
  2562. classes: combinedClasses,
  2563. attributes: combinedAttributes,
  2564. styles: combinedStyles
  2565. });
  2566. };
  2567. var sortKeys = function (label, keyName, array, order) {
  2568. try {
  2569. var sorted = sort(array, function (a, b) {
  2570. var aKey = a[keyName]();
  2571. var bKey = b[keyName]();
  2572. var aIndex = order.indexOf(aKey);
  2573. var bIndex = order.indexOf(bKey);
  2574. if (aIndex === -1) {
  2575. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2576. }
  2577. if (bIndex === -1) {
  2578. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2579. }
  2580. if (aIndex < bIndex) {
  2581. return -1;
  2582. } else if (bIndex < aIndex) {
  2583. return 1;
  2584. } else {
  2585. return 0;
  2586. }
  2587. });
  2588. return Result.value(sorted);
  2589. } catch (err) {
  2590. return Result.error([err]);
  2591. }
  2592. };
  2593. var uncurried = function (handler, purpose) {
  2594. return {
  2595. handler: handler,
  2596. purpose: constant(purpose)
  2597. };
  2598. };
  2599. var curried = function (handler, purpose) {
  2600. return {
  2601. cHandler: handler,
  2602. purpose: constant(purpose)
  2603. };
  2604. };
  2605. var curryArgs = function (descHandler, extraArgs) {
  2606. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  2607. };
  2608. var getCurried = function (descHandler) {
  2609. return descHandler.cHandler;
  2610. };
  2611. var behaviourTuple = function (name, handler) {
  2612. return {
  2613. name: constant(name),
  2614. handler: constant(handler)
  2615. };
  2616. };
  2617. var nameToHandlers = function (behaviours, info) {
  2618. var r = {};
  2619. each(behaviours, function (behaviour) {
  2620. r[behaviour.name()] = behaviour.handlers(info);
  2621. });
  2622. return r;
  2623. };
  2624. var groupByEvents = function (info, behaviours, base) {
  2625. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  2626. return byInnerKey(behaviourEvents, behaviourTuple);
  2627. };
  2628. var combine$1 = function (info, eventOrder, behaviours, base) {
  2629. var byEventName = groupByEvents(info, behaviours, base);
  2630. return combineGroups(byEventName, eventOrder);
  2631. };
  2632. var assemble = function (rawHandler) {
  2633. var handler = read(rawHandler);
  2634. return function (component, simulatedEvent) {
  2635. var rest = [];
  2636. for (var _i = 2; _i < arguments.length; _i++) {
  2637. rest[_i - 2] = arguments[_i];
  2638. }
  2639. var args = [
  2640. component,
  2641. simulatedEvent
  2642. ].concat(rest);
  2643. if (handler.abort.apply(undefined, args)) {
  2644. simulatedEvent.stop();
  2645. } else if (handler.can.apply(undefined, args)) {
  2646. handler.run.apply(undefined, args);
  2647. }
  2648. };
  2649. };
  2650. var missingOrderError = function (eventName, tuples) {
  2651. 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) {
  2652. return c.name();
  2653. }), null, 2)]);
  2654. };
  2655. var fuse$1 = function (tuples, eventOrder, eventName) {
  2656. var order = eventOrder[eventName];
  2657. if (!order) {
  2658. return missingOrderError(eventName, tuples);
  2659. } else {
  2660. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  2661. var handlers = map(sortedTuples, function (tuple) {
  2662. return tuple.handler();
  2663. });
  2664. return fuse(handlers);
  2665. });
  2666. }
  2667. };
  2668. var combineGroups = function (byEventName, eventOrder) {
  2669. var r = mapToArray(byEventName, function (tuples, eventName) {
  2670. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  2671. return combined.map(function (handler) {
  2672. var assembled = assemble(handler);
  2673. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  2674. return exists(tuples, function (t) {
  2675. return t.name() === o;
  2676. });
  2677. }).join(' > ') : tuples[0].name();
  2678. return wrap$1(eventName, uncurried(assembled, purpose));
  2679. });
  2680. });
  2681. return consolidate(r, {});
  2682. };
  2683. var toInfo = function (spec) {
  2684. return asRaw('custom.definition', objOf([
  2685. field('dom', 'dom', strict(), objOf([
  2686. strict$1('tag'),
  2687. defaulted$1('styles', {}),
  2688. defaulted$1('classes', []),
  2689. defaulted$1('attributes', {}),
  2690. option('value'),
  2691. option('innerHtml')
  2692. ])),
  2693. strict$1('components'),
  2694. strict$1('uid'),
  2695. defaulted$1('events', {}),
  2696. defaulted$1('apis', {}),
  2697. field('eventOrder', 'eventOrder', mergeWith({
  2698. 'alloy.execute': [
  2699. 'disabling',
  2700. 'alloy.base.behaviour',
  2701. 'toggling',
  2702. 'typeaheadevents'
  2703. ],
  2704. 'alloy.focus': [
  2705. 'alloy.base.behaviour',
  2706. 'focusing',
  2707. 'keying'
  2708. ],
  2709. 'alloy.system.init': [
  2710. 'alloy.base.behaviour',
  2711. 'disabling',
  2712. 'toggling',
  2713. 'representing'
  2714. ],
  2715. 'input': [
  2716. 'alloy.base.behaviour',
  2717. 'representing',
  2718. 'streaming',
  2719. 'invalidating'
  2720. ],
  2721. 'alloy.system.detached': [
  2722. 'alloy.base.behaviour',
  2723. 'representing',
  2724. 'item-events',
  2725. 'tooltipping'
  2726. ],
  2727. 'mousedown': [
  2728. 'focusing',
  2729. 'alloy.base.behaviour',
  2730. 'item-type-events'
  2731. ],
  2732. 'touchstart': [
  2733. 'focusing',
  2734. 'alloy.base.behaviour',
  2735. 'item-type-events'
  2736. ],
  2737. 'mouseover': [
  2738. 'item-type-events',
  2739. 'tooltipping'
  2740. ]
  2741. }), anyValue$1()),
  2742. option('domModification')
  2743. ]), spec);
  2744. };
  2745. var toDefinition = function (detail) {
  2746. return __assign(__assign({}, detail.dom), {
  2747. uid: detail.uid,
  2748. domChildren: map(detail.components, function (comp) {
  2749. return comp.element();
  2750. })
  2751. });
  2752. };
  2753. var toModification = function (detail) {
  2754. return detail.domModification.fold(function () {
  2755. return nu$6({});
  2756. }, nu$6);
  2757. };
  2758. var toEvents = function (info) {
  2759. return info.events;
  2760. };
  2761. var read$2 = function (element, attr) {
  2762. var value = get$2(element, attr);
  2763. return value === undefined || value === '' ? [] : value.split(' ');
  2764. };
  2765. var add = function (element, attr, id) {
  2766. var old = read$2(element, attr);
  2767. var nu = old.concat([id]);
  2768. set$1(element, attr, nu.join(' '));
  2769. return true;
  2770. };
  2771. var remove$2 = function (element, attr, id) {
  2772. var nu = filter(read$2(element, attr), function (v) {
  2773. return v !== id;
  2774. });
  2775. if (nu.length > 0) {
  2776. set$1(element, attr, nu.join(' '));
  2777. } else {
  2778. remove$1(element, attr);
  2779. }
  2780. return false;
  2781. };
  2782. var supports = function (element) {
  2783. return element.dom().classList !== undefined;
  2784. };
  2785. var get$3 = function (element) {
  2786. return read$2(element, 'class');
  2787. };
  2788. var add$1 = function (element, clazz) {
  2789. return add(element, 'class', clazz);
  2790. };
  2791. var remove$3 = function (element, clazz) {
  2792. return remove$2(element, 'class', clazz);
  2793. };
  2794. var add$2 = function (element, clazz) {
  2795. if (supports(element)) {
  2796. element.dom().classList.add(clazz);
  2797. } else {
  2798. add$1(element, clazz);
  2799. }
  2800. };
  2801. var cleanClass = function (element) {
  2802. var classList = supports(element) ? element.dom().classList : get$3(element);
  2803. if (classList.length === 0) {
  2804. remove$1(element, 'class');
  2805. }
  2806. };
  2807. var remove$4 = function (element, clazz) {
  2808. if (supports(element)) {
  2809. var classList = element.dom().classList;
  2810. classList.remove(clazz);
  2811. } else {
  2812. remove$3(element, clazz);
  2813. }
  2814. cleanClass(element);
  2815. };
  2816. var has$2 = function (element, clazz) {
  2817. return supports(element) && element.dom().classList.contains(clazz);
  2818. };
  2819. var add$3 = function (element, classes) {
  2820. each(classes, function (x) {
  2821. add$2(element, x);
  2822. });
  2823. };
  2824. var remove$5 = function (element, classes) {
  2825. each(classes, function (x) {
  2826. remove$4(element, x);
  2827. });
  2828. };
  2829. var isSupported = function (dom) {
  2830. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  2831. };
  2832. var inBody = function (element) {
  2833. var dom = isText(element) ? element.dom().parentNode : element.dom();
  2834. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  2835. };
  2836. var body = cached(function () {
  2837. return getBody(Element.fromDom(domGlobals.document));
  2838. });
  2839. var getBody = function (doc) {
  2840. var b = doc.dom().body;
  2841. if (b === null || b === undefined) {
  2842. throw new Error('Body is not available yet');
  2843. }
  2844. return Element.fromDom(b);
  2845. };
  2846. var internalSet = function (dom, property, value) {
  2847. if (!isString(value)) {
  2848. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  2849. throw new Error('CSS value must be a string: ' + value);
  2850. }
  2851. if (isSupported(dom)) {
  2852. dom.style.setProperty(property, value);
  2853. }
  2854. };
  2855. var internalRemove = function (dom, property) {
  2856. if (isSupported(dom)) {
  2857. dom.style.removeProperty(property);
  2858. }
  2859. };
  2860. var set$2 = function (element, property, value) {
  2861. var dom = element.dom();
  2862. internalSet(dom, property, value);
  2863. };
  2864. var setAll$1 = function (element, css) {
  2865. var dom = element.dom();
  2866. each$1(css, function (v, k) {
  2867. internalSet(dom, k, v);
  2868. });
  2869. };
  2870. var setOptions = function (element, css) {
  2871. var dom = element.dom();
  2872. each$1(css, function (v, k) {
  2873. v.fold(function () {
  2874. internalRemove(dom, k);
  2875. }, function (value) {
  2876. internalSet(dom, k, value);
  2877. });
  2878. });
  2879. };
  2880. var get$4 = function (element, property) {
  2881. var dom = element.dom();
  2882. var styles = domGlobals.window.getComputedStyle(dom);
  2883. var r = styles.getPropertyValue(property);
  2884. var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  2885. return v === null ? undefined : v;
  2886. };
  2887. var getUnsafeProperty = function (dom, property) {
  2888. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  2889. };
  2890. var getRaw = function (element, property) {
  2891. var dom = element.dom();
  2892. var raw = getUnsafeProperty(dom, property);
  2893. return Option.from(raw).filter(function (r) {
  2894. return r.length > 0;
  2895. });
  2896. };
  2897. var getAllRaw = function (element) {
  2898. var css = {};
  2899. var dom = element.dom();
  2900. if (isSupported(dom)) {
  2901. for (var i = 0; i < dom.style.length; i++) {
  2902. var ruleName = dom.style.item(i);
  2903. css[ruleName] = dom.style[ruleName];
  2904. }
  2905. }
  2906. return css;
  2907. };
  2908. var isValidValue = function (tag, property, value) {
  2909. var element = Element.fromTag(tag);
  2910. set$2(element, property, value);
  2911. var style = getRaw(element, property);
  2912. return style.isSome();
  2913. };
  2914. var remove$6 = function (element, property) {
  2915. var dom = element.dom();
  2916. internalRemove(dom, property);
  2917. if (has$1(element, 'style') && trim(get$2(element, 'style')) === '') {
  2918. remove$1(element, 'style');
  2919. }
  2920. };
  2921. var reflow = function (e) {
  2922. return e.dom().offsetWidth;
  2923. };
  2924. var get$5 = function (element) {
  2925. return element.dom().value;
  2926. };
  2927. var set$3 = function (element, value) {
  2928. if (value === undefined) {
  2929. throw new Error('Value.set was undefined');
  2930. }
  2931. element.dom().value = value;
  2932. };
  2933. var renderToDom = function (definition) {
  2934. var subject = Element.fromTag(definition.tag);
  2935. setAll(subject, definition.attributes);
  2936. add$3(subject, definition.classes);
  2937. setAll$1(subject, definition.styles);
  2938. definition.innerHtml.each(function (html) {
  2939. return set(subject, html);
  2940. });
  2941. var children = definition.domChildren;
  2942. append$1(subject, children);
  2943. definition.value.each(function (value) {
  2944. set$3(subject, value);
  2945. });
  2946. if (!definition.uid) {
  2947. debugger;
  2948. }
  2949. writeOnly(subject, definition.uid);
  2950. return subject;
  2951. };
  2952. var getBehaviours$1 = function (spec) {
  2953. var behaviours = get(spec, 'behaviours').getOr({});
  2954. var keys$1 = filter(keys(behaviours), function (k) {
  2955. return behaviours[k] !== undefined;
  2956. });
  2957. return map(keys$1, function (k) {
  2958. return behaviours[k].me;
  2959. });
  2960. };
  2961. var generateFrom$1 = function (spec, all) {
  2962. return generateFrom(spec, all);
  2963. };
  2964. var generate$3 = function (spec) {
  2965. var all = getBehaviours$1(spec);
  2966. return generateFrom$1(spec, all);
  2967. };
  2968. var getDomDefinition = function (info, bList, bData) {
  2969. var definition = toDefinition(info);
  2970. var infoModification = toModification(info);
  2971. var baseModification = { 'alloy.base.modification': infoModification };
  2972. var modification = bList.length > 0 ? combine(bData, baseModification, bList, definition) : infoModification;
  2973. return merge$1(definition, modification);
  2974. };
  2975. var getEvents = function (info, bList, bData) {
  2976. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  2977. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  2978. };
  2979. var build = function (spec) {
  2980. var getMe = function () {
  2981. return me;
  2982. };
  2983. var systemApi = Cell(singleton);
  2984. var info = getOrDie(toInfo(spec));
  2985. var bBlob = generate$3(spec);
  2986. var bList = getBehaviours(bBlob);
  2987. var bData = getData(bBlob);
  2988. var modDefinition = getDomDefinition(info, bList, bData);
  2989. var item = renderToDom(modDefinition);
  2990. var events = getEvents(info, bList, bData);
  2991. var subcomponents = Cell(info.components);
  2992. var connect = function (newApi) {
  2993. systemApi.set(newApi);
  2994. };
  2995. var disconnect = function () {
  2996. systemApi.set(NoContextApi(getMe));
  2997. };
  2998. var syncComponents = function () {
  2999. var children$1 = children(item);
  3000. var subs = bind(children$1, function (child) {
  3001. return systemApi.get().getByDom(child).fold(function () {
  3002. return [];
  3003. }, function (c) {
  3004. return [c];
  3005. });
  3006. });
  3007. subcomponents.set(subs);
  3008. };
  3009. var config = function (behaviour) {
  3010. var b = bData;
  3011. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  3012. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  3013. };
  3014. return f();
  3015. };
  3016. var hasConfigured = function (behaviour) {
  3017. return isFunction(bData[behaviour.name()]);
  3018. };
  3019. var getApis = function () {
  3020. return info.apis;
  3021. };
  3022. var readState = function (behaviourName) {
  3023. return bData[behaviourName]().map(function (b) {
  3024. return b.state.readState();
  3025. }).getOr('not enabled');
  3026. };
  3027. var me = {
  3028. getSystem: systemApi.get,
  3029. config: config,
  3030. hasConfigured: hasConfigured,
  3031. spec: constant(spec),
  3032. readState: readState,
  3033. getApis: getApis,
  3034. connect: connect,
  3035. disconnect: disconnect,
  3036. element: constant(item),
  3037. syncComponents: syncComponents,
  3038. components: subcomponents.get,
  3039. events: constant(events)
  3040. };
  3041. return me;
  3042. };
  3043. var buildSubcomponents = function (spec) {
  3044. var components = get(spec, 'components').getOr([]);
  3045. return map(components, build$1);
  3046. };
  3047. var buildFromSpec = function (userSpec) {
  3048. var _a = make(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  3049. var components = buildSubcomponents(spec);
  3050. var completeSpec = __assign(__assign({}, spec), {
  3051. events: __assign(__assign({}, DefaultEvents), specEvents),
  3052. components: components
  3053. });
  3054. return Result.value(build(completeSpec));
  3055. };
  3056. var text = function (textContent) {
  3057. var element = Element.fromText(textContent);
  3058. return external({ element: element });
  3059. };
  3060. var external = function (spec) {
  3061. var extSpec = asRawOrDie('external.component', objOfOnly([
  3062. strict$1('element'),
  3063. option('uid')
  3064. ]), spec);
  3065. var systemApi = Cell(NoContextApi());
  3066. var connect = function (newApi) {
  3067. systemApi.set(newApi);
  3068. };
  3069. var disconnect = function () {
  3070. systemApi.set(NoContextApi(function () {
  3071. return me;
  3072. }));
  3073. };
  3074. extSpec.uid.each(function (uid) {
  3075. writeOnly(extSpec.element, uid);
  3076. });
  3077. var me = {
  3078. getSystem: systemApi.get,
  3079. config: Option.none,
  3080. hasConfigured: constant(false),
  3081. connect: connect,
  3082. disconnect: disconnect,
  3083. getApis: function () {
  3084. return {};
  3085. },
  3086. element: constant(extSpec.element),
  3087. spec: constant(spec),
  3088. readState: constant('No state'),
  3089. syncComponents: noop,
  3090. components: constant([]),
  3091. events: constant({})
  3092. };
  3093. return premade(me);
  3094. };
  3095. var uids = generate$2;
  3096. var build$1 = function (spec) {
  3097. return getPremade(spec).fold(function () {
  3098. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  3099. return buildFromSpec(userSpecWithUid).getOrDie();
  3100. }, function (prebuilt) {
  3101. return prebuilt;
  3102. });
  3103. };
  3104. var premade$1 = premade;
  3105. function Dimension (name, getOffset) {
  3106. var set = function (element, h) {
  3107. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3108. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3109. }
  3110. var dom = element.dom();
  3111. if (isSupported(dom)) {
  3112. dom.style[name] = h + 'px';
  3113. }
  3114. };
  3115. var get = function (element) {
  3116. var r = getOffset(element);
  3117. if (r <= 0 || r === null) {
  3118. var css = get$4(element, name);
  3119. return parseFloat(css) || 0;
  3120. }
  3121. return r;
  3122. };
  3123. var getOuter = get;
  3124. var aggregate = function (element, properties) {
  3125. return foldl(properties, function (acc, property) {
  3126. var val = get$4(element, property);
  3127. var value = val === undefined ? 0 : parseInt(val, 10);
  3128. return isNaN(value) ? acc : acc + value;
  3129. }, 0);
  3130. };
  3131. var max = function (element, value, properties) {
  3132. var cumulativeInclusions = aggregate(element, properties);
  3133. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3134. return absoluteMax;
  3135. };
  3136. return {
  3137. set: set,
  3138. get: get,
  3139. getOuter: getOuter,
  3140. aggregate: aggregate,
  3141. max: max
  3142. };
  3143. }
  3144. var api = Dimension('height', function (element) {
  3145. var dom = element.dom();
  3146. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3147. });
  3148. var get$6 = function (element) {
  3149. return api.get(element);
  3150. };
  3151. var getOuter$1 = function (element) {
  3152. return api.getOuter(element);
  3153. };
  3154. var setMax = function (element, value) {
  3155. var inclusions = [
  3156. 'margin-top',
  3157. 'border-top-width',
  3158. 'padding-top',
  3159. 'padding-bottom',
  3160. 'border-bottom-width',
  3161. 'margin-bottom'
  3162. ];
  3163. var absMax = api.max(element, value, inclusions);
  3164. set$2(element, 'max-height', absMax + 'px');
  3165. };
  3166. var r = function (left, top) {
  3167. var translate = function (x, y) {
  3168. return r(left + x, top + y);
  3169. };
  3170. return {
  3171. left: constant(left),
  3172. top: constant(top),
  3173. translate: translate
  3174. };
  3175. };
  3176. var Position = r;
  3177. var boxPosition = function (dom) {
  3178. var box = dom.getBoundingClientRect();
  3179. return Position(box.left, box.top);
  3180. };
  3181. var firstDefinedOrZero = function (a, b) {
  3182. return a !== undefined ? a : b !== undefined ? b : 0;
  3183. };
  3184. var absolute = function (element) {
  3185. var doc = element.dom().ownerDocument;
  3186. var body = doc.body;
  3187. var win = doc.defaultView;
  3188. var html = doc.documentElement;
  3189. if (body === element.dom()) {
  3190. return Position(body.offsetLeft, body.offsetTop);
  3191. }
  3192. var scrollTop = firstDefinedOrZero(win.pageYOffset, html.scrollTop);
  3193. var scrollLeft = firstDefinedOrZero(win.pageXOffset, html.scrollLeft);
  3194. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  3195. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  3196. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  3197. };
  3198. var viewport = function (element) {
  3199. var dom = element.dom();
  3200. var doc = dom.ownerDocument;
  3201. var body = doc.body;
  3202. if (body === dom) {
  3203. return Position(body.offsetLeft, body.offsetTop);
  3204. }
  3205. if (!inBody(element)) {
  3206. return Position(0, 0);
  3207. }
  3208. return boxPosition(dom);
  3209. };
  3210. var api$1 = Dimension('width', function (element) {
  3211. return element.dom().offsetWidth;
  3212. });
  3213. var set$4 = function (element, h) {
  3214. api$1.set(element, h);
  3215. };
  3216. var get$7 = function (element) {
  3217. return api$1.get(element);
  3218. };
  3219. var getOuter$2 = function (element) {
  3220. return api$1.getOuter(element);
  3221. };
  3222. var setMax$1 = function (element, value) {
  3223. var inclusions = [
  3224. 'margin-left',
  3225. 'border-left-width',
  3226. 'padding-left',
  3227. 'padding-right',
  3228. 'border-right-width',
  3229. 'margin-right'
  3230. ];
  3231. var absMax = api$1.max(element, value, inclusions);
  3232. set$2(element, 'max-width', absMax + 'px');
  3233. };
  3234. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  3235. return {
  3236. target: constant(target),
  3237. x: constant(x),
  3238. y: constant(y),
  3239. stop: stop,
  3240. prevent: prevent,
  3241. kill: kill,
  3242. raw: constant(raw)
  3243. };
  3244. };
  3245. var fromRawEvent = function (rawEvent) {
  3246. var target = Element.fromDom(rawEvent.target);
  3247. var stop = function () {
  3248. rawEvent.stopPropagation();
  3249. };
  3250. var prevent = function () {
  3251. rawEvent.preventDefault();
  3252. };
  3253. var kill = compose(prevent, stop);
  3254. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  3255. };
  3256. var handle = function (filter, handler) {
  3257. return function (rawEvent) {
  3258. if (!filter(rawEvent)) {
  3259. return;
  3260. }
  3261. handler(fromRawEvent(rawEvent));
  3262. };
  3263. };
  3264. var binder = function (element, event, filter, handler, useCapture) {
  3265. var wrapped = handle(filter, handler);
  3266. element.dom().addEventListener(event, wrapped, useCapture);
  3267. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  3268. };
  3269. var bind$2 = function (element, event, filter, handler) {
  3270. return binder(element, event, filter, handler, false);
  3271. };
  3272. var capture = function (element, event, filter, handler) {
  3273. return binder(element, event, filter, handler, true);
  3274. };
  3275. var unbind = function (element, event, handler, useCapture) {
  3276. element.dom().removeEventListener(event, handler, useCapture);
  3277. };
  3278. var isSafari = detect$3().browser.isSafari();
  3279. var get$8 = function (_DOC) {
  3280. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  3281. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  3282. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  3283. return Position(x, y);
  3284. };
  3285. var to = function (x, y, _DOC) {
  3286. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  3287. var win = doc.defaultView;
  3288. win.scrollTo(x, y);
  3289. };
  3290. var get$9 = function (_win) {
  3291. var win = _win === undefined ? domGlobals.window : _win;
  3292. return Option.from(win['visualViewport']);
  3293. };
  3294. var bounds = function (x, y, width, height) {
  3295. return {
  3296. x: constant(x),
  3297. y: constant(y),
  3298. width: constant(width),
  3299. height: constant(height),
  3300. right: constant(x + width),
  3301. bottom: constant(y + height)
  3302. };
  3303. };
  3304. var getBounds = function (_win) {
  3305. var win = _win === undefined ? domGlobals.window : _win;
  3306. var doc = win.document;
  3307. var scroll = get$8(Element.fromDom(doc));
  3308. return get$9(win).fold(function () {
  3309. var html = win.document.documentElement;
  3310. var width = html.clientWidth;
  3311. var height = html.clientHeight;
  3312. return bounds(scroll.left(), scroll.top(), width, height);
  3313. }, function (visualViewport) {
  3314. return bounds(Math.max(visualViewport.pageLeft, scroll.left()), Math.max(visualViewport.pageTop, scroll.top()), visualViewport.width, visualViewport.height);
  3315. });
  3316. };
  3317. var walkUp = function (navigation, doc) {
  3318. var frame = navigation.view(doc);
  3319. return frame.fold(constant([]), function (f) {
  3320. var parent = navigation.owner(f);
  3321. var rest = walkUp(navigation, parent);
  3322. return [f].concat(rest);
  3323. });
  3324. };
  3325. var pathTo = function (element, navigation) {
  3326. var d = navigation.owner(element);
  3327. var paths = walkUp(navigation, d);
  3328. return Option.some(paths);
  3329. };
  3330. var view = function (doc) {
  3331. var element = doc.dom() === domGlobals.document ? Option.none() : Option.from(doc.dom().defaultView.frameElement);
  3332. return element.map(Element.fromDom);
  3333. };
  3334. var owner$1 = function (element) {
  3335. return owner(element);
  3336. };
  3337. var Navigation = /*#__PURE__*/Object.freeze({
  3338. __proto__: null,
  3339. view: view,
  3340. owner: owner$1
  3341. });
  3342. var find$3 = function (element) {
  3343. var doc = Element.fromDom(domGlobals.document);
  3344. var scroll = get$8(doc);
  3345. var path = pathTo(element, Navigation);
  3346. return path.fold(curry(absolute, element), function (frames) {
  3347. var offset = viewport(element);
  3348. var r = foldr(frames, function (b, a) {
  3349. var loc = viewport(a);
  3350. return {
  3351. left: b.left + loc.left(),
  3352. top: b.top + loc.top()
  3353. };
  3354. }, {
  3355. left: 0,
  3356. top: 0
  3357. });
  3358. return Position(r.left + offset.left() + scroll.left(), r.top + offset.top() + scroll.top());
  3359. });
  3360. };
  3361. var pointed = Immutable('point', 'width', 'height');
  3362. var rect = Immutable('x', 'y', 'width', 'height');
  3363. var bounds$1 = function (x, y, width, height) {
  3364. return {
  3365. x: constant(x),
  3366. y: constant(y),
  3367. width: constant(width),
  3368. height: constant(height),
  3369. right: constant(x + width),
  3370. bottom: constant(y + height)
  3371. };
  3372. };
  3373. var box = function (element) {
  3374. var xy = absolute(element);
  3375. var w = getOuter$2(element);
  3376. var h = getOuter$1(element);
  3377. return bounds$1(xy.left(), xy.top(), w, h);
  3378. };
  3379. var absolute$1 = function (element) {
  3380. var position = find$3(element);
  3381. var width = getOuter$2(element);
  3382. var height = getOuter$1(element);
  3383. return bounds$1(position.left(), position.top(), width, height);
  3384. };
  3385. var win = function () {
  3386. return getBounds(domGlobals.window);
  3387. };
  3388. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3389. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  3390. }
  3391. var ancestor$1 = function (scope, predicate, isRoot) {
  3392. var element = scope.dom();
  3393. var stop = isFunction(isRoot) ? isRoot : constant(false);
  3394. while (element.parentNode) {
  3395. element = element.parentNode;
  3396. var el = Element.fromDom(element);
  3397. if (predicate(el)) {
  3398. return Option.some(el);
  3399. } else if (stop(el)) {
  3400. break;
  3401. }
  3402. }
  3403. return Option.none();
  3404. };
  3405. var closest$1 = function (scope, predicate, isRoot) {
  3406. var is = function (s, test) {
  3407. return test(s);
  3408. };
  3409. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3410. };
  3411. var descendant = function (scope, predicate) {
  3412. var descend = function (node) {
  3413. for (var i = 0; i < node.childNodes.length; i++) {
  3414. var child_1 = Element.fromDom(node.childNodes[i]);
  3415. if (predicate(child_1)) {
  3416. return Option.some(child_1);
  3417. }
  3418. var res = descend(node.childNodes[i]);
  3419. if (res.isSome()) {
  3420. return res;
  3421. }
  3422. }
  3423. return Option.none();
  3424. };
  3425. return descend(scope.dom());
  3426. };
  3427. var closest$2 = function (scope, predicate, isRoot) {
  3428. return closest$1(scope, predicate, isRoot).isSome();
  3429. };
  3430. var ancestor$2 = function (scope, selector, isRoot) {
  3431. return ancestor$1(scope, function (e) {
  3432. return is(e, selector);
  3433. }, isRoot);
  3434. };
  3435. var descendant$1 = function (scope, selector) {
  3436. return one(selector, scope);
  3437. };
  3438. var closest$3 = function (scope, selector, isRoot) {
  3439. return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  3440. };
  3441. var find$4 = function (queryElem) {
  3442. var dependent = closest$1(queryElem, function (elem) {
  3443. if (!isElement(elem)) {
  3444. return false;
  3445. }
  3446. var id = get$2(elem, 'id');
  3447. return id !== undefined && id.indexOf('aria-owns') > -1;
  3448. });
  3449. return dependent.bind(function (dep) {
  3450. var id = get$2(dep, 'id');
  3451. var doc = owner(dep);
  3452. return descendant$1(doc, '[aria-owns="' + id + '"]');
  3453. });
  3454. };
  3455. var manager = function () {
  3456. var ariaId = generate$1('aria-owns');
  3457. var link = function (elem) {
  3458. set$1(elem, 'aria-owns', ariaId);
  3459. };
  3460. var unlink = function (elem) {
  3461. remove$1(elem, 'aria-owns');
  3462. };
  3463. return {
  3464. id: constant(ariaId),
  3465. link: link,
  3466. unlink: unlink
  3467. };
  3468. };
  3469. var isAriaPartOf = function (component, queryElem) {
  3470. return find$4(queryElem).exists(function (owner) {
  3471. return isPartOf(component, owner);
  3472. });
  3473. };
  3474. var isPartOf = function (component, queryElem) {
  3475. return closest$2(queryElem, function (el) {
  3476. return eq(el, component.element());
  3477. }, constant(false)) || isAriaPartOf(component, queryElem);
  3478. };
  3479. var unknown$3 = 'unknown';
  3480. var EventConfiguration;
  3481. (function (EventConfiguration) {
  3482. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3483. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3484. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3485. }(EventConfiguration || (EventConfiguration = {})));
  3486. var eventConfig = Cell({});
  3487. var makeEventLogger = function (eventName, initialTarget) {
  3488. var sequence = [];
  3489. var startTime = new Date().getTime();
  3490. return {
  3491. logEventCut: function (name, target, purpose) {
  3492. sequence.push({
  3493. outcome: 'cut',
  3494. target: target,
  3495. purpose: purpose
  3496. });
  3497. },
  3498. logEventStopped: function (name, target, purpose) {
  3499. sequence.push({
  3500. outcome: 'stopped',
  3501. target: target,
  3502. purpose: purpose
  3503. });
  3504. },
  3505. logNoParent: function (name, target, purpose) {
  3506. sequence.push({
  3507. outcome: 'no-parent',
  3508. target: target,
  3509. purpose: purpose
  3510. });
  3511. },
  3512. logEventNoHandlers: function (name, target) {
  3513. sequence.push({
  3514. outcome: 'no-handlers-left',
  3515. target: target
  3516. });
  3517. },
  3518. logEventResponse: function (name, target, purpose) {
  3519. sequence.push({
  3520. outcome: 'response',
  3521. purpose: purpose,
  3522. target: target
  3523. });
  3524. },
  3525. write: function () {
  3526. var finishTime = new Date().getTime();
  3527. if (contains([
  3528. 'mousemove',
  3529. 'mouseover',
  3530. 'mouseout',
  3531. systemInit()
  3532. ], eventName)) {
  3533. return;
  3534. }
  3535. domGlobals.console.log(eventName, {
  3536. event: eventName,
  3537. time: finishTime - startTime,
  3538. target: initialTarget.dom(),
  3539. sequence: map(sequence, function (s) {
  3540. if (!contains([
  3541. 'cut',
  3542. 'stopped',
  3543. 'response'
  3544. ], s.outcome)) {
  3545. return s.outcome;
  3546. } else {
  3547. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3548. }
  3549. })
  3550. });
  3551. }
  3552. };
  3553. };
  3554. var processEvent = function (eventName, initialTarget, f) {
  3555. var status = get(eventConfig.get(), eventName).orThunk(function () {
  3556. var patterns = keys(eventConfig.get());
  3557. return findMap(patterns, function (p) {
  3558. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  3559. });
  3560. }).getOr(EventConfiguration.NORMAL);
  3561. switch (status) {
  3562. case EventConfiguration.NORMAL:
  3563. return f(noLogger());
  3564. case EventConfiguration.LOGGING: {
  3565. var logger = makeEventLogger(eventName, initialTarget);
  3566. var output = f(logger);
  3567. logger.write();
  3568. return output;
  3569. }
  3570. case EventConfiguration.STOP:
  3571. return true;
  3572. }
  3573. };
  3574. var path = [
  3575. 'alloy/data/Fields',
  3576. 'alloy/debugging/Debugging'
  3577. ];
  3578. var getTrace = function () {
  3579. var err = new Error();
  3580. if (err.stack !== undefined) {
  3581. var lines = err.stack.split('\n');
  3582. return find(lines, function (line) {
  3583. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3584. return line.indexOf(p) > -1;
  3585. });
  3586. }).getOr(unknown$3);
  3587. } else {
  3588. return unknown$3;
  3589. }
  3590. };
  3591. var ignoreEvent = {
  3592. logEventCut: noop,
  3593. logEventStopped: noop,
  3594. logNoParent: noop,
  3595. logEventNoHandlers: noop,
  3596. logEventResponse: noop,
  3597. write: noop
  3598. };
  3599. var monitorEvent = function (eventName, initialTarget, f) {
  3600. return processEvent(eventName, initialTarget, f);
  3601. };
  3602. var noLogger = constant(ignoreEvent);
  3603. var menuFields = constant([
  3604. strict$1('menu'),
  3605. strict$1('selectedMenu')
  3606. ]);
  3607. var itemFields = constant([
  3608. strict$1('item'),
  3609. strict$1('selectedItem')
  3610. ]);
  3611. var schema = constant(objOf(itemFields().concat(menuFields())));
  3612. var itemSchema = constant(objOf(itemFields()));
  3613. var _initSize = strictObjOf('initSize', [
  3614. strict$1('numColumns'),
  3615. strict$1('numRows')
  3616. ]);
  3617. var itemMarkers = function () {
  3618. return strictOf('markers', itemSchema());
  3619. };
  3620. var tieredMenuMarkers = function () {
  3621. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3622. };
  3623. var markers = function (required) {
  3624. return strictObjOf('markers', map(required, strict$1));
  3625. };
  3626. var onPresenceHandler = function (label, fieldName, presence) {
  3627. var trace = getTrace();
  3628. return field(fieldName, fieldName, presence, valueOf(function (f) {
  3629. return Result.value(function () {
  3630. var args = [];
  3631. for (var _i = 0; _i < arguments.length; _i++) {
  3632. args[_i] = arguments[_i];
  3633. }
  3634. return f.apply(undefined, args);
  3635. });
  3636. }));
  3637. };
  3638. var onHandler = function (fieldName) {
  3639. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  3640. };
  3641. var onKeyboardHandler = function (fieldName) {
  3642. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  3643. };
  3644. var onStrictHandler = function (fieldName) {
  3645. return onPresenceHandler('onHandler', fieldName, strict());
  3646. };
  3647. var onStrictKeyboardHandler = function (fieldName) {
  3648. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  3649. };
  3650. var output = function (name, value) {
  3651. return state$1(name, constant(value));
  3652. };
  3653. var snapshot = function (name) {
  3654. return state$1(name, identity);
  3655. };
  3656. var initSize = constant(_initSize);
  3657. var nu$7 = Immutable('x', 'y', 'bubble', 'direction', 'label');
  3658. var adt$2 = Adt.generate([
  3659. { southeast: [] },
  3660. { southwest: [] },
  3661. { northeast: [] },
  3662. { northwest: [] },
  3663. { south: [] },
  3664. { north: [] },
  3665. { east: [] },
  3666. { west: [] }
  3667. ]);
  3668. var cata = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3669. return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3670. };
  3671. var cataVertical = function (subject, south, middle, north) {
  3672. return subject.fold(south, south, north, north, south, north, middle, middle);
  3673. };
  3674. var cataHorizontal = function (subject, east, middle, west) {
  3675. return subject.fold(east, west, east, west, middle, middle, east, west);
  3676. };
  3677. var southeast = adt$2.southeast;
  3678. var southwest = adt$2.southwest;
  3679. var northeast = adt$2.northeast;
  3680. var northwest = adt$2.northwest;
  3681. var south = adt$2.south;
  3682. var north = adt$2.north;
  3683. var east = adt$2.east;
  3684. var west = adt$2.west;
  3685. var eastX = function (anchor) {
  3686. return anchor.x();
  3687. };
  3688. var middleX = function (anchor, element) {
  3689. return anchor.x() + anchor.width() / 2 - element.width() / 2;
  3690. };
  3691. var westX = function (anchor, element) {
  3692. return anchor.x() + anchor.width() - element.width();
  3693. };
  3694. var northY = function (anchor, element) {
  3695. return anchor.y() - element.height();
  3696. };
  3697. var southY = function (anchor) {
  3698. return anchor.y() + anchor.height();
  3699. };
  3700. var centreY = function (anchor, element) {
  3701. return anchor.y() + anchor.height() / 2 - element.height() / 2;
  3702. };
  3703. var eastEdgeX = function (anchor) {
  3704. return anchor.x() + anchor.width();
  3705. };
  3706. var westEdgeX = function (anchor, element) {
  3707. return anchor.x() - element.width();
  3708. };
  3709. var southeast$1 = function (anchor, element, bubbles) {
  3710. return nu$7(eastX(anchor), southY(anchor), bubbles.southeast(), southeast(), 'layout-se');
  3711. };
  3712. var southwest$1 = function (anchor, element, bubbles) {
  3713. return nu$7(westX(anchor, element), southY(anchor), bubbles.southwest(), southwest(), 'layout-sw');
  3714. };
  3715. var northeast$1 = function (anchor, element, bubbles) {
  3716. return nu$7(eastX(anchor), northY(anchor, element), bubbles.northeast(), northeast(), 'layout-ne');
  3717. };
  3718. var northwest$1 = function (anchor, element, bubbles) {
  3719. return nu$7(westX(anchor, element), northY(anchor, element), bubbles.northwest(), northwest(), 'layout-nw');
  3720. };
  3721. var north$1 = function (anchor, element, bubbles) {
  3722. return nu$7(middleX(anchor, element), northY(anchor, element), bubbles.north(), north(), 'layout-n');
  3723. };
  3724. var south$1 = function (anchor, element, bubbles) {
  3725. return nu$7(middleX(anchor, element), southY(anchor), bubbles.south(), south(), 'layout-s');
  3726. };
  3727. var east$1 = function (anchor, element, bubbles) {
  3728. return nu$7(eastEdgeX(anchor), centreY(anchor, element), bubbles.east(), east(), 'layout-e');
  3729. };
  3730. var west$1 = function (anchor, element, bubbles) {
  3731. return nu$7(westEdgeX(anchor, element), centreY(anchor, element), bubbles.west(), west(), 'layout-w');
  3732. };
  3733. var all$2 = function () {
  3734. return [
  3735. southeast$1,
  3736. southwest$1,
  3737. northeast$1,
  3738. northwest$1,
  3739. south$1,
  3740. north$1,
  3741. east$1,
  3742. west$1
  3743. ];
  3744. };
  3745. var allRtl = function () {
  3746. return [
  3747. southwest$1,
  3748. southeast$1,
  3749. northwest$1,
  3750. northeast$1,
  3751. south$1,
  3752. north$1,
  3753. east$1,
  3754. west$1
  3755. ];
  3756. };
  3757. var aboveOrBelow = function () {
  3758. return [
  3759. northeast$1,
  3760. northwest$1,
  3761. southeast$1,
  3762. southwest$1,
  3763. north$1,
  3764. south$1
  3765. ];
  3766. };
  3767. var aboveOrBelowRtl = function () {
  3768. return [
  3769. northwest$1,
  3770. northeast$1,
  3771. southwest$1,
  3772. southeast$1,
  3773. north$1,
  3774. south$1
  3775. ];
  3776. };
  3777. var belowOrAbove = function () {
  3778. return [
  3779. southeast$1,
  3780. southwest$1,
  3781. northeast$1,
  3782. northwest$1,
  3783. south$1,
  3784. north$1
  3785. ];
  3786. };
  3787. var belowOrAboveRtl = function () {
  3788. return [
  3789. southwest$1,
  3790. southeast$1,
  3791. northwest$1,
  3792. northeast$1,
  3793. south$1,
  3794. north$1
  3795. ];
  3796. };
  3797. var executeEvent = function (bConfig, bState, executor) {
  3798. return runOnExecute(function (component) {
  3799. executor(component, bConfig, bState);
  3800. });
  3801. };
  3802. var loadEvent = function (bConfig, bState, f) {
  3803. return runOnInit(function (component, simulatedEvent) {
  3804. f(component, bConfig, bState);
  3805. });
  3806. };
  3807. var create = function (schema, name, active, apis, extra, state) {
  3808. var configSchema = objOfOnly(schema);
  3809. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  3810. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3811. };
  3812. var createModes = function (modes, name, active, apis, extra, state) {
  3813. var configSchema = modes;
  3814. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  3815. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3816. };
  3817. var wrapApi = function (bName, apiFunction, apiName) {
  3818. var f = function (component) {
  3819. var rest = [];
  3820. for (var _i = 1; _i < arguments.length; _i++) {
  3821. rest[_i - 1] = arguments[_i];
  3822. }
  3823. var args = [component].concat(rest);
  3824. return component.config({ name: constant(bName) }).fold(function () {
  3825. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  3826. }, function (info) {
  3827. var rest = Array.prototype.slice.call(args, 1);
  3828. return apiFunction.apply(undefined, [
  3829. component,
  3830. info.config,
  3831. info.state
  3832. ].concat(rest));
  3833. });
  3834. };
  3835. return markAsBehaviourApi(f, apiName, apiFunction);
  3836. };
  3837. var revokeBehaviour = function (name) {
  3838. return {
  3839. key: name,
  3840. value: undefined
  3841. };
  3842. };
  3843. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  3844. var getConfig = function (info) {
  3845. return hasNonNullableKey(info, name) ? info[name]() : Option.none();
  3846. };
  3847. var wrappedApis = map$1(apis, function (apiF, apiName) {
  3848. return wrapApi(name, apiF, apiName);
  3849. });
  3850. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  3851. return markAsExtraApi(extraF, extraName);
  3852. });
  3853. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  3854. revoke: curry(revokeBehaviour, name),
  3855. config: function (spec) {
  3856. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  3857. return {
  3858. key: name,
  3859. value: {
  3860. config: prepared,
  3861. me: me,
  3862. configAsRaw: cached(function () {
  3863. return asRawOrDie(name + '-config', configSchema, spec);
  3864. }),
  3865. initialConfig: spec,
  3866. state: state
  3867. }
  3868. };
  3869. },
  3870. schema: function () {
  3871. return schemaSchema;
  3872. },
  3873. exhibit: function (info, base) {
  3874. return getConfig(info).bind(function (behaviourInfo) {
  3875. return get(active, 'exhibit').map(function (exhibitor) {
  3876. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  3877. });
  3878. }).getOr(nu$6({}));
  3879. },
  3880. name: function () {
  3881. return name;
  3882. },
  3883. handlers: function (info) {
  3884. return getConfig(info).map(function (behaviourInfo) {
  3885. var getEvents = get(active, 'events').getOr(function () {
  3886. return {};
  3887. });
  3888. return getEvents(behaviourInfo.config, behaviourInfo.state);
  3889. }).getOr({});
  3890. }
  3891. });
  3892. return me;
  3893. };
  3894. var derive$1 = function (capabilities) {
  3895. return wrapAll$1(capabilities);
  3896. };
  3897. var simpleSchema = objOfOnly([
  3898. strict$1('fields'),
  3899. strict$1('name'),
  3900. defaulted$1('active', {}),
  3901. defaulted$1('apis', {}),
  3902. defaulted$1('state', NoState),
  3903. defaulted$1('extra', {})
  3904. ]);
  3905. var create$1 = function (data) {
  3906. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  3907. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  3908. };
  3909. var modeSchema = objOfOnly([
  3910. strict$1('branchKey'),
  3911. strict$1('branches'),
  3912. strict$1('name'),
  3913. defaulted$1('active', {}),
  3914. defaulted$1('apis', {}),
  3915. defaulted$1('state', NoState),
  3916. defaulted$1('extra', {})
  3917. ]);
  3918. var createModes$1 = function (data) {
  3919. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  3920. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  3921. };
  3922. var revoke = constant(undefined);
  3923. var chooseChannels = function (channels, message) {
  3924. return message.universal() ? channels : filter(channels, function (ch) {
  3925. return contains(message.channels(), ch);
  3926. });
  3927. };
  3928. var events$1 = function (receiveConfig) {
  3929. return derive([run(receive(), function (component, message) {
  3930. var channelMap = receiveConfig.channels;
  3931. var channels = keys(channelMap);
  3932. var receivingData = message;
  3933. var targetChannels = chooseChannels(channels, receivingData);
  3934. each(targetChannels, function (ch) {
  3935. var channelInfo = channelMap[ch];
  3936. var channelSchema = channelInfo.schema;
  3937. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, receivingData.data());
  3938. channelInfo.onReceive(component, data);
  3939. });
  3940. })]);
  3941. };
  3942. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  3943. __proto__: null,
  3944. events: events$1
  3945. });
  3946. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  3947. onStrictHandler('onReceive'),
  3948. defaulted$1('schema', anyValue$1())
  3949. ])))];
  3950. var Receiving = create$1({
  3951. fields: ReceivingSchema,
  3952. name: 'receiving',
  3953. active: ActiveReceiving
  3954. });
  3955. var exhibit = function (base, posConfig) {
  3956. return nu$6({
  3957. classes: [],
  3958. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  3959. });
  3960. };
  3961. var ActivePosition = /*#__PURE__*/Object.freeze({
  3962. __proto__: null,
  3963. exhibit: exhibit
  3964. });
  3965. var focus$1 = function (element) {
  3966. element.dom().focus();
  3967. };
  3968. var blur = function (element) {
  3969. element.dom().blur();
  3970. };
  3971. var hasFocus = function (element) {
  3972. var doc = owner(element).dom();
  3973. return element.dom() === doc.activeElement;
  3974. };
  3975. var active = function (_doc) {
  3976. var doc = _doc !== undefined ? _doc.dom() : domGlobals.document;
  3977. return Option.from(doc.activeElement).map(Element.fromDom);
  3978. };
  3979. var search = function (element) {
  3980. return active(owner(element)).filter(function (e) {
  3981. return element.dom().contains(e.dom());
  3982. });
  3983. };
  3984. var preserve = function (f, container) {
  3985. var ownerDoc = owner(container);
  3986. var refocus = active(ownerDoc).bind(function (focused) {
  3987. var hasFocus = function (elem) {
  3988. return eq(focused, elem);
  3989. };
  3990. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  3991. });
  3992. var result = f(container);
  3993. refocus.each(function (oldFocus) {
  3994. active(ownerDoc).filter(function (newFocus) {
  3995. return eq(newFocus, oldFocus);
  3996. }).fold(function () {
  3997. focus$1(oldFocus);
  3998. }, noop);
  3999. });
  4000. return result;
  4001. };
  4002. var NuPositionCss = Immutable('position', 'left', 'top', 'right', 'bottom');
  4003. var applyPositionCss = function (element, position) {
  4004. var addPx = function (num) {
  4005. return num + 'px';
  4006. };
  4007. setOptions(element, {
  4008. position: Option.some(position.position()),
  4009. left: position.left().map(addPx),
  4010. top: position.top().map(addPx),
  4011. right: position.right().map(addPx),
  4012. bottom: position.bottom().map(addPx)
  4013. });
  4014. };
  4015. var adt$3 = Adt.generate([
  4016. { none: [] },
  4017. {
  4018. relative: [
  4019. 'x',
  4020. 'y',
  4021. 'width',
  4022. 'height'
  4023. ]
  4024. },
  4025. {
  4026. fixed: [
  4027. 'x',
  4028. 'y',
  4029. 'width',
  4030. 'height'
  4031. ]
  4032. }
  4033. ]);
  4034. var positionWithDirection = function (posName, decision, x, y, width, height) {
  4035. var decisionX = decision.x() - x;
  4036. var decisionY = decision.y() - y;
  4037. var decisionWidth = decision.width();
  4038. var decisionHeight = decision.height();
  4039. var decisionRight = width - (decisionX + decisionWidth);
  4040. var decisionBottom = height - (decisionY + decisionHeight);
  4041. var left = Option.some(decisionX);
  4042. var top = Option.some(decisionY);
  4043. var right = Option.some(decisionRight);
  4044. var bottom = Option.some(decisionBottom);
  4045. var none = Option.none();
  4046. return cata(decision.direction(), function () {
  4047. return NuPositionCss(posName, left, top, none, none);
  4048. }, function () {
  4049. return NuPositionCss(posName, none, top, right, none);
  4050. }, function () {
  4051. return NuPositionCss(posName, left, none, none, bottom);
  4052. }, function () {
  4053. return NuPositionCss(posName, none, none, right, bottom);
  4054. }, function () {
  4055. return NuPositionCss(posName, left, top, none, none);
  4056. }, function () {
  4057. return NuPositionCss(posName, left, none, none, bottom);
  4058. }, function () {
  4059. return NuPositionCss(posName, left, top, none, none);
  4060. }, function () {
  4061. return NuPositionCss(posName, none, top, right, none);
  4062. });
  4063. };
  4064. var reposition = function (origin, decision) {
  4065. return origin.fold(function () {
  4066. return NuPositionCss('absolute', Option.some(decision.x()), Option.some(decision.y()), Option.none(), Option.none());
  4067. }, function (x, y, width, height) {
  4068. return positionWithDirection('absolute', decision, x, y, width, height);
  4069. }, function (x, y, width, height) {
  4070. return positionWithDirection('fixed', decision, x, y, width, height);
  4071. });
  4072. };
  4073. var toBox = function (origin, element) {
  4074. var rel = curry(find$3, element);
  4075. var position = origin.fold(rel, rel, function () {
  4076. var scroll = get$8();
  4077. return find$3(element).translate(-scroll.left(), -scroll.top());
  4078. });
  4079. var width = getOuter$2(element);
  4080. var height = getOuter$1(element);
  4081. return bounds$1(position.left(), position.top(), width, height);
  4082. };
  4083. var viewport$1 = function (origin, getBounds) {
  4084. return getBounds.fold(function () {
  4085. return origin.fold(win, win, bounds$1);
  4086. }, function (b) {
  4087. return origin.fold(b, b, function () {
  4088. var bounds = b();
  4089. var pos = translate(origin, bounds.x(), bounds.y());
  4090. return bounds$1(pos.left(), pos.top(), bounds.width(), bounds.height());
  4091. });
  4092. });
  4093. };
  4094. var translate = function (origin, x, y) {
  4095. var pos = Position(x, y);
  4096. var removeScroll = function () {
  4097. var outerScroll = get$8();
  4098. return pos.translate(-outerScroll.left(), -outerScroll.top());
  4099. };
  4100. return origin.fold(constant(pos), constant(pos), removeScroll);
  4101. };
  4102. var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4103. return subject.fold(onNone, onRelative, onFixed);
  4104. };
  4105. var none$1 = adt$3.none;
  4106. var relative = adt$3.relative;
  4107. var fixed = adt$3.fixed;
  4108. var anchor = Immutable('anchorBox', 'origin');
  4109. var box$1 = function (anchorBox, origin) {
  4110. return anchor(anchorBox, origin);
  4111. };
  4112. var cycleBy = function (value, delta, min, max) {
  4113. var r = value + delta;
  4114. return r > max ? min : r < min ? max : r;
  4115. };
  4116. var clamp = function (value, min, max) {
  4117. return Math.min(Math.max(value, min), max);
  4118. };
  4119. var decision = MixedBag([
  4120. 'x',
  4121. 'y',
  4122. 'width',
  4123. 'height',
  4124. 'maxHeight',
  4125. 'maxWidth',
  4126. 'direction',
  4127. 'classes',
  4128. 'label',
  4129. 'candidateYforTest'
  4130. ], []);
  4131. var adt$4 = Adt.generate([
  4132. { fit: ['reposition'] },
  4133. {
  4134. nofit: [
  4135. 'reposition',
  4136. 'deltaW',
  4137. 'deltaH'
  4138. ]
  4139. }
  4140. ]);
  4141. var calcReposition = function (newX, newY, width, height, bounds) {
  4142. var boundsX = bounds.x();
  4143. var boundsY = bounds.y();
  4144. var boundsWidth = bounds.width();
  4145. var boundsHeight = bounds.height();
  4146. var xInBounds = newX >= boundsX;
  4147. var yInBounds = newY >= boundsY;
  4148. var originInBounds = xInBounds && yInBounds;
  4149. var xFit = newX + width <= boundsX + boundsWidth;
  4150. var yFit = newY + height <= boundsY + boundsHeight;
  4151. var sizeInBounds = xFit && yFit;
  4152. var deltaW = Math.abs(Math.min(width, xInBounds ? boundsX + boundsWidth - newX : boundsX - (newX + width)));
  4153. var deltaH = Math.abs(Math.min(height, yInBounds ? boundsY + boundsHeight - newY : boundsY - (newY + height)));
  4154. var limitX = clamp(newX, bounds.x(), bounds.right());
  4155. var limitY = clamp(newY, bounds.y(), bounds.bottom());
  4156. return {
  4157. originInBounds: originInBounds,
  4158. sizeInBounds: sizeInBounds,
  4159. limitX: limitX,
  4160. limitY: limitY,
  4161. deltaW: deltaW,
  4162. deltaH: deltaH
  4163. };
  4164. };
  4165. var attempt = function (candidate, width, height, bounds) {
  4166. var candidateX = candidate.x();
  4167. var candidateY = candidate.y();
  4168. var bubbleLeft = candidate.bubble().offset().left();
  4169. var bubbleTop = candidate.bubble().offset().top();
  4170. var boundsY = bounds.y();
  4171. var boundsBottom = bounds.bottom();
  4172. var boundsX = bounds.x();
  4173. var boundsRight = bounds.right();
  4174. var newX = candidateX + bubbleLeft;
  4175. var newY = candidateY + bubbleTop;
  4176. var _a = calcReposition(newX, newY, width, height, bounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, limitX = _a.limitX, limitY = _a.limitY, deltaW = _a.deltaW, deltaH = _a.deltaH;
  4177. var upAvailable = constant(limitY + deltaH - boundsY);
  4178. var downAvailable = constant(boundsBottom - limitY);
  4179. var maxHeight = cataVertical(candidate.direction(), downAvailable, downAvailable, upAvailable);
  4180. var westAvailable = constant(limitX + deltaW - boundsX);
  4181. var eastAvailable = constant(boundsRight - limitX);
  4182. var maxWidth = cataHorizontal(candidate.direction(), eastAvailable, eastAvailable, westAvailable);
  4183. var reposition = decision({
  4184. x: limitX,
  4185. y: limitY,
  4186. width: deltaW,
  4187. height: deltaH,
  4188. maxHeight: maxHeight,
  4189. maxWidth: maxWidth,
  4190. direction: candidate.direction(),
  4191. classes: {
  4192. on: candidate.bubble().classesOn(),
  4193. off: candidate.bubble().classesOff()
  4194. },
  4195. label: candidate.label(),
  4196. candidateYforTest: newY
  4197. });
  4198. return originInBounds && sizeInBounds ? adt$4.fit(reposition) : adt$4.nofit(reposition, deltaW, deltaH);
  4199. };
  4200. var attempts = function (candidates, anchorBox, elementBox, bubbles, bounds) {
  4201. var panelWidth = elementBox.width();
  4202. var panelHeight = elementBox.height();
  4203. var attemptBestFit = function (layout, reposition, deltaW, deltaH) {
  4204. var next = layout(anchorBox, elementBox, bubbles);
  4205. var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  4206. return attemptLayout.fold(adt$4.fit, function (newReposition, newDeltaW, newDeltaH) {
  4207. var improved = newDeltaH > deltaH || newDeltaW > deltaW;
  4208. return improved ? adt$4.nofit(newReposition, newDeltaW, newDeltaH) : adt$4.nofit(reposition, deltaW, deltaH);
  4209. });
  4210. };
  4211. var abc = foldl(candidates, function (b, a) {
  4212. var bestNext = curry(attemptBestFit, a);
  4213. return b.fold(adt$4.fit, bestNext);
  4214. }, adt$4.nofit(decision({
  4215. x: anchorBox.x(),
  4216. y: anchorBox.y(),
  4217. width: elementBox.width(),
  4218. height: elementBox.height(),
  4219. maxHeight: elementBox.height(),
  4220. maxWidth: elementBox.width(),
  4221. direction: southeast(),
  4222. classes: {
  4223. on: [],
  4224. off: []
  4225. },
  4226. label: 'none',
  4227. candidateYforTest: anchorBox.y()
  4228. }), -1, -1));
  4229. return abc.fold(identity, identity);
  4230. };
  4231. var elementSize = function (p) {
  4232. return {
  4233. width: constant(getOuter$2(p)),
  4234. height: constant(getOuter$1(p))
  4235. };
  4236. };
  4237. var layout = function (anchorBox, element, bubbles, options) {
  4238. remove$6(element, 'max-height');
  4239. remove$6(element, 'max-width');
  4240. var elementBox = elementSize(element);
  4241. return attempts(options.preference(), anchorBox, elementBox, bubbles, options.bounds());
  4242. };
  4243. var setClasses = function (element, decision) {
  4244. var classInfo = decision.classes();
  4245. remove$5(element, classInfo.off);
  4246. add$3(element, classInfo.on);
  4247. };
  4248. var setHeight = function (element, decision, options) {
  4249. var maxHeightFunction = options.maxHeightFunction();
  4250. maxHeightFunction(element, decision.maxHeight());
  4251. };
  4252. var setWidth = function (element, decision, options) {
  4253. var maxWidthFunction = options.maxWidthFunction();
  4254. maxWidthFunction(element, decision.maxWidth());
  4255. };
  4256. var position = function (element, decision, options) {
  4257. applyPositionCss(element, reposition(options.origin(), decision));
  4258. };
  4259. var setMaxHeight = function (element, maxHeight) {
  4260. setMax(element, Math.floor(maxHeight));
  4261. };
  4262. var anchored = constant(function (element, available) {
  4263. setMaxHeight(element, available);
  4264. setAll$1(element, {
  4265. 'overflow-x': 'hidden',
  4266. 'overflow-y': 'auto'
  4267. });
  4268. });
  4269. var expandable = constant(function (element, available) {
  4270. setMaxHeight(element, available);
  4271. });
  4272. var reparteeOptions = MixedBag([
  4273. 'bounds',
  4274. 'origin',
  4275. 'preference',
  4276. 'maxHeightFunction',
  4277. 'maxWidthFunction'
  4278. ], []);
  4279. var defaultOr = function (options, key, dephault) {
  4280. return options[key] === undefined ? dephault : options[key];
  4281. };
  4282. var simple = function (anchor, element, bubble, layouts, getBounds, overrideOptions) {
  4283. var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  4284. var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  4285. var anchorBox = anchor.anchorBox();
  4286. var origin = anchor.origin();
  4287. var options = reparteeOptions({
  4288. bounds: viewport$1(origin, getBounds),
  4289. origin: origin,
  4290. preference: layouts,
  4291. maxHeightFunction: maxHeightFunction,
  4292. maxWidthFunction: maxWidthFunction
  4293. });
  4294. go(anchorBox, element, bubble, options);
  4295. };
  4296. var go = function (anchorBox, element, bubble, options) {
  4297. var decision = layout(anchorBox, element, bubble, options);
  4298. position(element, decision, options);
  4299. setClasses(element, decision);
  4300. setHeight(element, decision, options);
  4301. setWidth(element, decision, options);
  4302. };
  4303. var allAlignments = [
  4304. 'valignCentre',
  4305. 'alignLeft',
  4306. 'alignRight',
  4307. 'alignCentre',
  4308. 'top',
  4309. 'bottom',
  4310. 'left',
  4311. 'right'
  4312. ];
  4313. var nu$8 = function (width, yoffset, classes) {
  4314. var getClasses = function (prop) {
  4315. return get(classes, prop).getOr([]);
  4316. };
  4317. var make = function (xDelta, yDelta, alignmentsOn) {
  4318. var alignmentsOff = difference(allAlignments, alignmentsOn);
  4319. return {
  4320. offset: function () {
  4321. return Position(xDelta, yDelta);
  4322. },
  4323. classesOn: function () {
  4324. return bind(alignmentsOn, getClasses);
  4325. },
  4326. classesOff: function () {
  4327. return bind(alignmentsOff, getClasses);
  4328. }
  4329. };
  4330. };
  4331. return {
  4332. southeast: function () {
  4333. return make(-width, yoffset, [
  4334. 'top',
  4335. 'alignLeft'
  4336. ]);
  4337. },
  4338. southwest: function () {
  4339. return make(width, yoffset, [
  4340. 'top',
  4341. 'alignRight'
  4342. ]);
  4343. },
  4344. south: function () {
  4345. return make(-width / 2, yoffset, [
  4346. 'top',
  4347. 'alignCentre'
  4348. ]);
  4349. },
  4350. northeast: function () {
  4351. return make(-width, -yoffset, [
  4352. 'bottom',
  4353. 'alignLeft'
  4354. ]);
  4355. },
  4356. northwest: function () {
  4357. return make(width, -yoffset, [
  4358. 'bottom',
  4359. 'alignRight'
  4360. ]);
  4361. },
  4362. north: function () {
  4363. return make(-width / 2, -yoffset, [
  4364. 'bottom',
  4365. 'alignCentre'
  4366. ]);
  4367. },
  4368. east: function () {
  4369. return make(width, -yoffset / 2, [
  4370. 'valignCentre',
  4371. 'left'
  4372. ]);
  4373. },
  4374. west: function () {
  4375. return make(-width, -yoffset / 2, [
  4376. 'valignCentre',
  4377. 'right'
  4378. ]);
  4379. },
  4380. innerNorthwest: function () {
  4381. return make(-width, yoffset, [
  4382. 'top',
  4383. 'alignRight'
  4384. ]);
  4385. },
  4386. innerNortheast: function () {
  4387. return make(width, yoffset, [
  4388. 'top',
  4389. 'alignLeft'
  4390. ]);
  4391. },
  4392. innerNorth: function () {
  4393. return make(-width / 2, yoffset, [
  4394. 'top',
  4395. 'alignCentre'
  4396. ]);
  4397. },
  4398. innerSouthwest: function () {
  4399. return make(-width, -yoffset, [
  4400. 'bottom',
  4401. 'alignRight'
  4402. ]);
  4403. },
  4404. innerSoutheast: function () {
  4405. return make(width, -yoffset, [
  4406. 'bottom',
  4407. 'alignLeft'
  4408. ]);
  4409. },
  4410. innerSouth: function () {
  4411. return make(-width / 2, -yoffset, [
  4412. 'bottom',
  4413. 'alignCentre'
  4414. ]);
  4415. },
  4416. innerWest: function () {
  4417. return make(width, -yoffset / 2, [
  4418. 'valignCentre',
  4419. 'right'
  4420. ]);
  4421. },
  4422. innerEast: function () {
  4423. return make(-width, -yoffset / 2, [
  4424. 'valignCentre',
  4425. 'left'
  4426. ]);
  4427. }
  4428. };
  4429. };
  4430. var fallback = function () {
  4431. return nu$8(0, 0, {});
  4432. };
  4433. var nu$9 = function (x) {
  4434. return x;
  4435. };
  4436. var onDirection = function (isLtr, isRtl) {
  4437. return function (element) {
  4438. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4439. };
  4440. };
  4441. var getDirection = function (element) {
  4442. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4443. };
  4444. var AttributeValue;
  4445. (function (AttributeValue) {
  4446. AttributeValue['TopToBottom'] = 'toptobottom';
  4447. AttributeValue['BottomToTop'] = 'bottomtotop';
  4448. }(AttributeValue || (AttributeValue = {})));
  4449. var Attribute = 'data-alloy-vertical-dir';
  4450. var isBottomToTopDir = function (el) {
  4451. return closest$2(el, function (current) {
  4452. return isElement(current) && get$2(current, Attribute) === AttributeValue.BottomToTop;
  4453. });
  4454. };
  4455. var schema$1 = function () {
  4456. return optionObjOf('layouts', [
  4457. strict$1('onLtr'),
  4458. strict$1('onRtl'),
  4459. option('onBottomLtr'),
  4460. option('onBottomRtl')
  4461. ]);
  4462. };
  4463. var get$a = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
  4464. var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  4465. var customLtr = info.layouts.map(function (ls) {
  4466. return ls.onLtr(elem);
  4467. });
  4468. var customRtl = info.layouts.map(function (ls) {
  4469. return ls.onRtl(elem);
  4470. });
  4471. var ltr = isBottomToTop ? info.layouts.bind(function (ls) {
  4472. return ls.onBottomLtr.map(function (f) {
  4473. return f(elem);
  4474. });
  4475. }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  4476. var rtl = isBottomToTop ? info.layouts.bind(function (ls) {
  4477. return ls.onBottomRtl.map(function (f) {
  4478. return f(elem);
  4479. });
  4480. }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  4481. var f = onDirection(ltr, rtl);
  4482. return f(elem);
  4483. };
  4484. var placement = function (component, anchorInfo, origin) {
  4485. var hotspot = anchorInfo.hotspot;
  4486. var anchorBox = toBox(origin, hotspot.element());
  4487. var layouts = get$a(component.element(), anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Option.some(anchorInfo.hotspot.element()));
  4488. return Option.some(nu$9({
  4489. anchorBox: anchorBox,
  4490. bubble: anchorInfo.bubble.getOr(fallback()),
  4491. overrides: anchorInfo.overrides,
  4492. layouts: layouts,
  4493. placer: Option.none()
  4494. }));
  4495. };
  4496. var HotspotAnchor = [
  4497. strict$1('hotspot'),
  4498. option('bubble'),
  4499. defaulted$1('overrides', {}),
  4500. schema$1(),
  4501. output('placement', placement)
  4502. ];
  4503. var placement$1 = function (component, anchorInfo, origin) {
  4504. var pos = translate(origin, anchorInfo.x, anchorInfo.y);
  4505. var anchorBox = bounds$1(pos.left(), pos.top(), anchorInfo.width, anchorInfo.height);
  4506. var layouts = get$a(component.element(), anchorInfo, all$2(), allRtl(), all$2(), allRtl(), Option.none());
  4507. return Option.some(nu$9({
  4508. anchorBox: anchorBox,
  4509. bubble: anchorInfo.bubble,
  4510. overrides: anchorInfo.overrides,
  4511. layouts: layouts,
  4512. placer: Option.none()
  4513. }));
  4514. };
  4515. var MakeshiftAnchor = [
  4516. strict$1('x'),
  4517. strict$1('y'),
  4518. defaulted$1('height', 0),
  4519. defaulted$1('width', 0),
  4520. defaulted$1('bubble', fallback()),
  4521. defaulted$1('overrides', {}),
  4522. schema$1(),
  4523. output('placement', placement$1)
  4524. ];
  4525. var zeroWidth = '\uFEFF';
  4526. var nbsp = '\xA0';
  4527. var create$2 = Immutable('start', 'soffset', 'finish', 'foffset');
  4528. var SimRange = { create: create$2 };
  4529. var adt$5 = Adt.generate([
  4530. { before: ['element'] },
  4531. {
  4532. on: [
  4533. 'element',
  4534. 'offset'
  4535. ]
  4536. },
  4537. { after: ['element'] }
  4538. ]);
  4539. var cata$2 = function (subject, onBefore, onOn, onAfter) {
  4540. return subject.fold(onBefore, onOn, onAfter);
  4541. };
  4542. var getStart = function (situ) {
  4543. return situ.fold(identity, identity, identity);
  4544. };
  4545. var before$2 = adt$5.before;
  4546. var on = adt$5.on;
  4547. var after$1 = adt$5.after;
  4548. var Situ = {
  4549. before: before$2,
  4550. on: on,
  4551. after: after$1,
  4552. cata: cata$2,
  4553. getStart: getStart
  4554. };
  4555. var adt$6 = Adt.generate([
  4556. { domRange: ['rng'] },
  4557. {
  4558. relative: [
  4559. 'startSitu',
  4560. 'finishSitu'
  4561. ]
  4562. },
  4563. {
  4564. exact: [
  4565. 'start',
  4566. 'soffset',
  4567. 'finish',
  4568. 'foffset'
  4569. ]
  4570. }
  4571. ]);
  4572. var exactFromRange = function (simRange) {
  4573. return adt$6.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  4574. };
  4575. var getStart$1 = function (selection) {
  4576. return selection.match({
  4577. domRange: function (rng) {
  4578. return Element.fromDom(rng.startContainer);
  4579. },
  4580. relative: function (startSitu, finishSitu) {
  4581. return Situ.getStart(startSitu);
  4582. },
  4583. exact: function (start, soffset, finish, foffset) {
  4584. return start;
  4585. }
  4586. });
  4587. };
  4588. var domRange = adt$6.domRange;
  4589. var relative$1 = adt$6.relative;
  4590. var exact = adt$6.exact;
  4591. var getWin = function (selection) {
  4592. var start = getStart$1(selection);
  4593. return defaultView(start);
  4594. };
  4595. var range$1 = SimRange.create;
  4596. var Selection = {
  4597. domRange: domRange,
  4598. relative: relative$1,
  4599. exact: exact,
  4600. exactFromRange: exactFromRange,
  4601. getWin: getWin,
  4602. range: range$1
  4603. };
  4604. var setStart = function (rng, situ) {
  4605. situ.fold(function (e) {
  4606. rng.setStartBefore(e.dom());
  4607. }, function (e, o) {
  4608. rng.setStart(e.dom(), o);
  4609. }, function (e) {
  4610. rng.setStartAfter(e.dom());
  4611. });
  4612. };
  4613. var setFinish = function (rng, situ) {
  4614. situ.fold(function (e) {
  4615. rng.setEndBefore(e.dom());
  4616. }, function (e, o) {
  4617. rng.setEnd(e.dom(), o);
  4618. }, function (e) {
  4619. rng.setEndAfter(e.dom());
  4620. });
  4621. };
  4622. var relativeToNative = function (win, startSitu, finishSitu) {
  4623. var range = win.document.createRange();
  4624. setStart(range, startSitu);
  4625. setFinish(range, finishSitu);
  4626. return range;
  4627. };
  4628. var exactToNative = function (win, start, soffset, finish, foffset) {
  4629. var rng = win.document.createRange();
  4630. rng.setStart(start.dom(), soffset);
  4631. rng.setEnd(finish.dom(), foffset);
  4632. return rng;
  4633. };
  4634. var toRect = function (rect) {
  4635. return {
  4636. left: constant(rect.left),
  4637. top: constant(rect.top),
  4638. right: constant(rect.right),
  4639. bottom: constant(rect.bottom),
  4640. width: constant(rect.width),
  4641. height: constant(rect.height)
  4642. };
  4643. };
  4644. var getFirstRect = function (rng) {
  4645. var rects = rng.getClientRects();
  4646. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  4647. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  4648. };
  4649. var adt$7 = Adt.generate([
  4650. {
  4651. ltr: [
  4652. 'start',
  4653. 'soffset',
  4654. 'finish',
  4655. 'foffset'
  4656. ]
  4657. },
  4658. {
  4659. rtl: [
  4660. 'start',
  4661. 'soffset',
  4662. 'finish',
  4663. 'foffset'
  4664. ]
  4665. }
  4666. ]);
  4667. var fromRange = function (win, type, range) {
  4668. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  4669. };
  4670. var getRanges = function (win, selection) {
  4671. return selection.match({
  4672. domRange: function (rng) {
  4673. return {
  4674. ltr: constant(rng),
  4675. rtl: Option.none
  4676. };
  4677. },
  4678. relative: function (startSitu, finishSitu) {
  4679. return {
  4680. ltr: cached(function () {
  4681. return relativeToNative(win, startSitu, finishSitu);
  4682. }),
  4683. rtl: cached(function () {
  4684. return Option.some(relativeToNative(win, finishSitu, startSitu));
  4685. })
  4686. };
  4687. },
  4688. exact: function (start, soffset, finish, foffset) {
  4689. return {
  4690. ltr: cached(function () {
  4691. return exactToNative(win, start, soffset, finish, foffset);
  4692. }),
  4693. rtl: cached(function () {
  4694. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  4695. })
  4696. };
  4697. }
  4698. });
  4699. };
  4700. var doDiagnose = function (win, ranges) {
  4701. var rng = ranges.ltr();
  4702. if (rng.collapsed) {
  4703. var reversed = ranges.rtl().filter(function (rev) {
  4704. return rev.collapsed === false;
  4705. });
  4706. return reversed.map(function (rev) {
  4707. return adt$7.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  4708. }).getOrThunk(function () {
  4709. return fromRange(win, adt$7.ltr, rng);
  4710. });
  4711. } else {
  4712. return fromRange(win, adt$7.ltr, rng);
  4713. }
  4714. };
  4715. var diagnose = function (win, selection) {
  4716. var ranges = getRanges(win, selection);
  4717. return doDiagnose(win, ranges);
  4718. };
  4719. var asLtrRange = function (win, selection) {
  4720. var diagnosis = diagnose(win, selection);
  4721. return diagnosis.match({
  4722. ltr: function (start, soffset, finish, foffset) {
  4723. var rng = win.document.createRange();
  4724. rng.setStart(start.dom(), soffset);
  4725. rng.setEnd(finish.dom(), foffset);
  4726. return rng;
  4727. },
  4728. rtl: function (start, soffset, finish, foffset) {
  4729. var rng = win.document.createRange();
  4730. rng.setStart(finish.dom(), foffset);
  4731. rng.setEnd(start.dom(), soffset);
  4732. return rng;
  4733. }
  4734. });
  4735. };
  4736. var ltr = adt$7.ltr;
  4737. var rtl = adt$7.rtl;
  4738. function NodeValue (is, name) {
  4739. var get = function (element) {
  4740. if (!is(element)) {
  4741. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  4742. }
  4743. return getOption(element).getOr('');
  4744. };
  4745. var getOption = function (element) {
  4746. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  4747. };
  4748. var set = function (element, value) {
  4749. if (!is(element)) {
  4750. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  4751. }
  4752. element.dom().nodeValue = value;
  4753. };
  4754. return {
  4755. get: get,
  4756. getOption: getOption,
  4757. set: set
  4758. };
  4759. }
  4760. var api$2 = NodeValue(isText, 'text');
  4761. var get$b = function (element) {
  4762. return api$2.get(element);
  4763. };
  4764. var getOption = function (element) {
  4765. return api$2.getOption(element);
  4766. };
  4767. var getEnd = function (element) {
  4768. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  4769. return children(element).length;
  4770. }, function (v) {
  4771. return v.length;
  4772. });
  4773. };
  4774. var isTextNodeWithCursorPosition = function (el) {
  4775. return getOption(el).filter(function (text) {
  4776. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  4777. }).isSome();
  4778. };
  4779. var elementsWithCursorPosition = [
  4780. 'img',
  4781. 'br'
  4782. ];
  4783. var isCursorPosition = function (elem) {
  4784. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  4785. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  4786. };
  4787. var last$1 = function (element) {
  4788. return descendantRtl(element, isCursorPosition);
  4789. };
  4790. var descendantRtl = function (scope, predicate) {
  4791. var descend = function (element) {
  4792. var children$1 = children(element);
  4793. for (var i = children$1.length - 1; i >= 0; i--) {
  4794. var child = children$1[i];
  4795. if (predicate(child)) {
  4796. return Option.some(child);
  4797. }
  4798. var res = descend(child);
  4799. if (res.isSome()) {
  4800. return res;
  4801. }
  4802. }
  4803. return Option.none();
  4804. };
  4805. return descend(scope);
  4806. };
  4807. var descendants = function (scope, selector) {
  4808. return all(selector, scope);
  4809. };
  4810. var makeRange = function (start, soffset, finish, foffset) {
  4811. var doc = owner(start);
  4812. var rng = doc.dom().createRange();
  4813. rng.setStart(start.dom(), soffset);
  4814. rng.setEnd(finish.dom(), foffset);
  4815. return rng;
  4816. };
  4817. var after$2 = function (start, soffset, finish, foffset) {
  4818. var r = makeRange(start, soffset, finish, foffset);
  4819. var same = eq(start, finish) && soffset === foffset;
  4820. return r.collapsed && !same;
  4821. };
  4822. var readRange = function (selection) {
  4823. if (selection.rangeCount > 0) {
  4824. var firstRng = selection.getRangeAt(0);
  4825. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  4826. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  4827. } else {
  4828. return Option.none();
  4829. }
  4830. };
  4831. var doGetExact = function (selection) {
  4832. var anchor = Element.fromDom(selection.anchorNode);
  4833. var focus = Element.fromDom(selection.focusNode);
  4834. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  4835. };
  4836. var getExact = function (win) {
  4837. return Option.from(win.getSelection()).filter(function (sel) {
  4838. return sel.rangeCount > 0;
  4839. }).bind(doGetExact);
  4840. };
  4841. var getFirstRect$1 = function (win, selection) {
  4842. var rng = asLtrRange(win, selection);
  4843. return getFirstRect(rng);
  4844. };
  4845. var point = Immutable('element', 'offset');
  4846. var descendOnce = function (element, offset) {
  4847. var children$1 = children(element);
  4848. if (children$1.length === 0) {
  4849. return point(element, offset);
  4850. } else if (offset < children$1.length) {
  4851. return point(children$1[offset], 0);
  4852. } else {
  4853. var last = children$1[children$1.length - 1];
  4854. var len = isText(last) ? get$b(last).length : children(last).length;
  4855. return point(last, len);
  4856. }
  4857. };
  4858. var adt$8 = Adt.generate([
  4859. { screen: ['point'] },
  4860. {
  4861. absolute: [
  4862. 'point',
  4863. 'scrollLeft',
  4864. 'scrollTop'
  4865. ]
  4866. }
  4867. ]);
  4868. var toFixed = function (pos) {
  4869. return pos.fold(identity, function (point, scrollLeft, scrollTop) {
  4870. return point.translate(-scrollLeft, -scrollTop);
  4871. });
  4872. };
  4873. var toAbsolute = function (pos) {
  4874. return pos.fold(identity, identity);
  4875. };
  4876. var sum = function (points) {
  4877. return foldl(points, function (b, a) {
  4878. return b.translate(a.left(), a.top());
  4879. }, Position(0, 0));
  4880. };
  4881. var sumAsFixed = function (positions) {
  4882. var points = map(positions, toFixed);
  4883. return sum(points);
  4884. };
  4885. var sumAsAbsolute = function (positions) {
  4886. var points = map(positions, toAbsolute);
  4887. return sum(points);
  4888. };
  4889. var screen = adt$8.screen;
  4890. var absolute$2 = adt$8.absolute;
  4891. var getOffset = function (component, origin, anchorInfo) {
  4892. var win = defaultView(anchorInfo.root).dom();
  4893. var hasSameOwner = function (frame) {
  4894. var frameOwner = owner(frame);
  4895. var compOwner = owner(component.element());
  4896. return eq(frameOwner, compOwner);
  4897. };
  4898. return Option.from(win.frameElement).map(Element.fromDom).filter(hasSameOwner).map(absolute);
  4899. };
  4900. var getRootPoint = function (component, origin, anchorInfo) {
  4901. var doc = owner(component.element());
  4902. var outerScroll = get$8(doc);
  4903. var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  4904. return absolute$2(offset, outerScroll.left(), outerScroll.top());
  4905. };
  4906. var capRect = function (left, top, width, height) {
  4907. var newLeft = left, newTop = top, newWidth = width, newHeight = height;
  4908. if (left < 0) {
  4909. newLeft = 0;
  4910. newWidth = width + left;
  4911. }
  4912. if (top < 0) {
  4913. newTop = 0;
  4914. newHeight = height + top;
  4915. }
  4916. var point = screen(Position(newLeft, newTop));
  4917. return Option.some(pointed(point, newWidth, newHeight));
  4918. };
  4919. var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  4920. return optBox.map(function (box) {
  4921. var points = [
  4922. rootPoint,
  4923. box.point()
  4924. ];
  4925. var topLeft = cata$1(origin, function () {
  4926. return sumAsAbsolute(points);
  4927. }, function () {
  4928. return sumAsAbsolute(points);
  4929. }, function () {
  4930. return sumAsFixed(points);
  4931. });
  4932. var anchorBox = rect(topLeft.left(), topLeft.top(), box.width(), box.height());
  4933. var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  4934. var layoutsRtl = anchorInfo.showAbove ? belowOrAboveRtl() : belowOrAboveRtl();
  4935. var layouts = get$a(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Option.none());
  4936. return nu$9({
  4937. anchorBox: anchorBox,
  4938. bubble: anchorInfo.bubble.getOr(fallback()),
  4939. overrides: anchorInfo.overrides,
  4940. layouts: layouts,
  4941. placer: Option.none()
  4942. });
  4943. });
  4944. };
  4945. var ContentAnchorCommon = {
  4946. capRect: capRect,
  4947. calcNewAnchor: calcNewAnchor
  4948. };
  4949. var point$1 = Immutable('element', 'offset');
  4950. var descendOnce$1 = function (element, offset) {
  4951. return isText(element) ? point$1(element, offset) : descendOnce(element, offset);
  4952. };
  4953. var getAnchorSelection = function (win, anchorInfo) {
  4954. var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  4955. return function () {
  4956. return getExact(win);
  4957. };
  4958. });
  4959. return getSelection().map(function (sel) {
  4960. var modStart = descendOnce$1(sel.start(), sel.soffset());
  4961. var modFinish = descendOnce$1(sel.finish(), sel.foffset());
  4962. return Selection.range(modStart.element(), modStart.offset(), modFinish.element(), modFinish.offset());
  4963. });
  4964. };
  4965. var placement$2 = function (component, anchorInfo, origin) {
  4966. var win = defaultView(anchorInfo.root).dom();
  4967. var rootPoint = getRootPoint(component, origin, anchorInfo);
  4968. var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  4969. var optRect = getFirstRect$1(win, Selection.exactFromRange(sel)).orThunk(function () {
  4970. var x = Element.fromText(zeroWidth);
  4971. before(sel.start(), x);
  4972. return getFirstRect$1(win, Selection.exact(x, 0, x, 1)).map(function (rect) {
  4973. remove(x);
  4974. return rect;
  4975. });
  4976. });
  4977. return optRect.bind(function (rawRect) {
  4978. return ContentAnchorCommon.capRect(rawRect.left(), rawRect.top(), rawRect.width(), rawRect.height());
  4979. });
  4980. });
  4981. var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  4982. return isElement(sel.start()) ? Option.some(sel.start()) : parent(sel.start());
  4983. });
  4984. var elem = targetElement.getOr(component.element());
  4985. return ContentAnchorCommon.calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  4986. };
  4987. var SelectionAnchor = [
  4988. option('getSelection'),
  4989. strict$1('root'),
  4990. option('bubble'),
  4991. schema$1(),
  4992. defaulted$1('overrides', {}),
  4993. defaulted$1('showAbove', false),
  4994. output('placement', placement$2)
  4995. ];
  4996. var placement$3 = function (component, anchorInfo, origin) {
  4997. var rootPoint = getRootPoint(component, origin, anchorInfo);
  4998. return anchorInfo.node.bind(function (target) {
  4999. var rect = target.dom().getBoundingClientRect();
  5000. var nodeBox = ContentAnchorCommon.capRect(rect.left, rect.top, rect.width, rect.height);
  5001. var elem = anchorInfo.node.getOr(component.element());
  5002. return ContentAnchorCommon.calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  5003. });
  5004. };
  5005. var NodeAnchor = [
  5006. strict$1('node'),
  5007. strict$1('root'),
  5008. option('bubble'),
  5009. schema$1(),
  5010. defaulted$1('overrides', {}),
  5011. defaulted$1('showAbove', false),
  5012. output('placement', placement$3)
  5013. ];
  5014. var eastX$1 = function (anchor) {
  5015. return anchor.x() + anchor.width();
  5016. };
  5017. var westX$1 = function (anchor, element) {
  5018. return anchor.x() - element.width();
  5019. };
  5020. var northY$1 = function (anchor, element) {
  5021. return anchor.y() - element.height() + anchor.height();
  5022. };
  5023. var southY$1 = function (anchor) {
  5024. return anchor.y();
  5025. };
  5026. var southeast$2 = function (anchor, element, bubbles) {
  5027. return nu$7(eastX$1(anchor), southY$1(anchor), bubbles.southeast(), southeast(), 'link-layout-se');
  5028. };
  5029. var southwest$2 = function (anchor, element, bubbles) {
  5030. return nu$7(westX$1(anchor, element), southY$1(anchor), bubbles.southwest(), southwest(), 'link-layout-sw');
  5031. };
  5032. var northeast$2 = function (anchor, element, bubbles) {
  5033. return nu$7(eastX$1(anchor), northY$1(anchor, element), bubbles.northeast(), northeast(), 'link-layout-ne');
  5034. };
  5035. var northwest$2 = function (anchor, element, bubbles) {
  5036. return nu$7(westX$1(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest(), 'link-layout-nw');
  5037. };
  5038. var all$3 = function () {
  5039. return [
  5040. southeast$2,
  5041. southwest$2,
  5042. northeast$2,
  5043. northwest$2
  5044. ];
  5045. };
  5046. var allRtl$1 = function () {
  5047. return [
  5048. southwest$2,
  5049. southeast$2,
  5050. northwest$2,
  5051. northeast$2
  5052. ];
  5053. };
  5054. var placement$4 = function (component, submenuInfo, origin) {
  5055. var anchorBox = toBox(origin, submenuInfo.item.element());
  5056. var layouts = get$a(component.element(), submenuInfo, all$3(), allRtl$1(), all$3(), allRtl$1(), Option.none());
  5057. return Option.some(nu$9({
  5058. anchorBox: anchorBox,
  5059. bubble: fallback(),
  5060. overrides: submenuInfo.overrides,
  5061. layouts: layouts,
  5062. placer: Option.none()
  5063. }));
  5064. };
  5065. var SubmenuAnchor = [
  5066. strict$1('item'),
  5067. schema$1(),
  5068. defaulted$1('overrides', {}),
  5069. output('placement', placement$4)
  5070. ];
  5071. var AnchorSchema = choose$1('anchor', {
  5072. selection: SelectionAnchor,
  5073. node: NodeAnchor,
  5074. hotspot: HotspotAnchor,
  5075. submenu: SubmenuAnchor,
  5076. makeshift: MakeshiftAnchor
  5077. });
  5078. var getFixedOrigin = function () {
  5079. var html = domGlobals.document.documentElement;
  5080. return fixed(0, 0, html.clientWidth, html.clientHeight);
  5081. };
  5082. var getRelativeOrigin = function (component) {
  5083. var position = absolute(component.element());
  5084. var bounds = component.element().dom().getBoundingClientRect();
  5085. return relative(position.left(), position.top(), bounds.width, bounds.height);
  5086. };
  5087. var place = function (component, origin, anchoring, getBounds, placee) {
  5088. var anchor = box$1(anchoring.anchorBox, origin);
  5089. simple(anchor, placee.element(), anchoring.bubble, anchoring.layouts, getBounds, anchoring.overrides);
  5090. };
  5091. var position$1 = function (component, posConfig, posState, anchor, placee) {
  5092. positionWithin(component, posConfig, posState, anchor, placee, Option.none());
  5093. };
  5094. var positionWithin = function (component, posConfig, posState, anchor, placee, boxElement) {
  5095. var boundsBox = boxElement.map(box);
  5096. return positionWithinBounds(component, posConfig, posState, anchor, placee, boundsBox);
  5097. };
  5098. var positionWithinBounds = function (component, posConfig, posState, anchor, placee, bounds) {
  5099. var anchorage = asRawOrDie('positioning anchor.info', AnchorSchema, anchor);
  5100. preserve(function () {
  5101. set$2(placee.element(), 'position', 'fixed');
  5102. var oldVisibility = getRaw(placee.element(), 'visibility');
  5103. set$2(placee.element(), 'visibility', 'hidden');
  5104. var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5105. var placer = anchorage.placement;
  5106. var getBounds = bounds.map(constant).or(posConfig.getBounds);
  5107. placer(component, anchorage, origin).each(function (anchoring) {
  5108. var doPlace = anchoring.placer.getOr(place);
  5109. doPlace(component, origin, anchoring, getBounds, placee);
  5110. });
  5111. oldVisibility.fold(function () {
  5112. remove$6(placee.element(), 'visibility');
  5113. }, function (vis) {
  5114. set$2(placee.element(), 'visibility', vis);
  5115. });
  5116. 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')) {
  5117. remove$6(placee.element(), 'position');
  5118. }
  5119. }, placee.element());
  5120. };
  5121. var getMode = function (component, pConfig, pState) {
  5122. return pConfig.useFixed() ? 'fixed' : 'absolute';
  5123. };
  5124. var PositionApis = /*#__PURE__*/Object.freeze({
  5125. __proto__: null,
  5126. position: position$1,
  5127. positionWithin: positionWithin,
  5128. positionWithinBounds: positionWithinBounds,
  5129. getMode: getMode
  5130. });
  5131. var PositionSchema = [
  5132. defaulted$1('useFixed', never),
  5133. option('getBounds')
  5134. ];
  5135. var Positioning = create$1({
  5136. fields: PositionSchema,
  5137. name: 'positioning',
  5138. active: ActivePosition,
  5139. apis: PositionApis
  5140. });
  5141. var fireDetaching = function (component) {
  5142. emit(component, detachedFromDom());
  5143. var children = component.components();
  5144. each(children, fireDetaching);
  5145. };
  5146. var fireAttaching = function (component) {
  5147. var children = component.components();
  5148. each(children, fireAttaching);
  5149. emit(component, attachedToDom());
  5150. };
  5151. var attach = function (parent, child) {
  5152. append(parent.element(), child.element());
  5153. };
  5154. var detachChildren = function (component) {
  5155. each(component.components(), function (childComp) {
  5156. return remove(childComp.element());
  5157. });
  5158. empty(component.element());
  5159. component.syncComponents();
  5160. };
  5161. var replaceChildren = function (component, newChildren) {
  5162. var subs = component.components();
  5163. detachChildren(component);
  5164. var deleted = difference(subs, newChildren);
  5165. each(deleted, function (comp) {
  5166. fireDetaching(comp);
  5167. component.getSystem().removeFromWorld(comp);
  5168. });
  5169. each(newChildren, function (childComp) {
  5170. if (!childComp.getSystem().isConnected()) {
  5171. component.getSystem().addToWorld(childComp);
  5172. attach(component, childComp);
  5173. if (inBody(component.element())) {
  5174. fireAttaching(childComp);
  5175. }
  5176. } else {
  5177. attach(component, childComp);
  5178. }
  5179. component.syncComponents();
  5180. });
  5181. };
  5182. var attach$1 = function (parent, child) {
  5183. attachWith(parent, child, append);
  5184. };
  5185. var attachWith = function (parent, child, insertion) {
  5186. parent.getSystem().addToWorld(child);
  5187. insertion(parent.element(), child.element());
  5188. if (inBody(parent.element())) {
  5189. fireAttaching(child);
  5190. }
  5191. parent.syncComponents();
  5192. };
  5193. var doDetach = function (component) {
  5194. fireDetaching(component);
  5195. remove(component.element());
  5196. component.getSystem().removeFromWorld(component);
  5197. };
  5198. var detach = function (component) {
  5199. var parent$1 = parent(component.element()).bind(function (p) {
  5200. return component.getSystem().getByDom(p).toOption();
  5201. });
  5202. doDetach(component);
  5203. parent$1.each(function (p) {
  5204. p.syncComponents();
  5205. });
  5206. };
  5207. var detachChildren$1 = function (component) {
  5208. var subs = component.components();
  5209. each(subs, doDetach);
  5210. empty(component.element());
  5211. component.syncComponents();
  5212. };
  5213. var attachSystem = function (element, guiSystem) {
  5214. attachSystemWith(element, guiSystem, append);
  5215. };
  5216. var attachSystemAfter = function (element, guiSystem) {
  5217. attachSystemWith(element, guiSystem, after);
  5218. };
  5219. var attachSystemWith = function (element, guiSystem, inserter) {
  5220. inserter(element, guiSystem.element());
  5221. var children$1 = children(guiSystem.element());
  5222. each(children$1, function (child) {
  5223. guiSystem.getByDom(child).each(fireAttaching);
  5224. });
  5225. };
  5226. var detachSystem = function (guiSystem) {
  5227. var children$1 = children(guiSystem.element());
  5228. each(children$1, function (child) {
  5229. guiSystem.getByDom(child).each(fireDetaching);
  5230. });
  5231. remove(guiSystem.element());
  5232. };
  5233. var rebuild = function (sandbox, sConfig, sState, data) {
  5234. sState.get().each(function (data) {
  5235. detachChildren$1(sandbox);
  5236. });
  5237. var point = sConfig.getAttachPoint(sandbox);
  5238. attach$1(point, sandbox);
  5239. var built = sandbox.getSystem().build(data);
  5240. attach$1(sandbox, built);
  5241. sState.set(built);
  5242. return built;
  5243. };
  5244. var open = function (sandbox, sConfig, sState, data) {
  5245. var newState = rebuild(sandbox, sConfig, sState, data);
  5246. sConfig.onOpen(sandbox, newState);
  5247. return newState;
  5248. };
  5249. var setContent = function (sandbox, sConfig, sState, data) {
  5250. return sState.get().map(function () {
  5251. return rebuild(sandbox, sConfig, sState, data);
  5252. });
  5253. };
  5254. var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5255. cloak(sandbox, sConfig);
  5256. open(sandbox, sConfig, sState, data);
  5257. transaction();
  5258. decloak(sandbox, sConfig);
  5259. };
  5260. var close = function (sandbox, sConfig, sState) {
  5261. sState.get().each(function (data) {
  5262. detachChildren$1(sandbox);
  5263. detach(sandbox);
  5264. sConfig.onClose(sandbox, data);
  5265. sState.clear();
  5266. });
  5267. };
  5268. var isOpen = function (sandbox, sConfig, sState) {
  5269. return sState.isOpen();
  5270. };
  5271. var isPartOf$1 = function (sandbox, sConfig, sState, queryElem) {
  5272. return isOpen(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5273. return sConfig.isPartOf(sandbox, data, queryElem);
  5274. });
  5275. };
  5276. var getState = function (sandbox, sConfig, sState) {
  5277. return sState.get();
  5278. };
  5279. var store = function (sandbox, cssKey, attr, newValue) {
  5280. getRaw(sandbox.element(), cssKey).fold(function () {
  5281. remove$1(sandbox.element(), attr);
  5282. }, function (v) {
  5283. set$1(sandbox.element(), attr, v);
  5284. });
  5285. set$2(sandbox.element(), cssKey, newValue);
  5286. };
  5287. var restore = function (sandbox, cssKey, attr) {
  5288. if (has$1(sandbox.element(), attr)) {
  5289. var oldValue = get$2(sandbox.element(), attr);
  5290. set$2(sandbox.element(), cssKey, oldValue);
  5291. } else {
  5292. remove$6(sandbox.element(), cssKey);
  5293. }
  5294. };
  5295. var cloak = function (sandbox, sConfig, sState) {
  5296. var sink = sConfig.getAttachPoint(sandbox);
  5297. set$2(sandbox.element(), 'position', Positioning.getMode(sink));
  5298. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5299. };
  5300. var hasPosition = function (element) {
  5301. return exists([
  5302. 'top',
  5303. 'left',
  5304. 'right',
  5305. 'bottom'
  5306. ], function (pos) {
  5307. return getRaw(element, pos).isSome();
  5308. });
  5309. };
  5310. var decloak = function (sandbox, sConfig, sState) {
  5311. if (!hasPosition(sandbox.element())) {
  5312. remove$6(sandbox.element(), 'position');
  5313. }
  5314. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  5315. };
  5316. var SandboxApis = /*#__PURE__*/Object.freeze({
  5317. __proto__: null,
  5318. cloak: cloak,
  5319. decloak: decloak,
  5320. open: open,
  5321. openWhileCloaked: openWhileCloaked,
  5322. close: close,
  5323. isOpen: isOpen,
  5324. isPartOf: isPartOf$1,
  5325. getState: getState,
  5326. setContent: setContent
  5327. });
  5328. var events$2 = function (sandboxConfig, sandboxState) {
  5329. return derive([run(sandboxClose(), function (sandbox, simulatedEvent) {
  5330. close(sandbox, sandboxConfig, sandboxState);
  5331. })]);
  5332. };
  5333. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  5334. __proto__: null,
  5335. events: events$2
  5336. });
  5337. var SandboxSchema = [
  5338. onHandler('onOpen'),
  5339. onHandler('onClose'),
  5340. strict$1('isPartOf'),
  5341. strict$1('getAttachPoint'),
  5342. defaulted$1('cloakVisibilityAttr', 'data-precloak-visibility')
  5343. ];
  5344. var init = function () {
  5345. var contents = Cell(Option.none());
  5346. var readState = constant('not-implemented');
  5347. var isOpen = function () {
  5348. return contents.get().isSome();
  5349. };
  5350. var set = function (comp) {
  5351. contents.set(Option.some(comp));
  5352. };
  5353. var get = function () {
  5354. return contents.get();
  5355. };
  5356. var clear = function () {
  5357. contents.set(Option.none());
  5358. };
  5359. return nu$5({
  5360. readState: readState,
  5361. isOpen: isOpen,
  5362. clear: clear,
  5363. set: set,
  5364. get: get
  5365. });
  5366. };
  5367. var SandboxState = /*#__PURE__*/Object.freeze({
  5368. __proto__: null,
  5369. init: init
  5370. });
  5371. var Sandboxing = create$1({
  5372. fields: SandboxSchema,
  5373. name: 'sandboxing',
  5374. active: ActiveSandbox,
  5375. apis: SandboxApis,
  5376. state: SandboxState
  5377. });
  5378. var dismissPopups = constant('dismiss.popups');
  5379. var repositionPopups = constant('reposition.popups');
  5380. var mouseReleased = constant('mouse.released');
  5381. var schema$2 = objOfOnly([
  5382. defaulted$1('isExtraPart', constant(false)),
  5383. optionObjOf('fireEventInstead', [defaulted$1('event', dismissRequested())])
  5384. ]);
  5385. var receivingChannel = function (rawSpec) {
  5386. var _a;
  5387. var detail = asRawOrDie('Dismissal', schema$2, rawSpec);
  5388. return _a = {}, _a[dismissPopups()] = {
  5389. schema: objOfOnly([strict$1('target')]),
  5390. onReceive: function (sandbox, data) {
  5391. if (Sandboxing.isOpen(sandbox)) {
  5392. var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  5393. if (!isPart) {
  5394. detail.fireEventInstead.fold(function () {
  5395. return Sandboxing.close(sandbox);
  5396. }, function (fe) {
  5397. return emit(sandbox, fe.event);
  5398. });
  5399. }
  5400. }
  5401. }
  5402. }, _a;
  5403. };
  5404. var schema$3 = objOfOnly([
  5405. defaulted$1('isExtraPart', constant(false)),
  5406. optionObjOf('fireEventInstead', [defaulted$1('event', repositionRequested())]),
  5407. strictFunction('doReposition')
  5408. ]);
  5409. var receivingChannel$1 = function (rawSpec) {
  5410. var _a;
  5411. var detail = asRawOrDie('Reposition', schema$3, rawSpec);
  5412. return _a = {}, _a[repositionPopups()] = {
  5413. onReceive: function (sandbox) {
  5414. if (Sandboxing.isOpen(sandbox)) {
  5415. detail.fireEventInstead.fold(function () {
  5416. return detail.doReposition(sandbox);
  5417. }, function (fe) {
  5418. return emit(sandbox, fe.event);
  5419. });
  5420. }
  5421. }
  5422. }, _a;
  5423. };
  5424. var onLoad = function (component, repConfig, repState) {
  5425. repConfig.store.manager.onLoad(component, repConfig, repState);
  5426. };
  5427. var onUnload = function (component, repConfig, repState) {
  5428. repConfig.store.manager.onUnload(component, repConfig, repState);
  5429. };
  5430. var setValue = function (component, repConfig, repState, data) {
  5431. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5432. };
  5433. var getValue = function (component, repConfig, repState) {
  5434. return repConfig.store.manager.getValue(component, repConfig, repState);
  5435. };
  5436. var getState$1 = function (component, repConfig, repState) {
  5437. return repState;
  5438. };
  5439. var RepresentApis = /*#__PURE__*/Object.freeze({
  5440. __proto__: null,
  5441. onLoad: onLoad,
  5442. onUnload: onUnload,
  5443. setValue: setValue,
  5444. getValue: getValue,
  5445. getState: getState$1
  5446. });
  5447. var events$3 = function (repConfig, repState) {
  5448. var es = repConfig.resetOnDom ? [
  5449. runOnAttached(function (comp, se) {
  5450. onLoad(comp, repConfig, repState);
  5451. }),
  5452. runOnDetached(function (comp, se) {
  5453. onUnload(comp, repConfig, repState);
  5454. })
  5455. ] : [loadEvent(repConfig, repState, onLoad)];
  5456. return derive(es);
  5457. };
  5458. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5459. __proto__: null,
  5460. events: events$3
  5461. });
  5462. var memory = function () {
  5463. var data = Cell(null);
  5464. var readState = function () {
  5465. return {
  5466. mode: 'memory',
  5467. value: data.get()
  5468. };
  5469. };
  5470. var isNotSet = function () {
  5471. return data.get() === null;
  5472. };
  5473. var clear = function () {
  5474. data.set(null);
  5475. };
  5476. return nu$5({
  5477. set: data.set,
  5478. get: data.get,
  5479. isNotSet: isNotSet,
  5480. clear: clear,
  5481. readState: readState
  5482. });
  5483. };
  5484. var manual = function () {
  5485. var readState = function () {
  5486. };
  5487. return nu$5({ readState: readState });
  5488. };
  5489. var dataset = function () {
  5490. var dataByValue = Cell({});
  5491. var dataByText = Cell({});
  5492. var readState = function () {
  5493. return {
  5494. mode: 'dataset',
  5495. dataByValue: dataByValue.get(),
  5496. dataByText: dataByText.get()
  5497. };
  5498. };
  5499. var clear = function () {
  5500. dataByValue.set({});
  5501. dataByText.set({});
  5502. };
  5503. var lookup = function (itemString) {
  5504. return get(dataByValue.get(), itemString).orThunk(function () {
  5505. return get(dataByText.get(), itemString);
  5506. });
  5507. };
  5508. var update = function (items) {
  5509. var currentDataByValue = dataByValue.get();
  5510. var currentDataByText = dataByText.get();
  5511. var newDataByValue = {};
  5512. var newDataByText = {};
  5513. each(items, function (item) {
  5514. newDataByValue[item.value] = item;
  5515. get(item, 'meta').each(function (meta) {
  5516. get(meta, 'text').each(function (text) {
  5517. newDataByText[text] = item;
  5518. });
  5519. });
  5520. });
  5521. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5522. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5523. };
  5524. return nu$5({
  5525. readState: readState,
  5526. lookup: lookup,
  5527. update: update,
  5528. clear: clear
  5529. });
  5530. };
  5531. var init$1 = function (spec) {
  5532. return spec.store.manager.state(spec);
  5533. };
  5534. var RepresentState = /*#__PURE__*/Object.freeze({
  5535. __proto__: null,
  5536. memory: memory,
  5537. dataset: dataset,
  5538. manual: manual,
  5539. init: init$1
  5540. });
  5541. var setValue$1 = function (component, repConfig, repState, data) {
  5542. var store = repConfig.store;
  5543. repState.update([data]);
  5544. store.setValue(component, data);
  5545. repConfig.onSetValue(component, data);
  5546. };
  5547. var getValue$1 = function (component, repConfig, repState) {
  5548. var store = repConfig.store;
  5549. var key = store.getDataKey(component);
  5550. return repState.lookup(key).fold(function () {
  5551. return store.getFallbackEntry(key);
  5552. }, function (data) {
  5553. return data;
  5554. });
  5555. };
  5556. var onLoad$1 = function (component, repConfig, repState) {
  5557. var store = repConfig.store;
  5558. store.initialValue.each(function (data) {
  5559. setValue$1(component, repConfig, repState, data);
  5560. });
  5561. };
  5562. var onUnload$1 = function (component, repConfig, repState) {
  5563. repState.clear();
  5564. };
  5565. var DatasetStore = [
  5566. option('initialValue'),
  5567. strict$1('getFallbackEntry'),
  5568. strict$1('getDataKey'),
  5569. strict$1('setValue'),
  5570. output('manager', {
  5571. setValue: setValue$1,
  5572. getValue: getValue$1,
  5573. onLoad: onLoad$1,
  5574. onUnload: onUnload$1,
  5575. state: dataset
  5576. })
  5577. ];
  5578. var getValue$2 = function (component, repConfig, repState) {
  5579. return repConfig.store.getValue(component);
  5580. };
  5581. var setValue$2 = function (component, repConfig, repState, data) {
  5582. repConfig.store.setValue(component, data);
  5583. repConfig.onSetValue(component, data);
  5584. };
  5585. var onLoad$2 = function (component, repConfig, repState) {
  5586. repConfig.store.initialValue.each(function (data) {
  5587. repConfig.store.setValue(component, data);
  5588. });
  5589. };
  5590. var ManualStore = [
  5591. strict$1('getValue'),
  5592. defaulted$1('setValue', noop),
  5593. option('initialValue'),
  5594. output('manager', {
  5595. setValue: setValue$2,
  5596. getValue: getValue$2,
  5597. onLoad: onLoad$2,
  5598. onUnload: noop,
  5599. state: NoState.init
  5600. })
  5601. ];
  5602. var setValue$3 = function (component, repConfig, repState, data) {
  5603. repState.set(data);
  5604. repConfig.onSetValue(component, data);
  5605. };
  5606. var getValue$3 = function (component, repConfig, repState) {
  5607. return repState.get();
  5608. };
  5609. var onLoad$3 = function (component, repConfig, repState) {
  5610. repConfig.store.initialValue.each(function (initVal) {
  5611. if (repState.isNotSet()) {
  5612. repState.set(initVal);
  5613. }
  5614. });
  5615. };
  5616. var onUnload$2 = function (component, repConfig, repState) {
  5617. repState.clear();
  5618. };
  5619. var MemoryStore = [
  5620. option('initialValue'),
  5621. output('manager', {
  5622. setValue: setValue$3,
  5623. getValue: getValue$3,
  5624. onLoad: onLoad$3,
  5625. onUnload: onUnload$2,
  5626. state: memory
  5627. })
  5628. ];
  5629. var RepresentSchema = [
  5630. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5631. memory: MemoryStore,
  5632. manual: ManualStore,
  5633. dataset: DatasetStore
  5634. })),
  5635. onHandler('onSetValue'),
  5636. defaulted$1('resetOnDom', false)
  5637. ];
  5638. var Representing = create$1({
  5639. fields: RepresentSchema,
  5640. name: 'representing',
  5641. active: ActiveRepresenting,
  5642. apis: RepresentApis,
  5643. extra: {
  5644. setValueFrom: function (component, source) {
  5645. var value = Representing.getValue(source);
  5646. Representing.setValue(component, value);
  5647. }
  5648. },
  5649. state: RepresentState
  5650. });
  5651. var field$1 = function (name, forbidden) {
  5652. return defaultedObjOf(name, {}, map(forbidden, function (f) {
  5653. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  5654. }).concat([state$1('dump', identity)]));
  5655. };
  5656. var get$c = function (data) {
  5657. return data.dump;
  5658. };
  5659. var augment = function (data, original) {
  5660. return __assign(__assign({}, data.dump), derive$1(original));
  5661. };
  5662. var SketchBehaviours = {
  5663. field: field$1,
  5664. augment: augment,
  5665. get: get$c
  5666. };
  5667. var _placeholder = 'placeholder';
  5668. var adt$9 = Adt.generate([
  5669. {
  5670. single: [
  5671. 'required',
  5672. 'valueThunk'
  5673. ]
  5674. },
  5675. {
  5676. multiple: [
  5677. 'required',
  5678. 'valueThunks'
  5679. ]
  5680. }
  5681. ]);
  5682. var isSubstituted = function (spec) {
  5683. return has(spec, 'uiType');
  5684. };
  5685. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  5686. if (owner.exists(function (o) {
  5687. return o !== compSpec.owner;
  5688. })) {
  5689. return adt$9.single(true, constant(compSpec));
  5690. }
  5691. return get(placeholders, compSpec.name).fold(function () {
  5692. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  5693. }, function (newSpec) {
  5694. return newSpec.replace();
  5695. });
  5696. };
  5697. var scan = function (owner, detail, compSpec, placeholders) {
  5698. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  5699. return subPlaceholder(owner, detail, compSpec, placeholders);
  5700. } else {
  5701. return adt$9.single(false, constant(compSpec));
  5702. }
  5703. };
  5704. var substitute = function (owner, detail, compSpec, placeholders) {
  5705. var base = scan(owner, detail, compSpec, placeholders);
  5706. return base.fold(function (req, valueThunk) {
  5707. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  5708. var childSpecs = get(value, 'components').getOr([]);
  5709. var substituted = bind(childSpecs, function (c) {
  5710. return substitute(owner, detail, c, placeholders);
  5711. });
  5712. return [__assign(__assign({}, value), { components: substituted })];
  5713. }, function (req, valuesThunk) {
  5714. if (isSubstituted(compSpec)) {
  5715. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  5716. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  5717. return preprocessor(values);
  5718. } else {
  5719. return valuesThunk(detail);
  5720. }
  5721. });
  5722. };
  5723. var substituteAll = function (owner, detail, components, placeholders) {
  5724. return bind(components, function (c) {
  5725. return substitute(owner, detail, c, placeholders);
  5726. });
  5727. };
  5728. var oneReplace = function (label, replacements) {
  5729. var called = false;
  5730. var used = function () {
  5731. return called;
  5732. };
  5733. var replace = function () {
  5734. if (called) {
  5735. throw new Error('Trying to use the same placeholder more than once: ' + label);
  5736. }
  5737. called = true;
  5738. return replacements;
  5739. };
  5740. var required = function () {
  5741. return replacements.fold(function (req, _) {
  5742. return req;
  5743. }, function (req, _) {
  5744. return req;
  5745. });
  5746. };
  5747. return {
  5748. name: constant(label),
  5749. required: required,
  5750. used: used,
  5751. replace: replace
  5752. };
  5753. };
  5754. var substitutePlaces = function (owner, detail, components, placeholders) {
  5755. var ps = map$1(placeholders, function (ph, name) {
  5756. return oneReplace(name, ph);
  5757. });
  5758. var outcome = substituteAll(owner, detail, components, ps);
  5759. each$1(ps, function (p) {
  5760. if (p.used() === false && p.required()) {
  5761. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  5762. }
  5763. });
  5764. return outcome;
  5765. };
  5766. var single = adt$9.single;
  5767. var multiple = adt$9.multiple;
  5768. var placeholder = constant(_placeholder);
  5769. var adt$a = Adt.generate([
  5770. { required: ['data'] },
  5771. { external: ['data'] },
  5772. { optional: ['data'] },
  5773. { group: ['data'] }
  5774. ]);
  5775. var fFactory = defaulted$1('factory', { sketch: identity });
  5776. var fSchema = defaulted$1('schema', []);
  5777. var fName = strict$1('name');
  5778. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  5779. return '<alloy.' + generate$1(typeSpec.name) + '>';
  5780. }), anyValue$1());
  5781. var fGroupSchema = state$1('schema', function () {
  5782. return [option('preprocess')];
  5783. });
  5784. var fDefaults = defaulted$1('defaults', constant({}));
  5785. var fOverrides = defaulted$1('overrides', constant({}));
  5786. var requiredSpec = objOf([
  5787. fFactory,
  5788. fSchema,
  5789. fName,
  5790. fPname,
  5791. fDefaults,
  5792. fOverrides
  5793. ]);
  5794. var externalSpec = objOf([
  5795. fFactory,
  5796. fSchema,
  5797. fName,
  5798. fDefaults,
  5799. fOverrides
  5800. ]);
  5801. var optionalSpec = objOf([
  5802. fFactory,
  5803. fSchema,
  5804. fName,
  5805. fPname,
  5806. fDefaults,
  5807. fOverrides
  5808. ]);
  5809. var groupSpec = objOf([
  5810. fFactory,
  5811. fGroupSchema,
  5812. fName,
  5813. strict$1('unit'),
  5814. fPname,
  5815. fDefaults,
  5816. fOverrides
  5817. ]);
  5818. var asNamedPart = function (part) {
  5819. return part.fold(Option.some, Option.none, Option.some, Option.some);
  5820. };
  5821. var name$1 = function (part) {
  5822. var get = function (data) {
  5823. return data.name;
  5824. };
  5825. return part.fold(get, get, get, get);
  5826. };
  5827. var asCommon = function (part) {
  5828. return part.fold(identity, identity, identity, identity);
  5829. };
  5830. var convert = function (adtConstructor, partSchema) {
  5831. return function (spec) {
  5832. var data = asRawOrDie('Converting part type', partSchema, spec);
  5833. return adtConstructor(data);
  5834. };
  5835. };
  5836. var required = convert(adt$a.required, requiredSpec);
  5837. var external$1 = convert(adt$a.external, externalSpec);
  5838. var optional = convert(adt$a.optional, optionalSpec);
  5839. var group = convert(adt$a.group, groupSpec);
  5840. var original = constant('entirety');
  5841. var PartType = /*#__PURE__*/Object.freeze({
  5842. __proto__: null,
  5843. required: required,
  5844. external: external$1,
  5845. optional: optional,
  5846. group: group,
  5847. asNamedPart: asNamedPart,
  5848. name: name$1,
  5849. asCommon: asCommon,
  5850. original: original
  5851. });
  5852. var combine$2 = function (detail, data, partSpec, partValidated) {
  5853. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  5854. };
  5855. var subs = function (owner, detail, parts) {
  5856. var internals = {};
  5857. var externals = {};
  5858. each(parts, function (part) {
  5859. part.fold(function (data) {
  5860. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  5861. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5862. });
  5863. }, function (data) {
  5864. var partSpec = detail.parts[data.name];
  5865. externals[data.name] = constant(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  5866. }, function (data) {
  5867. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  5868. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5869. });
  5870. }, function (data) {
  5871. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  5872. var units = detail[data.name];
  5873. return map(units, function (u) {
  5874. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  5875. });
  5876. });
  5877. });
  5878. });
  5879. return {
  5880. internals: constant(internals),
  5881. externals: constant(externals)
  5882. };
  5883. };
  5884. var generate$4 = function (owner, parts) {
  5885. var r = {};
  5886. each(parts, function (part) {
  5887. asNamedPart(part).each(function (np) {
  5888. var g = doGenerateOne(owner, np.pname);
  5889. r[np.name] = function (config) {
  5890. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  5891. return __assign(__assign({}, g), {
  5892. config: config,
  5893. validated: validated
  5894. });
  5895. };
  5896. });
  5897. });
  5898. return r;
  5899. };
  5900. var doGenerateOne = function (owner, pname) {
  5901. return {
  5902. uiType: placeholder(),
  5903. owner: owner,
  5904. name: pname
  5905. };
  5906. };
  5907. var generateOne = function (owner, pname, config) {
  5908. return {
  5909. uiType: placeholder(),
  5910. owner: owner,
  5911. name: pname,
  5912. config: config,
  5913. validated: {}
  5914. };
  5915. };
  5916. var schemas = function (parts) {
  5917. return bind(parts, function (part) {
  5918. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  5919. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  5920. }).toArray();
  5921. });
  5922. };
  5923. var names = function (parts) {
  5924. return map(parts, name$1);
  5925. };
  5926. var substitutes = function (owner, detail, parts) {
  5927. return subs(owner, detail, parts);
  5928. };
  5929. var components = function (owner, detail, internals) {
  5930. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  5931. };
  5932. var getPart = function (component, detail, partKey) {
  5933. var uid = detail.partUids[partKey];
  5934. return component.getSystem().getByUid(uid).toOption();
  5935. };
  5936. var getPartOrDie = function (component, detail, partKey) {
  5937. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  5938. };
  5939. var getParts = function (component, detail, partKeys) {
  5940. var r = {};
  5941. var uids = detail.partUids;
  5942. var system = component.getSystem();
  5943. each(partKeys, function (pk) {
  5944. r[pk] = constant(system.getByUid(uids[pk]));
  5945. });
  5946. return r;
  5947. };
  5948. var getAllParts = function (component, detail) {
  5949. var system = component.getSystem();
  5950. return map$1(detail.partUids, function (pUid, k) {
  5951. return constant(system.getByUid(pUid));
  5952. });
  5953. };
  5954. var getAllPartNames = function (detail) {
  5955. return keys(detail.partUids);
  5956. };
  5957. var getPartsOrDie = function (component, detail, partKeys) {
  5958. var r = {};
  5959. var uids = detail.partUids;
  5960. var system = component.getSystem();
  5961. each(partKeys, function (pk) {
  5962. r[pk] = constant(system.getByUid(uids[pk]).getOrDie());
  5963. });
  5964. return r;
  5965. };
  5966. var defaultUids = function (baseUid, partTypes) {
  5967. var partNames = names(partTypes);
  5968. return wrapAll$1(map(partNames, function (pn) {
  5969. return {
  5970. key: pn,
  5971. value: baseUid + '-' + pn
  5972. };
  5973. }));
  5974. };
  5975. var defaultUidsSchema = function (partTypes) {
  5976. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  5977. return defaultUids(spec.uid, partTypes);
  5978. }), anyValue$1());
  5979. };
  5980. var AlloyParts = /*#__PURE__*/Object.freeze({
  5981. __proto__: null,
  5982. generate: generate$4,
  5983. generateOne: generateOne,
  5984. schemas: schemas,
  5985. names: names,
  5986. substitutes: substitutes,
  5987. components: components,
  5988. defaultUids: defaultUids,
  5989. defaultUidsSchema: defaultUidsSchema,
  5990. getAllParts: getAllParts,
  5991. getAllPartNames: getAllPartNames,
  5992. getPart: getPart,
  5993. getPartOrDie: getPartOrDie,
  5994. getParts: getParts,
  5995. getPartsOrDie: getPartsOrDie
  5996. });
  5997. var base = function (partSchemas, partUidsSchemas) {
  5998. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  5999. return ps.concat([
  6000. strict$1('uid'),
  6001. defaulted$1('dom', {}),
  6002. defaulted$1('components', []),
  6003. snapshot('originalSpec'),
  6004. defaulted$1('debug.sketcher', {})
  6005. ]).concat(partUidsSchemas);
  6006. };
  6007. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6008. var baseS = base(partSchemas, partUidsSchemas);
  6009. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6010. };
  6011. var single$1 = function (owner, schema, factory, spec) {
  6012. var specWithUid = supplyUid(spec);
  6013. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  6014. return factory(detail, specWithUid);
  6015. };
  6016. var composite = function (owner, schema, partTypes, factory, spec) {
  6017. var specWithUid = supplyUid(spec);
  6018. var partSchemas = schemas(partTypes);
  6019. var partUidsSchema = defaultUidsSchema(partTypes);
  6020. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6021. var subs = substitutes(owner, detail, partTypes);
  6022. var components$1 = components(owner, detail, subs.internals());
  6023. return factory(detail, components$1, specWithUid, subs.externals());
  6024. };
  6025. var hasUid = function (spec) {
  6026. return has(spec, 'uid');
  6027. };
  6028. var supplyUid = function (spec) {
  6029. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  6030. };
  6031. function isSketchSpec(spec) {
  6032. return spec.uid !== undefined;
  6033. }
  6034. var singleSchema = objOfOnly([
  6035. strict$1('name'),
  6036. strict$1('factory'),
  6037. strict$1('configFields'),
  6038. defaulted$1('apis', {}),
  6039. defaulted$1('extraApis', {})
  6040. ]);
  6041. var compositeSchema = objOfOnly([
  6042. strict$1('name'),
  6043. strict$1('factory'),
  6044. strict$1('configFields'),
  6045. strict$1('partFields'),
  6046. defaulted$1('apis', {}),
  6047. defaulted$1('extraApis', {})
  6048. ]);
  6049. var single$2 = function (rawConfig) {
  6050. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6051. var sketch = function (spec) {
  6052. return single$1(config.name, config.configFields, config.factory, spec);
  6053. };
  6054. var apis = map$1(config.apis, makeApi);
  6055. var extraApis = map$1(config.extraApis, function (f, k) {
  6056. return markAsExtraApi(f, k);
  6057. });
  6058. return __assign(__assign({
  6059. name: constant(config.name),
  6060. configFields: constant(config.configFields),
  6061. sketch: sketch
  6062. }, apis), extraApis);
  6063. };
  6064. var composite$1 = function (rawConfig) {
  6065. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6066. var sketch = function (spec) {
  6067. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  6068. };
  6069. var parts = generate$4(config.name, config.partFields);
  6070. var apis = map$1(config.apis, makeApi);
  6071. var extraApis = map$1(config.extraApis, function (f, k) {
  6072. return markAsExtraApi(f, k);
  6073. });
  6074. return __assign(__assign({
  6075. name: constant(config.name),
  6076. partFields: constant(config.partFields),
  6077. configFields: constant(config.configFields),
  6078. sketch: sketch,
  6079. parts: constant(parts)
  6080. }, apis), extraApis);
  6081. };
  6082. var cat = function (arr) {
  6083. var r = [];
  6084. var push = function (x) {
  6085. r.push(x);
  6086. };
  6087. for (var i = 0; i < arr.length; i++) {
  6088. arr[i].each(push);
  6089. }
  6090. return r;
  6091. };
  6092. var sequence = function (arr) {
  6093. var r = [];
  6094. for (var i = 0; i < arr.length; i++) {
  6095. var x = arr[i];
  6096. if (x.isSome()) {
  6097. r.push(x.getOrDie());
  6098. } else {
  6099. return Option.none();
  6100. }
  6101. }
  6102. return Option.some(r);
  6103. };
  6104. var lift2 = function (oa, ob, f) {
  6105. return oa.isSome() && ob.isSome() ? Option.some(f(oa.getOrDie(), ob.getOrDie())) : Option.none();
  6106. };
  6107. var lift3 = function (oa, ob, oc, f) {
  6108. return oa.isSome() && ob.isSome() && oc.isSome() ? Option.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Option.none();
  6109. };
  6110. var inside = function (target) {
  6111. return name(target) === 'input' && get$2(target, 'type') !== 'radio' || name(target) === 'textarea';
  6112. };
  6113. var getCurrent = function (component, composeConfig, composeState) {
  6114. return composeConfig.find(component);
  6115. };
  6116. var ComposeApis = /*#__PURE__*/Object.freeze({
  6117. __proto__: null,
  6118. getCurrent: getCurrent
  6119. });
  6120. var ComposeSchema = [strict$1('find')];
  6121. var Composing = create$1({
  6122. fields: ComposeSchema,
  6123. name: 'composing',
  6124. apis: ComposeApis
  6125. });
  6126. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6127. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  6128. each(highlighted, function (h) {
  6129. if (!exists(skip, function (skipComp) {
  6130. return skipComp.element() === h;
  6131. })) {
  6132. remove$4(h, hConfig.highlightClass);
  6133. component.getSystem().getByDom(h).each(function (target) {
  6134. hConfig.onDehighlight(component, target);
  6135. emit(target, dehighlight());
  6136. });
  6137. }
  6138. });
  6139. };
  6140. var dehighlightAll = function (component, hConfig, hState) {
  6141. return dehighlightAllExcept(component, hConfig, hState, []);
  6142. };
  6143. var dehighlight$1 = function (component, hConfig, hState, target) {
  6144. if (isHighlighted(component, hConfig, hState, target)) {
  6145. remove$4(target.element(), hConfig.highlightClass);
  6146. hConfig.onDehighlight(component, target);
  6147. emit(target, dehighlight());
  6148. }
  6149. };
  6150. var highlight$1 = function (component, hConfig, hState, target) {
  6151. dehighlightAllExcept(component, hConfig, hState, [target]);
  6152. if (!isHighlighted(component, hConfig, hState, target)) {
  6153. add$2(target.element(), hConfig.highlightClass);
  6154. hConfig.onHighlight(component, target);
  6155. emit(target, highlight());
  6156. }
  6157. };
  6158. var highlightFirst = function (component, hConfig, hState) {
  6159. getFirst(component, hConfig).each(function (firstComp) {
  6160. highlight$1(component, hConfig, hState, firstComp);
  6161. });
  6162. };
  6163. var highlightLast = function (component, hConfig, hState) {
  6164. getLast(component, hConfig).each(function (lastComp) {
  6165. highlight$1(component, hConfig, hState, lastComp);
  6166. });
  6167. };
  6168. var highlightAt = function (component, hConfig, hState, index) {
  6169. getByIndex(component, hConfig, hState, index).fold(function (err) {
  6170. throw new Error(err);
  6171. }, function (firstComp) {
  6172. highlight$1(component, hConfig, hState, firstComp);
  6173. });
  6174. };
  6175. var highlightBy = function (component, hConfig, hState, predicate) {
  6176. var candidates = getCandidates(component, hConfig);
  6177. var targetComp = find(candidates, predicate);
  6178. targetComp.each(function (c) {
  6179. highlight$1(component, hConfig, hState, c);
  6180. });
  6181. };
  6182. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6183. return has$2(queryTarget.element(), hConfig.highlightClass);
  6184. };
  6185. var getHighlighted = function (component, hConfig, hState) {
  6186. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  6187. return component.getSystem().getByDom(e).toOption();
  6188. });
  6189. };
  6190. var getByIndex = function (component, hConfig, hState, index) {
  6191. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6192. return Option.from(items[index]).fold(function () {
  6193. return Result.error('No element found with index ' + index);
  6194. }, component.getSystem().getByDom);
  6195. };
  6196. var getFirst = function (component, hConfig, hState) {
  6197. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  6198. return component.getSystem().getByDom(e).toOption();
  6199. });
  6200. };
  6201. var getLast = function (component, hConfig, hState) {
  6202. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6203. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  6204. return last.bind(function (c) {
  6205. return component.getSystem().getByDom(c).toOption();
  6206. });
  6207. };
  6208. var getDelta = function (component, hConfig, hState, delta) {
  6209. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6210. var current = findIndex(items, function (item) {
  6211. return has$2(item, hConfig.highlightClass);
  6212. });
  6213. return current.bind(function (selected) {
  6214. var dest = cycleBy(selected, delta, 0, items.length - 1);
  6215. return component.getSystem().getByDom(items[dest]).toOption();
  6216. });
  6217. };
  6218. var getPrevious = function (component, hConfig, hState) {
  6219. return getDelta(component, hConfig, hState, -1);
  6220. };
  6221. var getNext = function (component, hConfig, hState) {
  6222. return getDelta(component, hConfig, hState, +1);
  6223. };
  6224. var getCandidates = function (component, hConfig, hState) {
  6225. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6226. return cat(map(items, function (i) {
  6227. return component.getSystem().getByDom(i).toOption();
  6228. }));
  6229. };
  6230. var HighlightApis = /*#__PURE__*/Object.freeze({
  6231. __proto__: null,
  6232. dehighlightAll: dehighlightAll,
  6233. dehighlight: dehighlight$1,
  6234. highlight: highlight$1,
  6235. highlightFirst: highlightFirst,
  6236. highlightLast: highlightLast,
  6237. highlightAt: highlightAt,
  6238. highlightBy: highlightBy,
  6239. isHighlighted: isHighlighted,
  6240. getHighlighted: getHighlighted,
  6241. getFirst: getFirst,
  6242. getLast: getLast,
  6243. getPrevious: getPrevious,
  6244. getNext: getNext,
  6245. getCandidates: getCandidates
  6246. });
  6247. var HighlightSchema = [
  6248. strict$1('highlightClass'),
  6249. strict$1('itemClass'),
  6250. onHandler('onHighlight'),
  6251. onHandler('onDehighlight')
  6252. ];
  6253. var Highlighting = create$1({
  6254. fields: HighlightSchema,
  6255. name: 'highlighting',
  6256. apis: HighlightApis
  6257. });
  6258. var BACKSPACE = function () {
  6259. return [8];
  6260. };
  6261. var TAB = function () {
  6262. return [9];
  6263. };
  6264. var ENTER = function () {
  6265. return [13];
  6266. };
  6267. var ESCAPE = function () {
  6268. return [27];
  6269. };
  6270. var SPACE = function () {
  6271. return [32];
  6272. };
  6273. var LEFT = function () {
  6274. return [37];
  6275. };
  6276. var UP = function () {
  6277. return [38];
  6278. };
  6279. var RIGHT = function () {
  6280. return [39];
  6281. };
  6282. var DOWN = function () {
  6283. return [40];
  6284. };
  6285. var cyclePrev = function (values, index, predicate) {
  6286. var before = reverse(values.slice(0, index));
  6287. var after = reverse(values.slice(index + 1));
  6288. return find(before.concat(after), predicate);
  6289. };
  6290. var tryPrev = function (values, index, predicate) {
  6291. var before = reverse(values.slice(0, index));
  6292. return find(before, predicate);
  6293. };
  6294. var cycleNext = function (values, index, predicate) {
  6295. var before = values.slice(0, index);
  6296. var after = values.slice(index + 1);
  6297. return find(after.concat(before), predicate);
  6298. };
  6299. var tryNext = function (values, index, predicate) {
  6300. var after = values.slice(index + 1);
  6301. return find(after, predicate);
  6302. };
  6303. var inSet = function (keys) {
  6304. return function (event) {
  6305. var raw = event.raw();
  6306. return contains(keys, raw.which);
  6307. };
  6308. };
  6309. var and = function (preds) {
  6310. return function (event) {
  6311. return forall(preds, function (pred) {
  6312. return pred(event);
  6313. });
  6314. };
  6315. };
  6316. var isShift = function (event) {
  6317. var raw = event.raw();
  6318. return raw.shiftKey === true;
  6319. };
  6320. var isControl = function (event) {
  6321. var raw = event.raw();
  6322. return raw.ctrlKey === true;
  6323. };
  6324. var isNotShift = not(isShift);
  6325. var rule = function (matches, action) {
  6326. return {
  6327. matches: matches,
  6328. classification: action
  6329. };
  6330. };
  6331. var choose$2 = function (transitions, event) {
  6332. var transition = find(transitions, function (t) {
  6333. return t.matches(event);
  6334. });
  6335. return transition.map(function (t) {
  6336. return t.classification;
  6337. });
  6338. };
  6339. var reportFocusShifting = function (component, prevFocus, newFocus) {
  6340. var noChange = prevFocus.exists(function (p) {
  6341. return newFocus.exists(function (n) {
  6342. return eq(n, p);
  6343. });
  6344. });
  6345. if (!noChange) {
  6346. emitWith(component, focusShifted(), {
  6347. prevFocus: prevFocus,
  6348. newFocus: newFocus
  6349. });
  6350. }
  6351. };
  6352. var dom = function () {
  6353. var get = function (component) {
  6354. return search(component.element());
  6355. };
  6356. var set = function (component, focusee) {
  6357. var prevFocus = get(component);
  6358. component.getSystem().triggerFocus(focusee, component.element());
  6359. var newFocus = get(component);
  6360. reportFocusShifting(component, prevFocus, newFocus);
  6361. };
  6362. return {
  6363. get: get,
  6364. set: set
  6365. };
  6366. };
  6367. var highlights = function () {
  6368. var get = function (component) {
  6369. return Highlighting.getHighlighted(component).map(function (item) {
  6370. return item.element();
  6371. });
  6372. };
  6373. var set = function (component, element) {
  6374. var prevFocus = get(component);
  6375. component.getSystem().getByDom(element).fold(noop, function (item) {
  6376. Highlighting.highlight(component, item);
  6377. });
  6378. var newFocus = get(component);
  6379. reportFocusShifting(component, prevFocus, newFocus);
  6380. };
  6381. return {
  6382. get: get,
  6383. set: set
  6384. };
  6385. };
  6386. var FocusInsideModes;
  6387. (function (FocusInsideModes) {
  6388. FocusInsideModes['OnFocusMode'] = 'onFocus';
  6389. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  6390. FocusInsideModes['OnApiMode'] = 'onApi';
  6391. }(FocusInsideModes || (FocusInsideModes = {})));
  6392. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  6393. var schema = function () {
  6394. return infoSchema.concat([
  6395. defaulted$1('focusManager', dom()),
  6396. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  6397. return contains([
  6398. 'onFocus',
  6399. 'onEnterOrSpace',
  6400. 'onApi'
  6401. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  6402. })),
  6403. output('handler', me),
  6404. output('state', stateInit),
  6405. output('sendFocusIn', optFocusIn)
  6406. ]);
  6407. };
  6408. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  6409. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  6410. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  6411. return rule(component, simulatedEvent, keyingConfig, keyingState);
  6412. });
  6413. };
  6414. var toEvents = function (keyingConfig, keyingState) {
  6415. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  6416. return run(focus(), function (component, simulatedEvent) {
  6417. focusIn(component, keyingConfig, keyingState);
  6418. simulatedEvent.stop();
  6419. });
  6420. });
  6421. var tryGoInsideComponent = function (component, simulatedEvent) {
  6422. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  6423. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  6424. optFocusIn(keyingConfig).each(function (focusIn) {
  6425. focusIn(component, keyingConfig, keyingState);
  6426. simulatedEvent.stop();
  6427. });
  6428. }
  6429. };
  6430. return derive(onFocusHandler.toArray().concat([
  6431. run(keydown(), function (component, simulatedEvent) {
  6432. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  6433. tryGoInsideComponent(component, simulatedEvent);
  6434. }, function (_) {
  6435. simulatedEvent.stop();
  6436. });
  6437. }),
  6438. run(keyup(), function (component, simulatedEvent) {
  6439. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  6440. simulatedEvent.stop();
  6441. });
  6442. })
  6443. ]));
  6444. };
  6445. var me = {
  6446. schema: schema,
  6447. processKey: processKey,
  6448. toEvents: toEvents
  6449. };
  6450. return me;
  6451. };
  6452. var create$3 = function (cyclicField) {
  6453. var schema = [
  6454. option('onEscape'),
  6455. option('onEnter'),
  6456. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  6457. defaulted$1('firstTabstop', 0),
  6458. defaulted$1('useTabstopAt', constant(true)),
  6459. option('visibilitySelector')
  6460. ].concat([cyclicField]);
  6461. var isVisible = function (tabbingConfig, element) {
  6462. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  6463. return closest$3(element, sel);
  6464. }).getOr(element);
  6465. return get$6(target) > 0;
  6466. };
  6467. var findInitial = function (component, tabbingConfig) {
  6468. var tabstops = descendants(component.element(), tabbingConfig.selector);
  6469. var visibles = filter(tabstops, function (elem) {
  6470. return isVisible(tabbingConfig, elem);
  6471. });
  6472. return Option.from(visibles[tabbingConfig.firstTabstop]);
  6473. };
  6474. var findCurrent = function (component, tabbingConfig) {
  6475. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  6476. return closest$3(elem, tabbingConfig.selector);
  6477. });
  6478. };
  6479. var isTabstop = function (tabbingConfig, element) {
  6480. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  6481. };
  6482. var focusIn = function (component, tabbingConfig, tabbingState) {
  6483. findInitial(component, tabbingConfig).each(function (target) {
  6484. tabbingConfig.focusManager.set(component, target);
  6485. });
  6486. };
  6487. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  6488. return cycle(tabstops, stopIndex, function (elem) {
  6489. return isTabstop(tabbingConfig, elem);
  6490. }).fold(function () {
  6491. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  6492. }, function (target) {
  6493. tabbingConfig.focusManager.set(component, target);
  6494. return Option.some(true);
  6495. });
  6496. };
  6497. var go = function (component, simulatedEvent, tabbingConfig, cycle) {
  6498. var tabstops = descendants(component.element(), tabbingConfig.selector);
  6499. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  6500. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  6501. return optStopIndex.bind(function (stopIndex) {
  6502. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  6503. });
  6504. });
  6505. };
  6506. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  6507. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  6508. return go(component, simulatedEvent, tabbingConfig, navigate);
  6509. };
  6510. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  6511. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  6512. return go(component, simulatedEvent, tabbingConfig, navigate);
  6513. };
  6514. var execute = function (component, simulatedEvent, tabbingConfig) {
  6515. return tabbingConfig.onEnter.bind(function (f) {
  6516. return f(component, simulatedEvent);
  6517. });
  6518. };
  6519. var exit = function (component, simulatedEvent, tabbingConfig) {
  6520. return tabbingConfig.onEscape.bind(function (f) {
  6521. return f(component, simulatedEvent);
  6522. });
  6523. };
  6524. var getKeydownRules = constant([
  6525. rule(and([
  6526. isShift,
  6527. inSet(TAB())
  6528. ]), goBackwards),
  6529. rule(inSet(TAB()), goForwards),
  6530. rule(inSet(ESCAPE()), exit),
  6531. rule(and([
  6532. isNotShift,
  6533. inSet(ENTER())
  6534. ]), execute)
  6535. ]);
  6536. var getKeyupRules = constant([]);
  6537. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  6538. return Option.some(focusIn);
  6539. });
  6540. };
  6541. var AcyclicType = create$3(state$1('cyclic', constant(false)));
  6542. var CyclicType = create$3(state$1('cyclic', constant(true)));
  6543. var doDefaultExecute = function (component, simulatedEvent, focused) {
  6544. dispatch(component, focused, execute());
  6545. return Option.some(true);
  6546. };
  6547. var defaultExecute = function (component, simulatedEvent, focused) {
  6548. return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  6549. };
  6550. var stopEventForFirefox = function (component, simulatedEvent) {
  6551. return Option.some(true);
  6552. };
  6553. var schema$4 = [
  6554. defaulted$1('execute', defaultExecute),
  6555. defaulted$1('useSpace', false),
  6556. defaulted$1('useEnter', true),
  6557. defaulted$1('useControlEnter', false),
  6558. defaulted$1('useDown', false)
  6559. ];
  6560. var execute$1 = function (component, simulatedEvent, executeConfig) {
  6561. return executeConfig.execute(component, simulatedEvent, component.element());
  6562. };
  6563. var getKeydownRules = function (component, simulatedEvent, executeConfig, executeState) {
  6564. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  6565. var enterExec = executeConfig.useEnter ? ENTER() : [];
  6566. var downExec = executeConfig.useDown ? DOWN() : [];
  6567. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  6568. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  6569. isControl,
  6570. inSet(ENTER())
  6571. ]), execute$1)] : []);
  6572. };
  6573. var getKeyupRules = function (component, simulatedEvent, executeConfig, executeState) {
  6574. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  6575. };
  6576. var ExecutionType = typical(schema$4, NoState.init, getKeydownRules, getKeyupRules, function () {
  6577. return Option.none();
  6578. });
  6579. var flatgrid = function () {
  6580. var dimensions = Cell(Option.none());
  6581. var setGridSize = function (numRows, numColumns) {
  6582. dimensions.set(Option.some({
  6583. numRows: constant(numRows),
  6584. numColumns: constant(numColumns)
  6585. }));
  6586. };
  6587. var getNumRows = function () {
  6588. return dimensions.get().map(function (d) {
  6589. return d.numRows();
  6590. });
  6591. };
  6592. var getNumColumns = function () {
  6593. return dimensions.get().map(function (d) {
  6594. return d.numColumns();
  6595. });
  6596. };
  6597. return nu$5({
  6598. readState: function () {
  6599. return dimensions.get().map(function (d) {
  6600. return {
  6601. numRows: String(d.numRows()),
  6602. numColumns: String(d.numColumns())
  6603. };
  6604. }).getOr({
  6605. numRows: '?',
  6606. numColumns: '?'
  6607. });
  6608. },
  6609. setGridSize: setGridSize,
  6610. getNumRows: getNumRows,
  6611. getNumColumns: getNumColumns
  6612. });
  6613. };
  6614. var init$2 = function (spec) {
  6615. return spec.state(spec);
  6616. };
  6617. var KeyingState = /*#__PURE__*/Object.freeze({
  6618. __proto__: null,
  6619. flatgrid: flatgrid,
  6620. init: init$2
  6621. });
  6622. var useH = function (movement) {
  6623. return function (component, simulatedEvent, config, state) {
  6624. var move = movement(component.element());
  6625. return use(move, component, simulatedEvent, config, state);
  6626. };
  6627. };
  6628. var west$2 = function (moveLeft, moveRight) {
  6629. var movement = onDirection(moveLeft, moveRight);
  6630. return useH(movement);
  6631. };
  6632. var east$2 = function (moveLeft, moveRight) {
  6633. var movement = onDirection(moveRight, moveLeft);
  6634. return useH(movement);
  6635. };
  6636. var useV = function (move) {
  6637. return function (component, simulatedEvent, config, state) {
  6638. return use(move, component, simulatedEvent, config, state);
  6639. };
  6640. };
  6641. var use = function (move, component, simulatedEvent, config, state) {
  6642. var outcome = config.focusManager.get(component).bind(function (focused) {
  6643. return move(component.element(), focused, config, state);
  6644. });
  6645. return outcome.map(function (newFocus) {
  6646. config.focusManager.set(component, newFocus);
  6647. return true;
  6648. });
  6649. };
  6650. var north$2 = useV;
  6651. var south$2 = useV;
  6652. var move = useV;
  6653. var isHidden = function (dom) {
  6654. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  6655. };
  6656. var isVisible = function (element) {
  6657. var dom = element.dom();
  6658. return !isHidden(dom);
  6659. };
  6660. var locate = function (candidates, predicate) {
  6661. return findIndex(candidates, predicate).map(function (index) {
  6662. return {
  6663. index: constant(index),
  6664. candidates: constant(candidates)
  6665. };
  6666. });
  6667. };
  6668. var locateVisible = function (container, current, selector) {
  6669. var predicate = function (x) {
  6670. return eq(x, current);
  6671. };
  6672. var candidates = descendants(container, selector);
  6673. var visible = filter(candidates, isVisible);
  6674. return locate(visible, predicate);
  6675. };
  6676. var findIndex$1 = function (elements, target) {
  6677. return findIndex(elements, function (elem) {
  6678. return eq(target, elem);
  6679. });
  6680. };
  6681. var withGrid = function (values, index, numCols, f) {
  6682. var oldRow = Math.floor(index / numCols);
  6683. var oldColumn = index % numCols;
  6684. return f(oldRow, oldColumn).bind(function (address) {
  6685. var newIndex = address.row() * numCols + address.column();
  6686. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  6687. });
  6688. };
  6689. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  6690. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6691. var onLastRow = oldRow === numRows - 1;
  6692. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  6693. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  6694. return Option.some({
  6695. row: constant(oldRow),
  6696. column: constant(newColumn)
  6697. });
  6698. });
  6699. };
  6700. var cycleVertical = function (values, index, numRows, numCols, delta) {
  6701. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6702. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  6703. var onLastRow = newRow === numRows - 1;
  6704. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  6705. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  6706. return Option.some({
  6707. row: constant(newRow),
  6708. column: constant(newCol)
  6709. });
  6710. });
  6711. };
  6712. var cycleRight = function (values, index, numRows, numCols) {
  6713. return cycleHorizontal(values, index, numRows, numCols, +1);
  6714. };
  6715. var cycleLeft = function (values, index, numRows, numCols) {
  6716. return cycleHorizontal(values, index, numRows, numCols, -1);
  6717. };
  6718. var cycleUp = function (values, index, numRows, numCols) {
  6719. return cycleVertical(values, index, numRows, numCols, -1);
  6720. };
  6721. var cycleDown = function (values, index, numRows, numCols) {
  6722. return cycleVertical(values, index, numRows, numCols, +1);
  6723. };
  6724. var schema$5 = [
  6725. strict$1('selector'),
  6726. defaulted$1('execute', defaultExecute),
  6727. onKeyboardHandler('onEscape'),
  6728. defaulted$1('captureTab', false),
  6729. initSize()
  6730. ];
  6731. var focusIn = function (component, gridConfig, gridState) {
  6732. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  6733. gridConfig.focusManager.set(component, first);
  6734. });
  6735. };
  6736. var findCurrent = function (component, gridConfig) {
  6737. return gridConfig.focusManager.get(component).bind(function (elem) {
  6738. return closest$3(elem, gridConfig.selector);
  6739. });
  6740. };
  6741. var execute$2 = function (component, simulatedEvent, gridConfig, gridState) {
  6742. return findCurrent(component, gridConfig).bind(function (focused) {
  6743. return gridConfig.execute(component, simulatedEvent, focused);
  6744. });
  6745. };
  6746. var doMove = function (cycle) {
  6747. return function (element, focused, gridConfig, gridState) {
  6748. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  6749. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  6750. });
  6751. };
  6752. };
  6753. var handleTab = function (component, simulatedEvent, gridConfig) {
  6754. return gridConfig.captureTab ? Option.some(true) : Option.none();
  6755. };
  6756. var doEscape = function (component, simulatedEvent, gridConfig) {
  6757. return gridConfig.onEscape(component, simulatedEvent);
  6758. };
  6759. var moveLeft = doMove(cycleLeft);
  6760. var moveRight = doMove(cycleRight);
  6761. var moveNorth = doMove(cycleUp);
  6762. var moveSouth = doMove(cycleDown);
  6763. var getKeydownRules$1 = constant([
  6764. rule(inSet(LEFT()), west$2(moveLeft, moveRight)),
  6765. rule(inSet(RIGHT()), east$2(moveLeft, moveRight)),
  6766. rule(inSet(UP()), north$2(moveNorth)),
  6767. rule(inSet(DOWN()), south$2(moveSouth)),
  6768. rule(and([
  6769. isShift,
  6770. inSet(TAB())
  6771. ]), handleTab),
  6772. rule(and([
  6773. isNotShift,
  6774. inSet(TAB())
  6775. ]), handleTab),
  6776. rule(inSet(ESCAPE()), doEscape),
  6777. rule(inSet(SPACE().concat(ENTER())), execute$2)
  6778. ]);
  6779. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6780. var FlatgridType = typical(schema$5, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  6781. return Option.some(focusIn);
  6782. });
  6783. var horizontal = function (container, selector, current, delta) {
  6784. var isDisabledButton = function (candidate) {
  6785. return name(candidate) === 'button' && get$2(candidate, 'disabled') === 'disabled';
  6786. };
  6787. var tryCycle = function (initial, index, candidates) {
  6788. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  6789. if (newIndex === initial) {
  6790. return Option.none();
  6791. } else {
  6792. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  6793. }
  6794. };
  6795. return locateVisible(container, current, selector).bind(function (identified) {
  6796. var index = identified.index();
  6797. var candidates = identified.candidates();
  6798. return tryCycle(index, index, candidates);
  6799. });
  6800. };
  6801. var schema$6 = [
  6802. strict$1('selector'),
  6803. defaulted$1('getInitial', Option.none),
  6804. defaulted$1('execute', defaultExecute),
  6805. onKeyboardHandler('onEscape'),
  6806. defaulted$1('executeOnMove', false),
  6807. defaulted$1('allowVertical', true)
  6808. ];
  6809. var findCurrent$1 = function (component, flowConfig) {
  6810. return flowConfig.focusManager.get(component).bind(function (elem) {
  6811. return closest$3(elem, flowConfig.selector);
  6812. });
  6813. };
  6814. var execute$3 = function (component, simulatedEvent, flowConfig) {
  6815. return findCurrent$1(component, flowConfig).bind(function (focused) {
  6816. return flowConfig.execute(component, simulatedEvent, focused);
  6817. });
  6818. };
  6819. var focusIn$1 = function (component, flowConfig, state) {
  6820. flowConfig.getInitial(component).orThunk(function () {
  6821. return descendant$1(component.element(), flowConfig.selector);
  6822. }).each(function (first) {
  6823. flowConfig.focusManager.set(component, first);
  6824. });
  6825. };
  6826. var moveLeft$1 = function (element, focused, info) {
  6827. return horizontal(element, info.selector, focused, -1);
  6828. };
  6829. var moveRight$1 = function (element, focused, info) {
  6830. return horizontal(element, info.selector, focused, +1);
  6831. };
  6832. var doMove$1 = function (movement) {
  6833. return function (component, simulatedEvent, flowConfig, flowState) {
  6834. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  6835. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  6836. });
  6837. };
  6838. };
  6839. var doEscape$1 = function (component, simulatedEvent, flowConfig) {
  6840. return flowConfig.onEscape(component, simulatedEvent);
  6841. };
  6842. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  6843. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  6844. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  6845. return [
  6846. rule(inSet(westMovers), doMove$1(west$2(moveLeft$1, moveRight$1))),
  6847. rule(inSet(eastMovers), doMove$1(east$2(moveLeft$1, moveRight$1))),
  6848. rule(inSet(ENTER()), execute$3),
  6849. rule(inSet(SPACE()), execute$3),
  6850. rule(inSet(ESCAPE()), doEscape$1)
  6851. ];
  6852. };
  6853. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6854. var FlowType = typical(schema$6, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  6855. return Option.some(focusIn$1);
  6856. });
  6857. var outcome = MixedBag([
  6858. 'rowIndex',
  6859. 'columnIndex',
  6860. 'cell'
  6861. ], []);
  6862. var toCell = function (matrix, rowIndex, columnIndex) {
  6863. return Option.from(matrix[rowIndex]).bind(function (row) {
  6864. return Option.from(row[columnIndex]).map(function (cell) {
  6865. return outcome({
  6866. rowIndex: rowIndex,
  6867. columnIndex: columnIndex,
  6868. cell: cell
  6869. });
  6870. });
  6871. });
  6872. };
  6873. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  6874. var row = matrix[rowIndex];
  6875. var colsInRow = row.length;
  6876. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  6877. return toCell(matrix, rowIndex, newColIndex);
  6878. };
  6879. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  6880. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  6881. var colsInNextRow = matrix[nextRowIndex].length;
  6882. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6883. return toCell(matrix, nextRowIndex, nextColIndex);
  6884. };
  6885. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  6886. var row = matrix[rowIndex];
  6887. var colsInRow = row.length;
  6888. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  6889. return toCell(matrix, rowIndex, newColIndex);
  6890. };
  6891. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  6892. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  6893. var colsInNextRow = matrix[nextRowIndex].length;
  6894. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6895. return toCell(matrix, nextRowIndex, nextColIndex);
  6896. };
  6897. var cycleRight$1 = function (matrix, startRow, startCol) {
  6898. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  6899. };
  6900. var cycleLeft$1 = function (matrix, startRow, startCol) {
  6901. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  6902. };
  6903. var cycleUp$1 = function (matrix, startRow, startCol) {
  6904. return cycleVertical$1(matrix, startCol, startRow, -1);
  6905. };
  6906. var cycleDown$1 = function (matrix, startRow, startCol) {
  6907. return cycleVertical$1(matrix, startCol, startRow, +1);
  6908. };
  6909. var moveLeft$2 = function (matrix, startRow, startCol) {
  6910. return moveHorizontal(matrix, startRow, startCol, -1);
  6911. };
  6912. var moveRight$2 = function (matrix, startRow, startCol) {
  6913. return moveHorizontal(matrix, startRow, startCol, +1);
  6914. };
  6915. var moveUp = function (matrix, startRow, startCol) {
  6916. return moveVertical(matrix, startCol, startRow, -1);
  6917. };
  6918. var moveDown = function (matrix, startRow, startCol) {
  6919. return moveVertical(matrix, startCol, startRow, +1);
  6920. };
  6921. var schema$7 = [
  6922. strictObjOf('selectors', [
  6923. strict$1('row'),
  6924. strict$1('cell')
  6925. ]),
  6926. defaulted$1('cycles', true),
  6927. defaulted$1('previousSelector', Option.none),
  6928. defaulted$1('execute', defaultExecute)
  6929. ];
  6930. var focusIn$2 = function (component, matrixConfig, state) {
  6931. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  6932. var selectors = matrixConfig.selectors;
  6933. return descendant$1(component.element(), selectors.cell);
  6934. });
  6935. focused.each(function (cell) {
  6936. matrixConfig.focusManager.set(component, cell);
  6937. });
  6938. };
  6939. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  6940. return search(component.element()).bind(function (focused) {
  6941. return matrixConfig.execute(component, simulatedEvent, focused);
  6942. });
  6943. };
  6944. var toMatrix = function (rows, matrixConfig) {
  6945. return map(rows, function (row) {
  6946. return descendants(row, matrixConfig.selectors.cell);
  6947. });
  6948. };
  6949. var doMove$2 = function (ifCycle, ifMove) {
  6950. return function (element, focused, matrixConfig) {
  6951. var move = matrixConfig.cycles ? ifCycle : ifMove;
  6952. return closest$3(focused, matrixConfig.selectors.row).bind(function (inRow) {
  6953. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  6954. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  6955. var allRows = descendants(element, matrixConfig.selectors.row);
  6956. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  6957. var matrix = toMatrix(allRows, matrixConfig);
  6958. return move(matrix, rowIndex, colIndex).map(function (next) {
  6959. return next.cell();
  6960. });
  6961. });
  6962. });
  6963. });
  6964. };
  6965. };
  6966. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  6967. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  6968. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  6969. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  6970. var getKeydownRules$3 = constant([
  6971. rule(inSet(LEFT()), west$2(moveLeft$3, moveRight$3)),
  6972. rule(inSet(RIGHT()), east$2(moveLeft$3, moveRight$3)),
  6973. rule(inSet(UP()), north$2(moveNorth$1)),
  6974. rule(inSet(DOWN()), south$2(moveSouth$1)),
  6975. rule(inSet(SPACE().concat(ENTER())), execute$4)
  6976. ]);
  6977. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6978. var MatrixType = typical(schema$7, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  6979. return Option.some(focusIn$2);
  6980. });
  6981. var schema$8 = [
  6982. strict$1('selector'),
  6983. defaulted$1('execute', defaultExecute),
  6984. defaulted$1('moveOnTab', false)
  6985. ];
  6986. var execute$5 = function (component, simulatedEvent, menuConfig) {
  6987. return menuConfig.focusManager.get(component).bind(function (focused) {
  6988. return menuConfig.execute(component, simulatedEvent, focused);
  6989. });
  6990. };
  6991. var focusIn$3 = function (component, menuConfig, state) {
  6992. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  6993. menuConfig.focusManager.set(component, first);
  6994. });
  6995. };
  6996. var moveUp$1 = function (element, focused, info) {
  6997. return horizontal(element, info.selector, focused, -1);
  6998. };
  6999. var moveDown$1 = function (element, focused, info) {
  7000. return horizontal(element, info.selector, focused, +1);
  7001. };
  7002. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  7003. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  7004. };
  7005. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  7006. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  7007. };
  7008. var getKeydownRules$4 = constant([
  7009. rule(inSet(UP()), move(moveUp$1)),
  7010. rule(inSet(DOWN()), move(moveDown$1)),
  7011. rule(and([
  7012. isShift,
  7013. inSet(TAB())
  7014. ]), fireShiftTab),
  7015. rule(and([
  7016. isNotShift,
  7017. inSet(TAB())
  7018. ]), fireTab),
  7019. rule(inSet(ENTER()), execute$5),
  7020. rule(inSet(SPACE()), execute$5)
  7021. ]);
  7022. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  7023. var MenuType = typical(schema$8, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  7024. return Option.some(focusIn$3);
  7025. });
  7026. var schema$9 = [
  7027. onKeyboardHandler('onSpace'),
  7028. onKeyboardHandler('onEnter'),
  7029. onKeyboardHandler('onShiftEnter'),
  7030. onKeyboardHandler('onLeft'),
  7031. onKeyboardHandler('onRight'),
  7032. onKeyboardHandler('onTab'),
  7033. onKeyboardHandler('onShiftTab'),
  7034. onKeyboardHandler('onUp'),
  7035. onKeyboardHandler('onDown'),
  7036. onKeyboardHandler('onEscape'),
  7037. defaulted$1('stopSpaceKeyup', false),
  7038. option('focusIn')
  7039. ];
  7040. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  7041. return [
  7042. rule(inSet(SPACE()), specialInfo.onSpace),
  7043. rule(and([
  7044. isNotShift,
  7045. inSet(ENTER())
  7046. ]), specialInfo.onEnter),
  7047. rule(and([
  7048. isShift,
  7049. inSet(ENTER())
  7050. ]), specialInfo.onShiftEnter),
  7051. rule(and([
  7052. isShift,
  7053. inSet(TAB())
  7054. ]), specialInfo.onShiftTab),
  7055. rule(and([
  7056. isNotShift,
  7057. inSet(TAB())
  7058. ]), specialInfo.onTab),
  7059. rule(inSet(UP()), specialInfo.onUp),
  7060. rule(inSet(DOWN()), specialInfo.onDown),
  7061. rule(inSet(LEFT()), specialInfo.onLeft),
  7062. rule(inSet(RIGHT()), specialInfo.onRight),
  7063. rule(inSet(SPACE()), specialInfo.onSpace),
  7064. rule(inSet(ESCAPE()), specialInfo.onEscape)
  7065. ];
  7066. };
  7067. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  7068. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  7069. };
  7070. var SpecialType = typical(schema$9, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  7071. return specialInfo.focusIn;
  7072. });
  7073. var acyclic = AcyclicType.schema();
  7074. var cyclic = CyclicType.schema();
  7075. var flow = FlowType.schema();
  7076. var flatgrid$1 = FlatgridType.schema();
  7077. var matrix = MatrixType.schema();
  7078. var execution = ExecutionType.schema();
  7079. var menu = MenuType.schema();
  7080. var special = SpecialType.schema();
  7081. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7082. __proto__: null,
  7083. acyclic: acyclic,
  7084. cyclic: cyclic,
  7085. flow: flow,
  7086. flatgrid: flatgrid$1,
  7087. matrix: matrix,
  7088. execution: execution,
  7089. menu: menu,
  7090. special: special
  7091. });
  7092. var isFlatgridState = function (keyState) {
  7093. return hasNonNullableKey(keyState, 'setGridSize');
  7094. };
  7095. var Keying = createModes$1({
  7096. branchKey: 'mode',
  7097. branches: KeyboardBranches,
  7098. name: 'keying',
  7099. active: {
  7100. events: function (keyingConfig, keyingState) {
  7101. var handler = keyingConfig.handler;
  7102. return handler.toEvents(keyingConfig, keyingState);
  7103. }
  7104. },
  7105. apis: {
  7106. focusIn: function (component, keyConfig, keyState) {
  7107. keyConfig.sendFocusIn(keyConfig).fold(function () {
  7108. component.getSystem().triggerFocus(component.element(), component.element());
  7109. }, function (sendFocusIn) {
  7110. sendFocusIn(component, keyConfig, keyState);
  7111. });
  7112. },
  7113. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7114. if (!isFlatgridState(keyState)) {
  7115. domGlobals.console.error('Layout does not support setGridSize');
  7116. } else {
  7117. keyState.setGridSize(numRows, numColumns);
  7118. }
  7119. }
  7120. },
  7121. state: KeyingState
  7122. });
  7123. var set$5 = function (component, replaceConfig, replaceState, data) {
  7124. preserve(function () {
  7125. var newChildren = map(data, component.getSystem().build);
  7126. replaceChildren(component, newChildren);
  7127. }, component.element());
  7128. };
  7129. var insert = function (component, replaceConfig, insertion, childSpec) {
  7130. var child = component.getSystem().build(childSpec);
  7131. attachWith(component, child, insertion);
  7132. };
  7133. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  7134. insert(component, replaceConfig, append, appendee);
  7135. };
  7136. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  7137. insert(component, replaceConfig, prepend, prependee);
  7138. };
  7139. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  7140. var children = contents(component);
  7141. var foundChild = find(children, function (child) {
  7142. return eq(removee.element(), child.element());
  7143. });
  7144. foundChild.each(detach);
  7145. };
  7146. var contents = function (component, replaceConfig) {
  7147. return component.components();
  7148. };
  7149. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7150. var children = contents(component);
  7151. return Option.from(children[replaceeIndex]).map(function (replacee) {
  7152. remove$7(component, replaceConfig, replaceState, replacee);
  7153. replacer.each(function (r) {
  7154. insert(component, replaceConfig, function (p, c) {
  7155. appendAt(p, c, replaceeIndex);
  7156. }, r);
  7157. });
  7158. return replacee;
  7159. });
  7160. };
  7161. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7162. var children = contents(component);
  7163. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  7164. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7165. });
  7166. };
  7167. var ReplaceApis = /*#__PURE__*/Object.freeze({
  7168. __proto__: null,
  7169. append: append$2,
  7170. prepend: prepend$1,
  7171. remove: remove$7,
  7172. replaceAt: replaceAt,
  7173. replaceBy: replaceBy,
  7174. set: set$5,
  7175. contents: contents
  7176. });
  7177. var Replacing = create$1({
  7178. fields: [],
  7179. name: 'replacing',
  7180. apis: ReplaceApis
  7181. });
  7182. var events$4 = function (name, eventHandlers) {
  7183. var events = derive(eventHandlers);
  7184. return create$1({
  7185. fields: [strict$1('enabled')],
  7186. name: name,
  7187. active: { events: constant(events) }
  7188. });
  7189. };
  7190. var config = function (name, eventHandlers) {
  7191. var me = events$4(name, eventHandlers);
  7192. return {
  7193. key: name,
  7194. value: {
  7195. config: {},
  7196. me: me,
  7197. configAsRaw: constant({}),
  7198. initialConfig: {},
  7199. state: NoState
  7200. }
  7201. };
  7202. };
  7203. var focus$2 = function (component, focusConfig) {
  7204. if (!focusConfig.ignore) {
  7205. focus$1(component.element());
  7206. focusConfig.onFocus(component);
  7207. }
  7208. };
  7209. var blur$1 = function (component, focusConfig) {
  7210. if (!focusConfig.ignore) {
  7211. blur(component.element());
  7212. }
  7213. };
  7214. var isFocused = function (component) {
  7215. return hasFocus(component.element());
  7216. };
  7217. var FocusApis = /*#__PURE__*/Object.freeze({
  7218. __proto__: null,
  7219. focus: focus$2,
  7220. blur: blur$1,
  7221. isFocused: isFocused
  7222. });
  7223. var exhibit$1 = function (base, focusConfig) {
  7224. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  7225. return nu$6(mod);
  7226. };
  7227. var events$5 = function (focusConfig) {
  7228. return derive([run(focus(), function (component, simulatedEvent) {
  7229. focus$2(component, focusConfig);
  7230. simulatedEvent.stop();
  7231. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  7232. simulatedEvent.event().prevent();
  7233. })] : []));
  7234. };
  7235. var ActiveFocus = /*#__PURE__*/Object.freeze({
  7236. __proto__: null,
  7237. exhibit: exhibit$1,
  7238. events: events$5
  7239. });
  7240. var FocusSchema = [
  7241. onHandler('onFocus'),
  7242. defaulted$1('stopMousedown', false),
  7243. defaulted$1('ignore', false)
  7244. ];
  7245. var Focusing = create$1({
  7246. fields: FocusSchema,
  7247. name: 'focusing',
  7248. active: ActiveFocus,
  7249. apis: FocusApis
  7250. });
  7251. var updateAriaState = function (component, toggleConfig, toggleState) {
  7252. var ariaInfo = toggleConfig.aria;
  7253. ariaInfo.update(component, ariaInfo, toggleState.get());
  7254. };
  7255. var updateClass = function (component, toggleConfig, toggleState) {
  7256. toggleConfig.toggleClass.each(function (toggleClass) {
  7257. if (toggleState.get()) {
  7258. add$2(component.element(), toggleClass);
  7259. } else {
  7260. remove$4(component.element(), toggleClass);
  7261. }
  7262. });
  7263. };
  7264. var toggle = function (component, toggleConfig, toggleState) {
  7265. set$6(component, toggleConfig, toggleState, !toggleState.get());
  7266. };
  7267. var on$1 = function (component, toggleConfig, toggleState) {
  7268. toggleState.set(true);
  7269. updateClass(component, toggleConfig, toggleState);
  7270. updateAriaState(component, toggleConfig, toggleState);
  7271. };
  7272. var off = function (component, toggleConfig, toggleState) {
  7273. toggleState.set(false);
  7274. updateClass(component, toggleConfig, toggleState);
  7275. updateAriaState(component, toggleConfig, toggleState);
  7276. };
  7277. var set$6 = function (component, toggleConfig, toggleState, state) {
  7278. var action = state ? on$1 : off;
  7279. action(component, toggleConfig, toggleState);
  7280. };
  7281. var isOn = function (component, toggleConfig, toggleState) {
  7282. return toggleState.get();
  7283. };
  7284. var onLoad$4 = function (component, toggleConfig, toggleState) {
  7285. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  7286. };
  7287. var ToggleApis = /*#__PURE__*/Object.freeze({
  7288. __proto__: null,
  7289. onLoad: onLoad$4,
  7290. toggle: toggle,
  7291. isOn: isOn,
  7292. on: on$1,
  7293. off: off,
  7294. set: set$6
  7295. });
  7296. var exhibit$2 = function () {
  7297. return nu$6({});
  7298. };
  7299. var events$6 = function (toggleConfig, toggleState) {
  7300. var execute = executeEvent(toggleConfig, toggleState, toggle);
  7301. var load = loadEvent(toggleConfig, toggleState, onLoad$4);
  7302. return derive(flatten([
  7303. toggleConfig.toggleOnExecute ? [execute] : [],
  7304. [load]
  7305. ]));
  7306. };
  7307. var ActiveToggle = /*#__PURE__*/Object.freeze({
  7308. __proto__: null,
  7309. exhibit: exhibit$2,
  7310. events: events$6
  7311. });
  7312. var SetupBehaviourCellState = function (initialState) {
  7313. var init = function () {
  7314. var cell = Cell(initialState);
  7315. var get = function () {
  7316. return cell.get();
  7317. };
  7318. var set = function (newState) {
  7319. return cell.set(newState);
  7320. };
  7321. var clear = function () {
  7322. return cell.set(initialState);
  7323. };
  7324. var readState = function () {
  7325. return cell.get();
  7326. };
  7327. return {
  7328. get: get,
  7329. set: set,
  7330. clear: clear,
  7331. readState: readState
  7332. };
  7333. };
  7334. return { init: init };
  7335. };
  7336. var updatePressed = function (component, ariaInfo, status) {
  7337. set$1(component.element(), 'aria-pressed', status);
  7338. if (ariaInfo.syncWithExpanded) {
  7339. updateExpanded(component, ariaInfo, status);
  7340. }
  7341. };
  7342. var updateSelected = function (component, ariaInfo, status) {
  7343. set$1(component.element(), 'aria-selected', status);
  7344. };
  7345. var updateChecked = function (component, ariaInfo, status) {
  7346. set$1(component.element(), 'aria-checked', status);
  7347. };
  7348. var updateExpanded = function (component, ariaInfo, status) {
  7349. set$1(component.element(), 'aria-expanded', status);
  7350. };
  7351. var ToggleSchema = [
  7352. defaulted$1('selected', false),
  7353. option('toggleClass'),
  7354. defaulted$1('toggleOnExecute', true),
  7355. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  7356. pressed: [
  7357. defaulted$1('syncWithExpanded', false),
  7358. output('update', updatePressed)
  7359. ],
  7360. checked: [output('update', updateChecked)],
  7361. expanded: [output('update', updateExpanded)],
  7362. selected: [output('update', updateSelected)],
  7363. none: [output('update', noop)]
  7364. }))
  7365. ];
  7366. var Toggling = create$1({
  7367. fields: ToggleSchema,
  7368. name: 'toggling',
  7369. active: ActiveToggle,
  7370. apis: ToggleApis,
  7371. state: SetupBehaviourCellState(false)
  7372. });
  7373. var pointerEvents = function () {
  7374. var onClick = function (component, simulatedEvent) {
  7375. simulatedEvent.stop();
  7376. emitExecute(component);
  7377. };
  7378. return [
  7379. run(click(), onClick),
  7380. run(tap(), onClick),
  7381. cutter(touchstart()),
  7382. cutter(mousedown())
  7383. ];
  7384. };
  7385. var events$7 = function (optAction) {
  7386. var executeHandler = function (action) {
  7387. return runOnExecute(function (component, simulatedEvent) {
  7388. action(component);
  7389. simulatedEvent.stop();
  7390. });
  7391. };
  7392. return derive(flatten([
  7393. optAction.map(executeHandler).toArray(),
  7394. pointerEvents()
  7395. ]));
  7396. };
  7397. var hoverEvent = 'alloy.item-hover';
  7398. var focusEvent = 'alloy.item-focus';
  7399. var onHover = function (item) {
  7400. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  7401. if (!Focusing.isFocused(item)) {
  7402. Focusing.focus(item);
  7403. }
  7404. emitWith(item, hoverEvent, { item: item });
  7405. }
  7406. };
  7407. var onFocus = function (item) {
  7408. emitWith(item, focusEvent, { item: item });
  7409. };
  7410. var hover = constant(hoverEvent);
  7411. var focus$3 = constant(focusEvent);
  7412. var builder = function (detail) {
  7413. return {
  7414. dom: detail.dom,
  7415. 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 } : {}) }),
  7416. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7417. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7418. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7419. }),
  7420. Focusing.config({
  7421. ignore: detail.ignoreFocus,
  7422. stopMousedown: detail.ignoreFocus,
  7423. onFocus: function (component) {
  7424. onFocus(component);
  7425. }
  7426. }),
  7427. Keying.config({ mode: 'execution' }),
  7428. Representing.config({
  7429. store: {
  7430. mode: 'memory',
  7431. initialValue: detail.data
  7432. }
  7433. }),
  7434. config('item-type-events', __spreadArrays(pointerEvents(), [
  7435. run(mouseover(), onHover),
  7436. run(focusItem(), Focusing.focus)
  7437. ]))
  7438. ]),
  7439. components: detail.components,
  7440. eventOrder: detail.eventOrder
  7441. };
  7442. };
  7443. var schema$a = [
  7444. strict$1('data'),
  7445. strict$1('components'),
  7446. strict$1('dom'),
  7447. defaulted$1('hasSubmenu', false),
  7448. option('toggling'),
  7449. SketchBehaviours.field('itemBehaviours', [
  7450. Toggling,
  7451. Focusing,
  7452. Keying,
  7453. Representing
  7454. ]),
  7455. defaulted$1('ignoreFocus', false),
  7456. defaulted$1('domModification', {}),
  7457. output('builder', builder),
  7458. defaulted$1('eventOrder', {})
  7459. ];
  7460. var builder$1 = function (detail) {
  7461. return {
  7462. dom: detail.dom,
  7463. components: detail.components,
  7464. events: derive([stopper(focusItem())])
  7465. };
  7466. };
  7467. var schema$b = [
  7468. strict$1('dom'),
  7469. strict$1('components'),
  7470. output('builder', builder$1)
  7471. ];
  7472. var owner$2 = function () {
  7473. return 'item-widget';
  7474. };
  7475. var parts = constant([required({
  7476. name: 'widget',
  7477. overrides: function (detail) {
  7478. return {
  7479. behaviours: derive$1([Representing.config({
  7480. store: {
  7481. mode: 'manual',
  7482. getValue: function (component) {
  7483. return detail.data;
  7484. },
  7485. setValue: function () {
  7486. }
  7487. }
  7488. })])
  7489. };
  7490. }
  7491. })]);
  7492. var builder$2 = function (detail) {
  7493. var subs = substitutes(owner$2(), detail, parts());
  7494. var components$1 = components(owner$2(), detail, subs.internals());
  7495. var focusWidget = function (component) {
  7496. return getPart(component, detail, 'widget').map(function (widget) {
  7497. Keying.focusIn(widget);
  7498. return widget;
  7499. });
  7500. };
  7501. var onHorizontalArrow = function (component, simulatedEvent) {
  7502. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  7503. if (detail.autofocus) {
  7504. simulatedEvent.setSource(component.element());
  7505. return Option.none();
  7506. } else {
  7507. return Option.none();
  7508. }
  7509. }();
  7510. };
  7511. return {
  7512. dom: detail.dom,
  7513. components: components$1,
  7514. domModification: detail.domModification,
  7515. events: derive([
  7516. runOnExecute(function (component, simulatedEvent) {
  7517. focusWidget(component).each(function (widget) {
  7518. simulatedEvent.stop();
  7519. });
  7520. }),
  7521. run(mouseover(), onHover),
  7522. run(focusItem(), function (component, simulatedEvent) {
  7523. if (detail.autofocus) {
  7524. focusWidget(component);
  7525. } else {
  7526. Focusing.focus(component);
  7527. }
  7528. })
  7529. ]),
  7530. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7531. Representing.config({
  7532. store: {
  7533. mode: 'memory',
  7534. initialValue: detail.data
  7535. }
  7536. }),
  7537. Focusing.config({
  7538. ignore: detail.ignoreFocus,
  7539. onFocus: function (component) {
  7540. onFocus(component);
  7541. }
  7542. }),
  7543. Keying.config({
  7544. mode: 'special',
  7545. focusIn: detail.autofocus ? function (component) {
  7546. focusWidget(component);
  7547. } : revoke(),
  7548. onLeft: onHorizontalArrow,
  7549. onRight: onHorizontalArrow,
  7550. onEscape: function (component, simulatedEvent) {
  7551. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7552. Focusing.focus(component);
  7553. return Option.some(true);
  7554. } else if (detail.autofocus) {
  7555. simulatedEvent.setSource(component.element());
  7556. return Option.none();
  7557. } else {
  7558. return Option.none();
  7559. }
  7560. }
  7561. })
  7562. ])
  7563. };
  7564. };
  7565. var schema$c = [
  7566. strict$1('uid'),
  7567. strict$1('data'),
  7568. strict$1('components'),
  7569. strict$1('dom'),
  7570. defaulted$1('autofocus', false),
  7571. defaulted$1('ignoreFocus', false),
  7572. SketchBehaviours.field('widgetBehaviours', [
  7573. Representing,
  7574. Focusing,
  7575. Keying
  7576. ]),
  7577. defaulted$1('domModification', {}),
  7578. defaultUidsSchema(parts()),
  7579. output('builder', builder$2)
  7580. ];
  7581. var itemSchema$1 = choose$1('type', {
  7582. widget: schema$c,
  7583. item: schema$a,
  7584. separator: schema$b
  7585. });
  7586. var configureGrid = function (detail, movementInfo) {
  7587. return {
  7588. mode: 'flatgrid',
  7589. selector: '.' + detail.markers.item,
  7590. initSize: {
  7591. numColumns: movementInfo.initSize.numColumns,
  7592. numRows: movementInfo.initSize.numRows
  7593. },
  7594. focusManager: detail.focusManager
  7595. };
  7596. };
  7597. var configureMatrix = function (detail, movementInfo) {
  7598. return {
  7599. mode: 'matrix',
  7600. selectors: {
  7601. row: movementInfo.rowSelector,
  7602. cell: '.' + detail.markers.item
  7603. },
  7604. focusManager: detail.focusManager
  7605. };
  7606. };
  7607. var configureMenu = function (detail, movementInfo) {
  7608. return {
  7609. mode: 'menu',
  7610. selector: '.' + detail.markers.item,
  7611. moveOnTab: movementInfo.moveOnTab,
  7612. focusManager: detail.focusManager
  7613. };
  7614. };
  7615. var parts$1 = constant([group({
  7616. factory: {
  7617. sketch: function (spec) {
  7618. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  7619. return itemInfo.builder(itemInfo);
  7620. }
  7621. },
  7622. name: 'items',
  7623. unit: 'item',
  7624. defaults: function (detail, u) {
  7625. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  7626. },
  7627. overrides: function (detail, u) {
  7628. return {
  7629. type: u.type,
  7630. ignoreFocus: detail.fakeFocus,
  7631. domModification: { classes: [detail.markers.item] }
  7632. };
  7633. }
  7634. })]);
  7635. var schema$d = constant([
  7636. strict$1('value'),
  7637. strict$1('items'),
  7638. strict$1('dom'),
  7639. strict$1('components'),
  7640. defaulted$1('eventOrder', {}),
  7641. field$1('menuBehaviours', [
  7642. Highlighting,
  7643. Representing,
  7644. Composing,
  7645. Keying
  7646. ]),
  7647. defaultedOf('movement', {
  7648. mode: 'menu',
  7649. moveOnTab: true
  7650. }, choose$1('mode', {
  7651. grid: [
  7652. initSize(),
  7653. output('config', configureGrid)
  7654. ],
  7655. matrix: [
  7656. output('config', configureMatrix),
  7657. strict$1('rowSelector')
  7658. ],
  7659. menu: [
  7660. defaulted$1('moveOnTab', true),
  7661. output('config', configureMenu)
  7662. ]
  7663. })),
  7664. itemMarkers(),
  7665. defaulted$1('fakeFocus', false),
  7666. defaulted$1('focusManager', dom()),
  7667. onHandler('onHighlight')
  7668. ]);
  7669. var focus$4 = constant('alloy.menu-focus');
  7670. var make$1 = function (detail, components, spec, externals) {
  7671. return {
  7672. uid: detail.uid,
  7673. dom: detail.dom,
  7674. markers: detail.markers,
  7675. behaviours: augment(detail.menuBehaviours, [
  7676. Highlighting.config({
  7677. highlightClass: detail.markers.selectedItem,
  7678. itemClass: detail.markers.item,
  7679. onHighlight: detail.onHighlight
  7680. }),
  7681. Representing.config({
  7682. store: {
  7683. mode: 'memory',
  7684. initialValue: detail.value
  7685. }
  7686. }),
  7687. Composing.config({ find: Option.some }),
  7688. Keying.config(detail.movement.config(detail, detail.movement))
  7689. ]),
  7690. events: derive([
  7691. run(focus$3(), function (menu, simulatedEvent) {
  7692. var event = simulatedEvent.event();
  7693. menu.getSystem().getByDom(event.target()).each(function (item) {
  7694. Highlighting.highlight(menu, item);
  7695. simulatedEvent.stop();
  7696. emitWith(menu, focus$4(), {
  7697. menu: menu,
  7698. item: item
  7699. });
  7700. });
  7701. }),
  7702. run(hover(), function (menu, simulatedEvent) {
  7703. var item = simulatedEvent.event().item();
  7704. Highlighting.highlight(menu, item);
  7705. })
  7706. ]),
  7707. components: components,
  7708. eventOrder: detail.eventOrder,
  7709. domModification: { attributes: { role: 'menu' } }
  7710. };
  7711. };
  7712. var Menu = composite$1({
  7713. name: 'Menu',
  7714. configFields: schema$d(),
  7715. partFields: parts$1(),
  7716. factory: make$1
  7717. });
  7718. var transpose = function (obj) {
  7719. return tupleMap(obj, function (v, k) {
  7720. return {
  7721. k: v,
  7722. v: k
  7723. };
  7724. });
  7725. };
  7726. var trace = function (items, byItem, byMenu, finish) {
  7727. return get(byMenu, finish).bind(function (triggerItem) {
  7728. return get(items, triggerItem).bind(function (triggerMenu) {
  7729. var rest = trace(items, byItem, byMenu, triggerMenu);
  7730. return Option.some([triggerMenu].concat(rest));
  7731. });
  7732. }).getOr([]);
  7733. };
  7734. var generate$5 = function (menus, expansions) {
  7735. var items = {};
  7736. each$1(menus, function (menuItems, menu) {
  7737. each(menuItems, function (item) {
  7738. items[item] = menu;
  7739. });
  7740. });
  7741. var byItem = expansions;
  7742. var byMenu = transpose(expansions);
  7743. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  7744. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  7745. });
  7746. return map$1(items, function (menu) {
  7747. return get(menuPaths, menu).getOr([menu]);
  7748. });
  7749. };
  7750. var init$3 = function () {
  7751. var expansions = Cell({});
  7752. var menus = Cell({});
  7753. var paths = Cell({});
  7754. var primary = Cell(Option.none());
  7755. var directory = Cell({});
  7756. var clear = function () {
  7757. expansions.set({});
  7758. menus.set({});
  7759. paths.set({});
  7760. primary.set(Option.none());
  7761. };
  7762. var isClear = function () {
  7763. return primary.get().isNone();
  7764. };
  7765. var setMenuBuilt = function (menuName, built) {
  7766. var _a;
  7767. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  7768. type: 'prepared',
  7769. menu: built
  7770. }, _a)));
  7771. };
  7772. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  7773. primary.set(Option.some(sPrimary));
  7774. expansions.set(sExpansions);
  7775. menus.set(sMenus);
  7776. directory.set(dir);
  7777. var sPaths = generate$5(dir, sExpansions);
  7778. paths.set(sPaths);
  7779. };
  7780. var getTriggeringItem = function (menuValue) {
  7781. return find$1(expansions.get(), function (v, k) {
  7782. return v === menuValue;
  7783. });
  7784. };
  7785. var getTriggerData = function (menuValue, getItemByValue, path) {
  7786. return getPreparedMenu(menuValue).bind(function (menu) {
  7787. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  7788. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  7789. return {
  7790. triggeredMenu: menu,
  7791. triggeringItem: triggeredItem,
  7792. triggeringPath: path
  7793. };
  7794. });
  7795. });
  7796. });
  7797. };
  7798. var getTriggeringPath = function (itemValue, getItemByValue) {
  7799. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  7800. return getPreparedMenu(menuValue).isSome();
  7801. });
  7802. return get(paths.get(), itemValue).bind(function (path) {
  7803. var revPath = reverse(extraPath.concat(path));
  7804. var triggers = bind(revPath, function (menuValue, menuIndex) {
  7805. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  7806. return primary.get().is(menuValue) ? [] : [Option.none()];
  7807. }, function (data) {
  7808. return [Option.some(data)];
  7809. });
  7810. });
  7811. return sequence(triggers);
  7812. });
  7813. };
  7814. var expand = function (itemValue) {
  7815. return get(expansions.get(), itemValue).map(function (menu) {
  7816. var current = get(paths.get(), itemValue).getOr([]);
  7817. return [menu].concat(current);
  7818. });
  7819. };
  7820. var collapse = function (itemValue) {
  7821. return get(paths.get(), itemValue).bind(function (path) {
  7822. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  7823. });
  7824. };
  7825. var refresh = function (itemValue) {
  7826. return get(paths.get(), itemValue);
  7827. };
  7828. var getPreparedMenu = function (menuValue) {
  7829. return lookupMenu(menuValue).bind(extractPreparedMenu);
  7830. };
  7831. var lookupMenu = function (menuValue) {
  7832. return get(menus.get(), menuValue);
  7833. };
  7834. var lookupItem = function (itemValue) {
  7835. return get(expansions.get(), itemValue);
  7836. };
  7837. var otherMenus = function (path) {
  7838. var menuValues = directory.get();
  7839. return difference(keys(menuValues), path);
  7840. };
  7841. var getPrimary = function () {
  7842. return primary.get().bind(getPreparedMenu);
  7843. };
  7844. var getMenus = function () {
  7845. return menus.get();
  7846. };
  7847. return {
  7848. setMenuBuilt: setMenuBuilt,
  7849. setContents: setContents,
  7850. expand: expand,
  7851. refresh: refresh,
  7852. collapse: collapse,
  7853. lookupMenu: lookupMenu,
  7854. lookupItem: lookupItem,
  7855. otherMenus: otherMenus,
  7856. getPrimary: getPrimary,
  7857. getMenus: getMenus,
  7858. clear: clear,
  7859. isClear: isClear,
  7860. getTriggeringPath: getTriggeringPath
  7861. };
  7862. };
  7863. var extractPreparedMenu = function (prep) {
  7864. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  7865. };
  7866. var LayeredState = {
  7867. init: init$3,
  7868. extractPreparedMenu: extractPreparedMenu
  7869. };
  7870. var make$2 = function (detail, rawUiSpec) {
  7871. var submenuParentItems = Cell(Option.none());
  7872. var buildMenus = function (container, primaryName, menus) {
  7873. return map$1(menus, function (spec, name) {
  7874. var makeSketch = function () {
  7875. return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), {
  7876. value: name,
  7877. items: spec.items,
  7878. markers: detail.markers,
  7879. fakeFocus: detail.fakeFocus,
  7880. onHighlight: detail.onHighlight,
  7881. focusManager: detail.fakeFocus ? highlights() : dom()
  7882. }));
  7883. };
  7884. return name === primaryName ? {
  7885. type: 'prepared',
  7886. menu: container.getSystem().build(makeSketch())
  7887. } : {
  7888. type: 'notbuilt',
  7889. nbMenu: makeSketch
  7890. };
  7891. });
  7892. };
  7893. var layeredState = LayeredState.init();
  7894. var setup = function (container) {
  7895. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  7896. var directory = toDirectory();
  7897. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  7898. return layeredState.getPrimary();
  7899. };
  7900. var getItemValue = function (item) {
  7901. return Representing.getValue(item).value;
  7902. };
  7903. var getItemByValue = function (container, menus, itemValue) {
  7904. return findMap(menus, function (menu) {
  7905. if (!menu.getSystem().isConnected()) {
  7906. return Option.none();
  7907. }
  7908. var candidates = Highlighting.getCandidates(menu);
  7909. return find(candidates, function (c) {
  7910. return getItemValue(c) === itemValue;
  7911. });
  7912. });
  7913. };
  7914. var toDirectory = function (container) {
  7915. return map$1(detail.data.menus, function (data, menuName) {
  7916. return bind(data.items, function (item) {
  7917. return item.type === 'separator' ? [] : [item.data.value];
  7918. });
  7919. });
  7920. };
  7921. var setActiveMenu = function (container, menu) {
  7922. Highlighting.highlight(container, menu);
  7923. Highlighting.getHighlighted(menu).orThunk(function () {
  7924. return Highlighting.getFirst(menu);
  7925. }).each(function (item) {
  7926. dispatch(container, item.element(), focusItem());
  7927. });
  7928. };
  7929. var getMenus = function (state, menuValues) {
  7930. return cat(map(menuValues, function (mv) {
  7931. return state.lookupMenu(mv).bind(function (prep) {
  7932. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  7933. });
  7934. }));
  7935. };
  7936. var closeOthers = function (container, state, path) {
  7937. var others = getMenus(state, state.otherMenus(path));
  7938. each(others, function (o) {
  7939. remove$5(o.element(), [detail.markers.backgroundMenu]);
  7940. if (!detail.stayInDom) {
  7941. Replacing.remove(container, o);
  7942. }
  7943. });
  7944. };
  7945. var getSubmenuParents = function (container) {
  7946. return submenuParentItems.get().getOrThunk(function () {
  7947. var r = {};
  7948. var items = descendants(container.element(), '.' + detail.markers.item);
  7949. var parentItems = filter(items, function (i) {
  7950. return get$2(i, 'aria-haspopup') === 'true';
  7951. });
  7952. each(parentItems, function (i) {
  7953. container.getSystem().getByDom(i).each(function (itemComp) {
  7954. var key = getItemValue(itemComp);
  7955. r[key] = itemComp;
  7956. });
  7957. });
  7958. submenuParentItems.set(Option.some(r));
  7959. return r;
  7960. });
  7961. };
  7962. var updateAriaExpansions = function (container, path) {
  7963. var parentItems = getSubmenuParents(container);
  7964. each$1(parentItems, function (v, k) {
  7965. var expanded = contains(path, k);
  7966. set$1(v.element(), 'aria-expanded', expanded);
  7967. });
  7968. };
  7969. var updateMenuPath = function (container, state, path) {
  7970. return Option.from(path[0]).bind(function (latestMenuName) {
  7971. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  7972. if (menuPrep.type === 'notbuilt') {
  7973. return Option.none();
  7974. } else {
  7975. var activeMenu = menuPrep.menu;
  7976. var rest = getMenus(state, path.slice(1));
  7977. each(rest, function (r) {
  7978. add$2(r.element(), detail.markers.backgroundMenu);
  7979. });
  7980. if (!inBody(activeMenu.element())) {
  7981. Replacing.append(container, premade$1(activeMenu));
  7982. }
  7983. remove$5(activeMenu.element(), [detail.markers.backgroundMenu]);
  7984. setActiveMenu(container, activeMenu);
  7985. closeOthers(container, state, path);
  7986. return Option.some(activeMenu);
  7987. }
  7988. });
  7989. });
  7990. };
  7991. var ExpandHighlightDecision;
  7992. (function (ExpandHighlightDecision) {
  7993. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  7994. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  7995. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  7996. var buildIfRequired = function (container, menuName, menuPrep) {
  7997. if (menuPrep.type === 'notbuilt') {
  7998. var menu = container.getSystem().build(menuPrep.nbMenu());
  7999. layeredState.setMenuBuilt(menuName, menu);
  8000. return menu;
  8001. } else {
  8002. return menuPrep.menu;
  8003. }
  8004. };
  8005. var expandRight = function (container, item, decision) {
  8006. if (decision === void 0) {
  8007. decision = ExpandHighlightDecision.HighlightSubmenu;
  8008. }
  8009. var value = getItemValue(item);
  8010. return layeredState.expand(value).bind(function (path) {
  8011. updateAriaExpansions(container, path);
  8012. return Option.from(path[0]).bind(function (menuName) {
  8013. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8014. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8015. if (!inBody(activeMenu.element())) {
  8016. Replacing.append(container, premade$1(activeMenu));
  8017. }
  8018. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8019. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8020. Highlighting.highlightFirst(activeMenu);
  8021. return updateMenuPath(container, layeredState, path);
  8022. } else {
  8023. Highlighting.dehighlightAll(activeMenu);
  8024. return Option.some(item);
  8025. }
  8026. });
  8027. });
  8028. });
  8029. };
  8030. var collapseLeft = function (container, item) {
  8031. var value = getItemValue(item);
  8032. return layeredState.collapse(value).bind(function (path) {
  8033. updateAriaExpansions(container, path);
  8034. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8035. detail.onCollapseMenu(container, item, activeMenu);
  8036. return activeMenu;
  8037. });
  8038. });
  8039. };
  8040. var updateView = function (container, item) {
  8041. var value = getItemValue(item);
  8042. return layeredState.refresh(value).bind(function (path) {
  8043. updateAriaExpansions(container, path);
  8044. return updateMenuPath(container, layeredState, path);
  8045. });
  8046. };
  8047. var onRight = function (container, item) {
  8048. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8049. };
  8050. var onLeft = function (container, item) {
  8051. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  8052. };
  8053. var onEscape = function (container, item) {
  8054. return collapseLeft(container, item).orThunk(function () {
  8055. return detail.onEscape(container, item).map(function () {
  8056. return container;
  8057. });
  8058. });
  8059. };
  8060. var keyOnItem = function (f) {
  8061. return function (container, simulatedEvent) {
  8062. return closest$3(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8063. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  8064. return f(container, item).map(function () {
  8065. return true;
  8066. });
  8067. });
  8068. });
  8069. };
  8070. };
  8071. var events = derive([
  8072. run(focus$4(), function (sandbox, simulatedEvent) {
  8073. var item = simulatedEvent.event().item();
  8074. layeredState.lookupItem(getItemValue(item)).each(function () {
  8075. var menu = simulatedEvent.event().menu();
  8076. Highlighting.highlight(sandbox, menu);
  8077. var value = getItemValue(simulatedEvent.event().item());
  8078. layeredState.refresh(value).each(function (path) {
  8079. return closeOthers(sandbox, layeredState, path);
  8080. });
  8081. });
  8082. }),
  8083. runOnExecute(function (component, simulatedEvent) {
  8084. var target = simulatedEvent.event().target();
  8085. component.getSystem().getByDom(target).each(function (item) {
  8086. var itemValue = getItemValue(item);
  8087. if (itemValue.indexOf('collapse-item') === 0) {
  8088. collapseLeft(component, item);
  8089. }
  8090. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8091. detail.onExecute(component, item);
  8092. }, function () {
  8093. });
  8094. });
  8095. }),
  8096. runOnAttached(function (container, simulatedEvent) {
  8097. setup(container).each(function (primary) {
  8098. Replacing.append(container, premade$1(primary));
  8099. detail.onOpenMenu(container, primary);
  8100. if (detail.highlightImmediately) {
  8101. setActiveMenu(container, primary);
  8102. }
  8103. });
  8104. })
  8105. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8106. var item = simulatedEvent.event().item();
  8107. updateView(sandbox, item);
  8108. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8109. detail.onHover(sandbox, item);
  8110. })] : []));
  8111. var getActiveItem = function (container) {
  8112. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8113. };
  8114. var collapseMenuApi = function (container) {
  8115. getActiveItem(container).each(function (currentItem) {
  8116. collapseLeft(container, currentItem);
  8117. });
  8118. };
  8119. var highlightPrimary = function (container) {
  8120. layeredState.getPrimary().each(function (primary) {
  8121. setActiveMenu(container, primary);
  8122. });
  8123. };
  8124. var extractMenuFromContainer = function (container) {
  8125. return Option.from(container.components()[0]).filter(function (comp) {
  8126. return get$2(comp.element(), 'role') === 'menu';
  8127. });
  8128. };
  8129. var repositionMenus = function (container) {
  8130. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8131. return getActiveItem(container).bind(function (currentItem) {
  8132. var itemValue = getItemValue(currentItem);
  8133. var allMenus = values(layeredState.getMenus());
  8134. var preparedMenus = cat(map(allMenus, LayeredState.extractPreparedMenu));
  8135. return layeredState.getTriggeringPath(itemValue, function (v) {
  8136. return getItemByValue(container, preparedMenus, v);
  8137. });
  8138. }).map(function (triggeringPath) {
  8139. return {
  8140. primary: primary,
  8141. triggeringPath: triggeringPath
  8142. };
  8143. });
  8144. });
  8145. maybeActivePrimary.fold(function () {
  8146. extractMenuFromContainer(container).each(function (primaryMenu) {
  8147. detail.onRepositionMenu(container, primaryMenu, []);
  8148. });
  8149. }, function (_a) {
  8150. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8151. detail.onRepositionMenu(container, primary, triggeringPath);
  8152. });
  8153. };
  8154. var apis = {
  8155. collapseMenu: collapseMenuApi,
  8156. highlightPrimary: highlightPrimary,
  8157. repositionMenus: repositionMenus
  8158. };
  8159. return {
  8160. uid: detail.uid,
  8161. dom: detail.dom,
  8162. markers: detail.markers,
  8163. behaviours: augment(detail.tmenuBehaviours, [
  8164. Keying.config({
  8165. mode: 'special',
  8166. onRight: keyOnItem(onRight),
  8167. onLeft: keyOnItem(onLeft),
  8168. onEscape: keyOnItem(onEscape),
  8169. focusIn: function (container, keyInfo) {
  8170. layeredState.getPrimary().each(function (primary) {
  8171. dispatch(container, primary.element(), focusItem());
  8172. });
  8173. }
  8174. }),
  8175. Highlighting.config({
  8176. highlightClass: detail.markers.selectedMenu,
  8177. itemClass: detail.markers.menu
  8178. }),
  8179. Composing.config({
  8180. find: function (container) {
  8181. return Highlighting.getHighlighted(container);
  8182. }
  8183. }),
  8184. Replacing.config({})
  8185. ]),
  8186. eventOrder: detail.eventOrder,
  8187. apis: apis,
  8188. events: events
  8189. };
  8190. };
  8191. var collapseItem = constant('collapse-item');
  8192. var tieredData = function (primary, menus, expansions) {
  8193. return {
  8194. primary: primary,
  8195. menus: menus,
  8196. expansions: expansions
  8197. };
  8198. };
  8199. var singleData = function (name, menu) {
  8200. return {
  8201. primary: name,
  8202. menus: wrap$1(name, menu),
  8203. expansions: {}
  8204. };
  8205. };
  8206. var collapseItem$1 = function (text) {
  8207. return {
  8208. value: generate$1(collapseItem()),
  8209. meta: { text: text }
  8210. };
  8211. };
  8212. var tieredMenu = single$2({
  8213. name: 'TieredMenu',
  8214. configFields: [
  8215. onStrictKeyboardHandler('onExecute'),
  8216. onStrictKeyboardHandler('onEscape'),
  8217. onStrictHandler('onOpenMenu'),
  8218. onStrictHandler('onOpenSubmenu'),
  8219. onHandler('onRepositionMenu'),
  8220. onHandler('onCollapseMenu'),
  8221. defaulted$1('highlightImmediately', true),
  8222. strictObjOf('data', [
  8223. strict$1('primary'),
  8224. strict$1('menus'),
  8225. strict$1('expansions')
  8226. ]),
  8227. defaulted$1('fakeFocus', false),
  8228. onHandler('onHighlight'),
  8229. onHandler('onHover'),
  8230. tieredMenuMarkers(),
  8231. strict$1('dom'),
  8232. defaulted$1('navigateOnHover', true),
  8233. defaulted$1('stayInDom', false),
  8234. field$1('tmenuBehaviours', [
  8235. Keying,
  8236. Highlighting,
  8237. Composing,
  8238. Replacing
  8239. ]),
  8240. defaulted$1('eventOrder', {})
  8241. ],
  8242. apis: {
  8243. collapseMenu: function (apis, tmenu) {
  8244. apis.collapseMenu(tmenu);
  8245. },
  8246. highlightPrimary: function (apis, tmenu) {
  8247. apis.highlightPrimary(tmenu);
  8248. },
  8249. repositionMenus: function (apis, tmenu) {
  8250. apis.repositionMenus(tmenu);
  8251. }
  8252. },
  8253. factory: make$2,
  8254. extraApis: {
  8255. tieredData: tieredData,
  8256. singleData: singleData,
  8257. collapseItem: collapseItem$1
  8258. }
  8259. });
  8260. var makeMenu = function (detail, menuSandbox, anchor, menuSpec, getBounds) {
  8261. var lazySink = function () {
  8262. return detail.lazySink(menuSandbox);
  8263. };
  8264. var layouts = menuSpec.type === 'horizontal' ? {
  8265. layouts: {
  8266. onLtr: function () {
  8267. return belowOrAbove();
  8268. },
  8269. onRtl: function () {
  8270. return belowOrAboveRtl();
  8271. }
  8272. }
  8273. } : {};
  8274. var isFirstTierSubmenu = function (triggeringPaths) {
  8275. return triggeringPaths.length === 2;
  8276. };
  8277. var getSubmenuLayouts = function (triggeringPaths) {
  8278. return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  8279. };
  8280. return tieredMenu.sketch({
  8281. dom: { tag: 'div' },
  8282. data: menuSpec.data,
  8283. markers: menuSpec.menu.markers,
  8284. highlightImmediately: menuSpec.menu.highlightImmediately,
  8285. onEscape: function () {
  8286. Sandboxing.close(menuSandbox);
  8287. detail.onEscape.map(function (handler) {
  8288. return handler(menuSandbox);
  8289. });
  8290. return Option.some(true);
  8291. },
  8292. onExecute: function () {
  8293. return Option.some(true);
  8294. },
  8295. onOpenMenu: function (tmenu, menu) {
  8296. Positioning.positionWithinBounds(lazySink().getOrDie(), anchor, menu, getBounds());
  8297. },
  8298. onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  8299. var sink = lazySink().getOrDie();
  8300. Positioning.position(sink, __assign({
  8301. anchor: 'submenu',
  8302. item: item
  8303. }, getSubmenuLayouts(triggeringPaths)), submenu);
  8304. },
  8305. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  8306. var sink = lazySink().getOrDie();
  8307. Positioning.positionWithinBounds(sink, anchor, primaryMenu, getBounds());
  8308. each(submenuTriggers, function (st) {
  8309. var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  8310. Positioning.position(sink, __assign({
  8311. anchor: 'submenu',
  8312. item: st.triggeringItem
  8313. }, submenuLayouts), st.triggeredMenu);
  8314. });
  8315. }
  8316. });
  8317. };
  8318. var factory = function (detail, spec) {
  8319. var isPartOfRelated = function (sandbox, queryElem) {
  8320. var related = detail.getRelated(sandbox);
  8321. return related.exists(function (rel) {
  8322. return isPartOf(rel, queryElem);
  8323. });
  8324. };
  8325. var setContent = function (sandbox, thing) {
  8326. Sandboxing.setContent(sandbox, thing);
  8327. };
  8328. var showAt = function (sandbox, anchor, thing) {
  8329. showWithin(sandbox, anchor, thing, Option.none());
  8330. };
  8331. var showWithin = function (sandbox, anchor, thing, boxElement) {
  8332. showWithinBounds(sandbox, anchor, thing, function () {
  8333. return boxElement.map(function (elem) {
  8334. return box(elem);
  8335. });
  8336. });
  8337. };
  8338. var showWithinBounds = function (sandbox, anchor, thing, getBounds) {
  8339. var sink = detail.lazySink(sandbox).getOrDie();
  8340. Sandboxing.openWhileCloaked(sandbox, thing, function () {
  8341. return Positioning.positionWithinBounds(sink, anchor, sandbox, getBounds());
  8342. });
  8343. Representing.setValue(sandbox, Option.some({
  8344. mode: 'position',
  8345. anchor: anchor,
  8346. getBounds: getBounds
  8347. }));
  8348. };
  8349. var showMenuAt = function (sandbox, anchor, menuSpec) {
  8350. showMenuWithinBounds(sandbox, anchor, menuSpec, function () {
  8351. return Option.none();
  8352. });
  8353. };
  8354. var showMenuWithinBounds = function (sandbox, anchor, menuSpec, getBounds) {
  8355. var menu = makeMenu(detail, sandbox, anchor, menuSpec, getBounds);
  8356. Sandboxing.open(sandbox, menu);
  8357. Representing.setValue(sandbox, Option.some({
  8358. mode: 'menu',
  8359. menu: menu
  8360. }));
  8361. };
  8362. var hide = function (sandbox) {
  8363. if (Sandboxing.isOpen(sandbox)) {
  8364. Representing.setValue(sandbox, Option.none());
  8365. Sandboxing.close(sandbox);
  8366. }
  8367. };
  8368. var getContent = function (sandbox) {
  8369. return Sandboxing.getState(sandbox);
  8370. };
  8371. var reposition = function (sandbox) {
  8372. if (Sandboxing.isOpen(sandbox)) {
  8373. Representing.getValue(sandbox).each(function (state) {
  8374. switch (state.mode) {
  8375. case 'menu':
  8376. Sandboxing.getState(sandbox).each(function (tmenu) {
  8377. tieredMenu.repositionMenus(tmenu);
  8378. });
  8379. break;
  8380. case 'position':
  8381. var sink = detail.lazySink(sandbox).getOrDie();
  8382. Positioning.positionWithinBounds(sink, state.anchor, sandbox, state.getBounds());
  8383. break;
  8384. }
  8385. });
  8386. }
  8387. };
  8388. var apis = {
  8389. setContent: setContent,
  8390. showAt: showAt,
  8391. showWithin: showWithin,
  8392. showWithinBounds: showWithinBounds,
  8393. showMenuAt: showMenuAt,
  8394. showMenuWithinBounds: showMenuWithinBounds,
  8395. hide: hide,
  8396. getContent: getContent,
  8397. reposition: reposition,
  8398. isOpen: Sandboxing.isOpen
  8399. };
  8400. return {
  8401. uid: detail.uid,
  8402. dom: detail.dom,
  8403. behaviours: augment(detail.inlineBehaviours, [
  8404. Sandboxing.config({
  8405. isPartOf: function (sandbox, data, queryElem) {
  8406. return isPartOf(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  8407. },
  8408. getAttachPoint: function (sandbox) {
  8409. return detail.lazySink(sandbox).getOrDie();
  8410. },
  8411. onOpen: function (sandbox) {
  8412. detail.onShow(sandbox);
  8413. },
  8414. onClose: function (sandbox) {
  8415. detail.onHide(sandbox);
  8416. }
  8417. }),
  8418. Representing.config({
  8419. store: {
  8420. mode: 'memory',
  8421. initialValue: Option.none()
  8422. }
  8423. }),
  8424. Receiving.config({
  8425. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: constant(false) }, detail.fireDismissalEventInstead.map(function (fe) {
  8426. return { fireEventInstead: { event: fe.event } };
  8427. }).getOr({})))), receivingChannel$1(__assign(__assign({ isExtraPart: constant(false) }, detail.fireRepositionEventInstead.map(function (fe) {
  8428. return { fireEventInstead: { event: fe.event } };
  8429. }).getOr({})), { doReposition: reposition })))
  8430. })
  8431. ]),
  8432. eventOrder: detail.eventOrder,
  8433. apis: apis
  8434. };
  8435. };
  8436. var InlineView = single$2({
  8437. name: 'InlineView',
  8438. configFields: [
  8439. strict$1('lazySink'),
  8440. onHandler('onShow'),
  8441. onHandler('onHide'),
  8442. optionFunction('onEscape'),
  8443. field$1('inlineBehaviours', [
  8444. Sandboxing,
  8445. Representing,
  8446. Receiving
  8447. ]),
  8448. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  8449. optionObjOf('fireRepositionEventInstead', [defaulted$1('event', repositionRequested())]),
  8450. defaulted$1('getRelated', Option.none),
  8451. defaulted$1('eventOrder', Option.none)
  8452. ],
  8453. factory: factory,
  8454. apis: {
  8455. showAt: function (apis, component, anchor, thing) {
  8456. apis.showAt(component, anchor, thing);
  8457. },
  8458. showWithin: function (apis, component, anchor, thing, boxElement) {
  8459. apis.showWithin(component, anchor, thing, boxElement);
  8460. },
  8461. showWithinBounds: function (apis, component, anchor, thing, bounds) {
  8462. apis.showWithinBounds(component, anchor, thing, bounds);
  8463. },
  8464. showMenuAt: function (apis, component, anchor, menuSpec) {
  8465. apis.showMenuAt(component, anchor, menuSpec);
  8466. },
  8467. showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  8468. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  8469. },
  8470. hide: function (apis, component) {
  8471. apis.hide(component);
  8472. },
  8473. isOpen: function (apis, component) {
  8474. return apis.isOpen(component);
  8475. },
  8476. getContent: function (apis, component) {
  8477. return apis.getContent(component);
  8478. },
  8479. setContent: function (apis, component, thing) {
  8480. apis.setContent(component, thing);
  8481. },
  8482. reposition: function (apis, component) {
  8483. apis.reposition(component);
  8484. }
  8485. }
  8486. });
  8487. var westEdgeX$1 = function (anchor) {
  8488. return anchor.x();
  8489. };
  8490. var middleX$1 = function (anchor, element) {
  8491. return anchor.x() + anchor.width() / 2 - element.width() / 2;
  8492. };
  8493. var eastEdgeX$1 = function (anchor, element) {
  8494. return anchor.x() + anchor.width() - element.width();
  8495. };
  8496. var northY$2 = function (anchor) {
  8497. return anchor.y();
  8498. };
  8499. var southY$2 = function (anchor, element) {
  8500. return anchor.y() + anchor.height() - element.height();
  8501. };
  8502. var southeast$3 = function (anchor, element, bubbles) {
  8503. return nu$7(westEdgeX$1(anchor), southY$2(anchor, element), bubbles.innerSoutheast(), southeast(), 'layout-se');
  8504. };
  8505. var southwest$3 = function (anchor, element, bubbles) {
  8506. return nu$7(eastEdgeX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouthwest(), southwest(), 'layout-sw');
  8507. };
  8508. var northeast$3 = function (anchor, element, bubbles) {
  8509. return nu$7(westEdgeX$1(anchor), northY$2(anchor), bubbles.innerNortheast(), northeast(), 'layout-ne');
  8510. };
  8511. var northwest$3 = function (anchor, element, bubbles) {
  8512. return nu$7(eastEdgeX$1(anchor, element), northY$2(anchor), bubbles.innerNorthwest(), northwest(), 'layout-nw');
  8513. };
  8514. var north$3 = function (anchor, element, bubbles) {
  8515. return nu$7(middleX$1(anchor, element), northY$2(anchor), bubbles.innerNorth(), north(), 'layout-n');
  8516. };
  8517. var south$3 = function (anchor, element, bubbles) {
  8518. return nu$7(middleX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouth(), south(), 'layout-s');
  8519. };
  8520. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  8521. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  8522. var global$4 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  8523. var getSkinUrl = function (editor) {
  8524. var settings = editor.settings;
  8525. var skin = settings.skin;
  8526. var skinUrl = settings.skin_url;
  8527. if (skin !== false) {
  8528. var skinName = skin ? skin : 'oxide';
  8529. if (skinUrl) {
  8530. skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  8531. } else {
  8532. skinUrl = global$4.baseURL + '/skins/ui/' + skinName;
  8533. }
  8534. }
  8535. return skinUrl;
  8536. };
  8537. var isReadOnly = function (editor) {
  8538. return editor.getParam('readonly', false, 'boolean');
  8539. };
  8540. var isSkinDisabled = function (editor) {
  8541. return editor.getParam('skin') === false;
  8542. };
  8543. var getHeightSetting = function (editor) {
  8544. return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  8545. };
  8546. var getWidthSetting = function (editor) {
  8547. return editor.getParam('width', global$3.DOM.getStyle(editor.getElement(), 'width'));
  8548. };
  8549. var getMinWidthSetting = function (editor) {
  8550. return Option.from(editor.settings.min_width).filter(isNumber);
  8551. };
  8552. var getMinHeightSetting = function (editor) {
  8553. return Option.from(editor.settings.min_height).filter(isNumber);
  8554. };
  8555. var getMaxWidthSetting = function (editor) {
  8556. return Option.from(editor.getParam('max_width')).filter(isNumber);
  8557. };
  8558. var getMaxHeightSetting = function (editor) {
  8559. return Option.from(editor.getParam('max_height')).filter(isNumber);
  8560. };
  8561. var getUserStyleFormats = function (editor) {
  8562. return Option.from(editor.getParam('style_formats')).filter(isArray);
  8563. };
  8564. var isMergeStyleFormats = function (editor) {
  8565. return editor.getParam('style_formats_merge', false, 'boolean');
  8566. };
  8567. var getRemovedMenuItems = function (editor) {
  8568. return editor.getParam('removed_menuitems', '');
  8569. };
  8570. var isMenubarEnabled = function (editor) {
  8571. return editor.getParam('menubar', true, 'boolean') !== false;
  8572. };
  8573. var isToolbarEnabled = function (editor) {
  8574. var toolbar = editor.getParam('toolbar', true);
  8575. var isToolbarTrue = toolbar === true;
  8576. var isToolbarString = isString(toolbar);
  8577. var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  8578. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  8579. };
  8580. var getMultipleToolbarsSetting = function (editor) {
  8581. var keys$1 = keys(editor.settings);
  8582. var toolbarKeys = filter(keys$1, function (key) {
  8583. return /^toolbar([1-9])$/.test(key);
  8584. });
  8585. var toolbars = map(toolbarKeys, function (key) {
  8586. return editor.getParam(key, false, 'string');
  8587. });
  8588. var toolbarArray = filter(toolbars, function (toolbar) {
  8589. return typeof toolbar === 'string';
  8590. });
  8591. return toolbarArray.length > 0 ? Option.some(toolbarArray) : Option.none();
  8592. };
  8593. var isMultipleToolbars = function (editor) {
  8594. return getMultipleToolbarsSetting(editor).fold(function () {
  8595. var toolbar = editor.getParam('toolbar', [], 'string[]');
  8596. return toolbar.length > 0;
  8597. }, function () {
  8598. return true;
  8599. });
  8600. };
  8601. var ToolbarMode;
  8602. (function (ToolbarMode) {
  8603. ToolbarMode['default'] = 'wrap';
  8604. ToolbarMode['floating'] = 'floating';
  8605. ToolbarMode['sliding'] = 'sliding';
  8606. ToolbarMode['scrolling'] = 'scrolling';
  8607. }(ToolbarMode || (ToolbarMode = {})));
  8608. var getToolbarMode = function (editor) {
  8609. return editor.getParam('toolbar_mode', '', 'string');
  8610. };
  8611. var ToolbarLocation;
  8612. (function (ToolbarLocation) {
  8613. ToolbarLocation['top'] = 'top';
  8614. ToolbarLocation['bottom'] = 'bottom';
  8615. }(ToolbarLocation || (ToolbarLocation = {})));
  8616. var getToolbarGroups = function (editor) {
  8617. return editor.getParam('toolbar_groups', {}, 'object');
  8618. };
  8619. var isToolbarLocationTop = function (editor) {
  8620. return editor.getParam('toolbar_location', ToolbarLocation.top, 'string') !== ToolbarLocation.bottom;
  8621. };
  8622. var fixedContainerSelector = function (editor) {
  8623. return editor.getParam('fixed_toolbar_container', '', 'string');
  8624. };
  8625. var fixedContainerElement = function (editor) {
  8626. var selector = fixedContainerSelector(editor);
  8627. return selector.length > 0 && editor.inline ? descendant$1(body(), selector) : Option.none();
  8628. };
  8629. var useFixedContainer = function (editor) {
  8630. return editor.inline && fixedContainerElement(editor).isSome();
  8631. };
  8632. var getUiContainer = function (editor) {
  8633. var fixedContainer = fixedContainerElement(editor);
  8634. return fixedContainer.getOr(body());
  8635. };
  8636. var isDistractionFree = function (editor) {
  8637. return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  8638. };
  8639. var isStickyToolbar = function (editor) {
  8640. var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  8641. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  8642. };
  8643. var isDraggableModal = function (editor) {
  8644. return editor.getParam('draggable_modal', false, 'boolean');
  8645. };
  8646. var factory$1 = function (detail) {
  8647. var events = events$7(detail.action);
  8648. var tag = detail.dom.tag;
  8649. var lookupAttr = function (attr) {
  8650. return get(detail.dom, 'attributes').bind(function (attrs) {
  8651. return get(attrs, attr);
  8652. });
  8653. };
  8654. var getModAttributes = function () {
  8655. if (tag === 'button') {
  8656. var type = lookupAttr('type').getOr('button');
  8657. var roleAttrs = lookupAttr('role').map(function (role) {
  8658. return { role: role };
  8659. }).getOr({});
  8660. return __assign({ type: type }, roleAttrs);
  8661. } else {
  8662. var role = lookupAttr('role').getOr('button');
  8663. return { role: role };
  8664. }
  8665. };
  8666. return {
  8667. uid: detail.uid,
  8668. dom: detail.dom,
  8669. components: detail.components,
  8670. events: events,
  8671. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  8672. Focusing.config({}),
  8673. Keying.config({
  8674. mode: 'execution',
  8675. useSpace: true,
  8676. useEnter: true
  8677. })
  8678. ]),
  8679. domModification: { attributes: getModAttributes() },
  8680. eventOrder: detail.eventOrder
  8681. };
  8682. };
  8683. var Button = single$2({
  8684. name: 'Button',
  8685. factory: factory$1,
  8686. configFields: [
  8687. defaulted$1('uid', undefined),
  8688. strict$1('dom'),
  8689. defaulted$1('components', []),
  8690. SketchBehaviours.field('buttonBehaviours', [
  8691. Focusing,
  8692. Keying
  8693. ]),
  8694. option('action'),
  8695. option('role'),
  8696. defaulted$1('eventOrder', {})
  8697. ]
  8698. });
  8699. var record = function (spec) {
  8700. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento');
  8701. var get = function (anyInSystem) {
  8702. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  8703. };
  8704. var getOpt = function (anyInSystem) {
  8705. return anyInSystem.getSystem().getByUid(uid).toOption();
  8706. };
  8707. var asSpec = function () {
  8708. return __assign(__assign({}, spec), { uid: uid });
  8709. };
  8710. return {
  8711. get: get,
  8712. getOpt: getOpt,
  8713. asSpec: asSpec
  8714. };
  8715. };
  8716. var defaultIcon = function (icons) {
  8717. return Option.from(icons()['temporary-placeholder']).getOr('!not found!');
  8718. };
  8719. var get$d = function (name, icons) {
  8720. return Option.from(icons()[name]).getOrThunk(function () {
  8721. return defaultIcon(icons);
  8722. });
  8723. };
  8724. var getOr = function (name, icons, fallback) {
  8725. return Option.from(icons()[name]).or(fallback).getOrThunk(function () {
  8726. return defaultIcon(icons);
  8727. });
  8728. };
  8729. var getFirst$1 = function (names, icons) {
  8730. return findMap(names, function (name) {
  8731. return Option.from(icons()[name]);
  8732. }).getOrThunk(function () {
  8733. return defaultIcon(icons);
  8734. });
  8735. };
  8736. var notificationIconMap = {
  8737. success: 'checkmark',
  8738. error: 'warning',
  8739. err: 'error',
  8740. warning: 'warning',
  8741. warn: 'warning',
  8742. info: 'info'
  8743. };
  8744. var factory$2 = function (detail) {
  8745. var memBannerText = record({
  8746. dom: {
  8747. tag: 'p',
  8748. innerHtml: detail.translationProvider(detail.text)
  8749. },
  8750. behaviours: derive$1([Replacing.config({})])
  8751. });
  8752. var renderPercentBar = function (percent) {
  8753. return {
  8754. dom: {
  8755. tag: 'div',
  8756. classes: ['tox-bar'],
  8757. attributes: { style: 'width: ' + percent + '%' }
  8758. }
  8759. };
  8760. };
  8761. var renderPercentText = function (percent) {
  8762. return {
  8763. dom: {
  8764. tag: 'div',
  8765. classes: ['tox-text'],
  8766. innerHtml: percent + '%'
  8767. }
  8768. };
  8769. };
  8770. var memBannerProgress = record({
  8771. dom: {
  8772. tag: 'div',
  8773. classes: detail.progress ? [
  8774. 'tox-progress-bar',
  8775. 'tox-progress-indicator'
  8776. ] : ['tox-progress-bar']
  8777. },
  8778. components: [
  8779. {
  8780. dom: {
  8781. tag: 'div',
  8782. classes: ['tox-bar-container']
  8783. },
  8784. components: [renderPercentBar(0)]
  8785. },
  8786. renderPercentText(0)
  8787. ],
  8788. behaviours: derive$1([Replacing.config({})])
  8789. });
  8790. var updateProgress = function (comp, percent) {
  8791. if (comp.getSystem().isConnected()) {
  8792. memBannerProgress.getOpt(comp).each(function (progress) {
  8793. Replacing.set(progress, [
  8794. {
  8795. dom: {
  8796. tag: 'div',
  8797. classes: ['tox-bar-container']
  8798. },
  8799. components: [renderPercentBar(percent)]
  8800. },
  8801. renderPercentText(percent)
  8802. ]);
  8803. });
  8804. }
  8805. };
  8806. var updateText = function (comp, text$1) {
  8807. if (comp.getSystem().isConnected()) {
  8808. var banner = memBannerText.get(comp);
  8809. Replacing.set(banner, [text(text$1)]);
  8810. }
  8811. };
  8812. var apis = {
  8813. updateProgress: updateProgress,
  8814. updateText: updateText
  8815. };
  8816. var iconChoices = flatten([
  8817. detail.icon.toArray(),
  8818. detail.level.toArray(),
  8819. detail.level.bind(function (level) {
  8820. return Option.from(notificationIconMap[level]);
  8821. }).toArray()
  8822. ]);
  8823. return {
  8824. uid: detail.uid,
  8825. dom: {
  8826. tag: 'div',
  8827. attributes: { role: 'alert' },
  8828. classes: detail.level.map(function (level) {
  8829. return [
  8830. 'tox-notification',
  8831. 'tox-notification--in',
  8832. 'tox-notification--' + level
  8833. ];
  8834. }).getOr([
  8835. 'tox-notification',
  8836. 'tox-notification--in'
  8837. ])
  8838. },
  8839. components: [
  8840. {
  8841. dom: {
  8842. tag: 'div',
  8843. classes: ['tox-notification__icon'],
  8844. innerHtml: getFirst$1(iconChoices, detail.iconProvider)
  8845. }
  8846. },
  8847. {
  8848. dom: {
  8849. tag: 'div',
  8850. classes: ['tox-notification__body']
  8851. },
  8852. components: [memBannerText.asSpec()],
  8853. behaviours: derive$1([Replacing.config({})])
  8854. }
  8855. ].concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [Button.sketch({
  8856. dom: {
  8857. tag: 'button',
  8858. classes: [
  8859. 'tox-notification__dismiss',
  8860. 'tox-button',
  8861. 'tox-button--naked',
  8862. 'tox-button--icon'
  8863. ]
  8864. },
  8865. components: [{
  8866. dom: {
  8867. tag: 'div',
  8868. classes: ['tox-icon'],
  8869. innerHtml: get$d('close', detail.iconProvider),
  8870. attributes: { 'aria-label': detail.translationProvider('Close') }
  8871. }
  8872. }],
  8873. action: function (comp) {
  8874. detail.onAction(comp);
  8875. }
  8876. })]),
  8877. apis: apis
  8878. };
  8879. };
  8880. var Notification = single$2({
  8881. name: 'Notification',
  8882. factory: factory$2,
  8883. configFields: [
  8884. option('level'),
  8885. strict$1('progress'),
  8886. strict$1('icon'),
  8887. strict$1('onAction'),
  8888. strict$1('text'),
  8889. strict$1('iconProvider'),
  8890. strict$1('translationProvider'),
  8891. defaultedBoolean('closeButton', true)
  8892. ],
  8893. apis: {
  8894. updateProgress: function (apis, comp, percent) {
  8895. apis.updateProgress(comp, percent);
  8896. },
  8897. updateText: function (apis, comp, text) {
  8898. apis.updateText(comp, text);
  8899. }
  8900. }
  8901. });
  8902. function NotificationManagerImpl (editor, extras, uiMothership) {
  8903. var backstage = extras.backstage;
  8904. var isToolbarLocationTop$1 = isToolbarLocationTop(editor);
  8905. var getLayoutDirection = function (rel) {
  8906. switch (rel) {
  8907. case 'bc-bc':
  8908. return south$3;
  8909. case 'tc-tc':
  8910. return north$3;
  8911. case 'tc-bc':
  8912. return north$1;
  8913. case 'bc-tc':
  8914. default:
  8915. return south$1;
  8916. }
  8917. };
  8918. var prePositionNotifications = function (notifications) {
  8919. each(notifications, function (notification) {
  8920. return notification.moveTo(0, 0);
  8921. });
  8922. };
  8923. var positionNotifications = function (notifications) {
  8924. if (notifications.length > 0) {
  8925. head(notifications).each(function (firstItem) {
  8926. return firstItem.moveRel(null, 'banner');
  8927. });
  8928. each(notifications, function (notification, index) {
  8929. if (index > 0) {
  8930. notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  8931. }
  8932. });
  8933. }
  8934. };
  8935. var reposition = function (notifications) {
  8936. prePositionNotifications(notifications);
  8937. positionNotifications(notifications);
  8938. };
  8939. var open = function (settings, closeCallback) {
  8940. var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
  8941. var close = function () {
  8942. closeCallback();
  8943. InlineView.hide(notificationWrapper);
  8944. };
  8945. var notification = build$1(Notification.sketch({
  8946. text: settings.text,
  8947. level: contains([
  8948. 'success',
  8949. 'error',
  8950. 'warning',
  8951. 'warn',
  8952. 'info'
  8953. ], settings.type) ? settings.type : undefined,
  8954. progress: settings.progressBar === true,
  8955. icon: Option.from(settings.icon),
  8956. closeButton: !hideCloseButton,
  8957. onAction: close,
  8958. iconProvider: backstage.shared.providers.icons,
  8959. translationProvider: backstage.shared.providers.translate
  8960. }));
  8961. var notificationWrapper = build$1(InlineView.sketch(__assign({
  8962. dom: {
  8963. tag: 'div',
  8964. classes: ['tox-notifications-container']
  8965. },
  8966. lazySink: extras.backstage.shared.getSink,
  8967. fireDismissalEventInstead: {}
  8968. }, isToolbarLocationTop$1 ? {} : { fireRepositionEventInstead: {} })));
  8969. uiMothership.add(notificationWrapper);
  8970. if (settings.timeout > 0) {
  8971. global$2.setTimeout(function () {
  8972. close();
  8973. }, settings.timeout);
  8974. }
  8975. return {
  8976. close: close,
  8977. moveTo: function (x, y) {
  8978. InlineView.showAt(notificationWrapper, {
  8979. anchor: 'makeshift',
  8980. x: x,
  8981. y: y
  8982. }, premade$1(notification));
  8983. },
  8984. moveRel: function (element, rel) {
  8985. if (rel !== 'banner') {
  8986. var layoutDirection_1 = getLayoutDirection(rel);
  8987. var nodeAnchor = {
  8988. anchor: 'node',
  8989. root: body(),
  8990. node: Option.some(Element.fromDom(element)),
  8991. layouts: {
  8992. onRtl: function () {
  8993. return [layoutDirection_1];
  8994. },
  8995. onLtr: function () {
  8996. return [layoutDirection_1];
  8997. }
  8998. }
  8999. };
  9000. InlineView.showAt(notificationWrapper, nodeAnchor, premade$1(notification));
  9001. } else {
  9002. InlineView.showAt(notificationWrapper, extras.backstage.shared.anchors.banner(), premade$1(notification));
  9003. }
  9004. },
  9005. text: function (nuText) {
  9006. Notification.updateText(notification, nuText);
  9007. },
  9008. settings: settings,
  9009. getEl: function () {
  9010. return notification.element().dom();
  9011. },
  9012. progressBar: {
  9013. value: function (percent) {
  9014. Notification.updateProgress(notification, percent);
  9015. }
  9016. }
  9017. };
  9018. };
  9019. var close = function (notification) {
  9020. notification.close();
  9021. };
  9022. var getArgs = function (notification) {
  9023. return notification.settings;
  9024. };
  9025. return {
  9026. open: open,
  9027. close: close,
  9028. reposition: reposition,
  9029. getArgs: getArgs
  9030. };
  9031. }
  9032. var first = function (fn, rate) {
  9033. var timer = null;
  9034. var cancel = function () {
  9035. if (timer !== null) {
  9036. domGlobals.clearTimeout(timer);
  9037. timer = null;
  9038. }
  9039. };
  9040. var throttle = function () {
  9041. var args = [];
  9042. for (var _i = 0; _i < arguments.length; _i++) {
  9043. args[_i] = arguments[_i];
  9044. }
  9045. if (timer === null) {
  9046. timer = domGlobals.setTimeout(function () {
  9047. fn.apply(null, args);
  9048. timer = null;
  9049. }, rate);
  9050. }
  9051. };
  9052. return {
  9053. cancel: cancel,
  9054. throttle: throttle
  9055. };
  9056. };
  9057. var last$2 = function (fn, rate) {
  9058. var timer = null;
  9059. var cancel = function () {
  9060. if (timer !== null) {
  9061. domGlobals.clearTimeout(timer);
  9062. timer = null;
  9063. }
  9064. };
  9065. var throttle = function () {
  9066. var args = [];
  9067. for (var _i = 0; _i < arguments.length; _i++) {
  9068. args[_i] = arguments[_i];
  9069. }
  9070. if (timer !== null) {
  9071. domGlobals.clearTimeout(timer);
  9072. }
  9073. timer = domGlobals.setTimeout(function () {
  9074. fn.apply(null, args);
  9075. timer = null;
  9076. }, rate);
  9077. };
  9078. return {
  9079. cancel: cancel,
  9080. throttle: throttle
  9081. };
  9082. };
  9083. var global$5 = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker');
  9084. var isBoundary = function (dom, node) {
  9085. return dom.isBlock(node) || contains([
  9086. 'BR',
  9087. 'IMG',
  9088. 'HR',
  9089. 'INPUT'
  9090. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  9091. };
  9092. var repeatLeft = function (dom, node, offset, process, rootNode) {
  9093. var search = global$5(dom, function (node) {
  9094. return isBoundary(dom, node);
  9095. });
  9096. return Option.from(search.backwards(node, offset, process, rootNode));
  9097. };
  9098. var autocompleteSelector = '[data-mce-autocompleter]';
  9099. var create$4 = function (editor, range) {
  9100. return detect$4(Element.fromDom(editor.selection.getNode())).getOrThunk(function () {
  9101. var wrapper = Element.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  9102. append(wrapper, Element.fromDom(range.extractContents()));
  9103. range.insertNode(wrapper.dom());
  9104. parent(wrapper).each(function (elm) {
  9105. return elm.dom().normalize();
  9106. });
  9107. last$1(wrapper).map(function (last) {
  9108. editor.selection.setCursorLocation(last.dom(), getEnd(last));
  9109. });
  9110. return wrapper;
  9111. });
  9112. };
  9113. var detect$4 = function (elm) {
  9114. return closest$3(elm, autocompleteSelector);
  9115. };
  9116. var isValidTextRange = function (rng) {
  9117. return rng.collapsed && rng.startContainer.nodeType === 3;
  9118. };
  9119. var getText = function (rng) {
  9120. return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  9121. };
  9122. var isWhitespace = function (chr) {
  9123. return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  9124. };
  9125. var stripTriggerChar = function (text, triggerCh) {
  9126. return text.substring(triggerCh.length);
  9127. };
  9128. var findChar = function (text, index, ch) {
  9129. var i;
  9130. for (i = index - 1; i >= 0; i--) {
  9131. var char = text.charAt(i);
  9132. if (isWhitespace(char)) {
  9133. return Option.none();
  9134. }
  9135. if (char === ch) {
  9136. break;
  9137. }
  9138. }
  9139. return Option.some(i);
  9140. };
  9141. var findStart = function (dom, initRange, ch, minChars) {
  9142. if (minChars === void 0) {
  9143. minChars = 0;
  9144. }
  9145. if (!isValidTextRange(initRange)) {
  9146. return Option.none();
  9147. }
  9148. var findTriggerChIndex = function (element, offset, text) {
  9149. return findChar(text, offset, ch).getOr(offset);
  9150. };
  9151. var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  9152. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) {
  9153. var range = initRange.cloneRange();
  9154. range.setStart(spot.container, spot.offset);
  9155. range.setEnd(initRange.endContainer, initRange.endOffset);
  9156. if (range.collapsed) {
  9157. return Option.none();
  9158. }
  9159. var text = getText(range);
  9160. var triggerCharIndex = text.lastIndexOf(ch);
  9161. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  9162. return Option.none();
  9163. } else {
  9164. return Option.some({
  9165. text: stripTriggerChar(text, ch),
  9166. range: range,
  9167. triggerChar: ch
  9168. });
  9169. }
  9170. });
  9171. };
  9172. var getContext = function (dom, initRange, ch, minChars) {
  9173. if (minChars === void 0) {
  9174. minChars = 0;
  9175. }
  9176. return detect$4(Element.fromDom(initRange.startContainer)).fold(function () {
  9177. return findStart(dom, initRange, ch, minChars);
  9178. }, function (elm) {
  9179. var range = dom.createRng();
  9180. range.selectNode(elm.dom());
  9181. var text = getText(range);
  9182. return Option.some({
  9183. range: range,
  9184. text: stripTriggerChar(text, ch),
  9185. triggerChar: ch
  9186. });
  9187. });
  9188. };
  9189. var setup = function (api, editor) {
  9190. editor.on('keypress compositionend', api.onKeypress.throttle);
  9191. editor.on('remove', api.onKeypress.cancel);
  9192. var redirectKeyToItem = function (item, e) {
  9193. emitWith(item, keydown(), { raw: e });
  9194. };
  9195. editor.on('keydown', function (e) {
  9196. var getItem = function () {
  9197. return api.getView().bind(Highlighting.getHighlighted);
  9198. };
  9199. if (e.which === 8) {
  9200. api.onKeypress.throttle(e);
  9201. }
  9202. if (api.isActive()) {
  9203. if (e.which === 27) {
  9204. api.cancelIfNecessary();
  9205. }
  9206. if (api.isMenuOpen()) {
  9207. if (e.which === 13) {
  9208. getItem().each(emitExecute);
  9209. e.preventDefault();
  9210. } else if (e.which === 40) {
  9211. getItem().fold(function () {
  9212. api.getView().each(Highlighting.highlightFirst);
  9213. }, function (item) {
  9214. redirectKeyToItem(item, e);
  9215. });
  9216. e.preventDefault();
  9217. e.stopImmediatePropagation();
  9218. } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  9219. getItem().each(function (item) {
  9220. redirectKeyToItem(item, e);
  9221. e.preventDefault();
  9222. e.stopImmediatePropagation();
  9223. });
  9224. }
  9225. } else {
  9226. if (e.which === 13 || e.which === 38 || e.which === 40) {
  9227. api.cancelIfNecessary();
  9228. }
  9229. }
  9230. }
  9231. });
  9232. editor.on('NodeChange', function (e) {
  9233. if (api.isActive() && !api.isProcessingAction() && detect$4(Element.fromDom(e.element)).isNone()) {
  9234. api.cancelIfNecessary();
  9235. }
  9236. });
  9237. };
  9238. var AutocompleterEditorEvents = { setup: setup };
  9239. var global$6 = tinymce.util.Tools.resolve('tinymce.util.Promise');
  9240. var point$2 = function (container, offset) {
  9241. return {
  9242. container: container,
  9243. offset: offset
  9244. };
  9245. };
  9246. var isText$1 = function (node) {
  9247. return node.nodeType === domGlobals.Node.TEXT_NODE;
  9248. };
  9249. var isElement$1 = function (node) {
  9250. return node.nodeType === domGlobals.Node.ELEMENT_NODE;
  9251. };
  9252. var toLast = function (node) {
  9253. if (isText$1(node)) {
  9254. return point$2(node, node.data.length);
  9255. } else {
  9256. var children = node.childNodes;
  9257. return children.length > 0 ? toLast(children[children.length - 1]) : point$2(node, children.length);
  9258. }
  9259. };
  9260. var toLeaf = function (node, offset) {
  9261. var children = node.childNodes;
  9262. if (children.length > 0 && offset < children.length) {
  9263. return toLeaf(children[offset], 0);
  9264. } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  9265. return toLast(children[children.length - 1]);
  9266. } else {
  9267. return point$2(node, offset);
  9268. }
  9269. };
  9270. var isPreviousCharContent = function (dom, leaf) {
  9271. return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) {
  9272. return offset === 0 ? -1 : offset;
  9273. }, dom.getRoot()).filter(function (spot) {
  9274. var char = spot.container.data.charAt(spot.offset - 1);
  9275. return !isWhitespace(char);
  9276. }).isSome();
  9277. };
  9278. var isStartOfWord = function (dom) {
  9279. return function (rng) {
  9280. var leaf = toLeaf(rng.startContainer, rng.startOffset);
  9281. return !isPreviousCharContent(dom, leaf);
  9282. };
  9283. };
  9284. var getTriggerContext = function (dom, initRange, database) {
  9285. return findMap(database.triggerChars, function (ch) {
  9286. return getContext(dom, initRange, ch);
  9287. });
  9288. };
  9289. var lookup = function (editor, getDatabase) {
  9290. var database = getDatabase();
  9291. var rng = editor.selection.getRng();
  9292. return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  9293. return lookupWithContext(editor, getDatabase, context);
  9294. });
  9295. };
  9296. var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  9297. if (fetchOptions === void 0) {
  9298. fetchOptions = {};
  9299. }
  9300. var database = getDatabase();
  9301. var rng = editor.selection.getRng();
  9302. var startText = rng.startContainer.nodeValue;
  9303. var autocompleters = filter(database.lookupByChar(context.triggerChar), function (autocompleter) {
  9304. return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  9305. return isStartOfWord(editor.dom);
  9306. })(context.range, startText, context.text);
  9307. });
  9308. if (autocompleters.length === 0) {
  9309. return Option.none();
  9310. }
  9311. var lookupData = global$6.all(map(autocompleters, function (ac) {
  9312. var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  9313. return fetchResult.then(function (results) {
  9314. return {
  9315. matchText: context.text,
  9316. items: results,
  9317. columns: ac.columns,
  9318. onAction: ac.onAction
  9319. };
  9320. });
  9321. }));
  9322. return Option.some({
  9323. lookupData: lookupData,
  9324. context: context
  9325. });
  9326. };
  9327. var separatorMenuItemSchema = objOf([
  9328. strictString('type'),
  9329. optionString('text')
  9330. ]);
  9331. var createSeparatorMenuItem = function (spec) {
  9332. return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  9333. };
  9334. var autocompleterItemSchema = objOf([
  9335. state$1('type', function () {
  9336. return 'autocompleteitem';
  9337. }),
  9338. state$1('active', function () {
  9339. return false;
  9340. }),
  9341. state$1('disabled', function () {
  9342. return false;
  9343. }),
  9344. defaulted$1('meta', {}),
  9345. strictString('value'),
  9346. optionString('text'),
  9347. optionString('icon')
  9348. ]);
  9349. var autocompleterSchema = objOf([
  9350. strictString('type'),
  9351. strictString('ch'),
  9352. defaultedNumber('minChars', 1),
  9353. defaulted$1('columns', 1),
  9354. defaultedNumber('maxResults', 10),
  9355. optionFunction('matches'),
  9356. strictFunction('fetch'),
  9357. strictFunction('onAction')
  9358. ]);
  9359. var createSeparatorItem = function (spec) {
  9360. return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  9361. };
  9362. var createAutocompleterItem = function (spec) {
  9363. return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  9364. };
  9365. var createAutocompleter = function (spec) {
  9366. return asRaw('Autocompleter', autocompleterSchema, spec);
  9367. };
  9368. var stringArray = function (a) {
  9369. var all = {};
  9370. each(a, function (key) {
  9371. all[key] = {};
  9372. });
  9373. return keys(all);
  9374. };
  9375. var register = function (editor) {
  9376. var popups = editor.ui.registry.getAll().popups;
  9377. var dataset = map$1(popups, function (popup) {
  9378. return createAutocompleter(popup).fold(function (err) {
  9379. throw new Error(formatError(err));
  9380. }, function (x) {
  9381. return x;
  9382. });
  9383. });
  9384. var triggerChars = stringArray(mapToArray(dataset, function (v) {
  9385. return v.ch;
  9386. }));
  9387. var datasetValues = values(dataset);
  9388. var lookupByChar = function (ch) {
  9389. return filter(datasetValues, function (dv) {
  9390. return dv.ch === ch;
  9391. });
  9392. };
  9393. return {
  9394. dataset: dataset,
  9395. triggerChars: triggerChars,
  9396. lookupByChar: lookupByChar
  9397. };
  9398. };
  9399. var commonMenuItemFields = [
  9400. defaultedBoolean('disabled', false),
  9401. optionString('text'),
  9402. optionString('shortcut'),
  9403. field('value', 'value', defaultedThunk(function () {
  9404. return generate$1('menuitem-value');
  9405. }), anyValue$1()),
  9406. defaulted$1('meta', {})
  9407. ];
  9408. var menuItemSchema = objOf([
  9409. strictString('type'),
  9410. defaultedFunction('onSetup', function () {
  9411. return noop;
  9412. }),
  9413. defaultedFunction('onAction', noop),
  9414. optionString('icon')
  9415. ].concat(commonMenuItemFields));
  9416. var createMenuItem = function (spec) {
  9417. return asRaw('menuitem', menuItemSchema, spec);
  9418. };
  9419. var nestedMenuItemSchema = objOf([
  9420. strictString('type'),
  9421. strictFunction('getSubmenuItems'),
  9422. defaultedFunction('onSetup', function () {
  9423. return noop;
  9424. }),
  9425. optionString('icon')
  9426. ].concat(commonMenuItemFields));
  9427. var createNestedMenuItem = function (spec) {
  9428. return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  9429. };
  9430. var toggleMenuItemSchema = objOf([
  9431. strictString('type'),
  9432. defaultedBoolean('active', false),
  9433. defaultedFunction('onSetup', function () {
  9434. return noop;
  9435. }),
  9436. strictFunction('onAction')
  9437. ].concat(commonMenuItemFields));
  9438. var createToggleMenuItem = function (spec) {
  9439. return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  9440. };
  9441. var choiceMenuItemSchema = objOf([
  9442. strictString('type'),
  9443. defaultedBoolean('active', false),
  9444. optionString('icon')
  9445. ].concat(commonMenuItemFields));
  9446. var createChoiceMenuItem = function (spec) {
  9447. return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  9448. };
  9449. var fancyTypes = [
  9450. 'inserttable',
  9451. 'colorswatch'
  9452. ];
  9453. var fancyMenuItemSchema = objOf([
  9454. strictString('type'),
  9455. strictStringEnum('fancytype', fancyTypes),
  9456. defaultedFunction('onAction', noop)
  9457. ]);
  9458. var createFancyMenuItem = function (spec) {
  9459. return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  9460. };
  9461. var detectSize = function (comp, margin, selectorClass) {
  9462. var descendants$1 = descendants(comp.element(), '.' + selectorClass);
  9463. if (descendants$1.length > 0) {
  9464. var columnLength = findIndex(descendants$1, function (c) {
  9465. var thisTop = c.dom().getBoundingClientRect().top;
  9466. var cTop = descendants$1[0].dom().getBoundingClientRect().top;
  9467. return Math.abs(thisTop - cTop) > margin;
  9468. }).getOr(descendants$1.length);
  9469. return Option.some({
  9470. numColumns: columnLength,
  9471. numRows: Math.ceil(descendants$1.length / columnLength)
  9472. });
  9473. } else {
  9474. return Option.none();
  9475. }
  9476. };
  9477. var namedEvents = function (name, handlers) {
  9478. return derive$1([config(name, handlers)]);
  9479. };
  9480. var unnamedEvents = function (handlers) {
  9481. return namedEvents(generate$1('unnamed-events'), handlers);
  9482. };
  9483. var SimpleBehaviours = {
  9484. namedEvents: namedEvents,
  9485. unnamedEvents: unnamedEvents
  9486. };
  9487. var TooltippingSchema = [
  9488. strict$1('lazySink'),
  9489. strict$1('tooltipDom'),
  9490. defaulted$1('exclusive', true),
  9491. defaulted$1('tooltipComponents', []),
  9492. defaulted$1('delay', 300),
  9493. defaultedStringEnum('mode', 'normal', [
  9494. 'normal',
  9495. 'follow-highlight'
  9496. ]),
  9497. defaulted$1('anchor', function (comp) {
  9498. return {
  9499. anchor: 'hotspot',
  9500. hotspot: comp,
  9501. layouts: {
  9502. onLtr: constant([
  9503. south$1,
  9504. north$1,
  9505. southeast$1,
  9506. northeast$1,
  9507. southwest$1,
  9508. northwest$1
  9509. ]),
  9510. onRtl: constant([
  9511. south$1,
  9512. north$1,
  9513. southeast$1,
  9514. northeast$1,
  9515. southwest$1,
  9516. northwest$1
  9517. ])
  9518. }
  9519. };
  9520. }),
  9521. onHandler('onHide'),
  9522. onHandler('onShow')
  9523. ];
  9524. var init$4 = function () {
  9525. var timer = Cell(Option.none());
  9526. var popup = Cell(Option.none());
  9527. var getTooltip = function () {
  9528. return popup.get();
  9529. };
  9530. var setTooltip = function (comp) {
  9531. popup.set(Option.some(comp));
  9532. };
  9533. var clearTooltip = function () {
  9534. popup.set(Option.none());
  9535. };
  9536. var clearTimer = function () {
  9537. timer.get().each(function (t) {
  9538. domGlobals.clearTimeout(t);
  9539. });
  9540. };
  9541. var resetTimer = function (f, delay) {
  9542. clearTimer();
  9543. timer.set(Option.some(domGlobals.setTimeout(function () {
  9544. f();
  9545. }, delay)));
  9546. };
  9547. var isShowing = function () {
  9548. return popup.get().isSome();
  9549. };
  9550. var readState = constant('not-implemented');
  9551. return nu$5({
  9552. getTooltip: getTooltip,
  9553. isShowing: isShowing,
  9554. setTooltip: setTooltip,
  9555. clearTooltip: clearTooltip,
  9556. clearTimer: clearTimer,
  9557. resetTimer: resetTimer,
  9558. readState: readState
  9559. });
  9560. };
  9561. var TooltippingState = /*#__PURE__*/Object.freeze({
  9562. __proto__: null,
  9563. init: init$4
  9564. });
  9565. var ExclusivityChannel = generate$1('tooltip.exclusive');
  9566. var ShowTooltipEvent = generate$1('tooltip.show');
  9567. var HideTooltipEvent = generate$1('tooltip.hide');
  9568. var hideAllExclusive = function (component, tConfig, tState) {
  9569. component.getSystem().broadcastOn([ExclusivityChannel], {});
  9570. };
  9571. var setComponents = function (component, tConfig, tState, specs) {
  9572. tState.getTooltip().each(function (tooltip) {
  9573. if (tooltip.getSystem().isConnected()) {
  9574. Replacing.set(tooltip, specs);
  9575. }
  9576. });
  9577. };
  9578. var TooltippingApis = /*#__PURE__*/Object.freeze({
  9579. __proto__: null,
  9580. hideAllExclusive: hideAllExclusive,
  9581. setComponents: setComponents
  9582. });
  9583. var events$8 = function (tooltipConfig, state) {
  9584. var hide = function (comp) {
  9585. state.getTooltip().each(function (p) {
  9586. detach(p);
  9587. tooltipConfig.onHide(comp, p);
  9588. state.clearTooltip();
  9589. });
  9590. state.clearTimer();
  9591. };
  9592. var show = function (comp) {
  9593. if (!state.isShowing()) {
  9594. hideAllExclusive(comp);
  9595. var sink = tooltipConfig.lazySink(comp).getOrDie();
  9596. var popup = comp.getSystem().build({
  9597. dom: tooltipConfig.tooltipDom,
  9598. components: tooltipConfig.tooltipComponents,
  9599. events: derive(tooltipConfig.mode === 'normal' ? [
  9600. run(mouseover(), function (_) {
  9601. emit(comp, ShowTooltipEvent);
  9602. }),
  9603. run(mouseout(), function (_) {
  9604. emit(comp, HideTooltipEvent);
  9605. })
  9606. ] : []),
  9607. behaviours: derive$1([Replacing.config({})])
  9608. });
  9609. state.setTooltip(popup);
  9610. attach$1(sink, popup);
  9611. tooltipConfig.onShow(comp, popup);
  9612. Positioning.position(sink, tooltipConfig.anchor(comp), popup);
  9613. }
  9614. };
  9615. return derive(flatten([
  9616. [
  9617. run(ShowTooltipEvent, function (comp) {
  9618. state.resetTimer(function () {
  9619. show(comp);
  9620. }, tooltipConfig.delay);
  9621. }),
  9622. run(HideTooltipEvent, function (comp) {
  9623. state.resetTimer(function () {
  9624. hide(comp);
  9625. }, tooltipConfig.delay);
  9626. }),
  9627. run(receive(), function (comp, message) {
  9628. var receivingData = message;
  9629. if (contains(receivingData.channels(), ExclusivityChannel)) {
  9630. hide(comp);
  9631. }
  9632. }),
  9633. runOnDetached(function (comp) {
  9634. hide(comp);
  9635. })
  9636. ],
  9637. tooltipConfig.mode === 'normal' ? [
  9638. run(focusin(), function (comp) {
  9639. emit(comp, ShowTooltipEvent);
  9640. }),
  9641. run(postBlur(), function (comp) {
  9642. emit(comp, HideTooltipEvent);
  9643. }),
  9644. run(mouseover(), function (comp) {
  9645. emit(comp, ShowTooltipEvent);
  9646. }),
  9647. run(mouseout(), function (comp) {
  9648. emit(comp, HideTooltipEvent);
  9649. })
  9650. ] : [
  9651. run(highlight(), function (comp, se) {
  9652. emit(comp, ShowTooltipEvent);
  9653. }),
  9654. run(dehighlight(), function (comp) {
  9655. emit(comp, HideTooltipEvent);
  9656. })
  9657. ]
  9658. ]));
  9659. };
  9660. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  9661. __proto__: null,
  9662. events: events$8
  9663. });
  9664. var Tooltipping = create$1({
  9665. fields: TooltippingSchema,
  9666. name: 'tooltipping',
  9667. active: ActiveTooltipping,
  9668. state: TooltippingState,
  9669. apis: TooltippingApis
  9670. });
  9671. var global$7 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  9672. var navClass = 'tox-menu-nav__js';
  9673. var selectableClass = 'tox-collection__item';
  9674. var colorClass = 'tox-swatch';
  9675. var presetClasses = {
  9676. normal: navClass,
  9677. color: colorClass
  9678. };
  9679. var tickedClass = 'tox-collection__item--enabled';
  9680. var groupHeadingClass = 'tox-collection__group-heading';
  9681. var iconClass = 'tox-collection__item-icon';
  9682. var textClass = 'tox-collection__item-label';
  9683. var accessoryClass = 'tox-collection__item-accessory';
  9684. var caretClass = 'tox-collection__item-caret';
  9685. var checkmarkClass = 'tox-collection__item-checkmark';
  9686. var activeClass = 'tox-collection__item--active';
  9687. var iconClassRtl = 'tox-collection__item-icon-rtl';
  9688. var classForPreset = function (presets) {
  9689. return get(presetClasses, presets).getOr(navClass);
  9690. };
  9691. var global$8 = tinymce.util.Tools.resolve('tinymce.Env');
  9692. var convertText = function (source) {
  9693. var mac = {
  9694. alt: '&#x2325;',
  9695. ctrl: '&#x2303;',
  9696. shift: '&#x21E7;',
  9697. meta: '&#x2318;',
  9698. access: '&#x2303;&#x2325;'
  9699. };
  9700. var other = {
  9701. meta: 'Ctrl',
  9702. access: 'Shift+Alt'
  9703. };
  9704. var replace = global$8.mac ? mac : other;
  9705. var shortcut = source.split('+');
  9706. var updated = map(shortcut, function (segment) {
  9707. var search = segment.toLowerCase().trim();
  9708. return has(replace, search) ? replace[search] : segment;
  9709. });
  9710. return global$8.mac ? updated.join('') : updated.join('+');
  9711. };
  9712. var ConvertShortcut = { convertText: convertText };
  9713. var renderIcon = function (iconHtml) {
  9714. return {
  9715. dom: {
  9716. tag: 'div',
  9717. classes: [iconClass],
  9718. innerHtml: iconHtml
  9719. }
  9720. };
  9721. };
  9722. var renderText = function (text$1) {
  9723. return {
  9724. dom: {
  9725. tag: 'div',
  9726. classes: [textClass]
  9727. },
  9728. components: [text(global$7.translate(text$1))]
  9729. };
  9730. };
  9731. var renderHtml = function (html) {
  9732. return {
  9733. dom: {
  9734. tag: 'div',
  9735. classes: [textClass],
  9736. innerHtml: html
  9737. }
  9738. };
  9739. };
  9740. var renderStyledText = function (style, text$1) {
  9741. return {
  9742. dom: {
  9743. tag: 'div',
  9744. classes: [textClass]
  9745. },
  9746. components: [{
  9747. dom: {
  9748. tag: style.tag,
  9749. styles: style.styles
  9750. },
  9751. components: [text(global$7.translate(text$1))]
  9752. }]
  9753. };
  9754. };
  9755. var renderShortcut = function (shortcut) {
  9756. return {
  9757. dom: {
  9758. tag: 'div',
  9759. classes: [accessoryClass],
  9760. innerHtml: ConvertShortcut.convertText(shortcut)
  9761. }
  9762. };
  9763. };
  9764. var renderCheckmark = function (icons) {
  9765. return {
  9766. dom: {
  9767. tag: 'div',
  9768. classes: [
  9769. iconClass,
  9770. checkmarkClass
  9771. ],
  9772. innerHtml: get$d('checkmark', icons)
  9773. }
  9774. };
  9775. };
  9776. var renderSubmenuCaret = function (icons) {
  9777. return {
  9778. dom: {
  9779. tag: 'div',
  9780. classes: [caretClass],
  9781. innerHtml: get$d('chevron-right', icons)
  9782. }
  9783. };
  9784. };
  9785. var renderDownwardsCaret = function (icons) {
  9786. return {
  9787. dom: {
  9788. tag: 'div',
  9789. classes: [caretClass],
  9790. innerHtml: get$d('chevron-down', icons)
  9791. }
  9792. };
  9793. };
  9794. var renderColorStructure = function (itemText, itemValue, iconSvg, providerBackstage) {
  9795. var colorPickerCommand = 'custom';
  9796. var removeColorCommand = 'remove';
  9797. var getDom = function () {
  9798. var common = colorClass;
  9799. var icon = iconSvg.getOr('');
  9800. var attributes = itemText.map(function (text) {
  9801. return { title: providerBackstage.translate(text) };
  9802. }).getOr({});
  9803. var baseDom = {
  9804. tag: 'div',
  9805. attributes: attributes,
  9806. classes: [common]
  9807. };
  9808. if (itemValue === colorPickerCommand) {
  9809. return __assign(__assign({}, baseDom), {
  9810. tag: 'button',
  9811. classes: __spreadArrays(baseDom.classes, ['tox-swatches__picker-btn']),
  9812. innerHtml: icon
  9813. });
  9814. } else if (itemValue === removeColorCommand) {
  9815. return __assign(__assign({}, baseDom), {
  9816. classes: __spreadArrays(baseDom.classes, ['tox-swatch--remove']),
  9817. innerHtml: icon
  9818. });
  9819. } else {
  9820. return __assign(__assign({}, baseDom), {
  9821. attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }),
  9822. styles: { 'background-color': itemValue }
  9823. });
  9824. }
  9825. };
  9826. return {
  9827. dom: getDom(),
  9828. optComponents: []
  9829. };
  9830. };
  9831. var renderNormalItemStructure = function (info, icon, renderIcons, textRender, rtlClass) {
  9832. var leftIcon = renderIcons ? info.checkMark.orThunk(function () {
  9833. return icon.or(Option.some('')).map(renderIcon);
  9834. }) : Option.none();
  9835. var domTitle = info.ariaLabel.map(function (label) {
  9836. return { attributes: { title: global$7.translate(label) } };
  9837. }).getOr({});
  9838. var dom = __assign({
  9839. tag: 'div',
  9840. classes: [
  9841. navClass,
  9842. selectableClass
  9843. ].concat(rtlClass ? [iconClassRtl] : [])
  9844. }, domTitle);
  9845. var content = info.htmlContent.fold(function () {
  9846. return info.textContent.map(textRender);
  9847. }, function (html) {
  9848. return Option.some(renderHtml(html));
  9849. });
  9850. var menuItem = {
  9851. dom: dom,
  9852. optComponents: [
  9853. leftIcon,
  9854. content,
  9855. info.shortcutContent.map(renderShortcut),
  9856. info.caret
  9857. ]
  9858. };
  9859. return menuItem;
  9860. };
  9861. var rtlIcon = [
  9862. 'list-num-default',
  9863. 'list-num-lower-alpha',
  9864. 'list-num-lower-greek',
  9865. 'list-num-lower-roman',
  9866. 'list-num-upper-alpha',
  9867. 'list-num-upper-roman'
  9868. ];
  9869. var rtlTransform = [
  9870. 'list-bull-circle',
  9871. 'list-bull-default',
  9872. 'list-bull-square'
  9873. ];
  9874. var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  9875. if (fallbackIcon === void 0) {
  9876. fallbackIcon = Option.none();
  9877. }
  9878. var getIconName = function (iconName) {
  9879. return iconName.map(function (name) {
  9880. return global$7.isRtl() && contains(rtlIcon, name) ? name + '-rtl' : name;
  9881. });
  9882. };
  9883. var needRtlClass = global$7.isRtl() && info.iconContent.exists(function (name) {
  9884. return contains(rtlTransform, name);
  9885. });
  9886. var icon = getIconName(info.iconContent).map(function (iconName) {
  9887. return getOr(iconName, providersBackstage.icons, fallbackIcon);
  9888. });
  9889. var textRender = Option.from(info.meta).fold(function () {
  9890. return renderText;
  9891. }, function (meta) {
  9892. return has(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  9893. });
  9894. if (info.presets === 'color') {
  9895. return renderColorStructure(info.ariaLabel, info.value, icon, providersBackstage);
  9896. } else {
  9897. return renderNormalItemStructure(info, icon, renderIcons, textRender, needRtlClass);
  9898. }
  9899. };
  9900. var nativeDisabled = [
  9901. 'input',
  9902. 'button',
  9903. 'textarea',
  9904. 'select'
  9905. ];
  9906. var onLoad$5 = function (component, disableConfig, disableState) {
  9907. if (disableConfig.disabled) {
  9908. disable(component, disableConfig);
  9909. }
  9910. };
  9911. var hasNative = function (component, config) {
  9912. return config.useNative === true && contains(nativeDisabled, name(component.element()));
  9913. };
  9914. var nativeIsDisabled = function (component) {
  9915. return has$1(component.element(), 'disabled');
  9916. };
  9917. var nativeDisable = function (component) {
  9918. set$1(component.element(), 'disabled', 'disabled');
  9919. };
  9920. var nativeEnable = function (component) {
  9921. remove$1(component.element(), 'disabled');
  9922. };
  9923. var ariaIsDisabled = function (component) {
  9924. return get$2(component.element(), 'aria-disabled') === 'true';
  9925. };
  9926. var ariaDisable = function (component) {
  9927. set$1(component.element(), 'aria-disabled', 'true');
  9928. };
  9929. var ariaEnable = function (component) {
  9930. set$1(component.element(), 'aria-disabled', 'false');
  9931. };
  9932. var disable = function (component, disableConfig, disableState) {
  9933. disableConfig.disableClass.each(function (disableClass) {
  9934. add$2(component.element(), disableClass);
  9935. });
  9936. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  9937. f(component);
  9938. disableConfig.onDisabled(component);
  9939. };
  9940. var enable = function (component, disableConfig, disableState) {
  9941. disableConfig.disableClass.each(function (disableClass) {
  9942. remove$4(component.element(), disableClass);
  9943. });
  9944. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  9945. f(component);
  9946. disableConfig.onEnabled(component);
  9947. };
  9948. var isDisabled = function (component, disableConfig) {
  9949. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  9950. };
  9951. var set$7 = function (component, disableConfig, disableState, disabled) {
  9952. var f = disabled ? disable : enable;
  9953. f(component, disableConfig, disableState);
  9954. };
  9955. var DisableApis = /*#__PURE__*/Object.freeze({
  9956. __proto__: null,
  9957. enable: enable,
  9958. disable: disable,
  9959. isDisabled: isDisabled,
  9960. onLoad: onLoad$5,
  9961. set: set$7
  9962. });
  9963. var exhibit$3 = function (base, disableConfig) {
  9964. return nu$6({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  9965. };
  9966. var events$9 = function (disableConfig, disableState) {
  9967. return derive([
  9968. abort(execute(), function (component, simulatedEvent) {
  9969. return isDisabled(component, disableConfig);
  9970. }),
  9971. loadEvent(disableConfig, disableState, onLoad$5)
  9972. ]);
  9973. };
  9974. var ActiveDisable = /*#__PURE__*/Object.freeze({
  9975. __proto__: null,
  9976. exhibit: exhibit$3,
  9977. events: events$9
  9978. });
  9979. var DisableSchema = [
  9980. defaulted$1('disabled', false),
  9981. defaulted$1('useNative', true),
  9982. option('disableClass'),
  9983. onHandler('onDisabled'),
  9984. onHandler('onEnabled')
  9985. ];
  9986. var Disabling = create$1({
  9987. fields: DisableSchema,
  9988. name: 'disabling',
  9989. active: ActiveDisable,
  9990. apis: DisableApis
  9991. });
  9992. var item = function (disabled) {
  9993. return Disabling.config({
  9994. disabled: disabled,
  9995. disableClass: 'tox-collection__item--state-disabled'
  9996. });
  9997. };
  9998. var button = function (disabled) {
  9999. return Disabling.config({ disabled: disabled });
  10000. };
  10001. var splitButton = function (disabled) {
  10002. return Disabling.config({
  10003. disabled: disabled,
  10004. disableClass: 'tox-tbtn--disabled'
  10005. });
  10006. };
  10007. var toolbarButton = function (disabled) {
  10008. return Disabling.config({
  10009. disabled: disabled,
  10010. disableClass: 'tox-tbtn--disabled',
  10011. useNative: false
  10012. });
  10013. };
  10014. var DisablingConfigs = {
  10015. item: item,
  10016. button: button,
  10017. splitButton: splitButton,
  10018. toolbarButton: toolbarButton
  10019. };
  10020. var runWithApi = function (info, comp) {
  10021. var api = info.getApi(comp);
  10022. return function (f) {
  10023. f(api);
  10024. };
  10025. };
  10026. var onControlAttached = function (info, editorOffCell) {
  10027. return runOnAttached(function (comp) {
  10028. var run = runWithApi(info, comp);
  10029. run(function (api) {
  10030. var onDestroy = info.onSetup(api);
  10031. if (onDestroy !== null && onDestroy !== undefined) {
  10032. editorOffCell.set(onDestroy);
  10033. }
  10034. });
  10035. });
  10036. };
  10037. var onControlDetached = function (getApi, editorOffCell) {
  10038. return runOnDetached(function (comp) {
  10039. return runWithApi(getApi, comp)(editorOffCell.get());
  10040. });
  10041. };
  10042. var ItemResponse;
  10043. (function (ItemResponse) {
  10044. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  10045. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  10046. }(ItemResponse || (ItemResponse = {})));
  10047. var ItemResponse$1 = ItemResponse;
  10048. var onMenuItemExecute = function (info, itemResponse) {
  10049. return runOnExecute(function (comp, simulatedEvent) {
  10050. runWithApi(info, comp)(info.onAction);
  10051. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  10052. emit(comp, sandboxClose());
  10053. simulatedEvent.stop();
  10054. }
  10055. });
  10056. };
  10057. var menuItemEventOrder = {
  10058. 'alloy.execute': [
  10059. 'disabling',
  10060. 'alloy.base.behaviour',
  10061. 'toggling',
  10062. 'item-events'
  10063. ]
  10064. };
  10065. var componentRenderPipeline = function (xs) {
  10066. return bind(xs, function (o) {
  10067. return o.toArray();
  10068. });
  10069. };
  10070. var renderCommonItem = function (spec, structure, itemResponse) {
  10071. var editorOffCell = Cell(noop);
  10072. return {
  10073. type: 'item',
  10074. dom: structure.dom,
  10075. components: componentRenderPipeline(structure.optComponents),
  10076. data: spec.data,
  10077. eventOrder: menuItemEventOrder,
  10078. hasSubmenu: spec.triggersSubmenu,
  10079. itemBehaviours: derive$1([
  10080. config('item-events', [
  10081. onMenuItemExecute(spec, itemResponse),
  10082. onControlAttached(spec, editorOffCell),
  10083. onControlDetached(spec, editorOffCell)
  10084. ]),
  10085. DisablingConfigs.item(spec.disabled),
  10086. Replacing.config({})
  10087. ].concat(spec.itemBehaviours))
  10088. };
  10089. };
  10090. var buildData = function (source) {
  10091. return {
  10092. value: source.value,
  10093. meta: __assign({ text: source.text.getOr('') }, source.meta)
  10094. };
  10095. };
  10096. var tooltipBehaviour = function (meta, sharedBackstage) {
  10097. return get(meta, 'tooltipWorker').map(function (tooltipWorker) {
  10098. return [Tooltipping.config({
  10099. lazySink: sharedBackstage.getSink,
  10100. tooltipDom: {
  10101. tag: 'div',
  10102. classes: ['tox-tooltip-worker-container']
  10103. },
  10104. tooltipComponents: [],
  10105. anchor: function (comp) {
  10106. return {
  10107. anchor: 'submenu',
  10108. item: comp,
  10109. overrides: { maxHeightFunction: expandable }
  10110. };
  10111. },
  10112. mode: 'follow-highlight',
  10113. onShow: function (component, _tooltip) {
  10114. tooltipWorker(function (elm) {
  10115. Tooltipping.setComponents(component, [external({ element: Element.fromDom(elm) })]);
  10116. });
  10117. }
  10118. })];
  10119. }).getOr([]);
  10120. };
  10121. var escapeRegExp = function (text) {
  10122. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  10123. };
  10124. var encodeText = function (text) {
  10125. return global$3.DOM.encode(text);
  10126. };
  10127. var replaceText = function (text, matchText) {
  10128. var translated = global$7.translate(text);
  10129. var encoded = encodeText(translated);
  10130. if (matchText.length > 0) {
  10131. var escapedMatchRegex = new RegExp(escapeRegExp(matchText), 'gi');
  10132. return encoded.replace(escapedMatchRegex, function (match) {
  10133. return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  10134. });
  10135. } else {
  10136. return encoded;
  10137. }
  10138. };
  10139. var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  10140. if (renderIcons === void 0) {
  10141. renderIcons = true;
  10142. }
  10143. var structure = renderItemStructure({
  10144. presets: presets,
  10145. textContent: Option.none(),
  10146. htmlContent: useText ? spec.text.map(function (text) {
  10147. return replaceText(text, matchText);
  10148. }) : Option.none(),
  10149. ariaLabel: spec.text,
  10150. iconContent: spec.icon,
  10151. shortcutContent: Option.none(),
  10152. checkMark: Option.none(),
  10153. caret: Option.none(),
  10154. value: spec.value
  10155. }, sharedBackstage.providers, renderIcons, spec.icon);
  10156. return renderCommonItem({
  10157. data: buildData(spec),
  10158. disabled: spec.disabled,
  10159. getApi: function () {
  10160. return {};
  10161. },
  10162. onAction: function (_api) {
  10163. return onItemValueHandler(spec.value, spec.meta);
  10164. },
  10165. onSetup: function () {
  10166. return function () {
  10167. };
  10168. },
  10169. triggersSubmenu: false,
  10170. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  10171. }, structure, itemResponse);
  10172. };
  10173. var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage) {
  10174. var getApi = function (component) {
  10175. return {
  10176. setActive: function (state) {
  10177. Toggling.set(component, state);
  10178. },
  10179. isActive: function () {
  10180. return Toggling.isOn(component);
  10181. },
  10182. isDisabled: function () {
  10183. return Disabling.isDisabled(component);
  10184. },
  10185. setDisabled: function (state) {
  10186. return Disabling.set(component, state);
  10187. }
  10188. };
  10189. };
  10190. var structure = renderItemStructure({
  10191. presets: presets,
  10192. textContent: useText ? spec.text : Option.none(),
  10193. htmlContent: Option.none(),
  10194. ariaLabel: spec.text,
  10195. iconContent: spec.icon,
  10196. shortcutContent: useText ? spec.shortcut : Option.none(),
  10197. checkMark: useText ? Option.some(renderCheckmark(providersBackstage.icons)) : Option.none(),
  10198. caret: Option.none(),
  10199. value: spec.value
  10200. }, providersBackstage, true);
  10201. return deepMerge(renderCommonItem({
  10202. data: buildData(spec),
  10203. disabled: spec.disabled,
  10204. getApi: getApi,
  10205. onAction: function (_api) {
  10206. return onItemValueHandler(spec.value);
  10207. },
  10208. onSetup: function (api) {
  10209. api.setActive(isSelected);
  10210. return function () {
  10211. };
  10212. },
  10213. triggersSubmenu: false,
  10214. itemBehaviours: []
  10215. }, structure, itemResponse), {
  10216. toggling: {
  10217. toggleClass: tickedClass,
  10218. toggleOnExecute: false,
  10219. selected: spec.active
  10220. }
  10221. });
  10222. };
  10223. var parts$2 = constant(generate$4(owner$2(), parts()));
  10224. var cellOverEvent = generate$1('cell-over');
  10225. var cellExecuteEvent = generate$1('cell-execute');
  10226. var makeCell = function (row, col, labelId) {
  10227. var _a;
  10228. var emitCellOver = function (c) {
  10229. return emitWith(c, cellOverEvent, {
  10230. row: row,
  10231. col: col
  10232. });
  10233. };
  10234. var emitExecute = function (c) {
  10235. return emitWith(c, cellExecuteEvent, {
  10236. row: row,
  10237. col: col
  10238. });
  10239. };
  10240. var onClick = function (c, se) {
  10241. se.stop();
  10242. emitExecute(c);
  10243. };
  10244. return build$1({
  10245. dom: {
  10246. tag: 'div',
  10247. attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  10248. },
  10249. behaviours: derive$1([
  10250. config('insert-table-picker-cell', [
  10251. run(mouseover(), Focusing.focus),
  10252. run(execute(), emitExecute),
  10253. run(click(), onClick),
  10254. run(tap(), onClick)
  10255. ]),
  10256. Toggling.config({
  10257. toggleClass: 'tox-insert-table-picker__selected',
  10258. toggleOnExecute: false
  10259. }),
  10260. Focusing.config({ onFocus: emitCellOver })
  10261. ])
  10262. });
  10263. };
  10264. var makeCells = function (labelId, numRows, numCols) {
  10265. var cells = [];
  10266. for (var i = 0; i < numRows; i++) {
  10267. var row = [];
  10268. for (var j = 0; j < numCols; j++) {
  10269. row.push(makeCell(i, j, labelId));
  10270. }
  10271. cells.push(row);
  10272. }
  10273. return cells;
  10274. };
  10275. var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  10276. for (var i = 0; i < numRows; i++) {
  10277. for (var j = 0; j < numColumns; j++) {
  10278. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  10279. }
  10280. }
  10281. };
  10282. var makeComponents = function (cells) {
  10283. return bind(cells, function (cellRow) {
  10284. return map(cellRow, premade$1);
  10285. });
  10286. };
  10287. var makeLabelText = function (row, col) {
  10288. return text(col + 1 + 'x' + (row + 1));
  10289. };
  10290. function renderInsertTableMenuItem(spec) {
  10291. var numRows = 10;
  10292. var numColumns = 10;
  10293. var sizeLabelId = generate$1('size-label');
  10294. var cells = makeCells(sizeLabelId, numRows, numColumns);
  10295. var memLabel = record({
  10296. dom: {
  10297. tag: 'span',
  10298. classes: ['tox-insert-table-picker__label'],
  10299. attributes: { id: sizeLabelId }
  10300. },
  10301. components: [text('0x0')],
  10302. behaviours: derive$1([Replacing.config({})])
  10303. });
  10304. return {
  10305. type: 'widget',
  10306. data: { value: generate$1('widget-id') },
  10307. dom: {
  10308. tag: 'div',
  10309. classes: ['tox-fancymenuitem']
  10310. },
  10311. autofocus: true,
  10312. components: [parts$2().widget({
  10313. dom: {
  10314. tag: 'div',
  10315. classes: ['tox-insert-table-picker']
  10316. },
  10317. components: makeComponents(cells).concat(memLabel.asSpec()),
  10318. behaviours: derive$1([
  10319. config('insert-table-picker', [
  10320. runWithTarget(cellOverEvent, function (c, t, e) {
  10321. var row = e.event().row();
  10322. var col = e.event().col();
  10323. selectCells(cells, row, col, numRows, numColumns);
  10324. Replacing.set(memLabel.get(c), [makeLabelText(row, col)]);
  10325. }),
  10326. runWithTarget(cellExecuteEvent, function (c, _, e) {
  10327. spec.onAction({
  10328. numRows: e.event().row() + 1,
  10329. numColumns: e.event().col() + 1
  10330. });
  10331. emit(c, sandboxClose());
  10332. })
  10333. ]),
  10334. Keying.config({
  10335. initSize: {
  10336. numRows: numRows,
  10337. numColumns: numColumns
  10338. },
  10339. mode: 'flatgrid',
  10340. selector: '[role="button"]'
  10341. })
  10342. ])
  10343. })]
  10344. };
  10345. }
  10346. var hexColour = function (hexString) {
  10347. return { value: constant(hexString) };
  10348. };
  10349. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  10350. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  10351. var isHexString = function (hex) {
  10352. return shorthandRegex.test(hex) || longformRegex.test(hex);
  10353. };
  10354. var getLongForm = function (hex) {
  10355. var hexString = hex.value().replace(shorthandRegex, function (m, r, g, b) {
  10356. return r + r + g + g + b + b;
  10357. });
  10358. return { value: constant(hexString) };
  10359. };
  10360. var extractValues = function (hex) {
  10361. var longForm = getLongForm(hex);
  10362. var splitForm = longformRegex.exec(longForm.value());
  10363. return splitForm === null ? [
  10364. 'FFFFFF',
  10365. 'FF',
  10366. 'FF',
  10367. 'FF'
  10368. ] : splitForm;
  10369. };
  10370. var toHex = function (component) {
  10371. var hex = component.toString(16);
  10372. return hex.length === 1 ? '0' + hex : hex;
  10373. };
  10374. var fromRgba = function (rgbaColour) {
  10375. var value = toHex(rgbaColour.red()) + toHex(rgbaColour.green()) + toHex(rgbaColour.blue());
  10376. return hexColour(value);
  10377. };
  10378. var min = Math.min;
  10379. var max = Math.max;
  10380. var round = Math.round;
  10381. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  10382. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  10383. var rgbaColour = function (red, green, blue, alpha) {
  10384. return {
  10385. red: constant(red),
  10386. green: constant(green),
  10387. blue: constant(blue),
  10388. alpha: constant(alpha)
  10389. };
  10390. };
  10391. var isRgbaComponent = function (value) {
  10392. var num = parseInt(value, 10);
  10393. return num.toString() === value && num >= 0 && num <= 255;
  10394. };
  10395. var fromHsv = function (hsv) {
  10396. var r;
  10397. var g;
  10398. var b;
  10399. var hue = (hsv.hue() || 0) % 360;
  10400. var saturation = hsv.saturation() / 100;
  10401. var brightness = hsv.value() / 100;
  10402. saturation = max(0, min(saturation, 1));
  10403. brightness = max(0, min(brightness, 1));
  10404. if (saturation === 0) {
  10405. r = g = b = round(255 * brightness);
  10406. return rgbaColour(r, g, b, 1);
  10407. }
  10408. var side = hue / 60;
  10409. var chroma = brightness * saturation;
  10410. var x = chroma * (1 - Math.abs(side % 2 - 1));
  10411. var match = brightness - chroma;
  10412. switch (Math.floor(side)) {
  10413. case 0:
  10414. r = chroma;
  10415. g = x;
  10416. b = 0;
  10417. break;
  10418. case 1:
  10419. r = x;
  10420. g = chroma;
  10421. b = 0;
  10422. break;
  10423. case 2:
  10424. r = 0;
  10425. g = chroma;
  10426. b = x;
  10427. break;
  10428. case 3:
  10429. r = 0;
  10430. g = x;
  10431. b = chroma;
  10432. break;
  10433. case 4:
  10434. r = x;
  10435. g = 0;
  10436. b = chroma;
  10437. break;
  10438. case 5:
  10439. r = chroma;
  10440. g = 0;
  10441. b = x;
  10442. break;
  10443. default:
  10444. r = g = b = 0;
  10445. }
  10446. r = round(255 * (r + match));
  10447. g = round(255 * (g + match));
  10448. b = round(255 * (b + match));
  10449. return rgbaColour(r, g, b, 1);
  10450. };
  10451. var fromHex = function (hexColour) {
  10452. var result = extractValues(hexColour);
  10453. var red = parseInt(result[1], 16);
  10454. var green = parseInt(result[2], 16);
  10455. var blue = parseInt(result[3], 16);
  10456. return rgbaColour(red, green, blue, 1);
  10457. };
  10458. var fromStringValues = function (red, green, blue, alpha) {
  10459. var r = parseInt(red, 10);
  10460. var g = parseInt(green, 10);
  10461. var b = parseInt(blue, 10);
  10462. var a = parseFloat(alpha);
  10463. return rgbaColour(r, g, b, a);
  10464. };
  10465. var fromString = function (rgbaString) {
  10466. if (rgbaString === 'transparent') {
  10467. return Option.some(rgbaColour(0, 0, 0, 0));
  10468. }
  10469. var rgbMatch = rgbRegex.exec(rgbaString);
  10470. if (rgbMatch !== null) {
  10471. return Option.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  10472. }
  10473. var rgbaMatch = rgbaRegex.exec(rgbaString);
  10474. if (rgbaMatch !== null) {
  10475. return Option.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  10476. }
  10477. return Option.none();
  10478. };
  10479. var toString = function (rgba) {
  10480. return 'rgba(' + rgba.red() + ',' + rgba.green() + ',' + rgba.blue() + ',' + rgba.alpha() + ')';
  10481. };
  10482. var redColour = constant(rgbaColour(255, 0, 0, 1));
  10483. var global$9 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  10484. var storageName = 'tinymce-custom-colors';
  10485. function ColorCache (max) {
  10486. if (max === void 0) {
  10487. max = 10;
  10488. }
  10489. var storageString = global$9.getItem(storageName);
  10490. var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  10491. var prune = function (list) {
  10492. var diff = max - list.length;
  10493. return diff < 0 ? list.slice(0, max) : list;
  10494. };
  10495. var cache = prune(localstorage);
  10496. var add = function (key) {
  10497. indexOf(cache, key).each(remove);
  10498. cache.unshift(key);
  10499. if (cache.length > max) {
  10500. cache.pop();
  10501. }
  10502. global$9.setItem(storageName, JSON.stringify(cache));
  10503. };
  10504. var remove = function (idx) {
  10505. cache.splice(idx, 1);
  10506. };
  10507. var state = function () {
  10508. return cache.slice(0);
  10509. };
  10510. return {
  10511. add: add,
  10512. state: state
  10513. };
  10514. }
  10515. var choiceItem = 'choiceitem';
  10516. var defaultColors = [
  10517. {
  10518. type: choiceItem,
  10519. text: 'Light Green',
  10520. value: '#BFEDD2'
  10521. },
  10522. {
  10523. type: choiceItem,
  10524. text: 'Light Yellow',
  10525. value: '#FBEEB8'
  10526. },
  10527. {
  10528. type: choiceItem,
  10529. text: 'Light Red',
  10530. value: '#F8CAC6'
  10531. },
  10532. {
  10533. type: choiceItem,
  10534. text: 'Light Purple',
  10535. value: '#ECCAFA'
  10536. },
  10537. {
  10538. type: choiceItem,
  10539. text: 'Light Blue',
  10540. value: '#C2E0F4'
  10541. },
  10542. {
  10543. type: choiceItem,
  10544. text: 'Green',
  10545. value: '#2DC26B'
  10546. },
  10547. {
  10548. type: choiceItem,
  10549. text: 'Yellow',
  10550. value: '#F1C40F'
  10551. },
  10552. {
  10553. type: choiceItem,
  10554. text: 'Red',
  10555. value: '#E03E2D'
  10556. },
  10557. {
  10558. type: choiceItem,
  10559. text: 'Purple',
  10560. value: '#B96AD9'
  10561. },
  10562. {
  10563. type: choiceItem,
  10564. text: 'Blue',
  10565. value: '#3598DB'
  10566. },
  10567. {
  10568. type: choiceItem,
  10569. text: 'Dark Turquoise',
  10570. value: '#169179'
  10571. },
  10572. {
  10573. type: choiceItem,
  10574. text: 'Orange',
  10575. value: '#E67E23'
  10576. },
  10577. {
  10578. type: choiceItem,
  10579. text: 'Dark Red',
  10580. value: '#BA372A'
  10581. },
  10582. {
  10583. type: choiceItem,
  10584. text: 'Dark Purple',
  10585. value: '#843FA1'
  10586. },
  10587. {
  10588. type: choiceItem,
  10589. text: 'Dark Blue',
  10590. value: '#236FA1'
  10591. },
  10592. {
  10593. type: choiceItem,
  10594. text: 'Light Gray',
  10595. value: '#ECF0F1'
  10596. },
  10597. {
  10598. type: choiceItem,
  10599. text: 'Medium Gray',
  10600. value: '#CED4D9'
  10601. },
  10602. {
  10603. type: choiceItem,
  10604. text: 'Gray',
  10605. value: '#95A5A6'
  10606. },
  10607. {
  10608. type: choiceItem,
  10609. text: 'Dark Gray',
  10610. value: '#7E8C8D'
  10611. },
  10612. {
  10613. type: choiceItem,
  10614. text: 'Navy Blue',
  10615. value: '#34495E'
  10616. },
  10617. {
  10618. type: choiceItem,
  10619. text: 'Black',
  10620. value: '#000000'
  10621. },
  10622. {
  10623. type: choiceItem,
  10624. text: 'White',
  10625. value: '#ffffff'
  10626. }
  10627. ];
  10628. var colorCache = ColorCache(10);
  10629. var mapColors = function (colorMap) {
  10630. var colors = [];
  10631. var canvas = domGlobals.document.createElement('canvas');
  10632. canvas.height = 1;
  10633. canvas.width = 1;
  10634. var ctx = canvas.getContext('2d');
  10635. var byteAsHex = function (colorByte, alphaByte) {
  10636. var bg = 255;
  10637. var alpha = alphaByte / 255;
  10638. var colorByteWithWhiteBg = Math.round(colorByte * alpha + bg * (1 - alpha));
  10639. return ('0' + colorByteWithWhiteBg.toString(16)).slice(-2).toUpperCase();
  10640. };
  10641. var asHexColor = function (color) {
  10642. if (/^[0-9A-Fa-f]{6}$/.test(color)) {
  10643. return '#' + color.toUpperCase();
  10644. }
  10645. ctx.clearRect(0, 0, canvas.width, canvas.height);
  10646. ctx.fillStyle = '#FFFFFF';
  10647. ctx.fillStyle = color;
  10648. ctx.fillRect(0, 0, 1, 1);
  10649. var rgba = ctx.getImageData(0, 0, 1, 1).data;
  10650. var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3];
  10651. return '#' + byteAsHex(r, a) + byteAsHex(g, a) + byteAsHex(b, a);
  10652. };
  10653. for (var i = 0; i < colorMap.length; i += 2) {
  10654. colors.push({
  10655. text: colorMap[i + 1],
  10656. value: asHexColor(colorMap[i]),
  10657. type: 'choiceitem'
  10658. });
  10659. }
  10660. return colors;
  10661. };
  10662. var getColorCols = function (editor, defaultCols) {
  10663. return editor.getParam('color_cols', defaultCols, 'number');
  10664. };
  10665. var hasCustomColors = function (editor) {
  10666. return editor.getParam('custom_colors') !== false;
  10667. };
  10668. var getColorMap = function (editor) {
  10669. return editor.getParam('color_map');
  10670. };
  10671. var getColors = function (editor) {
  10672. var unmapped = getColorMap(editor);
  10673. return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  10674. };
  10675. var getCurrentColors = function () {
  10676. return map(colorCache.state(), function (color) {
  10677. return {
  10678. type: choiceItem,
  10679. text: color,
  10680. value: color
  10681. };
  10682. });
  10683. };
  10684. var addColor = function (color) {
  10685. colorCache.add(color);
  10686. };
  10687. var Settings = {
  10688. mapColors: mapColors,
  10689. getColorCols: getColorCols,
  10690. hasCustomColors: hasCustomColors,
  10691. getColorMap: getColorMap,
  10692. getColors: getColors,
  10693. getCurrentColors: getCurrentColors,
  10694. addColor: addColor
  10695. };
  10696. var fireSkinLoaded = function (editor) {
  10697. return editor.fire('SkinLoaded');
  10698. };
  10699. var fireSkinLoadError = function (editor, error) {
  10700. return editor.fire('SkinLoadError', error);
  10701. };
  10702. var fireResizeEditor = function (editor) {
  10703. return editor.fire('ResizeEditor');
  10704. };
  10705. var fireBeforeRenderUI = function (editor) {
  10706. return editor.fire('BeforeRenderUI');
  10707. };
  10708. var fireResizeContent = function (editor, e) {
  10709. return editor.fire('ResizeContent', e);
  10710. };
  10711. var fireScrollContent = function (editor, e) {
  10712. return editor.fire('ScrollContent', e);
  10713. };
  10714. var fireTextColorChange = function (editor, data) {
  10715. return editor.fire('TextColorChange', data);
  10716. };
  10717. var Events = {
  10718. fireSkinLoaded: fireSkinLoaded,
  10719. fireSkinLoadError: fireSkinLoadError,
  10720. fireResizeEditor: fireResizeEditor,
  10721. fireScrollContent: fireScrollContent,
  10722. fireBeforeRenderUI: fireBeforeRenderUI,
  10723. fireResizeContent: fireResizeContent,
  10724. fireTextColorChange: fireTextColorChange
  10725. };
  10726. var getCurrentColor = function (editor, format) {
  10727. var color;
  10728. editor.dom.getParents(editor.selection.getStart(), function (elm) {
  10729. var value;
  10730. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  10731. color = color ? color : value;
  10732. }
  10733. });
  10734. return color;
  10735. };
  10736. var applyFormat = function (editor, format, value) {
  10737. editor.undoManager.transact(function () {
  10738. editor.focus();
  10739. editor.formatter.apply(format, { value: value });
  10740. editor.nodeChanged();
  10741. });
  10742. };
  10743. var removeFormat = function (editor, format) {
  10744. editor.undoManager.transact(function () {
  10745. editor.focus();
  10746. editor.formatter.remove(format, { value: null }, null, true);
  10747. editor.nodeChanged();
  10748. });
  10749. };
  10750. var registerCommands = function (editor) {
  10751. editor.addCommand('mceApplyTextcolor', function (format, value) {
  10752. applyFormat(editor, format, value);
  10753. });
  10754. editor.addCommand('mceRemoveTextcolor', function (format) {
  10755. removeFormat(editor, format);
  10756. });
  10757. };
  10758. var calcCols = function (colors) {
  10759. return Math.max(5, Math.ceil(Math.sqrt(colors)));
  10760. };
  10761. var getColorCols$1 = function (editor) {
  10762. var colors = Settings.getColors(editor);
  10763. var defaultCols = calcCols(colors.length);
  10764. return Settings.getColorCols(editor, defaultCols);
  10765. };
  10766. var getAdditionalColors = function (hasCustom) {
  10767. var type = 'choiceitem';
  10768. var remove = {
  10769. type: type,
  10770. text: 'Remove color',
  10771. icon: 'color-swatch-remove-color',
  10772. value: 'remove'
  10773. };
  10774. var custom = {
  10775. type: type,
  10776. text: 'Custom color',
  10777. icon: 'color-picker',
  10778. value: 'custom'
  10779. };
  10780. return hasCustom ? [
  10781. remove,
  10782. custom
  10783. ] : [remove];
  10784. };
  10785. var applyColor = function (editor, format, value, onChoice) {
  10786. if (value === 'custom') {
  10787. var dialog = colorPickerDialog(editor);
  10788. dialog(function (colorOpt) {
  10789. colorOpt.each(function (color) {
  10790. Settings.addColor(color);
  10791. editor.execCommand('mceApplyTextcolor', format, color);
  10792. onChoice(color);
  10793. });
  10794. }, '#000000');
  10795. } else if (value === 'remove') {
  10796. onChoice('');
  10797. editor.execCommand('mceRemoveTextcolor', format);
  10798. } else {
  10799. onChoice(value);
  10800. editor.execCommand('mceApplyTextcolor', format, value);
  10801. }
  10802. };
  10803. var getMenuColors = function (colors, hasCustom) {
  10804. return colors.concat(Settings.getCurrentColors().concat(getAdditionalColors(hasCustom)));
  10805. };
  10806. var getFetch = function (colors, hasCustom) {
  10807. return function (callback) {
  10808. callback(getMenuColors(colors, hasCustom));
  10809. };
  10810. };
  10811. var setIconColor = function (splitButtonApi, name, newColor) {
  10812. var setIconFillAndStroke = function (pathId, color) {
  10813. splitButtonApi.setIconFill(pathId, color);
  10814. splitButtonApi.setIconStroke(pathId, color);
  10815. };
  10816. var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  10817. setIconFillAndStroke(id, newColor);
  10818. };
  10819. var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  10820. editor.ui.registry.addSplitButton(name, {
  10821. tooltip: tooltip,
  10822. presets: 'color',
  10823. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  10824. select: function (value) {
  10825. var optCurrentRgb = Option.from(getCurrentColor(editor, format));
  10826. return optCurrentRgb.bind(function (currentRgb) {
  10827. return fromString(currentRgb).map(function (rgba) {
  10828. var currentHex = fromRgba(rgba).value();
  10829. return contains$1(value.toLowerCase(), currentHex);
  10830. });
  10831. }).getOr(false);
  10832. },
  10833. columns: getColorCols$1(editor),
  10834. fetch: getFetch(Settings.getColors(editor), Settings.hasCustomColors(editor)),
  10835. onAction: function (splitButtonApi) {
  10836. if (lastColor.get() !== null) {
  10837. applyColor(editor, format, lastColor.get(), function () {
  10838. });
  10839. }
  10840. },
  10841. onItemAction: function (splitButtonApi, value) {
  10842. applyColor(editor, format, value, function (newColor) {
  10843. lastColor.set(newColor);
  10844. Events.fireTextColorChange(editor, {
  10845. name: name,
  10846. color: newColor
  10847. });
  10848. });
  10849. },
  10850. onSetup: function (splitButtonApi) {
  10851. if (lastColor.get() !== null) {
  10852. setIconColor(splitButtonApi, name, lastColor.get());
  10853. }
  10854. var handler = function (e) {
  10855. if (e.name === name) {
  10856. setIconColor(splitButtonApi, e.name, e.color);
  10857. }
  10858. };
  10859. editor.on('TextColorChange', handler);
  10860. return function () {
  10861. editor.off('TextColorChange', handler);
  10862. };
  10863. }
  10864. });
  10865. };
  10866. var registerTextColorMenuItem = function (editor, name, format, text) {
  10867. editor.ui.registry.addNestedMenuItem(name, {
  10868. text: text,
  10869. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  10870. getSubmenuItems: function () {
  10871. return [{
  10872. type: 'fancymenuitem',
  10873. fancytype: 'colorswatch',
  10874. onAction: function (data) {
  10875. applyColor(editor, format, data.value, noop);
  10876. }
  10877. }];
  10878. }
  10879. });
  10880. };
  10881. var colorPickerDialog = function (editor) {
  10882. return function (callback, value) {
  10883. var getOnSubmit = function (callback) {
  10884. return function (api) {
  10885. var data = api.getData();
  10886. callback(Option.from(data.colorpicker));
  10887. api.close();
  10888. };
  10889. };
  10890. var onAction = function (api, details) {
  10891. if (details.name === 'hex-valid') {
  10892. if (details.value) {
  10893. api.enable('ok');
  10894. } else {
  10895. api.disable('ok');
  10896. }
  10897. }
  10898. };
  10899. var initialData = { colorpicker: value };
  10900. var submit = getOnSubmit(callback);
  10901. editor.windowManager.open({
  10902. title: 'Color Picker',
  10903. size: 'normal',
  10904. body: {
  10905. type: 'panel',
  10906. items: [{
  10907. type: 'colorpicker',
  10908. name: 'colorpicker',
  10909. label: 'Color'
  10910. }]
  10911. },
  10912. buttons: [
  10913. {
  10914. type: 'cancel',
  10915. name: 'cancel',
  10916. text: 'Cancel'
  10917. },
  10918. {
  10919. type: 'submit',
  10920. name: 'save',
  10921. text: 'Save',
  10922. primary: true
  10923. }
  10924. ],
  10925. initialData: initialData,
  10926. onAction: onAction,
  10927. onSubmit: submit,
  10928. onClose: function () {
  10929. },
  10930. onCancel: function () {
  10931. callback(Option.none());
  10932. }
  10933. });
  10934. };
  10935. };
  10936. var register$1 = function (editor) {
  10937. registerCommands(editor);
  10938. var lastForeColor = Cell(null);
  10939. var lastBackColor = Cell(null);
  10940. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  10941. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  10942. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  10943. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  10944. };
  10945. var ColorSwatch = {
  10946. register: register$1,
  10947. getColors: getMenuColors,
  10948. getFetch: getFetch,
  10949. colorPickerDialog: colorPickerDialog,
  10950. getCurrentColor: getCurrentColor,
  10951. getColorCols: getColorCols$1,
  10952. calcCols: calcCols
  10953. };
  10954. var forMenu = function (presets) {
  10955. if (presets === 'color') {
  10956. return 'tox-swatches';
  10957. } else {
  10958. return 'tox-menu';
  10959. }
  10960. };
  10961. var classes = function (presets) {
  10962. return {
  10963. backgroundMenu: 'tox-background-menu',
  10964. selectedMenu: 'tox-selected-menu',
  10965. selectedItem: 'tox-collection__item--active',
  10966. hasIcons: 'tox-menu--has-icons',
  10967. menu: forMenu(presets),
  10968. tieredMenu: 'tox-tiered-menu'
  10969. };
  10970. };
  10971. var markers$1 = function (presets) {
  10972. var menuClasses = classes(presets);
  10973. return {
  10974. backgroundMenu: menuClasses.backgroundMenu,
  10975. selectedMenu: menuClasses.selectedMenu,
  10976. menu: menuClasses.menu,
  10977. selectedItem: menuClasses.selectedItem,
  10978. item: classForPreset(presets)
  10979. };
  10980. };
  10981. var dom$1 = function (hasIcons, columns, presets) {
  10982. var menuClasses = classes(presets);
  10983. return {
  10984. tag: 'div',
  10985. classes: flatten([
  10986. [
  10987. menuClasses.menu,
  10988. 'tox-menu-' + columns + '-column'
  10989. ],
  10990. hasIcons ? [menuClasses.hasIcons] : []
  10991. ])
  10992. };
  10993. };
  10994. var components$1 = [Menu.parts().items({})];
  10995. var part = function (hasIcons, columns, presets) {
  10996. var menuClasses = classes(presets);
  10997. var d = {
  10998. tag: 'div',
  10999. classes: flatten([[menuClasses.tieredMenu]])
  11000. };
  11001. return {
  11002. dom: d,
  11003. markers: markers$1(presets)
  11004. };
  11005. };
  11006. var chunk$1 = function (rowDom, numColumns) {
  11007. return function (items) {
  11008. var chunks = chunk(items, numColumns);
  11009. return map(chunks, function (c) {
  11010. return {
  11011. dom: rowDom,
  11012. components: c
  11013. };
  11014. });
  11015. };
  11016. };
  11017. var forSwatch = function (columns) {
  11018. return {
  11019. dom: {
  11020. tag: 'div',
  11021. classes: [
  11022. 'tox-menu',
  11023. 'tox-swatches-menu'
  11024. ]
  11025. },
  11026. components: [{
  11027. dom: {
  11028. tag: 'div',
  11029. classes: ['tox-swatches']
  11030. },
  11031. components: [Menu.parts().items({
  11032. preprocess: columns !== 'auto' ? chunk$1({
  11033. tag: 'div',
  11034. classes: ['tox-swatches__row']
  11035. }, columns) : identity
  11036. })]
  11037. }]
  11038. };
  11039. };
  11040. var forToolbar = function (columns) {
  11041. return {
  11042. dom: {
  11043. tag: 'div',
  11044. classes: [
  11045. 'tox-menu',
  11046. 'tox-collection',
  11047. 'tox-collection--toolbar',
  11048. 'tox-collection--toolbar-lg'
  11049. ]
  11050. },
  11051. components: [Menu.parts().items({
  11052. preprocess: chunk$1({
  11053. tag: 'div',
  11054. classes: ['tox-collection__group']
  11055. }, columns)
  11056. })]
  11057. };
  11058. };
  11059. var preprocessCollection = function (items, isSeparator) {
  11060. var allSplits = [];
  11061. var currentSplit = [];
  11062. each(items, function (item, i) {
  11063. if (isSeparator(item, i)) {
  11064. if (currentSplit.length > 0) {
  11065. allSplits.push(currentSplit);
  11066. }
  11067. currentSplit = [];
  11068. if (has(item.dom, 'innerHtml')) {
  11069. currentSplit.push(item);
  11070. }
  11071. } else {
  11072. currentSplit.push(item);
  11073. }
  11074. });
  11075. if (currentSplit.length > 0) {
  11076. allSplits.push(currentSplit);
  11077. }
  11078. return map(allSplits, function (s) {
  11079. return {
  11080. dom: {
  11081. tag: 'div',
  11082. classes: ['tox-collection__group']
  11083. },
  11084. components: s
  11085. };
  11086. });
  11087. };
  11088. var forCollection = function (columns, initItems, _hasIcons) {
  11089. return {
  11090. dom: {
  11091. tag: 'div',
  11092. classes: [
  11093. 'tox-menu',
  11094. 'tox-collection'
  11095. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  11096. },
  11097. components: [Menu.parts().items({
  11098. preprocess: function (items) {
  11099. if (columns !== 'auto' && columns > 1) {
  11100. return chunk$1({
  11101. tag: 'div',
  11102. classes: ['tox-collection__group']
  11103. }, columns)(items);
  11104. } else {
  11105. return preprocessCollection(items, function (_item, i) {
  11106. return initItems[i].type === 'separator';
  11107. });
  11108. }
  11109. }
  11110. })]
  11111. };
  11112. };
  11113. var forHorizontalCollection = function (initItems, _hasIcons) {
  11114. return {
  11115. dom: {
  11116. tag: 'div',
  11117. classes: [
  11118. 'tox-collection',
  11119. 'tox-collection--horizontal'
  11120. ]
  11121. },
  11122. components: [Menu.parts().items({
  11123. preprocess: function (items) {
  11124. return preprocessCollection(items, function (_item, i) {
  11125. return initItems[i].type === 'separator';
  11126. });
  11127. }
  11128. })]
  11129. };
  11130. };
  11131. var hasIcon = function (item) {
  11132. return item.icon !== undefined || item.type === 'togglemenuitem' || item.type === 'choicemenuitem';
  11133. };
  11134. var menuHasIcons = function (xs) {
  11135. return exists(xs, hasIcon);
  11136. };
  11137. var handleError = function (error) {
  11138. domGlobals.console.error(formatError(error));
  11139. domGlobals.console.log(error);
  11140. return Option.none();
  11141. };
  11142. var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  11143. var structure = forHorizontalCollection(items);
  11144. return {
  11145. value: value,
  11146. dom: structure.dom,
  11147. components: structure.components,
  11148. items: items
  11149. };
  11150. };
  11151. var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  11152. if (presets === 'color') {
  11153. var structure = forSwatch(columns);
  11154. return {
  11155. value: value,
  11156. dom: structure.dom,
  11157. components: structure.components,
  11158. items: items
  11159. };
  11160. }
  11161. if (presets === 'normal' && columns === 'auto') {
  11162. var structure = forCollection(columns, items);
  11163. return {
  11164. value: value,
  11165. dom: structure.dom,
  11166. components: structure.components,
  11167. items: items
  11168. };
  11169. }
  11170. if (presets === 'normal' && columns === 1) {
  11171. var structure = forCollection(1, items);
  11172. return {
  11173. value: value,
  11174. dom: structure.dom,
  11175. components: structure.components,
  11176. items: items
  11177. };
  11178. }
  11179. if (presets === 'normal') {
  11180. var structure = forCollection(columns, items);
  11181. return {
  11182. value: value,
  11183. dom: structure.dom,
  11184. components: structure.components,
  11185. items: items
  11186. };
  11187. }
  11188. if (presets === 'listpreview' && columns !== 'auto') {
  11189. var structure = forToolbar(columns);
  11190. return {
  11191. value: value,
  11192. dom: structure.dom,
  11193. components: structure.components,
  11194. items: items
  11195. };
  11196. }
  11197. return {
  11198. value: value,
  11199. dom: dom$1(hasIcons, columns, presets),
  11200. components: components$1,
  11201. items: items
  11202. };
  11203. };
  11204. var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  11205. var hasIcons = menuHasIcons(items);
  11206. var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  11207. var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  11208. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  11209. };
  11210. var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  11211. return cat(map(items, function (item) {
  11212. if (item.type === 'choiceitem') {
  11213. return createChoiceMenuItem(item).fold(handleError, function (d) {
  11214. return Option.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage));
  11215. });
  11216. } else {
  11217. return Option.none();
  11218. }
  11219. }));
  11220. };
  11221. var deriveMenuMovement = function (columns, presets) {
  11222. var menuMarkers = markers$1(presets);
  11223. if (columns === 1) {
  11224. return {
  11225. mode: 'menu',
  11226. moveOnTab: true
  11227. };
  11228. } else if (columns === 'auto') {
  11229. return {
  11230. mode: 'grid',
  11231. selector: '.' + menuMarkers.item,
  11232. initSize: {
  11233. numColumns: 1,
  11234. numRows: 1
  11235. }
  11236. };
  11237. } else {
  11238. var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  11239. return {
  11240. mode: 'matrix',
  11241. rowSelector: '.' + rowClass
  11242. };
  11243. }
  11244. };
  11245. var deriveCollectionMovement = function (columns, presets) {
  11246. if (columns === 1) {
  11247. return {
  11248. mode: 'menu',
  11249. moveOnTab: false,
  11250. selector: '.tox-collection__item'
  11251. };
  11252. } else if (columns === 'auto') {
  11253. return {
  11254. mode: 'flatgrid',
  11255. selector: '.' + 'tox-collection__item',
  11256. initSize: {
  11257. numColumns: 1,
  11258. numRows: 1
  11259. }
  11260. };
  11261. } else {
  11262. return {
  11263. mode: 'matrix',
  11264. selectors: {
  11265. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  11266. cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  11267. }
  11268. };
  11269. }
  11270. };
  11271. function renderColorSwatchItem(spec, backstage) {
  11272. var items = ColorSwatch.getColors(backstage.colorinput.getColors(), backstage.colorinput.hasCustomColors());
  11273. var columns = backstage.colorinput.getColorCols();
  11274. var presets = 'color';
  11275. var menuSpec = createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  11276. spec.onAction({ value: value });
  11277. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  11278. return false;
  11279. }, backstage.shared.providers);
  11280. var widgetSpec = __assign(__assign({}, menuSpec), {
  11281. markers: markers$1(presets),
  11282. movement: deriveMenuMovement(columns, presets)
  11283. });
  11284. return {
  11285. type: 'widget',
  11286. data: { value: generate$1('widget-id') },
  11287. dom: {
  11288. tag: 'div',
  11289. classes: ['tox-fancymenuitem']
  11290. },
  11291. autofocus: true,
  11292. components: [parts$2().widget(Menu.sketch(widgetSpec))]
  11293. };
  11294. }
  11295. var fancyMenuItems = {
  11296. inserttable: renderInsertTableMenuItem,
  11297. colorswatch: renderColorSwatchItem
  11298. };
  11299. var valueOpt = function (obj, key) {
  11300. return Object.prototype.hasOwnProperty.call(obj, key) ? Option.some(obj[key]) : Option.none();
  11301. };
  11302. var renderFancyMenuItem = function (spec, backstage) {
  11303. return valueOpt(fancyMenuItems, spec.fancytype).map(function (render) {
  11304. return render(spec, backstage);
  11305. });
  11306. };
  11307. var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  11308. if (renderIcons === void 0) {
  11309. renderIcons = true;
  11310. }
  11311. var getApi = function (component) {
  11312. return {
  11313. isDisabled: function () {
  11314. return Disabling.isDisabled(component);
  11315. },
  11316. setDisabled: function (state) {
  11317. return Disabling.set(component, state);
  11318. }
  11319. };
  11320. };
  11321. var structure = renderItemStructure({
  11322. presets: 'normal',
  11323. iconContent: spec.icon,
  11324. textContent: spec.text,
  11325. htmlContent: Option.none(),
  11326. ariaLabel: spec.text,
  11327. caret: Option.none(),
  11328. checkMark: Option.none(),
  11329. shortcutContent: spec.shortcut
  11330. }, providersBackstage, renderIcons);
  11331. return renderCommonItem({
  11332. data: buildData(spec),
  11333. getApi: getApi,
  11334. disabled: spec.disabled,
  11335. onAction: spec.onAction,
  11336. onSetup: spec.onSetup,
  11337. triggersSubmenu: false,
  11338. itemBehaviours: []
  11339. }, structure, itemResponse);
  11340. };
  11341. var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  11342. if (renderIcons === void 0) {
  11343. renderIcons = true;
  11344. }
  11345. if (downwardsCaret === void 0) {
  11346. downwardsCaret = false;
  11347. }
  11348. var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  11349. var getApi = function (component) {
  11350. return {
  11351. isDisabled: function () {
  11352. return Disabling.isDisabled(component);
  11353. },
  11354. setDisabled: function (state) {
  11355. return Disabling.set(component, state);
  11356. }
  11357. };
  11358. };
  11359. var structure = renderItemStructure({
  11360. presets: 'normal',
  11361. iconContent: spec.icon,
  11362. textContent: spec.text,
  11363. htmlContent: Option.none(),
  11364. ariaLabel: spec.text,
  11365. caret: Option.some(caret),
  11366. checkMark: Option.none(),
  11367. shortcutContent: spec.shortcut
  11368. }, providersBackstage, renderIcons);
  11369. return renderCommonItem({
  11370. data: buildData(spec),
  11371. getApi: getApi,
  11372. disabled: spec.disabled,
  11373. onAction: noop,
  11374. onSetup: spec.onSetup,
  11375. triggersSubmenu: true,
  11376. itemBehaviours: []
  11377. }, structure, itemResponse);
  11378. };
  11379. var renderSeparatorItem = function (spec) {
  11380. var innerHtml = spec.text.fold(function () {
  11381. return {};
  11382. }, function (text) {
  11383. return { innerHtml: text };
  11384. });
  11385. return {
  11386. type: 'separator',
  11387. dom: __assign({
  11388. tag: 'div',
  11389. classes: [
  11390. selectableClass,
  11391. groupHeadingClass
  11392. ]
  11393. }, innerHtml),
  11394. components: []
  11395. };
  11396. };
  11397. var renderToggleMenuItem = function (spec, itemResponse, providersBackstage) {
  11398. var getApi = function (component) {
  11399. return {
  11400. setActive: function (state) {
  11401. Toggling.set(component, state);
  11402. },
  11403. isActive: function () {
  11404. return Toggling.isOn(component);
  11405. },
  11406. isDisabled: function () {
  11407. return Disabling.isDisabled(component);
  11408. },
  11409. setDisabled: function (state) {
  11410. return Disabling.set(component, state);
  11411. }
  11412. };
  11413. };
  11414. var structure = renderItemStructure({
  11415. iconContent: Option.none(),
  11416. textContent: spec.text,
  11417. htmlContent: Option.none(),
  11418. ariaLabel: spec.text,
  11419. checkMark: Option.some(renderCheckmark(providersBackstage.icons)),
  11420. caret: Option.none(),
  11421. shortcutContent: spec.shortcut,
  11422. presets: 'normal',
  11423. meta: spec.meta
  11424. }, providersBackstage, true);
  11425. return deepMerge(renderCommonItem({
  11426. data: buildData(spec),
  11427. disabled: spec.disabled,
  11428. getApi: getApi,
  11429. onAction: spec.onAction,
  11430. onSetup: spec.onSetup,
  11431. triggersSubmenu: false,
  11432. itemBehaviours: []
  11433. }, structure, itemResponse), {
  11434. toggling: {
  11435. toggleClass: tickedClass,
  11436. toggleOnExecute: false,
  11437. selected: spec.active
  11438. }
  11439. });
  11440. };
  11441. var autocomplete = renderAutocompleteItem;
  11442. var separator = renderSeparatorItem;
  11443. var normal = renderNormalItem;
  11444. var nested = renderNestedItem;
  11445. var toggle$1 = renderToggleMenuItem;
  11446. var fancy = renderFancyMenuItem;
  11447. var FocusMode;
  11448. (function (FocusMode) {
  11449. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  11450. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  11451. }(FocusMode || (FocusMode = {})));
  11452. var hasIcon$1 = function (item) {
  11453. return item.icon !== undefined || item.type === 'togglemenuitem' || item.type === 'choicemenuitem';
  11454. };
  11455. var menuHasIcons$1 = function (xs) {
  11456. return exists(xs, hasIcon$1);
  11457. };
  11458. var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  11459. var providersBackstage = backstage.shared.providers;
  11460. var parseForHorizontalMenu = function (menuitem) {
  11461. return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  11462. shortcut: Option.none(),
  11463. icon: menuitem.text.isSome() ? Option.none() : menuitem.icon
  11464. });
  11465. };
  11466. switch (item.type) {
  11467. case 'menuitem':
  11468. return createMenuItem(item).fold(handleError, function (d) {
  11469. return Option.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  11470. });
  11471. case 'nestedmenuitem':
  11472. return createNestedMenuItem(item).fold(handleError, function (d) {
  11473. return Option.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  11474. });
  11475. case 'togglemenuitem':
  11476. return createToggleMenuItem(item).fold(handleError, function (d) {
  11477. return Option.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage));
  11478. });
  11479. case 'separator':
  11480. return createSeparatorMenuItem(item).fold(handleError, function (d) {
  11481. return Option.some(separator(d));
  11482. });
  11483. case 'fancymenuitem':
  11484. return createFancyMenuItem(item).fold(handleError, function (d) {
  11485. return fancy(parseForHorizontalMenu(d), backstage);
  11486. });
  11487. default: {
  11488. domGlobals.console.error('Unknown item in general menu', item);
  11489. return Option.none();
  11490. }
  11491. }
  11492. };
  11493. var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage) {
  11494. var renderText = columns === 1;
  11495. var renderIcons = !renderText || menuHasIcons$1(items);
  11496. return cat(map(items, function (item) {
  11497. if (item.type === 'separator') {
  11498. return createSeparatorItem(item).fold(handleError, function (d) {
  11499. return Option.some(separator(d));
  11500. });
  11501. } else {
  11502. return createAutocompleterItem(item).fold(handleError, function (d) {
  11503. return Option.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  11504. });
  11505. }
  11506. }));
  11507. };
  11508. var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  11509. var hasIcons = menuHasIcons$1(items);
  11510. var alloyItems = cat(map(items, function (item) {
  11511. var itemHasIcon = function (i) {
  11512. return isHorizontalMenu ? !i.hasOwnProperty('text') : hasIcons;
  11513. };
  11514. var createItem = function (i) {
  11515. return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  11516. };
  11517. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  11518. return createItem(__assign(__assign({}, item), { disabled: true }));
  11519. } else {
  11520. return createItem(item);
  11521. }
  11522. }));
  11523. var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  11524. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  11525. };
  11526. var createTieredDataFrom = function (partialMenu) {
  11527. return tieredMenu.singleData(partialMenu.value, partialMenu);
  11528. };
  11529. var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  11530. var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom();
  11531. var movement = deriveMenuMovement(columns, presets);
  11532. var menuMarkers = markers$1(presets);
  11533. return {
  11534. dom: partialMenu.dom,
  11535. components: partialMenu.components,
  11536. items: partialMenu.items,
  11537. value: partialMenu.value,
  11538. markers: {
  11539. selectedItem: menuMarkers.selectedItem,
  11540. item: menuMarkers.item
  11541. },
  11542. movement: movement,
  11543. fakeFocus: focusMode === FocusMode.ContentFocus,
  11544. focusManager: focusManager,
  11545. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, se) {
  11546. detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  11547. var numColumns = _a.numColumns, numRows = _a.numRows;
  11548. Keying.setGridSize(comp, numRows, numColumns);
  11549. });
  11550. })])
  11551. };
  11552. };
  11553. var register$2 = function (editor, sharedBackstage) {
  11554. var activeAutocompleter = Cell(Option.none());
  11555. var processingAction = Cell(false);
  11556. var autocompleter = build$1(InlineView.sketch({
  11557. dom: {
  11558. tag: 'div',
  11559. classes: ['tox-autocompleter']
  11560. },
  11561. components: [],
  11562. fireDismissalEventInstead: {},
  11563. inlineBehaviours: derive$1([config('dismissAutocompleter', [run(dismissRequested(), function () {
  11564. return cancelIfNecessary();
  11565. })])]),
  11566. lazySink: sharedBackstage.getSink
  11567. }));
  11568. var isMenuOpen = function () {
  11569. return InlineView.isOpen(autocompleter);
  11570. };
  11571. var isActive = function () {
  11572. return activeAutocompleter.get().isSome();
  11573. };
  11574. var hideIfNecessary = function () {
  11575. if (isActive()) {
  11576. InlineView.hide(autocompleter);
  11577. }
  11578. };
  11579. var cancelIfNecessary = function () {
  11580. if (isActive()) {
  11581. var lastElement = activeAutocompleter.get().map(function (ac) {
  11582. return ac.element;
  11583. });
  11584. detect$4(lastElement.getOr(Element.fromDom(editor.selection.getNode()))).each(unwrap);
  11585. hideIfNecessary();
  11586. activeAutocompleter.set(Option.none());
  11587. processingAction.set(false);
  11588. }
  11589. };
  11590. var getAutocompleters = cached(function () {
  11591. return register(editor);
  11592. });
  11593. var getCombinedItems = function (triggerChar, matches) {
  11594. var columns = findMap(matches, function (m) {
  11595. return Option.from(m.columns);
  11596. }).getOr(1);
  11597. return bind(matches, function (match) {
  11598. var choices = match.items;
  11599. return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  11600. var nr = editor.selection.getRng();
  11601. getContext(editor.dom, nr, triggerChar).fold(function () {
  11602. return domGlobals.console.error('Lost context. Cursor probably moved');
  11603. }, function (_a) {
  11604. var range = _a.range;
  11605. var autocompleterApi = {
  11606. hide: function () {
  11607. cancelIfNecessary();
  11608. },
  11609. reload: function (fetchOptions) {
  11610. hideIfNecessary();
  11611. load(fetchOptions);
  11612. }
  11613. };
  11614. processingAction.set(true);
  11615. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  11616. processingAction.set(false);
  11617. });
  11618. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage);
  11619. });
  11620. };
  11621. var commenceIfNecessary = function (context) {
  11622. if (!isActive()) {
  11623. var wrapper = create$4(editor, context.range);
  11624. activeAutocompleter.set(Option.some({
  11625. triggerChar: context.triggerChar,
  11626. element: wrapper,
  11627. matchLength: context.text.length
  11628. }));
  11629. processingAction.set(false);
  11630. }
  11631. };
  11632. var display = function (ac, context, lookupData, items) {
  11633. ac.matchLength = context.text.length;
  11634. var columns = findMap(lookupData, function (ld) {
  11635. return Option.from(ld.columns);
  11636. }).getOr(1);
  11637. InlineView.showAt(autocompleter, {
  11638. anchor: 'node',
  11639. root: Element.fromDom(editor.getBody()),
  11640. node: Option.from(ac.element)
  11641. }, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')));
  11642. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  11643. };
  11644. var doLookup = function (fetchOptions) {
  11645. return activeAutocompleter.get().map(function (ac) {
  11646. return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  11647. return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  11648. });
  11649. }).getOrThunk(function () {
  11650. return lookup(editor, getAutocompleters);
  11651. });
  11652. };
  11653. var load = function (fetchOptions) {
  11654. doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  11655. commenceIfNecessary(lookupInfo.context);
  11656. lookupInfo.lookupData.then(function (lookupData) {
  11657. activeAutocompleter.get().map(function (ac) {
  11658. var context = lookupInfo.context;
  11659. if (ac.triggerChar === context.triggerChar) {
  11660. var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  11661. if (combinedItems.length > 0) {
  11662. display(ac, context, lookupData, combinedItems);
  11663. } else if (context.text.length - ac.matchLength >= 10) {
  11664. cancelIfNecessary();
  11665. } else {
  11666. hideIfNecessary();
  11667. }
  11668. }
  11669. });
  11670. });
  11671. });
  11672. };
  11673. var onKeypress = last$2(function (e) {
  11674. if (e.which === 27) {
  11675. return;
  11676. }
  11677. load();
  11678. }, 50);
  11679. var autocompleterUiApi = {
  11680. onKeypress: onKeypress,
  11681. cancelIfNecessary: cancelIfNecessary,
  11682. isMenuOpen: isMenuOpen,
  11683. isActive: isActive,
  11684. isProcessingAction: processingAction.get,
  11685. getView: function () {
  11686. return InlineView.getContent(autocompleter);
  11687. }
  11688. };
  11689. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  11690. };
  11691. var Autocompleter = { register: register$2 };
  11692. var filter$1 = constant(true);
  11693. var bind$3 = function (element, event, handler) {
  11694. return bind$2(element, event, filter$1, handler);
  11695. };
  11696. var capture$1 = function (element, event, handler) {
  11697. return capture(element, event, filter$1, handler);
  11698. };
  11699. var fromRawEvent$1 = fromRawEvent;
  11700. var closest$4 = function (scope, selector, isRoot) {
  11701. return closest$3(scope, selector, isRoot).isSome();
  11702. };
  11703. function DelayedFunction (fun, delay) {
  11704. var ref = null;
  11705. var schedule = function () {
  11706. var args = [];
  11707. for (var _i = 0; _i < arguments.length; _i++) {
  11708. args[_i] = arguments[_i];
  11709. }
  11710. ref = domGlobals.setTimeout(function () {
  11711. fun.apply(null, args);
  11712. ref = null;
  11713. }, delay);
  11714. };
  11715. var cancel = function () {
  11716. if (ref !== null) {
  11717. domGlobals.clearTimeout(ref);
  11718. ref = null;
  11719. }
  11720. };
  11721. return {
  11722. cancel: cancel,
  11723. schedule: schedule
  11724. };
  11725. }
  11726. var SIGNIFICANT_MOVE = 5;
  11727. var LONGPRESS_DELAY = 400;
  11728. var getTouch = function (event) {
  11729. var raw = event.raw();
  11730. if (raw.touches === undefined || raw.touches.length !== 1) {
  11731. return Option.none();
  11732. }
  11733. return Option.some(raw.touches[0]);
  11734. };
  11735. var isFarEnough = function (touch, data) {
  11736. var distX = Math.abs(touch.clientX - data.x());
  11737. var distY = Math.abs(touch.clientY - data.y());
  11738. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  11739. };
  11740. var monitor = function (settings) {
  11741. var startData = Cell(Option.none());
  11742. var longpressFired = Cell(false);
  11743. var longpress$1 = DelayedFunction(function (event) {
  11744. settings.triggerEvent(longpress(), event);
  11745. longpressFired.set(true);
  11746. }, LONGPRESS_DELAY);
  11747. var handleTouchstart = function (event) {
  11748. getTouch(event).each(function (touch) {
  11749. longpress$1.cancel();
  11750. var data = {
  11751. x: constant(touch.clientX),
  11752. y: constant(touch.clientY),
  11753. target: event.target
  11754. };
  11755. longpress$1.schedule(event);
  11756. longpressFired.set(false);
  11757. startData.set(Option.some(data));
  11758. });
  11759. return Option.none();
  11760. };
  11761. var handleTouchmove = function (event) {
  11762. longpress$1.cancel();
  11763. getTouch(event).each(function (touch) {
  11764. startData.get().each(function (data) {
  11765. if (isFarEnough(touch, data)) {
  11766. startData.set(Option.none());
  11767. }
  11768. });
  11769. });
  11770. return Option.none();
  11771. };
  11772. var handleTouchend = function (event) {
  11773. longpress$1.cancel();
  11774. var isSame = function (data) {
  11775. return eq(data.target(), event.target());
  11776. };
  11777. return startData.get().filter(isSame).map(function (data) {
  11778. if (longpressFired.get()) {
  11779. event.prevent();
  11780. return false;
  11781. } else {
  11782. return settings.triggerEvent(tap(), event);
  11783. }
  11784. });
  11785. };
  11786. var handlers = wrapAll$1([
  11787. {
  11788. key: touchstart(),
  11789. value: handleTouchstart
  11790. },
  11791. {
  11792. key: touchmove(),
  11793. value: handleTouchmove
  11794. },
  11795. {
  11796. key: touchend(),
  11797. value: handleTouchend
  11798. }
  11799. ]);
  11800. var fireIfReady = function (event, type) {
  11801. return get(handlers, type).bind(function (handler) {
  11802. return handler(event);
  11803. });
  11804. };
  11805. return { fireIfReady: fireIfReady };
  11806. };
  11807. var isDangerous = function (event) {
  11808. var keyEv = event.raw();
  11809. return keyEv.which === BACKSPACE()[0] && !contains([
  11810. 'input',
  11811. 'textarea'
  11812. ], name(event.target())) && !closest$4(event.target(), '[contenteditable="true"]');
  11813. };
  11814. var isFirefox = detect$3().browser.isFirefox();
  11815. var settingsSchema = objOfOnly([
  11816. strictFunction('triggerEvent'),
  11817. defaulted$1('stopBackspace', true)
  11818. ]);
  11819. var bindFocus = function (container, handler) {
  11820. if (isFirefox) {
  11821. return capture$1(container, 'focus', handler);
  11822. } else {
  11823. return bind$3(container, 'focusin', handler);
  11824. }
  11825. };
  11826. var bindBlur = function (container, handler) {
  11827. if (isFirefox) {
  11828. return capture$1(container, 'blur', handler);
  11829. } else {
  11830. return bind$3(container, 'focusout', handler);
  11831. }
  11832. };
  11833. var setup$1 = function (container, rawSettings) {
  11834. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  11835. var pointerEvents = [
  11836. 'touchstart',
  11837. 'touchmove',
  11838. 'touchend',
  11839. 'touchcancel',
  11840. 'gesturestart',
  11841. 'mousedown',
  11842. 'mouseup',
  11843. 'mouseover',
  11844. 'mousemove',
  11845. 'mouseout',
  11846. 'click'
  11847. ];
  11848. var tapEvent = monitor(settings);
  11849. var simpleEvents = map(pointerEvents.concat([
  11850. 'selectstart',
  11851. 'input',
  11852. 'contextmenu',
  11853. 'change',
  11854. 'transitionend',
  11855. 'drag',
  11856. 'dragstart',
  11857. 'dragend',
  11858. 'dragenter',
  11859. 'dragleave',
  11860. 'dragover',
  11861. 'drop',
  11862. 'keyup'
  11863. ]), function (type) {
  11864. return bind$3(container, type, function (event) {
  11865. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  11866. if (tapStopped) {
  11867. event.kill();
  11868. }
  11869. });
  11870. var stopped = settings.triggerEvent(type, event);
  11871. if (stopped) {
  11872. event.kill();
  11873. }
  11874. });
  11875. });
  11876. var pasteTimeout = Cell(Option.none());
  11877. var onPaste = bind$3(container, 'paste', function (event) {
  11878. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11879. if (tapStopped) {
  11880. event.kill();
  11881. }
  11882. });
  11883. var stopped = settings.triggerEvent('paste', event);
  11884. if (stopped) {
  11885. event.kill();
  11886. }
  11887. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11888. settings.triggerEvent(postPaste(), event);
  11889. }, 0)));
  11890. });
  11891. var onKeydown = bind$3(container, 'keydown', function (event) {
  11892. var stopped = settings.triggerEvent('keydown', event);
  11893. if (stopped) {
  11894. event.kill();
  11895. } else if (settings.stopBackspace === true && isDangerous(event)) {
  11896. event.prevent();
  11897. }
  11898. });
  11899. var onFocusIn = bindFocus(container, function (event) {
  11900. var stopped = settings.triggerEvent('focusin', event);
  11901. if (stopped) {
  11902. event.kill();
  11903. }
  11904. });
  11905. var focusoutTimeout = Cell(Option.none());
  11906. var onFocusOut = bindBlur(container, function (event) {
  11907. var stopped = settings.triggerEvent('focusout', event);
  11908. if (stopped) {
  11909. event.kill();
  11910. }
  11911. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11912. settings.triggerEvent(postBlur(), event);
  11913. }, 0)));
  11914. });
  11915. var unbind = function () {
  11916. each(simpleEvents, function (e) {
  11917. e.unbind();
  11918. });
  11919. onKeydown.unbind();
  11920. onFocusIn.unbind();
  11921. onFocusOut.unbind();
  11922. onPaste.unbind();
  11923. pasteTimeout.get().each(domGlobals.clearTimeout);
  11924. focusoutTimeout.get().each(domGlobals.clearTimeout);
  11925. };
  11926. return { unbind: unbind };
  11927. };
  11928. var derive$2 = function (rawEvent, rawTarget) {
  11929. var source = get(rawEvent, 'target').map(function (getTarget) {
  11930. return getTarget();
  11931. }).getOr(rawTarget);
  11932. return Cell(source);
  11933. };
  11934. var fromSource = function (event, source) {
  11935. var stopper = Cell(false);
  11936. var cutter = Cell(false);
  11937. var stop = function () {
  11938. stopper.set(true);
  11939. };
  11940. var cut = function () {
  11941. cutter.set(true);
  11942. };
  11943. return {
  11944. stop: stop,
  11945. cut: cut,
  11946. isStopped: stopper.get,
  11947. isCut: cutter.get,
  11948. event: constant(event),
  11949. setSource: source.set,
  11950. getSource: source.get
  11951. };
  11952. };
  11953. var fromExternal = function (event) {
  11954. var stopper = Cell(false);
  11955. var stop = function () {
  11956. stopper.set(true);
  11957. };
  11958. return {
  11959. stop: stop,
  11960. cut: noop,
  11961. isStopped: stopper.get,
  11962. isCut: constant(false),
  11963. event: constant(event),
  11964. setSource: die('Cannot set source of a broadcasted event'),
  11965. getSource: die('Cannot get source of a broadcasted event')
  11966. };
  11967. };
  11968. var adt$b = Adt.generate([
  11969. { stopped: [] },
  11970. { resume: ['element'] },
  11971. { complete: [] }
  11972. ]);
  11973. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11974. var handler = lookup(eventType, target);
  11975. var simulatedEvent = fromSource(rawEvent, source);
  11976. return handler.fold(function () {
  11977. logger.logEventNoHandlers(eventType, target);
  11978. return adt$b.complete();
  11979. }, function (handlerInfo) {
  11980. var descHandler = handlerInfo.descHandler();
  11981. var eventHandler = getCurried(descHandler);
  11982. eventHandler(simulatedEvent);
  11983. if (simulatedEvent.isStopped()) {
  11984. logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose());
  11985. return adt$b.stopped();
  11986. } else if (simulatedEvent.isCut()) {
  11987. logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose());
  11988. return adt$b.complete();
  11989. } else {
  11990. return parent(handlerInfo.element()).fold(function () {
  11991. logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose());
  11992. return adt$b.complete();
  11993. }, function (parent) {
  11994. logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose());
  11995. return adt$b.resume(parent);
  11996. });
  11997. }
  11998. });
  11999. };
  12000. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12001. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  12002. return true;
  12003. }, function (parent) {
  12004. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12005. }, function () {
  12006. return false;
  12007. });
  12008. };
  12009. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12010. var source = derive$2(rawEvent, target);
  12011. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12012. };
  12013. var broadcast = function (listeners, rawEvent, logger) {
  12014. var simulatedEvent = fromExternal(rawEvent);
  12015. each(listeners, function (listener) {
  12016. var descHandler = listener.descHandler();
  12017. var handler = getCurried(descHandler);
  12018. handler(simulatedEvent);
  12019. });
  12020. return simulatedEvent.isStopped();
  12021. };
  12022. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12023. var rawTarget = rawEvent.target();
  12024. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  12025. };
  12026. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12027. var source = derive$2(rawEvent, rawTarget);
  12028. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12029. };
  12030. var eventHandler = Immutable('element', 'descHandler');
  12031. var broadcastHandler = function (id, handler) {
  12032. return {
  12033. id: constant(id),
  12034. descHandler: constant(handler)
  12035. };
  12036. };
  12037. function EventRegistry () {
  12038. var registry = {};
  12039. var registerId = function (extraArgs, id, events) {
  12040. each$1(events, function (v, k) {
  12041. var handlers = registry[k] !== undefined ? registry[k] : {};
  12042. handlers[id] = curryArgs(v, extraArgs);
  12043. registry[k] = handlers;
  12044. });
  12045. };
  12046. var findHandler = function (handlers, elem) {
  12047. return read$1(elem).fold(function () {
  12048. return Option.none();
  12049. }, function (id) {
  12050. return handlers.bind(function (h) {
  12051. return get(h, id);
  12052. }).map(function (descHandler) {
  12053. return eventHandler(elem, descHandler);
  12054. });
  12055. });
  12056. };
  12057. var filterByType = function (type) {
  12058. return get(registry, type).map(function (handlers) {
  12059. return mapToArray(handlers, function (f, id) {
  12060. return broadcastHandler(id, f);
  12061. });
  12062. }).getOr([]);
  12063. };
  12064. var find = function (isAboveRoot, type, target) {
  12065. var handlers = get(registry, type);
  12066. return closest(target, function (elem) {
  12067. return findHandler(handlers, elem);
  12068. }, isAboveRoot);
  12069. };
  12070. var unregisterId = function (id) {
  12071. each$1(registry, function (handlersById, eventName) {
  12072. if (handlersById.hasOwnProperty(id)) {
  12073. delete handlersById[id];
  12074. }
  12075. });
  12076. };
  12077. return {
  12078. registerId: registerId,
  12079. unregisterId: unregisterId,
  12080. filterByType: filterByType,
  12081. find: find
  12082. };
  12083. }
  12084. function Registry () {
  12085. var events = EventRegistry();
  12086. var components = {};
  12087. var readOrTag = function (component) {
  12088. var elem = component.element();
  12089. return read$1(elem).fold(function () {
  12090. return write('uid-', component.element());
  12091. }, function (uid) {
  12092. return uid;
  12093. });
  12094. };
  12095. var failOnDuplicate = function (component, tagId) {
  12096. var conflict = components[tagId];
  12097. if (conflict === component) {
  12098. unregister(component);
  12099. } else {
  12100. 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');
  12101. }
  12102. };
  12103. var register = function (component) {
  12104. var tagId = readOrTag(component);
  12105. if (hasNonNullableKey(components, tagId)) {
  12106. failOnDuplicate(component, tagId);
  12107. }
  12108. var extraArgs = [component];
  12109. events.registerId(extraArgs, tagId, component.events());
  12110. components[tagId] = component;
  12111. };
  12112. var unregister = function (component) {
  12113. read$1(component.element()).each(function (tagId) {
  12114. delete components[tagId];
  12115. events.unregisterId(tagId);
  12116. });
  12117. };
  12118. var filter = function (type) {
  12119. return events.filterByType(type);
  12120. };
  12121. var find = function (isAboveRoot, type, target) {
  12122. return events.find(isAboveRoot, type, target);
  12123. };
  12124. var getById = function (id) {
  12125. return get(components, id);
  12126. };
  12127. return {
  12128. find: find,
  12129. filter: filter,
  12130. register: register,
  12131. unregister: unregister,
  12132. getById: getById
  12133. };
  12134. }
  12135. var factory$3 = function (detail) {
  12136. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  12137. return {
  12138. uid: detail.uid,
  12139. dom: __assign({
  12140. tag: 'div',
  12141. attributes: __assign({ role: 'presentation' }, attributes)
  12142. }, domWithoutAttributes),
  12143. components: detail.components,
  12144. behaviours: get$c(detail.containerBehaviours),
  12145. events: detail.events,
  12146. domModification: detail.domModification,
  12147. eventOrder: detail.eventOrder
  12148. };
  12149. };
  12150. var Container = single$2({
  12151. name: 'Container',
  12152. factory: factory$3,
  12153. configFields: [
  12154. defaulted$1('components', []),
  12155. field$1('containerBehaviours', []),
  12156. defaulted$1('events', {}),
  12157. defaulted$1('domModification', {}),
  12158. defaulted$1('eventOrder', {})
  12159. ]
  12160. });
  12161. var takeover = function (root) {
  12162. var isAboveRoot = function (el) {
  12163. return parent(root.element()).fold(function () {
  12164. return true;
  12165. }, function (parent) {
  12166. return eq(el, parent);
  12167. });
  12168. };
  12169. var registry = Registry();
  12170. var lookup = function (eventName, target) {
  12171. return registry.find(isAboveRoot, eventName, target);
  12172. };
  12173. var domEvents = setup$1(root.element(), {
  12174. triggerEvent: function (eventName, event) {
  12175. return monitorEvent(eventName, event.target(), function (logger) {
  12176. return triggerUntilStopped(lookup, eventName, event, logger);
  12177. });
  12178. }
  12179. });
  12180. var systemApi = {
  12181. debugInfo: constant('real'),
  12182. triggerEvent: function (eventName, target, data) {
  12183. monitorEvent(eventName, target, function (logger) {
  12184. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  12185. });
  12186. },
  12187. triggerFocus: function (target, originator) {
  12188. read$1(target).fold(function () {
  12189. focus$1(target);
  12190. }, function (_alloyId) {
  12191. monitorEvent(focus(), target, function (logger) {
  12192. triggerHandler(lookup, focus(), {
  12193. originator: constant(originator),
  12194. kill: noop,
  12195. prevent: noop,
  12196. target: constant(target)
  12197. }, target, logger);
  12198. return false;
  12199. });
  12200. });
  12201. },
  12202. triggerEscape: function (comp, simulatedEvent) {
  12203. systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
  12204. },
  12205. getByUid: function (uid) {
  12206. return getByUid(uid);
  12207. },
  12208. getByDom: function (elem) {
  12209. return getByDom(elem);
  12210. },
  12211. build: build$1,
  12212. addToGui: function (c) {
  12213. add(c);
  12214. },
  12215. removeFromGui: function (c) {
  12216. remove$1(c);
  12217. },
  12218. addToWorld: function (c) {
  12219. addToWorld(c);
  12220. },
  12221. removeFromWorld: function (c) {
  12222. removeFromWorld(c);
  12223. },
  12224. broadcast: function (message) {
  12225. broadcast$1(message);
  12226. },
  12227. broadcastOn: function (channels, message) {
  12228. broadcastOn(channels, message);
  12229. },
  12230. broadcastEvent: function (eventName, event) {
  12231. broadcastEvent(eventName, event);
  12232. },
  12233. isConnected: constant(true)
  12234. };
  12235. var addToWorld = function (component) {
  12236. component.connect(systemApi);
  12237. if (!isText(component.element())) {
  12238. registry.register(component);
  12239. each(component.components(), addToWorld);
  12240. systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
  12241. }
  12242. };
  12243. var removeFromWorld = function (component) {
  12244. if (!isText(component.element())) {
  12245. each(component.components(), removeFromWorld);
  12246. registry.unregister(component);
  12247. }
  12248. component.disconnect();
  12249. };
  12250. var add = function (component) {
  12251. attach$1(root, component);
  12252. };
  12253. var remove$1 = function (component) {
  12254. detach(component);
  12255. };
  12256. var destroy = function () {
  12257. domEvents.unbind();
  12258. remove(root.element());
  12259. };
  12260. var broadcastData = function (data) {
  12261. var receivers = registry.filter(receive());
  12262. each(receivers, function (receiver) {
  12263. var descHandler = receiver.descHandler();
  12264. var handler = getCurried(descHandler);
  12265. handler(data);
  12266. });
  12267. };
  12268. var broadcast$1 = function (message) {
  12269. broadcastData({
  12270. universal: constant(true),
  12271. data: constant(message)
  12272. });
  12273. };
  12274. var broadcastOn = function (channels, message) {
  12275. broadcastData({
  12276. universal: constant(false),
  12277. channels: constant(channels),
  12278. data: constant(message)
  12279. });
  12280. };
  12281. var broadcastEvent = function (eventName, event) {
  12282. var listeners = registry.filter(eventName);
  12283. return broadcast(listeners, event);
  12284. };
  12285. var getByUid = function (uid) {
  12286. return registry.getById(uid).fold(function () {
  12287. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  12288. }, Result.value);
  12289. };
  12290. var getByDom = function (elem) {
  12291. var uid = read$1(elem).getOr('not found');
  12292. return getByUid(uid);
  12293. };
  12294. addToWorld(root);
  12295. return {
  12296. root: constant(root),
  12297. element: root.element,
  12298. destroy: destroy,
  12299. add: add,
  12300. remove: remove$1,
  12301. getByUid: getByUid,
  12302. getByDom: getByDom,
  12303. addToWorld: addToWorld,
  12304. removeFromWorld: removeFromWorld,
  12305. broadcast: broadcast$1,
  12306. broadcastOn: broadcastOn,
  12307. broadcastEvent: broadcastEvent
  12308. };
  12309. };
  12310. var formChangeEvent = generate$1('form-component-change');
  12311. var formCloseEvent = generate$1('form-close');
  12312. var formCancelEvent = generate$1('form-cancel');
  12313. var formActionEvent = generate$1('form-action');
  12314. var formSubmitEvent = generate$1('form-submit');
  12315. var formBlockEvent = generate$1('form-block');
  12316. var formUnblockEvent = generate$1('form-unblock');
  12317. var formTabChangeEvent = generate$1('form-tabchange');
  12318. var formResizeEvent = generate$1('form-resize');
  12319. var renderAlertBanner = function (spec, providersBackstage) {
  12320. return Container.sketch({
  12321. dom: {
  12322. tag: 'div',
  12323. attributes: { role: 'alert' },
  12324. classes: [
  12325. 'tox-notification',
  12326. 'tox-notification--in',
  12327. 'tox-notification--' + spec.level
  12328. ]
  12329. },
  12330. components: [
  12331. {
  12332. dom: {
  12333. tag: 'div',
  12334. classes: ['tox-notification__icon']
  12335. },
  12336. components: [Button.sketch({
  12337. dom: {
  12338. tag: 'button',
  12339. classes: [
  12340. 'tox-button',
  12341. 'tox-button--naked',
  12342. 'tox-button--icon'
  12343. ],
  12344. innerHtml: get$d(spec.icon, providersBackstage.icons),
  12345. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  12346. },
  12347. action: function (comp) {
  12348. emitWith(comp, formActionEvent, {
  12349. name: 'alert-banner',
  12350. value: spec.url
  12351. });
  12352. }
  12353. })]
  12354. },
  12355. {
  12356. dom: {
  12357. tag: 'div',
  12358. classes: ['tox-notification__body'],
  12359. innerHtml: providersBackstage.translate(spec.text)
  12360. }
  12361. }
  12362. ]
  12363. });
  12364. };
  12365. var renderBar = function (spec, backstage) {
  12366. return {
  12367. dom: {
  12368. tag: 'div',
  12369. classes: [
  12370. 'tox-bar',
  12371. 'tox-form__controls-h-stack'
  12372. ]
  12373. },
  12374. components: map(spec.items, backstage.interpreter)
  12375. };
  12376. };
  12377. var schema$e = constant([
  12378. defaulted$1('prefix', 'form-field'),
  12379. field$1('fieldBehaviours', [
  12380. Composing,
  12381. Representing
  12382. ])
  12383. ]);
  12384. var parts$3 = constant([
  12385. optional({
  12386. schema: [strict$1('dom')],
  12387. name: 'label'
  12388. }),
  12389. optional({
  12390. factory: {
  12391. sketch: function (spec) {
  12392. return {
  12393. uid: spec.uid,
  12394. dom: {
  12395. tag: 'span',
  12396. styles: { display: 'none' },
  12397. attributes: { 'aria-hidden': 'true' },
  12398. innerHtml: spec.text
  12399. }
  12400. };
  12401. }
  12402. },
  12403. schema: [strict$1('text')],
  12404. name: 'aria-descriptor'
  12405. }),
  12406. required({
  12407. factory: {
  12408. sketch: function (spec) {
  12409. var excludeFactory = exclude$1(spec, ['factory']);
  12410. return spec.factory.sketch(excludeFactory);
  12411. }
  12412. },
  12413. schema: [strict$1('factory')],
  12414. name: 'field'
  12415. })
  12416. ]);
  12417. var factory$4 = function (detail, components, spec, externals) {
  12418. var behaviours = augment(detail.fieldBehaviours, [
  12419. Composing.config({
  12420. find: function (container) {
  12421. return getPart(container, detail, 'field');
  12422. }
  12423. }),
  12424. Representing.config({
  12425. store: {
  12426. mode: 'manual',
  12427. getValue: function (field) {
  12428. return Composing.getCurrent(field).bind(Representing.getValue);
  12429. },
  12430. setValue: function (field, value) {
  12431. Composing.getCurrent(field).each(function (current) {
  12432. Representing.setValue(current, value);
  12433. });
  12434. }
  12435. }
  12436. })
  12437. ]);
  12438. var events = derive([runOnAttached(function (component, simulatedEvent) {
  12439. var ps = getParts(component, detail, [
  12440. 'label',
  12441. 'field',
  12442. 'aria-descriptor'
  12443. ]);
  12444. ps.field().each(function (field) {
  12445. var id = generate$1(detail.prefix);
  12446. ps.label().each(function (label) {
  12447. set$1(label.element(), 'for', id);
  12448. set$1(field.element(), 'id', id);
  12449. });
  12450. ps['aria-descriptor']().each(function (descriptor) {
  12451. var descriptorId = generate$1(detail.prefix);
  12452. set$1(descriptor.element(), 'id', descriptorId);
  12453. set$1(field.element(), 'aria-describedby', descriptorId);
  12454. });
  12455. });
  12456. })]);
  12457. var apis = {
  12458. getField: function (container) {
  12459. return getPart(container, detail, 'field');
  12460. },
  12461. getLabel: function (container) {
  12462. return getPart(container, detail, 'label');
  12463. }
  12464. };
  12465. return {
  12466. uid: detail.uid,
  12467. dom: detail.dom,
  12468. components: components,
  12469. behaviours: behaviours,
  12470. events: events,
  12471. apis: apis
  12472. };
  12473. };
  12474. var FormField = composite$1({
  12475. name: 'FormField',
  12476. configFields: schema$e(),
  12477. partFields: parts$3(),
  12478. factory: factory$4,
  12479. apis: {
  12480. getField: function (apis, comp) {
  12481. return apis.getField(comp);
  12482. },
  12483. getLabel: function (apis, comp) {
  12484. return apis.getLabel(comp);
  12485. }
  12486. }
  12487. });
  12488. var schema$f = constant([
  12489. option('data'),
  12490. defaulted$1('inputAttributes', {}),
  12491. defaulted$1('inputStyles', {}),
  12492. defaulted$1('tag', 'input'),
  12493. defaulted$1('inputClasses', []),
  12494. onHandler('onSetValue'),
  12495. defaulted$1('styles', {}),
  12496. defaulted$1('eventOrder', {}),
  12497. field$1('inputBehaviours', [
  12498. Representing,
  12499. Focusing
  12500. ]),
  12501. defaulted$1('selectOnFocus', true)
  12502. ]);
  12503. var focusBehaviours = function (detail) {
  12504. return derive$1([Focusing.config({
  12505. onFocus: !detail.selectOnFocus ? noop : function (component) {
  12506. var input = component.element();
  12507. var value = get$5(input);
  12508. input.dom().setSelectionRange(0, value.length);
  12509. }
  12510. })]);
  12511. };
  12512. var behaviours = function (detail) {
  12513. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  12514. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  12515. return { initialValue: data };
  12516. }).getOr({})), {
  12517. getValue: function (input) {
  12518. return get$5(input.element());
  12519. },
  12520. setValue: function (input, data) {
  12521. var current = get$5(input.element());
  12522. if (current !== data) {
  12523. set$3(input.element(), data);
  12524. }
  12525. }
  12526. }),
  12527. onSetValue: detail.onSetValue
  12528. })]));
  12529. };
  12530. var dom$2 = function (detail) {
  12531. return {
  12532. tag: detail.tag,
  12533. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  12534. styles: detail.inputStyles,
  12535. classes: detail.inputClasses
  12536. };
  12537. };
  12538. var factory$5 = function (detail, spec) {
  12539. return {
  12540. uid: detail.uid,
  12541. dom: dom$2(detail),
  12542. components: [],
  12543. behaviours: behaviours(detail),
  12544. eventOrder: detail.eventOrder
  12545. };
  12546. };
  12547. var Input = single$2({
  12548. name: 'Input',
  12549. configFields: schema$f(),
  12550. factory: factory$5
  12551. });
  12552. var exports$1 = {}, module = { exports: exports$1 };
  12553. (function (define, exports, module, require) {
  12554. (function (f) {
  12555. if (typeof exports === 'object' && typeof module !== 'undefined') {
  12556. module.exports = f();
  12557. } else if (typeof define === 'function' && define.amd) {
  12558. define([], f);
  12559. } else {
  12560. var g;
  12561. if (typeof window !== 'undefined') {
  12562. g = window;
  12563. } else if (typeof global !== 'undefined') {
  12564. g = global;
  12565. } else if (typeof self !== 'undefined') {
  12566. g = self;
  12567. } else {
  12568. g = this;
  12569. }
  12570. g.EphoxContactWrapper = f();
  12571. }
  12572. }(function () {
  12573. return function () {
  12574. function r(e, n, t) {
  12575. function o(i, f) {
  12576. if (!n[i]) {
  12577. if (!e[i]) {
  12578. var c = 'function' == typeof require && require;
  12579. if (!f && c)
  12580. return c(i, !0);
  12581. if (u)
  12582. return u(i, !0);
  12583. var a = new Error('Cannot find module \'' + i + '\'');
  12584. throw a.code = 'MODULE_NOT_FOUND', a;
  12585. }
  12586. var p = n[i] = { exports: {} };
  12587. e[i][0].call(p.exports, function (r) {
  12588. var n = e[i][1][r];
  12589. return o(n || r);
  12590. }, p, p.exports, r, e, n, t);
  12591. }
  12592. return n[i].exports;
  12593. }
  12594. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  12595. o(t[i]);
  12596. return o;
  12597. }
  12598. return r;
  12599. }()({
  12600. 1: [
  12601. function (require, module, exports) {
  12602. var process = module.exports = {};
  12603. var cachedSetTimeout;
  12604. var cachedClearTimeout;
  12605. function defaultSetTimout() {
  12606. throw new Error('setTimeout has not been defined');
  12607. }
  12608. function defaultClearTimeout() {
  12609. throw new Error('clearTimeout has not been defined');
  12610. }
  12611. (function () {
  12612. try {
  12613. if (typeof setTimeout === 'function') {
  12614. cachedSetTimeout = setTimeout;
  12615. } else {
  12616. cachedSetTimeout = defaultSetTimout;
  12617. }
  12618. } catch (e) {
  12619. cachedSetTimeout = defaultSetTimout;
  12620. }
  12621. try {
  12622. if (typeof clearTimeout === 'function') {
  12623. cachedClearTimeout = clearTimeout;
  12624. } else {
  12625. cachedClearTimeout = defaultClearTimeout;
  12626. }
  12627. } catch (e) {
  12628. cachedClearTimeout = defaultClearTimeout;
  12629. }
  12630. }());
  12631. function runTimeout(fun) {
  12632. if (cachedSetTimeout === setTimeout) {
  12633. return setTimeout(fun, 0);
  12634. }
  12635. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12636. cachedSetTimeout = setTimeout;
  12637. return setTimeout(fun, 0);
  12638. }
  12639. try {
  12640. return cachedSetTimeout(fun, 0);
  12641. } catch (e) {
  12642. try {
  12643. return cachedSetTimeout.call(null, fun, 0);
  12644. } catch (e) {
  12645. return cachedSetTimeout.call(this, fun, 0);
  12646. }
  12647. }
  12648. }
  12649. function runClearTimeout(marker) {
  12650. if (cachedClearTimeout === clearTimeout) {
  12651. return clearTimeout(marker);
  12652. }
  12653. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12654. cachedClearTimeout = clearTimeout;
  12655. return clearTimeout(marker);
  12656. }
  12657. try {
  12658. return cachedClearTimeout(marker);
  12659. } catch (e) {
  12660. try {
  12661. return cachedClearTimeout.call(null, marker);
  12662. } catch (e) {
  12663. return cachedClearTimeout.call(this, marker);
  12664. }
  12665. }
  12666. }
  12667. var queue = [];
  12668. var draining = false;
  12669. var currentQueue;
  12670. var queueIndex = -1;
  12671. function cleanUpNextTick() {
  12672. if (!draining || !currentQueue) {
  12673. return;
  12674. }
  12675. draining = false;
  12676. if (currentQueue.length) {
  12677. queue = currentQueue.concat(queue);
  12678. } else {
  12679. queueIndex = -1;
  12680. }
  12681. if (queue.length) {
  12682. drainQueue();
  12683. }
  12684. }
  12685. function drainQueue() {
  12686. if (draining) {
  12687. return;
  12688. }
  12689. var timeout = runTimeout(cleanUpNextTick);
  12690. draining = true;
  12691. var len = queue.length;
  12692. while (len) {
  12693. currentQueue = queue;
  12694. queue = [];
  12695. while (++queueIndex < len) {
  12696. if (currentQueue) {
  12697. currentQueue[queueIndex].run();
  12698. }
  12699. }
  12700. queueIndex = -1;
  12701. len = queue.length;
  12702. }
  12703. currentQueue = null;
  12704. draining = false;
  12705. runClearTimeout(timeout);
  12706. }
  12707. process.nextTick = function (fun) {
  12708. var args = new Array(arguments.length - 1);
  12709. if (arguments.length > 1) {
  12710. for (var i = 1; i < arguments.length; i++) {
  12711. args[i - 1] = arguments[i];
  12712. }
  12713. }
  12714. queue.push(new Item(fun, args));
  12715. if (queue.length === 1 && !draining) {
  12716. runTimeout(drainQueue);
  12717. }
  12718. };
  12719. function Item(fun, array) {
  12720. this.fun = fun;
  12721. this.array = array;
  12722. }
  12723. Item.prototype.run = function () {
  12724. this.fun.apply(null, this.array);
  12725. };
  12726. process.title = 'browser';
  12727. process.browser = true;
  12728. process.env = {};
  12729. process.argv = [];
  12730. process.version = '';
  12731. process.versions = {};
  12732. function noop() {
  12733. }
  12734. process.on = noop;
  12735. process.addListener = noop;
  12736. process.once = noop;
  12737. process.off = noop;
  12738. process.removeListener = noop;
  12739. process.removeAllListeners = noop;
  12740. process.emit = noop;
  12741. process.prependListener = noop;
  12742. process.prependOnceListener = noop;
  12743. process.listeners = function (name) {
  12744. return [];
  12745. };
  12746. process.binding = function (name) {
  12747. throw new Error('process.binding is not supported');
  12748. };
  12749. process.cwd = function () {
  12750. return '/';
  12751. };
  12752. process.chdir = function (dir) {
  12753. throw new Error('process.chdir is not supported');
  12754. };
  12755. process.umask = function () {
  12756. return 0;
  12757. };
  12758. },
  12759. {}
  12760. ],
  12761. 2: [
  12762. function (require, module, exports) {
  12763. (function (setImmediate) {
  12764. (function (root) {
  12765. var setTimeoutFunc = setTimeout;
  12766. function noop() {
  12767. }
  12768. function bind(fn, thisArg) {
  12769. return function () {
  12770. fn.apply(thisArg, arguments);
  12771. };
  12772. }
  12773. function Promise(fn) {
  12774. if (typeof this !== 'object')
  12775. throw new TypeError('Promises must be constructed via new');
  12776. if (typeof fn !== 'function')
  12777. throw new TypeError('not a function');
  12778. this._state = 0;
  12779. this._handled = false;
  12780. this._value = undefined;
  12781. this._deferreds = [];
  12782. doResolve(fn, this);
  12783. }
  12784. function handle(self, deferred) {
  12785. while (self._state === 3) {
  12786. self = self._value;
  12787. }
  12788. if (self._state === 0) {
  12789. self._deferreds.push(deferred);
  12790. return;
  12791. }
  12792. self._handled = true;
  12793. Promise._immediateFn(function () {
  12794. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  12795. if (cb === null) {
  12796. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  12797. return;
  12798. }
  12799. var ret;
  12800. try {
  12801. ret = cb(self._value);
  12802. } catch (e) {
  12803. reject(deferred.promise, e);
  12804. return;
  12805. }
  12806. resolve(deferred.promise, ret);
  12807. });
  12808. }
  12809. function resolve(self, newValue) {
  12810. try {
  12811. if (newValue === self)
  12812. throw new TypeError('A promise cannot be resolved with itself.');
  12813. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  12814. var then = newValue.then;
  12815. if (newValue instanceof Promise) {
  12816. self._state = 3;
  12817. self._value = newValue;
  12818. finale(self);
  12819. return;
  12820. } else if (typeof then === 'function') {
  12821. doResolve(bind(then, newValue), self);
  12822. return;
  12823. }
  12824. }
  12825. self._state = 1;
  12826. self._value = newValue;
  12827. finale(self);
  12828. } catch (e) {
  12829. reject(self, e);
  12830. }
  12831. }
  12832. function reject(self, newValue) {
  12833. self._state = 2;
  12834. self._value = newValue;
  12835. finale(self);
  12836. }
  12837. function finale(self) {
  12838. if (self._state === 2 && self._deferreds.length === 0) {
  12839. Promise._immediateFn(function () {
  12840. if (!self._handled) {
  12841. Promise._unhandledRejectionFn(self._value);
  12842. }
  12843. });
  12844. }
  12845. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  12846. handle(self, self._deferreds[i]);
  12847. }
  12848. self._deferreds = null;
  12849. }
  12850. function Handler(onFulfilled, onRejected, promise) {
  12851. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  12852. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  12853. this.promise = promise;
  12854. }
  12855. function doResolve(fn, self) {
  12856. var done = false;
  12857. try {
  12858. fn(function (value) {
  12859. if (done)
  12860. return;
  12861. done = true;
  12862. resolve(self, value);
  12863. }, function (reason) {
  12864. if (done)
  12865. return;
  12866. done = true;
  12867. reject(self, reason);
  12868. });
  12869. } catch (ex) {
  12870. if (done)
  12871. return;
  12872. done = true;
  12873. reject(self, ex);
  12874. }
  12875. }
  12876. Promise.prototype['catch'] = function (onRejected) {
  12877. return this.then(null, onRejected);
  12878. };
  12879. Promise.prototype.then = function (onFulfilled, onRejected) {
  12880. var prom = new this.constructor(noop);
  12881. handle(this, new Handler(onFulfilled, onRejected, prom));
  12882. return prom;
  12883. };
  12884. Promise.all = function (arr) {
  12885. var args = Array.prototype.slice.call(arr);
  12886. return new Promise(function (resolve, reject) {
  12887. if (args.length === 0)
  12888. return resolve([]);
  12889. var remaining = args.length;
  12890. function res(i, val) {
  12891. try {
  12892. if (val && (typeof val === 'object' || typeof val === 'function')) {
  12893. var then = val.then;
  12894. if (typeof then === 'function') {
  12895. then.call(val, function (val) {
  12896. res(i, val);
  12897. }, reject);
  12898. return;
  12899. }
  12900. }
  12901. args[i] = val;
  12902. if (--remaining === 0) {
  12903. resolve(args);
  12904. }
  12905. } catch (ex) {
  12906. reject(ex);
  12907. }
  12908. }
  12909. for (var i = 0; i < args.length; i++) {
  12910. res(i, args[i]);
  12911. }
  12912. });
  12913. };
  12914. Promise.resolve = function (value) {
  12915. if (value && typeof value === 'object' && value.constructor === Promise) {
  12916. return value;
  12917. }
  12918. return new Promise(function (resolve) {
  12919. resolve(value);
  12920. });
  12921. };
  12922. Promise.reject = function (value) {
  12923. return new Promise(function (resolve, reject) {
  12924. reject(value);
  12925. });
  12926. };
  12927. Promise.race = function (values) {
  12928. return new Promise(function (resolve, reject) {
  12929. for (var i = 0, len = values.length; i < len; i++) {
  12930. values[i].then(resolve, reject);
  12931. }
  12932. });
  12933. };
  12934. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  12935. setImmediate(fn);
  12936. } : function (fn) {
  12937. setTimeoutFunc(fn, 0);
  12938. };
  12939. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  12940. if (typeof console !== 'undefined' && console) {
  12941. console.warn('Possible Unhandled Promise Rejection:', err);
  12942. }
  12943. };
  12944. Promise._setImmediateFn = function _setImmediateFn(fn) {
  12945. Promise._immediateFn = fn;
  12946. };
  12947. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  12948. Promise._unhandledRejectionFn = fn;
  12949. };
  12950. if (typeof module !== 'undefined' && module.exports) {
  12951. module.exports = Promise;
  12952. } else if (!root.Promise) {
  12953. root.Promise = Promise;
  12954. }
  12955. }(this));
  12956. }.call(this, require('timers').setImmediate));
  12957. },
  12958. { 'timers': 3 }
  12959. ],
  12960. 3: [
  12961. function (require, module, exports) {
  12962. (function (setImmediate, clearImmediate) {
  12963. var nextTick = require('process/browser.js').nextTick;
  12964. var apply = Function.prototype.apply;
  12965. var slice = Array.prototype.slice;
  12966. var immediateIds = {};
  12967. var nextImmediateId = 0;
  12968. exports.setTimeout = function () {
  12969. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  12970. };
  12971. exports.setInterval = function () {
  12972. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12973. };
  12974. exports.clearTimeout = exports.clearInterval = function (timeout) {
  12975. timeout.close();
  12976. };
  12977. function Timeout(id, clearFn) {
  12978. this._id = id;
  12979. this._clearFn = clearFn;
  12980. }
  12981. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  12982. };
  12983. Timeout.prototype.close = function () {
  12984. this._clearFn.call(window, this._id);
  12985. };
  12986. exports.enroll = function (item, msecs) {
  12987. clearTimeout(item._idleTimeoutId);
  12988. item._idleTimeout = msecs;
  12989. };
  12990. exports.unenroll = function (item) {
  12991. clearTimeout(item._idleTimeoutId);
  12992. item._idleTimeout = -1;
  12993. };
  12994. exports._unrefActive = exports.active = function (item) {
  12995. clearTimeout(item._idleTimeoutId);
  12996. var msecs = item._idleTimeout;
  12997. if (msecs >= 0) {
  12998. item._idleTimeoutId = setTimeout(function onTimeout() {
  12999. if (item._onTimeout)
  13000. item._onTimeout();
  13001. }, msecs);
  13002. }
  13003. };
  13004. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  13005. var id = nextImmediateId++;
  13006. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  13007. immediateIds[id] = true;
  13008. nextTick(function onNextTick() {
  13009. if (immediateIds[id]) {
  13010. if (args) {
  13011. fn.apply(null, args);
  13012. } else {
  13013. fn.call(null);
  13014. }
  13015. exports.clearImmediate(id);
  13016. }
  13017. });
  13018. return id;
  13019. };
  13020. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  13021. delete immediateIds[id];
  13022. };
  13023. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  13024. },
  13025. {
  13026. 'process/browser.js': 1,
  13027. 'timers': 3
  13028. }
  13029. ],
  13030. 4: [
  13031. function (require, module, exports) {
  13032. var promisePolyfill = require('promise-polyfill');
  13033. var Global = function () {
  13034. if (typeof window !== 'undefined') {
  13035. return window;
  13036. } else {
  13037. return Function('return this;')();
  13038. }
  13039. }();
  13040. module.exports = { boltExport: Global.Promise || promisePolyfill };
  13041. },
  13042. { 'promise-polyfill': 2 }
  13043. ]
  13044. }, {}, [4])(4);
  13045. }));
  13046. }(undefined, exports$1, module, undefined));
  13047. var Promise = module.exports.boltExport;
  13048. var nu$a = function (baseFn) {
  13049. var data = Option.none();
  13050. var callbacks = [];
  13051. var map = function (f) {
  13052. return nu$a(function (nCallback) {
  13053. get(function (data) {
  13054. nCallback(f(data));
  13055. });
  13056. });
  13057. };
  13058. var get = function (nCallback) {
  13059. if (isReady()) {
  13060. call(nCallback);
  13061. } else {
  13062. callbacks.push(nCallback);
  13063. }
  13064. };
  13065. var set = function (x) {
  13066. data = Option.some(x);
  13067. run(callbacks);
  13068. callbacks = [];
  13069. };
  13070. var isReady = function () {
  13071. return data.isSome();
  13072. };
  13073. var run = function (cbs) {
  13074. each(cbs, call);
  13075. };
  13076. var call = function (cb) {
  13077. data.each(function (x) {
  13078. domGlobals.setTimeout(function () {
  13079. cb(x);
  13080. }, 0);
  13081. });
  13082. };
  13083. baseFn(set);
  13084. return {
  13085. get: get,
  13086. map: map,
  13087. isReady: isReady
  13088. };
  13089. };
  13090. var pure$1 = function (a) {
  13091. return nu$a(function (callback) {
  13092. callback(a);
  13093. });
  13094. };
  13095. var LazyValue = {
  13096. nu: nu$a,
  13097. pure: pure$1
  13098. };
  13099. var errorReporter = function (err) {
  13100. domGlobals.setTimeout(function () {
  13101. throw err;
  13102. }, 0);
  13103. };
  13104. var make$3 = function (run) {
  13105. var get = function (callback) {
  13106. run().then(callback, errorReporter);
  13107. };
  13108. var map = function (fab) {
  13109. return make$3(function () {
  13110. return run().then(fab);
  13111. });
  13112. };
  13113. var bind = function (aFutureB) {
  13114. return make$3(function () {
  13115. return run().then(function (v) {
  13116. return aFutureB(v).toPromise();
  13117. });
  13118. });
  13119. };
  13120. var anonBind = function (futureB) {
  13121. return make$3(function () {
  13122. return run().then(function () {
  13123. return futureB.toPromise();
  13124. });
  13125. });
  13126. };
  13127. var toLazy = function () {
  13128. return LazyValue.nu(get);
  13129. };
  13130. var toCached = function () {
  13131. var cache = null;
  13132. return make$3(function () {
  13133. if (cache === null) {
  13134. cache = run();
  13135. }
  13136. return cache;
  13137. });
  13138. };
  13139. var toPromise = run;
  13140. return {
  13141. map: map,
  13142. bind: bind,
  13143. anonBind: anonBind,
  13144. toLazy: toLazy,
  13145. toCached: toCached,
  13146. toPromise: toPromise,
  13147. get: get
  13148. };
  13149. };
  13150. var nu$b = function (baseFn) {
  13151. return make$3(function () {
  13152. return new Promise(baseFn);
  13153. });
  13154. };
  13155. var pure$2 = function (a) {
  13156. return make$3(function () {
  13157. return Promise.resolve(a);
  13158. });
  13159. };
  13160. var Future = {
  13161. nu: nu$b,
  13162. pure: pure$2
  13163. };
  13164. var ariaElements = [
  13165. 'input',
  13166. 'textarea'
  13167. ];
  13168. var isAriaElement = function (elem) {
  13169. var name$1 = name(elem);
  13170. return contains(ariaElements, name$1);
  13171. };
  13172. var markValid = function (component, invalidConfig) {
  13173. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13174. remove$4(elem, invalidConfig.invalidClass);
  13175. invalidConfig.notify.each(function (notifyInfo) {
  13176. if (isAriaElement(component.element())) {
  13177. set$1(component.element(), 'aria-invalid', false);
  13178. }
  13179. notifyInfo.getContainer(component).each(function (container) {
  13180. set(container, notifyInfo.validHtml);
  13181. });
  13182. notifyInfo.onValid(component);
  13183. });
  13184. };
  13185. var markInvalid = function (component, invalidConfig, invalidState, text) {
  13186. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13187. add$2(elem, invalidConfig.invalidClass);
  13188. invalidConfig.notify.each(function (notifyInfo) {
  13189. if (isAriaElement(component.element())) {
  13190. set$1(component.element(), 'aria-invalid', true);
  13191. }
  13192. notifyInfo.getContainer(component).each(function (container) {
  13193. set(container, text);
  13194. });
  13195. notifyInfo.onInvalid(component, text);
  13196. });
  13197. };
  13198. var query = function (component, invalidConfig, invalidState) {
  13199. return invalidConfig.validator.fold(function () {
  13200. return Future.pure(Result.value(true));
  13201. }, function (validatorInfo) {
  13202. return validatorInfo.validate(component);
  13203. });
  13204. };
  13205. var run$1 = function (component, invalidConfig, invalidState) {
  13206. invalidConfig.notify.each(function (notifyInfo) {
  13207. notifyInfo.onValidate(component);
  13208. });
  13209. return query(component, invalidConfig).map(function (valid) {
  13210. if (component.getSystem().isConnected()) {
  13211. return valid.fold(function (err) {
  13212. markInvalid(component, invalidConfig, invalidState, err);
  13213. return Result.error(err);
  13214. }, function (v) {
  13215. markValid(component, invalidConfig);
  13216. return Result.value(v);
  13217. });
  13218. } else {
  13219. return Result.error('No longer in system');
  13220. }
  13221. });
  13222. };
  13223. var isInvalid = function (component, invalidConfig) {
  13224. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13225. return has$2(elem, invalidConfig.invalidClass);
  13226. };
  13227. var InvalidateApis = /*#__PURE__*/Object.freeze({
  13228. __proto__: null,
  13229. markValid: markValid,
  13230. markInvalid: markInvalid,
  13231. query: query,
  13232. run: run$1,
  13233. isInvalid: isInvalid
  13234. });
  13235. var events$a = function (invalidConfig, invalidState) {
  13236. return invalidConfig.validator.map(function (validatorInfo) {
  13237. return derive([run(validatorInfo.onEvent, function (component) {
  13238. run$1(component, invalidConfig, invalidState).get(identity);
  13239. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  13240. run$1(component, invalidConfig, invalidState).get(noop);
  13241. })] : []));
  13242. }).getOr({});
  13243. };
  13244. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  13245. __proto__: null,
  13246. events: events$a
  13247. });
  13248. var InvalidateSchema = [
  13249. strict$1('invalidClass'),
  13250. defaulted$1('getRoot', Option.none),
  13251. optionObjOf('notify', [
  13252. defaulted$1('aria', 'alert'),
  13253. defaulted$1('getContainer', Option.none),
  13254. defaulted$1('validHtml', ''),
  13255. onHandler('onValid'),
  13256. onHandler('onInvalid'),
  13257. onHandler('onValidate')
  13258. ]),
  13259. optionObjOf('validator', [
  13260. strict$1('validate'),
  13261. defaulted$1('onEvent', 'input'),
  13262. defaulted$1('validateOnLoad', true)
  13263. ])
  13264. ];
  13265. var Invalidating = create$1({
  13266. fields: InvalidateSchema,
  13267. name: 'invalidating',
  13268. active: ActiveInvalidate,
  13269. apis: InvalidateApis,
  13270. extra: {
  13271. validation: function (validator) {
  13272. return function (component) {
  13273. var v = Representing.getValue(component);
  13274. return Future.pure(validator(v));
  13275. };
  13276. }
  13277. }
  13278. });
  13279. var exhibit$4 = function (base, tabConfig) {
  13280. return nu$6({
  13281. attributes: wrapAll$1([{
  13282. key: tabConfig.tabAttr,
  13283. value: 'true'
  13284. }])
  13285. });
  13286. };
  13287. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  13288. __proto__: null,
  13289. exhibit: exhibit$4
  13290. });
  13291. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  13292. var Tabstopping = create$1({
  13293. fields: TabstopSchema,
  13294. name: 'tabstopping',
  13295. active: ActiveTabstopping
  13296. });
  13297. var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13298. var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  13299. return FormField.sketch(spec);
  13300. };
  13301. var renderFormField = function (pLabel, pField) {
  13302. return renderFormFieldWith(pLabel, pField, [], []);
  13303. };
  13304. var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13305. return {
  13306. dom: renderFormFieldDomWith(extraClasses),
  13307. components: pLabel.toArray().concat([pField]),
  13308. fieldBehaviours: derive$1(extraBehaviours)
  13309. };
  13310. };
  13311. var renderFormFieldDom = function () {
  13312. return renderFormFieldDomWith([]);
  13313. };
  13314. var renderFormFieldDomWith = function (extraClasses) {
  13315. return {
  13316. tag: 'div',
  13317. classes: ['tox-form__group'].concat(extraClasses)
  13318. };
  13319. };
  13320. var renderLabel = function (label, providersBackstage) {
  13321. return FormField.parts().label({
  13322. dom: {
  13323. tag: 'label',
  13324. classes: ['tox-label'],
  13325. innerHtml: providersBackstage.translate(label)
  13326. }
  13327. });
  13328. };
  13329. var getCoupled = function (component, coupleConfig, coupleState, name) {
  13330. return coupleState.getOrCreate(component, coupleConfig, name);
  13331. };
  13332. var CouplingApis = /*#__PURE__*/Object.freeze({
  13333. __proto__: null,
  13334. getCoupled: getCoupled
  13335. });
  13336. var CouplingSchema = [strictOf('others', setOf$1(Result.value, anyValue$1()))];
  13337. var init$5 = function () {
  13338. var coupled = {};
  13339. var getOrCreate = function (component, coupleConfig, name) {
  13340. var available = keys(coupleConfig.others);
  13341. if (!available) {
  13342. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  13343. } else {
  13344. return get(coupled, name).getOrThunk(function () {
  13345. var builder = get(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  13346. var spec = builder(component);
  13347. var built = component.getSystem().build(spec);
  13348. coupled[name] = built;
  13349. return built;
  13350. });
  13351. }
  13352. };
  13353. var readState = constant({});
  13354. return nu$5({
  13355. readState: readState,
  13356. getOrCreate: getOrCreate
  13357. });
  13358. };
  13359. var CouplingState = /*#__PURE__*/Object.freeze({
  13360. __proto__: null,
  13361. init: init$5
  13362. });
  13363. var Coupling = create$1({
  13364. fields: CouplingSchema,
  13365. name: 'coupling',
  13366. apis: CouplingApis,
  13367. state: CouplingState
  13368. });
  13369. var suffix = constant('sink');
  13370. var partType = constant(optional({
  13371. name: suffix(),
  13372. overrides: constant({
  13373. dom: { tag: 'div' },
  13374. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  13375. events: derive([
  13376. cutter(keydown()),
  13377. cutter(mousedown()),
  13378. cutter(click())
  13379. ])
  13380. })
  13381. }));
  13382. var HighlightOnOpen;
  13383. (function (HighlightOnOpen) {
  13384. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  13385. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  13386. }(HighlightOnOpen || (HighlightOnOpen = {})));
  13387. var getAnchor = function (detail, component) {
  13388. var hotspot = detail.getHotspot(component).getOr(component);
  13389. var anchor = 'hotspot';
  13390. var overrides = detail.getAnchorOverrides();
  13391. return detail.layouts.fold(function () {
  13392. return {
  13393. anchor: anchor,
  13394. hotspot: hotspot,
  13395. overrides: overrides
  13396. };
  13397. }, function (layouts) {
  13398. return {
  13399. anchor: anchor,
  13400. hotspot: hotspot,
  13401. overrides: overrides,
  13402. layouts: layouts
  13403. };
  13404. });
  13405. };
  13406. var fetch = function (detail, mapFetch, component) {
  13407. var fetcher = detail.fetch;
  13408. return fetcher(component).map(mapFetch);
  13409. };
  13410. var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  13411. var futureData = fetch(detail, mapFetch, component);
  13412. var getLazySink = getSink(component, detail);
  13413. return futureData.map(function (tdata) {
  13414. return tdata.bind(function (data) {
  13415. return Option.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  13416. uid: generate$2(''),
  13417. data: data,
  13418. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  13419. onOpenMenu: function (tmenu, menu) {
  13420. var sink = getLazySink().getOrDie();
  13421. Positioning.position(sink, anchor, menu);
  13422. Sandboxing.decloak(sandbox);
  13423. },
  13424. onOpenSubmenu: function (tmenu, item, submenu) {
  13425. var sink = getLazySink().getOrDie();
  13426. Positioning.position(sink, {
  13427. anchor: 'submenu',
  13428. item: item
  13429. }, submenu);
  13430. Sandboxing.decloak(sandbox);
  13431. },
  13432. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  13433. var sink = getLazySink().getOrDie();
  13434. Positioning.position(sink, anchor, primaryMenu);
  13435. each(submenuTriggers, function (st) {
  13436. Positioning.position(sink, {
  13437. anchor: 'submenu',
  13438. item: st.triggeringItem
  13439. }, st.triggeredMenu);
  13440. });
  13441. },
  13442. onEscape: function () {
  13443. Focusing.focus(component);
  13444. Sandboxing.close(sandbox);
  13445. return Option.some(true);
  13446. }
  13447. })));
  13448. });
  13449. });
  13450. };
  13451. var open$1 = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  13452. var anchor = getAnchor(detail, hotspot);
  13453. var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  13454. return processed.map(function (tdata) {
  13455. tdata.fold(function () {
  13456. if (Sandboxing.isOpen(sandbox)) {
  13457. Sandboxing.close(sandbox);
  13458. }
  13459. }, function (data) {
  13460. Sandboxing.cloak(sandbox);
  13461. Sandboxing.open(sandbox, data);
  13462. onOpenSync(sandbox);
  13463. });
  13464. return sandbox;
  13465. });
  13466. };
  13467. var close$1 = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  13468. Sandboxing.close(sandbox);
  13469. return Future.pure(sandbox);
  13470. };
  13471. var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  13472. var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  13473. var showing = Sandboxing.isOpen(sandbox);
  13474. var action = showing ? close$1 : open$1;
  13475. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  13476. };
  13477. var matchWidth = function (hotspot, container, useMinWidth) {
  13478. var menu = Composing.getCurrent(container).getOr(container);
  13479. var buttonWidth = get$7(hotspot.element());
  13480. if (useMinWidth) {
  13481. set$2(menu.element(), 'min-width', buttonWidth + 'px');
  13482. } else {
  13483. set$4(menu.element(), buttonWidth);
  13484. }
  13485. };
  13486. var getSink = function (anyInSystem, sinkDetail) {
  13487. return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  13488. return function () {
  13489. return Result.value(internalSink);
  13490. };
  13491. }).getOrThunk(function () {
  13492. return sinkDetail.lazySink.fold(function () {
  13493. return function () {
  13494. return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  13495. };
  13496. }, function (lazySinkFn) {
  13497. return function () {
  13498. return lazySinkFn(anyInSystem);
  13499. };
  13500. });
  13501. });
  13502. };
  13503. var doRepositionMenus = function (sandbox) {
  13504. Sandboxing.getState(sandbox).each(function (tmenu) {
  13505. tieredMenu.repositionMenus(tmenu);
  13506. });
  13507. };
  13508. var makeSandbox = function (detail, hotspot, extras) {
  13509. var ariaOwner = manager();
  13510. var onOpen = function (component, menu) {
  13511. var anchor = getAnchor(detail, hotspot);
  13512. ariaOwner.link(hotspot.element());
  13513. if (detail.matchWidth) {
  13514. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  13515. }
  13516. detail.onOpen(anchor, component, menu);
  13517. if (extras !== undefined && extras.onOpen !== undefined) {
  13518. extras.onOpen(component, menu);
  13519. }
  13520. };
  13521. var onClose = function (component, menu) {
  13522. ariaOwner.unlink(hotspot.element());
  13523. if (extras !== undefined && extras.onClose !== undefined) {
  13524. extras.onClose(component, menu);
  13525. }
  13526. };
  13527. var lazySink = getSink(hotspot, detail);
  13528. return {
  13529. dom: {
  13530. tag: 'div',
  13531. classes: detail.sandboxClasses,
  13532. attributes: {
  13533. id: ariaOwner.id(),
  13534. role: 'listbox'
  13535. }
  13536. },
  13537. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  13538. Representing.config({
  13539. store: {
  13540. mode: 'memory',
  13541. initialValue: hotspot
  13542. }
  13543. }),
  13544. Sandboxing.config({
  13545. onOpen: onOpen,
  13546. onClose: onClose,
  13547. isPartOf: function (container, data, queryElem) {
  13548. return isPartOf(data, queryElem) || isPartOf(hotspot, queryElem);
  13549. },
  13550. getAttachPoint: function () {
  13551. return lazySink().getOrDie();
  13552. }
  13553. }),
  13554. Composing.config({
  13555. find: function (sandbox) {
  13556. return Sandboxing.getState(sandbox).bind(function (menu) {
  13557. return Composing.getCurrent(menu);
  13558. });
  13559. }
  13560. }),
  13561. Receiving.config({
  13562. channels: __assign(__assign({}, receivingChannel({ isExtraPart: constant(false) })), receivingChannel$1({
  13563. isExtraPart: constant(false),
  13564. doReposition: doRepositionMenus
  13565. }))
  13566. })
  13567. ])
  13568. };
  13569. };
  13570. var repositionMenus = function (comp) {
  13571. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13572. doRepositionMenus(sandbox);
  13573. };
  13574. var sandboxFields = function () {
  13575. return [
  13576. defaulted$1('sandboxClasses', []),
  13577. SketchBehaviours.field('sandboxBehaviours', [
  13578. Composing,
  13579. Receiving,
  13580. Sandboxing,
  13581. Representing
  13582. ])
  13583. ];
  13584. };
  13585. var schema$g = constant([
  13586. strict$1('dom'),
  13587. strict$1('fetch'),
  13588. onHandler('onOpen'),
  13589. onKeyboardHandler('onExecute'),
  13590. defaulted$1('getHotspot', Option.some),
  13591. defaulted$1('getAnchorOverrides', constant({})),
  13592. schema$1(),
  13593. field$1('dropdownBehaviours', [
  13594. Toggling,
  13595. Coupling,
  13596. Keying,
  13597. Focusing
  13598. ]),
  13599. strict$1('toggleClass'),
  13600. defaulted$1('eventOrder', {}),
  13601. option('lazySink'),
  13602. defaulted$1('matchWidth', false),
  13603. defaulted$1('useMinWidth', false),
  13604. option('role')
  13605. ].concat(sandboxFields()));
  13606. var parts$4 = constant([
  13607. external$1({
  13608. schema: [tieredMenuMarkers()],
  13609. name: 'menu',
  13610. defaults: function (detail) {
  13611. return { onExecute: detail.onExecute };
  13612. }
  13613. }),
  13614. partType()
  13615. ]);
  13616. var factory$6 = function (detail, components, _spec, externals) {
  13617. var _a;
  13618. var lookupAttr = function (attr) {
  13619. return get(detail.dom, 'attributes').bind(function (attrs) {
  13620. return get(attrs, attr);
  13621. });
  13622. };
  13623. var switchToMenu = function (sandbox) {
  13624. Sandboxing.getState(sandbox).each(function (tmenu) {
  13625. tieredMenu.highlightPrimary(tmenu);
  13626. });
  13627. };
  13628. var action = function (component) {
  13629. var onOpenSync = switchToMenu;
  13630. togglePopup(detail, function (x) {
  13631. return x;
  13632. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  13633. };
  13634. var apis = {
  13635. expand: function (comp) {
  13636. if (!Toggling.isOn(comp)) {
  13637. togglePopup(detail, function (x) {
  13638. return x;
  13639. }, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  13640. }
  13641. },
  13642. open: function (comp) {
  13643. if (!Toggling.isOn(comp)) {
  13644. togglePopup(detail, function (x) {
  13645. return x;
  13646. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13647. }
  13648. },
  13649. isOpen: Toggling.isOn,
  13650. close: function (comp) {
  13651. if (Toggling.isOn(comp)) {
  13652. togglePopup(detail, function (x) {
  13653. return x;
  13654. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13655. }
  13656. },
  13657. repositionMenus: function (comp) {
  13658. if (Toggling.isOn(comp)) {
  13659. repositionMenus(comp);
  13660. }
  13661. }
  13662. };
  13663. var triggerExecute = function (comp, se) {
  13664. emitExecute(comp);
  13665. return Option.some(true);
  13666. };
  13667. return {
  13668. uid: detail.uid,
  13669. dom: detail.dom,
  13670. components: components,
  13671. behaviours: augment(detail.dropdownBehaviours, [
  13672. Toggling.config({
  13673. toggleClass: detail.toggleClass,
  13674. aria: { mode: 'expanded' }
  13675. }),
  13676. Coupling.config({
  13677. others: {
  13678. sandbox: function (hotspot) {
  13679. return makeSandbox(detail, hotspot, {
  13680. onOpen: function () {
  13681. Toggling.on(hotspot);
  13682. },
  13683. onClose: function () {
  13684. Toggling.off(hotspot);
  13685. }
  13686. });
  13687. }
  13688. }
  13689. }),
  13690. Keying.config({
  13691. mode: 'special',
  13692. onSpace: triggerExecute,
  13693. onEnter: triggerExecute,
  13694. onDown: function (comp, se) {
  13695. if (Dropdown.isOpen(comp)) {
  13696. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13697. switchToMenu(sandbox);
  13698. } else {
  13699. Dropdown.open(comp);
  13700. }
  13701. return Option.some(true);
  13702. },
  13703. onEscape: function (comp, se) {
  13704. if (Dropdown.isOpen(comp)) {
  13705. Dropdown.close(comp);
  13706. return Option.some(true);
  13707. } else {
  13708. return Option.none();
  13709. }
  13710. }
  13711. }),
  13712. Focusing.config({})
  13713. ]),
  13714. events: events$7(Option.some(action)),
  13715. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [
  13716. 'disabling',
  13717. 'toggling',
  13718. 'alloy.base.behaviour'
  13719. ], _a)),
  13720. apis: apis,
  13721. domModification: {
  13722. attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  13723. return {};
  13724. }, function (role) {
  13725. return { role: role };
  13726. })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  13727. }
  13728. };
  13729. };
  13730. var Dropdown = composite$1({
  13731. name: 'Dropdown',
  13732. configFields: schema$g(),
  13733. partFields: parts$4(),
  13734. factory: factory$6,
  13735. apis: {
  13736. open: function (apis, comp) {
  13737. return apis.open(comp);
  13738. },
  13739. expand: function (apis, comp) {
  13740. return apis.expand(comp);
  13741. },
  13742. close: function (apis, comp) {
  13743. return apis.close(comp);
  13744. },
  13745. isOpen: function (apis, comp) {
  13746. return apis.isOpen(comp);
  13747. },
  13748. repositionMenus: function (apis, comp) {
  13749. return apis.repositionMenus(comp);
  13750. }
  13751. }
  13752. });
  13753. var exhibit$5 = function () {
  13754. return nu$6({
  13755. styles: {
  13756. '-webkit-user-select': 'none',
  13757. 'user-select': 'none',
  13758. '-ms-user-select': 'none',
  13759. '-moz-user-select': '-moz-none'
  13760. },
  13761. attributes: { unselectable: 'on' }
  13762. });
  13763. };
  13764. var events$b = function () {
  13765. return derive([abort(selectstart(), constant(true))]);
  13766. };
  13767. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  13768. __proto__: null,
  13769. events: events$b,
  13770. exhibit: exhibit$5
  13771. });
  13772. var Unselecting = create$1({
  13773. fields: [],
  13774. name: 'unselecting',
  13775. active: ActiveUnselecting
  13776. });
  13777. var renderPanelButton = function (spec, sharedBackstage) {
  13778. return Dropdown.sketch({
  13779. dom: spec.dom,
  13780. components: spec.components,
  13781. toggleClass: 'mce-active',
  13782. dropdownBehaviours: derive$1([
  13783. Unselecting.config({}),
  13784. Tabstopping.config({})
  13785. ]),
  13786. layouts: spec.layouts,
  13787. sandboxClasses: ['tox-dialog__popups'],
  13788. lazySink: sharedBackstage.getSink,
  13789. fetch: function (comp) {
  13790. return Future.nu(function (callback) {
  13791. return spec.fetch(callback);
  13792. }).map(function (items) {
  13793. return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  13794. spec.onItemAction(comp, value);
  13795. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  13796. return false;
  13797. }, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  13798. });
  13799. },
  13800. parts: { menu: part(false, 1, spec.presets) }
  13801. });
  13802. };
  13803. var colorInputChangeEvent = generate$1('color-input-change');
  13804. var colorSwatchChangeEvent = generate$1('color-swatch-change');
  13805. var colorPickerCancelEvent = generate$1('color-picker-cancel');
  13806. var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  13807. var pField = FormField.parts().field({
  13808. factory: Input,
  13809. inputClasses: ['tox-textfield'],
  13810. onSetValue: function (c) {
  13811. return Invalidating.run(c).get(function () {
  13812. });
  13813. },
  13814. inputBehaviours: derive$1([
  13815. Tabstopping.config({}),
  13816. Invalidating.config({
  13817. invalidClass: 'tox-textbox-field-invalid',
  13818. getRoot: function (comp) {
  13819. return parent(comp.element());
  13820. },
  13821. notify: {
  13822. onValid: function (comp) {
  13823. var val = Representing.getValue(comp);
  13824. emitWith(comp, colorInputChangeEvent, { color: val });
  13825. }
  13826. },
  13827. validator: {
  13828. validateOnLoad: false,
  13829. validate: function (input) {
  13830. var inputValue = Representing.getValue(input);
  13831. if (inputValue.length === 0) {
  13832. return Future.pure(Result.value(true));
  13833. } else {
  13834. var span = Element.fromTag('span');
  13835. set$2(span, 'background-color', inputValue);
  13836. var res = getRaw(span, 'background-color').fold(function () {
  13837. return Result.error('blah');
  13838. }, function (_) {
  13839. return Result.value(inputValue);
  13840. });
  13841. return Future.pure(res);
  13842. }
  13843. }
  13844. }
  13845. })
  13846. ]),
  13847. selectOnFocus: false
  13848. });
  13849. var pLabel = spec.label.map(function (label) {
  13850. return renderLabel(label, sharedBackstage.providers);
  13851. });
  13852. var emitSwatchChange = function (colorBit, value) {
  13853. emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  13854. };
  13855. var onItemAction = function (comp, value) {
  13856. memColorButton.getOpt(comp).each(function (colorBit) {
  13857. if (value === 'custom') {
  13858. colorInputBackstage.colorPicker(function (valueOpt) {
  13859. valueOpt.fold(function () {
  13860. return emit(colorBit, colorPickerCancelEvent);
  13861. }, function (value) {
  13862. emitSwatchChange(colorBit, value);
  13863. Settings.addColor(value);
  13864. });
  13865. }, '#ffffff');
  13866. } else if (value === 'remove') {
  13867. emitSwatchChange(colorBit, '');
  13868. } else {
  13869. emitSwatchChange(colorBit, value);
  13870. }
  13871. });
  13872. };
  13873. var memColorButton = record(renderPanelButton({
  13874. dom: {
  13875. tag: 'span',
  13876. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  13877. },
  13878. layouts: {
  13879. onRtl: function () {
  13880. return [southeast$1];
  13881. },
  13882. onLtr: function () {
  13883. return [southwest$1];
  13884. }
  13885. },
  13886. components: [],
  13887. fetch: ColorSwatch.getFetch(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  13888. columns: colorInputBackstage.getColorCols(),
  13889. presets: 'color',
  13890. onItemAction: onItemAction
  13891. }, sharedBackstage));
  13892. return FormField.sketch({
  13893. dom: {
  13894. tag: 'div',
  13895. classes: ['tox-form__group']
  13896. },
  13897. components: pLabel.toArray().concat([{
  13898. dom: {
  13899. tag: 'div',
  13900. classes: ['tox-color-input']
  13901. },
  13902. components: [
  13903. pField,
  13904. memColorButton.asSpec()
  13905. ]
  13906. }]),
  13907. fieldBehaviours: derive$1([config('form-field-events', [
  13908. run(colorInputChangeEvent, function (comp, se) {
  13909. memColorButton.getOpt(comp).each(function (colorButton) {
  13910. set$2(colorButton.element(), 'background-color', se.event().color());
  13911. });
  13912. emitWith(comp, formChangeEvent, { name: spec.name });
  13913. }),
  13914. run(colorSwatchChangeEvent, function (comp, se) {
  13915. FormField.getField(comp).each(function (field) {
  13916. Representing.setValue(field, se.event().value());
  13917. Composing.getCurrent(comp).each(Focusing.focus);
  13918. });
  13919. }),
  13920. run(colorPickerCancelEvent, function (comp, se) {
  13921. FormField.getField(comp).each(function (field) {
  13922. Composing.getCurrent(comp).each(Focusing.focus);
  13923. });
  13924. })
  13925. ])])
  13926. });
  13927. };
  13928. var hsvColour = function (hue, saturation, value) {
  13929. return {
  13930. hue: constant(hue),
  13931. saturation: constant(saturation),
  13932. value: constant(value)
  13933. };
  13934. };
  13935. var fromRgb = function (rgbaColour) {
  13936. var h = 0;
  13937. var s = 0;
  13938. var v = 0;
  13939. var r = rgbaColour.red() / 255;
  13940. var g = rgbaColour.green() / 255;
  13941. var b = rgbaColour.blue() / 255;
  13942. var minRGB = Math.min(r, Math.min(g, b));
  13943. var maxRGB = Math.max(r, Math.max(g, b));
  13944. if (minRGB === maxRGB) {
  13945. v = minRGB;
  13946. return hsvColour(0, 0, v * 100);
  13947. }
  13948. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  13949. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  13950. h = 60 * (h - d / (maxRGB - minRGB));
  13951. s = (maxRGB - minRGB) / maxRGB;
  13952. v = maxRGB;
  13953. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  13954. };
  13955. var calcHex = function (value) {
  13956. var hue = (100 - value) / 100 * 360;
  13957. var hsv = hsvColour(hue, 100, 100);
  13958. var rgb = fromHsv(hsv);
  13959. return fromRgba(rgb);
  13960. };
  13961. var fieldsUpdate = constant(generate$1('rgb-hex-update'));
  13962. var sliderUpdate = constant(generate$1('slider-update'));
  13963. var paletteUpdate = constant(generate$1('palette-update'));
  13964. var labelPart = optional({
  13965. schema: [strict$1('dom')],
  13966. name: 'label'
  13967. });
  13968. var edgePart = function (name) {
  13969. return optional({
  13970. name: '' + name + '-edge',
  13971. overrides: function (detail) {
  13972. var action = detail.model.manager.edgeActions[name];
  13973. return action.fold(function () {
  13974. return {};
  13975. }, function (a) {
  13976. return {
  13977. events: derive([
  13978. runActionExtra(touchstart(), function (comp, se, d) {
  13979. return a(comp, d);
  13980. }, [detail]),
  13981. runActionExtra(mousedown(), function (comp, se, d) {
  13982. return a(comp, d);
  13983. }, [detail]),
  13984. runActionExtra(mousemove(), function (comp, se, det) {
  13985. if (det.mouseIsDown.get()) {
  13986. a(comp, det);
  13987. }
  13988. }, [detail])
  13989. ])
  13990. };
  13991. });
  13992. }
  13993. });
  13994. };
  13995. var tlEdgePart = edgePart('top-left');
  13996. var tedgePart = edgePart('top');
  13997. var trEdgePart = edgePart('top-right');
  13998. var redgePart = edgePart('right');
  13999. var brEdgePart = edgePart('bottom-right');
  14000. var bedgePart = edgePart('bottom');
  14001. var blEdgePart = edgePart('bottom-left');
  14002. var ledgePart = edgePart('left');
  14003. var thumbPart = required({
  14004. name: 'thumb',
  14005. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  14006. overrides: function (detail) {
  14007. return {
  14008. events: derive([
  14009. redirectToPart(touchstart(), detail, 'spectrum'),
  14010. redirectToPart(touchmove(), detail, 'spectrum'),
  14011. redirectToPart(touchend(), detail, 'spectrum'),
  14012. redirectToPart(mousedown(), detail, 'spectrum'),
  14013. redirectToPart(mousemove(), detail, 'spectrum'),
  14014. redirectToPart(mouseup(), detail, 'spectrum')
  14015. ])
  14016. };
  14017. }
  14018. });
  14019. var spectrumPart = required({
  14020. schema: [state$1('mouseIsDown', function () {
  14021. return Cell(false);
  14022. })],
  14023. name: 'spectrum',
  14024. overrides: function (detail) {
  14025. var modelDetail = detail.model;
  14026. var model = modelDetail.manager;
  14027. var setValueFrom = function (component, simulatedEvent) {
  14028. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  14029. return model.setValueFrom(component, detail, value);
  14030. });
  14031. };
  14032. return {
  14033. behaviours: derive$1([
  14034. Keying.config({
  14035. mode: 'special',
  14036. onLeft: function (spectrum) {
  14037. return model.onLeft(spectrum, detail);
  14038. },
  14039. onRight: function (spectrum) {
  14040. return model.onRight(spectrum, detail);
  14041. },
  14042. onUp: function (spectrum) {
  14043. return model.onUp(spectrum, detail);
  14044. },
  14045. onDown: function (spectrum) {
  14046. return model.onDown(spectrum, detail);
  14047. }
  14048. }),
  14049. Focusing.config({})
  14050. ]),
  14051. events: derive([
  14052. run(touchstart(), setValueFrom),
  14053. run(touchmove(), setValueFrom),
  14054. run(mousedown(), setValueFrom),
  14055. run(mousemove(), function (spectrum, se) {
  14056. if (detail.mouseIsDown.get()) {
  14057. setValueFrom(spectrum, se);
  14058. }
  14059. })
  14060. ])
  14061. };
  14062. }
  14063. });
  14064. var SliderParts = [
  14065. labelPart,
  14066. ledgePart,
  14067. redgePart,
  14068. tedgePart,
  14069. bedgePart,
  14070. tlEdgePart,
  14071. trEdgePart,
  14072. blEdgePart,
  14073. brEdgePart,
  14074. thumbPart,
  14075. spectrumPart
  14076. ];
  14077. var _sliderChangeEvent = 'slider.change.value';
  14078. var sliderChangeEvent = constant(_sliderChangeEvent);
  14079. var isTouchEvent = function (evt) {
  14080. return evt.type.indexOf('touch') !== -1;
  14081. };
  14082. var getEventSource = function (simulatedEvent) {
  14083. var evt = simulatedEvent.event().raw();
  14084. if (isTouchEvent(evt)) {
  14085. var touchEvent = evt;
  14086. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  14087. return Position(t.clientX, t.clientY);
  14088. }) : Option.none();
  14089. } else {
  14090. var mouseEvent = evt;
  14091. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  14092. return Position(me.clientX, me.clientY);
  14093. }) : Option.none();
  14094. }
  14095. };
  14096. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  14097. var minX = function (detail) {
  14098. return detail.model.minX;
  14099. };
  14100. var minY = function (detail) {
  14101. return detail.model.minY;
  14102. };
  14103. var min1X = function (detail) {
  14104. return detail.model.minX - 1;
  14105. };
  14106. var min1Y = function (detail) {
  14107. return detail.model.minY - 1;
  14108. };
  14109. var maxX = function (detail) {
  14110. return detail.model.maxX;
  14111. };
  14112. var maxY = function (detail) {
  14113. return detail.model.maxY;
  14114. };
  14115. var max1X = function (detail) {
  14116. return detail.model.maxX + 1;
  14117. };
  14118. var max1Y = function (detail) {
  14119. return detail.model.maxY + 1;
  14120. };
  14121. var range$2 = function (detail, max, min) {
  14122. return max(detail) - min(detail);
  14123. };
  14124. var xRange = function (detail) {
  14125. return range$2(detail, maxX, minX);
  14126. };
  14127. var yRange = function (detail) {
  14128. return range$2(detail, maxY, minY);
  14129. };
  14130. var halfX = function (detail) {
  14131. return xRange(detail) / 2;
  14132. };
  14133. var halfY = function (detail) {
  14134. return yRange(detail) / 2;
  14135. };
  14136. var step = function (detail) {
  14137. return detail.stepSize;
  14138. };
  14139. var snap = function (detail) {
  14140. return detail.snapToGrid;
  14141. };
  14142. var snapStart = function (detail) {
  14143. return detail.snapStart;
  14144. };
  14145. var rounded = function (detail) {
  14146. return detail.rounded;
  14147. };
  14148. var hasEdge = function (detail, edgeName) {
  14149. return detail[edgeName + '-edge'] !== undefined;
  14150. };
  14151. var hasLEdge = function (detail) {
  14152. return hasEdge(detail, l);
  14153. };
  14154. var hasREdge = function (detail) {
  14155. return hasEdge(detail, r$1);
  14156. };
  14157. var hasTEdge = function (detail) {
  14158. return hasEdge(detail, t);
  14159. };
  14160. var hasBEdge = function (detail) {
  14161. return hasEdge(detail, b);
  14162. };
  14163. var currentValue = function (detail) {
  14164. return detail.model.value.get();
  14165. };
  14166. var xValue = function (x) {
  14167. return { x: constant(x) };
  14168. };
  14169. var yValue = function (y) {
  14170. return { y: constant(y) };
  14171. };
  14172. var xyValue = function (x, y) {
  14173. return {
  14174. x: constant(x),
  14175. y: constant(y)
  14176. };
  14177. };
  14178. var fireSliderChange = function (component, value) {
  14179. emitWith(component, sliderChangeEvent(), { value: value });
  14180. };
  14181. var setToTLEdgeXY = function (edge, detail) {
  14182. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  14183. };
  14184. var setToTEdge = function (edge, detail) {
  14185. fireSliderChange(edge, yValue(min1Y(detail)));
  14186. };
  14187. var setToTEdgeXY = function (edge, detail) {
  14188. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  14189. };
  14190. var setToTREdgeXY = function (edge, detail) {
  14191. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  14192. };
  14193. var setToREdge = function (edge, detail) {
  14194. fireSliderChange(edge, xValue(max1X(detail)));
  14195. };
  14196. var setToREdgeXY = function (edge, detail) {
  14197. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  14198. };
  14199. var setToBREdgeXY = function (edge, detail) {
  14200. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  14201. };
  14202. var setToBEdge = function (edge, detail) {
  14203. fireSliderChange(edge, yValue(max1Y(detail)));
  14204. };
  14205. var setToBEdgeXY = function (edge, detail) {
  14206. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  14207. };
  14208. var setToBLEdgeXY = function (edge, detail) {
  14209. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  14210. };
  14211. var setToLEdge = function (edge, detail) {
  14212. fireSliderChange(edge, xValue(min1X(detail)));
  14213. };
  14214. var setToLEdgeXY = function (edge, detail) {
  14215. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  14216. };
  14217. var reduceBy = function (value, min, max, step) {
  14218. if (value < min) {
  14219. return value;
  14220. } else if (value > max) {
  14221. return max;
  14222. } else if (value === min) {
  14223. return min - 1;
  14224. } else {
  14225. return Math.max(min, value - step);
  14226. }
  14227. };
  14228. var increaseBy = function (value, min, max, step) {
  14229. if (value > max) {
  14230. return value;
  14231. } else if (value < min) {
  14232. return min;
  14233. } else if (value === max) {
  14234. return max + 1;
  14235. } else {
  14236. return Math.min(max, value + step);
  14237. }
  14238. };
  14239. var capValue = function (value, min, max) {
  14240. return Math.max(min, Math.min(max, value));
  14241. };
  14242. var snapValueOf = function (value, min, max, step, snapStart) {
  14243. return snapStart.fold(function () {
  14244. var initValue = value - min;
  14245. var extraValue = Math.round(initValue / step) * step;
  14246. return capValue(min + extraValue, min - 1, max + 1);
  14247. }, function (start) {
  14248. var remainder = (value - start) % step;
  14249. var adjustment = Math.round(remainder / step);
  14250. var rawSteps = Math.floor((value - start) / step);
  14251. var maxSteps = Math.floor((max - start) / step);
  14252. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  14253. var r = start + numSteps * step;
  14254. return Math.max(start, r);
  14255. });
  14256. };
  14257. var findOffsetOf = function (value, min, max) {
  14258. return Math.min(max, Math.max(value, min)) - min;
  14259. };
  14260. var findValueOf = function (args) {
  14261. 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;
  14262. var capMin = hasMinEdge ? min - 1 : min;
  14263. var capMax = hasMaxEdge ? max + 1 : max;
  14264. if (value < minBound) {
  14265. return capMin;
  14266. } else if (value > maxBound) {
  14267. return capMax;
  14268. } else {
  14269. var offset = findOffsetOf(value, minBound, maxBound);
  14270. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  14271. if (snap && newValue >= min && newValue <= max) {
  14272. return snapValueOf(newValue, min, max, step, snapStart);
  14273. } else if (rounded) {
  14274. return Math.round(newValue);
  14275. } else {
  14276. return newValue;
  14277. }
  14278. }
  14279. };
  14280. var findOffsetOfValue = function (args) {
  14281. 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;
  14282. if (value < min) {
  14283. return hasMinEdge ? 0 : centerMinEdge;
  14284. } else if (value > max) {
  14285. return hasMaxEdge ? maxBound : centerMaxEdge;
  14286. } else {
  14287. return (value - min) / range * maxOffset;
  14288. }
  14289. };
  14290. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  14291. var getBounds$1 = function (component) {
  14292. return component.element().dom().getBoundingClientRect();
  14293. };
  14294. var getBoundsProperty = function (bounds, property) {
  14295. return bounds[property];
  14296. };
  14297. var getMinXBounds = function (component) {
  14298. var bounds = getBounds$1(component);
  14299. return getBoundsProperty(bounds, left);
  14300. };
  14301. var getMaxXBounds = function (component) {
  14302. var bounds = getBounds$1(component);
  14303. return getBoundsProperty(bounds, right);
  14304. };
  14305. var getMinYBounds = function (component) {
  14306. var bounds = getBounds$1(component);
  14307. return getBoundsProperty(bounds, top);
  14308. };
  14309. var getMaxYBounds = function (component) {
  14310. var bounds = getBounds$1(component);
  14311. return getBoundsProperty(bounds, bottom);
  14312. };
  14313. var getXScreenRange = function (component) {
  14314. var bounds = getBounds$1(component);
  14315. return getBoundsProperty(bounds, width);
  14316. };
  14317. var getYScreenRange = function (component) {
  14318. var bounds = getBounds$1(component);
  14319. return getBoundsProperty(bounds, height);
  14320. };
  14321. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  14322. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  14323. };
  14324. var getXCenterOffSetOf = function (component, spectrum) {
  14325. var componentBounds = getBounds$1(component);
  14326. var spectrumBounds = getBounds$1(spectrum);
  14327. var componentMinEdge = getBoundsProperty(componentBounds, left);
  14328. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  14329. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  14330. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14331. };
  14332. var getYCenterOffSetOf = function (component, spectrum) {
  14333. var componentBounds = getBounds$1(component);
  14334. var spectrumBounds = getBounds$1(spectrum);
  14335. var componentMinEdge = getBoundsProperty(componentBounds, top);
  14336. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  14337. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  14338. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14339. };
  14340. var fireSliderChange$1 = function (spectrum, value) {
  14341. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14342. };
  14343. var sliderValue = function (x) {
  14344. return { x: constant(x) };
  14345. };
  14346. var findValueOfOffset = function (spectrum, detail, left) {
  14347. var args = {
  14348. min: minX(detail),
  14349. max: maxX(detail),
  14350. range: xRange(detail),
  14351. value: left,
  14352. step: step(detail),
  14353. snap: snap(detail),
  14354. snapStart: snapStart(detail),
  14355. rounded: rounded(detail),
  14356. hasMinEdge: hasLEdge(detail),
  14357. hasMaxEdge: hasREdge(detail),
  14358. minBound: getMinXBounds(spectrum),
  14359. maxBound: getMaxXBounds(spectrum),
  14360. screenRange: getXScreenRange(spectrum)
  14361. };
  14362. return findValueOf(args);
  14363. };
  14364. var setValueFrom = function (spectrum, detail, value) {
  14365. var xValue = findValueOfOffset(spectrum, detail, value);
  14366. var sliderVal = sliderValue(xValue);
  14367. fireSliderChange$1(spectrum, sliderVal);
  14368. return xValue;
  14369. };
  14370. var setToMin = function (spectrum, detail) {
  14371. var min = minX(detail);
  14372. fireSliderChange$1(spectrum, sliderValue(min));
  14373. };
  14374. var setToMax = function (spectrum, detail) {
  14375. var max = maxX(detail);
  14376. fireSliderChange$1(spectrum, sliderValue(max));
  14377. };
  14378. var moveBy = function (direction, spectrum, detail) {
  14379. var f = direction > 0 ? increaseBy : reduceBy;
  14380. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  14381. fireSliderChange$1(spectrum, sliderValue(xValue));
  14382. return Option.some(xValue);
  14383. };
  14384. var handleMovement = function (direction) {
  14385. return function (spectrum, detail) {
  14386. return moveBy(direction, spectrum, detail).map(function () {
  14387. return true;
  14388. });
  14389. };
  14390. };
  14391. var getValueFromEvent = function (simulatedEvent) {
  14392. var pos = getEventSource(simulatedEvent);
  14393. return pos.map(function (p) {
  14394. return p.left();
  14395. });
  14396. };
  14397. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  14398. var minOffset = 0;
  14399. var maxOffset = getXScreenRange(spectrum);
  14400. var centerMinEdge = minEdge.bind(function (edge) {
  14401. return Option.some(getXCenterOffSetOf(edge, spectrum));
  14402. }).getOr(minOffset);
  14403. var centerMaxEdge = maxEdge.bind(function (edge) {
  14404. return Option.some(getXCenterOffSetOf(edge, spectrum));
  14405. }).getOr(maxOffset);
  14406. var args = {
  14407. min: minX(detail),
  14408. max: maxX(detail),
  14409. range: xRange(detail),
  14410. value: value,
  14411. hasMinEdge: hasLEdge(detail),
  14412. hasMaxEdge: hasREdge(detail),
  14413. minBound: getMinXBounds(spectrum),
  14414. minOffset: minOffset,
  14415. maxBound: getMaxXBounds(spectrum),
  14416. maxOffset: maxOffset,
  14417. centerMinEdge: centerMinEdge,
  14418. centerMaxEdge: centerMaxEdge
  14419. };
  14420. return findOffsetOfValue(args);
  14421. };
  14422. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14423. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  14424. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  14425. };
  14426. var setPositionFromValue = function (slider, thumb, detail, edges) {
  14427. var value = currentValue(detail);
  14428. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14429. var thumbRadius = get$7(thumb.element()) / 2;
  14430. set$2(thumb.element(), 'left', pos - thumbRadius + 'px');
  14431. };
  14432. var onLeft = handleMovement(-1);
  14433. var onRight = handleMovement(1);
  14434. var onUp = Option.none;
  14435. var onDown = Option.none;
  14436. var edgeActions = {
  14437. 'top-left': Option.none(),
  14438. 'top': Option.none(),
  14439. 'top-right': Option.none(),
  14440. 'right': Option.some(setToREdge),
  14441. 'bottom-right': Option.none(),
  14442. 'bottom': Option.none(),
  14443. 'bottom-left': Option.none(),
  14444. 'left': Option.some(setToLEdge)
  14445. };
  14446. var HorizontalModel = /*#__PURE__*/Object.freeze({
  14447. __proto__: null,
  14448. setValueFrom: setValueFrom,
  14449. setToMin: setToMin,
  14450. setToMax: setToMax,
  14451. findValueOfOffset: findValueOfOffset,
  14452. getValueFromEvent: getValueFromEvent,
  14453. findPositionOfValue: findPositionOfValue,
  14454. setPositionFromValue: setPositionFromValue,
  14455. onLeft: onLeft,
  14456. onRight: onRight,
  14457. onUp: onUp,
  14458. onDown: onDown,
  14459. edgeActions: edgeActions
  14460. });
  14461. var fireSliderChange$2 = function (spectrum, value) {
  14462. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14463. };
  14464. var sliderValue$1 = function (y) {
  14465. return { y: constant(y) };
  14466. };
  14467. var findValueOfOffset$1 = function (spectrum, detail, top) {
  14468. var args = {
  14469. min: minY(detail),
  14470. max: maxY(detail),
  14471. range: yRange(detail),
  14472. value: top,
  14473. step: step(detail),
  14474. snap: snap(detail),
  14475. snapStart: snapStart(detail),
  14476. rounded: rounded(detail),
  14477. hasMinEdge: hasTEdge(detail),
  14478. hasMaxEdge: hasBEdge(detail),
  14479. minBound: getMinYBounds(spectrum),
  14480. maxBound: getMaxYBounds(spectrum),
  14481. screenRange: getYScreenRange(spectrum)
  14482. };
  14483. return findValueOf(args);
  14484. };
  14485. var setValueFrom$1 = function (spectrum, detail, value) {
  14486. var yValue = findValueOfOffset$1(spectrum, detail, value);
  14487. var sliderVal = sliderValue$1(yValue);
  14488. fireSliderChange$2(spectrum, sliderVal);
  14489. return yValue;
  14490. };
  14491. var setToMin$1 = function (spectrum, detail) {
  14492. var min = minY(detail);
  14493. fireSliderChange$2(spectrum, sliderValue$1(min));
  14494. };
  14495. var setToMax$1 = function (spectrum, detail) {
  14496. var max = maxY(detail);
  14497. fireSliderChange$2(spectrum, sliderValue$1(max));
  14498. };
  14499. var moveBy$1 = function (direction, spectrum, detail) {
  14500. var f = direction > 0 ? increaseBy : reduceBy;
  14501. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  14502. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  14503. return Option.some(yValue);
  14504. };
  14505. var handleMovement$1 = function (direction) {
  14506. return function (spectrum, detail) {
  14507. return moveBy$1(direction, spectrum, detail).map(function () {
  14508. return true;
  14509. });
  14510. };
  14511. };
  14512. var getValueFromEvent$1 = function (simulatedEvent) {
  14513. var pos = getEventSource(simulatedEvent);
  14514. return pos.map(function (p) {
  14515. return p.top();
  14516. });
  14517. };
  14518. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  14519. var minOffset = 0;
  14520. var maxOffset = getYScreenRange(spectrum);
  14521. var centerMinEdge = minEdge.bind(function (edge) {
  14522. return Option.some(getYCenterOffSetOf(edge, spectrum));
  14523. }).getOr(minOffset);
  14524. var centerMaxEdge = maxEdge.bind(function (edge) {
  14525. return Option.some(getYCenterOffSetOf(edge, spectrum));
  14526. }).getOr(maxOffset);
  14527. var args = {
  14528. min: minY(detail),
  14529. max: maxY(detail),
  14530. range: yRange(detail),
  14531. value: value,
  14532. hasMinEdge: hasTEdge(detail),
  14533. hasMaxEdge: hasBEdge(detail),
  14534. minBound: getMinYBounds(spectrum),
  14535. minOffset: minOffset,
  14536. maxBound: getMaxYBounds(spectrum),
  14537. maxOffset: maxOffset,
  14538. centerMinEdge: centerMinEdge,
  14539. centerMaxEdge: centerMaxEdge
  14540. };
  14541. return findOffsetOfValue(args);
  14542. };
  14543. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14544. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  14545. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  14546. };
  14547. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  14548. var value = currentValue(detail);
  14549. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14550. var thumbRadius = get$6(thumb.element()) / 2;
  14551. set$2(thumb.element(), 'top', pos - thumbRadius + 'px');
  14552. };
  14553. var onLeft$1 = Option.none;
  14554. var onRight$1 = Option.none;
  14555. var onUp$1 = handleMovement$1(-1);
  14556. var onDown$1 = handleMovement$1(1);
  14557. var edgeActions$1 = {
  14558. 'top-left': Option.none(),
  14559. 'top': Option.some(setToTEdge),
  14560. 'top-right': Option.none(),
  14561. 'right': Option.none(),
  14562. 'bottom-right': Option.none(),
  14563. 'bottom': Option.some(setToBEdge),
  14564. 'bottom-left': Option.none(),
  14565. 'left': Option.none()
  14566. };
  14567. var VerticalModel = /*#__PURE__*/Object.freeze({
  14568. __proto__: null,
  14569. setValueFrom: setValueFrom$1,
  14570. setToMin: setToMin$1,
  14571. setToMax: setToMax$1,
  14572. findValueOfOffset: findValueOfOffset$1,
  14573. getValueFromEvent: getValueFromEvent$1,
  14574. findPositionOfValue: findPositionOfValue$1,
  14575. setPositionFromValue: setPositionFromValue$1,
  14576. onLeft: onLeft$1,
  14577. onRight: onRight$1,
  14578. onUp: onUp$1,
  14579. onDown: onDown$1,
  14580. edgeActions: edgeActions$1
  14581. });
  14582. var fireSliderChange$3 = function (spectrum, value) {
  14583. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14584. };
  14585. var sliderValue$2 = function (x, y) {
  14586. return {
  14587. x: constant(x),
  14588. y: constant(y)
  14589. };
  14590. };
  14591. var setValueFrom$2 = function (spectrum, detail, value) {
  14592. var xValue = findValueOfOffset(spectrum, detail, value.left());
  14593. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  14594. var val = sliderValue$2(xValue, yValue);
  14595. fireSliderChange$3(spectrum, val);
  14596. return val;
  14597. };
  14598. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  14599. var f = direction > 0 ? increaseBy : reduceBy;
  14600. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  14601. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  14602. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  14603. return Option.some(xValue);
  14604. };
  14605. var handleMovement$2 = function (direction, isVerticalMovement) {
  14606. return function (spectrum, detail) {
  14607. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  14608. return true;
  14609. });
  14610. };
  14611. };
  14612. var setToMin$2 = function (spectrum, detail) {
  14613. var mX = minX(detail);
  14614. var mY = minY(detail);
  14615. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14616. };
  14617. var setToMax$2 = function (spectrum, detail) {
  14618. var mX = maxX(detail);
  14619. var mY = maxY(detail);
  14620. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14621. };
  14622. var getValueFromEvent$2 = function (simulatedEvent) {
  14623. return getEventSource(simulatedEvent);
  14624. };
  14625. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  14626. var value = currentValue(detail);
  14627. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14628. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14629. var thumbXRadius = get$7(thumb.element()) / 2;
  14630. var thumbYRadius = get$6(thumb.element()) / 2;
  14631. set$2(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  14632. set$2(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  14633. };
  14634. var onLeft$2 = handleMovement$2(-1, false);
  14635. var onRight$2 = handleMovement$2(1, false);
  14636. var onUp$2 = handleMovement$2(-1, true);
  14637. var onDown$2 = handleMovement$2(1, true);
  14638. var edgeActions$2 = {
  14639. 'top-left': Option.some(setToTLEdgeXY),
  14640. 'top': Option.some(setToTEdgeXY),
  14641. 'top-right': Option.some(setToTREdgeXY),
  14642. 'right': Option.some(setToREdgeXY),
  14643. 'bottom-right': Option.some(setToBREdgeXY),
  14644. 'bottom': Option.some(setToBEdgeXY),
  14645. 'bottom-left': Option.some(setToBLEdgeXY),
  14646. 'left': Option.some(setToLEdgeXY)
  14647. };
  14648. var TwoDModel = /*#__PURE__*/Object.freeze({
  14649. __proto__: null,
  14650. setValueFrom: setValueFrom$2,
  14651. setToMin: setToMin$2,
  14652. setToMax: setToMax$2,
  14653. getValueFromEvent: getValueFromEvent$2,
  14654. setPositionFromValue: setPositionFromValue$2,
  14655. onLeft: onLeft$2,
  14656. onRight: onRight$2,
  14657. onUp: onUp$2,
  14658. onDown: onDown$2,
  14659. edgeActions: edgeActions$2
  14660. });
  14661. var SliderSchema = [
  14662. defaulted$1('stepSize', 1),
  14663. defaulted$1('onChange', noop),
  14664. defaulted$1('onChoose', noop),
  14665. defaulted$1('onInit', noop),
  14666. defaulted$1('onDragStart', noop),
  14667. defaulted$1('onDragEnd', noop),
  14668. defaulted$1('snapToGrid', false),
  14669. defaulted$1('rounded', true),
  14670. option('snapStart'),
  14671. strictOf('model', choose$1('mode', {
  14672. x: [
  14673. defaulted$1('minX', 0),
  14674. defaulted$1('maxX', 100),
  14675. state$1('value', function (spec) {
  14676. return Cell(spec.mode.minX);
  14677. }),
  14678. strict$1('getInitialValue'),
  14679. output('manager', HorizontalModel)
  14680. ],
  14681. y: [
  14682. defaulted$1('minY', 0),
  14683. defaulted$1('maxY', 100),
  14684. state$1('value', function (spec) {
  14685. return Cell(spec.mode.minY);
  14686. }),
  14687. strict$1('getInitialValue'),
  14688. output('manager', VerticalModel)
  14689. ],
  14690. xy: [
  14691. defaulted$1('minX', 0),
  14692. defaulted$1('maxX', 100),
  14693. defaulted$1('minY', 0),
  14694. defaulted$1('maxY', 100),
  14695. state$1('value', function (spec) {
  14696. return Cell({
  14697. x: constant(spec.mode.minX),
  14698. y: constant(spec.mode.minY)
  14699. });
  14700. }),
  14701. strict$1('getInitialValue'),
  14702. output('manager', TwoDModel)
  14703. ]
  14704. })),
  14705. field$1('sliderBehaviours', [
  14706. Keying,
  14707. Representing
  14708. ]),
  14709. state$1('mouseIsDown', function () {
  14710. return Cell(false);
  14711. })
  14712. ];
  14713. var sketch = function (detail, components, _spec, _externals) {
  14714. var _a;
  14715. var getThumb = function (component) {
  14716. return getPartOrDie(component, detail, 'thumb');
  14717. };
  14718. var getSpectrum = function (component) {
  14719. return getPartOrDie(component, detail, 'spectrum');
  14720. };
  14721. var getLeftEdge = function (component) {
  14722. return getPart(component, detail, 'left-edge');
  14723. };
  14724. var getRightEdge = function (component) {
  14725. return getPart(component, detail, 'right-edge');
  14726. };
  14727. var getTopEdge = function (component) {
  14728. return getPart(component, detail, 'top-edge');
  14729. };
  14730. var getBottomEdge = function (component) {
  14731. return getPart(component, detail, 'bottom-edge');
  14732. };
  14733. var modelDetail = detail.model;
  14734. var model = modelDetail.manager;
  14735. var refresh = function (slider, thumb) {
  14736. model.setPositionFromValue(slider, thumb, detail, {
  14737. getLeftEdge: getLeftEdge,
  14738. getRightEdge: getRightEdge,
  14739. getTopEdge: getTopEdge,
  14740. getBottomEdge: getBottomEdge,
  14741. getSpectrum: getSpectrum
  14742. });
  14743. };
  14744. var changeValue = function (slider, newValue) {
  14745. modelDetail.value.set(newValue);
  14746. var thumb = getThumb(slider);
  14747. refresh(slider, thumb);
  14748. detail.onChange(slider, thumb, newValue);
  14749. return Option.some(true);
  14750. };
  14751. var resetToMin = function (slider) {
  14752. model.setToMin(slider, detail);
  14753. };
  14754. var resetToMax = function (slider) {
  14755. model.setToMax(slider, detail);
  14756. };
  14757. var choose = function (slider) {
  14758. var fireOnChoose = function () {
  14759. getPart(slider, detail, 'thumb').each(function (thumb) {
  14760. var value = modelDetail.value.get();
  14761. detail.onChoose(slider, thumb, value);
  14762. });
  14763. };
  14764. var wasDown = detail.mouseIsDown.get();
  14765. detail.mouseIsDown.set(false);
  14766. if (wasDown) {
  14767. fireOnChoose();
  14768. }
  14769. };
  14770. var onDragStart = function (slider, simulatedEvent) {
  14771. simulatedEvent.stop();
  14772. detail.mouseIsDown.set(true);
  14773. detail.onDragStart(slider, getThumb(slider));
  14774. };
  14775. var onDragEnd = function (slider, simulatedEvent) {
  14776. simulatedEvent.stop();
  14777. detail.onDragEnd(slider, getThumb(slider));
  14778. choose(slider);
  14779. };
  14780. return {
  14781. uid: detail.uid,
  14782. dom: detail.dom,
  14783. components: components,
  14784. behaviours: augment(detail.sliderBehaviours, [
  14785. Keying.config({
  14786. mode: 'special',
  14787. focusIn: function (slider) {
  14788. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  14789. }
  14790. }),
  14791. Representing.config({
  14792. store: {
  14793. mode: 'manual',
  14794. getValue: function (_) {
  14795. return modelDetail.value.get();
  14796. }
  14797. }
  14798. }),
  14799. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  14800. ]),
  14801. events: derive([
  14802. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  14803. changeValue(slider, simulatedEvent.event().value());
  14804. }),
  14805. runOnAttached(function (slider, simulatedEvent) {
  14806. var getInitial = modelDetail.getInitialValue();
  14807. modelDetail.value.set(getInitial);
  14808. var thumb = getThumb(slider);
  14809. refresh(slider, thumb);
  14810. var spectrum = getSpectrum(slider);
  14811. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  14812. }),
  14813. run(touchstart(), onDragStart),
  14814. run(touchend(), onDragEnd),
  14815. run(mousedown(), onDragStart),
  14816. run(mouseup(), onDragEnd)
  14817. ]),
  14818. apis: {
  14819. resetToMin: resetToMin,
  14820. resetToMax: resetToMax,
  14821. changeValue: changeValue,
  14822. refresh: refresh
  14823. },
  14824. domModification: { styles: { position: 'relative' } }
  14825. };
  14826. };
  14827. var Slider = composite$1({
  14828. name: 'Slider',
  14829. configFields: SliderSchema,
  14830. partFields: SliderParts,
  14831. factory: sketch,
  14832. apis: {
  14833. resetToMin: function (apis, slider) {
  14834. apis.resetToMin(slider);
  14835. },
  14836. resetToMax: function (apis, slider) {
  14837. apis.resetToMax(slider);
  14838. },
  14839. refresh: function (apis, slider) {
  14840. apis.refresh(slider);
  14841. }
  14842. }
  14843. });
  14844. var sliderFactory = function (translate, getClass) {
  14845. var spectrum = Slider.parts().spectrum({
  14846. dom: {
  14847. tag: 'div',
  14848. classes: [getClass('hue-slider-spectrum')],
  14849. attributes: { role: 'presentation' }
  14850. }
  14851. });
  14852. var thumb = Slider.parts().thumb({
  14853. dom: {
  14854. tag: 'div',
  14855. classes: [getClass('hue-slider-thumb')],
  14856. attributes: { role: 'presentation' }
  14857. }
  14858. });
  14859. return Slider.sketch({
  14860. dom: {
  14861. tag: 'div',
  14862. classes: [getClass('hue-slider')],
  14863. attributes: { role: 'presentation' }
  14864. },
  14865. rounded: false,
  14866. model: {
  14867. mode: 'y',
  14868. getInitialValue: constant({ y: constant(0) })
  14869. },
  14870. components: [
  14871. spectrum,
  14872. thumb
  14873. ],
  14874. sliderBehaviours: derive$1([Focusing.config({})]),
  14875. onChange: function (slider, _thumb, value) {
  14876. emitWith(slider, sliderUpdate(), { value: value });
  14877. }
  14878. });
  14879. };
  14880. var owner$3 = 'form';
  14881. var schema$h = [field$1('formBehaviours', [Representing])];
  14882. var getPartName = function (name) {
  14883. return '<alloy.field.' + name + '>';
  14884. };
  14885. var sketch$1 = function (fSpec) {
  14886. var parts = function () {
  14887. var record = [];
  14888. var field = function (name, config) {
  14889. record.push(name);
  14890. return generateOne(owner$3, getPartName(name), config);
  14891. };
  14892. return {
  14893. field: field,
  14894. record: function () {
  14895. return record;
  14896. }
  14897. };
  14898. }();
  14899. var spec = fSpec(parts);
  14900. var partNames = parts.record();
  14901. var fieldParts = map(partNames, function (n) {
  14902. return required({
  14903. name: n,
  14904. pname: getPartName(n)
  14905. });
  14906. });
  14907. return composite(owner$3, schema$h, fieldParts, make$4, spec);
  14908. };
  14909. var toResult$1 = function (o, e) {
  14910. return o.fold(function () {
  14911. return Result.error(e);
  14912. }, Result.value);
  14913. };
  14914. var make$4 = function (detail, components) {
  14915. return {
  14916. uid: detail.uid,
  14917. dom: detail.dom,
  14918. components: components,
  14919. behaviours: augment(detail.formBehaviours, [Representing.config({
  14920. store: {
  14921. mode: 'manual',
  14922. getValue: function (form) {
  14923. var resPs = getAllParts(form, detail);
  14924. return map$1(resPs, function (resPThunk, pName) {
  14925. return resPThunk().bind(function (v) {
  14926. var opt = Composing.getCurrent(v);
  14927. return toResult$1(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element())));
  14928. }).map(Representing.getValue);
  14929. });
  14930. },
  14931. setValue: function (form, values) {
  14932. each$1(values, function (newValue, key) {
  14933. getPart(form, detail, key).each(function (wrapper) {
  14934. Composing.getCurrent(wrapper).each(function (field) {
  14935. Representing.setValue(field, newValue);
  14936. });
  14937. });
  14938. });
  14939. }
  14940. }
  14941. })]),
  14942. apis: {
  14943. getField: function (form, key) {
  14944. return getPart(form, detail, key).bind(Composing.getCurrent);
  14945. }
  14946. }
  14947. };
  14948. };
  14949. var Form = {
  14950. getField: makeApi(function (apis, component, key) {
  14951. return apis.getField(component, key);
  14952. }),
  14953. sketch: sketch$1
  14954. };
  14955. var validInput = generate$1('valid-input');
  14956. var invalidInput = generate$1('invalid-input');
  14957. var validatingInput = generate$1('validating-input');
  14958. var translatePrefix = 'colorcustom.rgb.';
  14959. var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  14960. var invalidation = function (label, isValid) {
  14961. return Invalidating.config({
  14962. invalidClass: getClass('invalid'),
  14963. notify: {
  14964. onValidate: function (comp) {
  14965. emitWith(comp, validatingInput, { type: label });
  14966. },
  14967. onValid: function (comp) {
  14968. emitWith(comp, validInput, {
  14969. type: label,
  14970. value: Representing.getValue(comp)
  14971. });
  14972. },
  14973. onInvalid: function (comp) {
  14974. emitWith(comp, invalidInput, {
  14975. type: label,
  14976. value: Representing.getValue(comp)
  14977. });
  14978. }
  14979. },
  14980. validator: {
  14981. validate: function (comp) {
  14982. var value = Representing.getValue(comp);
  14983. var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  14984. return Future.pure(res);
  14985. },
  14986. validateOnLoad: false
  14987. }
  14988. });
  14989. };
  14990. var renderTextField = function (isValid, name, label, description, data) {
  14991. var helptext = translate(translatePrefix + 'range');
  14992. var pLabel = FormField.parts().label({
  14993. dom: {
  14994. tag: 'label',
  14995. innerHtml: label,
  14996. attributes: { 'aria-label': description }
  14997. }
  14998. });
  14999. var pField = FormField.parts().field({
  15000. data: data,
  15001. factory: Input,
  15002. inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  15003. inputClasses: [getClass('textfield')],
  15004. inputBehaviours: derive$1([
  15005. invalidation(name, isValid),
  15006. Tabstopping.config({})
  15007. ]),
  15008. onSetValue: function (input) {
  15009. if (Invalidating.isInvalid(input)) {
  15010. var run = Invalidating.run(input);
  15011. run.get(noop);
  15012. }
  15013. }
  15014. });
  15015. var comps = [
  15016. pLabel,
  15017. pField
  15018. ];
  15019. var concats = name !== 'hex' ? [FormField.parts()['aria-descriptor']({ text: helptext })] : [];
  15020. var components = comps.concat(concats);
  15021. return {
  15022. dom: {
  15023. tag: 'div',
  15024. attributes: { role: 'presentation' }
  15025. },
  15026. components: components
  15027. };
  15028. };
  15029. var copyRgbToHex = function (form, rgba) {
  15030. var hex = fromRgba(rgba);
  15031. Form.getField(form, 'hex').each(function (hexField) {
  15032. if (!Focusing.isFocused(hexField)) {
  15033. Representing.setValue(form, { hex: hex.value() });
  15034. }
  15035. });
  15036. return hex;
  15037. };
  15038. var copyRgbToForm = function (form, rgb) {
  15039. var red = rgb.red();
  15040. var green = rgb.green();
  15041. var blue = rgb.blue();
  15042. Representing.setValue(form, {
  15043. red: red,
  15044. green: green,
  15045. blue: blue
  15046. });
  15047. };
  15048. var memPreview = record({
  15049. dom: {
  15050. tag: 'div',
  15051. classes: [getClass('rgba-preview')],
  15052. styles: { 'background-color': 'white' },
  15053. attributes: { role: 'presentation' }
  15054. }
  15055. });
  15056. var updatePreview = function (anyInSystem, hex) {
  15057. memPreview.getOpt(anyInSystem).each(function (preview) {
  15058. set$2(preview.element(), 'background-color', '#' + hex.value());
  15059. });
  15060. };
  15061. var factory = function () {
  15062. var state = {
  15063. red: constant(Cell(Option.some(255))),
  15064. green: constant(Cell(Option.some(255))),
  15065. blue: constant(Cell(Option.some(255))),
  15066. hex: constant(Cell(Option.some('ffffff')))
  15067. };
  15068. var copyHexToRgb = function (form, hex) {
  15069. var rgb = fromHex(hex);
  15070. copyRgbToForm(form, rgb);
  15071. setValueRgb(rgb);
  15072. };
  15073. var get = function (prop) {
  15074. return state[prop]().get();
  15075. };
  15076. var set = function (prop, value) {
  15077. state[prop]().set(value);
  15078. };
  15079. var getValueRgb = function () {
  15080. return get('red').bind(function (red) {
  15081. return get('green').bind(function (green) {
  15082. return get('blue').map(function (blue) {
  15083. return rgbaColour(red, green, blue, 1);
  15084. });
  15085. });
  15086. });
  15087. };
  15088. var setValueRgb = function (rgb) {
  15089. var red = rgb.red();
  15090. var green = rgb.green();
  15091. var blue = rgb.blue();
  15092. set('red', Option.some(red));
  15093. set('green', Option.some(green));
  15094. set('blue', Option.some(blue));
  15095. };
  15096. var onInvalidInput = function (form, simulatedEvent) {
  15097. var data = simulatedEvent.event();
  15098. if (data.type() !== 'hex') {
  15099. set(data.type(), Option.none());
  15100. } else {
  15101. onInvalidHexx(form);
  15102. }
  15103. };
  15104. var onValidHex = function (form, value) {
  15105. onValidHexx(form);
  15106. var hex = hexColour(value);
  15107. set('hex', Option.some(value));
  15108. var rgb = fromHex(hex);
  15109. copyRgbToForm(form, rgb);
  15110. setValueRgb(rgb);
  15111. emitWith(form, fieldsUpdate(), { hex: hex });
  15112. updatePreview(form, hex);
  15113. };
  15114. var onValidRgb = function (form, prop, value) {
  15115. var val = parseInt(value, 10);
  15116. set(prop, Option.some(val));
  15117. getValueRgb().each(function (rgb) {
  15118. var hex = copyRgbToHex(form, rgb);
  15119. updatePreview(form, hex);
  15120. });
  15121. };
  15122. var isHexInputEvent = function (data) {
  15123. return data.type() === 'hex';
  15124. };
  15125. var onValidInput = function (form, simulatedEvent) {
  15126. var data = simulatedEvent.event();
  15127. if (isHexInputEvent(data)) {
  15128. onValidHex(form, data.value());
  15129. } else {
  15130. onValidRgb(form, data.type(), data.value());
  15131. }
  15132. };
  15133. var formPartStrings = function (key) {
  15134. return {
  15135. label: translate(translatePrefix + key + '.label'),
  15136. description: translate(translatePrefix + key + '.description')
  15137. };
  15138. };
  15139. var redStrings = formPartStrings('red');
  15140. var greenStrings = formPartStrings('green');
  15141. var blueStrings = formPartStrings('blue');
  15142. var hexStrings = formPartStrings('hex');
  15143. return deepMerge(Form.sketch(function (parts) {
  15144. return {
  15145. dom: {
  15146. tag: 'form',
  15147. classes: [getClass('rgb-form')],
  15148. attributes: { 'aria-label': translate('aria.color.picker') }
  15149. },
  15150. components: [
  15151. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  15152. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  15153. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  15154. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  15155. memPreview.asSpec()
  15156. ],
  15157. formBehaviours: derive$1([
  15158. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  15159. config('rgb-form-events', [
  15160. run(validInput, onValidInput),
  15161. run(invalidInput, onInvalidInput),
  15162. run(validatingInput, onInvalidInput)
  15163. ])
  15164. ])
  15165. };
  15166. }), {
  15167. apis: {
  15168. updateHex: function (form, hex) {
  15169. Representing.setValue(form, { hex: hex.value() });
  15170. copyHexToRgb(form, hex);
  15171. updatePreview(form, hex);
  15172. }
  15173. }
  15174. });
  15175. };
  15176. var rgbFormSketcher = single$2({
  15177. factory: factory,
  15178. name: 'RgbForm',
  15179. configFields: [],
  15180. apis: {
  15181. updateHex: function (apis, form, hex) {
  15182. apis.updateHex(form, hex);
  15183. }
  15184. },
  15185. extraApis: {}
  15186. });
  15187. return rgbFormSketcher;
  15188. };
  15189. var paletteFactory = function (_translate, getClass) {
  15190. var spectrumPart = Slider.parts().spectrum({
  15191. dom: {
  15192. tag: 'canvas',
  15193. attributes: { role: 'presentation' },
  15194. classes: [getClass('sv-palette-spectrum')]
  15195. }
  15196. });
  15197. var thumbPart = Slider.parts().thumb({
  15198. dom: {
  15199. tag: 'div',
  15200. attributes: { role: 'presentation' },
  15201. classes: [getClass('sv-palette-thumb')],
  15202. innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  15203. }
  15204. });
  15205. var setColour = function (canvas, rgba) {
  15206. var width = canvas.width, height = canvas.height;
  15207. var ctx = canvas.getContext('2d');
  15208. if (ctx === null) {
  15209. return;
  15210. }
  15211. ctx.fillStyle = rgba;
  15212. ctx.fillRect(0, 0, width, height);
  15213. var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  15214. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  15215. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  15216. ctx.fillStyle = grdWhite;
  15217. ctx.fillRect(0, 0, width, height);
  15218. var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  15219. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  15220. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  15221. ctx.fillStyle = grdBlack;
  15222. ctx.fillRect(0, 0, width, height);
  15223. };
  15224. var setSliderColour = function (slider, rgba) {
  15225. var canvas = slider.components()[0].element().dom();
  15226. setColour(canvas, toString(rgba));
  15227. };
  15228. var factory = function (_detail) {
  15229. var getInitialValue = constant({
  15230. x: constant(0),
  15231. y: constant(0)
  15232. });
  15233. var onChange = function (slider, _thumb, value) {
  15234. emitWith(slider, paletteUpdate(), { value: value });
  15235. };
  15236. var onInit = function (_slider, _thumb, spectrum, _value) {
  15237. setColour(spectrum.element().dom(), toString(redColour()));
  15238. };
  15239. var sliderBehaviours = derive$1([
  15240. Composing.config({ find: Option.some }),
  15241. Focusing.config({})
  15242. ]);
  15243. return Slider.sketch({
  15244. dom: {
  15245. tag: 'div',
  15246. attributes: { role: 'presentation' },
  15247. classes: [getClass('sv-palette')]
  15248. },
  15249. model: {
  15250. mode: 'xy',
  15251. getInitialValue: getInitialValue
  15252. },
  15253. rounded: false,
  15254. components: [
  15255. spectrumPart,
  15256. thumbPart
  15257. ],
  15258. onChange: onChange,
  15259. onInit: onInit,
  15260. sliderBehaviours: sliderBehaviours
  15261. });
  15262. };
  15263. var saturationBrightnessPaletteSketcher = single$2({
  15264. factory: factory,
  15265. name: 'SaturationBrightnessPalette',
  15266. configFields: [],
  15267. apis: {
  15268. setRgba: function (_apis, slider, rgba) {
  15269. setSliderColour(slider, rgba);
  15270. }
  15271. },
  15272. extraApis: {}
  15273. });
  15274. return saturationBrightnessPaletteSketcher;
  15275. };
  15276. var makeFactory = function (translate, getClass) {
  15277. var factory = function (detail) {
  15278. var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  15279. var sbPalette = paletteFactory(translate, getClass);
  15280. var state = { paletteRgba: constant(Cell(redColour())) };
  15281. var memPalette = record(sbPalette.sketch({}));
  15282. var memRgb = record(rgbForm.sketch({}));
  15283. var updatePalette = function (anyInSystem, hex) {
  15284. memPalette.getOpt(anyInSystem).each(function (palette) {
  15285. var rgba = fromHex(hex);
  15286. state.paletteRgba().set(rgba);
  15287. sbPalette.setRgba(palette, rgba);
  15288. });
  15289. };
  15290. var updateFields = function (anyInSystem, hex) {
  15291. memRgb.getOpt(anyInSystem).each(function (form) {
  15292. rgbForm.updateHex(form, hex);
  15293. });
  15294. };
  15295. var runUpdates = function (anyInSystem, hex, updates) {
  15296. each(updates, function (update) {
  15297. update(anyInSystem, hex);
  15298. });
  15299. };
  15300. var paletteUpdates = function () {
  15301. var updates = [updateFields];
  15302. return function (form, simulatedEvent) {
  15303. var value = simulatedEvent.event().value();
  15304. var oldRgb = state.paletteRgba().get();
  15305. var hsvColour$1 = fromRgb(oldRgb);
  15306. var newHsvColour = hsvColour(hsvColour$1.hue(), value.x(), 100 - value.y());
  15307. var rgb = fromHsv(newHsvColour);
  15308. var nuHex = fromRgba(rgb);
  15309. runUpdates(form, nuHex, updates);
  15310. };
  15311. };
  15312. var sliderUpdates = function () {
  15313. var updates = [
  15314. updatePalette,
  15315. updateFields
  15316. ];
  15317. return function (form, simulatedEvent) {
  15318. var value = simulatedEvent.event().value();
  15319. var hex = calcHex(value.y());
  15320. runUpdates(form, hex, updates);
  15321. };
  15322. };
  15323. return {
  15324. uid: detail.uid,
  15325. dom: detail.dom,
  15326. components: [
  15327. memPalette.asSpec(),
  15328. sliderFactory(translate, getClass),
  15329. memRgb.asSpec()
  15330. ],
  15331. behaviours: derive$1([
  15332. config('colour-picker-events', [
  15333. run(paletteUpdate(), paletteUpdates()),
  15334. run(sliderUpdate(), sliderUpdates())
  15335. ]),
  15336. Composing.config({
  15337. find: function (comp) {
  15338. return memRgb.getOpt(comp);
  15339. }
  15340. }),
  15341. Keying.config({ mode: 'acyclic' })
  15342. ])
  15343. };
  15344. };
  15345. var colourPickerSketcher = single$2({
  15346. name: 'ColourPicker',
  15347. configFields: [
  15348. strict$1('dom'),
  15349. defaulted$1('onValidHex', noop),
  15350. defaulted$1('onInvalidHex', noop)
  15351. ],
  15352. factory: factory
  15353. });
  15354. return colourPickerSketcher;
  15355. };
  15356. var self$1 = function () {
  15357. return Composing.config({ find: Option.some });
  15358. };
  15359. var memento = function (mem) {
  15360. return Composing.config({ find: mem.getOpt });
  15361. };
  15362. var childAt = function (index) {
  15363. return Composing.config({
  15364. find: function (comp) {
  15365. return child(comp.element(), index).bind(function (element) {
  15366. return comp.getSystem().getByDom(element).toOption();
  15367. });
  15368. }
  15369. });
  15370. };
  15371. var ComposingConfigs = {
  15372. self: self$1,
  15373. memento: memento,
  15374. childAt: childAt
  15375. };
  15376. var english = {
  15377. 'colorcustom.rgb.red.label': 'R',
  15378. 'colorcustom.rgb.red.description': 'Red component',
  15379. 'colorcustom.rgb.green.label': 'G',
  15380. 'colorcustom.rgb.green.description': 'Green component',
  15381. 'colorcustom.rgb.blue.label': 'B',
  15382. 'colorcustom.rgb.blue.description': 'Blue component',
  15383. 'colorcustom.rgb.hex.label': '#',
  15384. 'colorcustom.rgb.hex.description': 'Hex color code',
  15385. 'colorcustom.rgb.range': 'Range 0 to 255',
  15386. 'colorcustom.sb.saturation': 'Saturation',
  15387. 'colorcustom.sb.brightness': 'Brightness',
  15388. 'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  15389. 'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  15390. 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  15391. 'colorcustom.hue.hue': 'Hue',
  15392. 'colorcustom.hue.slider': 'Hue Slider',
  15393. 'colorcustom.hue.palette': 'Hue Palette',
  15394. 'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  15395. 'aria.color.picker': 'Color Picker',
  15396. 'aria.input.invalid': 'Invalid input'
  15397. };
  15398. var getEnglishText = function (key) {
  15399. return english[key];
  15400. };
  15401. var translate$1 = function (key) {
  15402. return getEnglishText(key);
  15403. };
  15404. var renderColorPicker = function (spec) {
  15405. var getClass = function (key) {
  15406. return 'tox-' + key;
  15407. };
  15408. var colourPickerFactory = makeFactory(translate$1, getClass);
  15409. var onValidHex = function (form) {
  15410. emitWith(form, formActionEvent, {
  15411. name: 'hex-valid',
  15412. value: true
  15413. });
  15414. };
  15415. var onInvalidHex = function (form) {
  15416. emitWith(form, formActionEvent, {
  15417. name: 'hex-valid',
  15418. value: false
  15419. });
  15420. };
  15421. var memPicker = record(colourPickerFactory.sketch({
  15422. dom: {
  15423. tag: 'div',
  15424. classes: [getClass('color-picker-container')],
  15425. attributes: { role: 'presentation' }
  15426. },
  15427. onValidHex: onValidHex,
  15428. onInvalidHex: onInvalidHex
  15429. }));
  15430. return {
  15431. dom: { tag: 'div' },
  15432. components: [memPicker.asSpec()],
  15433. behaviours: derive$1([
  15434. Representing.config({
  15435. store: {
  15436. mode: 'manual',
  15437. getValue: function (comp) {
  15438. var picker = memPicker.get(comp);
  15439. var optRgbForm = Composing.getCurrent(picker);
  15440. var optHex = optRgbForm.bind(function (rgbForm) {
  15441. var formValues = Representing.getValue(rgbForm);
  15442. return formValues.hex;
  15443. });
  15444. return optHex.map(function (hex) {
  15445. return '#' + hex;
  15446. }).getOr('');
  15447. },
  15448. setValue: function (comp, newValue) {
  15449. var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  15450. var m = pattern.exec(newValue);
  15451. var picker = memPicker.get(comp);
  15452. var optRgbForm = Composing.getCurrent(picker);
  15453. optRgbForm.fold(function () {
  15454. domGlobals.console.log('Can not find form');
  15455. }, function (rgbForm) {
  15456. Representing.setValue(rgbForm, { hex: Option.from(m[1]).getOr('') });
  15457. Form.getField(rgbForm, 'hex').each(function (hexField) {
  15458. emit(hexField, input());
  15459. });
  15460. });
  15461. }
  15462. }
  15463. }),
  15464. ComposingConfigs.self()
  15465. ])
  15466. };
  15467. };
  15468. var global$a = tinymce.util.Tools.resolve('tinymce.Resource');
  15469. var isOldCustomEditor = function (spec) {
  15470. return Object.prototype.hasOwnProperty.call(spec, 'init');
  15471. };
  15472. var renderCustomEditor = function (spec) {
  15473. var editorApi = Cell(Option.none());
  15474. var memReplaced = record({ dom: { tag: spec.tag } });
  15475. var initialValue = Cell(Option.none());
  15476. return {
  15477. dom: {
  15478. tag: 'div',
  15479. classes: ['tox-custom-editor']
  15480. },
  15481. behaviours: derive$1([
  15482. config('editor-foo-events', [runOnAttached(function (component) {
  15483. memReplaced.getOpt(component).each(function (ta) {
  15484. (isOldCustomEditor(spec) ? spec.init(ta.element().dom()) : global$a.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  15485. return init(ta.element().dom(), spec.settings);
  15486. })).then(function (ea) {
  15487. initialValue.get().each(function (cvalue) {
  15488. ea.setValue(cvalue);
  15489. });
  15490. initialValue.set(Option.none());
  15491. editorApi.set(Option.some(ea));
  15492. });
  15493. });
  15494. })]),
  15495. Representing.config({
  15496. store: {
  15497. mode: 'manual',
  15498. getValue: function () {
  15499. return editorApi.get().fold(function () {
  15500. return initialValue.get().getOr('');
  15501. }, function (ed) {
  15502. return ed.getValue();
  15503. });
  15504. },
  15505. setValue: function (component, value) {
  15506. editorApi.get().fold(function () {
  15507. initialValue.set(Option.some(value));
  15508. }, function (ed) {
  15509. return ed.setValue(value);
  15510. });
  15511. }
  15512. }
  15513. }),
  15514. ComposingConfigs.self()
  15515. ]),
  15516. components: [memReplaced.asSpec()]
  15517. };
  15518. };
  15519. var processors = objOf([
  15520. defaulted$1('preprocess', identity),
  15521. defaulted$1('postprocess', identity)
  15522. ]);
  15523. var memento$1 = function (mem, rawProcessors) {
  15524. var ps = asRawOrDie('RepresentingConfigs.memento processors', processors, rawProcessors);
  15525. return Representing.config({
  15526. store: {
  15527. mode: 'manual',
  15528. getValue: function (comp) {
  15529. var other = mem.get(comp);
  15530. var rawValue = Representing.getValue(other);
  15531. return ps.postprocess(rawValue);
  15532. },
  15533. setValue: function (comp, rawValue) {
  15534. var newValue = ps.preprocess(rawValue);
  15535. var other = mem.get(comp);
  15536. Representing.setValue(other, newValue);
  15537. }
  15538. }
  15539. });
  15540. };
  15541. var withComp = function (optInitialValue, getter, setter) {
  15542. return Representing.config(deepMerge({
  15543. store: {
  15544. mode: 'manual',
  15545. getValue: getter,
  15546. setValue: setter
  15547. }
  15548. }, optInitialValue.map(function (initialValue) {
  15549. return { store: { initialValue: initialValue } };
  15550. }).getOr({})));
  15551. };
  15552. var withElement = function (initialValue, getter, setter) {
  15553. return withComp(initialValue, function (c) {
  15554. return getter(c.element());
  15555. }, function (c, v) {
  15556. return setter(c.element(), v);
  15557. });
  15558. };
  15559. var domValue = function (optInitialValue) {
  15560. return withElement(optInitialValue, get$5, set$3);
  15561. };
  15562. var domHtml = function (optInitialValue) {
  15563. return withElement(optInitialValue, get$1, set);
  15564. };
  15565. var memory$1 = function (initialValue) {
  15566. return Representing.config({
  15567. store: {
  15568. mode: 'memory',
  15569. initialValue: initialValue
  15570. }
  15571. });
  15572. };
  15573. var RepresentingConfigs = {
  15574. memento: memento$1,
  15575. withElement: withElement,
  15576. withComp: withComp,
  15577. domValue: domValue,
  15578. domHtml: domHtml,
  15579. memory: memory$1
  15580. };
  15581. var extensionsAccepted = '.jpg,.jpeg,.png,.gif';
  15582. var filterByExtension = function (files) {
  15583. var re = new RegExp('(' + extensionsAccepted.split(/\s*,\s*/).join('|') + ')$', 'i');
  15584. return filter(from$1(files), function (file) {
  15585. return re.test(file.name);
  15586. });
  15587. };
  15588. var renderDropZone = function (spec, providersBackstage) {
  15589. var stopper = function (_, se) {
  15590. se.stop();
  15591. };
  15592. var sequence = function (actions) {
  15593. return function (comp, se) {
  15594. each(actions, function (a) {
  15595. a(comp, se);
  15596. });
  15597. };
  15598. };
  15599. var onDrop = function (comp, se) {
  15600. if (!Disabling.isDisabled(comp)) {
  15601. var transferEvent = se.event().raw();
  15602. handleFiles(comp, transferEvent.dataTransfer.files);
  15603. }
  15604. };
  15605. var onSelect = function (component, simulatedEvent) {
  15606. var files = simulatedEvent.event().raw().target.files;
  15607. handleFiles(component, files);
  15608. };
  15609. var handleFiles = function (component, files) {
  15610. Representing.setValue(component, filterByExtension(files));
  15611. emitWith(component, formChangeEvent, { name: spec.name });
  15612. };
  15613. var memInput = record({
  15614. dom: {
  15615. tag: 'input',
  15616. attributes: {
  15617. type: 'file',
  15618. accept: 'image/*'
  15619. },
  15620. styles: { display: 'none' }
  15621. },
  15622. behaviours: derive$1([config('input-file-events', [
  15623. cutter(click()),
  15624. cutter(tap())
  15625. ])])
  15626. });
  15627. var renderField = function (s) {
  15628. return {
  15629. uid: s.uid,
  15630. dom: {
  15631. tag: 'div',
  15632. classes: ['tox-dropzone-container']
  15633. },
  15634. behaviours: derive$1([
  15635. RepresentingConfigs.memory([]),
  15636. ComposingConfigs.self(),
  15637. Disabling.config({}),
  15638. Toggling.config({
  15639. toggleClass: 'dragenter',
  15640. toggleOnExecute: false
  15641. }),
  15642. config('dropzone-events', [
  15643. run('dragenter', sequence([
  15644. stopper,
  15645. Toggling.toggle
  15646. ])),
  15647. run('dragleave', sequence([
  15648. stopper,
  15649. Toggling.toggle
  15650. ])),
  15651. run('dragover', stopper),
  15652. run('drop', sequence([
  15653. stopper,
  15654. onDrop
  15655. ])),
  15656. run(change(), onSelect)
  15657. ])
  15658. ]),
  15659. components: [{
  15660. dom: {
  15661. tag: 'div',
  15662. classes: ['tox-dropzone'],
  15663. styles: {}
  15664. },
  15665. components: [
  15666. {
  15667. dom: {
  15668. tag: 'p',
  15669. innerHtml: providersBackstage.translate('Drop an image here')
  15670. }
  15671. },
  15672. Button.sketch({
  15673. dom: {
  15674. tag: 'button',
  15675. innerHtml: providersBackstage.translate('Browse for an image'),
  15676. styles: { position: 'relative' },
  15677. classes: [
  15678. 'tox-button',
  15679. 'tox-button--secondary'
  15680. ]
  15681. },
  15682. components: [memInput.asSpec()],
  15683. action: function (comp) {
  15684. var inputComp = memInput.get(comp);
  15685. inputComp.element().dom().click();
  15686. },
  15687. buttonBehaviours: derive$1([Tabstopping.config({})])
  15688. })
  15689. ]
  15690. }]
  15691. };
  15692. };
  15693. var pLabel = spec.label.map(function (label) {
  15694. return renderLabel(label, providersBackstage);
  15695. });
  15696. var pField = FormField.parts().field({ factory: { sketch: renderField } });
  15697. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  15698. };
  15699. var renderGrid = function (spec, backstage) {
  15700. return {
  15701. dom: {
  15702. tag: 'div',
  15703. classes: [
  15704. 'tox-form__grid',
  15705. 'tox-form__grid--' + spec.columns + 'col'
  15706. ]
  15707. },
  15708. components: map(spec.items, backstage.interpreter)
  15709. };
  15710. };
  15711. var beforeObject = generate$1('alloy-fake-before-tabstop');
  15712. var afterObject = generate$1('alloy-fake-after-tabstop');
  15713. var craftWithClasses = function (classes) {
  15714. return {
  15715. dom: {
  15716. tag: 'div',
  15717. styles: {
  15718. width: '1px',
  15719. height: '1px',
  15720. outline: 'none'
  15721. },
  15722. attributes: { tabindex: '0' },
  15723. classes: classes
  15724. },
  15725. behaviours: derive$1([
  15726. Focusing.config({ ignore: true }),
  15727. Tabstopping.config({})
  15728. ])
  15729. };
  15730. };
  15731. var craft = function (spec) {
  15732. return {
  15733. dom: {
  15734. tag: 'div',
  15735. classes: ['tox-navobj']
  15736. },
  15737. components: [
  15738. craftWithClasses([beforeObject]),
  15739. spec,
  15740. craftWithClasses([afterObject])
  15741. ],
  15742. behaviours: derive$1([ComposingConfigs.childAt(1)])
  15743. };
  15744. };
  15745. var triggerTab = function (placeholder, shiftKey) {
  15746. emitWith(placeholder, keydown(), {
  15747. raw: {
  15748. which: 9,
  15749. shiftKey: shiftKey
  15750. }
  15751. });
  15752. };
  15753. var onFocus$1 = function (container, targetComp) {
  15754. var target = targetComp.element();
  15755. if (has$2(target, beforeObject)) {
  15756. triggerTab(container, true);
  15757. } else if (has$2(target, afterObject)) {
  15758. triggerTab(container, false);
  15759. }
  15760. };
  15761. var isPseudoStop = function (element) {
  15762. return closest$4(element, [
  15763. '.' + beforeObject,
  15764. '.' + afterObject
  15765. ].join(','), constant(false));
  15766. };
  15767. var NavigableObject = {
  15768. isPseudoStop: isPseudoStop,
  15769. onFocus: onFocus$1,
  15770. craft: craft
  15771. };
  15772. var platformNeedsSandboxing = !(detect$3().browser.isIE() || detect$3().browser.isEdge());
  15773. var getDynamicSource = function (isSandbox) {
  15774. var cachedValue = Cell('');
  15775. return {
  15776. getValue: function (frameComponent) {
  15777. return cachedValue.get();
  15778. },
  15779. setValue: function (frameComponent, html) {
  15780. if (!isSandbox) {
  15781. set$1(frameComponent.element(), 'src', 'javascript:\'\'');
  15782. var doc = frameComponent.element().dom().contentWindow.document;
  15783. doc.open();
  15784. doc.write(html);
  15785. doc.close();
  15786. } else {
  15787. set$1(frameComponent.element(), 'srcdoc', html);
  15788. }
  15789. cachedValue.set(html);
  15790. }
  15791. };
  15792. };
  15793. var renderIFrame = function (spec, providersBackstage) {
  15794. var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  15795. var attributes = __assign(__assign({}, spec.label.map(function (title) {
  15796. return { title: title };
  15797. }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  15798. var sourcing = getDynamicSource(isSandbox);
  15799. var pLabel = spec.label.map(function (label) {
  15800. return renderLabel(label, providersBackstage);
  15801. });
  15802. var factory = function (newSpec) {
  15803. return NavigableObject.craft({
  15804. uid: newSpec.uid,
  15805. dom: {
  15806. tag: 'iframe',
  15807. attributes: attributes
  15808. },
  15809. behaviours: derive$1([
  15810. Tabstopping.config({}),
  15811. Focusing.config({}),
  15812. RepresentingConfigs.withComp(Option.none(), sourcing.getValue, sourcing.setValue)
  15813. ])
  15814. });
  15815. };
  15816. var pField = FormField.parts().field({ factory: { sketch: factory } });
  15817. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  15818. };
  15819. function create$5(width, height) {
  15820. return resize(domGlobals.document.createElement('canvas'), width, height);
  15821. }
  15822. function clone$1(canvas) {
  15823. var tCanvas = create$5(canvas.width, canvas.height);
  15824. var ctx = get2dContext(tCanvas);
  15825. ctx.drawImage(canvas, 0, 0);
  15826. return tCanvas;
  15827. }
  15828. function get2dContext(canvas) {
  15829. return canvas.getContext('2d');
  15830. }
  15831. function resize(canvas, width, height) {
  15832. canvas.width = width;
  15833. canvas.height = height;
  15834. return canvas;
  15835. }
  15836. function getWidth(image) {
  15837. return image.naturalWidth || image.width;
  15838. }
  15839. function getHeight(image) {
  15840. return image.naturalHeight || image.height;
  15841. }
  15842. var promise = function () {
  15843. var Promise = function (fn) {
  15844. if (typeof this !== 'object') {
  15845. throw new TypeError('Promises must be constructed via new');
  15846. }
  15847. if (typeof fn !== 'function') {
  15848. throw new TypeError('not a function');
  15849. }
  15850. this._state = null;
  15851. this._value = null;
  15852. this._deferreds = [];
  15853. doResolve(fn, bind(resolve, this), bind(reject, this));
  15854. };
  15855. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  15856. domGlobals.setTimeout(fn, 1);
  15857. };
  15858. function bind(fn, thisArg) {
  15859. return function () {
  15860. return fn.apply(thisArg, arguments);
  15861. };
  15862. }
  15863. var isArray = Array.isArray || function (value) {
  15864. return Object.prototype.toString.call(value) === '[object Array]';
  15865. };
  15866. function handle(deferred) {
  15867. var me = this;
  15868. if (this._state === null) {
  15869. this._deferreds.push(deferred);
  15870. return;
  15871. }
  15872. asap(function () {
  15873. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  15874. if (cb === null) {
  15875. (me._state ? deferred.resolve : deferred.reject)(me._value);
  15876. return;
  15877. }
  15878. var ret;
  15879. try {
  15880. ret = cb(me._value);
  15881. } catch (e) {
  15882. deferred.reject(e);
  15883. return;
  15884. }
  15885. deferred.resolve(ret);
  15886. });
  15887. }
  15888. function resolve(newValue) {
  15889. try {
  15890. if (newValue === this) {
  15891. throw new TypeError('A promise cannot be resolved with itself.');
  15892. }
  15893. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  15894. var then = newValue.then;
  15895. if (typeof then === 'function') {
  15896. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  15897. return;
  15898. }
  15899. }
  15900. this._state = true;
  15901. this._value = newValue;
  15902. finale.call(this);
  15903. } catch (e) {
  15904. reject.call(this, e);
  15905. }
  15906. }
  15907. function reject(newValue) {
  15908. this._state = false;
  15909. this._value = newValue;
  15910. finale.call(this);
  15911. }
  15912. function finale() {
  15913. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  15914. var deferred = _a[_i];
  15915. handle.call(this, deferred);
  15916. }
  15917. this._deferreds = [];
  15918. }
  15919. function Handler(onFulfilled, onRejected, resolve, reject) {
  15920. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  15921. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  15922. this.resolve = resolve;
  15923. this.reject = reject;
  15924. }
  15925. function doResolve(fn, onFulfilled, onRejected) {
  15926. var done = false;
  15927. try {
  15928. fn(function (value) {
  15929. if (done) {
  15930. return;
  15931. }
  15932. done = true;
  15933. onFulfilled(value);
  15934. }, function (reason) {
  15935. if (done) {
  15936. return;
  15937. }
  15938. done = true;
  15939. onRejected(reason);
  15940. });
  15941. } catch (ex) {
  15942. if (done) {
  15943. return;
  15944. }
  15945. done = true;
  15946. onRejected(ex);
  15947. }
  15948. }
  15949. Promise.prototype.catch = function (onRejected) {
  15950. return this.then(null, onRejected);
  15951. };
  15952. Promise.prototype.then = function (onFulfilled, onRejected) {
  15953. var me = this;
  15954. return new Promise(function (resolve, reject) {
  15955. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  15956. });
  15957. };
  15958. Promise.all = function () {
  15959. var values = [];
  15960. for (var _i = 0; _i < arguments.length; _i++) {
  15961. values[_i] = arguments[_i];
  15962. }
  15963. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  15964. return new Promise(function (resolve, reject) {
  15965. if (args.length === 0) {
  15966. return resolve([]);
  15967. }
  15968. var remaining = args.length;
  15969. function res(i, val) {
  15970. try {
  15971. if (val && (typeof val === 'object' || typeof val === 'function')) {
  15972. var then = val.then;
  15973. if (typeof then === 'function') {
  15974. then.call(val, function (val) {
  15975. res(i, val);
  15976. }, reject);
  15977. return;
  15978. }
  15979. }
  15980. args[i] = val;
  15981. if (--remaining === 0) {
  15982. resolve(args);
  15983. }
  15984. } catch (ex) {
  15985. reject(ex);
  15986. }
  15987. }
  15988. for (var i = 0; i < args.length; i++) {
  15989. res(i, args[i]);
  15990. }
  15991. });
  15992. };
  15993. Promise.resolve = function (value) {
  15994. if (value && typeof value === 'object' && value.constructor === Promise) {
  15995. return value;
  15996. }
  15997. return new Promise(function (resolve) {
  15998. resolve(value);
  15999. });
  16000. };
  16001. Promise.reject = function (reason) {
  16002. return new Promise(function (resolve, reject) {
  16003. reject(reason);
  16004. });
  16005. };
  16006. Promise.race = function (values) {
  16007. return new Promise(function (resolve, reject) {
  16008. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  16009. var value = values_1[_i];
  16010. value.then(resolve, reject);
  16011. }
  16012. });
  16013. };
  16014. return Promise;
  16015. };
  16016. var Promise$1 = window.Promise ? window.Promise : promise();
  16017. function blobToImage(blob) {
  16018. return new Promise$1(function (resolve, reject) {
  16019. var blobUrl = domGlobals.URL.createObjectURL(blob);
  16020. var image = new domGlobals.Image();
  16021. var removeListeners = function () {
  16022. image.removeEventListener('load', loaded);
  16023. image.removeEventListener('error', error);
  16024. };
  16025. function loaded() {
  16026. removeListeners();
  16027. resolve(image);
  16028. }
  16029. function error() {
  16030. removeListeners();
  16031. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  16032. }
  16033. image.addEventListener('load', loaded);
  16034. image.addEventListener('error', error);
  16035. image.src = blobUrl;
  16036. if (image.complete) {
  16037. loaded();
  16038. }
  16039. });
  16040. }
  16041. function dataUriToBlobSync(uri) {
  16042. var data = uri.split(',');
  16043. var matches = /data:([^;]+)/.exec(data[0]);
  16044. if (!matches) {
  16045. return Option.none();
  16046. }
  16047. var mimetype = matches[1];
  16048. var base64 = data[1];
  16049. var sliceSize = 1024;
  16050. var byteCharacters = domGlobals.atob(base64);
  16051. var bytesLength = byteCharacters.length;
  16052. var slicesCount = Math.ceil(bytesLength / sliceSize);
  16053. var byteArrays = new Array(slicesCount);
  16054. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  16055. var begin = sliceIndex * sliceSize;
  16056. var end = Math.min(begin + sliceSize, bytesLength);
  16057. var bytes = new Array(end - begin);
  16058. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  16059. bytes[i] = byteCharacters[offset].charCodeAt(0);
  16060. }
  16061. byteArrays[sliceIndex] = new Uint8Array(bytes);
  16062. }
  16063. return Option.some(new domGlobals.Blob(byteArrays, { type: mimetype }));
  16064. }
  16065. function dataUriToBlob(uri) {
  16066. return new Promise$1(function (resolve, reject) {
  16067. dataUriToBlobSync(uri).fold(function () {
  16068. reject('uri is not base64: ' + uri);
  16069. }, resolve);
  16070. });
  16071. }
  16072. function canvasToBlob(canvas, type, quality) {
  16073. type = type || 'image/png';
  16074. if (domGlobals.HTMLCanvasElement.prototype.toBlob) {
  16075. return new Promise$1(function (resolve, reject) {
  16076. canvas.toBlob(function (blob) {
  16077. if (blob) {
  16078. resolve(blob);
  16079. } else {
  16080. reject();
  16081. }
  16082. }, type, quality);
  16083. });
  16084. } else {
  16085. return dataUriToBlob(canvas.toDataURL(type, quality));
  16086. }
  16087. }
  16088. function canvasToDataURL(canvas, type, quality) {
  16089. type = type || 'image/png';
  16090. return canvas.toDataURL(type, quality);
  16091. }
  16092. function blobToCanvas(blob) {
  16093. return blobToImage(blob).then(function (image) {
  16094. revokeImageUrl(image);
  16095. var canvas = create$5(getWidth(image), getHeight(image));
  16096. var context = get2dContext(canvas);
  16097. context.drawImage(image, 0, 0);
  16098. return canvas;
  16099. });
  16100. }
  16101. function blobToDataUri(blob) {
  16102. return new Promise$1(function (resolve) {
  16103. var reader = new domGlobals.FileReader();
  16104. reader.onloadend = function () {
  16105. resolve(reader.result);
  16106. };
  16107. reader.readAsDataURL(blob);
  16108. });
  16109. }
  16110. function revokeImageUrl(image) {
  16111. domGlobals.URL.revokeObjectURL(image.src);
  16112. }
  16113. function create$6(getCanvas, blob, uri) {
  16114. var initialType = blob.type;
  16115. var getType = constant(initialType);
  16116. function toBlob() {
  16117. return Promise$1.resolve(blob);
  16118. }
  16119. function toDataURL() {
  16120. return uri;
  16121. }
  16122. function toBase64() {
  16123. return uri.split(',')[1];
  16124. }
  16125. function toAdjustedBlob(type, quality) {
  16126. return getCanvas.then(function (canvas) {
  16127. return canvasToBlob(canvas, type, quality);
  16128. });
  16129. }
  16130. function toAdjustedDataURL(type, quality) {
  16131. return getCanvas.then(function (canvas) {
  16132. return canvasToDataURL(canvas, type, quality);
  16133. });
  16134. }
  16135. function toAdjustedBase64(type, quality) {
  16136. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  16137. return dataurl.split(',')[1];
  16138. });
  16139. }
  16140. function toCanvas() {
  16141. return getCanvas.then(clone$1);
  16142. }
  16143. return {
  16144. getType: getType,
  16145. toBlob: toBlob,
  16146. toDataURL: toDataURL,
  16147. toBase64: toBase64,
  16148. toAdjustedBlob: toAdjustedBlob,
  16149. toAdjustedDataURL: toAdjustedDataURL,
  16150. toAdjustedBase64: toAdjustedBase64,
  16151. toCanvas: toCanvas
  16152. };
  16153. }
  16154. function fromBlob(blob) {
  16155. return blobToDataUri(blob).then(function (uri) {
  16156. return create$6(blobToCanvas(blob), blob, uri);
  16157. });
  16158. }
  16159. function fromCanvas(canvas, type) {
  16160. return canvasToBlob(canvas, type).then(function (blob) {
  16161. return create$6(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  16162. });
  16163. }
  16164. var blobToImageResult = function (blob) {
  16165. return fromBlob(blob);
  16166. };
  16167. function clamp$1(value, min, max) {
  16168. var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  16169. if (parsedValue > max) {
  16170. parsedValue = max;
  16171. } else if (parsedValue < min) {
  16172. parsedValue = min;
  16173. }
  16174. return parsedValue;
  16175. }
  16176. function identity$1() {
  16177. return [
  16178. 1,
  16179. 0,
  16180. 0,
  16181. 0,
  16182. 0,
  16183. 0,
  16184. 1,
  16185. 0,
  16186. 0,
  16187. 0,
  16188. 0,
  16189. 0,
  16190. 1,
  16191. 0,
  16192. 0,
  16193. 0,
  16194. 0,
  16195. 0,
  16196. 1,
  16197. 0,
  16198. 0,
  16199. 0,
  16200. 0,
  16201. 0,
  16202. 1
  16203. ];
  16204. }
  16205. var DELTA_INDEX = [
  16206. 0,
  16207. 0.01,
  16208. 0.02,
  16209. 0.04,
  16210. 0.05,
  16211. 0.06,
  16212. 0.07,
  16213. 0.08,
  16214. 0.1,
  16215. 0.11,
  16216. 0.12,
  16217. 0.14,
  16218. 0.15,
  16219. 0.16,
  16220. 0.17,
  16221. 0.18,
  16222. 0.2,
  16223. 0.21,
  16224. 0.22,
  16225. 0.24,
  16226. 0.25,
  16227. 0.27,
  16228. 0.28,
  16229. 0.3,
  16230. 0.32,
  16231. 0.34,
  16232. 0.36,
  16233. 0.38,
  16234. 0.4,
  16235. 0.42,
  16236. 0.44,
  16237. 0.46,
  16238. 0.48,
  16239. 0.5,
  16240. 0.53,
  16241. 0.56,
  16242. 0.59,
  16243. 0.62,
  16244. 0.65,
  16245. 0.68,
  16246. 0.71,
  16247. 0.74,
  16248. 0.77,
  16249. 0.8,
  16250. 0.83,
  16251. 0.86,
  16252. 0.89,
  16253. 0.92,
  16254. 0.95,
  16255. 0.98,
  16256. 1,
  16257. 1.06,
  16258. 1.12,
  16259. 1.18,
  16260. 1.24,
  16261. 1.3,
  16262. 1.36,
  16263. 1.42,
  16264. 1.48,
  16265. 1.54,
  16266. 1.6,
  16267. 1.66,
  16268. 1.72,
  16269. 1.78,
  16270. 1.84,
  16271. 1.9,
  16272. 1.96,
  16273. 2,
  16274. 2.12,
  16275. 2.25,
  16276. 2.37,
  16277. 2.5,
  16278. 2.62,
  16279. 2.75,
  16280. 2.87,
  16281. 3,
  16282. 3.2,
  16283. 3.4,
  16284. 3.6,
  16285. 3.8,
  16286. 4,
  16287. 4.3,
  16288. 4.7,
  16289. 4.9,
  16290. 5,
  16291. 5.5,
  16292. 6,
  16293. 6.5,
  16294. 6.8,
  16295. 7,
  16296. 7.3,
  16297. 7.5,
  16298. 7.8,
  16299. 8,
  16300. 8.4,
  16301. 8.7,
  16302. 9,
  16303. 9.4,
  16304. 9.6,
  16305. 9.8,
  16306. 10
  16307. ];
  16308. function multiply(matrix1, matrix2) {
  16309. var col = [];
  16310. var out = new Array(25);
  16311. var val;
  16312. for (var i = 0; i < 5; i++) {
  16313. for (var j = 0; j < 5; j++) {
  16314. col[j] = matrix2[j + i * 5];
  16315. }
  16316. for (var j = 0; j < 5; j++) {
  16317. val = 0;
  16318. for (var k = 0; k < 5; k++) {
  16319. val += matrix1[j + k * 5] * col[k];
  16320. }
  16321. out[j + i * 5] = val;
  16322. }
  16323. }
  16324. return out;
  16325. }
  16326. function adjustContrast(matrix, value) {
  16327. var x;
  16328. value = clamp$1(value, -1, 1);
  16329. value *= 100;
  16330. if (value < 0) {
  16331. x = 127 + value / 100 * 127;
  16332. } else {
  16333. x = value % 1;
  16334. if (x === 0) {
  16335. x = DELTA_INDEX[value];
  16336. } else {
  16337. x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  16338. }
  16339. x = x * 127 + 127;
  16340. }
  16341. return multiply(matrix, [
  16342. x / 127,
  16343. 0,
  16344. 0,
  16345. 0,
  16346. 0.5 * (127 - x),
  16347. 0,
  16348. x / 127,
  16349. 0,
  16350. 0,
  16351. 0.5 * (127 - x),
  16352. 0,
  16353. 0,
  16354. x / 127,
  16355. 0,
  16356. 0.5 * (127 - x),
  16357. 0,
  16358. 0,
  16359. 0,
  16360. 1,
  16361. 0,
  16362. 0,
  16363. 0,
  16364. 0,
  16365. 0,
  16366. 1
  16367. ]);
  16368. }
  16369. function adjustBrightness(matrix, value) {
  16370. value = clamp$1(255 * value, -255, 255);
  16371. return multiply(matrix, [
  16372. 1,
  16373. 0,
  16374. 0,
  16375. 0,
  16376. value,
  16377. 0,
  16378. 1,
  16379. 0,
  16380. 0,
  16381. value,
  16382. 0,
  16383. 0,
  16384. 1,
  16385. 0,
  16386. value,
  16387. 0,
  16388. 0,
  16389. 0,
  16390. 1,
  16391. 0,
  16392. 0,
  16393. 0,
  16394. 0,
  16395. 0,
  16396. 1
  16397. ]);
  16398. }
  16399. function adjustColors(matrix, adjustR, adjustG, adjustB) {
  16400. adjustR = clamp$1(adjustR, 0, 2);
  16401. adjustG = clamp$1(adjustG, 0, 2);
  16402. adjustB = clamp$1(adjustB, 0, 2);
  16403. return multiply(matrix, [
  16404. adjustR,
  16405. 0,
  16406. 0,
  16407. 0,
  16408. 0,
  16409. 0,
  16410. adjustG,
  16411. 0,
  16412. 0,
  16413. 0,
  16414. 0,
  16415. 0,
  16416. adjustB,
  16417. 0,
  16418. 0,
  16419. 0,
  16420. 0,
  16421. 0,
  16422. 1,
  16423. 0,
  16424. 0,
  16425. 0,
  16426. 0,
  16427. 0,
  16428. 1
  16429. ]);
  16430. }
  16431. function colorFilter(ir, matrix) {
  16432. return ir.toCanvas().then(function (canvas) {
  16433. return applyColorFilter(canvas, ir.getType(), matrix);
  16434. });
  16435. }
  16436. function applyColorFilter(canvas, type, matrix) {
  16437. var context = get2dContext(canvas);
  16438. function applyMatrix(pixelsData, m) {
  16439. var r, g, b, a;
  16440. 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];
  16441. for (var i = 0; i < data.length; i += 4) {
  16442. r = data[i];
  16443. g = data[i + 1];
  16444. b = data[i + 2];
  16445. a = data[i + 3];
  16446. data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  16447. data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  16448. data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  16449. data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  16450. }
  16451. return pixelsData;
  16452. }
  16453. var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  16454. context.putImageData(pixels, 0, 0);
  16455. return fromCanvas(canvas, type);
  16456. }
  16457. function convoluteFilter(ir, matrix) {
  16458. return ir.toCanvas().then(function (canvas) {
  16459. return applyConvoluteFilter(canvas, ir.getType(), matrix);
  16460. });
  16461. }
  16462. function applyConvoluteFilter(canvas, type, matrix) {
  16463. var context = get2dContext(canvas);
  16464. function applyMatrix(pIn, pOut, aMatrix) {
  16465. function clamp(value, min, max) {
  16466. if (value > max) {
  16467. value = max;
  16468. } else if (value < min) {
  16469. value = min;
  16470. }
  16471. return value;
  16472. }
  16473. var side = Math.round(Math.sqrt(aMatrix.length));
  16474. var halfSide = Math.floor(side / 2);
  16475. var rgba = pIn.data;
  16476. var drgba = pOut.data;
  16477. var w = pIn.width;
  16478. var h = pIn.height;
  16479. for (var y = 0; y < h; y++) {
  16480. for (var x = 0; x < w; x++) {
  16481. var r = 0;
  16482. var g = 0;
  16483. var b = 0;
  16484. for (var cy = 0; cy < side; cy++) {
  16485. for (var cx = 0; cx < side; cx++) {
  16486. var scx = clamp(x + cx - halfSide, 0, w - 1);
  16487. var scy = clamp(y + cy - halfSide, 0, h - 1);
  16488. var innerOffset = (scy * w + scx) * 4;
  16489. var wt = aMatrix[cy * side + cx];
  16490. r += rgba[innerOffset] * wt;
  16491. g += rgba[innerOffset + 1] * wt;
  16492. b += rgba[innerOffset + 2] * wt;
  16493. }
  16494. }
  16495. var offset = (y * w + x) * 4;
  16496. drgba[offset] = clamp(r, 0, 255);
  16497. drgba[offset + 1] = clamp(g, 0, 255);
  16498. drgba[offset + 2] = clamp(b, 0, 255);
  16499. }
  16500. }
  16501. return pOut;
  16502. }
  16503. var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  16504. var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  16505. pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  16506. context.putImageData(pixelsOut, 0, 0);
  16507. return fromCanvas(canvas, type);
  16508. }
  16509. function functionColorFilter(colorFn) {
  16510. var filterImpl = function (canvas, type, value) {
  16511. var context = get2dContext(canvas);
  16512. var lookup = new Array(256);
  16513. function applyLookup(pixelsData, lookupData) {
  16514. var data = pixelsData.data;
  16515. for (var i = 0; i < data.length; i += 4) {
  16516. data[i] = lookupData[data[i]];
  16517. data[i + 1] = lookupData[data[i + 1]];
  16518. data[i + 2] = lookupData[data[i + 2]];
  16519. }
  16520. return pixelsData;
  16521. }
  16522. for (var i = 0; i < lookup.length; i++) {
  16523. lookup[i] = colorFn(i, value);
  16524. }
  16525. var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  16526. context.putImageData(pixels, 0, 0);
  16527. return fromCanvas(canvas, type);
  16528. };
  16529. return function (ir, value) {
  16530. return ir.toCanvas().then(function (canvas) {
  16531. return filterImpl(canvas, ir.getType(), value);
  16532. });
  16533. };
  16534. }
  16535. function complexAdjustableColorFilter(matrixAdjustFn) {
  16536. return function (ir, adjust) {
  16537. return colorFilter(ir, matrixAdjustFn(identity$1(), adjust));
  16538. };
  16539. }
  16540. function basicColorFilter(matrix) {
  16541. return function (ir) {
  16542. return colorFilter(ir, matrix);
  16543. };
  16544. }
  16545. function basicConvolutionFilter(kernel) {
  16546. return function (ir) {
  16547. return convoluteFilter(ir, kernel);
  16548. };
  16549. }
  16550. var invert = basicColorFilter([
  16551. -1,
  16552. 0,
  16553. 0,
  16554. 0,
  16555. 255,
  16556. 0,
  16557. -1,
  16558. 0,
  16559. 0,
  16560. 255,
  16561. 0,
  16562. 0,
  16563. -1,
  16564. 0,
  16565. 255,
  16566. 0,
  16567. 0,
  16568. 0,
  16569. 1,
  16570. 0,
  16571. 0,
  16572. 0,
  16573. 0,
  16574. 0,
  16575. 1
  16576. ]);
  16577. var brightness = complexAdjustableColorFilter(adjustBrightness);
  16578. var contrast = complexAdjustableColorFilter(adjustContrast);
  16579. var colorize = function (ir, adjustR, adjustG, adjustB) {
  16580. return colorFilter(ir, adjustColors(identity$1(), adjustR, adjustG, adjustB));
  16581. };
  16582. var sharpen = basicConvolutionFilter([
  16583. 0,
  16584. -1,
  16585. 0,
  16586. -1,
  16587. 5,
  16588. -1,
  16589. 0,
  16590. -1,
  16591. 0
  16592. ]);
  16593. var gamma = functionColorFilter(function (color, value) {
  16594. return Math.pow(color / 255, 1 - value) * 255;
  16595. });
  16596. function scale(image, dW, dH) {
  16597. var sW = getWidth(image);
  16598. var sH = getHeight(image);
  16599. var wRatio = dW / sW;
  16600. var hRatio = dH / sH;
  16601. var scaleCapped = false;
  16602. if (wRatio < 0.5 || wRatio > 2) {
  16603. wRatio = wRatio < 0.5 ? 0.5 : 2;
  16604. scaleCapped = true;
  16605. }
  16606. if (hRatio < 0.5 || hRatio > 2) {
  16607. hRatio = hRatio < 0.5 ? 0.5 : 2;
  16608. scaleCapped = true;
  16609. }
  16610. var scaled = _scale(image, wRatio, hRatio);
  16611. return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  16612. return scale(tCanvas, dW, dH);
  16613. });
  16614. }
  16615. function _scale(image, wRatio, hRatio) {
  16616. return new Promise$1(function (resolve) {
  16617. var sW = getWidth(image);
  16618. var sH = getHeight(image);
  16619. var dW = Math.floor(sW * wRatio);
  16620. var dH = Math.floor(sH * hRatio);
  16621. var canvas = create$5(dW, dH);
  16622. var context = get2dContext(canvas);
  16623. context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  16624. resolve(canvas);
  16625. });
  16626. }
  16627. function rotate(ir, angle) {
  16628. return ir.toCanvas().then(function (canvas) {
  16629. return applyRotate(canvas, ir.getType(), angle);
  16630. });
  16631. }
  16632. function applyRotate(image, type, angle) {
  16633. var canvas = create$5(image.width, image.height);
  16634. var context = get2dContext(canvas);
  16635. var translateX = 0;
  16636. var translateY = 0;
  16637. angle = angle < 0 ? 360 + angle : angle;
  16638. if (angle === 90 || angle === 270) {
  16639. resize(canvas, canvas.height, canvas.width);
  16640. }
  16641. if (angle === 90 || angle === 180) {
  16642. translateX = canvas.width;
  16643. }
  16644. if (angle === 270 || angle === 180) {
  16645. translateY = canvas.height;
  16646. }
  16647. context.translate(translateX, translateY);
  16648. context.rotate(angle * Math.PI / 180);
  16649. context.drawImage(image, 0, 0);
  16650. return fromCanvas(canvas, type);
  16651. }
  16652. function flip(ir, axis) {
  16653. return ir.toCanvas().then(function (canvas) {
  16654. return applyFlip(canvas, ir.getType(), axis);
  16655. });
  16656. }
  16657. function applyFlip(image, type, axis) {
  16658. var canvas = create$5(image.width, image.height);
  16659. var context = get2dContext(canvas);
  16660. if (axis === 'v') {
  16661. context.scale(1, -1);
  16662. context.drawImage(image, 0, -canvas.height);
  16663. } else {
  16664. context.scale(-1, 1);
  16665. context.drawImage(image, -canvas.width, 0);
  16666. }
  16667. return fromCanvas(canvas, type);
  16668. }
  16669. function crop(ir, x, y, w, h) {
  16670. return ir.toCanvas().then(function (canvas) {
  16671. return applyCrop(canvas, ir.getType(), x, y, w, h);
  16672. });
  16673. }
  16674. function applyCrop(image, type, x, y, w, h) {
  16675. var canvas = create$5(w, h);
  16676. var context = get2dContext(canvas);
  16677. context.drawImage(image, -x, -y);
  16678. return fromCanvas(canvas, type);
  16679. }
  16680. function resize$1(ir, w, h) {
  16681. return ir.toCanvas().then(function (canvas) {
  16682. return scale(canvas, w, h).then(function (newCanvas) {
  16683. return fromCanvas(newCanvas, ir.getType());
  16684. });
  16685. });
  16686. }
  16687. var invert$1 = function (ir) {
  16688. return invert(ir);
  16689. };
  16690. var sharpen$1 = function (ir) {
  16691. return sharpen(ir);
  16692. };
  16693. var gamma$1 = function (ir, value) {
  16694. return gamma(ir, value);
  16695. };
  16696. var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  16697. return colorize(ir, adjustR, adjustG, adjustB);
  16698. };
  16699. var brightness$1 = function (ir, adjust) {
  16700. return brightness(ir, adjust);
  16701. };
  16702. var contrast$1 = function (ir, adjust) {
  16703. return contrast(ir, adjust);
  16704. };
  16705. var flip$1 = function (ir, axis) {
  16706. return flip(ir, axis);
  16707. };
  16708. var crop$1 = function (ir, x, y, w, h) {
  16709. return crop(ir, x, y, w, h);
  16710. };
  16711. var resize$2 = function (ir, w, h) {
  16712. return resize$1(ir, w, h);
  16713. };
  16714. var rotate$1 = function (ir, angle) {
  16715. return rotate(ir, angle);
  16716. };
  16717. var renderIcon$1 = function (iconHtml, behaviours) {
  16718. return __assign({
  16719. dom: {
  16720. tag: 'span',
  16721. innerHtml: iconHtml,
  16722. classes: [
  16723. 'tox-icon',
  16724. 'tox-tbtn__icon-wrap'
  16725. ]
  16726. }
  16727. }, behaviours);
  16728. };
  16729. var renderIconFromPack = function (iconName, iconsProvider) {
  16730. return renderIcon$1(get$d(iconName, iconsProvider), {});
  16731. };
  16732. var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  16733. return renderIcon$1(get$d(iconName, iconsProvider), { behaviours: derive$1([Replacing.config({})]) });
  16734. };
  16735. var renderLabel$1 = function (text, prefix, providersBackstage) {
  16736. return {
  16737. dom: {
  16738. tag: 'span',
  16739. innerHtml: providersBackstage.translate(text),
  16740. classes: [prefix + '__select-label']
  16741. },
  16742. behaviours: derive$1([Replacing.config({})])
  16743. };
  16744. };
  16745. var internalToolbarButtonExecute = generate$1('toolbar.button.execute');
  16746. var onToolbarButtonExecute = function (info) {
  16747. return runOnExecute(function (comp, simulatedEvent) {
  16748. runWithApi(info, comp)(function (itemApi) {
  16749. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  16750. info.onAction(itemApi);
  16751. });
  16752. });
  16753. };
  16754. var toolbarButtonEventOrder = {
  16755. 'alloy.execute': [
  16756. 'disabling',
  16757. 'alloy.base.behaviour',
  16758. 'toggling',
  16759. 'toolbar-button-events'
  16760. ]
  16761. };
  16762. var updateMenuText = generate$1('update-menu-text');
  16763. var updateMenuIcon = generate$1('update-menu-icon');
  16764. var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  16765. var editorOffCell = Cell(noop);
  16766. var optMemDisplayText = spec.text.map(function (text) {
  16767. return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  16768. });
  16769. var optMemDisplayIcon = spec.icon.map(function (iconName) {
  16770. return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  16771. });
  16772. var onLeftOrRightInMenu = function (comp, se) {
  16773. var dropdown = Representing.getValue(comp);
  16774. Focusing.focus(dropdown);
  16775. emitWith(dropdown, 'keydown', { raw: se.event().raw() });
  16776. Dropdown.close(dropdown);
  16777. return Option.some(true);
  16778. };
  16779. var role = spec.role.fold(function () {
  16780. return {};
  16781. }, function (role) {
  16782. return { role: role };
  16783. });
  16784. var tooltipAttributes = spec.tooltip.fold(function () {
  16785. return {};
  16786. }, function (tooltip) {
  16787. var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  16788. return {
  16789. 'title': translatedTooltip,
  16790. 'aria-label': translatedTooltip
  16791. };
  16792. });
  16793. var memDropdown = record(Dropdown.sketch(__assign(__assign({}, role), {
  16794. dom: {
  16795. tag: 'button',
  16796. classes: [
  16797. prefix,
  16798. prefix + '--select'
  16799. ].concat(map(spec.classes, function (c) {
  16800. return prefix + '--' + c;
  16801. })),
  16802. attributes: __assign({}, tooltipAttributes)
  16803. },
  16804. components: componentRenderPipeline([
  16805. optMemDisplayIcon.map(function (mem) {
  16806. return mem.asSpec();
  16807. }),
  16808. optMemDisplayText.map(function (mem) {
  16809. return mem.asSpec();
  16810. }),
  16811. Option.some({
  16812. dom: {
  16813. tag: 'div',
  16814. classes: [prefix + '__select-chevron'],
  16815. innerHtml: get$d('chevron-down', sharedBackstage.providers.icons)
  16816. }
  16817. })
  16818. ]),
  16819. matchWidth: true,
  16820. useMinWidth: true,
  16821. dropdownBehaviours: derive$1(__spreadArrays(spec.dropdownBehaviours, [
  16822. DisablingConfigs.button(spec.disabled),
  16823. Unselecting.config({}),
  16824. Replacing.config({}),
  16825. config('dropdown-events', [
  16826. onControlAttached(spec, editorOffCell),
  16827. onControlDetached(spec, editorOffCell)
  16828. ]),
  16829. config('menubutton-update-display-text', [
  16830. run(updateMenuText, function (comp, se) {
  16831. optMemDisplayText.bind(function (mem) {
  16832. return mem.getOpt(comp);
  16833. }).each(function (displayText) {
  16834. Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event().text()))]);
  16835. });
  16836. }),
  16837. run(updateMenuIcon, function (comp, se) {
  16838. optMemDisplayIcon.bind(function (mem) {
  16839. return mem.getOpt(comp);
  16840. }).each(function (displayIcon) {
  16841. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event().icon(), sharedBackstage.providers.icons)]);
  16842. });
  16843. })
  16844. ])
  16845. ])),
  16846. eventOrder: deepMerge(toolbarButtonEventOrder, {
  16847. mousedown: [
  16848. 'focusing',
  16849. 'alloy.base.behaviour',
  16850. 'item-type-events',
  16851. 'normal-dropdown-events'
  16852. ]
  16853. }),
  16854. sandboxBehaviours: derive$1([Keying.config({
  16855. mode: 'special',
  16856. onLeft: onLeftOrRightInMenu,
  16857. onRight: onLeftOrRightInMenu
  16858. })]),
  16859. lazySink: sharedBackstage.getSink,
  16860. toggleClass: prefix + '--active',
  16861. parts: { menu: part(false, spec.columns, spec.presets) },
  16862. fetch: function () {
  16863. return Future.nu(spec.fetch);
  16864. }
  16865. })));
  16866. return memDropdown.asSpec();
  16867. };
  16868. var isMenuItemReference = function (item) {
  16869. return isString(item);
  16870. };
  16871. var isSeparator = function (item) {
  16872. return item.type === 'separator';
  16873. };
  16874. var isExpandingMenuItem = function (item) {
  16875. return has(item, 'getSubmenuItems');
  16876. };
  16877. var separator$1 = { type: 'separator' };
  16878. var unwrapReferences = function (items, menuItems) {
  16879. var realItems = foldl(items, function (acc, item) {
  16880. if (isMenuItemReference(item)) {
  16881. if (item === '') {
  16882. return acc;
  16883. } else if (item === '|') {
  16884. return acc.length > 0 && !isSeparator(acc[acc.length - 1]) ? acc.concat([separator$1]) : acc;
  16885. } else if (has(menuItems, item.toLowerCase())) {
  16886. return acc.concat([menuItems[item.toLowerCase()]]);
  16887. } else {
  16888. return acc;
  16889. }
  16890. } else {
  16891. return acc.concat([item]);
  16892. }
  16893. }, []);
  16894. if (realItems.length > 0 && isSeparator(realItems[realItems.length - 1])) {
  16895. realItems.pop();
  16896. }
  16897. return realItems;
  16898. };
  16899. var getFromExpandingItem = function (item, menuItems) {
  16900. var submenuItems = item.getSubmenuItems();
  16901. var rest = expand(submenuItems, menuItems);
  16902. var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  16903. var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  16904. return {
  16905. item: item,
  16906. menus: newMenus,
  16907. expansions: newExpansions
  16908. };
  16909. };
  16910. var getFromItem = function (item, menuItems) {
  16911. return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  16912. item: item,
  16913. menus: {},
  16914. expansions: {}
  16915. };
  16916. };
  16917. var generateValueIfRequired = function (item) {
  16918. if (isSeparator(item)) {
  16919. return item;
  16920. } else {
  16921. var itemValue = get(item, 'value').getOrThunk(function () {
  16922. return generate$1('generated-menu-item');
  16923. });
  16924. return deepMerge({ value: itemValue }, item);
  16925. }
  16926. };
  16927. var expand = function (items, menuItems) {
  16928. var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  16929. return foldr(realItems, function (acc, item) {
  16930. var itemWithValue = generateValueIfRequired(item);
  16931. var newData = getFromItem(itemWithValue, menuItems);
  16932. return {
  16933. menus: deepMerge(acc.menus, newData.menus),
  16934. items: [newData.item].concat(acc.items),
  16935. expansions: deepMerge(acc.expansions, newData.expansions)
  16936. };
  16937. }, {
  16938. menus: {},
  16939. expansions: {},
  16940. items: []
  16941. });
  16942. };
  16943. var build$2 = function (items, itemResponse, backstage, isHorizontalMenu) {
  16944. var primary = generate$1('primary-menu');
  16945. var data = expand(items, backstage.shared.providers.menuItems());
  16946. if (data.items.length === 0) {
  16947. return Option.none();
  16948. }
  16949. var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  16950. var submenus = map$1(data.menus, function (menuItems, menuName) {
  16951. return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  16952. });
  16953. var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  16954. return Option.from(tieredMenu.tieredData(primary, menus, data.expansions));
  16955. };
  16956. var getMenuButtonApi = function (component) {
  16957. return {
  16958. isDisabled: function () {
  16959. return Disabling.isDisabled(component);
  16960. },
  16961. setDisabled: function (state) {
  16962. return Disabling.set(component, state);
  16963. },
  16964. setActive: function (state) {
  16965. var elm = component.element();
  16966. if (state) {
  16967. add$2(elm, 'tox-tbtn--enabled');
  16968. set$1(elm, 'aria-pressed', true);
  16969. } else {
  16970. remove$4(elm, 'tox-tbtn--enabled');
  16971. remove$1(elm, 'aria-pressed');
  16972. }
  16973. },
  16974. isActive: function () {
  16975. return has$2(component.element(), 'tox-tbtn--enabled');
  16976. }
  16977. };
  16978. };
  16979. var renderMenuButton = function (spec, prefix, backstage, role) {
  16980. return renderCommonDropdown({
  16981. text: spec.text,
  16982. icon: spec.icon,
  16983. tooltip: spec.tooltip,
  16984. role: role,
  16985. fetch: function (callback) {
  16986. spec.fetch(function (items) {
  16987. callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  16988. });
  16989. },
  16990. onSetup: spec.onSetup,
  16991. getApi: getMenuButtonApi,
  16992. columns: 1,
  16993. presets: 'normal',
  16994. classes: [],
  16995. dropdownBehaviours: [Tabstopping.config({})]
  16996. }, prefix, backstage.shared);
  16997. };
  16998. var getFetch$1 = function (items, getButton, backstage) {
  16999. var getMenuItemAction = function (item) {
  17000. return function (api) {
  17001. var newValue = !api.isActive();
  17002. api.setActive(newValue);
  17003. item.storage.set(newValue);
  17004. backstage.shared.getSink().each(function (sink) {
  17005. getButton().getOpt(sink).each(function (orig) {
  17006. focus$1(orig.element());
  17007. emitWith(orig, formActionEvent, {
  17008. name: item.name,
  17009. value: item.storage.get()
  17010. });
  17011. });
  17012. });
  17013. };
  17014. };
  17015. var getMenuItemSetup = function (item) {
  17016. return function (api) {
  17017. api.setActive(item.storage.get());
  17018. };
  17019. };
  17020. return function (success) {
  17021. success(map(items, function (item) {
  17022. var text = item.text.fold(function () {
  17023. return {};
  17024. }, function (text) {
  17025. return { text: text };
  17026. });
  17027. return __assign(__assign({
  17028. type: item.type,
  17029. active: false
  17030. }, text), {
  17031. onAction: getMenuItemAction(item),
  17032. onSetup: getMenuItemSetup(item)
  17033. });
  17034. }));
  17035. };
  17036. };
  17037. var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components) {
  17038. if (extraBehaviours === void 0) {
  17039. extraBehaviours = [];
  17040. }
  17041. var action = actionOpt.fold(function () {
  17042. return {};
  17043. }, function (action) {
  17044. return { action: action };
  17045. });
  17046. var common = __assign({
  17047. buttonBehaviours: derive$1([
  17048. DisablingConfigs.button(spec.disabled),
  17049. Tabstopping.config({}),
  17050. config('button press', [
  17051. preventDefault('click'),
  17052. preventDefault('mousedown')
  17053. ])
  17054. ].concat(extraBehaviours)),
  17055. eventOrder: {
  17056. click: [
  17057. 'button press',
  17058. 'alloy.base.behaviour'
  17059. ],
  17060. mousedown: [
  17061. 'button press',
  17062. 'alloy.base.behaviour'
  17063. ]
  17064. }
  17065. }, action);
  17066. var domFinal = deepMerge(common, { dom: dom });
  17067. return deepMerge(domFinal, { components: components });
  17068. };
  17069. var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  17070. if (extraBehaviours === void 0) {
  17071. extraBehaviours = [];
  17072. }
  17073. var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  17074. return {
  17075. 'aria-label': providersBackstage.translate(tooltip),
  17076. 'title': providersBackstage.translate(tooltip)
  17077. };
  17078. }).getOr({});
  17079. var dom = {
  17080. tag: 'button',
  17081. classes: ['tox-tbtn'],
  17082. attributes: tooltipAttributes
  17083. };
  17084. var icon = spec.icon.map(function (iconName) {
  17085. return renderIconFromPack(iconName, providersBackstage.icons);
  17086. });
  17087. var components = componentRenderPipeline([icon]);
  17088. return renderCommonSpec(spec, action, extraBehaviours, dom, components);
  17089. };
  17090. var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  17091. if (extraBehaviours === void 0) {
  17092. extraBehaviours = [];
  17093. }
  17094. var iconButtonSpec = renderIconButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours);
  17095. return Button.sketch(iconButtonSpec);
  17096. };
  17097. var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17098. if (extraBehaviours === void 0) {
  17099. extraBehaviours = [];
  17100. }
  17101. if (extraClasses === void 0) {
  17102. extraClasses = [];
  17103. }
  17104. var translatedText = providersBackstage.translate(spec.text);
  17105. var icon = spec.icon ? spec.icon.map(function (iconName) {
  17106. return renderIconFromPack(iconName, providersBackstage.icons);
  17107. }) : Option.none();
  17108. var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  17109. var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  17110. var classes = __spreadArrays(!spec.primary && !spec.borderless ? [
  17111. 'tox-button',
  17112. 'tox-button--secondary'
  17113. ] : ['tox-button'], icon.isSome() ? ['tox-button--icon'] : [], spec.borderless ? ['tox-button--naked'] : [], extraClasses);
  17114. var dom = __assign(__assign({
  17115. tag: 'button',
  17116. classes: classes
  17117. }, innerHtml), { attributes: { title: translatedText } });
  17118. return renderCommonSpec(spec, action, extraBehaviours, dom, components);
  17119. };
  17120. var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17121. if (extraBehaviours === void 0) {
  17122. extraBehaviours = [];
  17123. }
  17124. if (extraClasses === void 0) {
  17125. extraClasses = [];
  17126. }
  17127. var buttonSpec = renderButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours, extraClasses);
  17128. return Button.sketch(buttonSpec);
  17129. };
  17130. var getAction = function (name, buttonType) {
  17131. return function (comp) {
  17132. if (buttonType === 'custom') {
  17133. emitWith(comp, formActionEvent, {
  17134. name: name,
  17135. value: {}
  17136. });
  17137. } else if (buttonType === 'submit') {
  17138. emit(comp, formSubmitEvent);
  17139. } else if (buttonType === 'cancel') {
  17140. emit(comp, formCancelEvent);
  17141. } else {
  17142. domGlobals.console.error('Unknown button type: ', buttonType);
  17143. }
  17144. };
  17145. };
  17146. var isMenuFooterButtonSpec = function (spec, buttonType) {
  17147. return buttonType === 'menu';
  17148. };
  17149. var isNormalFooterButtonSpec = function (spec, buttonType) {
  17150. return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  17151. };
  17152. var renderFooterButton = function (spec, buttonType, backstage) {
  17153. if (isMenuFooterButtonSpec(spec, buttonType)) {
  17154. var getButton = function () {
  17155. return memButton_1;
  17156. };
  17157. var menuButtonSpec = spec;
  17158. var fixedSpec = __assign(__assign({}, spec), {
  17159. onSetup: function (api) {
  17160. api.setDisabled(spec.disabled);
  17161. return noop;
  17162. },
  17163. fetch: getFetch$1(menuButtonSpec.items, getButton, backstage)
  17164. });
  17165. var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Option.none()));
  17166. return memButton_1.asSpec();
  17167. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  17168. var action = getAction(spec.name, buttonType);
  17169. var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  17170. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  17171. } else {
  17172. domGlobals.console.error('Unknown footer button type: ', buttonType);
  17173. }
  17174. };
  17175. var renderDialogButton = function (spec, providersBackstage) {
  17176. var action = getAction(spec.name, 'custom');
  17177. return renderFormField(Option.none(), FormField.parts().field(__assign({ factory: Button }, renderButtonSpec(spec, Option.some(action), providersBackstage, [
  17178. RepresentingConfigs.memory(''),
  17179. ComposingConfigs.self()
  17180. ]))));
  17181. };
  17182. var schema$i = constant([
  17183. defaulted$1('field1Name', 'field1'),
  17184. defaulted$1('field2Name', 'field2'),
  17185. onStrictHandler('onLockedChange'),
  17186. markers(['lockClass']),
  17187. defaulted$1('locked', false),
  17188. SketchBehaviours.field('coupledFieldBehaviours', [
  17189. Composing,
  17190. Representing
  17191. ])
  17192. ]);
  17193. var getField = function (comp, detail, partName) {
  17194. return getPart(comp, detail, partName).bind(Composing.getCurrent);
  17195. };
  17196. var coupledPart = function (selfName, otherName) {
  17197. return required({
  17198. factory: FormField,
  17199. name: selfName,
  17200. overrides: function (detail) {
  17201. return {
  17202. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run(input(), function (me) {
  17203. getField(me, detail, otherName).each(function (other) {
  17204. getPart(me, detail, 'lock').each(function (lock) {
  17205. if (Toggling.isOn(lock)) {
  17206. detail.onLockedChange(me, other, lock);
  17207. }
  17208. });
  17209. });
  17210. })])])
  17211. };
  17212. }
  17213. });
  17214. };
  17215. var parts$5 = constant([
  17216. coupledPart('field1', 'field2'),
  17217. coupledPart('field2', 'field1'),
  17218. required({
  17219. factory: Button,
  17220. schema: [strict$1('dom')],
  17221. name: 'lock',
  17222. overrides: function (detail) {
  17223. return {
  17224. buttonBehaviours: derive$1([Toggling.config({
  17225. selected: detail.locked,
  17226. toggleClass: detail.markers.lockClass,
  17227. aria: { mode: 'pressed' }
  17228. })])
  17229. };
  17230. }
  17231. })
  17232. ]);
  17233. var factory$7 = function (detail, components, spec, externals) {
  17234. return {
  17235. uid: detail.uid,
  17236. dom: detail.dom,
  17237. components: components,
  17238. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  17239. Composing.config({ find: Option.some }),
  17240. Representing.config({
  17241. store: {
  17242. mode: 'manual',
  17243. getValue: function (comp) {
  17244. var _a;
  17245. var parts = getPartsOrDie(comp, detail, [
  17246. 'field1',
  17247. 'field2'
  17248. ]);
  17249. return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  17250. },
  17251. setValue: function (comp, value) {
  17252. var parts = getPartsOrDie(comp, detail, [
  17253. 'field1',
  17254. 'field2'
  17255. ]);
  17256. if (hasNonNullableKey(value, detail.field1Name)) {
  17257. Representing.setValue(parts.field1(), value[detail.field1Name]);
  17258. }
  17259. if (hasNonNullableKey(value, detail.field2Name)) {
  17260. Representing.setValue(parts.field2(), value[detail.field2Name]);
  17261. }
  17262. }
  17263. }
  17264. })
  17265. ]),
  17266. apis: {
  17267. getField1: function (component) {
  17268. return getPart(component, detail, 'field1');
  17269. },
  17270. getField2: function (component) {
  17271. return getPart(component, detail, 'field2');
  17272. },
  17273. getLock: function (component) {
  17274. return getPart(component, detail, 'lock');
  17275. }
  17276. }
  17277. };
  17278. };
  17279. var FormCoupledInputs = composite$1({
  17280. name: 'FormCoupledInputs',
  17281. configFields: schema$i(),
  17282. partFields: parts$5(),
  17283. factory: factory$7,
  17284. apis: {
  17285. getField1: function (apis, component) {
  17286. return apis.getField1(component);
  17287. },
  17288. getField2: function (apis, component) {
  17289. return apis.getField2(component);
  17290. },
  17291. getLock: function (apis, component) {
  17292. return apis.getLock(component);
  17293. }
  17294. }
  17295. });
  17296. var formatSize = function (size) {
  17297. var unitDec = {
  17298. '': 0,
  17299. 'px': 0,
  17300. 'pt': 1,
  17301. 'mm': 1,
  17302. 'pc': 2,
  17303. 'ex': 2,
  17304. 'em': 2,
  17305. 'ch': 2,
  17306. 'rem': 2,
  17307. 'cm': 3,
  17308. 'in': 4,
  17309. '%': 4
  17310. };
  17311. var maxDecimal = function (unit) {
  17312. return unit in unitDec ? unitDec[unit] : 1;
  17313. };
  17314. var numText = size.value.toFixed(maxDecimal(size.unit));
  17315. if (numText.indexOf('.') !== -1) {
  17316. numText = numText.replace(/\.?0*$/, '');
  17317. }
  17318. return numText + size.unit;
  17319. };
  17320. var parseSize = function (sizeText) {
  17321. var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  17322. var match = numPattern.exec(sizeText);
  17323. if (match !== null) {
  17324. var value = parseFloat(match[1]);
  17325. var unit = match[2];
  17326. return Result.value({
  17327. value: value,
  17328. unit: unit
  17329. });
  17330. } else {
  17331. return Result.error(sizeText);
  17332. }
  17333. };
  17334. var convertUnit = function (size, unit) {
  17335. var inInch = {
  17336. '': 96,
  17337. 'px': 96,
  17338. 'pt': 72,
  17339. 'cm': 2.54,
  17340. 'pc': 12,
  17341. 'mm': 25.4,
  17342. 'in': 1
  17343. };
  17344. var supported = function (u) {
  17345. return Object.prototype.hasOwnProperty.call(inInch, u);
  17346. };
  17347. if (size.unit === unit) {
  17348. return Option.some(size.value);
  17349. } else if (supported(size.unit) && supported(unit)) {
  17350. if (inInch[size.unit] === inInch[unit]) {
  17351. return Option.some(size.value);
  17352. } else {
  17353. return Option.some(size.value / inInch[size.unit] * inInch[unit]);
  17354. }
  17355. } else {
  17356. return Option.none();
  17357. }
  17358. };
  17359. var noSizeConversion = function (input) {
  17360. return Option.none();
  17361. };
  17362. var ratioSizeConversion = function (scale, unit) {
  17363. return function (size) {
  17364. return convertUnit(size, unit).map(function (value) {
  17365. return {
  17366. value: value * scale,
  17367. unit: unit
  17368. };
  17369. });
  17370. };
  17371. };
  17372. var makeRatioConverter = function (currentFieldText, otherFieldText) {
  17373. var cValue = parseSize(currentFieldText).toOption();
  17374. var oValue = parseSize(otherFieldText).toOption();
  17375. return lift2(cValue, oValue, function (cSize, oSize) {
  17376. return convertUnit(cSize, oSize.unit).map(function (val) {
  17377. return oSize.value / val;
  17378. }).map(function (r) {
  17379. return ratioSizeConversion(r, oSize.unit);
  17380. }).getOr(noSizeConversion);
  17381. }).getOr(noSizeConversion);
  17382. };
  17383. var renderSizeInput = function (spec, providersBackstage) {
  17384. var converter = noSizeConversion;
  17385. var ratioEvent = generate$1('ratio-event');
  17386. var pLock = FormCoupledInputs.parts().lock({
  17387. dom: {
  17388. tag: 'button',
  17389. classes: [
  17390. 'tox-lock',
  17391. 'tox-button',
  17392. 'tox-button--naked',
  17393. 'tox-button--icon'
  17394. ],
  17395. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  17396. },
  17397. components: [
  17398. {
  17399. dom: {
  17400. tag: 'span',
  17401. classes: [
  17402. 'tox-icon',
  17403. 'tox-lock-icon__lock'
  17404. ],
  17405. innerHtml: get$d('lock', providersBackstage.icons)
  17406. }
  17407. },
  17408. {
  17409. dom: {
  17410. tag: 'span',
  17411. classes: [
  17412. 'tox-icon',
  17413. 'tox-lock-icon__unlock'
  17414. ],
  17415. innerHtml: get$d('unlock', providersBackstage.icons)
  17416. }
  17417. }
  17418. ],
  17419. buttonBehaviours: derive$1([
  17420. DisablingConfigs.button(spec.disabled),
  17421. Tabstopping.config({})
  17422. ])
  17423. });
  17424. var formGroup = function (components) {
  17425. return {
  17426. dom: {
  17427. tag: 'div',
  17428. classes: ['tox-form__group']
  17429. },
  17430. components: components
  17431. };
  17432. };
  17433. var getFieldPart = function (isField1) {
  17434. return FormField.parts().field({
  17435. factory: Input,
  17436. inputClasses: ['tox-textfield'],
  17437. inputBehaviours: derive$1([
  17438. Disabling.config({ disabled: spec.disabled }),
  17439. Tabstopping.config({}),
  17440. config('size-input-events', [
  17441. run(focusin(), function (component, simulatedEvent) {
  17442. emitWith(component, ratioEvent, { isField1: isField1 });
  17443. }),
  17444. run(change(), function (component, simulatedEvent) {
  17445. emitWith(component, formChangeEvent, { name: spec.name });
  17446. })
  17447. ])
  17448. ]),
  17449. selectOnFocus: false
  17450. });
  17451. };
  17452. var getLabel = function (label) {
  17453. return {
  17454. dom: {
  17455. tag: 'label',
  17456. classes: ['tox-label'],
  17457. innerHtml: providersBackstage.translate(label)
  17458. }
  17459. };
  17460. };
  17461. var widthField = FormCoupledInputs.parts().field1(formGroup([
  17462. FormField.parts().label(getLabel('Width')),
  17463. getFieldPart(true)
  17464. ]));
  17465. var heightField = FormCoupledInputs.parts().field2(formGroup([
  17466. FormField.parts().label(getLabel('Height')),
  17467. getFieldPart(false)
  17468. ]));
  17469. return FormCoupledInputs.sketch({
  17470. dom: {
  17471. tag: 'div',
  17472. classes: ['tox-form__group']
  17473. },
  17474. components: [{
  17475. dom: {
  17476. tag: 'div',
  17477. classes: ['tox-form__controls-h-stack']
  17478. },
  17479. components: [
  17480. widthField,
  17481. heightField,
  17482. formGroup([
  17483. getLabel('&nbsp;'),
  17484. pLock
  17485. ])
  17486. ]
  17487. }],
  17488. field1Name: 'width',
  17489. field2Name: 'height',
  17490. locked: true,
  17491. markers: { lockClass: 'tox-locked' },
  17492. onLockedChange: function (current, other, lock) {
  17493. parseSize(Representing.getValue(current)).each(function (size) {
  17494. converter(size).each(function (newSize) {
  17495. Representing.setValue(other, formatSize(newSize));
  17496. });
  17497. });
  17498. },
  17499. coupledFieldBehaviours: derive$1([
  17500. Disabling.config({
  17501. disabled: spec.disabled,
  17502. onDisabled: function (comp) {
  17503. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  17504. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  17505. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  17506. },
  17507. onEnabled: function (comp) {
  17508. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  17509. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  17510. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  17511. }
  17512. }),
  17513. config('size-input-events2', [run(ratioEvent, function (component, simulatedEvent) {
  17514. var isField1 = simulatedEvent.event().isField1();
  17515. var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  17516. var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  17517. var value1 = optCurrent.map(Representing.getValue).getOr('');
  17518. var value2 = optOther.map(Representing.getValue).getOr('');
  17519. converter = makeRatioConverter(value1, value2);
  17520. })])
  17521. ])
  17522. });
  17523. };
  17524. var undo = constant(generate$1('undo'));
  17525. var redo = constant(generate$1('redo'));
  17526. var zoom = constant(generate$1('zoom'));
  17527. var back = constant(generate$1('back'));
  17528. var apply = constant(generate$1('apply'));
  17529. var swap = constant(generate$1('swap'));
  17530. var transform = constant(generate$1('transform'));
  17531. var tempTransform = constant(generate$1('temp-transform'));
  17532. var transformApply = constant(generate$1('transform-apply'));
  17533. var internal = {
  17534. undo: undo,
  17535. redo: redo,
  17536. zoom: zoom,
  17537. back: back,
  17538. apply: apply,
  17539. swap: swap,
  17540. transform: transform,
  17541. tempTransform: tempTransform,
  17542. transformApply: transformApply
  17543. };
  17544. var saveState = constant('save-state');
  17545. var disable$1 = constant('disable');
  17546. var enable$1 = constant('enable');
  17547. var external$2 = {
  17548. formActionEvent: formActionEvent,
  17549. saveState: saveState,
  17550. disable: disable$1,
  17551. enable: enable$1
  17552. };
  17553. var renderEditPanel = function (imagePanel, providersBackstage) {
  17554. var createButton = function (text, action, disabled, primary) {
  17555. return record(renderButton({
  17556. name: text,
  17557. text: text,
  17558. disabled: disabled,
  17559. primary: primary,
  17560. icon: Option.none(),
  17561. borderless: false
  17562. }, action, providersBackstage));
  17563. };
  17564. var createIconButton = function (icon, tooltip, action, disabled) {
  17565. return record(renderIconButton({
  17566. name: icon,
  17567. icon: Option.some(icon),
  17568. tooltip: Option.some(tooltip),
  17569. disabled: disabled,
  17570. primary: false,
  17571. borderless: false
  17572. }, action, providersBackstage));
  17573. };
  17574. var disableAllComponents = function (comps, eventcomp) {
  17575. comps.map(function (mem) {
  17576. var component = mem.get(eventcomp);
  17577. if (component.hasConfigured(Disabling)) {
  17578. Disabling.disable(component);
  17579. }
  17580. });
  17581. };
  17582. var enableAllComponents = function (comps, eventcomp) {
  17583. comps.map(function (mem) {
  17584. var component = mem.get(eventcomp);
  17585. if (component.hasConfigured(Disabling)) {
  17586. Disabling.enable(component);
  17587. }
  17588. });
  17589. };
  17590. var panelDom = {
  17591. tag: 'div',
  17592. classes: [
  17593. 'tox-image-tools__toolbar',
  17594. 'tox-image-tools-edit-panel'
  17595. ]
  17596. };
  17597. var noop$1 = noop;
  17598. var emit$1 = function (comp, event, data) {
  17599. emitWith(comp, event, data);
  17600. };
  17601. var emitDisable = function (component) {
  17602. return emit(component, external$2.disable());
  17603. };
  17604. var emitEnable = function (component) {
  17605. return emit(component, external$2.enable());
  17606. };
  17607. var emitTransform = function (comp, transform) {
  17608. emitDisable(comp);
  17609. emit$1(comp, internal.transform(), { transform: transform });
  17610. emitEnable(comp);
  17611. };
  17612. var emitTempTransform = function (comp, transform) {
  17613. emitDisable(comp);
  17614. emit$1(comp, internal.tempTransform(), { transform: transform });
  17615. emitEnable(comp);
  17616. };
  17617. var getBackSwap = function (anyInSystem) {
  17618. return function () {
  17619. memContainer.getOpt(anyInSystem).each(function (container) {
  17620. Replacing.set(container, [ButtonPanel]);
  17621. });
  17622. };
  17623. };
  17624. var emitTransformApply = function (comp, transform) {
  17625. emitDisable(comp);
  17626. emit$1(comp, internal.transformApply(), {
  17627. transform: transform,
  17628. swap: getBackSwap(comp)
  17629. });
  17630. emitEnable(comp);
  17631. };
  17632. var createBackButton = function () {
  17633. return createButton('Back', function (button) {
  17634. return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  17635. }, false, false);
  17636. };
  17637. var createSpacer = function () {
  17638. return record({
  17639. dom: {
  17640. tag: 'div',
  17641. classes: ['tox-spacer']
  17642. },
  17643. behaviours: derive$1([Disabling.config({})])
  17644. });
  17645. };
  17646. var createApplyButton = function () {
  17647. return createButton('Apply', function (button) {
  17648. return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  17649. }, true, true);
  17650. };
  17651. var makeCropTransform = function () {
  17652. return function (ir) {
  17653. var rect = imagePanel.getRect();
  17654. return crop$1(ir, rect.x, rect.y, rect.w, rect.h);
  17655. };
  17656. };
  17657. var cropPanelComponents = [
  17658. createBackButton(),
  17659. createSpacer(),
  17660. createButton('Apply', function (button) {
  17661. var transform = makeCropTransform();
  17662. emitTransformApply(button, transform);
  17663. imagePanel.hideCrop();
  17664. }, false, true)
  17665. ];
  17666. var CropPanel = Container.sketch({
  17667. dom: panelDom,
  17668. components: cropPanelComponents.map(function (mem) {
  17669. return mem.asSpec();
  17670. }),
  17671. containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  17672. run(external$2.disable(), function (comp, se) {
  17673. disableAllComponents(cropPanelComponents, comp);
  17674. }),
  17675. run(external$2.enable(), function (comp, se) {
  17676. enableAllComponents(cropPanelComponents, comp);
  17677. })
  17678. ])])
  17679. });
  17680. var memSize = record(renderSizeInput({
  17681. name: 'size',
  17682. label: Option.none(),
  17683. constrain: true,
  17684. disabled: false
  17685. }, providersBackstage));
  17686. var makeResizeTransform = function (width, height) {
  17687. return function (ir) {
  17688. return resize$2(ir, width, height);
  17689. };
  17690. };
  17691. var resizePanelComponents = [
  17692. createBackButton(),
  17693. createSpacer(),
  17694. memSize,
  17695. createSpacer(),
  17696. createButton('Apply', function (button) {
  17697. memSize.getOpt(button).each(function (sizeInput) {
  17698. var value = Representing.getValue(sizeInput);
  17699. var width = parseInt(value.width, 10);
  17700. var height = parseInt(value.height, 10);
  17701. var transform = makeResizeTransform(width, height);
  17702. emitTransformApply(button, transform);
  17703. });
  17704. }, false, true)
  17705. ];
  17706. var ResizePanel = Container.sketch({
  17707. dom: panelDom,
  17708. components: resizePanelComponents.map(function (mem) {
  17709. return mem.asSpec();
  17710. }),
  17711. containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  17712. run(external$2.disable(), function (comp, se) {
  17713. disableAllComponents(resizePanelComponents, comp);
  17714. }),
  17715. run(external$2.enable(), function (comp, se) {
  17716. enableAllComponents(resizePanelComponents, comp);
  17717. })
  17718. ])])
  17719. });
  17720. var makeValueTransform = function (transform, value) {
  17721. return function (ir) {
  17722. return transform(ir, value);
  17723. };
  17724. };
  17725. var horizontalFlip = makeValueTransform(flip$1, 'h');
  17726. var verticalFlip = makeValueTransform(flip$1, 'v');
  17727. var counterclockwiseRotate = makeValueTransform(rotate$1, -90);
  17728. var clockwiseRotate = makeValueTransform(rotate$1, 90);
  17729. var flipRotateOnAction = function (comp, operation) {
  17730. emitTempTransform(comp, operation);
  17731. };
  17732. var flipRotateComponents = [
  17733. createBackButton(),
  17734. createSpacer(),
  17735. createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  17736. flipRotateOnAction(button, horizontalFlip);
  17737. }, false),
  17738. createIconButton('flip-vertically', 'Flip vertically', function (button) {
  17739. flipRotateOnAction(button, verticalFlip);
  17740. }, false),
  17741. createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  17742. flipRotateOnAction(button, counterclockwiseRotate);
  17743. }, false),
  17744. createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  17745. flipRotateOnAction(button, clockwiseRotate);
  17746. }, false),
  17747. createSpacer(),
  17748. createApplyButton()
  17749. ];
  17750. var FlipRotatePanel = Container.sketch({
  17751. dom: panelDom,
  17752. components: flipRotateComponents.map(function (mem) {
  17753. return mem.asSpec();
  17754. }),
  17755. containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  17756. run(external$2.disable(), function (comp, se) {
  17757. disableAllComponents(flipRotateComponents, comp);
  17758. }),
  17759. run(external$2.enable(), function (comp, se) {
  17760. enableAllComponents(flipRotateComponents, comp);
  17761. })
  17762. ])])
  17763. });
  17764. var makeSlider = function (label, onChoose, min, value, max) {
  17765. var labelPart = Slider.parts().label({
  17766. dom: {
  17767. tag: 'label',
  17768. classes: ['tox-label'],
  17769. innerHtml: providersBackstage.translate(label)
  17770. }
  17771. });
  17772. var spectrum = Slider.parts().spectrum({
  17773. dom: {
  17774. tag: 'div',
  17775. classes: ['tox-slider__rail'],
  17776. attributes: { role: 'presentation' }
  17777. }
  17778. });
  17779. var thumb = Slider.parts().thumb({
  17780. dom: {
  17781. tag: 'div',
  17782. classes: ['tox-slider__handle'],
  17783. attributes: { role: 'presentation' }
  17784. }
  17785. });
  17786. return record(Slider.sketch({
  17787. dom: {
  17788. tag: 'div',
  17789. classes: ['tox-slider'],
  17790. attributes: { role: 'presentation' }
  17791. },
  17792. model: {
  17793. mode: 'x',
  17794. minX: min,
  17795. maxX: max,
  17796. getInitialValue: constant({ x: constant(value) })
  17797. },
  17798. components: [
  17799. labelPart,
  17800. spectrum,
  17801. thumb
  17802. ],
  17803. sliderBehaviours: derive$1([Focusing.config({})]),
  17804. onChoose: onChoose
  17805. }));
  17806. };
  17807. var makeVariableSlider = function (label, transform, min, value, max) {
  17808. var onChoose = function (slider, thumb, value) {
  17809. var valTransform = makeValueTransform(transform, value.x() / 100);
  17810. emitTransform(slider, valTransform);
  17811. };
  17812. return makeSlider(label, onChoose, min, value, max);
  17813. };
  17814. var variableFilterPanelComponents = function (label, transform, min, value, max) {
  17815. return [
  17816. createBackButton(),
  17817. makeVariableSlider(label, transform, min, value, max),
  17818. createApplyButton()
  17819. ];
  17820. };
  17821. var createVariableFilterPanel = function (label, transform, min, value, max) {
  17822. var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  17823. return Container.sketch({
  17824. dom: panelDom,
  17825. components: filterPanelComponents.map(function (mem) {
  17826. return mem.asSpec();
  17827. }),
  17828. containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  17829. run(external$2.disable(), function (comp, se) {
  17830. disableAllComponents(filterPanelComponents, comp);
  17831. }),
  17832. run(external$2.enable(), function (comp, se) {
  17833. enableAllComponents(filterPanelComponents, comp);
  17834. })
  17835. ])])
  17836. });
  17837. };
  17838. var filterPanelComponents = [
  17839. createBackButton(),
  17840. createSpacer(),
  17841. createApplyButton()
  17842. ];
  17843. var FilterPanel = Container.sketch({
  17844. dom: panelDom,
  17845. components: filterPanelComponents.map(function (mem) {
  17846. return mem.asSpec();
  17847. })
  17848. });
  17849. var BrightnessPanel = createVariableFilterPanel('Brightness', brightness$1, -100, 0, 100);
  17850. var ContrastPanel = createVariableFilterPanel('Contrast', contrast$1, -100, 0, 100);
  17851. var GammaPanel = createVariableFilterPanel('Gamma', gamma$1, -100, 0, 100);
  17852. var makeColorTransform = function (red, green, blue) {
  17853. return function (ir) {
  17854. return colorize$1(ir, red, green, blue);
  17855. };
  17856. };
  17857. var makeColorSlider = function (label) {
  17858. var onChoose = function (slider, thumb, value) {
  17859. var redOpt = memRed.getOpt(slider);
  17860. var blueOpt = memBlue.getOpt(slider);
  17861. var greenOpt = memGreen.getOpt(slider);
  17862. redOpt.each(function (red) {
  17863. blueOpt.each(function (blue) {
  17864. greenOpt.each(function (green) {
  17865. var r = Representing.getValue(red).x() / 100;
  17866. var g = Representing.getValue(green).x() / 100;
  17867. var b = Representing.getValue(blue).x() / 100;
  17868. var transform = makeColorTransform(r, g, b);
  17869. emitTransform(slider, transform);
  17870. });
  17871. });
  17872. });
  17873. };
  17874. return makeSlider(label, onChoose, 0, 100, 200);
  17875. };
  17876. var memRed = makeColorSlider('R');
  17877. var memGreen = makeColorSlider('G');
  17878. var memBlue = makeColorSlider('B');
  17879. var colorizePanelComponents = [
  17880. createBackButton(),
  17881. memRed,
  17882. memGreen,
  17883. memBlue,
  17884. createApplyButton()
  17885. ];
  17886. var ColorizePanel = Container.sketch({
  17887. dom: panelDom,
  17888. components: colorizePanelComponents.map(function (mem) {
  17889. return mem.asSpec();
  17890. })
  17891. });
  17892. var getTransformPanelEvent = function (panel, transform, update) {
  17893. return function (button) {
  17894. var swap = function () {
  17895. memContainer.getOpt(button).each(function (container) {
  17896. Replacing.set(container, [panel]);
  17897. update(container);
  17898. });
  17899. };
  17900. emit$1(button, internal.swap(), {
  17901. transform: transform,
  17902. swap: swap
  17903. });
  17904. };
  17905. };
  17906. var cropPanelUpdate = function (_anyInSystem) {
  17907. imagePanel.showCrop();
  17908. };
  17909. var resizePanelUpdate = function (anyInSystem) {
  17910. memSize.getOpt(anyInSystem).each(function (sizeInput) {
  17911. var measurements = imagePanel.getMeasurements();
  17912. var width = measurements.width;
  17913. var height = measurements.height;
  17914. Representing.setValue(sizeInput, {
  17915. width: width,
  17916. height: height
  17917. });
  17918. });
  17919. };
  17920. var sharpenTransform = Option.some(sharpen$1);
  17921. var invertTransform = Option.some(invert$1);
  17922. var buttonPanelComponents = [
  17923. createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Option.none(), cropPanelUpdate), false),
  17924. createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Option.none(), resizePanelUpdate), false),
  17925. createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Option.none(), noop$1), false),
  17926. createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Option.none(), noop$1), false),
  17927. createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  17928. createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Option.none(), noop$1), false),
  17929. createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Option.none(), noop$1), false),
  17930. createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Option.none(), noop$1), false),
  17931. createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  17932. ];
  17933. var ButtonPanel = Container.sketch({
  17934. dom: panelDom,
  17935. components: buttonPanelComponents.map(function (mem) {
  17936. return mem.asSpec();
  17937. })
  17938. });
  17939. var container = Container.sketch({
  17940. dom: { tag: 'div' },
  17941. components: [ButtonPanel],
  17942. containerBehaviours: derive$1([Replacing.config({})])
  17943. });
  17944. var memContainer = record(container);
  17945. var getApplyButton = function (anyInSystem) {
  17946. return memContainer.getOpt(anyInSystem).map(function (container) {
  17947. var panel = container.components()[0];
  17948. return panel.components()[panel.components().length - 1];
  17949. });
  17950. };
  17951. return {
  17952. memContainer: memContainer,
  17953. getApplyButton: getApplyButton
  17954. };
  17955. };
  17956. var global$b = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');
  17957. var global$c = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  17958. var global$d = tinymce.util.Tools.resolve('tinymce.util.Observable');
  17959. var global$e = tinymce.util.Tools.resolve('tinymce.util.Tools');
  17960. var global$f = tinymce.util.Tools.resolve('tinymce.util.VK');
  17961. function getDocumentSize(doc) {
  17962. var documentElement, body, scrollWidth, clientWidth;
  17963. var offsetWidth, scrollHeight, clientHeight, offsetHeight;
  17964. var max = Math.max;
  17965. documentElement = doc.documentElement;
  17966. body = doc.body;
  17967. scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  17968. clientWidth = max(documentElement.clientWidth, body.clientWidth);
  17969. offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  17970. scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  17971. clientHeight = max(documentElement.clientHeight, body.clientHeight);
  17972. offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  17973. return {
  17974. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  17975. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  17976. };
  17977. }
  17978. function updateWithTouchData(e) {
  17979. var keys, i;
  17980. if (e.changedTouches) {
  17981. keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  17982. for (i = 0; i < keys.length; i++) {
  17983. e[keys[i]] = e.changedTouches[0][keys[i]];
  17984. }
  17985. }
  17986. }
  17987. function DragHelper (id, settings) {
  17988. var $eventOverlay;
  17989. var doc = settings.document || domGlobals.document;
  17990. var downButton;
  17991. var start, stop, drag, startX, startY;
  17992. settings = settings || {};
  17993. var handleElement = doc.getElementById(settings.handle || id);
  17994. start = function (e) {
  17995. var docSize = getDocumentSize(doc);
  17996. var handleElm, cursor;
  17997. updateWithTouchData(e);
  17998. e.preventDefault();
  17999. downButton = e.button;
  18000. handleElm = handleElement;
  18001. startX = e.screenX;
  18002. startY = e.screenY;
  18003. if (domGlobals.window.getComputedStyle) {
  18004. cursor = domGlobals.window.getComputedStyle(handleElm, null).getPropertyValue('cursor');
  18005. } else {
  18006. cursor = handleElm.runtimeStyle.cursor;
  18007. }
  18008. $eventOverlay = global$b('<div></div>').css({
  18009. position: 'absolute',
  18010. top: 0,
  18011. left: 0,
  18012. width: docSize.width,
  18013. height: docSize.height,
  18014. zIndex: 2147483647,
  18015. opacity: 0.0001,
  18016. cursor: cursor
  18017. }).appendTo(doc.body);
  18018. global$b(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop);
  18019. settings.start(e);
  18020. };
  18021. drag = function (e) {
  18022. updateWithTouchData(e);
  18023. if (e.button !== downButton) {
  18024. return stop(e);
  18025. }
  18026. e.deltaX = e.screenX - startX;
  18027. e.deltaY = e.screenY - startY;
  18028. e.preventDefault();
  18029. settings.drag(e);
  18030. };
  18031. stop = function (e) {
  18032. updateWithTouchData(e);
  18033. global$b(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop);
  18034. $eventOverlay.remove();
  18035. if (settings.stop) {
  18036. settings.stop(e);
  18037. }
  18038. };
  18039. this.destroy = function () {
  18040. global$b(handleElement).off();
  18041. };
  18042. global$b(handleElement).on('mousedown touchstart', start);
  18043. }
  18044. var count = 0;
  18045. var create$7 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  18046. var instance;
  18047. var dragHelpers;
  18048. var blockers;
  18049. var prefix = 'tox-';
  18050. var id = prefix + 'crid-' + count++;
  18051. var handles = [
  18052. {
  18053. name: 'move',
  18054. xMul: 0,
  18055. yMul: 0,
  18056. deltaX: 1,
  18057. deltaY: 1,
  18058. deltaW: 0,
  18059. deltaH: 0,
  18060. label: 'Crop Mask'
  18061. },
  18062. {
  18063. name: 'nw',
  18064. xMul: 0,
  18065. yMul: 0,
  18066. deltaX: 1,
  18067. deltaY: 1,
  18068. deltaW: -1,
  18069. deltaH: -1,
  18070. label: 'Top Left Crop Handle'
  18071. },
  18072. {
  18073. name: 'ne',
  18074. xMul: 1,
  18075. yMul: 0,
  18076. deltaX: 0,
  18077. deltaY: 1,
  18078. deltaW: 1,
  18079. deltaH: -1,
  18080. label: 'Top Right Crop Handle'
  18081. },
  18082. {
  18083. name: 'sw',
  18084. xMul: 0,
  18085. yMul: 1,
  18086. deltaX: 1,
  18087. deltaY: 0,
  18088. deltaW: -1,
  18089. deltaH: 1,
  18090. label: 'Bottom Left Crop Handle'
  18091. },
  18092. {
  18093. name: 'se',
  18094. xMul: 1,
  18095. yMul: 1,
  18096. deltaX: 0,
  18097. deltaY: 0,
  18098. deltaW: 1,
  18099. deltaH: 1,
  18100. label: 'Bottom Right Crop Handle'
  18101. }
  18102. ];
  18103. blockers = [
  18104. 'top',
  18105. 'right',
  18106. 'bottom',
  18107. 'left'
  18108. ];
  18109. var getAbsoluteRect = function (outerRect, relativeRect) {
  18110. return {
  18111. x: relativeRect.x + outerRect.x,
  18112. y: relativeRect.y + outerRect.y,
  18113. w: relativeRect.w,
  18114. h: relativeRect.h
  18115. };
  18116. };
  18117. var getRelativeRect = function (outerRect, innerRect) {
  18118. return {
  18119. x: innerRect.x - outerRect.x,
  18120. y: innerRect.y - outerRect.y,
  18121. w: innerRect.w,
  18122. h: innerRect.h
  18123. };
  18124. };
  18125. var getInnerRect = function () {
  18126. return getRelativeRect(clampRect, currentRect);
  18127. };
  18128. function moveRect(handle, startRect, deltaX, deltaY) {
  18129. var x, y, w, h, rect;
  18130. x = startRect.x;
  18131. y = startRect.y;
  18132. w = startRect.w;
  18133. h = startRect.h;
  18134. x += deltaX * handle.deltaX;
  18135. y += deltaY * handle.deltaY;
  18136. w += deltaX * handle.deltaW;
  18137. h += deltaY * handle.deltaH;
  18138. if (w < 20) {
  18139. w = 20;
  18140. }
  18141. if (h < 20) {
  18142. h = 20;
  18143. }
  18144. rect = currentRect = global$c.clamp({
  18145. x: x,
  18146. y: y,
  18147. w: w,
  18148. h: h
  18149. }, clampRect, handle.name === 'move');
  18150. rect = getRelativeRect(clampRect, rect);
  18151. instance.fire('updateRect', { rect: rect });
  18152. setInnerRect(rect);
  18153. }
  18154. function render() {
  18155. function createDragHelper(handle) {
  18156. var startRect;
  18157. return new DragHelper(id, {
  18158. document: containerElm.ownerDocument,
  18159. handle: id + '-' + handle.name,
  18160. start: function () {
  18161. startRect = currentRect;
  18162. },
  18163. drag: function (e) {
  18164. moveRect(handle, startRect, e.deltaX, e.deltaY);
  18165. }
  18166. });
  18167. }
  18168. global$b('<div id="' + id + '" class="' + prefix + 'croprect-container"' + ' role="grid" aria-dropeffect="execute">').appendTo(containerElm);
  18169. global$e.each(blockers, function (blocker) {
  18170. global$b('#' + id, containerElm).append('<div id="' + id + '-' + blocker + '"class="' + prefix + 'croprect-block" style="display: none" data-mce-bogus="all">');
  18171. });
  18172. global$e.each(handles, function (handle) {
  18173. 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 + '">');
  18174. });
  18175. dragHelpers = global$e.map(handles, createDragHelper);
  18176. repaint(currentRect);
  18177. global$b(containerElm).on('focusin focusout', function (e) {
  18178. global$b(e.target).attr('aria-grabbed', e.type === 'focus' ? 'true' : 'false');
  18179. });
  18180. global$b(containerElm).on('keydown', function (e) {
  18181. var activeHandle;
  18182. global$e.each(handles, function (handle) {
  18183. if (e.target.id === id + '-' + handle.name) {
  18184. activeHandle = handle;
  18185. return false;
  18186. }
  18187. });
  18188. function moveAndBlock(evt, handle, startRect, deltaX, deltaY) {
  18189. evt.stopPropagation();
  18190. evt.preventDefault();
  18191. moveRect(activeHandle, startRect, deltaX, deltaY);
  18192. }
  18193. switch (e.keyCode) {
  18194. case global$f.LEFT:
  18195. moveAndBlock(e, activeHandle, currentRect, -10, 0);
  18196. break;
  18197. case global$f.RIGHT:
  18198. moveAndBlock(e, activeHandle, currentRect, 10, 0);
  18199. break;
  18200. case global$f.UP:
  18201. moveAndBlock(e, activeHandle, currentRect, 0, -10);
  18202. break;
  18203. case global$f.DOWN:
  18204. moveAndBlock(e, activeHandle, currentRect, 0, 10);
  18205. break;
  18206. case global$f.ENTER:
  18207. case global$f.SPACEBAR:
  18208. e.preventDefault();
  18209. action();
  18210. break;
  18211. }
  18212. });
  18213. }
  18214. function toggleVisibility(state) {
  18215. var selectors;
  18216. selectors = global$e.map(handles, function (handle) {
  18217. return '#' + id + '-' + handle.name;
  18218. }).concat(global$e.map(blockers, function (blocker) {
  18219. return '#' + id + '-' + blocker;
  18220. })).join(',');
  18221. if (state) {
  18222. global$b(selectors, containerElm).show();
  18223. } else {
  18224. global$b(selectors, containerElm).hide();
  18225. }
  18226. }
  18227. function repaint(rect) {
  18228. function updateElementRect(name, rect) {
  18229. if (rect.h < 0) {
  18230. rect.h = 0;
  18231. }
  18232. if (rect.w < 0) {
  18233. rect.w = 0;
  18234. }
  18235. global$b('#' + id + '-' + name, containerElm).css({
  18236. left: rect.x,
  18237. top: rect.y,
  18238. width: rect.w,
  18239. height: rect.h
  18240. });
  18241. }
  18242. global$e.each(handles, function (handle) {
  18243. global$b('#' + id + '-' + handle.name, containerElm).css({
  18244. left: rect.w * handle.xMul + rect.x,
  18245. top: rect.h * handle.yMul + rect.y
  18246. });
  18247. });
  18248. updateElementRect('top', {
  18249. x: viewPortRect.x,
  18250. y: viewPortRect.y,
  18251. w: viewPortRect.w,
  18252. h: rect.y - viewPortRect.y
  18253. });
  18254. updateElementRect('right', {
  18255. x: rect.x + rect.w,
  18256. y: rect.y,
  18257. w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  18258. h: rect.h
  18259. });
  18260. updateElementRect('bottom', {
  18261. x: viewPortRect.x,
  18262. y: rect.y + rect.h,
  18263. w: viewPortRect.w,
  18264. h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  18265. });
  18266. updateElementRect('left', {
  18267. x: viewPortRect.x,
  18268. y: rect.y,
  18269. w: rect.x - viewPortRect.x,
  18270. h: rect.h
  18271. });
  18272. updateElementRect('move', rect);
  18273. }
  18274. function setRect(rect) {
  18275. currentRect = rect;
  18276. repaint(currentRect);
  18277. }
  18278. function setViewPortRect(rect) {
  18279. viewPortRect = rect;
  18280. repaint(currentRect);
  18281. }
  18282. function setInnerRect(rect) {
  18283. setRect(getAbsoluteRect(clampRect, rect));
  18284. }
  18285. function setClampRect(rect) {
  18286. clampRect = rect;
  18287. repaint(currentRect);
  18288. }
  18289. function destroy() {
  18290. global$e.each(dragHelpers, function (helper) {
  18291. helper.destroy();
  18292. });
  18293. dragHelpers = [];
  18294. }
  18295. render();
  18296. instance = global$e.extend({
  18297. toggleVisibility: toggleVisibility,
  18298. setClampRect: setClampRect,
  18299. setRect: setRect,
  18300. getInnerRect: getInnerRect,
  18301. setInnerRect: setInnerRect,
  18302. setViewPortRect: setViewPortRect,
  18303. destroy: destroy
  18304. }, global$d);
  18305. return instance;
  18306. };
  18307. var CropRect = { create: create$7 };
  18308. var loadImage = function (image) {
  18309. return new global$6(function (resolve) {
  18310. var loaded = function () {
  18311. image.removeEventListener('load', loaded);
  18312. resolve(image);
  18313. };
  18314. if (image.complete) {
  18315. resolve(image);
  18316. } else {
  18317. image.addEventListener('load', loaded);
  18318. }
  18319. });
  18320. };
  18321. var renderImagePanel = function (initialUrl) {
  18322. var memBg = record({
  18323. dom: {
  18324. tag: 'div',
  18325. classes: ['tox-image-tools__image-bg'],
  18326. attributes: { role: 'presentation' }
  18327. }
  18328. });
  18329. var zoomState = Cell(1);
  18330. var cropRect = Cell(Option.none());
  18331. var rectState = Cell({
  18332. x: 0,
  18333. y: 0,
  18334. w: 1,
  18335. h: 1
  18336. });
  18337. var viewRectState = Cell({
  18338. x: 0,
  18339. y: 0,
  18340. w: 1,
  18341. h: 1
  18342. });
  18343. var repaintImg = function (anyInSystem, img) {
  18344. memContainer.getOpt(anyInSystem).each(function (panel) {
  18345. var zoom = zoomState.get();
  18346. var panelW = get$7(panel.element());
  18347. var panelH = get$6(panel.element());
  18348. var width = img.dom().naturalWidth * zoom;
  18349. var height = img.dom().naturalHeight * zoom;
  18350. var left = Math.max(0, panelW / 2 - width / 2);
  18351. var top = Math.max(0, panelH / 2 - height / 2);
  18352. var css = {
  18353. left: left.toString() + 'px',
  18354. top: top.toString() + 'px',
  18355. width: width.toString() + 'px',
  18356. height: height.toString() + 'px',
  18357. position: 'absolute'
  18358. };
  18359. setAll$1(img, css);
  18360. memBg.getOpt(panel).each(function (bg) {
  18361. setAll$1(bg.element(), css);
  18362. });
  18363. cropRect.get().each(function (cRect) {
  18364. var rect = rectState.get();
  18365. cRect.setRect({
  18366. x: rect.x * zoom + left,
  18367. y: rect.y * zoom + top,
  18368. w: rect.w * zoom,
  18369. h: rect.h * zoom
  18370. });
  18371. cRect.setClampRect({
  18372. x: left,
  18373. y: top,
  18374. w: width,
  18375. h: height
  18376. });
  18377. cRect.setViewPortRect({
  18378. x: 0,
  18379. y: 0,
  18380. w: panelW,
  18381. h: panelH
  18382. });
  18383. });
  18384. });
  18385. };
  18386. var zoomFit = function (anyInSystem, img) {
  18387. memContainer.getOpt(anyInSystem).each(function (panel) {
  18388. var panelW = get$7(panel.element());
  18389. var panelH = get$6(panel.element());
  18390. var width = img.dom().naturalWidth;
  18391. var height = img.dom().naturalHeight;
  18392. var zoom = Math.min(panelW / width, panelH / height);
  18393. if (zoom >= 1) {
  18394. zoomState.set(1);
  18395. } else {
  18396. zoomState.set(zoom);
  18397. }
  18398. });
  18399. };
  18400. var updateSrc = function (anyInSystem, url) {
  18401. var img = Element.fromTag('img');
  18402. set$1(img, 'src', url);
  18403. return loadImage(img.dom()).then(function () {
  18404. return memContainer.getOpt(anyInSystem).map(function (panel) {
  18405. var aImg = external({ element: img });
  18406. Replacing.replaceAt(panel, 1, Option.some(aImg));
  18407. var lastViewRect = viewRectState.get();
  18408. var viewRect = {
  18409. x: 0,
  18410. y: 0,
  18411. w: img.dom().naturalWidth,
  18412. h: img.dom().naturalHeight
  18413. };
  18414. viewRectState.set(viewRect);
  18415. var rect = global$c.inflate(viewRect, -20, -20);
  18416. rectState.set(rect);
  18417. if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  18418. zoomFit(panel, img);
  18419. }
  18420. repaintImg(panel, img);
  18421. return img;
  18422. });
  18423. });
  18424. };
  18425. var zoom = function (anyInSystem, direction) {
  18426. var currentZoom = zoomState.get();
  18427. var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  18428. zoomState.set(newZoom);
  18429. memContainer.getOpt(anyInSystem).each(function (panel) {
  18430. var img = panel.components()[1].element();
  18431. repaintImg(panel, img);
  18432. });
  18433. };
  18434. var showCrop = function () {
  18435. cropRect.get().each(function (cRect) {
  18436. cRect.toggleVisibility(true);
  18437. });
  18438. };
  18439. var hideCrop = function () {
  18440. cropRect.get().each(function (cRect) {
  18441. cRect.toggleVisibility(false);
  18442. });
  18443. };
  18444. var getRect = function () {
  18445. return rectState.get();
  18446. };
  18447. var container = Container.sketch({
  18448. dom: {
  18449. tag: 'div',
  18450. classes: ['tox-image-tools__image']
  18451. },
  18452. components: [
  18453. memBg.asSpec(),
  18454. {
  18455. dom: {
  18456. tag: 'img',
  18457. attributes: { src: initialUrl }
  18458. }
  18459. },
  18460. {
  18461. dom: { tag: 'div' },
  18462. behaviours: derive$1([config('image-panel-crop-events', [runOnAttached(function (comp) {
  18463. memContainer.getOpt(comp).each(function (container) {
  18464. var el = container.element().dom();
  18465. var cRect = CropRect.create({
  18466. x: 10,
  18467. y: 10,
  18468. w: 100,
  18469. h: 100
  18470. }, {
  18471. x: 0,
  18472. y: 0,
  18473. w: 200,
  18474. h: 200
  18475. }, {
  18476. x: 0,
  18477. y: 0,
  18478. w: 200,
  18479. h: 200
  18480. }, el, function () {
  18481. });
  18482. cRect.toggleVisibility(false);
  18483. cRect.on('updateRect', function (e) {
  18484. var rect = e.rect;
  18485. var zoom = zoomState.get();
  18486. var newRect = {
  18487. x: Math.round(rect.x / zoom),
  18488. y: Math.round(rect.y / zoom),
  18489. w: Math.round(rect.w / zoom),
  18490. h: Math.round(rect.h / zoom)
  18491. };
  18492. rectState.set(newRect);
  18493. });
  18494. cropRect.set(Option.some(cRect));
  18495. });
  18496. })])])
  18497. }
  18498. ],
  18499. containerBehaviours: derive$1([
  18500. Replacing.config({}),
  18501. config('image-panel-events', [runOnAttached(function (comp) {
  18502. updateSrc(comp, initialUrl);
  18503. })])
  18504. ])
  18505. });
  18506. var memContainer = record(container);
  18507. var getMeasurements = function () {
  18508. var viewRect = viewRectState.get();
  18509. return {
  18510. width: viewRect.w,
  18511. height: viewRect.h
  18512. };
  18513. };
  18514. return {
  18515. memContainer: memContainer,
  18516. updateSrc: updateSrc,
  18517. zoom: zoom,
  18518. showCrop: showCrop,
  18519. hideCrop: hideCrop,
  18520. getRect: getRect,
  18521. getMeasurements: getMeasurements
  18522. };
  18523. };
  18524. var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  18525. return renderIconButton({
  18526. name: innerHtml,
  18527. icon: Option.some(icon),
  18528. disabled: disabled,
  18529. tooltip: Option.some(innerHtml),
  18530. primary: false,
  18531. borderless: false
  18532. }, action, providersBackstage);
  18533. };
  18534. var setButtonEnabled = function (button, enabled) {
  18535. if (enabled) {
  18536. Disabling.enable(button);
  18537. } else {
  18538. Disabling.disable(button);
  18539. }
  18540. };
  18541. var renderSideBar = function (providersBackstage) {
  18542. var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  18543. memUndo.getOpt(anyInSystem).each(function (undo) {
  18544. setButtonEnabled(undo, undoEnabled);
  18545. });
  18546. memRedo.getOpt(anyInSystem).each(function (redo) {
  18547. setButtonEnabled(redo, redoEnabled);
  18548. });
  18549. };
  18550. var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  18551. emitWith(button, internal.undo(), { direction: 1 });
  18552. }, providersBackstage));
  18553. var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  18554. emitWith(button, internal.redo(), { direction: 1 });
  18555. }, providersBackstage));
  18556. var container = Container.sketch({
  18557. dom: {
  18558. tag: 'div',
  18559. classes: [
  18560. 'tox-image-tools__toolbar',
  18561. 'tox-image-tools__sidebar'
  18562. ]
  18563. },
  18564. components: [
  18565. memUndo.asSpec(),
  18566. memRedo.asSpec(),
  18567. createButton('Zoom in', 'zoom-in', false, function (button) {
  18568. emitWith(button, internal.zoom(), { direction: 1 });
  18569. }, providersBackstage),
  18570. createButton('Zoom out', 'zoom-out', false, function (button) {
  18571. emitWith(button, internal.zoom(), { direction: -1 });
  18572. }, providersBackstage)
  18573. ]
  18574. });
  18575. return {
  18576. container: container,
  18577. updateButtonUndoStates: updateButtonUndoStates
  18578. };
  18579. };
  18580. function UndoStack () {
  18581. var data = [];
  18582. var index = -1;
  18583. function add(state) {
  18584. var removed;
  18585. removed = data.splice(++index);
  18586. data.push(state);
  18587. return {
  18588. state: state,
  18589. removed: removed
  18590. };
  18591. }
  18592. function undo() {
  18593. if (canUndo()) {
  18594. return data[--index];
  18595. }
  18596. }
  18597. function redo() {
  18598. if (canRedo()) {
  18599. return data[++index];
  18600. }
  18601. }
  18602. function canUndo() {
  18603. return index > 0;
  18604. }
  18605. function canRedo() {
  18606. return index !== -1 && index < data.length - 1;
  18607. }
  18608. return {
  18609. data: data,
  18610. add: add,
  18611. undo: undo,
  18612. redo: redo,
  18613. canUndo: canUndo,
  18614. canRedo: canRedo
  18615. };
  18616. }
  18617. var makeState = function (initialState) {
  18618. var blobState = Cell(initialState);
  18619. var tempState = Cell(Option.none());
  18620. var undoStack = UndoStack();
  18621. undoStack.add(initialState);
  18622. var getBlobState = function () {
  18623. return blobState.get();
  18624. };
  18625. var setBlobState = function (state) {
  18626. blobState.set(state);
  18627. };
  18628. var getTempState = function () {
  18629. return tempState.get().fold(function () {
  18630. return blobState.get();
  18631. }, function (temp) {
  18632. return temp;
  18633. });
  18634. };
  18635. var updateTempState = function (blob) {
  18636. var newTempState = createState(blob);
  18637. destroyTempState();
  18638. tempState.set(Option.some(newTempState));
  18639. return newTempState.url;
  18640. };
  18641. var createState = function (blob) {
  18642. return {
  18643. blob: blob,
  18644. url: domGlobals.URL.createObjectURL(blob)
  18645. };
  18646. };
  18647. var destroyState = function (state) {
  18648. domGlobals.URL.revokeObjectURL(state.url);
  18649. };
  18650. var destroyStates = function (states) {
  18651. global$e.each(states, destroyState);
  18652. };
  18653. var destroyTempState = function () {
  18654. tempState.get().each(destroyState);
  18655. tempState.set(Option.none());
  18656. };
  18657. var addBlobState = function (blob) {
  18658. var newState = createState(blob);
  18659. setBlobState(newState);
  18660. var removed = undoStack.add(newState).removed;
  18661. destroyStates(removed);
  18662. return newState.url;
  18663. };
  18664. var addTempState = function (blob) {
  18665. var newState = createState(blob);
  18666. tempState.set(Option.some(newState));
  18667. return newState.url;
  18668. };
  18669. var applyTempState = function (postApply) {
  18670. return tempState.get().fold(function () {
  18671. }, function (temp) {
  18672. addBlobState(temp.blob);
  18673. postApply();
  18674. });
  18675. };
  18676. var undo = function () {
  18677. var currentState = undoStack.undo();
  18678. setBlobState(currentState);
  18679. return currentState.url;
  18680. };
  18681. var redo = function () {
  18682. var currentState = undoStack.redo();
  18683. setBlobState(currentState);
  18684. return currentState.url;
  18685. };
  18686. var getHistoryStates = function () {
  18687. var undoEnabled = undoStack.canUndo();
  18688. var redoEnabled = undoStack.canRedo();
  18689. return {
  18690. undoEnabled: undoEnabled,
  18691. redoEnabled: redoEnabled
  18692. };
  18693. };
  18694. return {
  18695. getBlobState: getBlobState,
  18696. setBlobState: setBlobState,
  18697. addBlobState: addBlobState,
  18698. getTempState: getTempState,
  18699. updateTempState: updateTempState,
  18700. addTempState: addTempState,
  18701. applyTempState: applyTempState,
  18702. destroyTempState: destroyTempState,
  18703. undo: undo,
  18704. redo: redo,
  18705. getHistoryStates: getHistoryStates
  18706. };
  18707. };
  18708. var renderImageTools = function (detail, providersBackstage) {
  18709. var state = makeState(detail.currentState);
  18710. var zoom = function (anyInSystem, simulatedEvent) {
  18711. var direction = simulatedEvent.event().direction();
  18712. imagePanel.zoom(anyInSystem, direction);
  18713. };
  18714. var updateButtonUndoStates = function (anyInSystem) {
  18715. var historyStates = state.getHistoryStates();
  18716. sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  18717. emitWith(anyInSystem, external$2.formActionEvent, {
  18718. name: external$2.saveState(),
  18719. value: historyStates.undoEnabled
  18720. });
  18721. };
  18722. var disableUndoRedo = function (anyInSystem) {
  18723. sideBar.updateButtonUndoStates(anyInSystem, false, false);
  18724. };
  18725. var undo = function (anyInSystem, _simulatedEvent) {
  18726. var url = state.undo();
  18727. updateSrc(anyInSystem, url).then(function (oImg) {
  18728. unblock(anyInSystem);
  18729. updateButtonUndoStates(anyInSystem);
  18730. });
  18731. };
  18732. var redo = function (anyInSystem, _simulatedEvent) {
  18733. var url = state.redo();
  18734. updateSrc(anyInSystem, url).then(function (oImg) {
  18735. unblock(anyInSystem);
  18736. updateButtonUndoStates(anyInSystem);
  18737. });
  18738. };
  18739. var imageResultToBlob = function (ir) {
  18740. return ir.toBlob();
  18741. };
  18742. var block = function (anyInSystem) {
  18743. emitWith(anyInSystem, external$2.formActionEvent, {
  18744. name: external$2.disable(),
  18745. value: {}
  18746. });
  18747. };
  18748. var unblock = function (anyInSystem) {
  18749. editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  18750. Disabling.enable(applyButton);
  18751. });
  18752. emitWith(anyInSystem, external$2.formActionEvent, {
  18753. name: external$2.enable(),
  18754. value: {}
  18755. });
  18756. };
  18757. var updateSrc = function (anyInSystem, src) {
  18758. block(anyInSystem);
  18759. return imagePanel.updateSrc(anyInSystem, src);
  18760. };
  18761. var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  18762. block(anyInSystem);
  18763. return blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  18764. return updateSrc(anyInSystem, url).then(function (oImg) {
  18765. updateButtonUndoStates(anyInSystem);
  18766. swap();
  18767. unblock(anyInSystem);
  18768. return oImg;
  18769. });
  18770. }).catch(function (err) {
  18771. domGlobals.console.log(err);
  18772. unblock(anyInSystem);
  18773. return err;
  18774. });
  18775. };
  18776. var manipulate = function (anyInSystem, filter, swap) {
  18777. var blob = state.getBlobState().blob;
  18778. var action = function (blob) {
  18779. return state.updateTempState(blob);
  18780. };
  18781. blobManipulate(anyInSystem, blob, filter, action, swap);
  18782. };
  18783. var tempManipulate = function (anyInSystem, filter) {
  18784. var blob = state.getTempState().blob;
  18785. var action = function (blob) {
  18786. return state.addTempState(blob);
  18787. };
  18788. blobManipulate(anyInSystem, blob, filter, action, noop);
  18789. };
  18790. var manipulateApply = function (anyInSystem, filter, swap) {
  18791. var blob = state.getBlobState().blob;
  18792. var action = function (blob) {
  18793. var url = state.addBlobState(blob);
  18794. destroyTempState(anyInSystem);
  18795. return url;
  18796. };
  18797. blobManipulate(anyInSystem, blob, filter, action, swap);
  18798. };
  18799. var apply = function (anyInSystem, simulatedEvent) {
  18800. var postApply = function () {
  18801. destroyTempState(anyInSystem);
  18802. var swap = simulatedEvent.event().swap();
  18803. swap();
  18804. };
  18805. state.applyTempState(postApply);
  18806. };
  18807. var destroyTempState = function (anyInSystem) {
  18808. var currentUrl = state.getBlobState().url;
  18809. state.destroyTempState();
  18810. updateButtonUndoStates(anyInSystem);
  18811. return currentUrl;
  18812. };
  18813. var cancel = function (anyInSystem) {
  18814. var currentUrl = destroyTempState(anyInSystem);
  18815. updateSrc(anyInSystem, currentUrl).then(function (oImg) {
  18816. unblock(anyInSystem);
  18817. });
  18818. };
  18819. var back = function (anyInSystem, simulatedEvent) {
  18820. cancel(anyInSystem);
  18821. var swap = simulatedEvent.event().swap();
  18822. swap();
  18823. imagePanel.hideCrop();
  18824. };
  18825. var transform = function (anyInSystem, simulatedEvent) {
  18826. return manipulate(anyInSystem, simulatedEvent.event().transform(), noop);
  18827. };
  18828. var tempTransform = function (anyInSystem, simulatedEvent) {
  18829. return tempManipulate(anyInSystem, simulatedEvent.event().transform());
  18830. };
  18831. var transformApply = function (anyInSystem, simulatedEvent) {
  18832. return manipulateApply(anyInSystem, simulatedEvent.event().transform(), simulatedEvent.event().swap());
  18833. };
  18834. var imagePanel = renderImagePanel(detail.currentState.url);
  18835. var sideBar = renderSideBar(providersBackstage);
  18836. var editPanel = renderEditPanel(imagePanel, providersBackstage);
  18837. var swap = function (anyInSystem, simulatedEvent) {
  18838. disableUndoRedo(anyInSystem);
  18839. var transform = simulatedEvent.event().transform();
  18840. var swap = simulatedEvent.event().swap();
  18841. transform.fold(function () {
  18842. swap();
  18843. }, function (transform) {
  18844. manipulate(anyInSystem, transform, swap);
  18845. });
  18846. };
  18847. return {
  18848. dom: {
  18849. tag: 'div',
  18850. attributes: { role: 'presentation' }
  18851. },
  18852. components: [
  18853. editPanel.memContainer.asSpec(),
  18854. imagePanel.memContainer.asSpec(),
  18855. sideBar.container
  18856. ],
  18857. behaviours: derive$1([
  18858. Representing.config({
  18859. store: {
  18860. mode: 'manual',
  18861. getValue: function () {
  18862. return state.getBlobState();
  18863. }
  18864. }
  18865. }),
  18866. config('image-tools-events', [
  18867. run(internal.undo(), undo),
  18868. run(internal.redo(), redo),
  18869. run(internal.zoom(), zoom),
  18870. run(internal.back(), back),
  18871. run(internal.apply(), apply),
  18872. run(internal.transform(), transform),
  18873. run(internal.tempTransform(), tempTransform),
  18874. run(internal.transformApply(), transformApply),
  18875. run(internal.swap(), swap)
  18876. ]),
  18877. ComposingConfigs.self()
  18878. ])
  18879. };
  18880. };
  18881. var factory$8 = function (detail, spec) {
  18882. var options = map(detail.options, function (option) {
  18883. return {
  18884. dom: {
  18885. tag: 'option',
  18886. value: option.value,
  18887. innerHtml: option.text
  18888. }
  18889. };
  18890. });
  18891. var initialValues = detail.data.map(function (v) {
  18892. return wrap$1('initialValue', v);
  18893. }).getOr({});
  18894. return {
  18895. uid: detail.uid,
  18896. dom: {
  18897. tag: 'select',
  18898. classes: detail.selectClasses,
  18899. attributes: detail.selectAttributes
  18900. },
  18901. components: options,
  18902. behaviours: augment(detail.selectBehaviours, [
  18903. Focusing.config({}),
  18904. Representing.config({
  18905. store: __assign({
  18906. mode: 'manual',
  18907. getValue: function (select) {
  18908. return get$5(select.element());
  18909. },
  18910. setValue: function (select, newValue) {
  18911. var found = find(detail.options, function (opt) {
  18912. return opt.value === newValue;
  18913. });
  18914. if (found.isSome()) {
  18915. set$3(select.element(), newValue);
  18916. }
  18917. }
  18918. }, initialValues)
  18919. })
  18920. ])
  18921. };
  18922. };
  18923. var HtmlSelect = single$2({
  18924. name: 'HtmlSelect',
  18925. configFields: [
  18926. strict$1('options'),
  18927. field$1('selectBehaviours', [
  18928. Focusing,
  18929. Representing
  18930. ]),
  18931. defaulted$1('selectClasses', []),
  18932. defaulted$1('selectAttributes', {}),
  18933. option('data')
  18934. ],
  18935. factory: factory$8
  18936. });
  18937. var renderSelectBox = function (spec, providersBackstage) {
  18938. var translatedOptions = map(spec.items, function (item) {
  18939. return {
  18940. text: providersBackstage.translate(item.text),
  18941. value: item.value
  18942. };
  18943. });
  18944. var pLabel = spec.label.map(function (label) {
  18945. return renderLabel(label, providersBackstage);
  18946. });
  18947. var pField = FormField.parts().field({
  18948. dom: {},
  18949. selectAttributes: { size: spec.size },
  18950. options: translatedOptions,
  18951. factory: HtmlSelect,
  18952. selectBehaviours: derive$1([
  18953. Disabling.config({ disabled: spec.disabled }),
  18954. Tabstopping.config({}),
  18955. config('selectbox-change', [run(change(), function (component, _) {
  18956. emitWith(component, formChangeEvent, { name: spec.name });
  18957. })])
  18958. ])
  18959. });
  18960. var chevron = spec.size > 1 ? Option.none() : Option.some({
  18961. dom: {
  18962. tag: 'div',
  18963. classes: ['tox-selectfield__icon-js'],
  18964. innerHtml: get$d('chevron-down', providersBackstage.icons)
  18965. }
  18966. });
  18967. var selectWrap = {
  18968. dom: {
  18969. tag: 'div',
  18970. classes: ['tox-selectfield']
  18971. },
  18972. components: flatten([
  18973. [pField],
  18974. chevron.toArray()
  18975. ])
  18976. };
  18977. return FormField.sketch({
  18978. dom: {
  18979. tag: 'div',
  18980. classes: ['tox-form__group']
  18981. },
  18982. components: flatten([
  18983. pLabel.toArray(),
  18984. [selectWrap]
  18985. ]),
  18986. fieldBehaviours: derive$1([Disabling.config({
  18987. disabled: spec.disabled,
  18988. onDisabled: function (comp) {
  18989. FormField.getField(comp).each(Disabling.disable);
  18990. },
  18991. onEnabled: function (comp) {
  18992. FormField.getField(comp).each(Disabling.enable);
  18993. }
  18994. })])
  18995. });
  18996. };
  18997. var renderTextField = function (spec, providersBackstage) {
  18998. var pLabel = spec.label.map(function (label) {
  18999. return renderLabel(label, providersBackstage);
  19000. });
  19001. var baseInputBehaviours = [
  19002. Disabling.config({ disabled: spec.disabled }),
  19003. Keying.config({
  19004. mode: 'execution',
  19005. useEnter: spec.multiline !== true,
  19006. useControlEnter: spec.multiline === true,
  19007. execute: function (comp) {
  19008. emit(comp, formSubmitEvent);
  19009. return Option.some(true);
  19010. }
  19011. }),
  19012. config('textfield-change', [
  19013. run(input(), function (component, _) {
  19014. emitWith(component, formChangeEvent, { name: spec.name });
  19015. }),
  19016. run(postPaste(), function (component, _) {
  19017. emitWith(component, formChangeEvent, { name: spec.name });
  19018. })
  19019. ]),
  19020. Tabstopping.config({})
  19021. ];
  19022. var validatingBehaviours = spec.validation.map(function (vl) {
  19023. return Invalidating.config({
  19024. getRoot: function (input) {
  19025. return parent(input.element());
  19026. },
  19027. invalidClass: 'tox-invalid',
  19028. validator: {
  19029. validate: function (input) {
  19030. var v = Representing.getValue(input);
  19031. var result = vl.validator(v);
  19032. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  19033. },
  19034. validateOnLoad: vl.validateOnLoad
  19035. }
  19036. });
  19037. }).toArray();
  19038. var placeholder = spec.placeholder.fold(constant({}), function (p) {
  19039. return { placeholder: providersBackstage.translate(p) };
  19040. });
  19041. var inputMode = spec.inputMode.fold(constant({}), function (mode) {
  19042. return { inputmode: mode };
  19043. });
  19044. var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  19045. var pField = FormField.parts().field({
  19046. tag: spec.multiline === true ? 'textarea' : 'input',
  19047. inputAttributes: inputAttributes,
  19048. inputClasses: [spec.classname],
  19049. inputBehaviours: derive$1(flatten([
  19050. baseInputBehaviours,
  19051. validatingBehaviours
  19052. ])),
  19053. selectOnFocus: false,
  19054. factory: Input
  19055. });
  19056. var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  19057. var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  19058. var extraBehaviours = [Disabling.config({
  19059. disabled: spec.disabled,
  19060. onDisabled: function (comp) {
  19061. FormField.getField(comp).each(Disabling.disable);
  19062. },
  19063. onEnabled: function (comp) {
  19064. FormField.getField(comp).each(Disabling.enable);
  19065. }
  19066. })];
  19067. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  19068. };
  19069. var renderInput = function (spec, providersBackstage) {
  19070. return renderTextField({
  19071. name: spec.name,
  19072. multiline: false,
  19073. label: spec.label,
  19074. inputMode: spec.inputMode,
  19075. placeholder: spec.placeholder,
  19076. flex: false,
  19077. disabled: spec.disabled,
  19078. classname: 'tox-textfield',
  19079. validation: Option.none(),
  19080. maximized: spec.maximized
  19081. }, providersBackstage);
  19082. };
  19083. var renderTextarea = function (spec, providersBackstage) {
  19084. return renderTextField({
  19085. name: spec.name,
  19086. multiline: true,
  19087. label: spec.label,
  19088. inputMode: Option.none(),
  19089. placeholder: spec.placeholder,
  19090. flex: true,
  19091. disabled: spec.disabled,
  19092. classname: 'tox-textarea',
  19093. validation: Option.none(),
  19094. maximized: spec.maximized
  19095. }, providersBackstage);
  19096. };
  19097. var events$c = function (streamConfig, streamState) {
  19098. var streams = streamConfig.stream.streams;
  19099. var processor = streams.setup(streamConfig, streamState);
  19100. return derive([
  19101. run(streamConfig.event, processor),
  19102. runOnDetached(function () {
  19103. return streamState.cancel();
  19104. })
  19105. ].concat(streamConfig.cancelEvent.map(function (e) {
  19106. return [run(e, function () {
  19107. return streamState.cancel();
  19108. })];
  19109. }).getOr([])));
  19110. };
  19111. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  19112. __proto__: null,
  19113. events: events$c
  19114. });
  19115. var throttle = function (_config) {
  19116. var state = Cell(null);
  19117. var readState = function () {
  19118. return { timer: state.get() !== null ? 'set' : 'unset' };
  19119. };
  19120. var setTimer = function (t) {
  19121. state.set(t);
  19122. };
  19123. var cancel = function () {
  19124. var t = state.get();
  19125. if (t !== null) {
  19126. t.cancel();
  19127. }
  19128. };
  19129. return nu$5({
  19130. readState: readState,
  19131. setTimer: setTimer,
  19132. cancel: cancel
  19133. });
  19134. };
  19135. var init$6 = function (spec) {
  19136. return spec.stream.streams.state(spec);
  19137. };
  19138. var StreamingState = /*#__PURE__*/Object.freeze({
  19139. __proto__: null,
  19140. throttle: throttle,
  19141. init: init$6
  19142. });
  19143. var setup$2 = function (streamInfo, streamState) {
  19144. var sInfo = streamInfo.stream;
  19145. var throttler = last$2(streamInfo.onStream, sInfo.delay);
  19146. streamState.setTimer(throttler);
  19147. return function (component, simulatedEvent) {
  19148. throttler.throttle(component, simulatedEvent);
  19149. if (sInfo.stopEvent) {
  19150. simulatedEvent.stop();
  19151. }
  19152. };
  19153. };
  19154. var StreamingSchema = [
  19155. strictOf('stream', choose$1('mode', {
  19156. throttle: [
  19157. strict$1('delay'),
  19158. defaulted$1('stopEvent', true),
  19159. output('streams', {
  19160. setup: setup$2,
  19161. state: throttle
  19162. })
  19163. ]
  19164. })),
  19165. defaulted$1('event', 'input'),
  19166. option('cancelEvent'),
  19167. onStrictHandler('onStream')
  19168. ];
  19169. var Streaming = create$1({
  19170. fields: StreamingSchema,
  19171. name: 'streaming',
  19172. active: ActiveStreaming,
  19173. state: StreamingState
  19174. });
  19175. var setValueFromItem = function (model, input, item) {
  19176. var itemData = Representing.getValue(item);
  19177. Representing.setValue(input, itemData);
  19178. setCursorAtEnd(input);
  19179. };
  19180. var setSelectionOn = function (input, f) {
  19181. var el = input.element();
  19182. var value = get$5(el);
  19183. var node = el.dom();
  19184. if (get$2(el, 'type') !== 'number') {
  19185. f(node, value);
  19186. }
  19187. };
  19188. var setCursorAtEnd = function (input) {
  19189. setSelectionOn(input, function (node, value) {
  19190. return node.setSelectionRange(value.length, value.length);
  19191. });
  19192. };
  19193. var setSelectionToEnd = function (input, startOffset) {
  19194. setSelectionOn(input, function (node, value) {
  19195. return node.setSelectionRange(startOffset, value.length);
  19196. });
  19197. };
  19198. var attemptSelectOver = function (model, input, item) {
  19199. if (!model.selectsOver) {
  19200. return Option.none();
  19201. } else {
  19202. var currentValue = Representing.getValue(input);
  19203. var inputDisplay_1 = model.getDisplayText(currentValue);
  19204. var itemValue = Representing.getValue(item);
  19205. var itemDisplay = model.getDisplayText(itemValue);
  19206. return itemDisplay.indexOf(inputDisplay_1) === 0 ? Option.some(function () {
  19207. setValueFromItem(model, input, item);
  19208. setSelectionToEnd(input, inputDisplay_1.length);
  19209. }) : Option.none();
  19210. }
  19211. };
  19212. var itemExecute = constant('alloy.typeahead.itemexecute');
  19213. var make$5 = function (detail, components, spec, externals) {
  19214. var navigateList = function (comp, simulatedEvent, highlighter) {
  19215. detail.previewing.set(false);
  19216. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19217. if (Sandboxing.isOpen(sandbox)) {
  19218. Composing.getCurrent(sandbox).each(function (menu) {
  19219. Highlighting.getHighlighted(menu).fold(function () {
  19220. highlighter(menu);
  19221. }, function () {
  19222. dispatchEvent(sandbox, menu.element(), 'keydown', simulatedEvent);
  19223. });
  19224. });
  19225. } else {
  19226. var onOpenSync = function (sandbox) {
  19227. Composing.getCurrent(sandbox).each(highlighter);
  19228. };
  19229. open$1(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19230. }
  19231. };
  19232. var focusBehaviours$1 = focusBehaviours(detail);
  19233. var mapFetch = function (comp) {
  19234. return function (tdata) {
  19235. return tdata.map(function (data) {
  19236. var menus = values(data.menus);
  19237. var items = bind(menus, function (menu) {
  19238. return filter(menu.items, function (item) {
  19239. return item.type === 'item';
  19240. });
  19241. });
  19242. var repState = Representing.getState(comp);
  19243. repState.update(map(items, function (item) {
  19244. return item.data;
  19245. }));
  19246. return data;
  19247. });
  19248. };
  19249. };
  19250. var behaviours = [
  19251. Focusing.config({}),
  19252. Representing.config({
  19253. onSetValue: detail.onSetValue,
  19254. store: __assign({
  19255. mode: 'dataset',
  19256. getDataKey: function (comp) {
  19257. return get$5(comp.element());
  19258. },
  19259. getFallbackEntry: function (itemString) {
  19260. return {
  19261. value: itemString,
  19262. meta: {}
  19263. };
  19264. },
  19265. setValue: function (comp, data) {
  19266. set$3(comp.element(), detail.model.getDisplayText(data));
  19267. }
  19268. }, detail.initialData.map(function (d) {
  19269. return wrap$1('initialValue', d);
  19270. }).getOr({}))
  19271. }),
  19272. Streaming.config({
  19273. stream: {
  19274. mode: 'throttle',
  19275. delay: detail.responseTime,
  19276. stopEvent: false
  19277. },
  19278. onStream: function (component, simulatedEvent) {
  19279. var sandbox = Coupling.getCoupled(component, 'sandbox');
  19280. var focusInInput = Focusing.isFocused(component);
  19281. if (focusInInput) {
  19282. if (get$5(component.element()).length >= detail.minChars) {
  19283. var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  19284. return Highlighting.getHighlighted(menu).map(Representing.getValue);
  19285. });
  19286. detail.previewing.set(true);
  19287. var onOpenSync = function (_sandbox) {
  19288. Composing.getCurrent(sandbox).each(function (menu) {
  19289. previousValue_1.fold(function () {
  19290. if (detail.model.selectsOver) {
  19291. Highlighting.highlightFirst(menu);
  19292. }
  19293. }, function (pv) {
  19294. Highlighting.highlightBy(menu, function (item) {
  19295. var itemData = Representing.getValue(item);
  19296. return itemData.value === pv.value;
  19297. });
  19298. Highlighting.getHighlighted(menu).orThunk(function () {
  19299. Highlighting.highlightFirst(menu);
  19300. return Option.none();
  19301. });
  19302. });
  19303. });
  19304. };
  19305. open$1(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19306. }
  19307. }
  19308. },
  19309. cancelEvent: typeaheadCancel()
  19310. }),
  19311. Keying.config({
  19312. mode: 'special',
  19313. onDown: function (comp, simulatedEvent) {
  19314. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  19315. return Option.some(true);
  19316. },
  19317. onEscape: function (comp) {
  19318. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19319. if (Sandboxing.isOpen(sandbox)) {
  19320. Sandboxing.close(sandbox);
  19321. return Option.some(true);
  19322. }
  19323. return Option.none();
  19324. },
  19325. onUp: function (comp, simulatedEvent) {
  19326. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  19327. return Option.some(true);
  19328. },
  19329. onEnter: function (comp) {
  19330. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19331. var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  19332. if (sandboxIsOpen && !detail.previewing.get()) {
  19333. return Composing.getCurrent(sandbox).bind(function (menu) {
  19334. return Highlighting.getHighlighted(menu);
  19335. }).map(function (item) {
  19336. emitWith(comp, itemExecute(), { item: item });
  19337. return true;
  19338. });
  19339. } else {
  19340. var currentValue = Representing.getValue(comp);
  19341. emit(comp, typeaheadCancel());
  19342. detail.onExecute(sandbox, comp, currentValue);
  19343. if (sandboxIsOpen) {
  19344. Sandboxing.close(sandbox);
  19345. }
  19346. return Option.some(true);
  19347. }
  19348. }
  19349. }),
  19350. Toggling.config({
  19351. toggleClass: detail.markers.openClass,
  19352. aria: { mode: 'expanded' }
  19353. }),
  19354. Coupling.config({
  19355. others: {
  19356. sandbox: function (hotspot) {
  19357. return makeSandbox(detail, hotspot, {
  19358. onOpen: function () {
  19359. return Toggling.on(hotspot);
  19360. },
  19361. onClose: function () {
  19362. return Toggling.off(hotspot);
  19363. }
  19364. });
  19365. }
  19366. }
  19367. }),
  19368. config('typeaheadevents', [
  19369. runOnExecute(function (comp) {
  19370. var onOpenSync = noop;
  19371. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19372. }),
  19373. run(itemExecute(), function (comp, se) {
  19374. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19375. setValueFromItem(detail.model, comp, se.event().item());
  19376. emit(comp, typeaheadCancel());
  19377. detail.onItemExecute(comp, sandbox, se.event().item(), Representing.getValue(comp));
  19378. Sandboxing.close(sandbox);
  19379. setCursorAtEnd(comp);
  19380. })
  19381. ].concat(detail.dismissOnBlur ? [run(postBlur(), function (typeahead) {
  19382. var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  19383. if (search(sandbox.element()).isNone()) {
  19384. Sandboxing.close(sandbox);
  19385. }
  19386. })] : []))
  19387. ];
  19388. return {
  19389. uid: detail.uid,
  19390. dom: dom$2(deepMerge(detail, {
  19391. inputAttributes: {
  19392. 'role': 'combobox',
  19393. 'aria-autocomplete': 'list',
  19394. 'aria-haspopup': 'true'
  19395. }
  19396. })),
  19397. behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  19398. eventOrder: detail.eventOrder
  19399. };
  19400. };
  19401. var schema$j = constant([
  19402. option('lazySink'),
  19403. strict$1('fetch'),
  19404. defaulted$1('minChars', 5),
  19405. defaulted$1('responseTime', 1000),
  19406. onHandler('onOpen'),
  19407. defaulted$1('getHotspot', Option.some),
  19408. defaulted$1('getAnchorOverrides', constant({})),
  19409. defaulted$1('layouts', Option.none()),
  19410. defaulted$1('eventOrder', {}),
  19411. defaultedObjOf('model', {}, [
  19412. defaulted$1('getDisplayText', function (itemData) {
  19413. return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  19414. }),
  19415. defaulted$1('selectsOver', true),
  19416. defaulted$1('populateFromBrowse', true)
  19417. ]),
  19418. onHandler('onSetValue'),
  19419. onKeyboardHandler('onExecute'),
  19420. onHandler('onItemExecute'),
  19421. defaulted$1('inputClasses', []),
  19422. defaulted$1('inputAttributes', {}),
  19423. defaulted$1('inputStyles', {}),
  19424. defaulted$1('matchWidth', true),
  19425. defaulted$1('useMinWidth', false),
  19426. defaulted$1('dismissOnBlur', true),
  19427. markers(['openClass']),
  19428. option('initialData'),
  19429. field$1('typeaheadBehaviours', [
  19430. Focusing,
  19431. Representing,
  19432. Streaming,
  19433. Keying,
  19434. Toggling,
  19435. Coupling
  19436. ]),
  19437. state$1('previewing', function () {
  19438. return Cell(true);
  19439. })
  19440. ].concat(schema$f()).concat(sandboxFields()));
  19441. var parts$6 = constant([external$1({
  19442. schema: [tieredMenuMarkers()],
  19443. name: 'menu',
  19444. overrides: function (detail) {
  19445. return {
  19446. fakeFocus: true,
  19447. onHighlight: function (menu, item) {
  19448. if (!detail.previewing.get()) {
  19449. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19450. if (detail.model.populateFromBrowse) {
  19451. setValueFromItem(detail.model, input, item);
  19452. }
  19453. });
  19454. } else {
  19455. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19456. attemptSelectOver(detail.model, input, item).fold(function () {
  19457. return Highlighting.dehighlight(menu, item);
  19458. }, function (fn) {
  19459. return fn();
  19460. });
  19461. });
  19462. }
  19463. detail.previewing.set(false);
  19464. },
  19465. onExecute: function (menu, item) {
  19466. return menu.getSystem().getByUid(detail.uid).toOption().map(function (typeahead) {
  19467. emitWith(typeahead, itemExecute(), { item: item });
  19468. return true;
  19469. });
  19470. },
  19471. onHover: function (menu, item) {
  19472. detail.previewing.set(false);
  19473. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19474. if (detail.model.populateFromBrowse) {
  19475. setValueFromItem(detail.model, input, item);
  19476. }
  19477. });
  19478. }
  19479. };
  19480. }
  19481. })]);
  19482. var Typeahead = composite$1({
  19483. name: 'Typeahead',
  19484. configFields: schema$j(),
  19485. partFields: parts$6(),
  19486. factory: make$5
  19487. });
  19488. var wrap$2 = function (delegate) {
  19489. var toCached = function () {
  19490. return wrap$2(delegate.toCached());
  19491. };
  19492. var bindFuture = function (f) {
  19493. return wrap$2(delegate.bind(function (resA) {
  19494. return resA.fold(function (err) {
  19495. return Future.pure(Result.error(err));
  19496. }, function (a) {
  19497. return f(a);
  19498. });
  19499. }));
  19500. };
  19501. var bindResult = function (f) {
  19502. return wrap$2(delegate.map(function (resA) {
  19503. return resA.bind(f);
  19504. }));
  19505. };
  19506. var mapResult = function (f) {
  19507. return wrap$2(delegate.map(function (resA) {
  19508. return resA.map(f);
  19509. }));
  19510. };
  19511. var mapError = function (f) {
  19512. return wrap$2(delegate.map(function (resA) {
  19513. return resA.mapError(f);
  19514. }));
  19515. };
  19516. var foldResult = function (whenError, whenValue) {
  19517. return delegate.map(function (res) {
  19518. return res.fold(whenError, whenValue);
  19519. });
  19520. };
  19521. var withTimeout = function (timeout, errorThunk) {
  19522. return wrap$2(Future.nu(function (callback) {
  19523. var timedOut = false;
  19524. var timer = domGlobals.setTimeout(function () {
  19525. timedOut = true;
  19526. callback(Result.error(errorThunk()));
  19527. }, timeout);
  19528. delegate.get(function (result) {
  19529. if (!timedOut) {
  19530. domGlobals.clearTimeout(timer);
  19531. callback(result);
  19532. }
  19533. });
  19534. }));
  19535. };
  19536. return __assign(__assign({}, delegate), {
  19537. toCached: toCached,
  19538. bindFuture: bindFuture,
  19539. bindResult: bindResult,
  19540. mapResult: mapResult,
  19541. mapError: mapError,
  19542. foldResult: foldResult,
  19543. withTimeout: withTimeout
  19544. });
  19545. };
  19546. var nu$c = function (worker) {
  19547. return wrap$2(Future.nu(worker));
  19548. };
  19549. var value$2 = function (value) {
  19550. return wrap$2(Future.pure(Result.value(value)));
  19551. };
  19552. var error$1 = function (error) {
  19553. return wrap$2(Future.pure(Result.error(error)));
  19554. };
  19555. var fromResult$1 = function (result) {
  19556. return wrap$2(Future.pure(result));
  19557. };
  19558. var fromFuture = function (future) {
  19559. return wrap$2(future.map(Result.value));
  19560. };
  19561. var fromPromise = function (promise) {
  19562. return nu$c(function (completer) {
  19563. promise.then(function (value) {
  19564. completer(Result.value(value));
  19565. }, function (error) {
  19566. completer(Result.error(error));
  19567. });
  19568. });
  19569. };
  19570. var FutureResult = {
  19571. nu: nu$c,
  19572. wrap: wrap$2,
  19573. pure: value$2,
  19574. value: value$2,
  19575. error: error$1,
  19576. fromResult: fromResult$1,
  19577. fromFuture: fromFuture,
  19578. fromPromise: fromPromise
  19579. };
  19580. var separator$2 = { type: 'separator' };
  19581. var toMenuItem = function (target) {
  19582. return {
  19583. type: 'menuitem',
  19584. value: target.url,
  19585. text: target.title,
  19586. meta: { attach: target.attach },
  19587. onAction: function () {
  19588. }
  19589. };
  19590. };
  19591. var staticMenuItem = function (title, url) {
  19592. return {
  19593. type: 'menuitem',
  19594. value: url,
  19595. text: title,
  19596. meta: { attach: undefined },
  19597. onAction: function () {
  19598. }
  19599. };
  19600. };
  19601. var toMenuItems = function (targets) {
  19602. return map(targets, toMenuItem);
  19603. };
  19604. var filterLinkTargets = function (type, targets) {
  19605. return filter(targets, function (target) {
  19606. return target.type === type;
  19607. });
  19608. };
  19609. var filteredTargets = function (type, targets) {
  19610. return toMenuItems(filterLinkTargets(type, targets));
  19611. };
  19612. var headerTargets = function (linkInfo) {
  19613. return filteredTargets('header', linkInfo.targets);
  19614. };
  19615. var anchorTargets = function (linkInfo) {
  19616. return filteredTargets('anchor', linkInfo.targets);
  19617. };
  19618. var anchorTargetTop = function (linkInfo) {
  19619. return Option.from(linkInfo.anchorTop).map(function (url) {
  19620. return staticMenuItem('<top>', url);
  19621. }).toArray();
  19622. };
  19623. var anchorTargetBottom = function (linkInfo) {
  19624. return Option.from(linkInfo.anchorBottom).map(function (url) {
  19625. return staticMenuItem('<bottom>', url);
  19626. }).toArray();
  19627. };
  19628. var historyTargets = function (history) {
  19629. return map(history, function (url) {
  19630. return staticMenuItem(url, url);
  19631. });
  19632. };
  19633. var joinMenuLists = function (items) {
  19634. return foldl(items, function (a, b) {
  19635. var bothEmpty = a.length === 0 || b.length === 0;
  19636. return bothEmpty ? a.concat(b) : a.concat(separator$2, b);
  19637. }, []);
  19638. };
  19639. var filterByQuery = function (term, menuItems) {
  19640. var lowerCaseTerm = term.toLowerCase();
  19641. return filter(menuItems, function (item) {
  19642. var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  19643. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  19644. });
  19645. };
  19646. var getItems = function (fileType, input, urlBackstage) {
  19647. var urlInputValue = Representing.getValue(input);
  19648. var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  19649. var info = urlBackstage.getLinkInformation();
  19650. return info.fold(function () {
  19651. return [];
  19652. }, function (linkInfo) {
  19653. var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  19654. return fileType === 'file' ? joinMenuLists([
  19655. history,
  19656. filterByQuery(term, headerTargets(linkInfo)),
  19657. filterByQuery(term, flatten([
  19658. anchorTargetTop(linkInfo),
  19659. anchorTargets(linkInfo),
  19660. anchorTargetBottom(linkInfo)
  19661. ]))
  19662. ]) : history;
  19663. });
  19664. };
  19665. var errorId = generate$1('aria-invalid');
  19666. var renderUrlInput = function (spec, backstage, urlBackstage) {
  19667. var _a;
  19668. var providersBackstage = backstage.shared.providers;
  19669. var updateHistory = function (component) {
  19670. var urlEntry = Representing.getValue(component);
  19671. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  19672. };
  19673. var pField = FormField.parts().field({
  19674. factory: Typeahead,
  19675. dismissOnBlur: true,
  19676. inputClasses: ['tox-textfield'],
  19677. sandboxClasses: ['tox-dialog__popups'],
  19678. inputAttributes: {
  19679. 'aria-errormessage': errorId,
  19680. 'type': 'url'
  19681. },
  19682. minChars: 0,
  19683. responseTime: 0,
  19684. fetch: function (input) {
  19685. var items = getItems(spec.filetype, input, urlBackstage);
  19686. var tdata = build$2(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  19687. return Future.pure(tdata);
  19688. },
  19689. getHotspot: function (comp) {
  19690. return memUrlBox.getOpt(comp);
  19691. },
  19692. onSetValue: function (comp, newValue) {
  19693. if (comp.hasConfigured(Invalidating)) {
  19694. Invalidating.run(comp).get(noop);
  19695. }
  19696. },
  19697. typeaheadBehaviours: derive$1(flatten([
  19698. urlBackstage.getValidationHandler().map(function (handler) {
  19699. return Invalidating.config({
  19700. getRoot: function (comp) {
  19701. return parent(comp.element());
  19702. },
  19703. invalidClass: 'tox-control-wrap--status-invalid',
  19704. notify: {
  19705. onInvalid: function (comp, err) {
  19706. memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  19707. set$1(invalidComp.element(), 'title', providersBackstage.translate(err));
  19708. });
  19709. }
  19710. },
  19711. validator: {
  19712. validate: function (input) {
  19713. var urlEntry = Representing.getValue(input);
  19714. return FutureResult.nu(function (completer) {
  19715. handler({
  19716. type: spec.filetype,
  19717. url: urlEntry.value
  19718. }, function (validation) {
  19719. if (validation.status === 'invalid') {
  19720. var err = Result.error(validation.message);
  19721. completer(err);
  19722. } else {
  19723. var val = Result.value(validation.message);
  19724. completer(val);
  19725. }
  19726. });
  19727. });
  19728. },
  19729. validateOnLoad: false
  19730. }
  19731. });
  19732. }).toArray(),
  19733. [
  19734. Disabling.config({ disabled: spec.disabled }),
  19735. Tabstopping.config({}),
  19736. config('urlinput-events', flatten([
  19737. spec.filetype === 'file' ? [run(input(), function (comp) {
  19738. emitWith(comp, formChangeEvent, { name: spec.name });
  19739. })] : [],
  19740. [
  19741. run(change(), function (comp) {
  19742. emitWith(comp, formChangeEvent, { name: spec.name });
  19743. updateHistory(comp);
  19744. }),
  19745. run(postPaste(), function (comp) {
  19746. emitWith(comp, formChangeEvent, { name: spec.name });
  19747. updateHistory(comp);
  19748. })
  19749. ]
  19750. ]))
  19751. ]
  19752. ])),
  19753. eventOrder: (_a = {}, _a[input()] = [
  19754. 'streaming',
  19755. 'urlinput-events',
  19756. 'invalidating'
  19757. ], _a),
  19758. model: {
  19759. getDisplayText: function (itemData) {
  19760. return itemData.value;
  19761. },
  19762. selectsOver: false,
  19763. populateFromBrowse: false
  19764. },
  19765. markers: { openClass: 'tox-textfield--popup-open' },
  19766. lazySink: backstage.shared.getSink,
  19767. parts: { menu: part(false, 1, 'normal') },
  19768. onExecute: function (_menu, component, _entry) {
  19769. emitWith(component, formSubmitEvent, {});
  19770. },
  19771. onItemExecute: function (typeahead, _sandbox, _item, _value) {
  19772. updateHistory(typeahead);
  19773. emitWith(typeahead, formChangeEvent, { name: spec.name });
  19774. }
  19775. });
  19776. var pLabel = spec.label.map(function (label) {
  19777. return renderLabel(label, providersBackstage);
  19778. });
  19779. var makeIcon = function (name, errId, icon, label) {
  19780. if (icon === void 0) {
  19781. icon = name;
  19782. }
  19783. if (label === void 0) {
  19784. label = name;
  19785. }
  19786. return {
  19787. dom: {
  19788. tag: 'div',
  19789. classes: [
  19790. 'tox-icon',
  19791. 'tox-control-wrap__status-icon-' + name
  19792. ],
  19793. innerHtml: get$d(icon, providersBackstage.icons),
  19794. attributes: __assign({
  19795. 'title': providersBackstage.translate(label),
  19796. 'aria-live': 'polite'
  19797. }, errId.fold(function () {
  19798. return {};
  19799. }, function (id) {
  19800. return { id: id };
  19801. }))
  19802. }
  19803. };
  19804. };
  19805. var memInvalidIcon = record(makeIcon('invalid', Option.some(errorId), 'warning'));
  19806. var memStatus = record({
  19807. dom: {
  19808. tag: 'div',
  19809. classes: ['tox-control-wrap__status-icon-wrap']
  19810. },
  19811. components: [memInvalidIcon.asSpec()]
  19812. });
  19813. var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  19814. var browseUrlEvent = generate$1('browser.url.event');
  19815. var memUrlBox = record({
  19816. dom: {
  19817. tag: 'div',
  19818. classes: ['tox-control-wrap']
  19819. },
  19820. components: [
  19821. pField,
  19822. memStatus.asSpec()
  19823. ],
  19824. behaviours: derive$1([Disabling.config({ disabled: spec.disabled })])
  19825. });
  19826. var memUrlPickerButton = record(renderButton({
  19827. name: spec.name,
  19828. icon: Option.some('browse'),
  19829. text: spec.label.getOr(''),
  19830. disabled: spec.disabled,
  19831. primary: false,
  19832. borderless: true
  19833. }, function (component) {
  19834. return emit(component, browseUrlEvent);
  19835. }, providersBackstage, [], ['tox-browse-url']));
  19836. var controlHWrapper = function () {
  19837. return {
  19838. dom: {
  19839. tag: 'div',
  19840. classes: ['tox-form__controls-h-stack']
  19841. },
  19842. components: flatten([
  19843. [memUrlBox.asSpec()],
  19844. optUrlPicker.map(function () {
  19845. return memUrlPickerButton.asSpec();
  19846. }).toArray()
  19847. ])
  19848. };
  19849. };
  19850. var openUrlPicker = function (comp) {
  19851. Composing.getCurrent(comp).each(function (field) {
  19852. var componentData = Representing.getValue(field);
  19853. var urlData = __assign({ fieldname: spec.name }, componentData);
  19854. optUrlPicker.each(function (picker) {
  19855. picker(urlData).get(function (chosenData) {
  19856. Representing.setValue(field, chosenData);
  19857. emitWith(comp, formChangeEvent, { name: spec.name });
  19858. });
  19859. });
  19860. });
  19861. };
  19862. return FormField.sketch({
  19863. dom: renderFormFieldDom(),
  19864. components: pLabel.toArray().concat([controlHWrapper()]),
  19865. fieldBehaviours: derive$1([
  19866. Disabling.config({
  19867. disabled: spec.disabled,
  19868. onDisabled: function (comp) {
  19869. FormField.getField(comp).each(Disabling.disable);
  19870. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  19871. },
  19872. onEnabled: function (comp) {
  19873. FormField.getField(comp).each(Disabling.enable);
  19874. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  19875. }
  19876. }),
  19877. config('url-input-events', [run(browseUrlEvent, openUrlPicker)])
  19878. ])
  19879. });
  19880. };
  19881. var renderCheckbox = function (spec, providerBackstage) {
  19882. var repBehaviour = Representing.config({
  19883. store: {
  19884. mode: 'manual',
  19885. getValue: function (comp) {
  19886. var el = comp.element().dom();
  19887. return el.checked;
  19888. },
  19889. setValue: function (comp, value) {
  19890. var el = comp.element().dom();
  19891. el.checked = value;
  19892. }
  19893. }
  19894. });
  19895. var toggleCheckboxHandler = function (comp) {
  19896. comp.element().dom().click();
  19897. return Option.some(true);
  19898. };
  19899. var pField = FormField.parts().field({
  19900. factory: { sketch: identity },
  19901. dom: {
  19902. tag: 'input',
  19903. classes: ['tox-checkbox__input'],
  19904. attributes: { type: 'checkbox' }
  19905. },
  19906. behaviours: derive$1([
  19907. ComposingConfigs.self(),
  19908. Disabling.config({ disabled: spec.disabled }),
  19909. Tabstopping.config({}),
  19910. Focusing.config({}),
  19911. repBehaviour,
  19912. Keying.config({
  19913. mode: 'special',
  19914. onEnter: toggleCheckboxHandler,
  19915. onSpace: toggleCheckboxHandler,
  19916. stopSpaceKeyup: true
  19917. }),
  19918. config('checkbox-events', [run(change(), function (component, _) {
  19919. emitWith(component, formChangeEvent, { name: spec.name });
  19920. })])
  19921. ])
  19922. });
  19923. var pLabel = FormField.parts().label({
  19924. dom: {
  19925. tag: 'span',
  19926. classes: ['tox-checkbox__label'],
  19927. innerHtml: providerBackstage.translate(spec.label)
  19928. },
  19929. behaviours: derive$1([Unselecting.config({})])
  19930. });
  19931. var makeIcon = function (className) {
  19932. var iconName = className === 'checked' ? 'selected' : 'unselected';
  19933. return {
  19934. dom: {
  19935. tag: 'span',
  19936. classes: [
  19937. 'tox-icon',
  19938. 'tox-checkbox-icon__' + className
  19939. ],
  19940. innerHtml: get$d(iconName, providerBackstage.icons)
  19941. }
  19942. };
  19943. };
  19944. var memIcons = record({
  19945. dom: {
  19946. tag: 'div',
  19947. classes: ['tox-checkbox__icons']
  19948. },
  19949. components: [
  19950. makeIcon('checked'),
  19951. makeIcon('unchecked')
  19952. ]
  19953. });
  19954. return FormField.sketch({
  19955. dom: {
  19956. tag: 'label',
  19957. classes: ['tox-checkbox']
  19958. },
  19959. components: [
  19960. pField,
  19961. memIcons.asSpec(),
  19962. pLabel
  19963. ],
  19964. fieldBehaviours: derive$1([Disabling.config({
  19965. disabled: spec.disabled,
  19966. disableClass: 'tox-checkbox--disabled',
  19967. onDisabled: function (comp) {
  19968. FormField.getField(comp).each(Disabling.disable);
  19969. },
  19970. onEnabled: function (comp) {
  19971. FormField.getField(comp).each(Disabling.enable);
  19972. }
  19973. })])
  19974. });
  19975. };
  19976. var renderHtmlPanel = function (spec) {
  19977. if (spec.presets === 'presentation') {
  19978. return Container.sketch({
  19979. dom: {
  19980. tag: 'div',
  19981. classes: ['tox-form__group'],
  19982. innerHtml: spec.html
  19983. }
  19984. });
  19985. } else {
  19986. return Container.sketch({
  19987. dom: {
  19988. tag: 'div',
  19989. classes: ['tox-form__group'],
  19990. innerHtml: spec.html,
  19991. attributes: { role: 'document' }
  19992. },
  19993. containerBehaviours: derive$1([
  19994. Tabstopping.config({}),
  19995. Focusing.config({})
  19996. ])
  19997. });
  19998. }
  19999. };
  20000. var renderLabel$2 = function (spec, backstageShared) {
  20001. var label = {
  20002. dom: {
  20003. tag: 'label',
  20004. innerHtml: backstageShared.providers.translate(spec.label),
  20005. classes: ['tox-label']
  20006. }
  20007. };
  20008. var comps = map(spec.items, backstageShared.interpreter);
  20009. return {
  20010. dom: {
  20011. tag: 'div',
  20012. classes: ['tox-form__group']
  20013. },
  20014. components: [label].concat(comps),
  20015. behaviours: derive$1([
  20016. ComposingConfigs.self(),
  20017. Replacing.config({}),
  20018. RepresentingConfigs.domHtml(Option.none()),
  20019. Keying.config({ mode: 'acyclic' })
  20020. ])
  20021. };
  20022. };
  20023. var renderCollection = function (spec, providersBackstage) {
  20024. var pLabel = spec.label.map(function (label) {
  20025. return renderLabel(label, providersBackstage);
  20026. });
  20027. var runOnItem = function (f) {
  20028. return function (comp, se) {
  20029. closest$3(se.event().target(), '[data-collection-item-value]').each(function (target) {
  20030. f(comp, se, target, get$2(target, 'data-collection-item-value'));
  20031. });
  20032. };
  20033. };
  20034. var escapeAttribute = function (ch) {
  20035. if (ch === '"') {
  20036. return '&quot;';
  20037. }
  20038. return ch;
  20039. };
  20040. var setContents = function (comp, items) {
  20041. var htmlLines = map(items, function (item) {
  20042. var itemText = global$7.translate(item.text);
  20043. var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  20044. var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  20045. var mapItemName = {
  20046. '_': ' ',
  20047. ' - ': ' ',
  20048. '-': ' '
  20049. };
  20050. var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  20051. return mapItemName[match];
  20052. });
  20053. return '<div class="tox-collection__item" tabindex="-1" data-collection-item-value="' + escapeAttribute(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  20054. });
  20055. var chunks = spec.columns > 1 && spec.columns !== 'auto' ? chunk(htmlLines, spec.columns) : [htmlLines];
  20056. var html = map(chunks, function (ch) {
  20057. return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  20058. });
  20059. set(comp.element(), html.join(''));
  20060. };
  20061. var onClick = runOnItem(function (comp, se, tgt, itemValue) {
  20062. se.stop();
  20063. emitWith(comp, formActionEvent, {
  20064. name: spec.name,
  20065. value: itemValue
  20066. });
  20067. });
  20068. var collectionEvents = [
  20069. run(mouseover(), runOnItem(function (comp, se, tgt) {
  20070. focus$1(tgt);
  20071. })),
  20072. run(click(), onClick),
  20073. run(tap(), onClick),
  20074. run(focusin(), runOnItem(function (comp, se, tgt) {
  20075. descendant$1(comp.element(), '.' + activeClass).each(function (currentActive) {
  20076. remove$4(currentActive, activeClass);
  20077. });
  20078. add$2(tgt, activeClass);
  20079. })),
  20080. run(focusout(), runOnItem(function (comp) {
  20081. descendant$1(comp.element(), '.' + activeClass).each(function (currentActive) {
  20082. remove$4(currentActive, activeClass);
  20083. });
  20084. })),
  20085. runOnExecute(runOnItem(function (comp, se, tgt, itemValue) {
  20086. emitWith(comp, formActionEvent, {
  20087. name: spec.name,
  20088. value: itemValue
  20089. });
  20090. }))
  20091. ];
  20092. var pField = FormField.parts().field({
  20093. dom: {
  20094. tag: 'div',
  20095. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  20096. },
  20097. components: [],
  20098. factory: { sketch: identity },
  20099. behaviours: derive$1([
  20100. Replacing.config({}),
  20101. Representing.config({
  20102. store: {
  20103. mode: 'memory',
  20104. initialValue: []
  20105. },
  20106. onSetValue: function (comp, items) {
  20107. setContents(comp, items);
  20108. if (spec.columns === 'auto') {
  20109. detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  20110. var numRows = _a.numRows, numColumns = _a.numColumns;
  20111. Keying.setGridSize(comp, numRows, numColumns);
  20112. });
  20113. }
  20114. emit(comp, formResizeEvent);
  20115. }
  20116. }),
  20117. Tabstopping.config({}),
  20118. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  20119. config('collection-events', collectionEvents)
  20120. ])
  20121. });
  20122. var extraClasses = ['tox-form__group--collection'];
  20123. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  20124. };
  20125. var renderTable = function (spec, providersBackstage) {
  20126. var renderTh = function (text) {
  20127. return {
  20128. dom: {
  20129. tag: 'th',
  20130. innerHtml: providersBackstage.translate(text)
  20131. }
  20132. };
  20133. };
  20134. var renderHeader = function (header) {
  20135. return {
  20136. dom: { tag: 'thead' },
  20137. components: [{
  20138. dom: { tag: 'tr' },
  20139. components: map(header, renderTh)
  20140. }]
  20141. };
  20142. };
  20143. var renderTd = function (text) {
  20144. return {
  20145. dom: {
  20146. tag: 'td',
  20147. innerHtml: providersBackstage.translate(text)
  20148. }
  20149. };
  20150. };
  20151. var renderTr = function (row) {
  20152. return {
  20153. dom: { tag: 'tr' },
  20154. components: map(row, renderTd)
  20155. };
  20156. };
  20157. var renderRows = function (rows) {
  20158. return {
  20159. dom: { tag: 'tbody' },
  20160. components: map(rows, renderTr)
  20161. };
  20162. };
  20163. return {
  20164. dom: {
  20165. tag: 'table',
  20166. classes: ['tox-dialog__table']
  20167. },
  20168. components: [
  20169. renderHeader(spec.header),
  20170. renderRows(spec.cells)
  20171. ],
  20172. behaviours: derive$1([
  20173. Tabstopping.config({}),
  20174. Focusing.config({})
  20175. ])
  20176. };
  20177. };
  20178. var renderPanel = function (spec, backstage) {
  20179. return {
  20180. dom: {
  20181. tag: 'div',
  20182. classes: spec.classes
  20183. },
  20184. components: map(spec.items, backstage.shared.interpreter)
  20185. };
  20186. };
  20187. var make$6 = function (render) {
  20188. return function (parts, spec, backstage) {
  20189. return get(spec, 'name').fold(function () {
  20190. return render(spec, backstage);
  20191. }, function (fieldName) {
  20192. return parts.field(fieldName, render(spec, backstage));
  20193. });
  20194. };
  20195. };
  20196. var makeIframe = function (render) {
  20197. return function (parts, spec, backstage) {
  20198. var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  20199. return make$6(render)(parts, iframeSpec, backstage);
  20200. };
  20201. };
  20202. var factories = {
  20203. bar: make$6(function (spec, backstage) {
  20204. return renderBar(spec, backstage.shared);
  20205. }),
  20206. collection: make$6(function (spec, backstage) {
  20207. return renderCollection(spec, backstage.shared.providers);
  20208. }),
  20209. alertbanner: make$6(function (spec, backstage) {
  20210. return renderAlertBanner(spec, backstage.shared.providers);
  20211. }),
  20212. input: make$6(function (spec, backstage) {
  20213. return renderInput(spec, backstage.shared.providers);
  20214. }),
  20215. textarea: make$6(function (spec, backstage) {
  20216. return renderTextarea(spec, backstage.shared.providers);
  20217. }),
  20218. label: make$6(function (spec, backstage) {
  20219. return renderLabel$2(spec, backstage.shared);
  20220. }),
  20221. iframe: makeIframe(function (spec, backstage) {
  20222. return renderIFrame(spec, backstage.shared.providers);
  20223. }),
  20224. button: make$6(function (spec, backstage) {
  20225. return renderDialogButton(spec, backstage.shared.providers);
  20226. }),
  20227. checkbox: make$6(function (spec, backstage) {
  20228. return renderCheckbox(spec, backstage.shared.providers);
  20229. }),
  20230. colorinput: make$6(function (spec, backstage) {
  20231. return renderColorInput(spec, backstage.shared, backstage.colorinput);
  20232. }),
  20233. colorpicker: make$6(renderColorPicker),
  20234. dropzone: make$6(function (spec, backstage) {
  20235. return renderDropZone(spec, backstage.shared.providers);
  20236. }),
  20237. grid: make$6(function (spec, backstage) {
  20238. return renderGrid(spec, backstage.shared);
  20239. }),
  20240. selectbox: make$6(function (spec, backstage) {
  20241. return renderSelectBox(spec, backstage.shared.providers);
  20242. }),
  20243. sizeinput: make$6(function (spec, backstage) {
  20244. return renderSizeInput(spec, backstage.shared.providers);
  20245. }),
  20246. urlinput: make$6(function (spec, backstage) {
  20247. return renderUrlInput(spec, backstage, backstage.urlinput);
  20248. }),
  20249. customeditor: make$6(renderCustomEditor),
  20250. htmlpanel: make$6(renderHtmlPanel),
  20251. imagetools: make$6(function (spec, backstage) {
  20252. return renderImageTools(spec, backstage.shared.providers);
  20253. }),
  20254. table: make$6(function (spec, backstage) {
  20255. return renderTable(spec, backstage.shared.providers);
  20256. }),
  20257. panel: make$6(function (spec, backstage) {
  20258. return renderPanel(spec, backstage);
  20259. })
  20260. };
  20261. var noFormParts = {
  20262. field: function (_name, spec) {
  20263. return spec;
  20264. }
  20265. };
  20266. var interpretInForm = function (parts, spec, oldBackstage) {
  20267. var newBackstage = deepMerge(oldBackstage, {
  20268. shared: {
  20269. interpreter: function (childSpec) {
  20270. return interpretParts(parts, childSpec, newBackstage);
  20271. }
  20272. }
  20273. });
  20274. return interpretParts(parts, spec, newBackstage);
  20275. };
  20276. var interpretParts = function (parts, spec, backstage) {
  20277. return get(factories, spec.type).fold(function () {
  20278. domGlobals.console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  20279. return spec;
  20280. }, function (factory) {
  20281. return factory(parts, spec, backstage);
  20282. });
  20283. };
  20284. var interpretWithoutForm = function (spec, backstage) {
  20285. var parts = noFormParts;
  20286. return interpretParts(parts, spec, backstage);
  20287. };
  20288. var bubbleAlignments = {
  20289. valignCentre: [],
  20290. alignCentre: [],
  20291. alignLeft: [],
  20292. alignRight: [],
  20293. right: [],
  20294. left: [],
  20295. bottom: [],
  20296. top: []
  20297. };
  20298. var getInlineDialogAnchor = function (bodyElement, lazyAnchorbar, useEditableAreaAnchor) {
  20299. var editableAreaAnchor = function () {
  20300. return {
  20301. anchor: 'node',
  20302. root: bodyElement(),
  20303. node: Option.from(bodyElement()),
  20304. bubble: nu$8(-12, -12, bubbleAlignments),
  20305. layouts: {
  20306. onRtl: function () {
  20307. return [northeast$3];
  20308. },
  20309. onLtr: function () {
  20310. return [northwest$3];
  20311. }
  20312. },
  20313. overrides: { maxHeightFunction: expandable() }
  20314. };
  20315. };
  20316. var standardAnchor = function () {
  20317. return {
  20318. anchor: 'hotspot',
  20319. hotspot: lazyAnchorbar(),
  20320. bubble: nu$8(-12, 12, bubbleAlignments),
  20321. layouts: {
  20322. onRtl: function () {
  20323. return [southeast$1];
  20324. },
  20325. onLtr: function () {
  20326. return [southwest$1];
  20327. }
  20328. },
  20329. overrides: { maxHeightFunction: expandable() }
  20330. };
  20331. };
  20332. return useEditableAreaAnchor ? editableAreaAnchor : standardAnchor;
  20333. };
  20334. var getBannerAnchor = function (bodyElement, lazyAnchorbar, useEditableAreaAnchor) {
  20335. var editableAreaAnchor = function () {
  20336. return {
  20337. anchor: 'node',
  20338. root: bodyElement(),
  20339. node: Option.from(bodyElement()),
  20340. layouts: {
  20341. onRtl: function () {
  20342. return [north$3];
  20343. },
  20344. onLtr: function () {
  20345. return [north$3];
  20346. }
  20347. }
  20348. };
  20349. };
  20350. var standardAnchor = function () {
  20351. return {
  20352. anchor: 'hotspot',
  20353. hotspot: lazyAnchorbar(),
  20354. layouts: {
  20355. onRtl: function () {
  20356. return [south$1];
  20357. },
  20358. onLtr: function () {
  20359. return [south$1];
  20360. }
  20361. }
  20362. };
  20363. };
  20364. return useEditableAreaAnchor ? editableAreaAnchor : standardAnchor;
  20365. };
  20366. var getCursorAnchor = function (editor, bodyElement) {
  20367. return function () {
  20368. return {
  20369. anchor: 'selection',
  20370. root: bodyElement(),
  20371. getSelection: function () {
  20372. var rng = editor.selection.getRng();
  20373. return Option.some(Selection.range(Element.fromDom(rng.startContainer), rng.startOffset, Element.fromDom(rng.endContainer), rng.endOffset));
  20374. }
  20375. };
  20376. };
  20377. };
  20378. var getNodeAnchor = function (bodyElement) {
  20379. return function (element) {
  20380. return {
  20381. anchor: 'node',
  20382. root: bodyElement(),
  20383. node: element
  20384. };
  20385. };
  20386. };
  20387. var getAnchors = function (editor, lazyAnchorbar) {
  20388. var useFixedToolbarContainer = useFixedContainer(editor);
  20389. var bodyElement = function () {
  20390. return Element.fromDom(editor.getBody());
  20391. };
  20392. var useEditableAreaAnchor = useFixedToolbarContainer || !isToolbarLocationTop(editor);
  20393. return {
  20394. inlineDialog: getInlineDialogAnchor(bodyElement, lazyAnchorbar, useEditableAreaAnchor),
  20395. banner: getBannerAnchor(bodyElement, lazyAnchorbar, useEditableAreaAnchor),
  20396. cursor: getCursorAnchor(editor, bodyElement),
  20397. node: getNodeAnchor(bodyElement)
  20398. };
  20399. };
  20400. var Anchors = { getAnchors: getAnchors };
  20401. var colorPicker = function (editor) {
  20402. return function (callback, value) {
  20403. var dialog = ColorSwatch.colorPickerDialog(editor);
  20404. dialog(callback, value);
  20405. };
  20406. };
  20407. var hasCustomColors$1 = function (editor) {
  20408. return function () {
  20409. return Settings.hasCustomColors(editor);
  20410. };
  20411. };
  20412. var getColors$1 = function (editor) {
  20413. return function () {
  20414. return Settings.getColors(editor);
  20415. };
  20416. };
  20417. var getColorCols$2 = function (editor) {
  20418. return function () {
  20419. return ColorSwatch.getColorCols(editor);
  20420. };
  20421. };
  20422. var ColorInputBackstage = function (editor) {
  20423. return {
  20424. colorPicker: colorPicker(editor),
  20425. hasCustomColors: hasCustomColors$1(editor),
  20426. getColors: getColors$1(editor),
  20427. getColorCols: getColorCols$2(editor)
  20428. };
  20429. };
  20430. var isDraggableModal$1 = function (editor) {
  20431. return function () {
  20432. return isDraggableModal(editor);
  20433. };
  20434. };
  20435. var DialogBackstage = function (editor) {
  20436. return { isDraggableModal: isDraggableModal$1(editor) };
  20437. };
  20438. var defaultStyleFormats = [
  20439. {
  20440. title: 'Headings',
  20441. items: [
  20442. {
  20443. title: 'Heading 1',
  20444. format: 'h1'
  20445. },
  20446. {
  20447. title: 'Heading 2',
  20448. format: 'h2'
  20449. },
  20450. {
  20451. title: 'Heading 3',
  20452. format: 'h3'
  20453. },
  20454. {
  20455. title: 'Heading 4',
  20456. format: 'h4'
  20457. },
  20458. {
  20459. title: 'Heading 5',
  20460. format: 'h5'
  20461. },
  20462. {
  20463. title: 'Heading 6',
  20464. format: 'h6'
  20465. }
  20466. ]
  20467. },
  20468. {
  20469. title: 'Inline',
  20470. items: [
  20471. {
  20472. title: 'Bold',
  20473. icon: 'bold',
  20474. format: 'bold'
  20475. },
  20476. {
  20477. title: 'Italic',
  20478. icon: 'italic',
  20479. format: 'italic'
  20480. },
  20481. {
  20482. title: 'Underline',
  20483. icon: 'underline',
  20484. format: 'underline'
  20485. },
  20486. {
  20487. title: 'Strikethrough',
  20488. icon: 'strike-through',
  20489. format: 'strikethrough'
  20490. },
  20491. {
  20492. title: 'Superscript',
  20493. icon: 'superscript',
  20494. format: 'superscript'
  20495. },
  20496. {
  20497. title: 'Subscript',
  20498. icon: 'subscript',
  20499. format: 'subscript'
  20500. },
  20501. {
  20502. title: 'Code',
  20503. icon: 'code',
  20504. format: 'code'
  20505. }
  20506. ]
  20507. },
  20508. {
  20509. title: 'Blocks',
  20510. items: [
  20511. {
  20512. title: 'Paragraph',
  20513. format: 'p'
  20514. },
  20515. {
  20516. title: 'Blockquote',
  20517. format: 'blockquote'
  20518. },
  20519. {
  20520. title: 'Div',
  20521. format: 'div'
  20522. },
  20523. {
  20524. title: 'Pre',
  20525. format: 'pre'
  20526. }
  20527. ]
  20528. },
  20529. {
  20530. title: 'Align',
  20531. items: [
  20532. {
  20533. title: 'Left',
  20534. icon: 'align-left',
  20535. format: 'alignleft'
  20536. },
  20537. {
  20538. title: 'Center',
  20539. icon: 'align-center',
  20540. format: 'aligncenter'
  20541. },
  20542. {
  20543. title: 'Right',
  20544. icon: 'align-right',
  20545. format: 'alignright'
  20546. },
  20547. {
  20548. title: 'Justify',
  20549. icon: 'align-justify',
  20550. format: 'alignjustify'
  20551. }
  20552. ]
  20553. }
  20554. ];
  20555. var isNestedFormat = function (format) {
  20556. return has(format, 'items');
  20557. };
  20558. var isBlockFormat = function (format) {
  20559. return has(format, 'block');
  20560. };
  20561. var isInlineFormat = function (format) {
  20562. return has(format, 'inline');
  20563. };
  20564. var isSelectorFormat = function (format) {
  20565. return has(format, 'selector');
  20566. };
  20567. var mapFormats = function (userFormats) {
  20568. return foldl(userFormats, function (acc, fmt) {
  20569. if (isNestedFormat(fmt)) {
  20570. var result = mapFormats(fmt.items);
  20571. return {
  20572. customFormats: acc.customFormats.concat(result.customFormats),
  20573. formats: acc.formats.concat([{
  20574. title: fmt.title,
  20575. items: result.formats
  20576. }])
  20577. };
  20578. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  20579. var formatName = 'custom-' + fmt.title.toLowerCase();
  20580. return {
  20581. customFormats: acc.customFormats.concat([{
  20582. name: formatName,
  20583. format: fmt
  20584. }]),
  20585. formats: acc.formats.concat([{
  20586. title: fmt.title,
  20587. format: formatName,
  20588. icon: fmt.icon
  20589. }])
  20590. };
  20591. } else {
  20592. return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  20593. }
  20594. }, {
  20595. customFormats: [],
  20596. formats: []
  20597. });
  20598. };
  20599. var registerCustomFormats = function (editor, userFormats) {
  20600. var result = mapFormats(userFormats);
  20601. var registerFormats = function (customFormats) {
  20602. each(customFormats, function (fmt) {
  20603. if (!editor.formatter.has(fmt.name)) {
  20604. editor.formatter.register(fmt.name, fmt.format);
  20605. }
  20606. });
  20607. };
  20608. if (editor.formatter) {
  20609. registerFormats(result.customFormats);
  20610. } else {
  20611. editor.on('init', function () {
  20612. registerFormats(result.customFormats);
  20613. });
  20614. }
  20615. return result.formats;
  20616. };
  20617. var getStyleFormats = function (editor) {
  20618. return getUserStyleFormats(editor).map(function (userFormats) {
  20619. var registeredUserFormats = registerCustomFormats(editor, userFormats);
  20620. return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  20621. }).getOr(defaultStyleFormats);
  20622. };
  20623. var processBasic = function (item, isSelectedFor, getPreviewFor) {
  20624. var formatterSpec = {
  20625. type: 'formatter',
  20626. isSelected: isSelectedFor(item.format),
  20627. getStylePreview: getPreviewFor(item.format)
  20628. };
  20629. return deepMerge(item, formatterSpec);
  20630. };
  20631. var register$3 = function (editor, formats, isSelectedFor, getPreviewFor) {
  20632. var enrichSupported = function (item) {
  20633. return processBasic(item, isSelectedFor, getPreviewFor);
  20634. };
  20635. var enrichMenu = function (item) {
  20636. var submenuSpec = { type: 'submenu' };
  20637. return deepMerge(item, submenuSpec);
  20638. };
  20639. var enrichCustom = function (item) {
  20640. var formatName = generate$1(item.title);
  20641. var customSpec = {
  20642. type: 'formatter',
  20643. format: formatName,
  20644. isSelected: isSelectedFor(formatName),
  20645. getStylePreview: getPreviewFor(formatName)
  20646. };
  20647. var newItem = deepMerge(item, customSpec);
  20648. editor.formatter.register(formatName, newItem);
  20649. return newItem;
  20650. };
  20651. var doEnrich = function (items) {
  20652. return map(items, function (item) {
  20653. var keys$1 = keys(item);
  20654. if (hasNonNullableKey(item, 'items')) {
  20655. var newItems_1 = doEnrich(item.items);
  20656. return deepMerge(enrichMenu(item), {
  20657. getStyleItems: function () {
  20658. return newItems_1;
  20659. }
  20660. });
  20661. } else if (hasNonNullableKey(item, 'format')) {
  20662. return enrichSupported(item);
  20663. } else if (keys$1.length === 1 && contains(keys$1, 'title')) {
  20664. return deepMerge(item, { type: 'separator' });
  20665. } else {
  20666. return enrichCustom(item);
  20667. }
  20668. });
  20669. };
  20670. return doEnrich(formats);
  20671. };
  20672. var init$7 = function (editor) {
  20673. var isSelectedFor = function (format) {
  20674. return function () {
  20675. return editor.formatter.match(format);
  20676. };
  20677. };
  20678. var getPreviewFor = function (format) {
  20679. return function () {
  20680. var fmt = editor.formatter.get(format);
  20681. return fmt !== undefined ? Option.some({
  20682. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  20683. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  20684. }) : Option.none();
  20685. };
  20686. };
  20687. var flatten = function (fmt) {
  20688. var subs = fmt.items;
  20689. return subs !== undefined && subs.length > 0 ? bind(subs, flatten) : [fmt.format];
  20690. };
  20691. var settingsFormats = Cell([]);
  20692. var settingsFlattenedFormats = Cell([]);
  20693. var eventsFormats = Cell([]);
  20694. var eventsFlattenedFormats = Cell([]);
  20695. var replaceSettings = Cell(false);
  20696. editor.on('PreInit', function (e) {
  20697. var formats = getStyleFormats(editor);
  20698. var enriched = register$3(editor, formats, isSelectedFor, getPreviewFor);
  20699. settingsFormats.set(enriched);
  20700. settingsFlattenedFormats.set(bind(enriched, flatten));
  20701. });
  20702. editor.on('addStyleModifications', function (e) {
  20703. var modifications = register$3(editor, e.items, isSelectedFor, getPreviewFor);
  20704. eventsFormats.set(modifications);
  20705. replaceSettings.set(e.replace);
  20706. eventsFlattenedFormats.set(bind(modifications, flatten));
  20707. });
  20708. var getData = function () {
  20709. var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  20710. var fromEvents = eventsFormats.get();
  20711. return fromSettings.concat(fromEvents);
  20712. };
  20713. var getFlattenedKeys = function () {
  20714. var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  20715. var fromEvents = eventsFlattenedFormats.get();
  20716. return fromSettings.concat(fromEvents);
  20717. };
  20718. return {
  20719. getData: getData,
  20720. getFlattenedKeys: getFlattenedKeys
  20721. };
  20722. };
  20723. var trim$1 = global$e.trim;
  20724. var hasContentEditableState = function (value) {
  20725. return function (node) {
  20726. if (node && node.nodeType === 1) {
  20727. if (node.contentEditable === value) {
  20728. return true;
  20729. }
  20730. if (node.getAttribute('data-mce-contenteditable') === value) {
  20731. return true;
  20732. }
  20733. }
  20734. return false;
  20735. };
  20736. };
  20737. var isContentEditableTrue = hasContentEditableState('true');
  20738. var isContentEditableFalse = hasContentEditableState('false');
  20739. var create$8 = function (type, title, url, level, attach) {
  20740. return {
  20741. type: type,
  20742. title: title,
  20743. url: url,
  20744. level: level,
  20745. attach: attach
  20746. };
  20747. };
  20748. var isChildOfContentEditableTrue = function (node) {
  20749. while (node = node.parentNode) {
  20750. var value = node.contentEditable;
  20751. if (value && value !== 'inherit') {
  20752. return isContentEditableTrue(node);
  20753. }
  20754. }
  20755. return false;
  20756. };
  20757. var select = function (selector, root) {
  20758. return map(descendants(Element.fromDom(root), selector), function (element) {
  20759. return element.dom();
  20760. });
  20761. };
  20762. var getElementText = function (elm) {
  20763. return elm.innerText || elm.textContent;
  20764. };
  20765. var getOrGenerateId = function (elm) {
  20766. return elm.id ? elm.id : generate$1('h');
  20767. };
  20768. var isAnchor = function (elm) {
  20769. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  20770. };
  20771. var isValidAnchor = function (elm) {
  20772. return isAnchor(elm) && isEditable(elm);
  20773. };
  20774. var isHeader = function (elm) {
  20775. return elm && /^(H[1-6])$/.test(elm.nodeName);
  20776. };
  20777. var isEditable = function (elm) {
  20778. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  20779. };
  20780. var isValidHeader = function (elm) {
  20781. return isHeader(elm) && isEditable(elm);
  20782. };
  20783. var getLevel = function (elm) {
  20784. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  20785. };
  20786. var headerTarget = function (elm) {
  20787. var headerId = getOrGenerateId(elm);
  20788. var attach = function () {
  20789. elm.id = headerId;
  20790. };
  20791. return create$8('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  20792. };
  20793. var anchorTarget = function (elm) {
  20794. var anchorId = elm.id || elm.name;
  20795. var anchorText = getElementText(elm);
  20796. return create$8('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  20797. };
  20798. var getHeaderTargets = function (elms) {
  20799. return map(filter(elms, isValidHeader), headerTarget);
  20800. };
  20801. var getAnchorTargets = function (elms) {
  20802. return map(filter(elms, isValidAnchor), anchorTarget);
  20803. };
  20804. var getTargetElements = function (elm) {
  20805. var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  20806. return elms;
  20807. };
  20808. var hasTitle = function (target) {
  20809. return trim$1(target.title).length > 0;
  20810. };
  20811. var find$5 = function (elm) {
  20812. var elms = getTargetElements(elm);
  20813. return filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  20814. };
  20815. var LinkTargets = { find: find$5 };
  20816. var STORAGE_KEY = 'tinymce-url-history';
  20817. var HISTORY_LENGTH = 5;
  20818. var isHttpUrl = function (url) {
  20819. return isString(url) && /^https?/.test(url);
  20820. };
  20821. var isArrayOfUrl = function (a) {
  20822. return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  20823. };
  20824. var isRecordOfUrlArray = function (r) {
  20825. return isObject(r) && find$1(r, function (value) {
  20826. return !isArrayOfUrl(value);
  20827. }).isNone();
  20828. };
  20829. var getAllHistory = function () {
  20830. var unparsedHistory = domGlobals.localStorage.getItem(STORAGE_KEY);
  20831. if (unparsedHistory === null) {
  20832. return {};
  20833. }
  20834. var history;
  20835. try {
  20836. history = JSON.parse(unparsedHistory);
  20837. } catch (e) {
  20838. if (e instanceof SyntaxError) {
  20839. domGlobals.console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  20840. return {};
  20841. }
  20842. throw e;
  20843. }
  20844. if (!isRecordOfUrlArray(history)) {
  20845. domGlobals.console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  20846. return {};
  20847. }
  20848. return history;
  20849. };
  20850. var setAllHistory = function (history) {
  20851. if (!isRecordOfUrlArray(history)) {
  20852. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  20853. }
  20854. domGlobals.localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
  20855. };
  20856. var getHistory = function (fileType) {
  20857. var history = getAllHistory();
  20858. return Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  20859. };
  20860. var addToHistory = function (url, fileType) {
  20861. if (!isHttpUrl(url)) {
  20862. return;
  20863. }
  20864. var history = getAllHistory();
  20865. var items = Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  20866. var itemsWithoutUrl = filter(items, function (item) {
  20867. return item !== url;
  20868. });
  20869. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  20870. setAllHistory(history);
  20871. };
  20872. var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  20873. var isTruthy = function (value) {
  20874. return !!value;
  20875. };
  20876. var makeMap = function (value) {
  20877. return map$1(global$e.makeMap(value, /[, ]/), isTruthy);
  20878. };
  20879. var getOpt$1 = function (obj, key) {
  20880. return hasOwnProperty$2.call(obj, key) ? Option.some(obj[key]) : Option.none();
  20881. };
  20882. var getTextSetting = function (settings, name, defaultValue) {
  20883. var value = getOpt$1(settings, name).getOr(defaultValue);
  20884. return isString(value) ? Option.some(value) : Option.none();
  20885. };
  20886. var getPicker = function (settings) {
  20887. return Option.some(settings.file_picker_callback).filter(isFunction);
  20888. };
  20889. var getPickerTypes = function (settings) {
  20890. var optFileTypes = Option.some(settings.file_picker_types).filter(isTruthy);
  20891. var optLegacyTypes = Option.some(settings.file_browser_callback_types).filter(isTruthy);
  20892. var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  20893. return getPicker(settings).fold(function () {
  20894. return false;
  20895. }, function (_picker) {
  20896. return optTypes.fold(function () {
  20897. return true;
  20898. }, function (types) {
  20899. return keys(types).length > 0 ? types : false;
  20900. });
  20901. });
  20902. };
  20903. var getPickerSetting = function (settings, filetype) {
  20904. var pickerTypes = getPickerTypes(settings);
  20905. if (isBoolean(pickerTypes)) {
  20906. return pickerTypes ? getPicker(settings) : Option.none();
  20907. } else {
  20908. return pickerTypes[filetype] ? getPicker(settings) : Option.none();
  20909. }
  20910. };
  20911. var getUrlPicker = function (editor, filetype) {
  20912. return getPickerSetting(editor.settings, filetype).map(function (picker) {
  20913. return function (entry) {
  20914. return Future.nu(function (completer) {
  20915. var handler = function (value, meta) {
  20916. if (!isString(value)) {
  20917. throw new Error('Expected value to be string');
  20918. }
  20919. if (meta !== undefined && !isObject(meta)) {
  20920. throw new Error('Expected meta to be a object');
  20921. }
  20922. var r = {
  20923. value: value,
  20924. meta: meta
  20925. };
  20926. completer(r);
  20927. };
  20928. var meta = __assign({
  20929. filetype: filetype,
  20930. fieldname: entry.fieldname
  20931. }, Option.from(entry.meta).getOr({}));
  20932. picker.call(editor, handler, entry.value, meta);
  20933. });
  20934. };
  20935. });
  20936. };
  20937. var getLinkInformation = function (editor) {
  20938. if (editor.settings.typeahead_urls === false) {
  20939. return Option.none();
  20940. }
  20941. return Option.some({
  20942. targets: LinkTargets.find(editor.getBody()),
  20943. anchorTop: getTextSetting(editor.settings, 'anchor_top', '#top').getOrUndefined(),
  20944. anchorBottom: getTextSetting(editor.settings, 'anchor_bottom', '#bottom').getOrUndefined()
  20945. });
  20946. };
  20947. var getValidationHandler = function (editor) {
  20948. var optValidator = Option.from(editor.settings.file_picker_validator_handler).filter(isFunction);
  20949. return optValidator.orThunk(function () {
  20950. return Option.from(editor.settings.filepicker_validator_handler).filter(isFunction);
  20951. });
  20952. };
  20953. var UrlInputBackstage = function (editor) {
  20954. return {
  20955. getHistory: getHistory,
  20956. addToHistory: addToHistory,
  20957. getLinkInformation: function () {
  20958. return getLinkInformation(editor);
  20959. },
  20960. getValidationHandler: function () {
  20961. return getValidationHandler(editor);
  20962. },
  20963. getUrlPicker: function (filetype) {
  20964. return getUrlPicker(editor, filetype);
  20965. }
  20966. };
  20967. };
  20968. var init$8 = function (sink, editor, lazyAnchorbar) {
  20969. var contextMenuState = Cell(false);
  20970. var backstage = {
  20971. shared: {
  20972. providers: {
  20973. icons: function () {
  20974. return editor.ui.registry.getAll().icons;
  20975. },
  20976. menuItems: function () {
  20977. return editor.ui.registry.getAll().menuItems;
  20978. },
  20979. translate: global$7.translate
  20980. },
  20981. interpreter: function (s) {
  20982. return interpretWithoutForm(s, backstage);
  20983. },
  20984. anchors: Anchors.getAnchors(editor, lazyAnchorbar),
  20985. getSink: function () {
  20986. return Result.value(sink);
  20987. }
  20988. },
  20989. urlinput: UrlInputBackstage(editor),
  20990. styleselect: init$7(editor),
  20991. colorinput: ColorInputBackstage(editor),
  20992. dialog: DialogBackstage(editor),
  20993. isContextMenuOpen: function () {
  20994. return contextMenuState.get();
  20995. },
  20996. setContextMenuState: function (state) {
  20997. return contextMenuState.set(state);
  20998. }
  20999. };
  21000. return backstage;
  21001. };
  21002. var expandable$1 = constant(function (element, available) {
  21003. setMax$1(element, Math.floor(available));
  21004. });
  21005. var showContextToolbarEvent = 'contexttoolbar-show';
  21006. var hideContextToolbarEvent = 'contexttoolbar-hide';
  21007. var schema$k = constant([
  21008. strict$1('items'),
  21009. markers(['itemSelector']),
  21010. field$1('tgroupBehaviours', [Keying])
  21011. ]);
  21012. var parts$7 = constant([group({
  21013. name: 'items',
  21014. unit: 'item'
  21015. })]);
  21016. var factory$9 = function (detail, components, spec, _externals) {
  21017. return {
  21018. uid: detail.uid,
  21019. dom: detail.dom,
  21020. components: components,
  21021. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  21022. mode: 'flow',
  21023. selector: detail.markers.itemSelector
  21024. })]),
  21025. domModification: { attributes: { role: 'toolbar' } }
  21026. };
  21027. };
  21028. var ToolbarGroup = composite$1({
  21029. name: 'ToolbarGroup',
  21030. configFields: schema$k(),
  21031. partFields: parts$7(),
  21032. factory: factory$9
  21033. });
  21034. var schema$l = constant([
  21035. strict$1('dom'),
  21036. defaulted$1('shell', true),
  21037. field$1('toolbarBehaviours', [Replacing])
  21038. ]);
  21039. var enhanceGroups = function () {
  21040. return { behaviours: derive$1([Replacing.config({})]) };
  21041. };
  21042. var parts$8 = constant([optional({
  21043. name: 'groups',
  21044. overrides: enhanceGroups
  21045. })]);
  21046. var factory$a = function (detail, components, spec, _externals) {
  21047. var setGroups = function (toolbar, groups) {
  21048. getGroupContainer(toolbar).fold(function () {
  21049. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21050. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21051. }, function (container) {
  21052. Replacing.set(container, groups);
  21053. });
  21054. };
  21055. var getGroupContainer = function (component) {
  21056. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  21057. };
  21058. var extra = detail.shell ? {
  21059. behaviours: [Replacing.config({})],
  21060. components: []
  21061. } : {
  21062. behaviours: [],
  21063. components: components
  21064. };
  21065. return {
  21066. uid: detail.uid,
  21067. dom: detail.dom,
  21068. components: extra.components,
  21069. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  21070. apis: { setGroups: setGroups },
  21071. domModification: { attributes: { role: 'group' } }
  21072. };
  21073. };
  21074. var Toolbar = composite$1({
  21075. name: 'Toolbar',
  21076. configFields: schema$l(),
  21077. partFields: parts$8(),
  21078. factory: factory$a,
  21079. apis: {
  21080. setGroups: function (apis, toolbar, groups) {
  21081. apis.setGroups(toolbar, groups);
  21082. }
  21083. }
  21084. });
  21085. var generate$6 = function (xs, f) {
  21086. var init = {
  21087. len: 0,
  21088. list: []
  21089. };
  21090. var r = foldl(xs, function (b, a) {
  21091. var value = f(a, b.len);
  21092. return value.fold(constant(b), function (v) {
  21093. return {
  21094. len: v.finish(),
  21095. list: b.list.concat([v])
  21096. };
  21097. });
  21098. }, init);
  21099. return r.list;
  21100. };
  21101. var output$1 = Immutable('within', 'extra', 'withinWidth');
  21102. var apportion = function (units, total, len) {
  21103. var parray = generate$6(units, function (unit, current) {
  21104. var width = len(unit);
  21105. return Option.some({
  21106. element: constant(unit),
  21107. start: constant(current),
  21108. finish: constant(current + width),
  21109. width: constant(width)
  21110. });
  21111. });
  21112. var within = filter(parray, function (unit) {
  21113. return unit.finish() <= total;
  21114. });
  21115. var withinWidth = foldr(within, function (acc, el) {
  21116. return acc + el.width();
  21117. }, 0);
  21118. var extra = parray.slice(within.length);
  21119. return {
  21120. within: constant(within),
  21121. extra: constant(extra),
  21122. withinWidth: constant(withinWidth)
  21123. };
  21124. };
  21125. var toUnit = function (parray) {
  21126. return map(parray, function (unit) {
  21127. return unit.element();
  21128. });
  21129. };
  21130. var fitLast = function (within, extra, withinWidth) {
  21131. var fits = toUnit(within.concat(extra));
  21132. return output$1(fits, [], withinWidth);
  21133. };
  21134. var overflow = function (within, extra, overflower, withinWidth) {
  21135. var fits = toUnit(within).concat([overflower]);
  21136. return output$1(fits, toUnit(extra), withinWidth);
  21137. };
  21138. var fitAll = function (within, extra, withinWidth) {
  21139. return output$1(toUnit(within), [], withinWidth);
  21140. };
  21141. var tryFit = function (total, units, len) {
  21142. var divide = apportion(units, total, len);
  21143. return divide.extra().length === 0 ? Option.some(divide) : Option.none();
  21144. };
  21145. var partition$3 = function (total, units, len, overflower) {
  21146. var divide = tryFit(total, units, len).getOrThunk(function () {
  21147. return apportion(units, total - len(overflower), len);
  21148. });
  21149. var within = divide.within();
  21150. var extra = divide.extra();
  21151. var withinWidth = divide.withinWidth();
  21152. if (extra.length === 1 && extra[0].width() <= len(overflower)) {
  21153. return fitLast(within, extra, withinWidth);
  21154. } else if (extra.length >= 1) {
  21155. return overflow(within, extra, overflower, withinWidth);
  21156. } else {
  21157. return fitAll(within, extra, withinWidth);
  21158. }
  21159. };
  21160. var setGroups = function (toolbar, storedGroups) {
  21161. var bGroups = map(storedGroups, function (g) {
  21162. return premade$1(g);
  21163. });
  21164. Toolbar.setGroups(toolbar, bGroups);
  21165. };
  21166. var findFocusedComp = function (comps) {
  21167. return findMap(comps, function (comp) {
  21168. return search(comp.element()).bind(function (focusedElm) {
  21169. return comp.getSystem().getByDom(focusedElm).toOption();
  21170. });
  21171. });
  21172. };
  21173. var refresh = function (toolbar, detail, setOverflow) {
  21174. var primary = getPartOrDie(toolbar, detail, 'primary');
  21175. var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  21176. set$2(primary.element(), 'visibility', 'hidden');
  21177. var groups = detail.builtGroups.get().concat([overflowGroup]);
  21178. var focusedComp = findFocusedComp(groups);
  21179. setOverflow([]);
  21180. setGroups(primary, groups);
  21181. var availableWidth = get$7(primary.element());
  21182. var overflows = partition$3(availableWidth, detail.builtGroups.get(), function (comp) {
  21183. return get$7(comp.element());
  21184. }, overflowGroup);
  21185. if (overflows.extra().length === 0) {
  21186. Replacing.remove(primary, overflowGroup);
  21187. setOverflow([]);
  21188. } else {
  21189. setGroups(primary, overflows.within());
  21190. setOverflow(overflows.extra());
  21191. }
  21192. remove$6(primary.element(), 'visibility');
  21193. reflow(primary.element());
  21194. focusedComp.each(Focusing.focus);
  21195. };
  21196. var schema$m = constant([
  21197. field$1('splitToolbarBehaviours', [Coupling]),
  21198. state$1('builtGroups', function () {
  21199. return Cell([]);
  21200. })
  21201. ]);
  21202. var schema$n = constant([
  21203. markers(['overflowToggledClass']),
  21204. optionFunction('getOverflowBounds'),
  21205. strict$1('lazySink'),
  21206. state$1('overflowGroups', function () {
  21207. return Cell([]);
  21208. })
  21209. ].concat(schema$m()));
  21210. var parts$9 = constant([
  21211. required({
  21212. factory: Toolbar,
  21213. schema: schema$l(),
  21214. name: 'primary'
  21215. }),
  21216. external$1({
  21217. schema: schema$l(),
  21218. name: 'overflow'
  21219. }),
  21220. external$1({ name: 'overflow-button' }),
  21221. external$1({ name: 'overflow-group' })
  21222. ]);
  21223. var schema$o = constant([
  21224. markers(['toggledClass']),
  21225. strict$1('lazySink'),
  21226. strictFunction('fetch'),
  21227. optionFunction('getBounds'),
  21228. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  21229. schema$1()
  21230. ]);
  21231. var parts$a = constant([
  21232. external$1({
  21233. name: 'button',
  21234. overrides: function (detail) {
  21235. return {
  21236. dom: { attributes: { 'aria-haspopup': 'true' } },
  21237. buttonBehaviours: derive$1([Toggling.config({
  21238. toggleClass: detail.markers.toggledClass,
  21239. aria: { mode: 'expanded' },
  21240. toggleOnExecute: false
  21241. })])
  21242. };
  21243. }
  21244. }),
  21245. external$1({
  21246. factory: Toolbar,
  21247. schema: schema$l(),
  21248. name: 'toolbar',
  21249. overrides: function (detail) {
  21250. return {
  21251. toolbarBehaviours: derive$1([Keying.config({
  21252. mode: 'cyclic',
  21253. onEscape: function (comp) {
  21254. getPart(comp, detail, 'button').each(Focusing.focus);
  21255. return Option.none();
  21256. }
  21257. })])
  21258. };
  21259. }
  21260. })
  21261. ]);
  21262. var toggle$2 = function (button, externals) {
  21263. var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  21264. if (Sandboxing.isOpen(toolbarSandbox)) {
  21265. Sandboxing.close(toolbarSandbox);
  21266. } else {
  21267. Sandboxing.open(toolbarSandbox, externals.toolbar());
  21268. }
  21269. };
  21270. var position$2 = function (button, toolbar, detail, layouts) {
  21271. var bounds = detail.getBounds.map(function (bounder) {
  21272. return bounder();
  21273. });
  21274. var sink = detail.lazySink(button).getOrDie();
  21275. Positioning.positionWithinBounds(sink, {
  21276. anchor: 'hotspot',
  21277. hotspot: button,
  21278. layouts: layouts,
  21279. overrides: { maxWidthFunction: expandable$1() }
  21280. }, toolbar, bounds);
  21281. };
  21282. var setGroups$1 = function (button, toolbar, detail, layouts, groups) {
  21283. Toolbar.setGroups(toolbar, groups);
  21284. position$2(button, toolbar, detail, layouts);
  21285. Toggling.on(button);
  21286. };
  21287. var makeSandbox$1 = function (button, spec, detail) {
  21288. var ariaOwner = manager();
  21289. var onOpen = function (sandbox, toolbar) {
  21290. detail.fetch().get(function (groups) {
  21291. setGroups$1(button, toolbar, detail, spec.layouts, groups);
  21292. ariaOwner.link(button.element());
  21293. Keying.focusIn(toolbar);
  21294. });
  21295. };
  21296. var onClose = function () {
  21297. Toggling.off(button);
  21298. Focusing.focus(button);
  21299. ariaOwner.unlink(button.element());
  21300. };
  21301. return {
  21302. dom: {
  21303. tag: 'div',
  21304. attributes: { id: ariaOwner.id() }
  21305. },
  21306. behaviours: derive$1([
  21307. Keying.config({
  21308. mode: 'special',
  21309. onEscape: function (comp) {
  21310. Sandboxing.close(comp);
  21311. return Option.some(true);
  21312. }
  21313. }),
  21314. Sandboxing.config({
  21315. onOpen: onOpen,
  21316. onClose: onClose,
  21317. isPartOf: function (container, data, queryElem) {
  21318. return isPartOf(data, queryElem) || isPartOf(button, queryElem);
  21319. },
  21320. getAttachPoint: function () {
  21321. return detail.lazySink(button).getOrDie();
  21322. }
  21323. }),
  21324. Receiving.config({
  21325. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: constant(false) }, detail.fireDismissalEventInstead.map(function (fe) {
  21326. return { fireEventInstead: { event: fe.event } };
  21327. }).getOr({})))), receivingChannel$1({
  21328. isExtraPart: constant(false),
  21329. doReposition: function () {
  21330. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21331. position$2(button, toolbar, detail, spec.layouts);
  21332. });
  21333. }
  21334. }))
  21335. })
  21336. ])
  21337. };
  21338. };
  21339. var factory$b = function (detail, components, spec, externals) {
  21340. return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
  21341. action: function (button) {
  21342. toggle$2(button, externals);
  21343. },
  21344. buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  21345. others: {
  21346. toolbarSandbox: function (button) {
  21347. return makeSandbox$1(button, spec, detail);
  21348. }
  21349. }
  21350. })])
  21351. }))), {
  21352. apis: {
  21353. setGroups: function (button, groups) {
  21354. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21355. setGroups$1(button, toolbar, detail, spec.layouts, groups);
  21356. });
  21357. },
  21358. reposition: function (button) {
  21359. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21360. position$2(button, toolbar, detail, spec.layouts);
  21361. });
  21362. },
  21363. toggle: function (button) {
  21364. toggle$2(button, externals);
  21365. },
  21366. getToolbar: function (button) {
  21367. return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  21368. }
  21369. }
  21370. });
  21371. };
  21372. var FloatingToolbarButton = composite$1({
  21373. name: 'FloatingToolbarButton',
  21374. factory: factory$b,
  21375. configFields: schema$o(),
  21376. partFields: parts$a(),
  21377. apis: {
  21378. setGroups: function (apis, button, groups) {
  21379. apis.setGroups(button, groups);
  21380. },
  21381. reposition: function (apis, button) {
  21382. apis.reposition(button);
  21383. },
  21384. toggle: function (apis, button) {
  21385. apis.toggle(button);
  21386. },
  21387. getToolbar: function (apis, button) {
  21388. return apis.getToolbar(button);
  21389. }
  21390. }
  21391. });
  21392. var buildGroups = function (comps) {
  21393. return map(comps, function (g) {
  21394. return premade$1(g);
  21395. });
  21396. };
  21397. var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
  21398. refresh(toolbar, detail, function (overflowGroups) {
  21399. detail.overflowGroups.set(overflowGroups);
  21400. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21401. FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  21402. });
  21403. });
  21404. };
  21405. var factory$c = function (detail, components, spec, externals) {
  21406. var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  21407. fetch: function () {
  21408. return Future.nu(function (resolve) {
  21409. resolve(buildGroups(detail.overflowGroups.get()));
  21410. });
  21411. },
  21412. layouts: {
  21413. onLtr: function () {
  21414. return [southwest$1];
  21415. },
  21416. onRtl: function () {
  21417. return [southeast$1];
  21418. },
  21419. onBottomLtr: function () {
  21420. return [northwest$1];
  21421. },
  21422. onBottomRtl: function () {
  21423. return [northeast$1];
  21424. }
  21425. },
  21426. getBounds: spec.getOverflowBounds,
  21427. lazySink: detail.lazySink,
  21428. fireDismissalEventInstead: {},
  21429. markers: { toggledClass: detail.markers.overflowToggledClass },
  21430. parts: {
  21431. button: externals['overflow-button'](),
  21432. toolbar: externals.overflow()
  21433. }
  21434. }));
  21435. return {
  21436. uid: detail.uid,
  21437. dom: detail.dom,
  21438. components: components,
  21439. behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  21440. others: {
  21441. overflowGroup: function () {
  21442. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
  21443. }
  21444. }
  21445. })]),
  21446. apis: {
  21447. setGroups: function (toolbar, groups) {
  21448. detail.builtGroups.set(map(groups, toolbar.getSystem().build));
  21449. refresh$1(toolbar, memFloatingToolbarButton, detail);
  21450. },
  21451. refresh: function (toolbar) {
  21452. return refresh$1(toolbar, memFloatingToolbarButton, detail);
  21453. },
  21454. toggle: function (toolbar) {
  21455. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21456. FloatingToolbarButton.toggle(floatingToolbarButton);
  21457. });
  21458. },
  21459. reposition: function (toolbar) {
  21460. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21461. FloatingToolbarButton.reposition(floatingToolbarButton);
  21462. });
  21463. },
  21464. getOverflow: function (toolbar) {
  21465. return memFloatingToolbarButton.getOpt(toolbar).bind(function (floatingToolbarButton) {
  21466. return FloatingToolbarButton.getToolbar(floatingToolbarButton);
  21467. });
  21468. }
  21469. },
  21470. domModification: { attributes: { role: 'group' } }
  21471. };
  21472. };
  21473. var SplitFloatingToolbar = composite$1({
  21474. name: 'SplitFloatingToolbar',
  21475. configFields: schema$n(),
  21476. partFields: parts$9(),
  21477. factory: factory$c,
  21478. apis: {
  21479. setGroups: function (apis, toolbar, groups) {
  21480. apis.setGroups(toolbar, groups);
  21481. },
  21482. refresh: function (apis, toolbar) {
  21483. apis.refresh(toolbar);
  21484. },
  21485. reposition: function (apis, toolbar) {
  21486. apis.reposition(toolbar);
  21487. },
  21488. toggle: function (apis, toolbar) {
  21489. apis.toggle(toolbar);
  21490. },
  21491. getOverflow: function (apis, toolbar) {
  21492. return apis.getOverflow(toolbar);
  21493. }
  21494. }
  21495. });
  21496. var getAnimationRoot = function (component, slideConfig) {
  21497. return slideConfig.getAnimationRoot.fold(function () {
  21498. return component.element();
  21499. }, function (get) {
  21500. return get(component);
  21501. });
  21502. };
  21503. var getDimensionProperty = function (slideConfig) {
  21504. return slideConfig.dimension.property;
  21505. };
  21506. var getDimension = function (slideConfig, elem) {
  21507. return slideConfig.dimension.getDimension(elem);
  21508. };
  21509. var disableTransitions = function (component, slideConfig) {
  21510. var root = getAnimationRoot(component, slideConfig);
  21511. remove$5(root, [
  21512. slideConfig.shrinkingClass,
  21513. slideConfig.growingClass
  21514. ]);
  21515. };
  21516. var setShrunk = function (component, slideConfig) {
  21517. remove$4(component.element(), slideConfig.openClass);
  21518. add$2(component.element(), slideConfig.closedClass);
  21519. set$2(component.element(), getDimensionProperty(slideConfig), '0px');
  21520. reflow(component.element());
  21521. };
  21522. var setGrown = function (component, slideConfig) {
  21523. remove$4(component.element(), slideConfig.closedClass);
  21524. add$2(component.element(), slideConfig.openClass);
  21525. remove$6(component.element(), getDimensionProperty(slideConfig));
  21526. };
  21527. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  21528. slideState.setCollapsed();
  21529. set$2(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  21530. reflow(component.element());
  21531. disableTransitions(component, slideConfig);
  21532. setShrunk(component, slideConfig);
  21533. slideConfig.onStartShrink(component);
  21534. slideConfig.onShrunk(component);
  21535. };
  21536. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  21537. var size = calculatedSize.getOrThunk(function () {
  21538. return getDimension(slideConfig, component.element());
  21539. });
  21540. slideState.setCollapsed();
  21541. set$2(component.element(), getDimensionProperty(slideConfig), size);
  21542. reflow(component.element());
  21543. var root = getAnimationRoot(component, slideConfig);
  21544. remove$4(root, slideConfig.growingClass);
  21545. add$2(root, slideConfig.shrinkingClass);
  21546. setShrunk(component, slideConfig);
  21547. slideConfig.onStartShrink(component);
  21548. };
  21549. var doStartSmartShrink = function (component, slideConfig, slideState) {
  21550. var size = getDimension(slideConfig, component.element());
  21551. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  21552. shrinker(component, slideConfig, slideState, Option.some(size));
  21553. };
  21554. var doStartGrow = function (component, slideConfig, slideState) {
  21555. var root = getAnimationRoot(component, slideConfig);
  21556. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  21557. var beforeSize = getDimension(slideConfig, component.element());
  21558. setGrown(component, slideConfig);
  21559. var fullSize = getDimension(slideConfig, component.element());
  21560. var startPartialGrow = function () {
  21561. set$2(component.element(), getDimensionProperty(slideConfig), beforeSize);
  21562. reflow(component.element());
  21563. };
  21564. var startCompleteGrow = function () {
  21565. setShrunk(component, slideConfig);
  21566. };
  21567. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  21568. setStartSize();
  21569. remove$4(root, slideConfig.shrinkingClass);
  21570. add$2(root, slideConfig.growingClass);
  21571. setGrown(component, slideConfig);
  21572. set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
  21573. slideState.setExpanded();
  21574. slideConfig.onStartGrow(component);
  21575. };
  21576. var refresh$2 = function (component, slideConfig, slideState) {
  21577. if (slideState.isExpanded()) {
  21578. remove$6(component.element(), getDimensionProperty(slideConfig));
  21579. var fullSize = getDimension(slideConfig, component.element());
  21580. set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
  21581. }
  21582. };
  21583. var grow = function (component, slideConfig, slideState) {
  21584. if (!slideState.isExpanded()) {
  21585. doStartGrow(component, slideConfig, slideState);
  21586. }
  21587. };
  21588. var shrink = function (component, slideConfig, slideState) {
  21589. if (slideState.isExpanded()) {
  21590. doStartSmartShrink(component, slideConfig, slideState);
  21591. }
  21592. };
  21593. var immediateShrink = function (component, slideConfig, slideState) {
  21594. if (slideState.isExpanded()) {
  21595. doImmediateShrink(component, slideConfig, slideState, Option.none());
  21596. }
  21597. };
  21598. var hasGrown = function (component, slideConfig, slideState) {
  21599. return slideState.isExpanded();
  21600. };
  21601. var hasShrunk = function (component, slideConfig, slideState) {
  21602. return slideState.isCollapsed();
  21603. };
  21604. var isGrowing = function (component, slideConfig, slideState) {
  21605. var root = getAnimationRoot(component, slideConfig);
  21606. return has$2(root, slideConfig.growingClass) === true;
  21607. };
  21608. var isShrinking = function (component, slideConfig, slideState) {
  21609. var root = getAnimationRoot(component, slideConfig);
  21610. return has$2(root, slideConfig.shrinkingClass) === true;
  21611. };
  21612. var isTransitioning = function (component, slideConfig, slideState) {
  21613. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  21614. };
  21615. var toggleGrow = function (component, slideConfig, slideState) {
  21616. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  21617. f(component, slideConfig, slideState);
  21618. };
  21619. var SlidingApis = /*#__PURE__*/Object.freeze({
  21620. __proto__: null,
  21621. refresh: refresh$2,
  21622. grow: grow,
  21623. shrink: shrink,
  21624. immediateShrink: immediateShrink,
  21625. hasGrown: hasGrown,
  21626. hasShrunk: hasShrunk,
  21627. isGrowing: isGrowing,
  21628. isShrinking: isShrinking,
  21629. isTransitioning: isTransitioning,
  21630. toggleGrow: toggleGrow,
  21631. disableTransitions: disableTransitions
  21632. });
  21633. var exhibit$6 = function (base, slideConfig) {
  21634. var expanded = slideConfig.expanded;
  21635. return expanded ? nu$6({
  21636. classes: [slideConfig.openClass],
  21637. styles: {}
  21638. }) : nu$6({
  21639. classes: [slideConfig.closedClass],
  21640. styles: wrap$1(slideConfig.dimension.property, '0px')
  21641. });
  21642. };
  21643. var events$d = function (slideConfig, slideState) {
  21644. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  21645. var raw = simulatedEvent.event().raw();
  21646. if (raw.propertyName === slideConfig.dimension.property) {
  21647. disableTransitions(component, slideConfig);
  21648. if (slideState.isExpanded()) {
  21649. remove$6(component.element(), slideConfig.dimension.property);
  21650. }
  21651. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  21652. notify(component);
  21653. }
  21654. })]);
  21655. };
  21656. var ActiveSliding = /*#__PURE__*/Object.freeze({
  21657. __proto__: null,
  21658. exhibit: exhibit$6,
  21659. events: events$d
  21660. });
  21661. var SlidingSchema = [
  21662. strict$1('closedClass'),
  21663. strict$1('openClass'),
  21664. strict$1('shrinkingClass'),
  21665. strict$1('growingClass'),
  21666. option('getAnimationRoot'),
  21667. onHandler('onShrunk'),
  21668. onHandler('onStartShrink'),
  21669. onHandler('onGrown'),
  21670. onHandler('onStartGrow'),
  21671. defaulted$1('expanded', false),
  21672. strictOf('dimension', choose$1('property', {
  21673. width: [
  21674. output('property', 'width'),
  21675. output('getDimension', function (elem) {
  21676. return get$7(elem) + 'px';
  21677. })
  21678. ],
  21679. height: [
  21680. output('property', 'height'),
  21681. output('getDimension', function (elem) {
  21682. return get$6(elem) + 'px';
  21683. })
  21684. ]
  21685. }))
  21686. ];
  21687. var init$9 = function (spec) {
  21688. var state = Cell(spec.expanded);
  21689. var readState = function () {
  21690. return 'expanded: ' + state.get();
  21691. };
  21692. return nu$5({
  21693. isExpanded: function () {
  21694. return state.get() === true;
  21695. },
  21696. isCollapsed: function () {
  21697. return state.get() === false;
  21698. },
  21699. setCollapsed: curry(state.set, false),
  21700. setExpanded: curry(state.set, true),
  21701. readState: readState
  21702. });
  21703. };
  21704. var SlidingState = /*#__PURE__*/Object.freeze({
  21705. __proto__: null,
  21706. init: init$9
  21707. });
  21708. var Sliding = create$1({
  21709. fields: SlidingSchema,
  21710. name: 'sliding',
  21711. active: ActiveSliding,
  21712. apis: SlidingApis,
  21713. state: SlidingState
  21714. });
  21715. var schema$p = constant([
  21716. markers([
  21717. 'closedClass',
  21718. 'openClass',
  21719. 'shrinkingClass',
  21720. 'growingClass',
  21721. 'overflowToggledClass'
  21722. ]),
  21723. onHandler('onOpened'),
  21724. onHandler('onClosed')
  21725. ].concat(schema$m()));
  21726. var parts$b = constant([
  21727. required({
  21728. factory: Toolbar,
  21729. schema: schema$l(),
  21730. name: 'primary'
  21731. }),
  21732. required({
  21733. factory: Toolbar,
  21734. schema: schema$l(),
  21735. name: 'overflow',
  21736. overrides: function (detail) {
  21737. return {
  21738. toolbarBehaviours: derive$1([
  21739. Sliding.config({
  21740. dimension: { property: 'height' },
  21741. closedClass: detail.markers.closedClass,
  21742. openClass: detail.markers.openClass,
  21743. shrinkingClass: detail.markers.shrinkingClass,
  21744. growingClass: detail.markers.growingClass,
  21745. onShrunk: function (comp) {
  21746. getPart(comp, detail, 'overflow-button').each(function (button) {
  21747. Toggling.off(button);
  21748. Focusing.focus(button);
  21749. });
  21750. detail.onClosed(comp);
  21751. },
  21752. onGrown: function (comp) {
  21753. Keying.focusIn(comp);
  21754. detail.onOpened(comp);
  21755. },
  21756. onStartGrow: function (comp) {
  21757. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  21758. }
  21759. }),
  21760. Keying.config({
  21761. mode: 'acyclic',
  21762. onEscape: function (comp) {
  21763. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  21764. return Option.some(true);
  21765. }
  21766. })
  21767. ])
  21768. };
  21769. }
  21770. }),
  21771. external$1({
  21772. name: 'overflow-button',
  21773. overrides: function (detail) {
  21774. return {
  21775. buttonBehaviours: derive$1([Toggling.config({
  21776. toggleClass: detail.markers.overflowToggledClass,
  21777. aria: { mode: 'pressed' },
  21778. toggleOnExecute: false
  21779. })])
  21780. };
  21781. }
  21782. }),
  21783. external$1({ name: 'overflow-group' })
  21784. ]);
  21785. var toggleToolbar = function (toolbar, detail) {
  21786. getPart(toolbar, detail, 'overflow').each(function (overf) {
  21787. refresh$3(toolbar, detail);
  21788. Sliding.toggleGrow(overf);
  21789. });
  21790. };
  21791. var refresh$3 = function (toolbar, detail) {
  21792. getPart(toolbar, detail, 'overflow').each(function (overflow) {
  21793. refresh(toolbar, detail, function (groups) {
  21794. var builtGroups = map(groups, function (g) {
  21795. return premade$1(g);
  21796. });
  21797. Toolbar.setGroups(overflow, builtGroups);
  21798. });
  21799. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  21800. if (Sliding.hasGrown(overflow)) {
  21801. Toggling.on(button);
  21802. }
  21803. });
  21804. Sliding.refresh(overflow);
  21805. });
  21806. };
  21807. var factory$d = function (detail, components, spec, externals) {
  21808. var toolbarToggleEvent = 'alloy.toolbar.toggle';
  21809. var doSetGroups = function (toolbar, groups) {
  21810. var built = map(groups, toolbar.getSystem().build);
  21811. detail.builtGroups.set(built);
  21812. };
  21813. return {
  21814. uid: detail.uid,
  21815. dom: detail.dom,
  21816. components: components,
  21817. behaviours: augment(detail.splitToolbarBehaviours, [
  21818. Coupling.config({
  21819. others: {
  21820. overflowGroup: function (toolbar) {
  21821. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  21822. items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  21823. action: function (_button) {
  21824. emit(toolbar, toolbarToggleEvent);
  21825. }
  21826. }))]
  21827. }));
  21828. }
  21829. }
  21830. }),
  21831. config('toolbar-toggle-events', [run(toolbarToggleEvent, function (toolbar) {
  21832. getPart(toolbar, detail, 'overflow').each(function (overf) {
  21833. refresh$3(toolbar, detail);
  21834. Sliding.toggleGrow(overf);
  21835. });
  21836. })])
  21837. ]),
  21838. apis: {
  21839. setGroups: function (toolbar, groups) {
  21840. doSetGroups(toolbar, groups);
  21841. refresh$3(toolbar, detail);
  21842. },
  21843. refresh: function (toolbar) {
  21844. return refresh$3(toolbar, detail);
  21845. },
  21846. toggle: function (toolbar) {
  21847. return toggleToolbar(toolbar, detail);
  21848. }
  21849. },
  21850. domModification: { attributes: { role: 'group' } }
  21851. };
  21852. };
  21853. var SplitSlidingToolbar = composite$1({
  21854. name: 'SplitSlidingToolbar',
  21855. configFields: schema$p(),
  21856. partFields: parts$b(),
  21857. factory: factory$d,
  21858. apis: {
  21859. setGroups: function (apis, toolbar, groups) {
  21860. apis.setGroups(toolbar, groups);
  21861. },
  21862. refresh: function (apis, toolbar) {
  21863. apis.refresh(toolbar);
  21864. },
  21865. toggle: function (apis, toolbar) {
  21866. apis.toggle(toolbar);
  21867. }
  21868. }
  21869. });
  21870. var toolbarHeightChange = constant(generate$1('toolbar-height-change'));
  21871. var ReadOnlyChannel = 'silver.readonly';
  21872. var ReadOnlyDataSchema = objOf([strictBoolean('readonly')]);
  21873. var setDisabledAll = function (element, state) {
  21874. all('*', element.element()).forEach(function (elm) {
  21875. element.getSystem().getByDom(elm).each(function (comp) {
  21876. if (comp.hasConfigured(Disabling)) {
  21877. Disabling.set(comp, state);
  21878. }
  21879. });
  21880. });
  21881. };
  21882. var broadcastReadonly = function (uiComponents, readonly) {
  21883. var outerContainer = uiComponents.outerContainer;
  21884. var target = outerContainer.element();
  21885. if (readonly) {
  21886. uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  21887. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  21888. }
  21889. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  21890. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  21891. };
  21892. var toggleToReadOnly = function (uiComponents, readonly) {
  21893. var outerContainer = uiComponents.outerContainer;
  21894. broadcastReadonly(uiComponents, readonly);
  21895. all('*', outerContainer.element()).forEach(function (elm) {
  21896. outerContainer.getSystem().getByDom(elm).each(function (comp) {
  21897. if (comp.hasConfigured(Disabling)) {
  21898. Disabling.set(comp, readonly);
  21899. }
  21900. });
  21901. });
  21902. };
  21903. var setupReadonlyModeSwitch = function (editor, uiComponents) {
  21904. editor.on('init', function () {
  21905. if (editor.readonly) {
  21906. toggleToReadOnly(uiComponents, true);
  21907. }
  21908. });
  21909. editor.on('SwitchMode', function () {
  21910. return toggleToReadOnly(uiComponents, editor.readonly);
  21911. });
  21912. if (isReadOnly(editor)) {
  21913. editor.setMode('readonly');
  21914. }
  21915. };
  21916. var createReadonlyReceivingForOverflow = function (getOverflow) {
  21917. var _a;
  21918. return Receiving.config({
  21919. channels: (_a = {}, _a[ReadOnlyChannel] = {
  21920. schema: ReadOnlyDataSchema,
  21921. onReceive: function (comp, data) {
  21922. getOverflow(comp).each(function (toolbar) {
  21923. setDisabledAll(toolbar, data.readonly);
  21924. });
  21925. }
  21926. }, _a)
  21927. });
  21928. };
  21929. var renderToolbarGroupCommon = function (toolbarGroup) {
  21930. var attributes = toolbarGroup.title.fold(function () {
  21931. return {};
  21932. }, function (title) {
  21933. return { attributes: { title: title } };
  21934. });
  21935. return {
  21936. dom: __assign({
  21937. tag: 'div',
  21938. classes: ['tox-toolbar__group']
  21939. }, attributes),
  21940. components: [ToolbarGroup.parts().items({})],
  21941. items: toolbarGroup.items,
  21942. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), .tox-split-button:not([disabled]), .tox-toolbar-nav-js:not([disabled])' },
  21943. tgroupBehaviours: derive$1([
  21944. Tabstopping.config({}),
  21945. Focusing.config({})
  21946. ])
  21947. };
  21948. };
  21949. var renderToolbarGroup = function (toolbarGroup) {
  21950. return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  21951. };
  21952. var getToolbarbehaviours = function (toolbarSpec, modeName, getOverflow) {
  21953. var onAttached = runOnAttached(function (component) {
  21954. var groups = map(toolbarSpec.initGroups, renderToolbarGroup);
  21955. Toolbar.setGroups(component, groups);
  21956. });
  21957. return derive$1([
  21958. Keying.config({
  21959. mode: modeName,
  21960. onEscape: toolbarSpec.onEscape,
  21961. selector: '.tox-toolbar__group'
  21962. }),
  21963. config('toolbar-events', [onAttached]),
  21964. createReadonlyReceivingForOverflow(getOverflow)
  21965. ]);
  21966. };
  21967. var renderMoreToolbarCommon = function (toolbarSpec, getOverflow) {
  21968. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  21969. return {
  21970. uid: toolbarSpec.uid,
  21971. dom: {
  21972. tag: 'div',
  21973. classes: ['tox-toolbar-overlord']
  21974. },
  21975. parts: {
  21976. 'overflow-group': renderToolbarGroupCommon({
  21977. title: Option.none(),
  21978. items: []
  21979. }),
  21980. 'overflow-button': renderIconButtonSpec({
  21981. name: 'more',
  21982. icon: Option.some('more-drawer'),
  21983. disabled: false,
  21984. tooltip: Option.some('More...'),
  21985. primary: false,
  21986. borderless: false
  21987. }, Option.none(), toolbarSpec.backstage.shared.providers)
  21988. },
  21989. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName, getOverflow)
  21990. };
  21991. };
  21992. var renderFloatingMoreToolbar = function (toolbarSpec) {
  21993. var baseSpec = renderMoreToolbarCommon(toolbarSpec, SplitFloatingToolbar.getOverflow);
  21994. var overflowXOffset = 4;
  21995. var primary = SplitFloatingToolbar.parts().primary({
  21996. dom: {
  21997. tag: 'div',
  21998. classes: ['tox-toolbar__primary']
  21999. }
  22000. });
  22001. return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22002. lazySink: toolbarSpec.getSink,
  22003. getOverflowBounds: function () {
  22004. var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element();
  22005. var headerBounds = absolute$1(headerElem);
  22006. var docElem = documentElement(headerElem);
  22007. var docBounds = absolute$1(docElem);
  22008. return bounds$1(headerBounds.x() + overflowXOffset, docBounds.y(), headerBounds.width() - overflowXOffset * 2, docBounds.height());
  22009. },
  22010. parts: __assign(__assign({}, baseSpec.parts), {
  22011. overflow: {
  22012. dom: {
  22013. tag: 'div',
  22014. classes: ['tox-toolbar__overflow'],
  22015. attributes: toolbarSpec.attributes
  22016. }
  22017. }
  22018. }),
  22019. components: [primary],
  22020. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  22021. }));
  22022. };
  22023. var renderSlidingMoreToolbar = function (toolbarSpec) {
  22024. var primary = SplitSlidingToolbar.parts().primary({
  22025. dom: {
  22026. tag: 'div',
  22027. classes: ['tox-toolbar__primary']
  22028. }
  22029. });
  22030. var overflow = SplitSlidingToolbar.parts().overflow({
  22031. dom: {
  22032. tag: 'div',
  22033. classes: ['tox-toolbar__overflow']
  22034. }
  22035. });
  22036. var baseSpec = renderMoreToolbarCommon(toolbarSpec, Option.none);
  22037. return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22038. components: [
  22039. primary,
  22040. overflow
  22041. ],
  22042. markers: {
  22043. openClass: 'tox-toolbar__overflow--open',
  22044. closedClass: 'tox-toolbar__overflow--closed',
  22045. growingClass: 'tox-toolbar__overflow--growing',
  22046. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  22047. overflowToggledClass: 'tox-tbtn--enabled'
  22048. },
  22049. onOpened: function (comp) {
  22050. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  22051. },
  22052. onClosed: function (comp) {
  22053. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  22054. }
  22055. }));
  22056. };
  22057. var renderToolbar = function (toolbarSpec) {
  22058. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  22059. return Toolbar.sketch({
  22060. uid: toolbarSpec.uid,
  22061. dom: {
  22062. tag: 'div',
  22063. classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
  22064. },
  22065. components: [Toolbar.parts().groups({})],
  22066. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName, constant(Option.none()))
  22067. });
  22068. };
  22069. var baseToolbarButtonFields = [
  22070. defaultedBoolean('disabled', false),
  22071. optionString('tooltip'),
  22072. optionString('icon'),
  22073. optionString('text'),
  22074. defaultedFunction('onSetup', function () {
  22075. return noop;
  22076. })
  22077. ];
  22078. var toolbarButtonSchema = objOf([
  22079. strictString('type'),
  22080. strictFunction('onAction')
  22081. ].concat(baseToolbarButtonFields));
  22082. var createToolbarButton = function (spec) {
  22083. return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  22084. };
  22085. var baseMenuButtonFields = [
  22086. optionString('text'),
  22087. optionString('tooltip'),
  22088. optionString('icon'),
  22089. strictFunction('fetch'),
  22090. defaultedFunction('onSetup', function () {
  22091. return noop;
  22092. })
  22093. ];
  22094. var MenuButtonSchema = objOf(__spreadArrays([strictString('type')], baseMenuButtonFields));
  22095. var createMenuButton = function (spec) {
  22096. return asRaw('menubutton', MenuButtonSchema, spec);
  22097. };
  22098. var splitButtonSchema = objOf([
  22099. strictString('type'),
  22100. optionString('tooltip'),
  22101. optionString('icon'),
  22102. optionString('text'),
  22103. optionFunction('select'),
  22104. strictFunction('fetch'),
  22105. defaultedFunction('onSetup', function () {
  22106. return noop;
  22107. }),
  22108. defaultedStringEnum('presets', 'normal', [
  22109. 'normal',
  22110. 'color',
  22111. 'listpreview'
  22112. ]),
  22113. defaulted$1('columns', 1),
  22114. strictFunction('onAction'),
  22115. strictFunction('onItemAction')
  22116. ]);
  22117. var createSplitButton = function (spec) {
  22118. return asRaw('SplitButton', splitButtonSchema, spec);
  22119. };
  22120. var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  22121. var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  22122. strictString('type'),
  22123. strictFunction('onAction')
  22124. ]));
  22125. var createToggleButton = function (spec) {
  22126. return asRaw('ToggleButton', toggleButtonSchema, spec);
  22127. };
  22128. var groupToolbarButtonSchema = objOf([
  22129. strictString('type'),
  22130. strictOf('items', oneOf([
  22131. arrOfObj$1([
  22132. strictString('name'),
  22133. strictArrayOf('items', string)
  22134. ]),
  22135. string
  22136. ]))
  22137. ].concat(baseToolbarButtonFields));
  22138. var createGroupToolbarButton = function (spec) {
  22139. return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  22140. };
  22141. var contextBarFields = [
  22142. defaultedFunction('predicate', function () {
  22143. return false;
  22144. }),
  22145. defaultedStringEnum('scope', 'node', [
  22146. 'node',
  22147. 'editor'
  22148. ]),
  22149. defaultedStringEnum('position', 'selection', [
  22150. 'node',
  22151. 'selection',
  22152. 'line'
  22153. ])
  22154. ];
  22155. var contextButtonFields = baseToolbarButtonFields.concat([
  22156. defaulted$1('type', 'contextformbutton'),
  22157. defaulted$1('primary', false),
  22158. strictFunction('onAction'),
  22159. state$1('original', identity)
  22160. ]);
  22161. var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  22162. defaulted$1('type', 'contextformbutton'),
  22163. defaulted$1('primary', false),
  22164. strictFunction('onAction'),
  22165. state$1('original', identity)
  22166. ]);
  22167. var launchButtonFields = baseToolbarButtonFields.concat([defaulted$1('type', 'contextformbutton')]);
  22168. var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted$1('type', 'contextformtogglebutton')]);
  22169. var toggleOrNormal = choose$1('type', {
  22170. contextformbutton: contextButtonFields,
  22171. contextformtogglebutton: contextToggleButtonFields
  22172. });
  22173. var contextFormSchema = objOf([
  22174. defaulted$1('type', 'contextform'),
  22175. defaultedFunction('initValue', function () {
  22176. return '';
  22177. }),
  22178. optionString('label'),
  22179. strictArrayOf('commands', toggleOrNormal),
  22180. optionOf('launch', choose$1('type', {
  22181. contextformbutton: launchButtonFields,
  22182. contextformtogglebutton: launchToggleButtonFields
  22183. }))
  22184. ].concat(contextBarFields));
  22185. var contextToolbarSchema = objOf([
  22186. defaulted$1('type', 'contexttoolbar'),
  22187. strictString('items')
  22188. ].concat(contextBarFields));
  22189. var createContextToolbar = function (spec) {
  22190. return asRaw('ContextToolbar', contextToolbarSchema, spec);
  22191. };
  22192. var createContextForm = function (spec) {
  22193. return asRaw('ContextForm', contextFormSchema, spec);
  22194. };
  22195. var getState$2 = function (component, replaceConfig, reflectState) {
  22196. return reflectState;
  22197. };
  22198. var ReflectingApis = /*#__PURE__*/Object.freeze({
  22199. __proto__: null,
  22200. getState: getState$2
  22201. });
  22202. var events$e = function (reflectingConfig, reflectingState) {
  22203. var update = function (component, data) {
  22204. reflectingConfig.updateState.each(function (updateState) {
  22205. var newState = updateState(component, data);
  22206. reflectingState.set(newState);
  22207. });
  22208. reflectingConfig.renderComponents.each(function (renderComponents) {
  22209. var newComponents = renderComponents(data, reflectingState.get());
  22210. var newChildren = map(newComponents, component.getSystem().build);
  22211. replaceChildren(component, newChildren);
  22212. });
  22213. };
  22214. return derive([
  22215. run(receive(), function (component, message) {
  22216. var receivingData = message;
  22217. var channel = reflectingConfig.channel;
  22218. if (contains(receivingData.channels(), channel)) {
  22219. update(component, receivingData.data());
  22220. }
  22221. }),
  22222. runOnAttached(function (comp, se) {
  22223. reflectingConfig.initialData.each(function (rawData) {
  22224. update(comp, rawData);
  22225. });
  22226. })
  22227. ]);
  22228. };
  22229. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  22230. __proto__: null,
  22231. events: events$e
  22232. });
  22233. var init$a = function () {
  22234. var cell = Cell(Option.none());
  22235. var set = function (optS) {
  22236. return cell.set(optS);
  22237. };
  22238. var clear = function () {
  22239. return cell.set(Option.none());
  22240. };
  22241. var get = function () {
  22242. return cell.get();
  22243. };
  22244. var readState = function () {
  22245. return cell.get().fold(function () {
  22246. return 'none';
  22247. }, function (x) {
  22248. return x;
  22249. });
  22250. };
  22251. return {
  22252. readState: readState,
  22253. get: get,
  22254. set: set,
  22255. clear: clear
  22256. };
  22257. };
  22258. var ReflectingState = /*#__PURE__*/Object.freeze({
  22259. __proto__: null,
  22260. init: init$a
  22261. });
  22262. var ReflectingSchema = [
  22263. strict$1('channel'),
  22264. option('renderComponents'),
  22265. option('updateState'),
  22266. option('initialData')
  22267. ];
  22268. var Reflecting = create$1({
  22269. fields: ReflectingSchema,
  22270. name: 'reflecting',
  22271. active: ActiveReflecting,
  22272. apis: ReflectingApis,
  22273. state: ReflectingState
  22274. });
  22275. var schema$q = constant([
  22276. strict$1('toggleClass'),
  22277. strict$1('fetch'),
  22278. onStrictHandler('onExecute'),
  22279. defaulted$1('getHotspot', Option.some),
  22280. defaulted$1('getAnchorOverrides', constant({})),
  22281. schema$1(),
  22282. onStrictHandler('onItemExecute'),
  22283. option('lazySink'),
  22284. strict$1('dom'),
  22285. onHandler('onOpen'),
  22286. field$1('splitDropdownBehaviours', [
  22287. Coupling,
  22288. Keying,
  22289. Focusing
  22290. ]),
  22291. defaulted$1('matchWidth', false),
  22292. defaulted$1('useMinWidth', false),
  22293. defaulted$1('eventOrder', {}),
  22294. option('role')
  22295. ].concat(sandboxFields()));
  22296. var arrowPart = required({
  22297. factory: Button,
  22298. schema: [strict$1('dom')],
  22299. name: 'arrow',
  22300. defaults: function () {
  22301. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22302. },
  22303. overrides: function (detail) {
  22304. return {
  22305. dom: {
  22306. tag: 'span',
  22307. attributes: { role: 'presentation' }
  22308. },
  22309. action: function (arrow) {
  22310. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  22311. },
  22312. buttonBehaviours: derive$1([Toggling.config({
  22313. toggleOnExecute: false,
  22314. toggleClass: detail.toggleClass
  22315. })])
  22316. };
  22317. }
  22318. });
  22319. var buttonPart = required({
  22320. factory: Button,
  22321. schema: [strict$1('dom')],
  22322. name: 'button',
  22323. defaults: function () {
  22324. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22325. },
  22326. overrides: function (detail) {
  22327. return {
  22328. dom: {
  22329. tag: 'span',
  22330. attributes: { role: 'presentation' }
  22331. },
  22332. action: function (btn) {
  22333. btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22334. detail.onExecute(splitDropdown, btn);
  22335. });
  22336. }
  22337. };
  22338. }
  22339. });
  22340. var parts$c = constant([
  22341. arrowPart,
  22342. buttonPart,
  22343. optional({
  22344. factory: {
  22345. sketch: function (spec) {
  22346. return {
  22347. uid: spec.uid,
  22348. dom: {
  22349. tag: 'span',
  22350. styles: { display: 'none' },
  22351. attributes: { 'aria-hidden': 'true' },
  22352. innerHtml: spec.text
  22353. }
  22354. };
  22355. }
  22356. },
  22357. schema: [strict$1('text')],
  22358. name: 'aria-descriptor'
  22359. }),
  22360. external$1({
  22361. schema: [tieredMenuMarkers()],
  22362. name: 'menu',
  22363. defaults: function (detail) {
  22364. return {
  22365. onExecute: function (tmenu, item) {
  22366. tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22367. detail.onItemExecute(splitDropdown, tmenu, item);
  22368. });
  22369. }
  22370. };
  22371. }
  22372. }),
  22373. partType()
  22374. ]);
  22375. var factory$e = function (detail, components, spec, externals) {
  22376. var switchToMenu = function (sandbox) {
  22377. Composing.getCurrent(sandbox).each(function (current) {
  22378. Highlighting.highlightFirst(current);
  22379. Keying.focusIn(current);
  22380. });
  22381. };
  22382. var action = function (component) {
  22383. var onOpenSync = switchToMenu;
  22384. togglePopup(detail, function (x) {
  22385. return x;
  22386. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22387. };
  22388. var openMenu = function (comp) {
  22389. action(comp);
  22390. return Option.some(true);
  22391. };
  22392. var executeOnButton = function (comp) {
  22393. var button = getPartOrDie(comp, detail, 'button');
  22394. emitExecute(button);
  22395. return Option.some(true);
  22396. };
  22397. var buttonEvents = __assign(__assign({}, derive([runOnAttached(function (component, simulatedEvent) {
  22398. var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  22399. ariaDescriptor.each(function (descriptor) {
  22400. var descriptorId = generate$1('aria');
  22401. set$1(descriptor.element(), 'id', descriptorId);
  22402. set$1(component.element(), 'aria-describedby', descriptorId);
  22403. });
  22404. })])), events$7(Option.some(action)));
  22405. var apis = {
  22406. repositionMenus: function (comp) {
  22407. if (Toggling.isOn(comp)) {
  22408. repositionMenus(comp);
  22409. }
  22410. }
  22411. };
  22412. return {
  22413. uid: detail.uid,
  22414. dom: detail.dom,
  22415. components: components,
  22416. apis: apis,
  22417. eventOrder: __assign(__assign({}, detail.eventOrder), {
  22418. 'alloy.execute': [
  22419. 'disabling',
  22420. 'toggling',
  22421. 'alloy.base.behaviour'
  22422. ]
  22423. }),
  22424. events: buttonEvents,
  22425. behaviours: augment(detail.splitDropdownBehaviours, [
  22426. Coupling.config({
  22427. others: {
  22428. sandbox: function (hotspot) {
  22429. var arrow = getPartOrDie(hotspot, detail, 'arrow');
  22430. var extras = {
  22431. onOpen: function () {
  22432. Toggling.on(arrow);
  22433. Toggling.on(hotspot);
  22434. },
  22435. onClose: function () {
  22436. Toggling.off(arrow);
  22437. Toggling.off(hotspot);
  22438. }
  22439. };
  22440. return makeSandbox(detail, hotspot, extras);
  22441. }
  22442. }
  22443. }),
  22444. Keying.config({
  22445. mode: 'special',
  22446. onSpace: executeOnButton,
  22447. onEnter: executeOnButton,
  22448. onDown: openMenu
  22449. }),
  22450. Focusing.config({}),
  22451. Toggling.config({
  22452. toggleOnExecute: false,
  22453. aria: { mode: 'expanded' }
  22454. })
  22455. ]),
  22456. domModification: {
  22457. attributes: {
  22458. 'role': detail.role.getOr('button'),
  22459. 'aria-haspopup': true
  22460. }
  22461. }
  22462. };
  22463. };
  22464. var SplitDropdown = composite$1({
  22465. name: 'SplitDropdown',
  22466. configFields: schema$q(),
  22467. partFields: parts$c(),
  22468. factory: factory$e,
  22469. apis: {
  22470. repositionMenus: function (apis, comp) {
  22471. return apis.repositionMenus(comp);
  22472. }
  22473. }
  22474. });
  22475. var getButtonApi = function (component) {
  22476. return {
  22477. isDisabled: function () {
  22478. return Disabling.isDisabled(component);
  22479. },
  22480. setDisabled: function (state) {
  22481. return Disabling.set(component, state);
  22482. }
  22483. };
  22484. };
  22485. var getToggleApi = function (component) {
  22486. return {
  22487. setActive: function (state) {
  22488. Toggling.set(component, state);
  22489. },
  22490. isActive: function () {
  22491. return Toggling.isOn(component);
  22492. },
  22493. isDisabled: function () {
  22494. return Disabling.isDisabled(component);
  22495. },
  22496. setDisabled: function (state) {
  22497. return Disabling.set(component, state);
  22498. }
  22499. };
  22500. };
  22501. var getTooltipAttributes = function (tooltip, providersBackstage) {
  22502. return tooltip.map(function (tooltip) {
  22503. return {
  22504. 'aria-label': providersBackstage.translate(tooltip),
  22505. 'title': providersBackstage.translate(tooltip)
  22506. };
  22507. }).getOr({});
  22508. };
  22509. var focusButtonEvent = generate$1('focus-button');
  22510. var rtlIcon$1 = [
  22511. 'checklist',
  22512. 'ordered-list'
  22513. ];
  22514. var rtlTransform$1 = [
  22515. 'indent',
  22516. 'outdent',
  22517. 'table-insert-column-after',
  22518. 'table-insert-column-before',
  22519. 'unordered-list'
  22520. ];
  22521. var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  22522. var _a;
  22523. var getIconName = function (iconName) {
  22524. return global$7.isRtl() && contains(rtlIcon$1, iconName) ? iconName + '-rtl' : iconName;
  22525. };
  22526. var needsRtlClass = global$7.isRtl() && icon.exists(function (name) {
  22527. return contains(rtlTransform$1, name);
  22528. });
  22529. return {
  22530. dom: {
  22531. tag: 'button',
  22532. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []).concat(needsRtlClass ? ['tox-tbtn__icon-rtl'] : []),
  22533. attributes: getTooltipAttributes(tooltip, providersBackstage)
  22534. },
  22535. components: componentRenderPipeline([
  22536. icon.map(function (iconName) {
  22537. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22538. }),
  22539. text.map(function (text) {
  22540. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22541. })
  22542. ]),
  22543. eventOrder: (_a = {}, _a[mousedown()] = [
  22544. 'focusing',
  22545. 'alloy.base.behaviour',
  22546. 'common-button-display-events'
  22547. ], _a),
  22548. buttonBehaviours: derive$1([config('common-button-display-events', [run(mousedown(), function (button, se) {
  22549. se.event().prevent();
  22550. emit(button, focusButtonEvent);
  22551. })])].concat(receiver.map(function (r) {
  22552. return Reflecting.config({
  22553. channel: r,
  22554. initialData: {
  22555. icon: icon,
  22556. text: text
  22557. },
  22558. renderComponents: function (data, _state) {
  22559. return componentRenderPipeline([
  22560. data.icon.map(function (iconName) {
  22561. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22562. }),
  22563. data.text.map(function (text) {
  22564. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22565. })
  22566. ]);
  22567. }
  22568. });
  22569. }).toArray()).concat(behaviours.getOr([])))
  22570. };
  22571. };
  22572. var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
  22573. var sharedBackstage = backstage.shared;
  22574. return FloatingToolbarButton.sketch({
  22575. lazySink: sharedBackstage.getSink,
  22576. fetch: function () {
  22577. return Future.nu(function (resolve) {
  22578. resolve(map(identifyButtons(spec.items), renderToolbarGroup));
  22579. });
  22580. },
  22581. markers: { toggledClass: 'tox-tbtn--enabled' },
  22582. parts: {
  22583. button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Option.none(), Option.none(), sharedBackstage.providers),
  22584. toolbar: {
  22585. dom: {
  22586. tag: 'div',
  22587. classes: ['tox-toolbar__overflow'],
  22588. attributes: attributes
  22589. }
  22590. }
  22591. }
  22592. });
  22593. };
  22594. var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  22595. var editorOffCell = Cell(noop);
  22596. var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Option.none(), Option.none(), providersBackstage);
  22597. return Button.sketch({
  22598. dom: structure.dom,
  22599. components: structure.components,
  22600. eventOrder: toolbarButtonEventOrder,
  22601. buttonBehaviours: derive$1([
  22602. config('toolbar-button-events', [
  22603. onToolbarButtonExecute({
  22604. onAction: spec.onAction,
  22605. getApi: specialisation.getApi
  22606. }),
  22607. onControlAttached(specialisation, editorOffCell),
  22608. onControlDetached(specialisation, editorOffCell)
  22609. ]),
  22610. DisablingConfigs.toolbarButton(spec.disabled)
  22611. ].concat(specialisation.toolbarButtonBehaviours))
  22612. });
  22613. };
  22614. var renderToolbarButton = function (spec, providersBackstage) {
  22615. return renderToolbarButtonWith(spec, providersBackstage, []);
  22616. };
  22617. var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  22618. return renderCommonToolbarButton(spec, {
  22619. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  22620. getApi: getButtonApi,
  22621. onSetup: spec.onSetup
  22622. }, providersBackstage);
  22623. };
  22624. var renderToolbarToggleButton = function (spec, providersBackstage) {
  22625. return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  22626. };
  22627. var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  22628. return deepMerge(renderCommonToolbarButton(spec, {
  22629. toolbarButtonBehaviours: [
  22630. Replacing.config({}),
  22631. Toggling.config({
  22632. toggleClass: 'tox-tbtn--enabled',
  22633. aria: { mode: 'pressed' },
  22634. toggleOnExecute: false
  22635. })
  22636. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  22637. getApi: getToggleApi,
  22638. onSetup: spec.onSetup
  22639. }, providersBackstage));
  22640. };
  22641. var fetchChoices = function (getApi, spec, providersBackstage) {
  22642. return function (comp) {
  22643. return Future.nu(function (callback) {
  22644. return spec.fetch(callback);
  22645. }).map(function (items) {
  22646. return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  22647. spec.onItemAction(getApi(comp), value);
  22648. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(function () {
  22649. return false;
  22650. }), providersBackstage), {
  22651. movement: deriveMenuMovement(spec.columns, spec.presets),
  22652. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, se) {
  22653. detectSize(comp, 4, classForPreset(spec.presets)).each(function (_a) {
  22654. var numRows = _a.numRows, numColumns = _a.numColumns;
  22655. Keying.setGridSize(comp, numRows, numColumns);
  22656. });
  22657. })])
  22658. })));
  22659. });
  22660. };
  22661. };
  22662. var renderSplitButton = function (spec, sharedBackstage) {
  22663. var _a;
  22664. var displayChannel = generate$1('channel-update-split-dropdown-display');
  22665. var getApi = function (comp) {
  22666. return {
  22667. isDisabled: function () {
  22668. return Disabling.isDisabled(comp);
  22669. },
  22670. setDisabled: function (state) {
  22671. return Disabling.set(comp, state);
  22672. },
  22673. setIconFill: function (id, value) {
  22674. descendant$1(comp.element(), 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  22675. set$1(underlinePath, 'fill', value);
  22676. });
  22677. },
  22678. setIconStroke: function (id, value) {
  22679. descendant$1(comp.element(), 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  22680. set$1(underlinePath, 'stroke', value);
  22681. });
  22682. },
  22683. setActive: function (state) {
  22684. set$1(comp.element(), 'aria-pressed', state);
  22685. descendant$1(comp.element(), 'span').each(function (button) {
  22686. comp.getSystem().getByDom(button).each(function (buttonComp) {
  22687. return Toggling.set(buttonComp, state);
  22688. });
  22689. });
  22690. },
  22691. isActive: function () {
  22692. return descendant$1(comp.element(), 'span').exists(function (button) {
  22693. return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  22694. });
  22695. }
  22696. };
  22697. };
  22698. var editorOffCell = Cell(noop);
  22699. var specialisation = {
  22700. getApi: getApi,
  22701. onSetup: spec.onSetup
  22702. };
  22703. return SplitDropdown.sketch({
  22704. dom: {
  22705. tag: 'div',
  22706. classes: ['tox-split-button'],
  22707. attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  22708. },
  22709. onExecute: function (button) {
  22710. spec.onAction(getApi(button));
  22711. },
  22712. onItemExecute: function (a, b, c) {
  22713. },
  22714. splitDropdownBehaviours: derive$1([
  22715. DisablingConfigs.splitButton(false),
  22716. config('split-dropdown-events', [
  22717. run(focusButtonEvent, Focusing.focus),
  22718. onControlAttached(specialisation, editorOffCell),
  22719. onControlDetached(specialisation, editorOffCell)
  22720. ]),
  22721. Unselecting.config({})
  22722. ]),
  22723. eventOrder: (_a = {}, _a[attachedToDom()] = [
  22724. 'alloy.base.behaviour',
  22725. 'split-dropdown-events'
  22726. ], _a),
  22727. toggleClass: 'tox-tbtn--enabled',
  22728. lazySink: sharedBackstage.getSink,
  22729. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  22730. parts: { menu: part(false, spec.columns, spec.presets) },
  22731. components: [
  22732. SplitDropdown.parts().button(renderCommonStructure(spec.icon, spec.text, Option.none(), Option.some(displayChannel), Option.some([Toggling.config({
  22733. toggleClass: 'tox-tbtn--enabled',
  22734. toggleOnExecute: false
  22735. })]), sharedBackstage.providers)),
  22736. SplitDropdown.parts().arrow({
  22737. dom: {
  22738. tag: 'button',
  22739. classes: [
  22740. 'tox-tbtn',
  22741. 'tox-split-button__chevron'
  22742. ],
  22743. innerHtml: get$d('chevron-down', sharedBackstage.providers.icons)
  22744. }
  22745. }),
  22746. SplitDropdown.parts()['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  22747. ]
  22748. });
  22749. };
  22750. var getFormApi = function (input) {
  22751. return {
  22752. hide: function () {
  22753. return emit(input, sandboxClose());
  22754. },
  22755. getValue: function () {
  22756. return Representing.getValue(input);
  22757. }
  22758. };
  22759. };
  22760. var runOnExecute$1 = function (memInput, original) {
  22761. return run(internalToolbarButtonExecute, function (comp, se) {
  22762. var input = memInput.get(comp);
  22763. var formApi = getFormApi(input);
  22764. original.onAction(formApi, se.event().buttonApi());
  22765. });
  22766. };
  22767. var renderContextButton = function (memInput, button, extras) {
  22768. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  22769. var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  22770. type: 'button',
  22771. onAction: function () {
  22772. }
  22773. })));
  22774. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  22775. };
  22776. var renderContextToggleButton = function (memInput, button, extras) {
  22777. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  22778. var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  22779. type: 'togglebutton',
  22780. onAction: function () {
  22781. }
  22782. })));
  22783. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  22784. };
  22785. var generateOne$1 = function (memInput, button, providersBackstage) {
  22786. var extras = { backstage: { shared: { providers: providersBackstage } } };
  22787. if (button.type === 'contextformtogglebutton') {
  22788. return renderContextToggleButton(memInput, button, extras);
  22789. } else {
  22790. return renderContextButton(memInput, button, extras);
  22791. }
  22792. };
  22793. var generate$7 = function (memInput, buttons, providersBackstage) {
  22794. var mementos = map(buttons, function (button) {
  22795. return record(generateOne$1(memInput, button, providersBackstage));
  22796. });
  22797. var asSpecs = function () {
  22798. return map(mementos, function (mem) {
  22799. return mem.asSpec();
  22800. });
  22801. };
  22802. var findPrimary = function (compInSystem) {
  22803. return findMap(buttons, function (button, i) {
  22804. if (button.primary) {
  22805. return Option.from(mementos[i]).bind(function (mem) {
  22806. return mem.getOpt(compInSystem);
  22807. }).filter(not(Disabling.isDisabled));
  22808. } else {
  22809. return Option.none();
  22810. }
  22811. });
  22812. };
  22813. return {
  22814. asSpecs: asSpecs,
  22815. findPrimary: findPrimary
  22816. };
  22817. };
  22818. var renderContextForm = function (toolbarType, ctx, backstage) {
  22819. var inputAttributes = ctx.label.fold(function () {
  22820. return {};
  22821. }, function (label) {
  22822. return { 'aria-label': label };
  22823. });
  22824. var memInput = record(Input.sketch({
  22825. inputClasses: [
  22826. 'tox-toolbar-textfield',
  22827. 'tox-toolbar-nav-js'
  22828. ],
  22829. data: ctx.initValue(),
  22830. inputAttributes: inputAttributes,
  22831. selectOnFocus: true,
  22832. inputBehaviours: derive$1([Keying.config({
  22833. mode: 'special',
  22834. onEnter: function (input) {
  22835. return commands.findPrimary(input).map(function (primary) {
  22836. emitExecute(primary);
  22837. return true;
  22838. });
  22839. },
  22840. onLeft: function (comp, se) {
  22841. se.cut();
  22842. return Option.none();
  22843. },
  22844. onRight: function (comp, se) {
  22845. se.cut();
  22846. return Option.none();
  22847. }
  22848. })])
  22849. }));
  22850. var commands = generate$7(memInput, ctx.commands, backstage.shared.providers);
  22851. return renderToolbar({
  22852. type: toolbarType,
  22853. uid: generate$1('context-toolbar'),
  22854. initGroups: [
  22855. {
  22856. title: Option.none(),
  22857. items: [memInput.asSpec()]
  22858. },
  22859. {
  22860. title: Option.none(),
  22861. items: commands.asSpecs()
  22862. }
  22863. ],
  22864. onEscape: Option.none,
  22865. cyclicKeying: true
  22866. });
  22867. };
  22868. var ContextForm = { renderContextForm: renderContextForm };
  22869. var getHorizontalBounds = function (contentAreaBox, viewportBounds) {
  22870. var x = Math.max(viewportBounds.x(), contentAreaBox.x());
  22871. var contentBoxWidth = contentAreaBox.right() - x;
  22872. var maxViewportWidth = viewportBounds.width() - (x - viewportBounds.x());
  22873. var width = Math.min(contentBoxWidth, maxViewportWidth);
  22874. return {
  22875. x: x,
  22876. width: width
  22877. };
  22878. };
  22879. var getVerticalBounds = function (editor, contentAreaBox, viewportBounds) {
  22880. var container = Element.fromDom(editor.getContainer());
  22881. var header = descendant$1(container, '.tox-editor-header').getOr(container);
  22882. var headerBox = box(header);
  22883. var isToolbarBelowContentArea = headerBox.y() >= contentAreaBox.bottom();
  22884. var isToolbarLocationTop$1 = isToolbarLocationTop(editor);
  22885. var isToolbarAbove = isToolbarLocationTop$1 && !isToolbarBelowContentArea;
  22886. if (editor.inline && isToolbarAbove) {
  22887. return {
  22888. y: Math.max(headerBox.bottom(), viewportBounds.y()),
  22889. bottom: viewportBounds.bottom()
  22890. };
  22891. }
  22892. if (editor.inline && !isToolbarAbove) {
  22893. return {
  22894. y: viewportBounds.y(),
  22895. bottom: Math.min(headerBox.y(), viewportBounds.bottom())
  22896. };
  22897. }
  22898. var containerBounds = box(container);
  22899. if (isToolbarAbove) {
  22900. return {
  22901. y: Math.max(headerBox.bottom(), viewportBounds.y()),
  22902. bottom: Math.min(containerBounds.bottom(), viewportBounds.bottom())
  22903. };
  22904. }
  22905. return {
  22906. y: Math.max(containerBounds.y(), viewportBounds.y()),
  22907. bottom: Math.min(headerBox.y(), viewportBounds.bottom())
  22908. };
  22909. };
  22910. var getContextToolbarBounds = function (editor) {
  22911. var viewportBounds = getBounds(domGlobals.window);
  22912. var contentAreaBox = box(Element.fromDom(editor.getContentAreaContainer()));
  22913. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  22914. var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
  22915. if (editor.inline && !toolbarOrMenubarEnabled) {
  22916. return bounds$1(x, viewportBounds.y(), width, viewportBounds.height());
  22917. } else {
  22918. var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds), y = _b.y, bottom = _b.bottom;
  22919. return bounds$1(x, y, width, bottom - y);
  22920. }
  22921. };
  22922. var matchTargetWith = function (elem, toolbars) {
  22923. return findMap(toolbars, function (toolbarApi) {
  22924. return toolbarApi.predicate(elem.dom()) ? Option.some({
  22925. toolbarApi: toolbarApi,
  22926. elem: elem
  22927. }) : Option.none();
  22928. });
  22929. };
  22930. var lookup$1 = function (scopes, editor) {
  22931. var rootElem = Element.fromDom(editor.getBody());
  22932. var isRoot = function (elem) {
  22933. return eq(elem, rootElem);
  22934. };
  22935. var startNode = Element.fromDom(editor.selection.getNode());
  22936. if (contains$2(startNode, rootElem)) {
  22937. return Option.none();
  22938. }
  22939. return matchTargetWith(startNode, scopes.inNodeScope).orThunk(function () {
  22940. return matchTargetWith(startNode, scopes.inEditorScope).orThunk(function () {
  22941. return ancestor(startNode, function (elem) {
  22942. return isRoot(elem) ? Option.none() : matchTargetWith(elem, scopes.inNodeScope);
  22943. }, isRoot);
  22944. });
  22945. });
  22946. };
  22947. var ToolbarLookup = { lookup: lookup$1 };
  22948. var categorise = function (contextToolbars, navigate) {
  22949. var forms = {};
  22950. var inNodeScope = [];
  22951. var inEditorScope = [];
  22952. var formNavigators = {};
  22953. var lookupTable = {};
  22954. var registerForm = function (key, toolbarApi) {
  22955. var contextForm = getOrDie(createContextForm(toolbarApi));
  22956. forms[key] = contextForm;
  22957. contextForm.launch.map(function (launch) {
  22958. formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarApi.launch), {
  22959. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  22960. onAction: function () {
  22961. navigate(contextForm);
  22962. }
  22963. });
  22964. });
  22965. if (contextForm.scope === 'editor') {
  22966. inEditorScope.push(contextForm);
  22967. } else {
  22968. inNodeScope.push(contextForm);
  22969. }
  22970. lookupTable[key] = contextForm;
  22971. };
  22972. var registerToolbar = function (key, toolbarApi) {
  22973. createContextToolbar(toolbarApi).each(function (contextToolbar) {
  22974. if (toolbarApi.scope === 'editor') {
  22975. inEditorScope.push(contextToolbar);
  22976. } else {
  22977. inNodeScope.push(contextToolbar);
  22978. }
  22979. lookupTable[key] = contextToolbar;
  22980. });
  22981. };
  22982. var keys$1 = keys(contextToolbars);
  22983. each(keys$1, function (key) {
  22984. var toolbarApi = contextToolbars[key];
  22985. if (toolbarApi.type === 'contextform') {
  22986. registerForm(key, toolbarApi);
  22987. } else if (toolbarApi.type === 'contexttoolbar') {
  22988. registerToolbar(key, toolbarApi);
  22989. }
  22990. });
  22991. return {
  22992. forms: forms,
  22993. inNodeScope: inNodeScope,
  22994. inEditorScope: inEditorScope,
  22995. lookupTable: lookupTable,
  22996. formNavigators: formNavigators
  22997. };
  22998. };
  22999. var ToolbarScopes = { categorise: categorise };
  23000. var forwardSlideEvent = generate$1('forward-slide');
  23001. var backSlideEvent = generate$1('backward-slide');
  23002. var changeSlideEvent = generate$1('change-slide-event');
  23003. var resizingClass = 'tox-pop--resizing';
  23004. var renderContextToolbar = function (spec) {
  23005. var stack = Cell([]);
  23006. return InlineView.sketch({
  23007. dom: {
  23008. tag: 'div',
  23009. classes: ['tox-pop']
  23010. },
  23011. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  23012. onShow: function (comp) {
  23013. stack.set([]);
  23014. InlineView.getContent(comp).each(function (c) {
  23015. remove$6(c.element(), 'visibility');
  23016. });
  23017. remove$4(comp.element(), resizingClass);
  23018. remove$6(comp.element(), 'width');
  23019. },
  23020. inlineBehaviours: derive$1([
  23021. config('context-toolbar-events', [
  23022. runOnSource(transitionend(), function (comp, se) {
  23023. InlineView.getContent(comp).each(function (c) {
  23024. });
  23025. remove$4(comp.element(), resizingClass);
  23026. remove$6(comp.element(), 'width');
  23027. }),
  23028. run(changeSlideEvent, function (comp, se) {
  23029. remove$6(comp.element(), 'width');
  23030. var currentWidth = get$7(comp.element());
  23031. InlineView.setContent(comp, se.event().contents());
  23032. add$2(comp.element(), resizingClass);
  23033. var newWidth = get$7(comp.element());
  23034. set$2(comp.element(), 'width', currentWidth + 'px');
  23035. InlineView.getContent(comp).each(function (newContents) {
  23036. se.event().focus().bind(function (f) {
  23037. focus$1(f);
  23038. return search(comp.element());
  23039. }).orThunk(function () {
  23040. Keying.focusIn(newContents);
  23041. return active();
  23042. });
  23043. });
  23044. global$2.setTimeout(function () {
  23045. set$2(comp.element(), 'width', newWidth + 'px');
  23046. }, 0);
  23047. }),
  23048. run(forwardSlideEvent, function (comp, se) {
  23049. InlineView.getContent(comp).each(function (oldContents) {
  23050. stack.set(stack.get().concat([{
  23051. bar: oldContents,
  23052. focus: active()
  23053. }]));
  23054. });
  23055. emitWith(comp, changeSlideEvent, {
  23056. contents: se.event().forwardContents(),
  23057. focus: Option.none()
  23058. });
  23059. }),
  23060. run(backSlideEvent, function (comp, se) {
  23061. last(stack.get()).each(function (last) {
  23062. stack.set(stack.get().slice(0, stack.get().length - 1));
  23063. emitWith(comp, changeSlideEvent, {
  23064. contents: premade$1(last.bar),
  23065. focus: last.focus
  23066. });
  23067. });
  23068. })
  23069. ]),
  23070. Keying.config({
  23071. mode: 'special',
  23072. onEscape: function (comp) {
  23073. return last(stack.get()).fold(function () {
  23074. return spec.onEscape();
  23075. }, function (_) {
  23076. emit(comp, backSlideEvent);
  23077. return Option.some(true);
  23078. });
  23079. }
  23080. })
  23081. ]),
  23082. lazySink: function () {
  23083. return Result.value(spec.sink);
  23084. }
  23085. });
  23086. };
  23087. var onSetupFormatToggle = function (editor, name) {
  23088. return function (api) {
  23089. var unbindCell = Cell(Option.none());
  23090. var init = function () {
  23091. api.setActive(editor.formatter.match(name));
  23092. var unbind = editor.formatter.formatChanged(name, api.setActive).unbind;
  23093. unbindCell.set(Option.some(unbind));
  23094. };
  23095. editor.initialized ? init() : editor.on('init', init);
  23096. return function () {
  23097. return unbindCell.get().each(function (unbind) {
  23098. return unbind();
  23099. });
  23100. };
  23101. };
  23102. };
  23103. var onActionToggleFormat = function (editor) {
  23104. return function (rawItem) {
  23105. return function () {
  23106. editor.undoManager.transact(function () {
  23107. editor.focus();
  23108. editor.execCommand('mceToggleFormat', false, rawItem.format);
  23109. });
  23110. };
  23111. };
  23112. };
  23113. var generateSelectItems = function (_editor, backstage, spec) {
  23114. var generateItem = function (rawItem, response, disabled, value) {
  23115. var translatedText = backstage.shared.providers.translate(rawItem.title);
  23116. if (rawItem.type === 'separator') {
  23117. return Option.some({
  23118. type: 'separator',
  23119. text: translatedText
  23120. });
  23121. } else if (rawItem.type === 'submenu') {
  23122. var items = bind(rawItem.getStyleItems(), function (si) {
  23123. return validate(si, response, value);
  23124. });
  23125. if (response === 0 && items.length <= 0) {
  23126. return Option.none();
  23127. } else {
  23128. return Option.some({
  23129. type: 'nestedmenuitem',
  23130. text: translatedText,
  23131. disabled: items.length <= 0,
  23132. getSubmenuItems: function () {
  23133. return bind(rawItem.getStyleItems(), function (si) {
  23134. return validate(si, response, value);
  23135. });
  23136. }
  23137. });
  23138. }
  23139. } else {
  23140. return Option.some(__assign({
  23141. type: 'togglemenuitem',
  23142. text: translatedText,
  23143. active: rawItem.isSelected(value),
  23144. disabled: disabled,
  23145. onAction: spec.onAction(rawItem)
  23146. }, rawItem.getStylePreview().fold(function () {
  23147. return {};
  23148. }, function (preview) {
  23149. return { meta: { style: preview } };
  23150. })));
  23151. }
  23152. };
  23153. var validate = function (item, response, value) {
  23154. var invalid = item.type === 'formatter' && spec.isInvalid(item);
  23155. if (response === 0) {
  23156. return invalid ? [] : generateItem(item, response, false, value).toArray();
  23157. } else {
  23158. return generateItem(item, response, invalid, value).toArray();
  23159. }
  23160. };
  23161. var validateItems = function (preItems) {
  23162. var value = spec.getCurrentValue();
  23163. var response = spec.shouldHide ? 0 : 1;
  23164. return bind(preItems, function (item) {
  23165. return validate(item, response, value);
  23166. });
  23167. };
  23168. var getFetch = function (backstage, getStyleItems) {
  23169. return function (callback) {
  23170. var preItems = getStyleItems();
  23171. var items = validateItems(preItems);
  23172. var menu = build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  23173. callback(menu);
  23174. };
  23175. };
  23176. return {
  23177. validateItems: validateItems,
  23178. getFetch: getFetch
  23179. };
  23180. };
  23181. var createMenuItems = function (editor, backstage, spec) {
  23182. var dataset = spec.dataset;
  23183. var getStyleItems = dataset.type === 'basic' ? function () {
  23184. return map(dataset.data, function (d) {
  23185. return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  23186. });
  23187. } : dataset.getData;
  23188. return {
  23189. items: generateSelectItems(editor, backstage, spec),
  23190. getStyleItems: getStyleItems
  23191. };
  23192. };
  23193. var createSelectButton = function (editor, backstage, spec) {
  23194. var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  23195. var getApi = function (comp) {
  23196. return {
  23197. getComponent: function () {
  23198. return comp;
  23199. }
  23200. };
  23201. };
  23202. var onSetup = function (api) {
  23203. spec.setInitialValue.each(function (f) {
  23204. return f(api.getComponent());
  23205. });
  23206. return spec.nodeChangeHandler.map(function (f) {
  23207. var handler = f(api.getComponent());
  23208. editor.on('NodeChange', handler);
  23209. return function () {
  23210. editor.off('NodeChange', handler);
  23211. };
  23212. }).getOr(noop);
  23213. };
  23214. return renderCommonDropdown({
  23215. text: spec.icon.isSome() ? Option.none() : Option.some(''),
  23216. icon: spec.icon,
  23217. tooltip: Option.from(spec.tooltip),
  23218. role: Option.none(),
  23219. fetch: items.getFetch(backstage, getStyleItems),
  23220. onSetup: onSetup,
  23221. getApi: getApi,
  23222. columns: 1,
  23223. presets: 'normal',
  23224. classes: spec.icon.isSome() ? [] : ['bespoke'],
  23225. dropdownBehaviours: []
  23226. }, 'tox-tbtn', backstage.shared);
  23227. };
  23228. var process = function (rawFormats) {
  23229. return map(rawFormats, function (item) {
  23230. var title = item, format = item;
  23231. var values = item.split('=');
  23232. if (values.length > 1) {
  23233. title = values[0];
  23234. format = values[1];
  23235. }
  23236. return {
  23237. title: title,
  23238. format: format
  23239. };
  23240. });
  23241. };
  23242. var buildBasicStaticDataset = function (data) {
  23243. return {
  23244. type: 'basic',
  23245. data: data
  23246. };
  23247. };
  23248. var Delimiter;
  23249. (function (Delimiter) {
  23250. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  23251. Delimiter[Delimiter['Space'] = 1] = 'Space';
  23252. }(Delimiter || (Delimiter = {})));
  23253. var split = function (rawFormats, delimiter) {
  23254. if (delimiter === Delimiter.SemiColon) {
  23255. return rawFormats.replace(/;$/, '').split(';');
  23256. } else {
  23257. return rawFormats.split(' ');
  23258. }
  23259. };
  23260. var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  23261. var rawFormats = get(editor.settings, settingName).getOr(defaults);
  23262. var data = process(split(rawFormats, delimiter));
  23263. return {
  23264. type: 'basic',
  23265. data: data
  23266. };
  23267. };
  23268. var alignMenuItems = [
  23269. {
  23270. title: 'Left',
  23271. icon: 'align-left',
  23272. format: 'alignleft'
  23273. },
  23274. {
  23275. title: 'Center',
  23276. icon: 'align-center',
  23277. format: 'aligncenter'
  23278. },
  23279. {
  23280. title: 'Right',
  23281. icon: 'align-right',
  23282. format: 'alignright'
  23283. },
  23284. {
  23285. title: 'Justify',
  23286. icon: 'align-justify',
  23287. format: 'alignjustify'
  23288. }
  23289. ];
  23290. var getSpec = function (editor) {
  23291. var getMatchingValue = function () {
  23292. return find(alignMenuItems, function (item) {
  23293. return editor.formatter.match(item.format);
  23294. });
  23295. };
  23296. var isSelectedFor = function (format) {
  23297. return function () {
  23298. return editor.formatter.match(format);
  23299. };
  23300. };
  23301. var getPreviewFor = function (_format) {
  23302. return function () {
  23303. return Option.none();
  23304. };
  23305. };
  23306. var updateSelectMenuIcon = function (comp) {
  23307. var match = getMatchingValue();
  23308. var alignment = match.fold(function () {
  23309. return 'left';
  23310. }, function (item) {
  23311. return item.title.toLowerCase();
  23312. });
  23313. emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  23314. };
  23315. var nodeChangeHandler = Option.some(function (comp) {
  23316. return function () {
  23317. return updateSelectMenuIcon(comp);
  23318. };
  23319. });
  23320. var setInitialValue = Option.some(function (comp) {
  23321. return updateSelectMenuIcon(comp);
  23322. });
  23323. var dataset = buildBasicStaticDataset(alignMenuItems);
  23324. return {
  23325. tooltip: 'Align',
  23326. icon: Option.some('align-left'),
  23327. isSelectedFor: isSelectedFor,
  23328. getCurrentValue: constant(Option.none()),
  23329. getPreviewFor: getPreviewFor,
  23330. onAction: onActionToggleFormat(editor),
  23331. setInitialValue: setInitialValue,
  23332. nodeChangeHandler: nodeChangeHandler,
  23333. dataset: dataset,
  23334. shouldHide: false,
  23335. isInvalid: function (item) {
  23336. return !editor.formatter.canApply(item.format);
  23337. }
  23338. };
  23339. };
  23340. var createAlignSelect = function (editor, backstage) {
  23341. return createSelectButton(editor, backstage, getSpec(editor));
  23342. };
  23343. var alignSelectMenu = function (editor, backstage) {
  23344. var menuItems = createMenuItems(editor, backstage, getSpec(editor));
  23345. editor.ui.registry.addNestedMenuItem('align', {
  23346. text: backstage.shared.providers.translate('Align'),
  23347. getSubmenuItems: function () {
  23348. return menuItems.items.validateItems(menuItems.getStyleItems());
  23349. }
  23350. });
  23351. };
  23352. 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';
  23353. var systemStackFonts = [
  23354. '-apple-system',
  23355. 'Segoe UI',
  23356. 'Roboto',
  23357. 'Helvetica Neue',
  23358. 'sans-serif'
  23359. ];
  23360. var splitFonts = function (fontFamily) {
  23361. var fonts = fontFamily.split(/\s*,\s*/);
  23362. return map(fonts, function (font) {
  23363. return font.replace(/^['"]+|['"]+$/g, '');
  23364. });
  23365. };
  23366. var isSystemFontStack = function (fontFamily) {
  23367. var matchesSystemStack = function () {
  23368. var fonts = splitFonts(fontFamily.toLowerCase());
  23369. return forall(systemStackFonts, function (font) {
  23370. return fonts.indexOf(font.toLowerCase()) > -1;
  23371. });
  23372. };
  23373. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  23374. };
  23375. var getSpec$1 = function (editor) {
  23376. var getMatchingValue = function () {
  23377. var getFirstFont = function (fontFamily) {
  23378. return fontFamily ? splitFonts(fontFamily)[0] : '';
  23379. };
  23380. var fontFamily = editor.queryCommandValue('FontName');
  23381. var items = dataset.data;
  23382. var font = fontFamily ? fontFamily.toLowerCase() : '';
  23383. var matchOpt = find(items, function (item) {
  23384. var format = item.format;
  23385. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  23386. }).orThunk(function () {
  23387. if (isSystemFontStack(font)) {
  23388. return Option.from({
  23389. title: 'System Font',
  23390. format: font
  23391. });
  23392. } else {
  23393. return Option.none();
  23394. }
  23395. });
  23396. return {
  23397. matchOpt: matchOpt,
  23398. font: fontFamily
  23399. };
  23400. };
  23401. var isSelectedFor = function (item) {
  23402. return function (valueOpt) {
  23403. return valueOpt.exists(function (value) {
  23404. return value.format === item;
  23405. });
  23406. };
  23407. };
  23408. var getCurrentValue = function () {
  23409. var matchOpt = getMatchingValue().matchOpt;
  23410. return matchOpt;
  23411. };
  23412. var getPreviewFor = function (item) {
  23413. return function () {
  23414. return Option.some({
  23415. tag: 'div',
  23416. styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  23417. });
  23418. };
  23419. };
  23420. var onAction = function (rawItem) {
  23421. return function () {
  23422. editor.undoManager.transact(function () {
  23423. editor.focus();
  23424. editor.execCommand('FontName', false, rawItem.format);
  23425. });
  23426. };
  23427. };
  23428. var updateSelectMenuText = function (comp) {
  23429. var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  23430. var text = matchOpt.fold(function () {
  23431. return font;
  23432. }, function (item) {
  23433. return item.title;
  23434. });
  23435. emitWith(comp, updateMenuText, { text: text });
  23436. };
  23437. var nodeChangeHandler = Option.some(function (comp) {
  23438. return function () {
  23439. return updateSelectMenuText(comp);
  23440. };
  23441. });
  23442. var setInitialValue = Option.some(function (comp) {
  23443. return updateSelectMenuText(comp);
  23444. });
  23445. var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  23446. return {
  23447. tooltip: 'Fonts',
  23448. icon: Option.none(),
  23449. isSelectedFor: isSelectedFor,
  23450. getCurrentValue: getCurrentValue,
  23451. getPreviewFor: getPreviewFor,
  23452. onAction: onAction,
  23453. setInitialValue: setInitialValue,
  23454. nodeChangeHandler: nodeChangeHandler,
  23455. dataset: dataset,
  23456. shouldHide: false,
  23457. isInvalid: function () {
  23458. return false;
  23459. }
  23460. };
  23461. };
  23462. var createFontSelect = function (editor, backstage) {
  23463. return createSelectButton(editor, backstage, getSpec$1(editor));
  23464. };
  23465. var fontSelectMenu = function (editor, backstage) {
  23466. var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  23467. editor.ui.registry.addNestedMenuItem('fontformats', {
  23468. text: backstage.shared.providers.translate('Fonts'),
  23469. getSubmenuItems: function () {
  23470. return menuItems.items.validateItems(menuItems.getStyleItems());
  23471. }
  23472. });
  23473. };
  23474. var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  23475. var legacyFontSizes = {
  23476. '8pt': '1',
  23477. '10pt': '2',
  23478. '12pt': '3',
  23479. '14pt': '4',
  23480. '18pt': '5',
  23481. '24pt': '6',
  23482. '36pt': '7'
  23483. };
  23484. var round$1 = function (number, precision) {
  23485. var factor = Math.pow(10, precision);
  23486. return Math.round(number * factor) / factor;
  23487. };
  23488. var toPt = function (fontSize, precision) {
  23489. if (/[0-9.]+px$/.test(fontSize)) {
  23490. return round$1(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  23491. }
  23492. return fontSize;
  23493. };
  23494. var toLegacy = function (fontSize) {
  23495. return get(legacyFontSizes, fontSize).getOr('');
  23496. };
  23497. var getSpec$2 = function (editor) {
  23498. var getMatchingValue = function () {
  23499. var matchOpt = Option.none();
  23500. var items = dataset.data;
  23501. var fontSize = editor.queryCommandValue('FontSize');
  23502. if (fontSize) {
  23503. var _loop_1 = function (precision) {
  23504. var pt = toPt(fontSize, precision);
  23505. var legacy = toLegacy(pt);
  23506. matchOpt = find(items, function (item) {
  23507. return item.format === fontSize || item.format === pt || item.format === legacy;
  23508. });
  23509. };
  23510. for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  23511. _loop_1(precision);
  23512. }
  23513. }
  23514. return {
  23515. matchOpt: matchOpt,
  23516. size: fontSize
  23517. };
  23518. };
  23519. var isSelectedFor = function (item) {
  23520. return function (valueOpt) {
  23521. return valueOpt.exists(function (value) {
  23522. return value.format === item;
  23523. });
  23524. };
  23525. };
  23526. var getCurrentValue = function () {
  23527. var matchOpt = getMatchingValue().matchOpt;
  23528. return matchOpt;
  23529. };
  23530. var getPreviewFor = constant(constant(Option.none()));
  23531. var onAction = function (rawItem) {
  23532. return function () {
  23533. editor.undoManager.transact(function () {
  23534. editor.focus();
  23535. editor.execCommand('FontSize', false, rawItem.format);
  23536. });
  23537. };
  23538. };
  23539. var updateSelectMenuText = function (comp) {
  23540. var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
  23541. var text = matchOpt.fold(function () {
  23542. return size;
  23543. }, function (match) {
  23544. return match.title;
  23545. });
  23546. emitWith(comp, updateMenuText, { text: text });
  23547. };
  23548. var nodeChangeHandler = Option.some(function (comp) {
  23549. return function () {
  23550. return updateSelectMenuText(comp);
  23551. };
  23552. });
  23553. var setInitialValue = Option.some(function (comp) {
  23554. return updateSelectMenuText(comp);
  23555. });
  23556. var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  23557. return {
  23558. tooltip: 'Font sizes',
  23559. icon: Option.none(),
  23560. isSelectedFor: isSelectedFor,
  23561. getPreviewFor: getPreviewFor,
  23562. getCurrentValue: getCurrentValue,
  23563. onAction: onAction,
  23564. setInitialValue: setInitialValue,
  23565. nodeChangeHandler: nodeChangeHandler,
  23566. dataset: dataset,
  23567. shouldHide: false,
  23568. isInvalid: function () {
  23569. return false;
  23570. }
  23571. };
  23572. };
  23573. var createFontsizeSelect = function (editor, backstage) {
  23574. return createSelectButton(editor, backstage, getSpec$2(editor));
  23575. };
  23576. var fontsizeSelectMenu = function (editor, backstage) {
  23577. var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  23578. editor.ui.registry.addNestedMenuItem('fontsizes', {
  23579. text: 'Font sizes',
  23580. getSubmenuItems: function () {
  23581. return menuItems.items.validateItems(menuItems.getStyleItems());
  23582. }
  23583. });
  23584. };
  23585. var findNearest = function (editor, getStyles, parents) {
  23586. var styles = getStyles();
  23587. return findMap(parents, function (parent) {
  23588. return find(styles, function (fmt) {
  23589. return editor.formatter.matchNode(parent, fmt.format);
  23590. });
  23591. }).orThunk(function () {
  23592. if (editor.formatter.match('p')) {
  23593. return Option.some({
  23594. title: 'Paragraph',
  23595. format: 'p'
  23596. });
  23597. }
  23598. return Option.none();
  23599. });
  23600. };
  23601. var getCurrentSelectionParents = function (editor) {
  23602. var currentNode = editor.selection.getStart(true) || editor.getBody();
  23603. return editor.dom.getParents(currentNode, function () {
  23604. return true;
  23605. }, editor.getBody());
  23606. };
  23607. var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  23608. var getSpec$3 = function (editor) {
  23609. var getMatchingValue = function (nodeChangeEvent) {
  23610. return findNearest(editor, function () {
  23611. return dataset.data;
  23612. }, nodeChangeEvent);
  23613. };
  23614. var isSelectedFor = function (format) {
  23615. return function () {
  23616. return editor.formatter.match(format);
  23617. };
  23618. };
  23619. var getPreviewFor = function (format) {
  23620. return function () {
  23621. var fmt = editor.formatter.get(format);
  23622. return Option.some({
  23623. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23624. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  23625. });
  23626. };
  23627. };
  23628. var updateSelectMenuText = function (parents, comp) {
  23629. var detectedFormat = getMatchingValue(parents);
  23630. var text = detectedFormat.fold(function () {
  23631. return 'Paragraph';
  23632. }, function (fmt) {
  23633. return fmt.title;
  23634. });
  23635. emitWith(comp, updateMenuText, { text: text });
  23636. };
  23637. var nodeChangeHandler = Option.some(function (comp) {
  23638. return function (e) {
  23639. return updateSelectMenuText(e.parents, comp);
  23640. };
  23641. });
  23642. var setInitialValue = Option.some(function (comp) {
  23643. var parents = getCurrentSelectionParents(editor);
  23644. updateSelectMenuText(parents, comp);
  23645. });
  23646. var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  23647. return {
  23648. tooltip: 'Blocks',
  23649. icon: Option.none(),
  23650. isSelectedFor: isSelectedFor,
  23651. getCurrentValue: constant(Option.none()),
  23652. getPreviewFor: getPreviewFor,
  23653. onAction: onActionToggleFormat(editor),
  23654. setInitialValue: setInitialValue,
  23655. nodeChangeHandler: nodeChangeHandler,
  23656. dataset: dataset,
  23657. shouldHide: false,
  23658. isInvalid: function (item) {
  23659. return !editor.formatter.canApply(item.format);
  23660. }
  23661. };
  23662. };
  23663. var createFormatSelect = function (editor, backstage) {
  23664. return createSelectButton(editor, backstage, getSpec$3(editor));
  23665. };
  23666. var formatSelectMenu = function (editor, backstage) {
  23667. var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  23668. editor.ui.registry.addNestedMenuItem('blockformats', {
  23669. text: 'Blocks',
  23670. getSubmenuItems: function () {
  23671. return menuItems.items.validateItems(menuItems.getStyleItems());
  23672. }
  23673. });
  23674. };
  23675. var getSpec$4 = function (editor, dataset) {
  23676. var isSelectedFor = function (format) {
  23677. return function () {
  23678. return editor.formatter.match(format);
  23679. };
  23680. };
  23681. var getPreviewFor = function (format) {
  23682. return function () {
  23683. var fmt = editor.formatter.get(format);
  23684. return fmt !== undefined ? Option.some({
  23685. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23686. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  23687. }) : Option.none();
  23688. };
  23689. };
  23690. var updateSelectMenuText = function (parents, comp) {
  23691. var getFormatItems = function (fmt) {
  23692. var subs = fmt.items;
  23693. return subs !== undefined && subs.length > 0 ? bind(subs, getFormatItems) : [{
  23694. title: fmt.title,
  23695. format: fmt.format
  23696. }];
  23697. };
  23698. var flattenedItems = bind(getStyleFormats(editor), getFormatItems);
  23699. var detectedFormat = findNearest(editor, function () {
  23700. return flattenedItems;
  23701. }, parents);
  23702. var text = detectedFormat.fold(function () {
  23703. return 'Paragraph';
  23704. }, function (fmt) {
  23705. return fmt.title;
  23706. });
  23707. emitWith(comp, updateMenuText, { text: text });
  23708. };
  23709. var nodeChangeHandler = Option.some(function (comp) {
  23710. return function (e) {
  23711. return updateSelectMenuText(e.parents, comp);
  23712. };
  23713. });
  23714. var setInitialValue = Option.some(function (comp) {
  23715. var parents = getCurrentSelectionParents(editor);
  23716. updateSelectMenuText(parents, comp);
  23717. });
  23718. return {
  23719. tooltip: 'Formats',
  23720. icon: Option.none(),
  23721. isSelectedFor: isSelectedFor,
  23722. getCurrentValue: constant(Option.none()),
  23723. getPreviewFor: getPreviewFor,
  23724. onAction: onActionToggleFormat(editor),
  23725. setInitialValue: setInitialValue,
  23726. nodeChangeHandler: nodeChangeHandler,
  23727. shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  23728. isInvalid: function (item) {
  23729. return !editor.formatter.canApply(item.format);
  23730. },
  23731. dataset: dataset
  23732. };
  23733. };
  23734. var createStyleSelect = function (editor, backstage) {
  23735. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  23736. return createSelectButton(editor, backstage, getSpec$4(editor, dataset));
  23737. };
  23738. var styleSelectMenu = function (editor, backstage) {
  23739. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  23740. var menuItems = createMenuItems(editor, backstage, getSpec$4(editor, dataset));
  23741. editor.ui.registry.addNestedMenuItem('formats', {
  23742. text: 'Formats',
  23743. getSubmenuItems: function () {
  23744. return menuItems.items.validateItems(menuItems.getStyleItems());
  23745. }
  23746. });
  23747. };
  23748. var defaultToolbar = [
  23749. {
  23750. name: 'history',
  23751. items: [
  23752. 'undo',
  23753. 'redo'
  23754. ]
  23755. },
  23756. {
  23757. name: 'styles',
  23758. items: ['styleselect']
  23759. },
  23760. {
  23761. name: 'formatting',
  23762. items: [
  23763. 'bold',
  23764. 'italic'
  23765. ]
  23766. },
  23767. {
  23768. name: 'alignment',
  23769. items: [
  23770. 'alignleft',
  23771. 'aligncenter',
  23772. 'alignright',
  23773. 'alignjustify'
  23774. ]
  23775. },
  23776. {
  23777. name: 'indentation',
  23778. items: [
  23779. 'outdent',
  23780. 'indent'
  23781. ]
  23782. },
  23783. {
  23784. name: 'permanent pen',
  23785. items: ['permanentpen']
  23786. },
  23787. {
  23788. name: 'comments',
  23789. items: ['addcomment']
  23790. }
  23791. ];
  23792. var renderFromBridge = function (bridgeBuilder, render) {
  23793. return function (spec, extras, editor) {
  23794. var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  23795. return formatError(errInfo);
  23796. }).getOrDie();
  23797. return render(internal, extras, editor);
  23798. };
  23799. };
  23800. var types = {
  23801. button: renderFromBridge(createToolbarButton, function (s, extras) {
  23802. return renderToolbarButton(s, extras.backstage.shared.providers);
  23803. }),
  23804. togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  23805. return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  23806. }),
  23807. menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  23808. return renderMenuButton(s, 'tox-tbtn', extras.backstage, Option.none());
  23809. }),
  23810. splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  23811. return renderSplitButton(s, extras.backstage.shared);
  23812. }),
  23813. grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
  23814. var _a;
  23815. var buttons = editor.ui.registry.getAll().buttons;
  23816. var identify = function (toolbar) {
  23817. return identifyButtons(editor, {
  23818. buttons: buttons,
  23819. toolbar: toolbar,
  23820. allowToolbarGroups: false
  23821. }, extras, Option.none());
  23822. };
  23823. var attributes = (_a = {}, _a[Attribute] = isToolbarLocationTop(editor) ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
  23824. switch (getToolbarMode(editor)) {
  23825. case ToolbarMode.floating:
  23826. return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  23827. default:
  23828. throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  23829. }
  23830. }),
  23831. styleSelectButton: function (editor, extras) {
  23832. return createStyleSelect(editor, extras.backstage);
  23833. },
  23834. fontsizeSelectButton: function (editor, extras) {
  23835. return createFontsizeSelect(editor, extras.backstage);
  23836. },
  23837. fontSelectButton: function (editor, extras) {
  23838. return createFontSelect(editor, extras.backstage);
  23839. },
  23840. formatButton: function (editor, extras) {
  23841. return createFormatSelect(editor, extras.backstage);
  23842. },
  23843. alignMenuButton: function (editor, extras) {
  23844. return createAlignSelect(editor, extras.backstage);
  23845. }
  23846. };
  23847. var extractFrom = function (spec, extras, editor) {
  23848. return get(types, spec.type).fold(function () {
  23849. domGlobals.console.error('skipping button defined by', spec);
  23850. return Option.none();
  23851. }, function (render) {
  23852. return Option.some(render(spec, extras, editor));
  23853. });
  23854. };
  23855. var bespokeButtons = {
  23856. styleselect: types.styleSelectButton,
  23857. fontsizeselect: types.fontsizeSelectButton,
  23858. fontselect: types.fontSelectButton,
  23859. formatselect: types.formatButton,
  23860. align: types.alignMenuButton
  23861. };
  23862. var removeUnusedDefaults = function (buttons) {
  23863. var filteredItemGroups = map(defaultToolbar, function (group) {
  23864. var items = filter(group.items, function (subItem) {
  23865. return has(buttons, subItem) || has(bespokeButtons, subItem);
  23866. });
  23867. return {
  23868. name: group.name,
  23869. items: items
  23870. };
  23871. });
  23872. return filter(filteredItemGroups, function (group) {
  23873. return group.items.length > 0;
  23874. });
  23875. };
  23876. var convertStringToolbar = function (strToolbar) {
  23877. var groupsStrings = strToolbar.split('|');
  23878. return map(groupsStrings, function (g) {
  23879. return { items: g.trim().split(' ') };
  23880. });
  23881. };
  23882. var isToolbarGroupSettingArray = function (toolbar) {
  23883. return isArrayOf(toolbar, function (t) {
  23884. return has(t, 'name') && has(t, 'items');
  23885. });
  23886. };
  23887. var createToolbar = function (toolbarConfig) {
  23888. var toolbar = toolbarConfig.toolbar;
  23889. var buttons = toolbarConfig.buttons;
  23890. if (toolbar === false) {
  23891. return [];
  23892. } else if (toolbar === undefined || toolbar === true) {
  23893. return removeUnusedDefaults(buttons);
  23894. } else if (isString(toolbar)) {
  23895. return convertStringToolbar(toolbar);
  23896. } else if (isToolbarGroupSettingArray(toolbar)) {
  23897. return toolbar;
  23898. } else {
  23899. domGlobals.console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  23900. return [];
  23901. }
  23902. };
  23903. var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
  23904. return get(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  23905. return prefixes.bind(function (ps) {
  23906. return findMap(ps, function (prefix) {
  23907. return get(buttons, prefix + toolbarItem.toLowerCase());
  23908. });
  23909. });
  23910. }).fold(function () {
  23911. return get(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  23912. return r(editor, extras);
  23913. }).orThunk(function () {
  23914. return Option.none();
  23915. });
  23916. }, function (spec) {
  23917. if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  23918. domGlobals.console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
  23919. return Option.none();
  23920. } else {
  23921. return extractFrom(spec, extras, editor);
  23922. }
  23923. });
  23924. };
  23925. var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  23926. var toolbarGroups = createToolbar(toolbarConfig);
  23927. var groups = map(toolbarGroups, function (group) {
  23928. var items = bind(group.items, function (toolbarItem) {
  23929. return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
  23930. });
  23931. return {
  23932. title: Option.from(editor.translate(group.name)),
  23933. items: items
  23934. };
  23935. });
  23936. return filter(groups, function (group) {
  23937. return group.items.length > 0;
  23938. });
  23939. };
  23940. var bubbleSize = 12;
  23941. var bubbleAlignments$1 = {
  23942. valignCentre: [],
  23943. alignCentre: [],
  23944. alignLeft: ['tox-pop--align-left'],
  23945. alignRight: ['tox-pop--align-right'],
  23946. right: ['tox-pop--right'],
  23947. left: ['tox-pop--left'],
  23948. bottom: ['tox-pop--bottom'],
  23949. top: ['tox-pop--top']
  23950. };
  23951. var anchorOverrides = {
  23952. maxHeightFunction: expandable(),
  23953. maxWidthFunction: expandable$1()
  23954. };
  23955. var desktopAnchorSpecLayouts = {
  23956. onLtr: function () {
  23957. return [
  23958. north$1,
  23959. south$1,
  23960. northeast$1,
  23961. southeast$1,
  23962. northwest$1,
  23963. southwest$1,
  23964. north$3,
  23965. south$3,
  23966. northeast$3,
  23967. southeast$3,
  23968. northwest$3,
  23969. southwest$3
  23970. ];
  23971. },
  23972. onRtl: function () {
  23973. return [
  23974. north$1,
  23975. south$1,
  23976. northwest$1,
  23977. southwest$1,
  23978. northeast$1,
  23979. southeast$1,
  23980. north$3,
  23981. south$3,
  23982. northwest$3,
  23983. southwest$3,
  23984. northeast$3,
  23985. southeast$3
  23986. ];
  23987. }
  23988. };
  23989. var mobileAnchorSpecLayouts = {
  23990. onLtr: function () {
  23991. return [
  23992. south$1,
  23993. southeast$1,
  23994. southwest$1,
  23995. northeast$1,
  23996. northwest$1,
  23997. north$1,
  23998. north$3,
  23999. south$3,
  24000. northeast$3,
  24001. southeast$3,
  24002. northwest$3,
  24003. southwest$3
  24004. ];
  24005. },
  24006. onRtl: function () {
  24007. return [
  24008. south$1,
  24009. southwest$1,
  24010. southeast$1,
  24011. northwest$1,
  24012. northeast$1,
  24013. north$1,
  24014. north$3,
  24015. south$3,
  24016. northwest$3,
  24017. southwest$3,
  24018. northeast$3,
  24019. southeast$3
  24020. ];
  24021. }
  24022. };
  24023. var getAnchorLayout = function (position, isTouch) {
  24024. if (position === 'line') {
  24025. return {
  24026. bubble: nu$8(bubbleSize, 0, bubbleAlignments$1),
  24027. layouts: {
  24028. onLtr: function () {
  24029. return [east$1];
  24030. },
  24031. onRtl: function () {
  24032. return [west$1];
  24033. }
  24034. },
  24035. overrides: anchorOverrides
  24036. };
  24037. } else {
  24038. return {
  24039. bubble: nu$8(0, bubbleSize, bubbleAlignments$1),
  24040. layouts: isTouch ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts,
  24041. overrides: anchorOverrides
  24042. };
  24043. }
  24044. };
  24045. var register$4 = function (editor, registryContextToolbars, sink, extras) {
  24046. var isTouch = detect$3().deviceType.isTouch;
  24047. var contextbar = build$1(renderContextToolbar({
  24048. sink: sink,
  24049. onEscape: function () {
  24050. editor.focus();
  24051. return Option.some(true);
  24052. }
  24053. }));
  24054. var getBounds = function () {
  24055. return getContextToolbarBounds(editor);
  24056. };
  24057. var isRangeOverlapping = function (aTop, aBottom, bTop, bBottom) {
  24058. return Math.max(aTop, bTop) <= Math.min(aBottom, bBottom);
  24059. };
  24060. var getLastElementVerticalBound = function () {
  24061. var nodeBounds = lastElement.get().map(function (ele) {
  24062. return ele.getBoundingClientRect();
  24063. }).getOrThunk(function () {
  24064. return editor.selection.getRng().getBoundingClientRect();
  24065. });
  24066. var diffTop = editor.inline ? get$8().top() : absolute$1(Element.fromDom(editor.getBody())).y();
  24067. return {
  24068. y: nodeBounds.top + diffTop,
  24069. bottom: nodeBounds.bottom + diffTop
  24070. };
  24071. };
  24072. var shouldContextToolbarHide = function () {
  24073. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24074. return true;
  24075. }
  24076. var lastElementBounds = getLastElementVerticalBound();
  24077. var contextToolbarBounds = getBounds();
  24078. return !isRangeOverlapping(lastElementBounds.y, lastElementBounds.bottom, contextToolbarBounds.y(), contextToolbarBounds.bottom());
  24079. };
  24080. var forceHide = function () {
  24081. InlineView.hide(contextbar);
  24082. };
  24083. var hideOrRepositionIfNecessary = function () {
  24084. lastAnchor.get().each(function (anchor) {
  24085. var contextBarEle = contextbar.element();
  24086. remove$6(contextBarEle, 'display');
  24087. if (shouldContextToolbarHide()) {
  24088. set$2(contextBarEle, 'display', 'none');
  24089. } else {
  24090. Positioning.positionWithinBounds(sink, anchor, contextbar, Option.some(getBounds()));
  24091. }
  24092. });
  24093. };
  24094. var lastAnchor = Cell(Option.none());
  24095. var lastElement = Cell(Option.none());
  24096. var timer = Cell(null);
  24097. var wrapInPopDialog = function (toolbarSpec) {
  24098. return {
  24099. dom: {
  24100. tag: 'div',
  24101. classes: ['tox-pop__dialog']
  24102. },
  24103. components: [toolbarSpec],
  24104. behaviours: derive$1([
  24105. Keying.config({ mode: 'acyclic' }),
  24106. config('pop-dialog-wrap-events', [
  24107. runOnAttached(function (comp) {
  24108. editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  24109. return Keying.focusIn(comp);
  24110. });
  24111. }),
  24112. runOnDetached(function (comp) {
  24113. editor.shortcuts.remove('ctrl+F9');
  24114. })
  24115. ])
  24116. ])
  24117. };
  24118. };
  24119. var getScopes = cached(function () {
  24120. return ToolbarScopes.categorise(registryContextToolbars, function (toolbarApi) {
  24121. var alloySpec = buildToolbar(toolbarApi);
  24122. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  24123. });
  24124. });
  24125. var buildToolbar = function (ctx) {
  24126. var buttons = editor.ui.registry.getAll().buttons;
  24127. var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
  24128. var scopes = getScopes();
  24129. return ctx.type === 'contexttoolbar' ? function () {
  24130. var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
  24131. var initGroups = identifyButtons(editor, {
  24132. buttons: allButtons,
  24133. toolbar: ctx.items,
  24134. allowToolbarGroups: false
  24135. }, extras, Option.some(['form:']));
  24136. return renderToolbar({
  24137. type: toolbarType,
  24138. uid: generate$1('context-toolbar'),
  24139. initGroups: initGroups,
  24140. onEscape: Option.none,
  24141. cyclicKeying: true
  24142. });
  24143. }() : function () {
  24144. return ContextForm.renderContextForm(toolbarType, ctx, extras.backstage);
  24145. }();
  24146. };
  24147. editor.on(showContextToolbarEvent, function (e) {
  24148. var scopes = getScopes();
  24149. get(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  24150. launchContext(ctx, e.target === editor ? Option.none() : Option.some(e));
  24151. InlineView.getContent(contextbar).each(Keying.focusIn);
  24152. });
  24153. });
  24154. var getAnchor = function (position, element) {
  24155. var anchorage = position === 'node' ? extras.backstage.shared.anchors.node(element) : extras.backstage.shared.anchors.cursor();
  24156. return deepMerge(anchorage, getAnchorLayout(position, isTouch()));
  24157. };
  24158. var launchContext = function (toolbarApi, elem) {
  24159. clearTimer();
  24160. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24161. return;
  24162. }
  24163. var toolbarSpec = buildToolbar(toolbarApi);
  24164. var sElem = elem.map(Element.fromDom);
  24165. var anchor = getAnchor(toolbarApi.position, sElem);
  24166. lastAnchor.set(Option.some(anchor));
  24167. lastElement.set(elem);
  24168. var contextBarEle = contextbar.element();
  24169. remove$6(contextBarEle, 'display');
  24170. InlineView.showWithinBounds(contextbar, anchor, wrapInPopDialog(toolbarSpec), function () {
  24171. return Option.some(getBounds());
  24172. });
  24173. if (shouldContextToolbarHide()) {
  24174. set$2(contextBarEle, 'display', 'none');
  24175. }
  24176. };
  24177. var launchContextToolbar = function () {
  24178. var scopes = getScopes();
  24179. ToolbarLookup.lookup(scopes, editor).fold(function () {
  24180. lastAnchor.set(Option.none());
  24181. InlineView.hide(contextbar);
  24182. }, function (info) {
  24183. launchContext(info.toolbarApi, Option.some(info.elem.dom()));
  24184. });
  24185. };
  24186. var clearTimer = function () {
  24187. var current = timer.get();
  24188. if (current !== null) {
  24189. global$2.clearTimeout(current);
  24190. timer.set(null);
  24191. }
  24192. };
  24193. var resetTimer = function (t) {
  24194. clearTimer();
  24195. timer.set(t);
  24196. };
  24197. editor.on('init', function () {
  24198. editor.on(hideContextToolbarEvent, forceHide);
  24199. editor.on('ScrollContent ScrollWindow longpress', hideOrRepositionIfNecessary);
  24200. editor.on('click keyup SetContent ObjectResized ResizeEditor', function (e) {
  24201. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24202. });
  24203. editor.on('focusout', function (e) {
  24204. global$2.setEditorTimeout(editor, function () {
  24205. if (search(sink.element()).isNone() && search(contextbar.element()).isNone()) {
  24206. lastAnchor.set(Option.none());
  24207. InlineView.hide(contextbar);
  24208. }
  24209. }, 0);
  24210. });
  24211. editor.on('SwitchMode', function () {
  24212. if (editor.readonly) {
  24213. lastAnchor.set(Option.none());
  24214. InlineView.hide(contextbar);
  24215. }
  24216. });
  24217. editor.on('NodeChange', function (e) {
  24218. search(contextbar.element()).fold(function () {
  24219. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24220. }, function (_) {
  24221. });
  24222. });
  24223. });
  24224. };
  24225. var ContextToolbar = { register: register$4 };
  24226. var setup$3 = function (editor, mothership, uiMothership) {
  24227. var broadcastEvent = function (name, evt) {
  24228. each([
  24229. mothership,
  24230. uiMothership
  24231. ], function (ship) {
  24232. ship.broadcastEvent(name, evt);
  24233. });
  24234. };
  24235. var broadcastOn = function (channel, message) {
  24236. each([
  24237. mothership,
  24238. uiMothership
  24239. ], function (ship) {
  24240. ship.broadcastOn([channel], message);
  24241. });
  24242. };
  24243. var fireDismissPopups = function (evt) {
  24244. return broadcastOn(dismissPopups(), { target: evt.target() });
  24245. };
  24246. var onTouchstart = bind$3(Element.fromDom(domGlobals.document), 'touchstart', fireDismissPopups);
  24247. var onTouchmove = bind$3(Element.fromDom(domGlobals.document), 'touchmove', function (evt) {
  24248. return broadcastEvent(documentTouchmove(), evt);
  24249. });
  24250. var onTouchend = bind$3(Element.fromDom(domGlobals.document), 'touchend', function (evt) {
  24251. return broadcastEvent(documentTouchend(), evt);
  24252. });
  24253. var onMousedown = bind$3(Element.fromDom(domGlobals.document), 'mousedown', fireDismissPopups);
  24254. var onMouseup = bind$3(Element.fromDom(domGlobals.document), 'mouseup', function (evt) {
  24255. if (evt.raw().button === 0) {
  24256. broadcastOn(mouseReleased(), { target: evt.target() });
  24257. }
  24258. });
  24259. var onContentClick = function (raw) {
  24260. return broadcastOn(dismissPopups(), { target: Element.fromDom(raw.target) });
  24261. };
  24262. var onContentMouseup = function (raw) {
  24263. if (raw.button === 0) {
  24264. broadcastOn(mouseReleased(), { target: Element.fromDom(raw.target) });
  24265. }
  24266. };
  24267. var onWindowScroll = function (evt) {
  24268. return broadcastEvent(windowScroll(), fromRawEvent$1(evt));
  24269. };
  24270. var onWindowResize = function (evt) {
  24271. broadcastOn(repositionPopups(), {});
  24272. broadcastEvent(windowResize(), fromRawEvent$1(evt));
  24273. };
  24274. var onEditorResize = function () {
  24275. return broadcastOn(repositionPopups(), {});
  24276. };
  24277. editor.on('PostRender', function () {
  24278. editor.on('click', onContentClick);
  24279. editor.on('tap', onContentClick);
  24280. editor.on('mouseup', onContentMouseup);
  24281. editor.on('ScrollWindow', onWindowScroll);
  24282. editor.on('ResizeWindow', onWindowResize);
  24283. editor.on('ResizeEditor', onEditorResize);
  24284. });
  24285. editor.on('remove', function () {
  24286. editor.off('click', onContentClick);
  24287. editor.off('tap', onContentClick);
  24288. editor.off('mouseup', onContentMouseup);
  24289. editor.off('ScrollWindow', onWindowScroll);
  24290. editor.off('ResizeWindow', onWindowResize);
  24291. editor.off('ResizeEditor', onEditorResize);
  24292. onMousedown.unbind();
  24293. onTouchstart.unbind();
  24294. onTouchmove.unbind();
  24295. onTouchend.unbind();
  24296. onMouseup.unbind();
  24297. });
  24298. editor.on('detach', function () {
  24299. detachSystem(mothership);
  24300. detachSystem(uiMothership);
  24301. mothership.destroy();
  24302. uiMothership.destroy();
  24303. });
  24304. };
  24305. var Events$1 = { setup: setup$3 };
  24306. var parts$d = AlloyParts;
  24307. var partType$1 = PartType;
  24308. var schema$r = constant([
  24309. defaulted$1('shell', false),
  24310. strict$1('makeItem'),
  24311. defaulted$1('setupItem', noop),
  24312. SketchBehaviours.field('listBehaviours', [Replacing])
  24313. ]);
  24314. var customListDetail = function () {
  24315. return { behaviours: derive$1([Replacing.config({})]) };
  24316. };
  24317. var itemsPart = optional({
  24318. name: 'items',
  24319. overrides: customListDetail
  24320. });
  24321. var parts$e = constant([itemsPart]);
  24322. var name$2 = constant('CustomList');
  24323. var factory$f = function (detail, components, spec, external) {
  24324. var setItems = function (list, items) {
  24325. getListContainer(list).fold(function () {
  24326. domGlobals.console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  24327. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  24328. }, function (container) {
  24329. var itemComps = Replacing.contents(container);
  24330. var numListsRequired = items.length;
  24331. var numListsToAdd = numListsRequired - itemComps.length;
  24332. var itemsToAdd = numListsToAdd > 0 ? range(numListsToAdd, function () {
  24333. return detail.makeItem();
  24334. }) : [];
  24335. var itemsToRemove = itemComps.slice(numListsRequired);
  24336. each(itemsToRemove, function (item) {
  24337. return Replacing.remove(container, item);
  24338. });
  24339. each(itemsToAdd, function (item) {
  24340. return Replacing.append(container, item);
  24341. });
  24342. var builtLists = Replacing.contents(container);
  24343. each(builtLists, function (item, i) {
  24344. detail.setupItem(list, item, items[i], i);
  24345. });
  24346. });
  24347. };
  24348. var extra = detail.shell ? {
  24349. behaviours: [Replacing.config({})],
  24350. components: []
  24351. } : {
  24352. behaviours: [],
  24353. components: components
  24354. };
  24355. var getListContainer = function (component) {
  24356. return detail.shell ? Option.some(component) : getPart(component, detail, 'items');
  24357. };
  24358. return {
  24359. uid: detail.uid,
  24360. dom: detail.dom,
  24361. components: extra.components,
  24362. behaviours: augment(detail.listBehaviours, extra.behaviours),
  24363. apis: { setItems: setItems }
  24364. };
  24365. };
  24366. var CustomList = composite$1({
  24367. name: name$2(),
  24368. configFields: schema$r(),
  24369. partFields: parts$e(),
  24370. factory: factory$f,
  24371. apis: {
  24372. setItems: function (apis, list, items) {
  24373. apis.setItems(list, items);
  24374. }
  24375. }
  24376. });
  24377. var getOffsetParent = function (element) {
  24378. var isFixed = getRaw(element, 'position').is('fixed');
  24379. var offsetParent$1 = isFixed ? Option.none() : offsetParent(element);
  24380. return offsetParent$1.orThunk(function () {
  24381. var marker = Element.fromTag('span');
  24382. return parent(element).bind(function (parent) {
  24383. append(parent, marker);
  24384. var offsetParent$1 = offsetParent(marker);
  24385. remove(marker);
  24386. return offsetParent$1;
  24387. });
  24388. });
  24389. };
  24390. var getOrigin = function (element) {
  24391. return getOffsetParent(element).map(absolute).getOrThunk(function () {
  24392. return Position(0, 0);
  24393. });
  24394. };
  24395. var morphAdt = Adt.generate([
  24396. { static: [] },
  24397. { absolute: ['positionCss'] },
  24398. { fixed: ['positionCss'] }
  24399. ]);
  24400. var appear = function (component, contextualInfo) {
  24401. var elem = component.element();
  24402. add$2(elem, contextualInfo.transitionClass);
  24403. remove$4(elem, contextualInfo.fadeOutClass);
  24404. add$2(elem, contextualInfo.fadeInClass);
  24405. contextualInfo.onShow(component);
  24406. };
  24407. var disappear = function (component, contextualInfo) {
  24408. var elem = component.element();
  24409. add$2(elem, contextualInfo.transitionClass);
  24410. remove$4(elem, contextualInfo.fadeInClass);
  24411. add$2(elem, contextualInfo.fadeOutClass);
  24412. contextualInfo.onHide(component);
  24413. };
  24414. var isPartiallyVisible = function (box, viewport) {
  24415. return box.y() < viewport.bottom() && box.bottom() > viewport.y();
  24416. };
  24417. var isTopCompletelyVisible = function (box, viewport) {
  24418. return box.y() >= viewport.y();
  24419. };
  24420. var isBottomCompletelyVisible = function (box, viewport) {
  24421. return box.bottom() <= viewport.bottom();
  24422. };
  24423. var isVisibleForModes = function (modes, box, viewport) {
  24424. return forall(modes, function (mode) {
  24425. switch (mode) {
  24426. case 'bottom':
  24427. return isBottomCompletelyVisible(box, viewport);
  24428. case 'top':
  24429. return isTopCompletelyVisible(box, viewport);
  24430. }
  24431. });
  24432. };
  24433. var getPrior = function (elem, state) {
  24434. return state.getInitialPosition().map(function (pos) {
  24435. return bounds$1(pos.bounds.x(), pos.bounds.y(), get$7(elem), get$6(elem));
  24436. });
  24437. };
  24438. var storePrior = function (elem, box, state) {
  24439. state.setInitialPosition(Option.some({
  24440. style: getAllRaw(elem),
  24441. position: get$4(elem, 'position') || 'static',
  24442. bounds: box
  24443. }));
  24444. };
  24445. var revertToOriginal = function (elem, box$1, state) {
  24446. return state.getInitialPosition().bind(function (position) {
  24447. state.setInitialPosition(Option.none());
  24448. switch (position.position) {
  24449. case 'static':
  24450. return Option.some(morphAdt.static());
  24451. case 'absolute':
  24452. var offsetBox_1 = getOffsetParent(elem).map(box).getOrThunk(function () {
  24453. return box(body());
  24454. });
  24455. return Option.some(morphAdt.absolute(NuPositionCss('absolute', get(position.style, 'left').map(function (_) {
  24456. return box$1.x() - offsetBox_1.x();
  24457. }), get(position.style, 'top').map(function (_) {
  24458. return box$1.y() - offsetBox_1.y();
  24459. }), get(position.style, 'right').map(function (_) {
  24460. return offsetBox_1.right() - box$1.right();
  24461. }), get(position.style, 'bottom').map(function (_) {
  24462. return offsetBox_1.bottom() - box$1.bottom();
  24463. }))));
  24464. default:
  24465. return Option.none();
  24466. }
  24467. });
  24468. };
  24469. var morphToOriginal = function (elem, dockInfo, viewport, state) {
  24470. return getPrior(elem, state).filter(function (box) {
  24471. return isVisibleForModes(dockInfo.modes, box, viewport);
  24472. }).bind(function (box) {
  24473. return revertToOriginal(elem, box, state);
  24474. });
  24475. };
  24476. var morphToFixed = function (elem, dockInfo, viewport, state) {
  24477. var box$1 = box(elem);
  24478. if (!isVisibleForModes(dockInfo.modes, box$1, viewport)) {
  24479. storePrior(elem, box$1, state);
  24480. var winBox = win();
  24481. var left = box$1.x() - winBox.x();
  24482. var top = viewport.y() - winBox.y();
  24483. var bottom = winBox.bottom() - viewport.bottom();
  24484. var isTop = box$1.y() <= viewport.y();
  24485. return Option.some(morphAdt.fixed(NuPositionCss('fixed', Option.some(left), isTop ? Option.some(top) : Option.none(), Option.none(), !isTop ? Option.some(bottom) : Option.none())));
  24486. } else {
  24487. return Option.none();
  24488. }
  24489. };
  24490. var getMorph = function (component, dockInfo, viewport, state) {
  24491. var elem = component.element();
  24492. var isDocked = getRaw(elem, 'position').is('fixed');
  24493. return isDocked ? morphToOriginal(elem, dockInfo, viewport, state) : morphToFixed(elem, dockInfo, viewport, state);
  24494. };
  24495. var getMorphToOriginal = function (component, state) {
  24496. var elem = component.element();
  24497. return getPrior(elem, state).bind(function (box) {
  24498. return revertToOriginal(elem, box, state);
  24499. });
  24500. };
  24501. var morphToStatic = function (component, config) {
  24502. each([
  24503. 'left',
  24504. 'right',
  24505. 'top',
  24506. 'bottom',
  24507. 'position'
  24508. ], function (prop) {
  24509. return remove$6(component.element(), prop);
  24510. });
  24511. config.onUndocked(component);
  24512. };
  24513. var morphToCoord = function (component, config, position) {
  24514. applyPositionCss(component.element(), position);
  24515. var method = position.position() === 'fixed' ? config.onDocked : config.onUndocked;
  24516. method(component);
  24517. };
  24518. var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  24519. if (morphToDocked === void 0) {
  24520. morphToDocked = false;
  24521. }
  24522. config.contextual.each(function (contextInfo) {
  24523. contextInfo.lazyContext(component).each(function (box) {
  24524. var isVisible = isPartiallyVisible(box, viewport);
  24525. if (isVisible !== state.isVisible()) {
  24526. state.setVisible(isVisible);
  24527. if (morphToDocked && !isVisible) {
  24528. add$3(component.element(), [contextInfo.fadeOutClass]);
  24529. contextInfo.onHide(component);
  24530. } else {
  24531. var method = isVisible ? appear : disappear;
  24532. method(component, contextInfo);
  24533. }
  24534. }
  24535. });
  24536. });
  24537. };
  24538. var refreshInternal = function (component, config, state) {
  24539. var viewport = config.lazyViewport(component);
  24540. var isDocked = state.isDocked();
  24541. if (isDocked) {
  24542. updateVisibility(component, config, state, viewport);
  24543. }
  24544. getMorph(component, config, viewport, state).each(function (morph) {
  24545. state.setDocked(!isDocked);
  24546. morph.fold(function () {
  24547. return morphToStatic(component, config);
  24548. }, function (position) {
  24549. return morphToCoord(component, config, position);
  24550. }, function (position) {
  24551. updateVisibility(component, config, state, viewport, true);
  24552. morphToCoord(component, config, position);
  24553. });
  24554. });
  24555. };
  24556. var resetInternal = function (component, config, state) {
  24557. var elem = component.element();
  24558. state.setDocked(false);
  24559. getMorphToOriginal(component, state).each(function (morph) {
  24560. morph.fold(function () {
  24561. return morphToStatic(component, config);
  24562. }, function (position) {
  24563. return morphToCoord(component, config, position);
  24564. }, noop);
  24565. });
  24566. state.setVisible(true);
  24567. config.contextual.each(function (contextInfo) {
  24568. remove$5(elem, [
  24569. contextInfo.fadeInClass,
  24570. contextInfo.fadeOutClass,
  24571. contextInfo.transitionClass
  24572. ]);
  24573. contextInfo.onShow(component);
  24574. });
  24575. refresh$4(component, config, state);
  24576. };
  24577. var refresh$4 = function (component, config, state) {
  24578. if (component.getSystem().isConnected()) {
  24579. refreshInternal(component, config, state);
  24580. }
  24581. };
  24582. var reset = function (component, config, state) {
  24583. if (state.isDocked()) {
  24584. resetInternal(component, config, state);
  24585. }
  24586. };
  24587. var isDocked = function (component, config, state) {
  24588. return state.isDocked();
  24589. };
  24590. var DockingApis = /*#__PURE__*/Object.freeze({
  24591. __proto__: null,
  24592. refresh: refresh$4,
  24593. reset: reset,
  24594. isDocked: isDocked
  24595. });
  24596. var events$f = function (dockInfo, dockState) {
  24597. return derive([
  24598. runOnSource(transitionend(), function (component, simulatedEvent) {
  24599. dockInfo.contextual.each(function (contextInfo) {
  24600. if (has$2(component.element(), contextInfo.transitionClass)) {
  24601. remove$5(component.element(), [
  24602. contextInfo.transitionClass,
  24603. contextInfo.fadeInClass
  24604. ]);
  24605. var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  24606. notify(component);
  24607. }
  24608. simulatedEvent.stop();
  24609. });
  24610. }),
  24611. run(windowScroll(), function (component, _) {
  24612. refresh$4(component, dockInfo, dockState);
  24613. }),
  24614. run(windowResize(), function (component, _) {
  24615. reset(component, dockInfo, dockState);
  24616. })
  24617. ]);
  24618. };
  24619. var ActiveDocking = /*#__PURE__*/Object.freeze({
  24620. __proto__: null,
  24621. events: events$f
  24622. });
  24623. var DockingSchema = [
  24624. optionObjOf('contextual', [
  24625. strictString('fadeInClass'),
  24626. strictString('fadeOutClass'),
  24627. strictString('transitionClass'),
  24628. strictFunction('lazyContext'),
  24629. onHandler('onShow'),
  24630. onHandler('onShown'),
  24631. onHandler('onHide'),
  24632. onHandler('onHidden')
  24633. ]),
  24634. defaultedFunction('lazyViewport', win),
  24635. defaultedArrayOf('modes', [
  24636. 'top',
  24637. 'bottom'
  24638. ], string),
  24639. onHandler('onDocked'),
  24640. onHandler('onUndocked')
  24641. ];
  24642. var init$b = function () {
  24643. var docked = Cell(false);
  24644. var visible = Cell(true);
  24645. var initialBounds = Cell(Option.none());
  24646. var readState = function () {
  24647. return 'docked: ' + docked.get() + ', visible: ' + visible.get();
  24648. };
  24649. return nu$5({
  24650. isDocked: function () {
  24651. return docked.get();
  24652. },
  24653. setDocked: function (state) {
  24654. return docked.set(state);
  24655. },
  24656. getInitialPosition: function () {
  24657. return initialBounds.get();
  24658. },
  24659. setInitialPosition: function (pos) {
  24660. return initialBounds.set(pos);
  24661. },
  24662. isVisible: function () {
  24663. return visible.get();
  24664. },
  24665. setVisible: function (state) {
  24666. return visible.set(state);
  24667. },
  24668. readState: readState
  24669. });
  24670. };
  24671. var DockingState = /*#__PURE__*/Object.freeze({
  24672. __proto__: null,
  24673. init: init$b
  24674. });
  24675. var Docking = create$1({
  24676. fields: DockingSchema,
  24677. name: 'docking',
  24678. active: ActiveDocking,
  24679. apis: DockingApis,
  24680. state: DockingState
  24681. });
  24682. var visibility = {
  24683. fadeInClass: 'tox-editor-dock-fadein',
  24684. fadeOutClass: 'tox-editor-dock-fadeout',
  24685. transitionClass: 'tox-editor-dock-transition'
  24686. };
  24687. var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  24688. var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  24689. var scrollFromBehindHeader = function (e, containerHeader) {
  24690. var doc = owner(containerHeader);
  24691. var viewHeight = doc.dom().defaultView.innerHeight;
  24692. var scrollPos = get$8(doc);
  24693. var markerElement = Element.fromDom(e.elm);
  24694. var markerPos = absolute$1(markerElement);
  24695. var markerHeight = get$6(markerElement);
  24696. var markerTop = markerPos.y();
  24697. var markerBottom = markerTop + markerHeight;
  24698. var editorHeaderPos = absolute(containerHeader);
  24699. var editorHeaderHeight = get$6(containerHeader);
  24700. var editorHeaderTop = editorHeaderPos.top();
  24701. var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  24702. var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top()) < 2;
  24703. var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top() + viewHeight)) < 2;
  24704. if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  24705. to(scrollPos.left(), markerTop - editorHeaderHeight, doc);
  24706. } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  24707. var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  24708. to(scrollPos.left(), y, doc);
  24709. }
  24710. };
  24711. var updateIframeContentFlow = function (header, isToolbarTop) {
  24712. var getOccupiedHeight = function (elm) {
  24713. return getOuter$1(elm) + (parseInt(get$4(elm, 'margin-top'), 10) || 0) + (parseInt(get$4(elm, 'margin-bottom'), 10) || 0);
  24714. };
  24715. var elm = header.element();
  24716. parent(elm).each(function (parentElem) {
  24717. var padding = 'padding-' + (isToolbarTop ? 'top' : 'bottom');
  24718. if (Docking.isDocked(header)) {
  24719. var parentWidth = get$7(parentElem);
  24720. set$2(elm, 'width', parentWidth + 'px');
  24721. set$2(parentElem, padding, getOccupiedHeight(elm) + 'px');
  24722. } else {
  24723. remove$6(elm, 'width');
  24724. remove$6(parentElem, padding);
  24725. }
  24726. });
  24727. };
  24728. var updateSinkVisibility = function (sinkElem, visible) {
  24729. if (visible) {
  24730. remove$4(sinkElem, visibility.fadeOutClass);
  24731. add$3(sinkElem, [
  24732. visibility.transitionClass,
  24733. visibility.fadeInClass
  24734. ]);
  24735. } else {
  24736. remove$4(sinkElem, visibility.fadeInClass);
  24737. add$3(sinkElem, [
  24738. visibility.fadeOutClass,
  24739. visibility.transitionClass
  24740. ]);
  24741. }
  24742. };
  24743. var updateEditorClasses = function (editor, docked) {
  24744. var editorContainer = Element.fromDom(editor.getContainer());
  24745. if (docked) {
  24746. add$2(editorContainer, editorStickyOnClass);
  24747. remove$4(editorContainer, editorStickyOffClass);
  24748. } else {
  24749. add$2(editorContainer, editorStickyOffClass);
  24750. remove$4(editorContainer, editorStickyOnClass);
  24751. }
  24752. };
  24753. var restoreFocus = function (headerElem, focusedElem) {
  24754. var ownerDoc = owner(focusedElem);
  24755. active(ownerDoc).filter(function (activeElm) {
  24756. return !eq(focusedElem, activeElm);
  24757. }).filter(function (activeElm) {
  24758. return eq(activeElm, Element.fromDom(ownerDoc.dom().body)) || contains$2(headerElem, activeElm);
  24759. }).each(function () {
  24760. return focus$1(focusedElem);
  24761. });
  24762. };
  24763. var findFocusedElem = function (rootElm, lazySink) {
  24764. return search(rootElm).orThunk(function () {
  24765. return lazySink().toOption().bind(function (sink) {
  24766. return search(sink.element());
  24767. });
  24768. });
  24769. };
  24770. var setup$4 = function (editor, lazyHeader) {
  24771. if (!editor.inline) {
  24772. if (!isToolbarLocationTop(editor)) {
  24773. editor.on('ResizeEditor', function () {
  24774. lazyHeader().each(Docking.reset);
  24775. });
  24776. }
  24777. editor.on('ResizeWindow ResizeEditor', function () {
  24778. lazyHeader().each(function (header) {
  24779. return updateIframeContentFlow(header, isToolbarLocationTop(editor));
  24780. });
  24781. });
  24782. editor.on('SkinLoaded', function () {
  24783. lazyHeader().each(function (comp) {
  24784. Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  24785. });
  24786. });
  24787. editor.on('FullscreenStateChanged', function () {
  24788. lazyHeader().each(Docking.reset);
  24789. });
  24790. }
  24791. editor.on('AfterScrollIntoView', function (e) {
  24792. lazyHeader().each(function (header) {
  24793. Docking.refresh(header);
  24794. var headerElem = header.element();
  24795. if (isVisible(headerElem)) {
  24796. scrollFromBehindHeader(e, headerElem);
  24797. }
  24798. });
  24799. });
  24800. editor.on('PostRender', function () {
  24801. updateEditorClasses(editor, false);
  24802. });
  24803. };
  24804. var isDocked$1 = function (lazyHeader) {
  24805. return lazyHeader().map(Docking.isDocked).getOr(false);
  24806. };
  24807. var getIframeBehaviours = function (isToolbarTop) {
  24808. var _a;
  24809. return [Receiving.config({
  24810. channels: (_a = {}, _a[toolbarHeightChange()] = {
  24811. onReceive: function (comp) {
  24812. updateIframeContentFlow(comp, isToolbarTop);
  24813. }
  24814. }, _a)
  24815. })];
  24816. };
  24817. var getBehaviours$2 = function (editor, lazySink) {
  24818. var focusedElm = Cell(Option.none());
  24819. var isToolbarTop = isToolbarLocationTop(editor);
  24820. var runOnSinkElement = function (f) {
  24821. lazySink().each(function (sink) {
  24822. return f(sink.element());
  24823. });
  24824. };
  24825. var onDockingSwitch = function (comp) {
  24826. if (!editor.inline) {
  24827. updateIframeContentFlow(comp, isToolbarTop);
  24828. }
  24829. updateEditorClasses(editor, Docking.isDocked(comp));
  24830. comp.getSystem().broadcastOn([repositionPopups()], {});
  24831. lazySink().each(function (sink) {
  24832. return sink.getSystem().broadcastOn([repositionPopups()], {});
  24833. });
  24834. };
  24835. var additionalBehaviours = editor.inline ? [] : getIframeBehaviours(isToolbarTop);
  24836. return __spreadArrays([
  24837. Focusing.config({}),
  24838. Docking.config({
  24839. contextual: __assign({
  24840. lazyContext: function (comp) {
  24841. var headerHeight = getOuter$1(comp.element());
  24842. var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  24843. var box$1 = box(Element.fromDom(container));
  24844. var boxHeight = box$1.height() - headerHeight;
  24845. var topBound = box$1.y() + (isToolbarTop ? 0 : headerHeight);
  24846. return Option.some(bounds$1(box$1.x(), topBound, box$1.width(), boxHeight));
  24847. },
  24848. onShow: function () {
  24849. runOnSinkElement(function (elem) {
  24850. return updateSinkVisibility(elem, true);
  24851. });
  24852. },
  24853. onShown: function (comp) {
  24854. runOnSinkElement(function (elem) {
  24855. return remove$5(elem, [
  24856. visibility.transitionClass,
  24857. visibility.fadeInClass
  24858. ]);
  24859. });
  24860. focusedElm.get().each(function (elem) {
  24861. restoreFocus(comp.element(), elem);
  24862. focusedElm.set(Option.none());
  24863. });
  24864. },
  24865. onHide: function (comp) {
  24866. focusedElm.set(findFocusedElem(comp.element(), lazySink));
  24867. runOnSinkElement(function (elem) {
  24868. return updateSinkVisibility(elem, false);
  24869. });
  24870. },
  24871. onHidden: function () {
  24872. runOnSinkElement(function (elem) {
  24873. return remove$5(elem, [visibility.transitionClass]);
  24874. });
  24875. }
  24876. }, visibility),
  24877. modes: [isToolbarTop ? 'top' : 'bottom'],
  24878. onDocked: onDockingSwitch,
  24879. onUndocked: onDockingSwitch
  24880. })
  24881. ], additionalBehaviours);
  24882. };
  24883. var StickyHeader = /*#__PURE__*/Object.freeze({
  24884. __proto__: null,
  24885. setup: setup$4,
  24886. isDocked: isDocked$1,
  24887. getBehaviours: getBehaviours$2
  24888. });
  24889. var setup$5 = noop;
  24890. var isDocked$2 = never;
  24891. var getBehaviours$3 = constant([]);
  24892. var StaticHeader = /*#__PURE__*/Object.freeze({
  24893. __proto__: null,
  24894. setup: setup$5,
  24895. isDocked: isDocked$2,
  24896. getBehaviours: getBehaviours$3
  24897. });
  24898. var renderHeader = function (spec) {
  24899. var editor = spec.editor;
  24900. var getBehaviours = spec.sticky ? getBehaviours$2 : getBehaviours$3;
  24901. return {
  24902. uid: spec.uid,
  24903. dom: spec.dom,
  24904. components: spec.components,
  24905. behaviours: derive$1(getBehaviours(editor, spec.getSink))
  24906. };
  24907. };
  24908. var factory$g = function (detail, spec) {
  24909. var setMenus = function (comp, menus) {
  24910. var newMenus = map(menus, function (m) {
  24911. var buttonSpec = {
  24912. type: 'menubutton',
  24913. text: m.text,
  24914. fetch: function (callback) {
  24915. callback(m.getItems());
  24916. }
  24917. };
  24918. var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  24919. return formatError(errInfo);
  24920. }).getOrDie();
  24921. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Option.some('menuitem'));
  24922. });
  24923. Replacing.set(comp, newMenus);
  24924. };
  24925. var apis = {
  24926. focus: Keying.focusIn,
  24927. setMenus: setMenus
  24928. };
  24929. return {
  24930. uid: detail.uid,
  24931. dom: detail.dom,
  24932. components: [],
  24933. behaviours: derive$1([
  24934. Replacing.config({}),
  24935. config('menubar-events', [
  24936. runOnAttached(function (component) {
  24937. detail.onSetup(component);
  24938. }),
  24939. run(mouseover(), function (comp, se) {
  24940. descendant$1(comp.element(), '.' + 'tox-mbtn--active').each(function (activeButton) {
  24941. closest$3(se.event().target(), '.' + 'tox-mbtn').each(function (hoveredButton) {
  24942. if (!eq(activeButton, hoveredButton)) {
  24943. comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  24944. comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  24945. Dropdown.expand(hoveredComp);
  24946. Dropdown.close(activeComp);
  24947. Focusing.focus(hoveredComp);
  24948. });
  24949. });
  24950. }
  24951. });
  24952. });
  24953. }),
  24954. run(focusShifted(), function (comp, se) {
  24955. se.event().prevFocus().bind(function (prev) {
  24956. return comp.getSystem().getByDom(prev).toOption();
  24957. }).each(function (prev) {
  24958. se.event().newFocus().bind(function (nu) {
  24959. return comp.getSystem().getByDom(nu).toOption();
  24960. }).each(function (nu) {
  24961. if (Dropdown.isOpen(prev)) {
  24962. Dropdown.expand(nu);
  24963. Dropdown.close(prev);
  24964. }
  24965. });
  24966. });
  24967. })
  24968. ]),
  24969. Keying.config({
  24970. mode: 'flow',
  24971. selector: '.' + 'tox-mbtn',
  24972. onEscape: function (comp) {
  24973. detail.onEscape(comp);
  24974. return Option.some(true);
  24975. }
  24976. }),
  24977. Tabstopping.config({})
  24978. ]),
  24979. apis: apis,
  24980. domModification: { attributes: { role: 'menubar' } }
  24981. };
  24982. };
  24983. var SilverMenubar = single$2({
  24984. factory: factory$g,
  24985. name: 'silver.Menubar',
  24986. configFields: [
  24987. strict$1('dom'),
  24988. strict$1('uid'),
  24989. strict$1('onEscape'),
  24990. strict$1('backstage'),
  24991. defaulted$1('onSetup', noop)
  24992. ],
  24993. apis: {
  24994. focus: function (apis, comp) {
  24995. apis.focus(comp);
  24996. },
  24997. setMenus: function (apis, comp, menus) {
  24998. apis.setMenus(comp, menus);
  24999. }
  25000. }
  25001. });
  25002. var owner$4 = 'container';
  25003. var schema$s = [field$1('slotBehaviours', [])];
  25004. var getPartName$1 = function (name) {
  25005. return '<alloy.field.' + name + '>';
  25006. };
  25007. var sketch$2 = function (sSpec) {
  25008. var parts = function () {
  25009. var record = [];
  25010. var slot = function (name, config) {
  25011. record.push(name);
  25012. return generateOne(owner$4, getPartName$1(name), config);
  25013. };
  25014. return {
  25015. slot: slot,
  25016. record: function () {
  25017. return record;
  25018. }
  25019. };
  25020. }();
  25021. var spec = sSpec(parts);
  25022. var partNames = parts.record();
  25023. var fieldParts = map(partNames, function (n) {
  25024. return required({
  25025. name: n,
  25026. pname: getPartName$1(n)
  25027. });
  25028. });
  25029. return composite(owner$4, schema$s, fieldParts, make$7, spec);
  25030. };
  25031. var make$7 = function (detail, components) {
  25032. var getSlotNames = function (_) {
  25033. return getAllPartNames(detail);
  25034. };
  25035. var getSlot = function (container, key) {
  25036. return getPart(container, detail, key);
  25037. };
  25038. var onSlot = function (f, def) {
  25039. return function (container, key) {
  25040. return getPart(container, detail, key).map(function (slot) {
  25041. return f(slot, key);
  25042. }).getOr(def);
  25043. };
  25044. };
  25045. var onSlots = function (f) {
  25046. return function (container, keys) {
  25047. each(keys, function (key) {
  25048. return f(container, key);
  25049. });
  25050. };
  25051. };
  25052. var doShowing = function (comp, key) {
  25053. return get$2(comp.element(), 'aria-hidden') !== 'true';
  25054. };
  25055. var doShow = function (comp, key) {
  25056. if (!doShowing(comp)) {
  25057. var element = comp.element();
  25058. remove$6(element, 'display');
  25059. remove$1(element, 'aria-hidden');
  25060. emitWith(comp, slotVisibility(), {
  25061. name: key,
  25062. visible: true
  25063. });
  25064. }
  25065. };
  25066. var doHide = function (comp, key) {
  25067. if (doShowing(comp)) {
  25068. var element = comp.element();
  25069. set$2(element, 'display', 'none');
  25070. set$1(element, 'aria-hidden', 'true');
  25071. emitWith(comp, slotVisibility(), {
  25072. name: key,
  25073. visible: false
  25074. });
  25075. }
  25076. };
  25077. var isShowing = onSlot(doShowing, false);
  25078. var hideSlot = onSlot(doHide);
  25079. var hideSlots = onSlots(hideSlot);
  25080. var hideAllSlots = function (container) {
  25081. return hideSlots(container, getSlotNames());
  25082. };
  25083. var showSlot = onSlot(doShow);
  25084. var apis = {
  25085. getSlotNames: getSlotNames,
  25086. getSlot: getSlot,
  25087. isShowing: isShowing,
  25088. hideSlot: hideSlot,
  25089. hideAllSlots: hideAllSlots,
  25090. showSlot: showSlot
  25091. };
  25092. return {
  25093. uid: detail.uid,
  25094. dom: detail.dom,
  25095. components: components,
  25096. behaviours: get$c(detail.slotBehaviours),
  25097. apis: apis
  25098. };
  25099. };
  25100. var slotApis = map$1({
  25101. getSlotNames: function (apis, c) {
  25102. return apis.getSlotNames(c);
  25103. },
  25104. getSlot: function (apis, c, key) {
  25105. return apis.getSlot(c, key);
  25106. },
  25107. isShowing: function (apis, c, key) {
  25108. return apis.isShowing(c, key);
  25109. },
  25110. hideSlot: function (apis, c, key) {
  25111. return apis.hideSlot(c, key);
  25112. },
  25113. hideAllSlots: function (apis, c) {
  25114. return apis.hideAllSlots(c);
  25115. },
  25116. showSlot: function (apis, c, key) {
  25117. return apis.showSlot(c, key);
  25118. }
  25119. }, function (value) {
  25120. return makeApi(value);
  25121. });
  25122. var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch$2 });
  25123. var sidebarSchema = objOf([
  25124. optionString('icon'),
  25125. optionString('tooltip'),
  25126. defaultedFunction('onShow', noop),
  25127. defaultedFunction('onHide', noop),
  25128. defaultedFunction('onSetup', function () {
  25129. return noop;
  25130. })
  25131. ]);
  25132. var createSidebar = function (spec) {
  25133. return asRaw('sidebar', sidebarSchema, spec);
  25134. };
  25135. var setup$6 = function (editor) {
  25136. var sidebars = editor.ui.registry.getAll().sidebars;
  25137. each(keys(sidebars), function (name) {
  25138. var spec = sidebars[name];
  25139. var isActive = function () {
  25140. return Option.from(editor.queryCommandValue('ToggleSidebar')).is(name);
  25141. };
  25142. editor.ui.registry.addToggleButton(name, {
  25143. icon: spec.icon,
  25144. tooltip: spec.tooltip,
  25145. onAction: function (buttonApi) {
  25146. editor.execCommand('ToggleSidebar', false, name);
  25147. buttonApi.setActive(isActive());
  25148. },
  25149. onSetup: function (buttonApi) {
  25150. var handleToggle = function () {
  25151. return buttonApi.setActive(isActive());
  25152. };
  25153. editor.on('ToggleSidebar', handleToggle);
  25154. return function () {
  25155. editor.off('ToggleSidebar', handleToggle);
  25156. };
  25157. }
  25158. });
  25159. });
  25160. };
  25161. var getApi = function (comp) {
  25162. return {
  25163. element: function () {
  25164. return comp.element().dom();
  25165. }
  25166. };
  25167. };
  25168. var makePanels = function (parts, panelConfigs) {
  25169. var specs = map(keys(panelConfigs), function (name) {
  25170. var spec = panelConfigs[name];
  25171. var bridged = getOrDie(createSidebar(spec));
  25172. return {
  25173. name: name,
  25174. getApi: getApi,
  25175. onSetup: bridged.onSetup,
  25176. onShow: bridged.onShow,
  25177. onHide: bridged.onHide
  25178. };
  25179. });
  25180. return map(specs, function (spec) {
  25181. var editorOffCell = Cell(noop);
  25182. return parts.slot(spec.name, {
  25183. dom: {
  25184. tag: 'div',
  25185. classes: ['tox-sidebar__pane']
  25186. },
  25187. behaviours: SimpleBehaviours.unnamedEvents([
  25188. onControlAttached(spec, editorOffCell),
  25189. onControlDetached(spec, editorOffCell),
  25190. run(slotVisibility(), function (sidepanel, se) {
  25191. var data = se.event();
  25192. var optSidePanelSpec = find(specs, function (config) {
  25193. return config.name === data.name();
  25194. });
  25195. optSidePanelSpec.each(function (sidePanelSpec) {
  25196. var handler = data.visible() ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  25197. handler(sidePanelSpec.getApi(sidepanel));
  25198. });
  25199. })
  25200. ])
  25201. });
  25202. });
  25203. };
  25204. var makeSidebar = function (panelConfigs) {
  25205. return SlotContainer.sketch(function (parts) {
  25206. return {
  25207. dom: {
  25208. tag: 'div',
  25209. classes: ['tox-sidebar__pane-container']
  25210. },
  25211. components: makePanels(parts, panelConfigs),
  25212. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  25213. return SlotContainer.hideAllSlots(slotContainer);
  25214. })])
  25215. };
  25216. });
  25217. };
  25218. var setSidebar = function (sidebar, panelConfigs) {
  25219. var optSlider = Composing.getCurrent(sidebar);
  25220. optSlider.each(function (slider) {
  25221. return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  25222. });
  25223. };
  25224. var toggleSidebar = function (sidebar, name) {
  25225. var optSlider = Composing.getCurrent(sidebar);
  25226. optSlider.each(function (slider) {
  25227. var optSlotContainer = Composing.getCurrent(slider);
  25228. optSlotContainer.each(function (slotContainer) {
  25229. if (Sliding.hasGrown(slider)) {
  25230. if (SlotContainer.isShowing(slotContainer, name)) {
  25231. Sliding.shrink(slider);
  25232. } else {
  25233. SlotContainer.hideAllSlots(slotContainer);
  25234. SlotContainer.showSlot(slotContainer, name);
  25235. }
  25236. } else {
  25237. SlotContainer.hideAllSlots(slotContainer);
  25238. SlotContainer.showSlot(slotContainer, name);
  25239. Sliding.grow(slider);
  25240. }
  25241. });
  25242. });
  25243. };
  25244. var whichSidebar = function (sidebar) {
  25245. var optSlider = Composing.getCurrent(sidebar);
  25246. return optSlider.bind(function (slider) {
  25247. var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  25248. if (sidebarOpen) {
  25249. var optSlotContainer = Composing.getCurrent(slider);
  25250. return optSlotContainer.bind(function (slotContainer) {
  25251. return find(SlotContainer.getSlotNames(slotContainer), function (name) {
  25252. return SlotContainer.isShowing(slotContainer, name);
  25253. });
  25254. });
  25255. } else {
  25256. return Option.none();
  25257. }
  25258. });
  25259. };
  25260. var fixSize = generate$1('FixSizeEvent');
  25261. var autoSize = generate$1('AutoSizeEvent');
  25262. var renderSidebar = function (spec) {
  25263. return {
  25264. uid: spec.uid,
  25265. dom: {
  25266. tag: 'div',
  25267. classes: ['tox-sidebar'],
  25268. attributes: { role: 'complementary' }
  25269. },
  25270. components: [{
  25271. dom: {
  25272. tag: 'div',
  25273. classes: ['tox-sidebar__slider']
  25274. },
  25275. components: [],
  25276. behaviours: derive$1([
  25277. Tabstopping.config({}),
  25278. Focusing.config({}),
  25279. Sliding.config({
  25280. dimension: { property: 'width' },
  25281. closedClass: 'tox-sidebar--sliding-closed',
  25282. openClass: 'tox-sidebar--sliding-open',
  25283. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  25284. growingClass: 'tox-sidebar--sliding-growing',
  25285. onShrunk: function (slider) {
  25286. var optSlotContainer = Composing.getCurrent(slider);
  25287. optSlotContainer.each(SlotContainer.hideAllSlots);
  25288. emit(slider, autoSize);
  25289. },
  25290. onGrown: function (slider) {
  25291. emit(slider, autoSize);
  25292. },
  25293. onStartGrow: function (slider) {
  25294. emitWith(slider, fixSize, { width: getRaw(slider.element(), 'width').getOr('') });
  25295. },
  25296. onStartShrink: function (slider) {
  25297. emitWith(slider, fixSize, { width: get$7(slider.element()) + 'px' });
  25298. }
  25299. }),
  25300. Replacing.config({}),
  25301. Composing.config({
  25302. find: function (comp) {
  25303. var children = Replacing.contents(comp);
  25304. return head(children);
  25305. }
  25306. })
  25307. ])
  25308. }],
  25309. behaviours: derive$1([
  25310. ComposingConfigs.childAt(0),
  25311. config('sidebar-sliding-events', [
  25312. run(fixSize, function (comp, se) {
  25313. set$2(comp.element(), 'width', se.event().width());
  25314. }),
  25315. run(autoSize, function (comp, se) {
  25316. remove$6(comp.element(), 'width');
  25317. })
  25318. ])
  25319. ])
  25320. };
  25321. };
  25322. var getAttrs = function (elem) {
  25323. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  25324. return foldl(attributes, function (b, attr) {
  25325. var _a;
  25326. if (attr.name === 'class') {
  25327. return b;
  25328. } else {
  25329. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  25330. }
  25331. }, {});
  25332. };
  25333. var getClasses = function (elem) {
  25334. return Array.prototype.slice.call(elem.dom().classList, 0);
  25335. };
  25336. var fromHtml$2 = function (html) {
  25337. var elem = Element.fromHtml(html);
  25338. var children$1 = children(elem);
  25339. var attrs = getAttrs(elem);
  25340. var classes = getClasses(elem);
  25341. var contents = children$1.length === 0 ? {} : { innerHtml: get$1(elem) };
  25342. return __assign({
  25343. tag: name(elem),
  25344. classes: classes,
  25345. attributes: attrs
  25346. }, contents);
  25347. };
  25348. var renderSpinner = function (providerBackstage) {
  25349. return {
  25350. dom: {
  25351. tag: 'div',
  25352. attributes: { 'aria-label': providerBackstage.translate('Loading...') },
  25353. classes: ['tox-throbber__busy-spinner']
  25354. },
  25355. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }],
  25356. behaviours: derive$1([
  25357. Keying.config({
  25358. mode: 'special',
  25359. onTab: function () {
  25360. return Option.some(true);
  25361. },
  25362. onShiftTab: function () {
  25363. return Option.some(true);
  25364. }
  25365. }),
  25366. Focusing.config({})
  25367. ])
  25368. };
  25369. };
  25370. var toggleThrobber = function (comp, state, providerBackstage) {
  25371. var element = comp.element();
  25372. if (state === true) {
  25373. Replacing.set(comp, [renderSpinner(providerBackstage)]);
  25374. remove$6(element, 'display');
  25375. remove$1(element, 'aria-hidden');
  25376. } else {
  25377. Replacing.set(comp, []);
  25378. set$2(element, 'display', 'none');
  25379. set$1(element, 'aria-hidden', 'true');
  25380. }
  25381. };
  25382. var renderThrobber = function (spec) {
  25383. return {
  25384. uid: spec.uid,
  25385. dom: {
  25386. tag: 'div',
  25387. attributes: { 'aria-hidden': 'true' },
  25388. classes: ['tox-throbber'],
  25389. styles: { display: 'none' }
  25390. },
  25391. behaviours: derive$1([Replacing.config({})]),
  25392. components: []
  25393. };
  25394. };
  25395. var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  25396. var throbberState = Cell(false);
  25397. var timer = Cell(Option.none());
  25398. var toggle = function (state) {
  25399. if (state !== throbberState.get()) {
  25400. toggleThrobber(lazyThrobber(), state, sharedBackstage.providers);
  25401. throbberState.set(state);
  25402. }
  25403. };
  25404. editor.on('ProgressState', function (e) {
  25405. timer.get().each(global$2.clearTimeout);
  25406. if (isNumber(e.time)) {
  25407. var timerId = global$2.setEditorTimeout(editor, function () {
  25408. return toggle(e.state);
  25409. }, e.time);
  25410. timer.set(Option.some(timerId));
  25411. } else {
  25412. toggle(e.state);
  25413. timer.set(Option.none());
  25414. }
  25415. });
  25416. };
  25417. var factory$h = function (detail, components, spec) {
  25418. var apis = {
  25419. getSocket: function (comp) {
  25420. return parts$d.getPart(comp, detail, 'socket');
  25421. },
  25422. setSidebar: function (comp, panelConfigs) {
  25423. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25424. return setSidebar(sidebar, panelConfigs);
  25425. });
  25426. },
  25427. toggleSidebar: function (comp, name) {
  25428. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25429. return toggleSidebar(sidebar, name);
  25430. });
  25431. },
  25432. whichSidebar: function (comp) {
  25433. return parts$d.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  25434. },
  25435. getHeader: function (comp) {
  25436. return parts$d.getPart(comp, detail, 'header');
  25437. },
  25438. getToolbar: function (comp) {
  25439. return parts$d.getPart(comp, detail, 'toolbar');
  25440. },
  25441. setToolbar: function (comp, groups) {
  25442. parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  25443. toolbar.getApis().setGroups(toolbar, groups);
  25444. });
  25445. },
  25446. setToolbars: function (comp, toolbars) {
  25447. parts$d.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  25448. CustomList.setItems(mToolbar, toolbars);
  25449. });
  25450. },
  25451. refreshToolbar: function (comp) {
  25452. var toolbar = parts$d.getPart(comp, detail, 'toolbar');
  25453. toolbar.each(function (toolbar) {
  25454. return toolbar.getApis().refresh(toolbar);
  25455. });
  25456. },
  25457. getThrobber: function (comp) {
  25458. return parts$d.getPart(comp, detail, 'throbber');
  25459. },
  25460. focusToolbar: function (comp) {
  25461. var optToolbar = parts$d.getPart(comp, detail, 'toolbar').orThunk(function () {
  25462. return parts$d.getPart(comp, detail, 'multiple-toolbar');
  25463. });
  25464. optToolbar.each(function (toolbar) {
  25465. Keying.focusIn(toolbar);
  25466. });
  25467. },
  25468. setMenubar: function (comp, menus) {
  25469. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  25470. SilverMenubar.setMenus(menubar, menus);
  25471. });
  25472. },
  25473. focusMenubar: function (comp) {
  25474. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  25475. SilverMenubar.focus(menubar);
  25476. });
  25477. }
  25478. };
  25479. return {
  25480. uid: detail.uid,
  25481. dom: detail.dom,
  25482. components: components,
  25483. apis: apis,
  25484. behaviours: detail.behaviours
  25485. };
  25486. };
  25487. var partMenubar = partType$1.optional({
  25488. factory: SilverMenubar,
  25489. name: 'menubar',
  25490. schema: [strict$1('backstage')]
  25491. });
  25492. var toolbarFactory = function (spec) {
  25493. if (spec.type === ToolbarMode.sliding) {
  25494. return renderSlidingMoreToolbar;
  25495. } else if (spec.type === ToolbarMode.floating) {
  25496. return renderFloatingMoreToolbar;
  25497. } else {
  25498. return renderToolbar;
  25499. }
  25500. };
  25501. var partMultipleToolbar = partType$1.optional({
  25502. factory: {
  25503. sketch: function (spec) {
  25504. return CustomList.sketch({
  25505. uid: spec.uid,
  25506. dom: spec.dom,
  25507. listBehaviours: derive$1([Keying.config({
  25508. mode: 'acyclic',
  25509. selector: '.tox-toolbar'
  25510. })]),
  25511. makeItem: function () {
  25512. return renderToolbar({
  25513. type: spec.type,
  25514. uid: generate$1('multiple-toolbar-item'),
  25515. cyclicKeying: false,
  25516. initGroups: [],
  25517. onEscape: function () {
  25518. return Option.none();
  25519. }
  25520. });
  25521. },
  25522. setupItem: function (mToolbar, tc, data, index) {
  25523. Toolbar.setGroups(tc, data);
  25524. },
  25525. shell: true
  25526. });
  25527. }
  25528. },
  25529. name: 'multiple-toolbar',
  25530. schema: [
  25531. strict$1('dom'),
  25532. strict$1('onEscape')
  25533. ]
  25534. });
  25535. var partToolbar = partType$1.optional({
  25536. factory: {
  25537. sketch: function (spec) {
  25538. var renderer = toolbarFactory(spec);
  25539. var toolbarSpec = {
  25540. type: spec.type,
  25541. uid: spec.uid,
  25542. onEscape: function () {
  25543. spec.onEscape();
  25544. return Option.some(true);
  25545. },
  25546. cyclicKeying: false,
  25547. initGroups: [],
  25548. getSink: spec.getSink,
  25549. backstage: spec.backstage,
  25550. moreDrawerData: {
  25551. lazyToolbar: spec.lazyToolbar,
  25552. lazyMoreButton: spec.lazyMoreButton,
  25553. lazyHeader: spec.lazyHeader
  25554. },
  25555. attributes: spec.attributes
  25556. };
  25557. return renderer(toolbarSpec);
  25558. }
  25559. },
  25560. name: 'toolbar',
  25561. schema: [
  25562. strict$1('dom'),
  25563. strict$1('onEscape'),
  25564. strict$1('getSink')
  25565. ]
  25566. });
  25567. var partHeader = partType$1.optional({
  25568. factory: { sketch: renderHeader },
  25569. name: 'header',
  25570. schema: [strict$1('dom')]
  25571. });
  25572. var partSocket = partType$1.optional({
  25573. name: 'socket',
  25574. schema: [strict$1('dom')]
  25575. });
  25576. var partSidebar = partType$1.optional({
  25577. factory: { sketch: renderSidebar },
  25578. name: 'sidebar',
  25579. schema: [strict$1('dom')]
  25580. });
  25581. var partThrobber = partType$1.optional({
  25582. factory: { sketch: renderThrobber },
  25583. name: 'throbber',
  25584. schema: [strict$1('dom')]
  25585. });
  25586. var OuterContainer = composite$1({
  25587. name: 'OuterContainer',
  25588. factory: factory$h,
  25589. configFields: [
  25590. strict$1('dom'),
  25591. strict$1('behaviours')
  25592. ],
  25593. partFields: [
  25594. partHeader,
  25595. partMenubar,
  25596. partToolbar,
  25597. partMultipleToolbar,
  25598. partSocket,
  25599. partSidebar,
  25600. partThrobber
  25601. ],
  25602. apis: {
  25603. getSocket: function (apis, comp) {
  25604. return apis.getSocket(comp);
  25605. },
  25606. setSidebar: function (apis, comp, panelConfigs) {
  25607. apis.setSidebar(comp, panelConfigs);
  25608. },
  25609. toggleSidebar: function (apis, comp, name) {
  25610. apis.toggleSidebar(comp, name);
  25611. },
  25612. whichSidebar: function (apis, comp) {
  25613. return apis.whichSidebar(comp);
  25614. },
  25615. getHeader: function (apis, comp) {
  25616. return apis.getHeader(comp);
  25617. },
  25618. getToolbar: function (apis, comp) {
  25619. return apis.getToolbar(comp);
  25620. },
  25621. setToolbar: function (apis, comp, grps) {
  25622. var groups = map(grps, function (grp) {
  25623. return renderToolbarGroup(grp);
  25624. });
  25625. apis.setToolbar(comp, groups);
  25626. },
  25627. setToolbars: function (apis, comp, ts) {
  25628. var renderedToolbars = map(ts, function (g) {
  25629. return map(g, renderToolbarGroup);
  25630. });
  25631. apis.setToolbars(comp, renderedToolbars);
  25632. },
  25633. refreshToolbar: function (apis, comp) {
  25634. return apis.refreshToolbar(comp);
  25635. },
  25636. getThrobber: function (apis, comp) {
  25637. return apis.getThrobber(comp);
  25638. },
  25639. setMenubar: function (apis, comp, menus) {
  25640. apis.setMenubar(comp, menus);
  25641. },
  25642. focusMenubar: function (apis, comp) {
  25643. apis.focusMenubar(comp);
  25644. },
  25645. focusToolbar: function (apis, comp) {
  25646. apis.focusToolbar(comp);
  25647. }
  25648. }
  25649. });
  25650. var defaultMenubar = 'file edit view insert format tools table help';
  25651. var defaultMenus = {
  25652. file: {
  25653. title: 'File',
  25654. items: 'newdocument restoredraft | preview | print | deleteallconversations'
  25655. },
  25656. edit: {
  25657. title: 'Edit',
  25658. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  25659. },
  25660. view: {
  25661. title: 'View',
  25662. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  25663. },
  25664. insert: {
  25665. title: 'Insert',
  25666. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  25667. },
  25668. format: {
  25669. title: 'Format',
  25670. items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align | forecolor backcolor | removeformat'
  25671. },
  25672. tools: {
  25673. title: 'Tools',
  25674. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  25675. },
  25676. table: {
  25677. title: 'Table',
  25678. items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  25679. },
  25680. help: {
  25681. title: 'Help',
  25682. items: 'help'
  25683. }
  25684. };
  25685. var make$8 = function (menu, registry, editor) {
  25686. var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  25687. return {
  25688. text: menu.title,
  25689. getItems: function () {
  25690. return bind(menu.items, function (i) {
  25691. var itemName = i.toLowerCase();
  25692. if (itemName.trim().length === 0) {
  25693. return [];
  25694. } else if (exists(removedMenuItems, function (removedMenuItem) {
  25695. return removedMenuItem === itemName;
  25696. })) {
  25697. return [];
  25698. } else if (itemName === 'separator' || itemName === '|') {
  25699. return [{ type: 'separator' }];
  25700. } else if (registry.menuItems[itemName]) {
  25701. return [registry.menuItems[itemName]];
  25702. } else {
  25703. return [];
  25704. }
  25705. });
  25706. }
  25707. };
  25708. };
  25709. var parseItemsString = function (items) {
  25710. if (typeof items === 'string') {
  25711. return items.split(' ');
  25712. }
  25713. return items;
  25714. };
  25715. var identifyMenus = function (editor, registry) {
  25716. var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
  25717. var userDefinedMenus = keys(registry.menus).length > 0;
  25718. var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  25719. var validMenus = filter(menubar, function (menuName) {
  25720. return userDefinedMenus ? registry.menus.hasOwnProperty(menuName) && registry.menus[menuName].hasOwnProperty('items') || defaultMenus.hasOwnProperty(menuName) : defaultMenus.hasOwnProperty(menuName);
  25721. });
  25722. var menus = map(validMenus, function (menuName) {
  25723. var menuData = rawMenuData[menuName];
  25724. return make$8({
  25725. title: menuData.title,
  25726. items: parseItemsString(menuData.items)
  25727. }, registry, editor);
  25728. });
  25729. return filter(menus, function (menu) {
  25730. var isNotSeparator = function (item) {
  25731. return item.type !== 'separator';
  25732. };
  25733. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  25734. });
  25735. };
  25736. var fireSkinLoaded$1 = function (editor) {
  25737. var done = function () {
  25738. editor._skinLoaded = true;
  25739. Events.fireSkinLoaded(editor);
  25740. };
  25741. return function () {
  25742. if (editor.initialized) {
  25743. done();
  25744. } else {
  25745. editor.on('init', done);
  25746. }
  25747. };
  25748. };
  25749. var fireSkinLoadError$1 = function (editor, err) {
  25750. return function () {
  25751. return Events.fireSkinLoadError(editor, { message: err });
  25752. };
  25753. };
  25754. var SkinLoaded = {
  25755. fireSkinLoaded: fireSkinLoaded$1,
  25756. fireSkinLoadError: fireSkinLoadError$1
  25757. };
  25758. var loadSkin = function (isInline, editor) {
  25759. var skinUrl = getSkinUrl(editor);
  25760. var skinUiCss;
  25761. if (skinUrl) {
  25762. skinUiCss = skinUrl + '/skin.min.css';
  25763. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  25764. }
  25765. if (isSkinDisabled(editor) === false && skinUiCss) {
  25766. global$3.DOM.styleSheetLoader.load(skinUiCss, SkinLoaded.fireSkinLoaded(editor), SkinLoaded.fireSkinLoadError(editor, 'Skin could not be loaded'));
  25767. } else {
  25768. SkinLoaded.fireSkinLoaded(editor)();
  25769. }
  25770. };
  25771. var iframe = curry(loadSkin, false);
  25772. var inline = curry(loadSkin, true);
  25773. var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  25774. var comp = uiComponents.outerContainer;
  25775. var toolbarConfig = rawUiConfig.toolbar;
  25776. var toolbarButtonsConfig = rawUiConfig.buttons;
  25777. if (isArrayOf(toolbarConfig, isString)) {
  25778. var toolbars = toolbarConfig.map(function (t) {
  25779. var config = {
  25780. toolbar: t,
  25781. buttons: toolbarButtonsConfig,
  25782. allowToolbarGroups: rawUiConfig.allowToolbarGroups
  25783. };
  25784. return identifyButtons(editor, config, { backstage: backstage }, Option.none());
  25785. });
  25786. OuterContainer.setToolbars(comp, toolbars);
  25787. } else {
  25788. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Option.none()));
  25789. }
  25790. };
  25791. var DOM = global$3.DOM;
  25792. var detection = detect$3();
  25793. var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  25794. var setupEvents = function (editor) {
  25795. var contentWindow = editor.getWin();
  25796. var initialDocEle = editor.getDoc().documentElement;
  25797. var lastWindowDimensions = Cell(Position(contentWindow.innerWidth, contentWindow.innerHeight));
  25798. var lastDocumentDimensions = Cell(Position(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  25799. var resize = function (e) {
  25800. var docEle = editor.getDoc().documentElement;
  25801. var outer = lastWindowDimensions.get();
  25802. var inner = lastDocumentDimensions.get();
  25803. if (outer.left() !== contentWindow.innerWidth || outer.top() !== contentWindow.innerHeight) {
  25804. lastWindowDimensions.set(Position(contentWindow.innerWidth, contentWindow.innerHeight));
  25805. Events.fireResizeContent(editor, e);
  25806. } else if (inner.left() !== docEle.offsetWidth || inner.top() !== docEle.offsetHeight) {
  25807. lastDocumentDimensions.set(Position(docEle.offsetWidth, docEle.offsetHeight));
  25808. Events.fireResizeContent(editor, e);
  25809. }
  25810. };
  25811. var scroll = function (e) {
  25812. return Events.fireScrollContent(editor, e);
  25813. };
  25814. DOM.bind(contentWindow, 'resize', resize);
  25815. DOM.bind(contentWindow, 'scroll', scroll);
  25816. var elementLoad = capture$1(Element.fromDom(editor.getBody()), 'load', resize);
  25817. editor.on('remove', function () {
  25818. elementLoad.unbind();
  25819. DOM.unbind(contentWindow, 'resize', resize);
  25820. DOM.unbind(contentWindow, 'scroll', scroll);
  25821. });
  25822. };
  25823. var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  25824. var lastToolbarWidth = Cell(0);
  25825. iframe(editor);
  25826. attachSystemAfter(Element.fromDom(args.targetNode), uiComponents.mothership);
  25827. attachSystem(body(), uiComponents.uiMothership);
  25828. editor.on('PostRender', function () {
  25829. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  25830. lastToolbarWidth.set(editor.getWin().innerWidth);
  25831. OuterContainer.setMenubar(uiComponents.outerContainer, identifyMenus(editor, rawUiConfig));
  25832. OuterContainer.setSidebar(uiComponents.outerContainer, rawUiConfig.sidebar);
  25833. setupEvents(editor);
  25834. });
  25835. var socket = OuterContainer.getSocket(uiComponents.outerContainer).getOrDie('Could not find expected socket element');
  25836. if (isiOS12 === true) {
  25837. setAll$1(socket.element(), {
  25838. 'overflow': 'scroll',
  25839. '-webkit-overflow-scrolling': 'touch'
  25840. });
  25841. var limit = first(function () {
  25842. editor.fire('ScrollContent');
  25843. }, 20);
  25844. bind$3(socket.element(), 'scroll', limit.throttle);
  25845. }
  25846. setupReadonlyModeSwitch(editor, uiComponents);
  25847. editor.addCommand('ToggleSidebar', function (ui, value) {
  25848. OuterContainer.toggleSidebar(uiComponents.outerContainer, value);
  25849. editor.fire('ToggleSidebar');
  25850. });
  25851. editor.addQueryValueHandler('ToggleSidebar', function () {
  25852. return OuterContainer.whichSidebar(uiComponents.outerContainer);
  25853. });
  25854. var toolbarMode = getToolbarMode(editor);
  25855. var refreshDrawer = function () {
  25856. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  25857. };
  25858. if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
  25859. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  25860. var width = editor.getWin().innerWidth;
  25861. if (width !== lastToolbarWidth.get()) {
  25862. refreshDrawer();
  25863. lastToolbarWidth.set(width);
  25864. }
  25865. });
  25866. }
  25867. return {
  25868. iframeContainer: socket.element().dom(),
  25869. editorContainer: uiComponents.outerContainer.element().dom()
  25870. };
  25871. };
  25872. var Iframe = { render: render };
  25873. var parseToInt = function (val) {
  25874. var re = /^[0-9\.]+(|px)$/i;
  25875. if (re.test('' + val)) {
  25876. return Option.some(parseInt('' + val, 10));
  25877. }
  25878. return Option.none();
  25879. };
  25880. var numToPx = function (val) {
  25881. return isNumber(val) ? val + 'px' : val;
  25882. };
  25883. var calcCappedSize = function (size, minSize, maxSize) {
  25884. var minOverride = minSize.filter(function (min) {
  25885. return size < min;
  25886. });
  25887. var maxOverride = maxSize.filter(function (max) {
  25888. return size > max;
  25889. });
  25890. return minOverride.or(maxOverride).getOr(size);
  25891. };
  25892. var Utils = {
  25893. calcCappedSize: calcCappedSize,
  25894. parseToInt: parseToInt,
  25895. numToPx: numToPx
  25896. };
  25897. var getHeight$1 = function (editor) {
  25898. var baseHeight = getHeightSetting(editor);
  25899. var minHeight = getMinHeightSetting(editor);
  25900. var maxHeight = getMaxHeightSetting(editor);
  25901. return Utils.parseToInt(baseHeight).map(function (height) {
  25902. return Utils.calcCappedSize(height, minHeight, maxHeight);
  25903. });
  25904. };
  25905. var getHeightWithFallback = function (editor) {
  25906. var height = getHeight$1(editor);
  25907. return height.getOr(getHeightSetting(editor));
  25908. };
  25909. var getWidth$1 = function (editor) {
  25910. var baseWidth = getWidthSetting(editor);
  25911. var minWidth = getMinWidthSetting(editor);
  25912. var maxWidth = getMaxWidthSetting(editor);
  25913. return Utils.parseToInt(baseWidth).map(function (width) {
  25914. return Utils.calcCappedSize(width, minWidth, maxWidth);
  25915. });
  25916. };
  25917. var getWidthWithFallback = function (editor) {
  25918. var width = getWidth$1(editor);
  25919. return width.getOr(getWidthSetting(editor));
  25920. };
  25921. var getTargetPosition = function (targetElm, isToolbarTop) {
  25922. var pos = box(targetElm);
  25923. return isToolbarTop ? pos.y() : pos.bottom();
  25924. };
  25925. var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  25926. var floatContainer;
  25927. var DOM = global$3.DOM;
  25928. var useFixedToolbarContainer = useFixedContainer(editor);
  25929. var isSticky = isStickyToolbar(editor);
  25930. var targetElm = Element.fromDom(args.targetNode);
  25931. var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth$1(editor));
  25932. var toolbarMode = getToolbarMode(editor);
  25933. var isSplitFloatingToolbar = toolbarMode === ToolbarMode.floating;
  25934. var isSplitToolbar = toolbarMode === ToolbarMode.sliding || isSplitFloatingToolbar;
  25935. var isToolbarTop = isToolbarLocationTop(editor);
  25936. var prevPos = Cell(getTargetPosition(targetElm, isToolbarTop));
  25937. var visible = Cell(false);
  25938. inline(editor);
  25939. var updateChromePosition = function (toolbar) {
  25940. var offset = isSplitToolbar ? toolbar.fold(function () {
  25941. return 0;
  25942. }, function (tbar) {
  25943. return tbar.components().length > 1 ? get$6(tbar.components()[1].element()) : 0;
  25944. }) : 0;
  25945. var targetBounds = box(targetElm);
  25946. var top = isToolbarTop ? targetBounds.y() - get$6(floatContainer.element()) + offset : targetBounds.bottom();
  25947. setAll$1(uiComponents.outerContainer.element(), {
  25948. position: 'absolute',
  25949. top: Math.round(top) + 'px',
  25950. left: Math.round(targetBounds.x()) + 'px'
  25951. });
  25952. var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
  25953. var bodyMargin = Utils.parseToInt(get$4(body(), 'margin-left')).getOr(0);
  25954. return get$7(body()) - targetBounds.x() + bodyMargin;
  25955. });
  25956. set$2(floatContainer.element(), 'max-width', maxWidth + 'px');
  25957. };
  25958. var updateChromeUi = function (resetDocking) {
  25959. if (resetDocking === void 0) {
  25960. resetDocking = false;
  25961. }
  25962. if (isSplitToolbar) {
  25963. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  25964. }
  25965. if (!useFixedToolbarContainer) {
  25966. var toolbar_1 = OuterContainer.getToolbar(uiComponents.outerContainer);
  25967. updateChromePosition(toolbar_1);
  25968. }
  25969. if (isSticky) {
  25970. resetDocking ? Docking.reset(floatContainer) : Docking.refresh(floatContainer);
  25971. }
  25972. if (isSplitFloatingToolbar) {
  25973. OuterContainer.getToolbar(uiComponents.outerContainer).each(function (toolbar) {
  25974. SplitFloatingToolbar.reposition(toolbar);
  25975. });
  25976. }
  25977. };
  25978. var show = function () {
  25979. visible.set(true);
  25980. set$2(uiComponents.outerContainer.element(), 'display', 'flex');
  25981. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  25982. remove$6(uiComponents.uiMothership.element(), 'display');
  25983. updateChromeUi();
  25984. };
  25985. var hide = function () {
  25986. visible.set(false);
  25987. if (uiComponents.outerContainer) {
  25988. set$2(uiComponents.outerContainer.element(), 'display', 'none');
  25989. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  25990. }
  25991. set$2(uiComponents.uiMothership.element(), 'display', 'none');
  25992. };
  25993. var render = function () {
  25994. if (floatContainer) {
  25995. show();
  25996. return;
  25997. }
  25998. floatContainer = OuterContainer.getHeader(uiComponents.outerContainer).getOrDie();
  25999. var uiContainer = getUiContainer(editor);
  26000. attachSystem(uiContainer, uiComponents.mothership);
  26001. attachSystem(uiContainer, uiComponents.uiMothership);
  26002. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26003. OuterContainer.setMenubar(uiComponents.outerContainer, identifyMenus(editor, rawUiConfig));
  26004. show();
  26005. editor.on('activate', show);
  26006. editor.on('deactivate', hide);
  26007. editor.on('SkinLoaded ResizeWindow', function () {
  26008. if (visible.get()) {
  26009. updateChromeUi(true);
  26010. }
  26011. });
  26012. editor.on('NodeChange keydown', function () {
  26013. global$2.requestAnimationFrame(function () {
  26014. var pos = getTargetPosition(targetElm, isToolbarTop);
  26015. if (visible.get() && pos !== prevPos.get()) {
  26016. updateChromeUi(true);
  26017. prevPos.set(pos);
  26018. }
  26019. });
  26020. });
  26021. editor.nodeChanged();
  26022. };
  26023. editor.on('focus', render);
  26024. editor.on('blur hide', hide);
  26025. editor.on('init', function () {
  26026. if (editor.hasFocus()) {
  26027. render();
  26028. }
  26029. });
  26030. setupReadonlyModeSwitch(editor, uiComponents);
  26031. return { editorContainer: uiComponents.outerContainer.element().dom() };
  26032. };
  26033. var Inline = { render: render$1 };
  26034. var register$5 = function (editor) {
  26035. var alignToolbarButtons = [
  26036. {
  26037. name: 'alignleft',
  26038. text: 'Align left',
  26039. cmd: 'JustifyLeft',
  26040. icon: 'align-left'
  26041. },
  26042. {
  26043. name: 'aligncenter',
  26044. text: 'Align center',
  26045. cmd: 'JustifyCenter',
  26046. icon: 'align-center'
  26047. },
  26048. {
  26049. name: 'alignright',
  26050. text: 'Align right',
  26051. cmd: 'JustifyRight',
  26052. icon: 'align-right'
  26053. },
  26054. {
  26055. name: 'alignjustify',
  26056. text: 'Justify',
  26057. cmd: 'JustifyFull',
  26058. icon: 'align-justify'
  26059. }
  26060. ];
  26061. global$e.each(alignToolbarButtons, function (item) {
  26062. editor.ui.registry.addToggleButton(item.name, {
  26063. tooltip: item.text,
  26064. onAction: function () {
  26065. return editor.execCommand(item.cmd);
  26066. },
  26067. icon: item.icon,
  26068. onSetup: onSetupFormatToggle(editor, item.name)
  26069. });
  26070. });
  26071. var alignNoneToolbarButton = {
  26072. name: 'alignnone',
  26073. text: 'No alignment',
  26074. cmd: 'JustifyNone',
  26075. icon: 'align-none'
  26076. };
  26077. editor.ui.registry.addButton(alignNoneToolbarButton.name, {
  26078. tooltip: alignNoneToolbarButton.text,
  26079. onAction: function () {
  26080. return editor.execCommand(alignNoneToolbarButton.cmd);
  26081. },
  26082. icon: alignNoneToolbarButton.icon
  26083. });
  26084. };
  26085. var AlignmentButtons = { register: register$5 };
  26086. var toggleFormat = function (editor, fmt) {
  26087. return function () {
  26088. editor.execCommand('mceToggleFormat', false, fmt);
  26089. };
  26090. };
  26091. var registerFormatButtons = function (editor) {
  26092. global$e.each([
  26093. {
  26094. name: 'bold',
  26095. text: 'Bold',
  26096. icon: 'bold'
  26097. },
  26098. {
  26099. name: 'italic',
  26100. text: 'Italic',
  26101. icon: 'italic'
  26102. },
  26103. {
  26104. name: 'underline',
  26105. text: 'Underline',
  26106. icon: 'underline'
  26107. },
  26108. {
  26109. name: 'strikethrough',
  26110. text: 'Strikethrough',
  26111. icon: 'strike-through'
  26112. },
  26113. {
  26114. name: 'subscript',
  26115. text: 'Subscript',
  26116. icon: 'subscript'
  26117. },
  26118. {
  26119. name: 'superscript',
  26120. text: 'Superscript',
  26121. icon: 'superscript'
  26122. }
  26123. ], function (btn, idx) {
  26124. editor.ui.registry.addToggleButton(btn.name, {
  26125. tooltip: btn.text,
  26126. icon: btn.icon,
  26127. onSetup: onSetupFormatToggle(editor, btn.name),
  26128. onAction: toggleFormat(editor, btn.name)
  26129. });
  26130. });
  26131. for (var i = 1; i <= 6; i++) {
  26132. var name_1 = 'h' + i;
  26133. editor.ui.registry.addToggleButton(name_1, {
  26134. text: name_1.toUpperCase(),
  26135. tooltip: 'Heading ' + i,
  26136. onSetup: onSetupFormatToggle(editor, name_1),
  26137. onAction: toggleFormat(editor, name_1)
  26138. });
  26139. }
  26140. };
  26141. var registerCommandButtons = function (editor) {
  26142. global$e.each([
  26143. {
  26144. name: 'cut',
  26145. text: 'Cut',
  26146. action: 'Cut',
  26147. icon: 'cut'
  26148. },
  26149. {
  26150. name: 'copy',
  26151. text: 'Copy',
  26152. action: 'Copy',
  26153. icon: 'copy'
  26154. },
  26155. {
  26156. name: 'paste',
  26157. text: 'Paste',
  26158. action: 'Paste',
  26159. icon: 'paste'
  26160. },
  26161. {
  26162. name: 'help',
  26163. text: 'Help',
  26164. action: 'mceHelp',
  26165. icon: 'help'
  26166. },
  26167. {
  26168. name: 'selectall',
  26169. text: 'Select all',
  26170. action: 'SelectAll',
  26171. icon: 'select-all'
  26172. },
  26173. {
  26174. name: 'newdocument',
  26175. text: 'New document',
  26176. action: 'mceNewDocument',
  26177. icon: 'new-document'
  26178. },
  26179. {
  26180. name: 'removeformat',
  26181. text: 'Clear formatting',
  26182. action: 'RemoveFormat',
  26183. icon: 'remove-formatting'
  26184. },
  26185. {
  26186. name: 'remove',
  26187. text: 'Remove',
  26188. action: 'Delete',
  26189. icon: 'remove'
  26190. }
  26191. ], function (btn) {
  26192. editor.ui.registry.addButton(btn.name, {
  26193. tooltip: btn.text,
  26194. icon: btn.icon,
  26195. onAction: function () {
  26196. return editor.execCommand(btn.action);
  26197. }
  26198. });
  26199. });
  26200. };
  26201. var registerCommandToggleButtons = function (editor) {
  26202. global$e.each([{
  26203. name: 'blockquote',
  26204. text: 'Blockquote',
  26205. action: 'mceBlockQuote',
  26206. icon: 'quote'
  26207. }], function (btn) {
  26208. editor.ui.registry.addToggleButton(btn.name, {
  26209. tooltip: btn.text,
  26210. icon: btn.icon,
  26211. onAction: function () {
  26212. return editor.execCommand(btn.action);
  26213. },
  26214. onSetup: onSetupFormatToggle(editor, btn.name)
  26215. });
  26216. });
  26217. };
  26218. var registerButtons = function (editor) {
  26219. registerFormatButtons(editor);
  26220. registerCommandButtons(editor);
  26221. registerCommandToggleButtons(editor);
  26222. };
  26223. var registerMenuItems = function (editor) {
  26224. global$e.each([
  26225. {
  26226. name: 'bold',
  26227. text: 'Bold',
  26228. action: 'Bold',
  26229. icon: 'bold',
  26230. shortcut: 'Meta+B'
  26231. },
  26232. {
  26233. name: 'italic',
  26234. text: 'Italic',
  26235. action: 'Italic',
  26236. icon: 'italic',
  26237. shortcut: 'Meta+I'
  26238. },
  26239. {
  26240. name: 'underline',
  26241. text: 'Underline',
  26242. action: 'Underline',
  26243. icon: 'underline',
  26244. shortcut: 'Meta+U'
  26245. },
  26246. {
  26247. name: 'strikethrough',
  26248. text: 'Strikethrough',
  26249. action: 'Strikethrough',
  26250. icon: 'strike-through',
  26251. shortcut: ''
  26252. },
  26253. {
  26254. name: 'subscript',
  26255. text: 'Subscript',
  26256. action: 'Subscript',
  26257. icon: 'subscript',
  26258. shortcut: ''
  26259. },
  26260. {
  26261. name: 'superscript',
  26262. text: 'Superscript',
  26263. action: 'Superscript',
  26264. icon: 'superscript',
  26265. shortcut: ''
  26266. },
  26267. {
  26268. name: 'removeformat',
  26269. text: 'Clear formatting',
  26270. action: 'RemoveFormat',
  26271. icon: 'remove-formatting',
  26272. shortcut: ''
  26273. },
  26274. {
  26275. name: 'newdocument',
  26276. text: 'New document',
  26277. action: 'mceNewDocument',
  26278. icon: 'new-document',
  26279. shortcut: ''
  26280. },
  26281. {
  26282. name: 'cut',
  26283. text: 'Cut',
  26284. action: 'Cut',
  26285. icon: 'cut',
  26286. shortcut: 'Meta+X'
  26287. },
  26288. {
  26289. name: 'copy',
  26290. text: 'Copy',
  26291. action: 'Copy',
  26292. icon: 'copy',
  26293. shortcut: 'Meta+C'
  26294. },
  26295. {
  26296. name: 'paste',
  26297. text: 'Paste',
  26298. action: 'Paste',
  26299. icon: 'paste',
  26300. shortcut: 'Meta+V'
  26301. },
  26302. {
  26303. name: 'selectall',
  26304. text: 'Select all',
  26305. action: 'SelectAll',
  26306. icon: 'select-all',
  26307. shortcut: 'Meta+A'
  26308. }
  26309. ], function (btn) {
  26310. editor.ui.registry.addMenuItem(btn.name, {
  26311. text: btn.text,
  26312. icon: btn.icon,
  26313. shortcut: btn.shortcut,
  26314. onAction: function () {
  26315. return editor.execCommand(btn.action);
  26316. }
  26317. });
  26318. });
  26319. editor.ui.registry.addMenuItem('codeformat', {
  26320. text: 'Code',
  26321. icon: 'sourcecode',
  26322. onAction: toggleFormat(editor, 'code')
  26323. });
  26324. };
  26325. var register$6 = function (editor) {
  26326. registerButtons(editor);
  26327. registerMenuItems(editor);
  26328. };
  26329. var SimpleControls = { register: register$6 };
  26330. var toggleUndoRedoState = function (api, editor, type) {
  26331. var checkState = function () {
  26332. return editor.undoManager ? editor.undoManager[type]() : false;
  26333. };
  26334. var onUndoStateChange = function () {
  26335. api.setDisabled(editor.readonly || !checkState());
  26336. };
  26337. api.setDisabled(!checkState());
  26338. editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  26339. return function () {
  26340. return editor.off('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  26341. };
  26342. };
  26343. var registerMenuItems$1 = function (editor) {
  26344. editor.ui.registry.addMenuItem('undo', {
  26345. text: 'Undo',
  26346. icon: 'undo',
  26347. shortcut: 'Meta+Z',
  26348. onSetup: function (api) {
  26349. return toggleUndoRedoState(api, editor, 'hasUndo');
  26350. },
  26351. onAction: function () {
  26352. return editor.execCommand('undo');
  26353. }
  26354. });
  26355. editor.ui.registry.addMenuItem('redo', {
  26356. text: 'Redo',
  26357. icon: 'redo',
  26358. shortcut: 'Meta+Y',
  26359. onSetup: function (api) {
  26360. return toggleUndoRedoState(api, editor, 'hasRedo');
  26361. },
  26362. onAction: function () {
  26363. return editor.execCommand('redo');
  26364. }
  26365. });
  26366. };
  26367. var registerButtons$1 = function (editor) {
  26368. editor.ui.registry.addButton('undo', {
  26369. tooltip: 'Undo',
  26370. icon: 'undo',
  26371. onSetup: function (api) {
  26372. return toggleUndoRedoState(api, editor, 'hasUndo');
  26373. },
  26374. onAction: function () {
  26375. return editor.execCommand('undo');
  26376. }
  26377. });
  26378. editor.ui.registry.addButton('redo', {
  26379. tooltip: 'Redo',
  26380. icon: 'redo',
  26381. onSetup: function (api) {
  26382. return toggleUndoRedoState(api, editor, 'hasRedo');
  26383. },
  26384. onAction: function () {
  26385. return editor.execCommand('redo');
  26386. }
  26387. });
  26388. };
  26389. var register$7 = function (editor) {
  26390. registerMenuItems$1(editor);
  26391. registerButtons$1(editor);
  26392. };
  26393. var UndoRedo = { register: register$7 };
  26394. var toggleVisualAidState = function (api, editor) {
  26395. api.setActive(editor.hasVisual);
  26396. var onVisualAid = function (e) {
  26397. api.setActive(e.hasVisual);
  26398. };
  26399. editor.on('VisualAid', onVisualAid);
  26400. return function () {
  26401. return editor.off('VisualAid', onVisualAid);
  26402. };
  26403. };
  26404. var registerMenuItems$2 = function (editor) {
  26405. editor.ui.registry.addToggleMenuItem('visualaid', {
  26406. text: 'Visual aids',
  26407. onSetup: function (api) {
  26408. return toggleVisualAidState(api, editor);
  26409. },
  26410. onAction: function () {
  26411. editor.execCommand('mceToggleVisualAid');
  26412. }
  26413. });
  26414. };
  26415. var registerToolbarButton = function (editor) {
  26416. editor.ui.registry.addButton('visualaid', {
  26417. tooltip: 'Visual aids',
  26418. text: 'Visual aids',
  26419. onAction: function () {
  26420. return editor.execCommand('mceToggleVisualAid');
  26421. }
  26422. });
  26423. };
  26424. var register$8 = function (editor) {
  26425. registerToolbarButton(editor);
  26426. registerMenuItems$2(editor);
  26427. };
  26428. var VisualAid = { register: register$8 };
  26429. var toggleOutdentState = function (api, editor) {
  26430. api.setDisabled(!editor.queryCommandState('outdent'));
  26431. var onNodeChange = function () {
  26432. api.setDisabled(!editor.queryCommandState('outdent'));
  26433. };
  26434. editor.on('NodeChange', onNodeChange);
  26435. return function () {
  26436. return editor.off('NodeChange', onNodeChange);
  26437. };
  26438. };
  26439. var registerButtons$2 = function (editor) {
  26440. editor.ui.registry.addButton('outdent', {
  26441. tooltip: 'Decrease indent',
  26442. icon: 'outdent',
  26443. onSetup: function (api) {
  26444. return toggleOutdentState(api, editor);
  26445. },
  26446. onAction: function () {
  26447. return editor.execCommand('outdent');
  26448. }
  26449. });
  26450. editor.ui.registry.addButton('indent', {
  26451. tooltip: 'Increase indent',
  26452. icon: 'indent',
  26453. onAction: function () {
  26454. return editor.execCommand('indent');
  26455. }
  26456. });
  26457. };
  26458. var register$9 = function (editor) {
  26459. registerButtons$2(editor);
  26460. };
  26461. var IndentOutdent = { register: register$9 };
  26462. var register$a = function (editor, backstage) {
  26463. alignSelectMenu(editor, backstage);
  26464. fontSelectMenu(editor, backstage);
  26465. styleSelectMenu(editor, backstage);
  26466. formatSelectMenu(editor, backstage);
  26467. fontsizeSelectMenu(editor, backstage);
  26468. };
  26469. var ComplexControls = { register: register$a };
  26470. var setup$8 = function (editor, backstage) {
  26471. AlignmentButtons.register(editor);
  26472. SimpleControls.register(editor);
  26473. ComplexControls.register(editor, backstage);
  26474. UndoRedo.register(editor);
  26475. ColorSwatch.register(editor);
  26476. VisualAid.register(editor);
  26477. IndentOutdent.register(editor);
  26478. };
  26479. var FormatControls = { setup: setup$8 };
  26480. var nu$d = function (x, y) {
  26481. return {
  26482. anchor: 'makeshift',
  26483. x: x,
  26484. y: y
  26485. };
  26486. };
  26487. var transpose$1 = function (pos, dx, dy) {
  26488. return nu$d(pos.x + dx, pos.y + dy);
  26489. };
  26490. var isTouchEvent$1 = function (e) {
  26491. return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  26492. };
  26493. var fromPageXY = function (e) {
  26494. if (isTouchEvent$1(e)) {
  26495. var touch = e.touches[0];
  26496. return nu$d(touch.pageX, touch.pageY);
  26497. } else {
  26498. return nu$d(e.pageX, e.pageY);
  26499. }
  26500. };
  26501. var fromClientXY = function (e) {
  26502. if (isTouchEvent$1(e)) {
  26503. var touch = e.touches[0];
  26504. return nu$d(touch.clientX, touch.clientY);
  26505. } else {
  26506. return nu$d(e.clientX, e.clientY);
  26507. }
  26508. };
  26509. var transposeContentAreaContainer = function (element, pos) {
  26510. var containerPos = global$3.DOM.getPos(element);
  26511. return transpose$1(pos, containerPos.x, containerPos.y);
  26512. };
  26513. var getPointAnchor = function (editor, e) {
  26514. if (e.type === 'contextmenu' || e.type === 'longpress') {
  26515. if (editor.inline) {
  26516. return fromPageXY(e);
  26517. } else {
  26518. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  26519. }
  26520. } else {
  26521. return getSelectionAnchor(editor);
  26522. }
  26523. };
  26524. var getSelectionAnchor = function (editor) {
  26525. return {
  26526. anchor: 'selection',
  26527. root: Element.fromDom(editor.selection.getNode())
  26528. };
  26529. };
  26530. var getNodeAnchor$1 = function (editor) {
  26531. return {
  26532. anchor: 'node',
  26533. node: Option.some(Element.fromDom(editor.selection.getNode())),
  26534. root: Element.fromDom(editor.getBody())
  26535. };
  26536. };
  26537. var getAnchorSpec = function (editor, e, isTriggeredByKeyboardEvent) {
  26538. return isTriggeredByKeyboardEvent ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
  26539. };
  26540. var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  26541. var items = buildMenu();
  26542. var anchorSpec = getAnchorSpec(editor, e, isTriggeredByKeyboardEvent);
  26543. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  26544. e.preventDefault();
  26545. InlineView.showMenuAt(contextmenu, anchorSpec, {
  26546. menu: { markers: markers$1('normal') },
  26547. data: menuData
  26548. });
  26549. });
  26550. };
  26551. var layouts = {
  26552. onLtr: function () {
  26553. return [
  26554. south$1,
  26555. southeast$1,
  26556. southwest$1,
  26557. northeast$1,
  26558. northwest$1,
  26559. north$1,
  26560. north$3,
  26561. south$3,
  26562. northeast$3,
  26563. southeast$3,
  26564. northwest$3,
  26565. southwest$3
  26566. ];
  26567. },
  26568. onRtl: function () {
  26569. return [
  26570. south$1,
  26571. southwest$1,
  26572. southeast$1,
  26573. northwest$1,
  26574. northeast$1,
  26575. north$1,
  26576. north$3,
  26577. south$3,
  26578. northwest$3,
  26579. southwest$3,
  26580. northeast$3,
  26581. southeast$3
  26582. ];
  26583. }
  26584. };
  26585. var bubbleSize$1 = 12;
  26586. var bubbleAlignments$2 = {
  26587. valignCentre: [],
  26588. alignCentre: [],
  26589. alignLeft: ['tox-pop--align-left'],
  26590. alignRight: ['tox-pop--align-right'],
  26591. right: ['tox-pop--right'],
  26592. left: ['tox-pop--left'],
  26593. bottom: ['tox-pop--bottom'],
  26594. top: ['tox-pop--top']
  26595. };
  26596. var isTouchWithinSelection = function (editor, e) {
  26597. var selection = editor.selection;
  26598. if (selection.isCollapsed() || e.touches.length < 1) {
  26599. return false;
  26600. } else {
  26601. var touch_1 = e.touches[0];
  26602. var rng = selection.getRng();
  26603. var rngRectOpt = getFirstRect$1(editor.getWin(), Selection.domRange(rng));
  26604. return rngRectOpt.exists(function (rngRect) {
  26605. return rngRect.left() <= touch_1.clientX && rngRect.right() >= touch_1.clientX && rngRect.top() <= touch_1.clientY && rngRect.bottom() >= touch_1.clientY;
  26606. });
  26607. }
  26608. };
  26609. var getAnchorSpec$1 = function (editor, isTriggeredByKeyboardEvent, e) {
  26610. var anchorSpec = isTriggeredByKeyboardEvent ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
  26611. return __assign({
  26612. bubble: nu$8(0, bubbleSize$1, bubbleAlignments$2),
  26613. layouts: layouts,
  26614. overrides: {
  26615. maxWidthFunction: expandable$1(),
  26616. maxHeightFunction: expandable()
  26617. }
  26618. }, anchorSpec);
  26619. };
  26620. var setupiOSOverrides = function (editor) {
  26621. var originalSelection = editor.selection.getRng();
  26622. var selectionReset = function () {
  26623. global$2.setEditorTimeout(editor, function () {
  26624. editor.selection.setRng(originalSelection);
  26625. }, 10);
  26626. unbindEventListeners();
  26627. };
  26628. editor.once('touchend', selectionReset);
  26629. var preventMousedown = function (e) {
  26630. e.preventDefault();
  26631. e.stopImmediatePropagation();
  26632. };
  26633. editor.on('mousedown', preventMousedown, true);
  26634. var clearSelectionReset = function () {
  26635. return unbindEventListeners();
  26636. };
  26637. editor.once('longpresscancel', clearSelectionReset);
  26638. var unbindEventListeners = function () {
  26639. editor.off('touchend', selectionReset);
  26640. editor.off('longpresscancel', clearSelectionReset);
  26641. editor.off('mousedown', preventMousedown);
  26642. };
  26643. };
  26644. var show = function (editor, e, items, backstage, contextmenu, isTriggeredByKeyboardEvent, highlightImmediately) {
  26645. var anchorSpec = getAnchorSpec$1(editor, isTriggeredByKeyboardEvent, e);
  26646. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  26647. e.preventDefault();
  26648. InlineView.showMenuWithinBounds(contextmenu, anchorSpec, {
  26649. menu: {
  26650. markers: markers$1('normal'),
  26651. highlightImmediately: highlightImmediately
  26652. },
  26653. data: menuData,
  26654. type: 'horizontal'
  26655. }, function () {
  26656. return Option.some(getContextToolbarBounds(editor));
  26657. });
  26658. editor.fire(hideContextToolbarEvent);
  26659. });
  26660. };
  26661. var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  26662. var detection = detect$3();
  26663. var isiOS = detection.os.isiOS();
  26664. var isOSX = detection.os.isOSX();
  26665. var isAndroid = detection.os.isAndroid();
  26666. var isTouch = detection.deviceType.isTouch();
  26667. var shouldHighlightImmediately = function () {
  26668. return !(isAndroid || isiOS || isOSX && isTouch);
  26669. };
  26670. var open = function () {
  26671. var items = buildMenu();
  26672. show(editor, e, items, backstage, contextmenu, isTriggeredByKeyboardEvent, shouldHighlightImmediately());
  26673. };
  26674. if ((isOSX || isiOS) && !isTriggeredByKeyboardEvent) {
  26675. var openiOS_1 = function () {
  26676. setupiOSOverrides(editor);
  26677. open();
  26678. };
  26679. if (isTouchWithinSelection(editor, e)) {
  26680. openiOS_1();
  26681. } else {
  26682. editor.once('selectionchange', openiOS_1);
  26683. editor.once('touchend', function () {
  26684. return editor.off('selectionchange', openiOS_1);
  26685. });
  26686. }
  26687. } else {
  26688. if (isAndroid && !isTriggeredByKeyboardEvent) {
  26689. editor.selection.setCursorLocation(e.target, 0);
  26690. }
  26691. open();
  26692. }
  26693. };
  26694. var patchPipeConfig = function (config) {
  26695. return typeof config === 'string' ? config.split(/[ ,]/) : config;
  26696. };
  26697. var shouldNeverUseNative = function (editor) {
  26698. return editor.settings.contextmenu_never_use_native || false;
  26699. };
  26700. var getMenuItems = function (editor, name, defaultItems) {
  26701. var contextMenus = editor.ui.registry.getAll().contextMenus;
  26702. return get(editor.settings, name).map(patchPipeConfig).getOrThunk(function () {
  26703. return filter(patchPipeConfig(defaultItems), function (item) {
  26704. return has(contextMenus, item);
  26705. });
  26706. });
  26707. };
  26708. var isContextMenuDisabled = function (editor) {
  26709. return editor.getParam('contextmenu') === false;
  26710. };
  26711. var getContextMenu = function (editor) {
  26712. return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  26713. };
  26714. var Settings$1 = {
  26715. shouldNeverUseNative: shouldNeverUseNative,
  26716. getContextMenu: getContextMenu,
  26717. isContextMenuDisabled: isContextMenuDisabled
  26718. };
  26719. var isSeparator$1 = function (item) {
  26720. return isString(item) ? item === '|' : item.type === 'separator';
  26721. };
  26722. var separator$3 = { type: 'separator' };
  26723. var makeContextItem = function (item) {
  26724. if (isString(item)) {
  26725. return item;
  26726. } else {
  26727. switch (item.type) {
  26728. case 'separator':
  26729. return separator$3;
  26730. case 'submenu':
  26731. return {
  26732. type: 'nestedmenuitem',
  26733. text: item.text,
  26734. icon: item.icon,
  26735. getSubmenuItems: function () {
  26736. var items = item.getSubmenuItems();
  26737. if (isString(items)) {
  26738. return items;
  26739. } else {
  26740. return map(items, makeContextItem);
  26741. }
  26742. }
  26743. };
  26744. default:
  26745. return {
  26746. type: 'menuitem',
  26747. text: item.text,
  26748. icon: item.icon,
  26749. onAction: noarg(item.onAction)
  26750. };
  26751. }
  26752. }
  26753. };
  26754. var addContextMenuGroup = function (xs, groupItems) {
  26755. if (groupItems.length === 0) {
  26756. return xs;
  26757. }
  26758. var lastMenuItem = last(xs).filter(function (item) {
  26759. return !isSeparator$1(item);
  26760. });
  26761. var before = lastMenuItem.fold(function () {
  26762. return [];
  26763. }, function (_) {
  26764. return [separator$3];
  26765. });
  26766. return xs.concat(before).concat(groupItems).concat([separator$3]);
  26767. };
  26768. var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  26769. var sections = foldl(menuConfig, function (acc, name) {
  26770. if (has(contextMenus, name)) {
  26771. var items = contextMenus[name].update(selectedElement);
  26772. if (isString(items)) {
  26773. return addContextMenuGroup(acc, items.split(' '));
  26774. } else if (items.length > 0) {
  26775. var allItems = map(items, makeContextItem);
  26776. return addContextMenuGroup(acc, allItems);
  26777. } else {
  26778. return acc;
  26779. }
  26780. } else {
  26781. return acc.concat([name]);
  26782. }
  26783. }, []);
  26784. if (sections.length > 0 && isSeparator$1(sections[sections.length - 1])) {
  26785. sections.pop();
  26786. }
  26787. return sections;
  26788. };
  26789. var isNativeOverrideKeyEvent = function (editor, e) {
  26790. return e.ctrlKey && !Settings$1.shouldNeverUseNative(editor);
  26791. };
  26792. var isTriggeredByKeyboard = function (editor, e) {
  26793. return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  26794. };
  26795. var setup$9 = function (editor, lazySink, backstage) {
  26796. var detection = detect$3();
  26797. var isTouch = detection.deviceType.isTouch;
  26798. var contextmenu = build$1(InlineView.sketch({
  26799. dom: { tag: 'div' },
  26800. lazySink: lazySink,
  26801. onEscape: function () {
  26802. return editor.focus();
  26803. },
  26804. onShow: function () {
  26805. return backstage.setContextMenuState(true);
  26806. },
  26807. onHide: function () {
  26808. return backstage.setContextMenuState(false);
  26809. },
  26810. fireDismissalEventInstead: {},
  26811. inlineBehaviours: derive$1([config('dismissContextMenu', [run(dismissRequested(), function (comp, se) {
  26812. Sandboxing.close(comp);
  26813. editor.focus();
  26814. })])])
  26815. }));
  26816. var hideContextMenu = function (_e) {
  26817. return InlineView.hide(contextmenu);
  26818. };
  26819. var showContextMenu = function (e) {
  26820. if (Settings$1.shouldNeverUseNative(editor)) {
  26821. e.preventDefault();
  26822. }
  26823. if (isNativeOverrideKeyEvent(editor, e) || Settings$1.isContextMenuDisabled(editor)) {
  26824. return;
  26825. }
  26826. var isTriggeredByKeyboardEvent = isTriggeredByKeyboard(editor, e);
  26827. var buildMenu = function () {
  26828. var selectedElement = isTriggeredByKeyboardEvent ? editor.selection.getStart(true) : e.target;
  26829. var registry = editor.ui.registry.getAll();
  26830. var menuConfig = Settings$1.getContextMenu(editor);
  26831. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  26832. };
  26833. var initAndShow$2 = isTouch() ? initAndShow$1 : initAndShow;
  26834. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent);
  26835. };
  26836. editor.on('init', function () {
  26837. var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  26838. editor.on(hideEvents, hideContextMenu);
  26839. editor.on('longpress contextmenu', showContextMenu);
  26840. });
  26841. };
  26842. var adt$c = Adt.generate([
  26843. {
  26844. offset: [
  26845. 'x',
  26846. 'y'
  26847. ]
  26848. },
  26849. {
  26850. absolute: [
  26851. 'x',
  26852. 'y'
  26853. ]
  26854. },
  26855. {
  26856. fixed: [
  26857. 'x',
  26858. 'y'
  26859. ]
  26860. }
  26861. ]);
  26862. var subtract = function (change) {
  26863. return function (point) {
  26864. return point.translate(-change.left(), -change.top());
  26865. };
  26866. };
  26867. var add$4 = function (change) {
  26868. return function (point) {
  26869. return point.translate(change.left(), change.top());
  26870. };
  26871. };
  26872. var transform$1 = function (changes) {
  26873. return function (x, y) {
  26874. return foldl(changes, function (rest, f) {
  26875. return f(rest);
  26876. }, Position(x, y));
  26877. };
  26878. };
  26879. var asFixed = function (coord, scroll, origin) {
  26880. return coord.fold(transform$1([
  26881. add$4(origin),
  26882. subtract(scroll)
  26883. ]), transform$1([subtract(scroll)]), transform$1([]));
  26884. };
  26885. var asAbsolute = function (coord, scroll, origin) {
  26886. return coord.fold(transform$1([add$4(origin)]), transform$1([]), transform$1([add$4(scroll)]));
  26887. };
  26888. var asOffset = function (coord, scroll, origin) {
  26889. return coord.fold(transform$1([]), transform$1([subtract(origin)]), transform$1([
  26890. add$4(scroll),
  26891. subtract(origin)
  26892. ]));
  26893. };
  26894. var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  26895. var a1 = asAbsolute(coord1, scroll, origin);
  26896. var a2 = asAbsolute(coord2, scroll, origin);
  26897. return Math.abs(a1.left() - a2.left()) <= xRange && Math.abs(a1.top() - a2.top()) <= yRange;
  26898. };
  26899. var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  26900. var a1 = asAbsolute(coord1, scroll, origin);
  26901. var a2 = asAbsolute(coord2, scroll, origin);
  26902. var left = Math.abs(a1.left() - a2.left());
  26903. var top = Math.abs(a1.top() - a2.top());
  26904. return Position(left, top);
  26905. };
  26906. var toStyles = function (coord, scroll, origin) {
  26907. var stylesOpt = coord.fold(function (x, y) {
  26908. return {
  26909. position: Option.some('absolute'),
  26910. left: Option.some(x + 'px'),
  26911. top: Option.some(y + 'px')
  26912. };
  26913. }, function (x, y) {
  26914. return {
  26915. position: Option.some('absolute'),
  26916. left: Option.some(x - origin.left() + 'px'),
  26917. top: Option.some(y - origin.top() + 'px')
  26918. };
  26919. }, function (x, y) {
  26920. return {
  26921. position: Option.some('fixed'),
  26922. left: Option.some(x + 'px'),
  26923. top: Option.some(y + 'px')
  26924. };
  26925. });
  26926. return __assign({
  26927. right: Option.none(),
  26928. bottom: Option.none()
  26929. }, stylesOpt);
  26930. };
  26931. var translate$2 = function (coord, deltaX, deltaY) {
  26932. return coord.fold(function (x, y) {
  26933. return offset(x + deltaX, y + deltaY);
  26934. }, function (x, y) {
  26935. return absolute$3(x + deltaX, y + deltaY);
  26936. }, function (x, y) {
  26937. return fixed$1(x + deltaX, y + deltaY);
  26938. });
  26939. };
  26940. var absorb = function (partialCoord, originalCoord, scroll, origin) {
  26941. var absorbOne = function (stencil, nu) {
  26942. return function (optX, optY) {
  26943. var original = stencil(originalCoord, scroll, origin);
  26944. return nu(optX.getOr(original.left()), optY.getOr(original.top()));
  26945. };
  26946. };
  26947. return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute$3), absorbOne(asFixed, fixed$1));
  26948. };
  26949. var offset = adt$c.offset;
  26950. var absolute$3 = adt$c.absolute;
  26951. var fixed$1 = adt$c.fixed;
  26952. var get$e = function (component, snapsInfo) {
  26953. var element = component.element();
  26954. var x = parseInt(get$2(element, snapsInfo.leftAttr), 10);
  26955. var y = parseInt(get$2(element, snapsInfo.topAttr), 10);
  26956. return isNaN(x) || isNaN(y) ? Option.none() : Option.some(Position(x, y));
  26957. };
  26958. var set$8 = function (component, snapsInfo, pt) {
  26959. var element = component.element();
  26960. set$1(element, snapsInfo.leftAttr, pt.left() + 'px');
  26961. set$1(element, snapsInfo.topAttr, pt.top() + 'px');
  26962. };
  26963. var clear = function (component, snapsInfo) {
  26964. var element = component.element();
  26965. remove$1(element, snapsInfo.leftAttr);
  26966. remove$1(element, snapsInfo.topAttr);
  26967. };
  26968. var getCoords = function (component, snapInfo, coord, delta) {
  26969. return get$e(component, snapInfo).fold(function () {
  26970. return coord;
  26971. }, function (fixed) {
  26972. return fixed$1(fixed.left() + delta.left(), fixed.top() + delta.top());
  26973. });
  26974. };
  26975. var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  26976. var newCoord = getCoords(component, snapInfo, coord, delta);
  26977. var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  26978. var fixedCoord = asFixed(newCoord, scroll, origin);
  26979. set$8(component, snapInfo, fixedCoord);
  26980. return snap.fold(function () {
  26981. return {
  26982. coord: fixed$1(fixedCoord.left(), fixedCoord.top()),
  26983. extra: Option.none()
  26984. };
  26985. }, function (spanned) {
  26986. return {
  26987. coord: spanned.output(),
  26988. extra: spanned.extra()
  26989. };
  26990. });
  26991. };
  26992. var stopDrag = function (component, snapInfo) {
  26993. clear(component, snapInfo);
  26994. };
  26995. var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  26996. return findMap(snaps, function (snap) {
  26997. var sensor = snap.sensor();
  26998. var inRange = withinRange(newCoord, sensor, snap.range().left(), snap.range().top(), scroll, origin);
  26999. return inRange ? Option.some({
  27000. output: constant(absorb(snap.output(), newCoord, scroll, origin)),
  27001. extra: snap.extra
  27002. }) : Option.none();
  27003. });
  27004. };
  27005. var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  27006. var snaps = snapInfo.getSnapPoints(component);
  27007. var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  27008. return matchSnap.orThunk(function () {
  27009. var bestSnap = foldl(snaps, function (acc, snap) {
  27010. var sensor = snap.sensor();
  27011. var deltas = getDeltas(newCoord, sensor, snap.range().left(), snap.range().top(), scroll, origin);
  27012. return acc.deltas.fold(function () {
  27013. return {
  27014. deltas: Option.some(deltas),
  27015. snap: Option.some(snap)
  27016. };
  27017. }, function (bestDeltas) {
  27018. var currAvg = (deltas.left() + deltas.top()) / 2;
  27019. var bestAvg = (bestDeltas.left() + bestDeltas.top()) / 2;
  27020. if (currAvg <= bestAvg) {
  27021. return {
  27022. deltas: Option.some(deltas),
  27023. snap: Option.some(snap)
  27024. };
  27025. } else {
  27026. return acc;
  27027. }
  27028. });
  27029. }, {
  27030. deltas: Option.none(),
  27031. snap: Option.none()
  27032. });
  27033. return bestSnap.snap.map(function (snap) {
  27034. return {
  27035. output: constant(absorb(snap.output(), newCoord, scroll, origin)),
  27036. extra: snap.extra
  27037. };
  27038. });
  27039. });
  27040. };
  27041. var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  27042. var snaps = snapInfo.getSnapPoints(component);
  27043. return findMatchingSnap(snaps, newCoord, scroll, origin);
  27044. };
  27045. var snapTo = function (snap, scroll, origin) {
  27046. return {
  27047. coord: absorb(snap.output(), snap.output(), scroll, origin),
  27048. extra: snap.extra()
  27049. };
  27050. };
  27051. var snapTo$1 = function (component, dragConfig, _state, snap) {
  27052. var target = dragConfig.getTarget(component.element());
  27053. if (dragConfig.repositionTarget) {
  27054. var doc = owner(component.element());
  27055. var scroll = get$8(doc);
  27056. var origin = getOrigin(target);
  27057. var snapPin = snapTo(snap, scroll, origin);
  27058. var styles = toStyles(snapPin.coord, scroll, origin);
  27059. setOptions(target, styles);
  27060. }
  27061. };
  27062. var DraggingApis = /*#__PURE__*/Object.freeze({
  27063. __proto__: null,
  27064. snapTo: snapTo$1
  27065. });
  27066. var initialAttribute = 'data-initial-z-index';
  27067. var resetZIndex = function (blocker) {
  27068. parent(blocker.element()).filter(isElement).each(function (root) {
  27069. var initZIndex = get$2(root, initialAttribute);
  27070. if (has$1(root, initialAttribute)) {
  27071. set$2(root, 'z-index', initZIndex);
  27072. } else {
  27073. remove$6(root, 'z-index');
  27074. }
  27075. remove$1(root, initialAttribute);
  27076. });
  27077. };
  27078. var changeZIndex = function (blocker) {
  27079. parent(blocker.element()).filter(isElement).each(function (root) {
  27080. getRaw(root, 'z-index').each(function (zindex) {
  27081. set$1(root, initialAttribute, zindex);
  27082. });
  27083. set$2(root, 'z-index', get$4(blocker.element(), 'z-index'));
  27084. });
  27085. };
  27086. var instigate = function (anyComponent, blocker) {
  27087. anyComponent.getSystem().addToGui(blocker);
  27088. changeZIndex(blocker);
  27089. };
  27090. var discard = function (blocker) {
  27091. resetZIndex(blocker);
  27092. blocker.getSystem().removeFromGui(blocker);
  27093. };
  27094. var createComponent = function (component, blockerClass, blockerEvents) {
  27095. return component.getSystem().build(Container.sketch({
  27096. dom: {
  27097. styles: {
  27098. 'left': '0px',
  27099. 'top': '0px',
  27100. 'width': '100%',
  27101. 'height': '100%',
  27102. 'position': 'fixed',
  27103. 'z-index': '1000000000000000'
  27104. },
  27105. classes: [blockerClass]
  27106. },
  27107. events: blockerEvents
  27108. }));
  27109. };
  27110. var SnapSchema = optionObjOf('snaps', [
  27111. strict$1('getSnapPoints'),
  27112. onHandler('onSensor'),
  27113. strict$1('leftAttr'),
  27114. strict$1('topAttr'),
  27115. defaulted$1('lazyViewport', win),
  27116. defaulted$1('mustSnap', false)
  27117. ]);
  27118. var schema$t = [
  27119. defaulted$1('useFixed', never),
  27120. strict$1('blockerClass'),
  27121. defaulted$1('getTarget', identity),
  27122. defaulted$1('onDrag', noop),
  27123. defaulted$1('repositionTarget', true),
  27124. defaulted$1('onDrop', noop),
  27125. defaultedFunction('getBounds', win),
  27126. SnapSchema
  27127. ];
  27128. var getCurrentCoord = function (target) {
  27129. return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
  27130. var nu = position === 'fixed' ? fixed$1 : offset;
  27131. return nu(parseInt(left, 10), parseInt(top, 10));
  27132. }).getOrThunk(function () {
  27133. var location = absolute(target);
  27134. return absolute$3(location.left(), location.top());
  27135. });
  27136. };
  27137. var clampCoords = function (component, coords, scroll, origin, startData) {
  27138. var bounds = startData.bounds;
  27139. var absoluteCoord = asAbsolute(coords, scroll, origin);
  27140. var newX = clamp(absoluteCoord.left(), bounds.x(), bounds.x() + bounds.width() - startData.width);
  27141. var newY = clamp(absoluteCoord.top(), bounds.y(), bounds.y() + bounds.height() - startData.height);
  27142. var newCoords = absolute$3(newX, newY);
  27143. return coords.fold(function () {
  27144. var offset$1 = asOffset(newCoords, scroll, origin);
  27145. return offset(offset$1.left(), offset$1.top());
  27146. }, function () {
  27147. return newCoords;
  27148. }, function () {
  27149. var fixed = asFixed(newCoords, scroll, origin);
  27150. return fixed$1(fixed.left(), fixed.top());
  27151. });
  27152. };
  27153. var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  27154. var newCoord = optSnaps.fold(function () {
  27155. var translated = translate$2(currentCoord, delta.left(), delta.top());
  27156. var fixedCoord = asFixed(translated, scroll, origin);
  27157. return fixed$1(fixedCoord.left(), fixedCoord.top());
  27158. }, function (snapInfo) {
  27159. var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  27160. snapping.extra.each(function (extra) {
  27161. snapInfo.onSensor(component, extra);
  27162. });
  27163. return snapping.coord;
  27164. });
  27165. return clampCoords(component, newCoord, scroll, origin, startData);
  27166. };
  27167. var dragBy = function (component, dragConfig, startData, delta) {
  27168. var target = dragConfig.getTarget(component.element());
  27169. if (dragConfig.repositionTarget) {
  27170. var doc = owner(component.element());
  27171. var scroll = get$8(doc);
  27172. var origin = getOrigin(target);
  27173. var currentCoord = getCurrentCoord(target);
  27174. var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll, origin, delta, startData);
  27175. var styles = toStyles(newCoord, scroll, origin);
  27176. setOptions(target, styles);
  27177. }
  27178. dragConfig.onDrag(component, target, delta);
  27179. };
  27180. var calcStartData = function (dragConfig, comp) {
  27181. return {
  27182. bounds: dragConfig.getBounds(),
  27183. height: getOuter$1(comp.element()),
  27184. width: getOuter$2(comp.element())
  27185. };
  27186. };
  27187. var move$1 = function (component, dragConfig, dragState, dragMode, event) {
  27188. var delta = dragState.update(dragMode, event);
  27189. var dragStartData = dragState.getStartData().getOrThunk(function () {
  27190. return calcStartData(dragConfig, component);
  27191. });
  27192. delta.each(function (dlt) {
  27193. dragBy(component, dragConfig, dragStartData, dlt);
  27194. });
  27195. };
  27196. var stop = function (component, blocker, dragConfig, dragState) {
  27197. blocker.each(discard);
  27198. dragConfig.snaps.each(function (snapInfo) {
  27199. stopDrag(component, snapInfo);
  27200. });
  27201. var target = dragConfig.getTarget(component.element());
  27202. dragState.reset();
  27203. dragConfig.onDrop(component, target);
  27204. };
  27205. var handlers = function (events) {
  27206. return function (dragConfig, dragState) {
  27207. var updateStartState = function (comp) {
  27208. dragState.setStartData(calcStartData(dragConfig, comp));
  27209. };
  27210. return derive(__spreadArrays([run(windowScroll(), function (comp) {
  27211. dragState.getStartData().each(function () {
  27212. return updateStartState(comp);
  27213. });
  27214. })], events(dragConfig, dragState, updateStartState)));
  27215. };
  27216. };
  27217. var init$c = function (dragApi) {
  27218. return derive([
  27219. run(mousedown(), dragApi.forceDrop),
  27220. run(mouseup(), dragApi.drop),
  27221. run(mousemove(), function (comp, simulatedEvent) {
  27222. dragApi.move(simulatedEvent.event());
  27223. }),
  27224. run(mouseout(), dragApi.delayDrop)
  27225. ]);
  27226. };
  27227. var getData$1 = function (event) {
  27228. return Option.from(Position(event.x(), event.y()));
  27229. };
  27230. var getDelta$1 = function (old, nu) {
  27231. return Position(nu.left() - old.left(), nu.top() - old.top());
  27232. };
  27233. var MouseData = /*#__PURE__*/Object.freeze({
  27234. __proto__: null,
  27235. getData: getData$1,
  27236. getDelta: getDelta$1
  27237. });
  27238. var events$g = function (dragConfig, dragState, updateStartState) {
  27239. return [run(mousedown(), function (component, simulatedEvent) {
  27240. var raw = simulatedEvent.event().raw();
  27241. if (raw.button !== 0) {
  27242. return;
  27243. }
  27244. simulatedEvent.stop();
  27245. var stop$1 = function () {
  27246. return stop(component, Option.some(blocker), dragConfig, dragState);
  27247. };
  27248. var delayDrop = DelayedFunction(stop$1, 200);
  27249. var dragApi = {
  27250. drop: stop$1,
  27251. delayDrop: delayDrop.schedule,
  27252. forceDrop: stop$1,
  27253. move: function (event) {
  27254. delayDrop.cancel();
  27255. move$1(component, dragConfig, dragState, MouseData, event);
  27256. }
  27257. };
  27258. var blocker = createComponent(component, dragConfig.blockerClass, init$c(dragApi));
  27259. var start = function () {
  27260. updateStartState(component);
  27261. instigate(component, blocker);
  27262. };
  27263. start();
  27264. })];
  27265. };
  27266. var schema$u = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$g) })]);
  27267. var init$d = function (dragApi) {
  27268. return derive([
  27269. run(touchstart(), dragApi.forceDrop),
  27270. run(touchend(), dragApi.drop),
  27271. run(touchcancel(), dragApi.drop),
  27272. run(touchmove(), function (comp, simulatedEvent) {
  27273. dragApi.move(simulatedEvent.event());
  27274. })
  27275. ]);
  27276. };
  27277. var getDataFrom = function (touches) {
  27278. var touch = touches[0];
  27279. return Option.some(Position(touch.clientX, touch.clientY));
  27280. };
  27281. var getData$2 = function (event) {
  27282. var raw = event.raw();
  27283. var touches = raw.touches;
  27284. return touches.length === 1 ? getDataFrom(touches) : Option.none();
  27285. };
  27286. var getDelta$2 = function (old, nu) {
  27287. return Position(nu.left() - old.left(), nu.top() - old.top());
  27288. };
  27289. var TouchData = /*#__PURE__*/Object.freeze({
  27290. __proto__: null,
  27291. getData: getData$2,
  27292. getDelta: getDelta$2
  27293. });
  27294. var events$h = function (dragConfig, dragState, updateStartState) {
  27295. var blockerCell = Cell(Option.none());
  27296. return [
  27297. run(touchstart(), function (component, simulatedEvent) {
  27298. simulatedEvent.stop();
  27299. var stop$1 = function () {
  27300. stop(component, blockerCell.get(), dragConfig, dragState);
  27301. blockerCell.set(Option.none());
  27302. };
  27303. var dragApi = {
  27304. drop: stop$1,
  27305. delayDrop: function () {
  27306. },
  27307. forceDrop: stop$1,
  27308. move: function (event) {
  27309. move$1(component, dragConfig, dragState, TouchData, event);
  27310. }
  27311. };
  27312. var blocker = createComponent(component, dragConfig.blockerClass, init$d(dragApi));
  27313. blockerCell.set(Option.some(blocker));
  27314. var start = function () {
  27315. updateStartState(component);
  27316. instigate(component, blocker);
  27317. };
  27318. start();
  27319. }),
  27320. run(touchmove(), function (component, simulatedEvent) {
  27321. simulatedEvent.stop();
  27322. move$1(component, dragConfig, dragState, TouchData, simulatedEvent.event());
  27323. }),
  27324. run(touchend(), function (component, simulatedEvent) {
  27325. simulatedEvent.stop();
  27326. stop(component, blockerCell.get(), dragConfig, dragState);
  27327. blockerCell.set(Option.none());
  27328. }),
  27329. run(touchcancel(), function (component) {
  27330. stop(component, blockerCell.get(), dragConfig, dragState);
  27331. blockerCell.set(Option.none());
  27332. })
  27333. ];
  27334. };
  27335. var schema$v = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$h) })]);
  27336. var events$i = function (dragConfig, dragState, updateStartState) {
  27337. return __spreadArrays(events$g(dragConfig, dragState, updateStartState), events$h(dragConfig, dragState, updateStartState));
  27338. };
  27339. var schema$w = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$i) })]);
  27340. var mouse = schema$u;
  27341. var touch = schema$v;
  27342. var mouseOrTouch = schema$w;
  27343. var DraggingBranches = /*#__PURE__*/Object.freeze({
  27344. __proto__: null,
  27345. mouse: mouse,
  27346. touch: touch,
  27347. mouseOrTouch: mouseOrTouch
  27348. });
  27349. var init$e = function () {
  27350. var previous = Option.none();
  27351. var startData = Option.none();
  27352. var reset = function () {
  27353. previous = Option.none();
  27354. startData = Option.none();
  27355. };
  27356. var calculateDelta = function (mode, nu) {
  27357. var result = previous.map(function (old) {
  27358. return mode.getDelta(old, nu);
  27359. });
  27360. previous = Option.some(nu);
  27361. return result;
  27362. };
  27363. var update = function (mode, dragEvent) {
  27364. return mode.getData(dragEvent).bind(function (nuData) {
  27365. return calculateDelta(mode, nuData);
  27366. });
  27367. };
  27368. var setStartData = function (data) {
  27369. startData = Option.some(data);
  27370. };
  27371. var getStartData = function () {
  27372. return startData;
  27373. };
  27374. var readState = constant({});
  27375. return nu$5({
  27376. readState: readState,
  27377. reset: reset,
  27378. update: update,
  27379. getStartData: getStartData,
  27380. setStartData: setStartData
  27381. });
  27382. };
  27383. var DragState = /*#__PURE__*/Object.freeze({
  27384. __proto__: null,
  27385. init: init$e
  27386. });
  27387. var Dragging = createModes$1({
  27388. branchKey: 'mode',
  27389. branches: DraggingBranches,
  27390. name: 'dragging',
  27391. active: {
  27392. events: function (dragConfig, dragState) {
  27393. var dragger = dragConfig.dragger;
  27394. return dragger.handlers(dragConfig, dragState);
  27395. }
  27396. },
  27397. extra: {
  27398. snap: MixedBag([
  27399. 'sensor',
  27400. 'range',
  27401. 'output'
  27402. ], ['extra'])
  27403. },
  27404. state: DragState,
  27405. apis: DraggingApis
  27406. });
  27407. var platform$1 = detect$3();
  27408. var snapWidth = 40;
  27409. var snapOffset = snapWidth / 2;
  27410. var calcSnap = function (selectorOpt, td, x, y, width, height) {
  27411. return selectorOpt.fold(function () {
  27412. return Dragging.snap({
  27413. sensor: absolute$3(x - snapOffset, y - snapOffset),
  27414. range: Position(width, height),
  27415. output: absolute$3(Option.some(x), Option.some(y)),
  27416. extra: { td: td }
  27417. });
  27418. }, function (selectorHandle) {
  27419. var sensorLeft = x - snapOffset;
  27420. var sensorTop = y - snapOffset;
  27421. var sensorWidth = snapWidth;
  27422. var sensorHeight = snapWidth;
  27423. var rect = selectorHandle.element().dom().getBoundingClientRect();
  27424. return Dragging.snap({
  27425. sensor: absolute$3(sensorLeft, sensorTop),
  27426. range: Position(sensorWidth, sensorHeight),
  27427. output: absolute$3(Option.some(x - rect.width / 2), Option.some(y - rect.height / 2)),
  27428. extra: { td: td }
  27429. });
  27430. });
  27431. };
  27432. var getSnapsConfig = function (getSnapPoints, cell, onChange) {
  27433. var isSameCell = function (cellOpt, td) {
  27434. return cellOpt.exists(function (currentTd) {
  27435. return eq(currentTd, td);
  27436. });
  27437. };
  27438. return {
  27439. getSnapPoints: getSnapPoints,
  27440. leftAttr: 'data-drag-left',
  27441. topAttr: 'data-drag-top',
  27442. onSensor: function (component, extra) {
  27443. var td = extra.td;
  27444. if (!isSameCell(cell.get(), td)) {
  27445. cell.set(Option.some(td));
  27446. onChange(td);
  27447. }
  27448. },
  27449. mustSnap: true
  27450. };
  27451. };
  27452. var createSelector = function (snaps) {
  27453. return record(Button.sketch({
  27454. dom: {
  27455. tag: 'div',
  27456. classes: ['tox-selector']
  27457. },
  27458. buttonBehaviours: derive$1([
  27459. Dragging.config({
  27460. mode: 'mouseOrTouch',
  27461. blockerClass: 'blocker',
  27462. snaps: snaps
  27463. }),
  27464. Unselecting.config({})
  27465. ]),
  27466. eventOrder: {
  27467. mousedown: [
  27468. 'dragging',
  27469. 'alloy.base.behaviour'
  27470. ],
  27471. touchstart: [
  27472. 'dragging',
  27473. 'alloy.base.behaviour'
  27474. ]
  27475. }
  27476. }));
  27477. };
  27478. var setup$a = function (editor, sink) {
  27479. var tlTds = Cell([]);
  27480. var brTds = Cell([]);
  27481. var isVisible = Cell(false);
  27482. var startCell = Cell(Option.none());
  27483. var finishCell = Cell(Option.none());
  27484. var getTopLeftSnap = function (td) {
  27485. var box = absolute$1(td);
  27486. return calcSnap(memTopLeft.getOpt(sink), td, box.x(), box.y(), box.width(), box.height());
  27487. };
  27488. var getTopLeftSnaps = function () {
  27489. return map(tlTds.get(), function (td) {
  27490. return getTopLeftSnap(td);
  27491. });
  27492. };
  27493. var getBottomRightSnap = function (td) {
  27494. var box = absolute$1(td);
  27495. return calcSnap(memBottomRight.getOpt(sink), td, box.right(), box.bottom(), box.width(), box.height());
  27496. };
  27497. var getBottomRightSnaps = function () {
  27498. return map(brTds.get(), function (td) {
  27499. return getBottomRightSnap(td);
  27500. });
  27501. };
  27502. var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
  27503. finishCell.get().each(function (finish) {
  27504. editor.fire('TableSelectorChange', {
  27505. start: start,
  27506. finish: finish
  27507. });
  27508. });
  27509. });
  27510. var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
  27511. startCell.get().each(function (start) {
  27512. editor.fire('TableSelectorChange', {
  27513. start: start,
  27514. finish: finish
  27515. });
  27516. });
  27517. });
  27518. var memTopLeft = createSelector(topLeftSnaps);
  27519. var memBottomRight = createSelector(bottomRightSnaps);
  27520. var topLeft = build$1(memTopLeft.asSpec());
  27521. var bottomRight = build$1(memBottomRight.asSpec());
  27522. var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  27523. var cellRect = cell.dom().getBoundingClientRect();
  27524. remove$6(selector.element(), 'display');
  27525. var viewportHeight = defaultView(Element.fromDom(editor.getBody())).dom().innerHeight;
  27526. var aboveViewport = isAbove(cellRect);
  27527. var belowViewport = isBelow(cellRect, viewportHeight);
  27528. if (aboveViewport || belowViewport) {
  27529. set$2(selector.element(), 'display', 'none');
  27530. }
  27531. };
  27532. var snapTo = function (selector, cell, getSnapConfig, pos) {
  27533. var snap = getSnapConfig(cell);
  27534. Dragging.snapTo(selector, snap);
  27535. var isAbove = function (rect) {
  27536. return rect[pos] < 0;
  27537. };
  27538. var isBelow = function (rect, viewportHeight) {
  27539. return rect[pos] > viewportHeight;
  27540. };
  27541. showOrHideHandle(selector, cell, isAbove, isBelow);
  27542. };
  27543. var snapTopLeft = function (cell) {
  27544. return snapTo(topLeft, cell, getTopLeftSnap, 'top');
  27545. };
  27546. var snapLastTopLeft = function () {
  27547. return startCell.get().each(snapTopLeft);
  27548. };
  27549. var snapBottomRight = function (cell) {
  27550. return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  27551. };
  27552. var snapLastBottomRight = function () {
  27553. return finishCell.get().each(snapBottomRight);
  27554. };
  27555. if (platform$1.deviceType.isTouch()) {
  27556. editor.on('TableSelectionChange', function (e) {
  27557. if (!isVisible.get()) {
  27558. attach$1(sink, topLeft);
  27559. attach$1(sink, bottomRight);
  27560. isVisible.set(true);
  27561. }
  27562. startCell.set(Option.some(e.start));
  27563. finishCell.set(Option.some(e.finish));
  27564. e.otherCells.each(function (otherCells) {
  27565. tlTds.set(otherCells.upOrLeftCells);
  27566. brTds.set(otherCells.downOrRightCells);
  27567. snapTopLeft(e.start);
  27568. snapBottomRight(e.finish);
  27569. });
  27570. });
  27571. editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
  27572. snapLastTopLeft();
  27573. snapLastBottomRight();
  27574. });
  27575. editor.on('TableSelectionClear', function () {
  27576. if (isVisible.get()) {
  27577. detach(topLeft);
  27578. detach(bottomRight);
  27579. isVisible.set(false);
  27580. }
  27581. startCell.set(Option.none());
  27582. finishCell.set(Option.none());
  27583. });
  27584. }
  27585. };
  27586. var TableSelectorHandles = { setup: setup$a };
  27587. var ResizeTypes;
  27588. (function (ResizeTypes) {
  27589. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  27590. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  27591. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  27592. }(ResizeTypes || (ResizeTypes = {})));
  27593. var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  27594. var dimensions = {};
  27595. dimensions.height = Utils.calcCappedSize(originalHeight + deltas.top(), getMinHeightSetting(editor), getMaxHeightSetting(editor));
  27596. if (resizeType === ResizeTypes.Both) {
  27597. dimensions.width = Utils.calcCappedSize(originalWidth + deltas.left(), getMinWidthSetting(editor), getMaxWidthSetting(editor));
  27598. }
  27599. return dimensions;
  27600. };
  27601. var resize$3 = function (editor, deltas, resizeType) {
  27602. var container = Element.fromDom(editor.getContainer());
  27603. var dimensions = getDimensions(editor, deltas, resizeType, get$6(container), get$7(container));
  27604. each$1(dimensions, function (val, dim) {
  27605. return set$2(container, dim, Utils.numToPx(val));
  27606. });
  27607. Events.fireResizeEditor(editor);
  27608. };
  27609. var isHidden$1 = function (elm) {
  27610. if (elm.nodeType === 1) {
  27611. if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  27612. return true;
  27613. }
  27614. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  27615. return true;
  27616. }
  27617. }
  27618. return false;
  27619. };
  27620. var renderElementPath = function (editor, settings) {
  27621. if (!settings.delimiter) {
  27622. settings.delimiter = '\xBB';
  27623. }
  27624. var getDataPath = function (data) {
  27625. var parts = data || [];
  27626. var newPathElements = map(parts, function (part, index) {
  27627. return Button.sketch({
  27628. dom: {
  27629. tag: 'div',
  27630. classes: ['tox-statusbar__path-item'],
  27631. attributes: {
  27632. 'role': 'button',
  27633. 'data-index': index,
  27634. 'tab-index': -1,
  27635. 'aria-level': index + 1
  27636. },
  27637. innerHtml: part.name
  27638. },
  27639. action: function (btn) {
  27640. editor.focus();
  27641. editor.selection.select(part.element);
  27642. editor.nodeChanged();
  27643. }
  27644. });
  27645. });
  27646. var divider = {
  27647. dom: {
  27648. tag: 'div',
  27649. classes: ['tox-statusbar__path-divider'],
  27650. attributes: { 'aria-hidden': true },
  27651. innerHtml: ' ' + settings.delimiter + ' '
  27652. }
  27653. };
  27654. return foldl(newPathElements.slice(1), function (acc, element) {
  27655. var newAcc = acc;
  27656. newAcc.push(divider);
  27657. newAcc.push(element);
  27658. return newAcc;
  27659. }, [newPathElements[0]]);
  27660. };
  27661. var updatePath = function (parents) {
  27662. var newPath = [];
  27663. var i = parents.length;
  27664. while (i-- > 0) {
  27665. var parent_1 = parents[i];
  27666. if (parent_1.nodeType === 1 && !isHidden$1(parent_1)) {
  27667. var args = editor.fire('ResolveName', {
  27668. name: parent_1.nodeName.toLowerCase(),
  27669. target: parent_1
  27670. });
  27671. if (!args.isDefaultPrevented()) {
  27672. newPath.push({
  27673. name: args.name,
  27674. element: parent_1
  27675. });
  27676. }
  27677. if (args.isPropagationStopped()) {
  27678. break;
  27679. }
  27680. }
  27681. }
  27682. return newPath;
  27683. };
  27684. return {
  27685. dom: {
  27686. tag: 'div',
  27687. classes: ['tox-statusbar__path'],
  27688. attributes: { role: 'navigation' }
  27689. },
  27690. behaviours: derive$1([
  27691. Keying.config({
  27692. mode: 'flow',
  27693. selector: 'div[role=button]'
  27694. }),
  27695. Tabstopping.config({}),
  27696. Replacing.config({}),
  27697. config('elementPathEvents', [runOnAttached(function (comp, e) {
  27698. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  27699. return Keying.focusIn(comp);
  27700. });
  27701. editor.on('NodeChange', function (e) {
  27702. var newPath = updatePath(e.parents);
  27703. if (newPath.length > 0) {
  27704. Replacing.set(comp, getDataPath(newPath));
  27705. } else {
  27706. Replacing.set(comp, []);
  27707. }
  27708. });
  27709. })])
  27710. ]),
  27711. components: []
  27712. };
  27713. };
  27714. var ElementPath = { renderElementPath: renderElementPath };
  27715. var renderWordCount = function (editor, providersBackstage) {
  27716. var replaceCountText = function (comp, count, mode) {
  27717. return Replacing.set(comp, [text(providersBackstage.translate([
  27718. '{0} ' + mode,
  27719. count[mode]
  27720. ]))]);
  27721. };
  27722. return Button.sketch({
  27723. dom: {
  27724. tag: 'button',
  27725. classes: ['tox-statusbar__wordcount']
  27726. },
  27727. components: [],
  27728. buttonBehaviours: derive$1([
  27729. Tabstopping.config({}),
  27730. Replacing.config({}),
  27731. Representing.config({
  27732. store: {
  27733. mode: 'memory',
  27734. initialValue: {
  27735. mode: 'words',
  27736. count: {
  27737. words: 0,
  27738. characters: 0
  27739. }
  27740. }
  27741. }
  27742. }),
  27743. config('wordcount-events', [
  27744. runOnExecute(function (comp) {
  27745. var currentVal = Representing.getValue(comp);
  27746. var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  27747. Representing.setValue(comp, {
  27748. mode: newMode,
  27749. count: currentVal.count
  27750. });
  27751. replaceCountText(comp, currentVal.count, newMode);
  27752. }),
  27753. runOnAttached(function (comp) {
  27754. editor.on('wordCountUpdate', function (e) {
  27755. var mode = Representing.getValue(comp).mode;
  27756. Representing.setValue(comp, {
  27757. mode: mode,
  27758. count: e.wordCount
  27759. });
  27760. replaceCountText(comp, e.wordCount, mode);
  27761. });
  27762. })
  27763. ])
  27764. ])
  27765. });
  27766. };
  27767. var renderStatusbar = function (editor, providersBackstage) {
  27768. var renderResizeHandlerIcon = function (resizeType) {
  27769. return {
  27770. dom: {
  27771. tag: 'div',
  27772. classes: ['tox-statusbar__resize-handle'],
  27773. attributes: {
  27774. 'title': providersBackstage.translate('Resize'),
  27775. 'aria-hidden': 'true'
  27776. },
  27777. innerHtml: get$d('resize-handle', providersBackstage.icons)
  27778. },
  27779. behaviours: derive$1([Dragging.config({
  27780. mode: 'mouse',
  27781. repositionTarget: false,
  27782. onDrag: function (comp, target, delta) {
  27783. resize$3(editor, delta, resizeType);
  27784. },
  27785. blockerClass: 'tox-blocker'
  27786. })])
  27787. };
  27788. };
  27789. var renderBranding = function () {
  27790. var label = global$7.translate([
  27791. 'Powered by {0}',
  27792. 'Tiny'
  27793. ]);
  27794. 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>';
  27795. return {
  27796. dom: {
  27797. tag: 'span',
  27798. classes: ['tox-statusbar__branding'],
  27799. innerHtml: linkHtml
  27800. }
  27801. };
  27802. };
  27803. var getResizeType = function (editor) {
  27804. var fallback = !contains$1(editor.settings.plugins, 'autoresize');
  27805. var resize = editor.getParam('resize', fallback);
  27806. if (resize === false) {
  27807. return ResizeTypes.None;
  27808. } else if (resize === 'both') {
  27809. return ResizeTypes.Both;
  27810. } else {
  27811. return ResizeTypes.Vertical;
  27812. }
  27813. };
  27814. var getTextComponents = function () {
  27815. var components = [];
  27816. if (editor.getParam('elementpath', true, 'boolean')) {
  27817. components.push(ElementPath.renderElementPath(editor, {}));
  27818. }
  27819. if (contains$1(editor.settings.plugins, 'wordcount')) {
  27820. components.push(renderWordCount(editor, providersBackstage));
  27821. }
  27822. if (editor.getParam('branding', true, 'boolean')) {
  27823. components.push(renderBranding());
  27824. }
  27825. if (components.length > 0) {
  27826. return [{
  27827. dom: {
  27828. tag: 'div',
  27829. classes: ['tox-statusbar__text-container']
  27830. },
  27831. components: components
  27832. }];
  27833. }
  27834. return [];
  27835. };
  27836. var getComponents = function () {
  27837. var components = getTextComponents();
  27838. var resizeType = getResizeType(editor);
  27839. if (resizeType !== ResizeTypes.None) {
  27840. components.push(renderResizeHandlerIcon(resizeType));
  27841. }
  27842. return components;
  27843. };
  27844. return {
  27845. dom: {
  27846. tag: 'div',
  27847. classes: ['tox-statusbar']
  27848. },
  27849. components: getComponents()
  27850. };
  27851. };
  27852. var setup$b = function (editor) {
  27853. var _a;
  27854. var isInline = editor.inline;
  27855. var mode = isInline ? Inline : Iframe;
  27856. var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  27857. var lazyOuterContainer = Option.none();
  27858. var platform = detect$3();
  27859. var isIE = platform.browser.isIE();
  27860. var platformClasses = isIE ? ['tox-platform-ie'] : [];
  27861. var isTouch = platform.deviceType.isTouch();
  27862. var touchPlatformClass = 'tox-platform-touch';
  27863. var deviceClasses = isTouch ? [touchPlatformClass] : [];
  27864. var isToolbarTop = isToolbarLocationTop(editor);
  27865. var dirAttributes = global$7.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  27866. var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarTop ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a) };
  27867. var lazyHeader = function () {
  27868. return lazyOuterContainer.bind(OuterContainer.getHeader);
  27869. };
  27870. var isHeaderDocked = function () {
  27871. return header.isDocked(lazyHeader);
  27872. };
  27873. var sink = build$1({
  27874. dom: __assign({
  27875. tag: 'div',
  27876. classes: [
  27877. 'tox',
  27878. 'tox-silver-sink',
  27879. 'tox-tinymce-aux'
  27880. ].concat(platformClasses).concat(deviceClasses)
  27881. }, dirAttributes),
  27882. behaviours: derive$1([Positioning.config({
  27883. useFixed: function () {
  27884. return isHeaderDocked();
  27885. }
  27886. })])
  27887. });
  27888. var lazySink = function () {
  27889. return Result.value(sink);
  27890. };
  27891. var memAnchorBar = record({
  27892. dom: {
  27893. tag: 'div',
  27894. classes: ['tox-anchorbar']
  27895. }
  27896. });
  27897. var lazyAnchorBar = function () {
  27898. return lazyOuterContainer.bind(function (container) {
  27899. return memAnchorBar.getOpt(container);
  27900. }).getOrDie('Could not find a anchor bar element');
  27901. };
  27902. var lazyToolbar = function () {
  27903. return lazyOuterContainer.bind(function (container) {
  27904. return OuterContainer.getToolbar(container);
  27905. }).getOrDie('Could not find more toolbar element');
  27906. };
  27907. var lazyThrobber = function () {
  27908. return lazyOuterContainer.bind(function (container) {
  27909. return OuterContainer.getThrobber(container);
  27910. }).getOrDie('Could not find throbber element');
  27911. };
  27912. var backstage = init$8(sink, editor, lazyAnchorBar);
  27913. var partMenubar = OuterContainer.parts().menubar({
  27914. dom: {
  27915. tag: 'div',
  27916. classes: ['tox-menubar']
  27917. },
  27918. backstage: backstage,
  27919. onEscape: function () {
  27920. editor.focus();
  27921. }
  27922. });
  27923. var toolbarMode = getToolbarMode(editor);
  27924. var partToolbar = OuterContainer.parts().toolbar(__assign({
  27925. dom: {
  27926. tag: 'div',
  27927. classes: ['tox-toolbar']
  27928. },
  27929. getSink: lazySink,
  27930. backstage: backstage,
  27931. onEscape: function () {
  27932. editor.focus();
  27933. },
  27934. type: toolbarMode,
  27935. lazyToolbar: lazyToolbar,
  27936. lazyHeader: function () {
  27937. return lazyHeader().getOrDie('Could not find header element');
  27938. }
  27939. }, verticalDirAttributes));
  27940. var partMultipleToolbar = OuterContainer.parts()['multiple-toolbar']({
  27941. dom: {
  27942. tag: 'div',
  27943. classes: ['tox-toolbar-overlord']
  27944. },
  27945. onEscape: function () {
  27946. },
  27947. type: toolbarMode
  27948. });
  27949. var partSocket = OuterContainer.parts().socket({
  27950. dom: {
  27951. tag: 'div',
  27952. classes: ['tox-edit-area']
  27953. }
  27954. });
  27955. var partSidebar = OuterContainer.parts().sidebar({
  27956. dom: {
  27957. tag: 'div',
  27958. classes: ['tox-sidebar']
  27959. }
  27960. });
  27961. var partThrobber = OuterContainer.parts().throbber({
  27962. dom: {
  27963. tag: 'div',
  27964. classes: ['tox-throbber']
  27965. },
  27966. backstage: backstage
  27967. });
  27968. var sb = editor.getParam('statusbar', true, 'boolean');
  27969. var statusbar = sb && !isInline ? Option.some(renderStatusbar(editor, backstage.shared.providers)) : Option.none();
  27970. var socketSidebarContainer = {
  27971. dom: {
  27972. tag: 'div',
  27973. classes: ['tox-sidebar-wrap']
  27974. },
  27975. components: [
  27976. partSocket,
  27977. partSidebar
  27978. ]
  27979. };
  27980. var hasMultipleToolbar = isMultipleToolbars(editor);
  27981. var hasToolbar = isToolbarEnabled(editor);
  27982. var hasMenubar = isMenubarEnabled(editor);
  27983. var getPartToolbar = function () {
  27984. if (hasMultipleToolbar) {
  27985. return [partMultipleToolbar];
  27986. } else if (hasToolbar) {
  27987. return [partToolbar];
  27988. } else {
  27989. return [];
  27990. }
  27991. };
  27992. var partHeader = OuterContainer.parts().header({
  27993. dom: __assign({
  27994. tag: 'div',
  27995. classes: ['tox-editor-header']
  27996. }, verticalDirAttributes),
  27997. components: flatten([
  27998. hasMenubar ? [partMenubar] : [],
  27999. getPartToolbar(),
  28000. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  28001. ]),
  28002. sticky: isStickyToolbar(editor),
  28003. editor: editor,
  28004. getSink: lazySink
  28005. });
  28006. var editorComponents = flatten([
  28007. isToolbarTop ? [partHeader] : [],
  28008. isInline ? [] : [socketSidebarContainer],
  28009. isToolbarTop ? [] : [partHeader]
  28010. ]);
  28011. var editorContainer = {
  28012. dom: {
  28013. tag: 'div',
  28014. classes: ['tox-editor-container']
  28015. },
  28016. components: editorComponents
  28017. };
  28018. var containerComponents = flatten([
  28019. [editorContainer],
  28020. isInline ? [] : statusbar.toArray(),
  28021. [partThrobber]
  28022. ]);
  28023. var isHidden = isDistractionFree(editor);
  28024. var attributes = __assign(__assign({ role: 'application' }, global$7.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  28025. var outerContainer = build$1(OuterContainer.sketch({
  28026. dom: {
  28027. tag: 'div',
  28028. classes: [
  28029. 'tox',
  28030. 'tox-tinymce'
  28031. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarTop ? [] : ['tox-tinymce--toolbar-bottom']).concat(deviceClasses).concat(platformClasses),
  28032. styles: __assign({ visibility: 'hidden' }, isHidden ? {
  28033. opacity: '0',
  28034. border: '0'
  28035. } : {}),
  28036. attributes: attributes
  28037. },
  28038. components: containerComponents,
  28039. behaviours: derive$1([Keying.config({
  28040. mode: 'cyclic',
  28041. 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'
  28042. })])
  28043. }));
  28044. lazyOuterContainer = Option.some(outerContainer);
  28045. editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  28046. OuterContainer.focusMenubar(outerContainer);
  28047. });
  28048. editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  28049. OuterContainer.focusToolbar(outerContainer);
  28050. });
  28051. var mothership = takeover(outerContainer);
  28052. var uiMothership = takeover(sink);
  28053. Events$1.setup(editor, mothership, uiMothership);
  28054. var getUi = function () {
  28055. var channels = {
  28056. broadcastAll: uiMothership.broadcast,
  28057. broadcastOn: uiMothership.broadcastOn,
  28058. register: function () {
  28059. }
  28060. };
  28061. return { channels: channels };
  28062. };
  28063. var setEditorSize = function () {
  28064. var parsedHeight = Utils.numToPx(getHeightWithFallback(editor));
  28065. var parsedWidth = Utils.numToPx(getWidthWithFallback(editor));
  28066. if (!editor.inline) {
  28067. if (isValidValue('div', 'width', parsedWidth)) {
  28068. set$2(outerContainer.element(), 'width', parsedWidth);
  28069. }
  28070. if (isValidValue('div', 'height', parsedHeight)) {
  28071. set$2(outerContainer.element(), 'height', parsedHeight);
  28072. } else {
  28073. set$2(outerContainer.element(), 'height', '200px');
  28074. }
  28075. }
  28076. return parsedHeight;
  28077. };
  28078. var renderUI = function () {
  28079. header.setup(editor, lazyHeader);
  28080. FormatControls.setup(editor, backstage);
  28081. setup$9(editor, lazySink, backstage);
  28082. setup$6(editor);
  28083. setup$7(editor, lazyThrobber, backstage.shared);
  28084. map$1(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
  28085. editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  28086. });
  28087. var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  28088. var toolbarOpt = getMultipleToolbarsSetting(editor);
  28089. var rawUiConfig = {
  28090. menuItems: menuItems,
  28091. menus: !editor.settings.menu ? {} : map$1(editor.settings.menu, function (menu) {
  28092. return __assign(__assign({}, menu), { items: menu.items });
  28093. }),
  28094. menubar: editor.settings.menubar,
  28095. toolbar: toolbarOpt.getOrThunk(function () {
  28096. return editor.getParam('toolbar', true);
  28097. }),
  28098. allowToolbarGroups: toolbarMode === ToolbarMode.floating,
  28099. buttons: buttons,
  28100. sidebar: sidebars
  28101. };
  28102. ContextToolbar.register(editor, contextToolbars, sink, { backstage: backstage });
  28103. TableSelectorHandles.setup(editor, sink);
  28104. var elm = editor.getElement();
  28105. var height = setEditorSize();
  28106. var uiComponents = {
  28107. mothership: mothership,
  28108. uiMothership: uiMothership,
  28109. outerContainer: outerContainer
  28110. };
  28111. var args = {
  28112. targetNode: elm,
  28113. height: height
  28114. };
  28115. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  28116. };
  28117. return {
  28118. mothership: mothership,
  28119. uiMothership: uiMothership,
  28120. backstage: backstage,
  28121. renderUI: renderUI,
  28122. getUi: getUi
  28123. };
  28124. };
  28125. var Render = { setup: setup$b };
  28126. var describedBy = function (describedElement, describeElement) {
  28127. var describeId = Option.from(get$2(describedElement, 'id')).fold(function () {
  28128. var id = generate$1('dialog-describe');
  28129. set$1(describeElement, 'id', id);
  28130. return id;
  28131. }, identity);
  28132. set$1(describedElement, 'aria-describedby', describeId);
  28133. };
  28134. var AriaLabel = {
  28135. labelledBy: function (labelledElement, labelElement) {
  28136. var labelId = Option.from(get$2(labelledElement, 'id')).fold(function () {
  28137. var id = generate$1('dialog-label');
  28138. set$1(labelElement, 'id', id);
  28139. return id;
  28140. }, identity);
  28141. set$1(labelledElement, 'aria-labelledby', labelId);
  28142. }
  28143. };
  28144. var schema$x = constant([
  28145. strict$1('lazySink'),
  28146. option('dragBlockClass'),
  28147. defaultedFunction('getBounds', win),
  28148. defaulted$1('useTabstopAt', constant(true)),
  28149. defaulted$1('eventOrder', {}),
  28150. field$1('modalBehaviours', [Keying]),
  28151. onKeyboardHandler('onExecute'),
  28152. onStrictKeyboardHandler('onEscape')
  28153. ]);
  28154. var basic = { sketch: identity };
  28155. var parts$f = constant([
  28156. optional({
  28157. name: 'draghandle',
  28158. overrides: function (detail, spec) {
  28159. return {
  28160. behaviours: derive$1([Dragging.config({
  28161. mode: 'mouse',
  28162. getTarget: function (handle) {
  28163. return ancestor$2(handle, '[role="dialog"]').getOr(handle);
  28164. },
  28165. 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),
  28166. getBounds: detail.getDragBounds
  28167. })])
  28168. };
  28169. }
  28170. }),
  28171. required({
  28172. schema: [strict$1('dom')],
  28173. name: 'title'
  28174. }),
  28175. required({
  28176. factory: basic,
  28177. schema: [strict$1('dom')],
  28178. name: 'close'
  28179. }),
  28180. required({
  28181. factory: basic,
  28182. schema: [strict$1('dom')],
  28183. name: 'body'
  28184. }),
  28185. optional({
  28186. factory: basic,
  28187. schema: [strict$1('dom')],
  28188. name: 'footer'
  28189. }),
  28190. external$1({
  28191. factory: {
  28192. sketch: function (spec, detail) {
  28193. return __assign(__assign({}, spec), {
  28194. dom: detail.dom,
  28195. components: detail.components
  28196. });
  28197. }
  28198. },
  28199. schema: [
  28200. defaulted$1('dom', {
  28201. tag: 'div',
  28202. styles: {
  28203. position: 'fixed',
  28204. left: '0px',
  28205. top: '0px',
  28206. right: '0px',
  28207. bottom: '0px'
  28208. }
  28209. }),
  28210. defaulted$1('components', [])
  28211. ],
  28212. name: 'blocker'
  28213. })
  28214. ]);
  28215. var factory$i = function (detail, components, spec, externals) {
  28216. var dialogBusyEvent = generate$1('alloy.dialog.busy');
  28217. var dialogIdleEvent = generate$1('alloy.dialog.idle');
  28218. var busyBehaviours = derive$1([
  28219. Keying.config({
  28220. mode: 'special',
  28221. onTab: function () {
  28222. return Option.some(true);
  28223. },
  28224. onShiftTab: function () {
  28225. return Option.some(true);
  28226. }
  28227. }),
  28228. Focusing.config({})
  28229. ]);
  28230. var showDialog = function (dialog) {
  28231. var sink = detail.lazySink(dialog).getOrDie();
  28232. var busyComp = Cell(Option.none());
  28233. var externalBlocker = externals.blocker();
  28234. var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  28235. components: externalBlocker.components.concat([premade$1(dialog)]),
  28236. behaviours: derive$1([
  28237. Focusing.config({}),
  28238. config('dialog-blocker-events', [
  28239. runOnSource(focusin(), function () {
  28240. Keying.focusIn(dialog);
  28241. }),
  28242. run(dialogIdleEvent, function (blocker, se) {
  28243. if (has$1(dialog.element(), 'aria-busy')) {
  28244. remove$1(dialog.element(), 'aria-busy');
  28245. busyComp.get().each(function (bc) {
  28246. return Replacing.remove(dialog, bc);
  28247. });
  28248. }
  28249. }),
  28250. run(dialogBusyEvent, function (blocker, se) {
  28251. set$1(dialog.element(), 'aria-busy', 'true');
  28252. var getBusySpec = se.event().getBusySpec();
  28253. busyComp.get().each(function (bc) {
  28254. Replacing.remove(dialog, bc);
  28255. });
  28256. var busySpec = getBusySpec(dialog, busyBehaviours);
  28257. var busy = blocker.getSystem().build(busySpec);
  28258. busyComp.set(Option.some(busy));
  28259. Replacing.append(dialog, premade$1(busy));
  28260. if (busy.hasConfigured(Keying)) {
  28261. Keying.focusIn(busy);
  28262. }
  28263. })
  28264. ])
  28265. ])
  28266. }));
  28267. attach$1(sink, blocker);
  28268. Keying.focusIn(dialog);
  28269. };
  28270. var hideDialog = function (dialog) {
  28271. parent(dialog.element()).each(function (blockerDom) {
  28272. dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  28273. detach(blocker);
  28274. });
  28275. });
  28276. };
  28277. var getDialogBody = function (dialog) {
  28278. return getPartOrDie(dialog, detail, 'body');
  28279. };
  28280. var getDialogFooter = function (dialog) {
  28281. return getPartOrDie(dialog, detail, 'footer');
  28282. };
  28283. var setBusy = function (dialog, getBusySpec) {
  28284. emitWith(dialog, dialogBusyEvent, { getBusySpec: getBusySpec });
  28285. };
  28286. var setIdle = function (dialog) {
  28287. emit(dialog, dialogIdleEvent);
  28288. };
  28289. var modalEventsId = generate$1('modal-events');
  28290. var eventOrder = __assign(__assign({}, detail.eventOrder), { 'alloy.system.attached': [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []) });
  28291. return {
  28292. uid: detail.uid,
  28293. dom: detail.dom,
  28294. components: components,
  28295. apis: {
  28296. show: showDialog,
  28297. hide: hideDialog,
  28298. getBody: getDialogBody,
  28299. getFooter: getDialogFooter,
  28300. setIdle: setIdle,
  28301. setBusy: setBusy
  28302. },
  28303. eventOrder: eventOrder,
  28304. domModification: {
  28305. attributes: {
  28306. 'role': 'dialog',
  28307. 'aria-modal': 'true'
  28308. }
  28309. },
  28310. behaviours: augment(detail.modalBehaviours, [
  28311. Replacing.config({}),
  28312. Keying.config({
  28313. mode: 'cyclic',
  28314. onEnter: detail.onExecute,
  28315. onEscape: detail.onEscape,
  28316. useTabstopAt: detail.useTabstopAt
  28317. }),
  28318. config(modalEventsId, [runOnAttached(function (c) {
  28319. AriaLabel.labelledBy(c.element(), getPartOrDie(c, detail, 'title').element());
  28320. describedBy(c.element(), getPartOrDie(c, detail, 'body').element());
  28321. })])
  28322. ])
  28323. };
  28324. };
  28325. var ModalDialog = composite$1({
  28326. name: 'ModalDialog',
  28327. configFields: schema$x(),
  28328. partFields: parts$f(),
  28329. factory: factory$i,
  28330. apis: {
  28331. show: function (apis, dialog) {
  28332. apis.show(dialog);
  28333. },
  28334. hide: function (apis, dialog) {
  28335. apis.hide(dialog);
  28336. },
  28337. getBody: function (apis, dialog) {
  28338. return apis.getBody(dialog);
  28339. },
  28340. getFooter: function (apis, dialog) {
  28341. return apis.getFooter(dialog);
  28342. },
  28343. setBusy: function (apis, dialog, getBusySpec) {
  28344. apis.setBusy(dialog, getBusySpec);
  28345. },
  28346. setIdle: function (apis, dialog) {
  28347. apis.setIdle(dialog);
  28348. }
  28349. }
  28350. });
  28351. var alertBannerFields = [
  28352. strictString('type'),
  28353. strictString('text'),
  28354. strictStringEnum('level', [
  28355. 'info',
  28356. 'warn',
  28357. 'error',
  28358. 'success'
  28359. ]),
  28360. strictString('icon'),
  28361. defaulted$1('url', '')
  28362. ];
  28363. var alertBannerSchema = objOf(alertBannerFields);
  28364. var createBarFields = function (itemsField) {
  28365. return [
  28366. strictString('type'),
  28367. itemsField
  28368. ];
  28369. };
  28370. var buttonFields = [
  28371. strictString('type'),
  28372. strictString('text'),
  28373. defaultedBoolean('disabled', false),
  28374. defaultedBoolean('primary', false),
  28375. field('name', 'name', defaultedThunk(function () {
  28376. return generate$1('button-name');
  28377. }), string),
  28378. optionString('icon'),
  28379. defaultedBoolean('borderless', false)
  28380. ];
  28381. var buttonSchema = objOf(buttonFields);
  28382. var checkboxFields = [
  28383. strictString('type'),
  28384. strictString('name'),
  28385. strictString('label'),
  28386. defaultedBoolean('disabled', false)
  28387. ];
  28388. var checkboxSchema = objOf(checkboxFields);
  28389. var checkboxDataProcessor = boolean;
  28390. var formComponentFields = [
  28391. strictString('type'),
  28392. strictString('name')
  28393. ];
  28394. var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  28395. var colorInputFields = formComponentWithLabelFields;
  28396. var colorInputSchema = objOf(colorInputFields);
  28397. var colorInputDataProcessor = string;
  28398. var colorPickerFields = formComponentWithLabelFields;
  28399. var colorPickerSchema = objOf(colorPickerFields);
  28400. var colorPickerDataProcessor = string;
  28401. var dropZoneFields = formComponentWithLabelFields;
  28402. var dropZoneSchema = objOf(dropZoneFields);
  28403. var dropZoneDataProcessor = arrOfVal();
  28404. var createGridFields = function (itemsField) {
  28405. return [
  28406. strictString('type'),
  28407. strictNumber('columns'),
  28408. itemsField
  28409. ];
  28410. };
  28411. var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  28412. var iframeSchema = objOf(iframeFields);
  28413. var iframeDataProcessor = string;
  28414. var inputFields = formComponentWithLabelFields.concat([
  28415. optionString('inputMode'),
  28416. optionString('placeholder'),
  28417. defaultedBoolean('maximized', false),
  28418. defaultedBoolean('disabled', false)
  28419. ]);
  28420. var inputSchema = objOf(inputFields);
  28421. var inputDataProcessor = string;
  28422. var selectBoxFields = formComponentWithLabelFields.concat([
  28423. strictArrayOfObj('items', [
  28424. strictString('text'),
  28425. strictString('value')
  28426. ]),
  28427. defaultedNumber('size', 1),
  28428. defaultedBoolean('disabled', false)
  28429. ]);
  28430. var selectBoxSchema = objOf(selectBoxFields);
  28431. var selectBoxDataProcessor = string;
  28432. var sizeInputFields = formComponentWithLabelFields.concat([
  28433. defaultedBoolean('constrain', true),
  28434. defaultedBoolean('disabled', false)
  28435. ]);
  28436. var sizeInputSchema = objOf(sizeInputFields);
  28437. var sizeInputDataProcessor = objOf([
  28438. strictString('width'),
  28439. strictString('height')
  28440. ]);
  28441. var textAreaFields = formComponentWithLabelFields.concat([
  28442. optionString('placeholder'),
  28443. defaultedBoolean('maximized', false),
  28444. defaultedBoolean('disabled', false)
  28445. ]);
  28446. var textAreaSchema = objOf(textAreaFields);
  28447. var textAreaDataProcessor = string;
  28448. var urlInputFields = formComponentWithLabelFields.concat([
  28449. defaultedStringEnum('filetype', 'file', [
  28450. 'image',
  28451. 'media',
  28452. 'file'
  28453. ]),
  28454. defaulted$1('disabled', false)
  28455. ]);
  28456. var urlInputSchema = objOf(urlInputFields);
  28457. var urlInputDataProcessor = objOf([
  28458. strictString('value'),
  28459. defaulted$1('meta', {})
  28460. ]);
  28461. var customEditorFields = formComponentFields.concat([
  28462. defaultedString('tag', 'textarea'),
  28463. strictString('scriptId'),
  28464. strictString('scriptUrl'),
  28465. defaultedPostMsg('settings', undefined)
  28466. ]);
  28467. var customEditorFieldsOld = formComponentFields.concat([
  28468. defaultedString('tag', 'textarea'),
  28469. strictFunction('init')
  28470. ]);
  28471. var customEditorSchema = valueOf(function (v) {
  28472. return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  28473. return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  28474. });
  28475. });
  28476. var customEditorDataProcessor = string;
  28477. var htmlPanelFields = [
  28478. strictString('type'),
  28479. strictString('html'),
  28480. defaultedStringEnum('presets', 'presentation', [
  28481. 'presentation',
  28482. 'document'
  28483. ])
  28484. ];
  28485. var htmlPanelSchema = objOf(htmlPanelFields);
  28486. var imageToolsFields = formComponentWithLabelFields.concat([strictOf('currentState', objOf([
  28487. strict$1('blob'),
  28488. strictString('url')
  28489. ]))]);
  28490. var imageToolsSchema = objOf(imageToolsFields);
  28491. var collectionFields = formComponentWithLabelFields.concat([defaulted$1('columns', 'auto')]);
  28492. var collectionSchema = objOf(collectionFields);
  28493. var collectionDataProcessor = arrOfObj$1([
  28494. strictString('value'),
  28495. strictString('text'),
  28496. strictString('icon')
  28497. ]);
  28498. var createLabelFields = function (itemsField) {
  28499. return [
  28500. strictString('type'),
  28501. strictString('label'),
  28502. itemsField
  28503. ];
  28504. };
  28505. var tableFields = [
  28506. strictString('type'),
  28507. strictArrayOf('header', string),
  28508. strictArrayOf('cells', arrOf(string))
  28509. ];
  28510. var tableSchema = objOf(tableFields);
  28511. var createItemsField = function (name) {
  28512. return field('items', 'items', strict(), arrOf(valueOf(function (v) {
  28513. return asRaw('Checking item of ' + name, itemSchema$2, v).fold(function (sErr) {
  28514. return Result.error(formatError(sErr));
  28515. }, function (passValue) {
  28516. return Result.value(passValue);
  28517. });
  28518. })));
  28519. };
  28520. var itemSchema$2 = valueThunkOf(function () {
  28521. return chooseProcessor('type', {
  28522. alertbanner: alertBannerSchema,
  28523. bar: objOf(createBarFields(createItemsField('bar'))),
  28524. button: buttonSchema,
  28525. checkbox: checkboxSchema,
  28526. colorinput: colorInputSchema,
  28527. colorpicker: colorPickerSchema,
  28528. dropzone: dropZoneSchema,
  28529. grid: objOf(createGridFields(createItemsField('grid'))),
  28530. iframe: iframeSchema,
  28531. input: inputSchema,
  28532. selectbox: selectBoxSchema,
  28533. sizeinput: sizeInputSchema,
  28534. textarea: textAreaSchema,
  28535. urlinput: urlInputSchema,
  28536. customeditor: customEditorSchema,
  28537. htmlpanel: htmlPanelSchema,
  28538. imagetools: imageToolsSchema,
  28539. collection: collectionSchema,
  28540. label: objOf(createLabelFields(createItemsField('label'))),
  28541. table: tableSchema,
  28542. panel: panelSchema
  28543. });
  28544. });
  28545. var panelFields = [
  28546. strictString('type'),
  28547. defaulted$1('classes', []),
  28548. strictArrayOf('items', itemSchema$2)
  28549. ];
  28550. var panelSchema = objOf(panelFields);
  28551. var tabFields = [
  28552. field('name', 'name', defaultedThunk(function () {
  28553. return generate$1('tab-name');
  28554. }), string),
  28555. strictString('title'),
  28556. strictArrayOf('items', itemSchema$2)
  28557. ];
  28558. var tabPanelFields = [
  28559. strictString('type'),
  28560. strictArrayOfObj('tabs', tabFields)
  28561. ];
  28562. var tabPanelSchema = objOf(tabPanelFields);
  28563. var dialogToggleMenuItemSchema = objOf([
  28564. strictString('type'),
  28565. strictString('name')
  28566. ].concat(commonMenuItemFields));
  28567. var dialogToggleMenuItemDataProcessor = boolean;
  28568. var baseButtonFields = [
  28569. field('name', 'name', defaultedThunk(function () {
  28570. return generate$1('button-name');
  28571. }), string),
  28572. optionString('icon'),
  28573. defaultedStringEnum('align', 'end', [
  28574. 'start',
  28575. 'end'
  28576. ]),
  28577. defaultedBoolean('primary', false),
  28578. defaultedBoolean('disabled', false)
  28579. ];
  28580. var dialogButtonFields = __spreadArrays(baseButtonFields, [strictString('text')]);
  28581. var normalButtonFields = __spreadArrays([strictStringEnum('type', [
  28582. 'submit',
  28583. 'cancel',
  28584. 'custom'
  28585. ])], dialogButtonFields);
  28586. var menuButtonFields = __spreadArrays([
  28587. strictStringEnum('type', ['menu']),
  28588. optionString('text'),
  28589. optionString('tooltip'),
  28590. optionString('icon'),
  28591. strictArrayOf('items', dialogToggleMenuItemSchema)
  28592. ], baseButtonFields);
  28593. var dialogButtonSchema = choose$1('type', {
  28594. submit: normalButtonFields,
  28595. cancel: normalButtonFields,
  28596. custom: normalButtonFields,
  28597. menu: menuButtonFields
  28598. });
  28599. var dialogButtonFields$1 = dialogButtonFields;
  28600. var dialogButtonSchema$1 = dialogButtonSchema;
  28601. var dialogSchema = objOf([
  28602. strictString('title'),
  28603. strictOf('body', chooseProcessor('type', {
  28604. panel: panelSchema,
  28605. tabpanel: tabPanelSchema
  28606. })),
  28607. defaultedString('size', 'normal'),
  28608. strictArrayOf('buttons', dialogButtonSchema$1),
  28609. defaulted$1('initialData', {}),
  28610. defaultedFunction('onAction', noop),
  28611. defaultedFunction('onChange', noop),
  28612. defaultedFunction('onSubmit', noop),
  28613. defaultedFunction('onClose', noop),
  28614. defaultedFunction('onCancel', noop),
  28615. defaulted$1('onTabChange', noop)
  28616. ]);
  28617. var createDialog = function (spec) {
  28618. return asRaw('dialog', dialogSchema, spec);
  28619. };
  28620. var getAllObjects = function (obj) {
  28621. if (isObject(obj)) {
  28622. return [obj].concat(bind(values(obj), getAllObjects));
  28623. } else if (isArray(obj)) {
  28624. return bind(obj, getAllObjects);
  28625. } else {
  28626. return [];
  28627. }
  28628. };
  28629. var isNamedItem = function (obj) {
  28630. return isString(obj.type) && isString(obj.name);
  28631. };
  28632. var dataProcessors = {
  28633. checkbox: checkboxDataProcessor,
  28634. colorinput: colorInputDataProcessor,
  28635. colorpicker: colorPickerDataProcessor,
  28636. dropzone: dropZoneDataProcessor,
  28637. input: inputDataProcessor,
  28638. iframe: iframeDataProcessor,
  28639. sizeinput: sizeInputDataProcessor,
  28640. selectbox: selectBoxDataProcessor,
  28641. size: sizeInputDataProcessor,
  28642. textarea: textAreaDataProcessor,
  28643. urlinput: urlInputDataProcessor,
  28644. customeditor: customEditorDataProcessor,
  28645. collection: collectionDataProcessor,
  28646. togglemenuitem: dialogToggleMenuItemDataProcessor
  28647. };
  28648. var getDataProcessor = function (item) {
  28649. return Option.from(dataProcessors[item.type]);
  28650. };
  28651. var getNamedItems = function (structure) {
  28652. return filter(getAllObjects(structure), isNamedItem);
  28653. };
  28654. var createDataValidator = function (structure) {
  28655. var namedItems = getNamedItems(structure);
  28656. var fields = bind(namedItems, function (item) {
  28657. return getDataProcessor(item).fold(function () {
  28658. return [];
  28659. }, function (schema) {
  28660. return [strictOf(item.name, schema)];
  28661. });
  28662. });
  28663. return objOf(fields);
  28664. };
  28665. var urlDialogButtonSchema = objOf(__spreadArrays([strictStringEnum('type', [
  28666. 'cancel',
  28667. 'custom'
  28668. ])], dialogButtonFields$1));
  28669. var urlDialogSchema = objOf([
  28670. strictString('title'),
  28671. strictString('url'),
  28672. optionNumber('height'),
  28673. optionNumber('width'),
  28674. optionArrayOf('buttons', urlDialogButtonSchema),
  28675. defaultedFunction('onAction', noop),
  28676. defaultedFunction('onCancel', noop),
  28677. defaultedFunction('onClose', noop),
  28678. defaultedFunction('onMessage', noop)
  28679. ]);
  28680. var createUrlDialog = function (spec) {
  28681. return asRaw('dialog', urlDialogSchema, spec);
  28682. };
  28683. var extract$1 = function (structure) {
  28684. var internalDialog = getOrDie(createDialog(structure));
  28685. var dataValidator = createDataValidator(structure);
  28686. var initialData = structure.initialData;
  28687. return {
  28688. internalDialog: internalDialog,
  28689. dataValidator: dataValidator,
  28690. initialData: initialData
  28691. };
  28692. };
  28693. var DialogManager = {
  28694. open: function (factory, structure) {
  28695. var extraction = extract$1(structure);
  28696. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  28697. },
  28698. openUrl: function (factory, structure) {
  28699. var internalDialog = getOrDie(createUrlDialog(structure));
  28700. return factory(internalDialog);
  28701. },
  28702. redial: function (structure) {
  28703. return extract$1(structure);
  28704. }
  28705. };
  28706. var value$3 = function () {
  28707. var subject = Cell(Option.none());
  28708. var clear = function () {
  28709. subject.set(Option.none());
  28710. };
  28711. var set = function (s) {
  28712. subject.set(Option.some(s));
  28713. };
  28714. var on = function (f) {
  28715. subject.get().each(f);
  28716. };
  28717. var isSet = function () {
  28718. return subject.get().isSome();
  28719. };
  28720. return {
  28721. clear: clear,
  28722. set: set,
  28723. isSet: isSet,
  28724. on: on
  28725. };
  28726. };
  28727. var toValidValues = function (values) {
  28728. var errors = [];
  28729. var result = {};
  28730. each$1(values, function (value, name) {
  28731. value.fold(function () {
  28732. errors.push(name);
  28733. }, function (v) {
  28734. result[name] = v;
  28735. });
  28736. });
  28737. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  28738. };
  28739. var renderBodyPanel = function (spec, backstage) {
  28740. var memForm = record(Form.sketch(function (parts) {
  28741. return {
  28742. dom: {
  28743. tag: 'div',
  28744. classes: ['tox-form'].concat(spec.classes)
  28745. },
  28746. components: map(spec.items, function (item) {
  28747. return interpretInForm(parts, item, backstage);
  28748. })
  28749. };
  28750. }));
  28751. return {
  28752. dom: {
  28753. tag: 'div',
  28754. classes: ['tox-dialog__body']
  28755. },
  28756. components: [{
  28757. dom: {
  28758. tag: 'div',
  28759. classes: ['tox-dialog__body-content']
  28760. },
  28761. components: [memForm.asSpec()]
  28762. }],
  28763. behaviours: derive$1([
  28764. Keying.config({
  28765. mode: 'acyclic',
  28766. useTabstopAt: not(NavigableObject.isPseudoStop)
  28767. }),
  28768. ComposingConfigs.memento(memForm),
  28769. RepresentingConfigs.memento(memForm, {
  28770. postprocess: function (formValue) {
  28771. return toValidValues(formValue).fold(function (err) {
  28772. domGlobals.console.error(err);
  28773. return {};
  28774. }, function (vals) {
  28775. return vals;
  28776. });
  28777. }
  28778. })
  28779. ])
  28780. };
  28781. };
  28782. var factory$j = function (detail, spec) {
  28783. return {
  28784. uid: detail.uid,
  28785. dom: detail.dom,
  28786. components: detail.components,
  28787. events: events$7(detail.action),
  28788. behaviours: augment(detail.tabButtonBehaviours, [
  28789. Focusing.config({}),
  28790. Keying.config({
  28791. mode: 'execution',
  28792. useSpace: true,
  28793. useEnter: true
  28794. }),
  28795. Representing.config({
  28796. store: {
  28797. mode: 'memory',
  28798. initialValue: detail.value
  28799. }
  28800. })
  28801. ]),
  28802. domModification: detail.domModification
  28803. };
  28804. };
  28805. var TabButton = single$2({
  28806. name: 'TabButton',
  28807. configFields: [
  28808. defaulted$1('uid', undefined),
  28809. strict$1('value'),
  28810. field('dom', 'dom', mergeWithThunk(function () {
  28811. return {
  28812. attributes: {
  28813. 'role': 'tab',
  28814. 'id': generate$1('aria'),
  28815. 'aria-selected': 'false'
  28816. }
  28817. };
  28818. }), anyValue$1()),
  28819. option('action'),
  28820. defaulted$1('domModification', {}),
  28821. field$1('tabButtonBehaviours', [
  28822. Focusing,
  28823. Keying,
  28824. Representing
  28825. ]),
  28826. strict$1('view')
  28827. ],
  28828. factory: factory$j
  28829. });
  28830. var schema$y = constant([
  28831. strict$1('tabs'),
  28832. strict$1('dom'),
  28833. defaulted$1('clickToDismiss', false),
  28834. field$1('tabbarBehaviours', [
  28835. Highlighting,
  28836. Keying
  28837. ]),
  28838. markers([
  28839. 'tabClass',
  28840. 'selectedClass'
  28841. ])
  28842. ]);
  28843. var tabsPart = group({
  28844. factory: TabButton,
  28845. name: 'tabs',
  28846. unit: 'tab',
  28847. overrides: function (barDetail) {
  28848. var dismissTab$1 = function (tabbar, button) {
  28849. Highlighting.dehighlight(tabbar, button);
  28850. emitWith(tabbar, dismissTab(), {
  28851. tabbar: tabbar,
  28852. button: button
  28853. });
  28854. };
  28855. var changeTab$1 = function (tabbar, button) {
  28856. Highlighting.highlight(tabbar, button);
  28857. emitWith(tabbar, changeTab(), {
  28858. tabbar: tabbar,
  28859. button: button
  28860. });
  28861. };
  28862. return {
  28863. action: function (button) {
  28864. var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  28865. var activeButton = Highlighting.isHighlighted(tabbar, button);
  28866. var response = function () {
  28867. if (activeButton && barDetail.clickToDismiss) {
  28868. return dismissTab$1;
  28869. } else if (!activeButton) {
  28870. return changeTab$1;
  28871. } else {
  28872. return noop;
  28873. }
  28874. }();
  28875. response(tabbar, button);
  28876. },
  28877. domModification: { classes: [barDetail.markers.tabClass] }
  28878. };
  28879. }
  28880. });
  28881. var parts$g = constant([tabsPart]);
  28882. var factory$k = function (detail, components, spec, externals) {
  28883. return {
  28884. 'uid': detail.uid,
  28885. 'dom': detail.dom,
  28886. 'components': components,
  28887. 'debug.sketcher': 'Tabbar',
  28888. 'domModification': { attributes: { role: 'tablist' } },
  28889. 'behaviours': augment(detail.tabbarBehaviours, [
  28890. Highlighting.config({
  28891. highlightClass: detail.markers.selectedClass,
  28892. itemClass: detail.markers.tabClass,
  28893. onHighlight: function (tabbar, tab) {
  28894. set$1(tab.element(), 'aria-selected', 'true');
  28895. },
  28896. onDehighlight: function (tabbar, tab) {
  28897. set$1(tab.element(), 'aria-selected', 'false');
  28898. }
  28899. }),
  28900. Keying.config({
  28901. mode: 'flow',
  28902. getInitial: function (tabbar) {
  28903. return Highlighting.getHighlighted(tabbar).map(function (tab) {
  28904. return tab.element();
  28905. });
  28906. },
  28907. selector: '.' + detail.markers.tabClass,
  28908. executeOnMove: true
  28909. })
  28910. ])
  28911. };
  28912. };
  28913. var Tabbar = composite$1({
  28914. name: 'Tabbar',
  28915. configFields: schema$y(),
  28916. partFields: parts$g(),
  28917. factory: factory$k
  28918. });
  28919. var factory$l = function (detail, spec) {
  28920. return {
  28921. uid: detail.uid,
  28922. dom: detail.dom,
  28923. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  28924. domModification: { attributes: { role: 'tabpanel' } }
  28925. };
  28926. };
  28927. var Tabview = single$2({
  28928. name: 'Tabview',
  28929. configFields: [field$1('tabviewBehaviours', [Replacing])],
  28930. factory: factory$l
  28931. });
  28932. var schema$z = constant([
  28933. defaulted$1('selectFirst', true),
  28934. onHandler('onChangeTab'),
  28935. onHandler('onDismissTab'),
  28936. defaulted$1('tabs', []),
  28937. field$1('tabSectionBehaviours', [])
  28938. ]);
  28939. var barPart = required({
  28940. factory: Tabbar,
  28941. schema: [
  28942. strict$1('dom'),
  28943. strictObjOf('markers', [
  28944. strict$1('tabClass'),
  28945. strict$1('selectedClass')
  28946. ])
  28947. ],
  28948. name: 'tabbar',
  28949. defaults: function (detail) {
  28950. return { tabs: detail.tabs };
  28951. }
  28952. });
  28953. var viewPart = required({
  28954. factory: Tabview,
  28955. name: 'tabview'
  28956. });
  28957. var parts$h = constant([
  28958. barPart,
  28959. viewPart
  28960. ]);
  28961. var factory$m = function (detail, components, spec, externals) {
  28962. var changeTab$1 = function (button) {
  28963. var tabValue = Representing.getValue(button);
  28964. getPart(button, detail, 'tabview').each(function (tabview) {
  28965. var tabWithValue = find(detail.tabs, function (t) {
  28966. return t.value === tabValue;
  28967. });
  28968. tabWithValue.each(function (tabData) {
  28969. var panel = tabData.view();
  28970. getOpt(button.element(), 'id').each(function (id) {
  28971. set$1(tabview.element(), 'aria-labelledby', id);
  28972. });
  28973. Replacing.set(tabview, panel);
  28974. detail.onChangeTab(tabview, button, panel);
  28975. });
  28976. });
  28977. };
  28978. var changeTabBy = function (section, byPred) {
  28979. getPart(section, detail, 'tabbar').each(function (tabbar) {
  28980. byPred(tabbar).each(emitExecute);
  28981. });
  28982. };
  28983. return {
  28984. uid: detail.uid,
  28985. dom: detail.dom,
  28986. components: components,
  28987. behaviours: get$c(detail.tabSectionBehaviours),
  28988. events: derive(flatten([
  28989. detail.selectFirst ? [runOnAttached(function (section, simulatedEvent) {
  28990. changeTabBy(section, Highlighting.getFirst);
  28991. })] : [],
  28992. [
  28993. run(changeTab(), function (section, simulatedEvent) {
  28994. var button = simulatedEvent.event().button();
  28995. changeTab$1(button);
  28996. }),
  28997. run(dismissTab(), function (section, simulatedEvent) {
  28998. var button = simulatedEvent.event().button();
  28999. detail.onDismissTab(section, button);
  29000. })
  29001. ]
  29002. ])),
  29003. apis: {
  29004. getViewItems: function (section) {
  29005. return getPart(section, detail, 'tabview').map(function (tabview) {
  29006. return Replacing.contents(tabview);
  29007. }).getOr([]);
  29008. },
  29009. showTab: function (section, tabKey) {
  29010. var getTabIfNotActive = function (tabbar) {
  29011. var candidates = Highlighting.getCandidates(tabbar);
  29012. var optTab = find(candidates, function (c) {
  29013. return Representing.getValue(c) === tabKey;
  29014. });
  29015. return optTab.filter(function (tab) {
  29016. return !Highlighting.isHighlighted(tabbar, tab);
  29017. });
  29018. };
  29019. changeTabBy(section, getTabIfNotActive);
  29020. }
  29021. }
  29022. };
  29023. };
  29024. var TabSection = composite$1({
  29025. name: 'TabSection',
  29026. configFields: schema$z(),
  29027. partFields: parts$h(),
  29028. factory: factory$m,
  29029. apis: {
  29030. getViewItems: function (apis, component) {
  29031. return apis.getViewItems(component);
  29032. },
  29033. showTab: function (apis, component, tabKey) {
  29034. apis.showTab(component, tabKey);
  29035. }
  29036. }
  29037. });
  29038. var measureHeights = function (allTabs, tabview, tabviewComp) {
  29039. return map(allTabs, function (tab, i) {
  29040. Replacing.set(tabviewComp, allTabs[i].view());
  29041. var rect = tabview.dom().getBoundingClientRect();
  29042. Replacing.set(tabviewComp, []);
  29043. return rect.height;
  29044. });
  29045. };
  29046. var getMaxHeight = function (heights) {
  29047. return head(sort(heights, function (a, b) {
  29048. if (a > b) {
  29049. return -1;
  29050. } else if (a < b) {
  29051. return +1;
  29052. } else {
  29053. return 0;
  29054. }
  29055. }));
  29056. };
  29057. var getMaxTabviewHeight = function (dialog, tabview, tablist) {
  29058. var documentElement$1 = documentElement(dialog).dom();
  29059. var rootElm = ancestor$2(dialog, '.tox-dialog-wrap').getOr(dialog);
  29060. var isFixed = get$4(rootElm, 'position') === 'fixed';
  29061. var maxHeight;
  29062. if (isFixed) {
  29063. maxHeight = Math.max(documentElement$1.clientHeight, domGlobals.window.innerHeight);
  29064. } else {
  29065. maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  29066. }
  29067. var tabviewHeight = get$6(tabview);
  29068. var isTabListBeside = tabview.dom().offsetLeft >= tablist.dom().offsetLeft + get$7(tablist);
  29069. var currentTabHeight = isTabListBeside ? Math.max(get$6(tablist), tabviewHeight) : tabviewHeight;
  29070. var dialogTopMargin = parseInt(get$4(dialog, 'margin-top'), 10) || 0;
  29071. var dialogBottomMargin = parseInt(get$4(dialog, 'margin-bottom'), 10) || 0;
  29072. var dialogHeight = get$6(dialog) + dialogTopMargin + dialogBottomMargin;
  29073. var chromeHeight = dialogHeight - currentTabHeight;
  29074. return maxHeight - chromeHeight;
  29075. };
  29076. var showTab = function (allTabs, comp) {
  29077. head(allTabs).each(function (tab) {
  29078. return TabSection.showTab(comp, tab.value);
  29079. });
  29080. };
  29081. var setTabviewHeight = function (tabview, height) {
  29082. set$2(tabview, 'height', height + 'px');
  29083. if (!detect$3().browser.isIE()) {
  29084. set$2(tabview, 'flex-basis', height + 'px');
  29085. } else {
  29086. remove$6(tabview, 'flex-basis');
  29087. }
  29088. };
  29089. var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  29090. ancestor$2(dialogBody, '[role="dialog"]').each(function (dialog) {
  29091. descendant$1(dialog, '[role="tablist"]').each(function (tablist) {
  29092. maxTabHeight.get().map(function (height) {
  29093. set$2(tabview, 'height', '0');
  29094. set$2(tabview, 'flex-basis', '0');
  29095. return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  29096. }).each(function (height) {
  29097. setTabviewHeight(tabview, height);
  29098. });
  29099. });
  29100. });
  29101. };
  29102. var getTabview = function (dialog) {
  29103. return descendant$1(dialog, '[role="tabpanel"]');
  29104. };
  29105. var setMode = function (allTabs) {
  29106. var smartTabHeight = function () {
  29107. var maxTabHeight = Cell(Option.none());
  29108. var extraEvents = [
  29109. runOnAttached(function (comp) {
  29110. var dialog = comp.element();
  29111. getTabview(dialog).each(function (tabview) {
  29112. set$2(tabview, 'visibility', 'hidden');
  29113. comp.getSystem().getByDom(tabview).toOption().each(function (tabviewComp) {
  29114. var heights = measureHeights(allTabs, tabview, tabviewComp);
  29115. var maxTabHeightOpt = getMaxHeight(heights);
  29116. maxTabHeight.set(maxTabHeightOpt);
  29117. });
  29118. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29119. remove$6(tabview, 'visibility');
  29120. showTab(allTabs, comp);
  29121. global$2.requestAnimationFrame(function () {
  29122. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29123. });
  29124. });
  29125. }),
  29126. run(windowResize(), function (comp) {
  29127. var dialog = comp.element();
  29128. getTabview(dialog).each(function (tabview) {
  29129. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29130. });
  29131. }),
  29132. run(formResizeEvent, function (comp, se) {
  29133. var dialog = comp.element();
  29134. getTabview(dialog).each(function (tabview) {
  29135. var oldFocus = active();
  29136. set$2(tabview, 'visibility', 'hidden');
  29137. var oldHeight = getRaw(tabview, 'height').map(function (h) {
  29138. return parseInt(h, 10);
  29139. });
  29140. remove$6(tabview, 'height');
  29141. remove$6(tabview, 'flex-basis');
  29142. var newHeight = tabview.dom().getBoundingClientRect().height;
  29143. var hasGrown = oldHeight.forall(function (h) {
  29144. return newHeight > h;
  29145. });
  29146. if (hasGrown) {
  29147. maxTabHeight.set(Option.from(newHeight));
  29148. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29149. } else {
  29150. oldHeight.each(function (h) {
  29151. setTabviewHeight(tabview, h);
  29152. });
  29153. }
  29154. remove$6(tabview, 'visibility');
  29155. oldFocus.each(focus$1);
  29156. });
  29157. })
  29158. ];
  29159. var selectFirst = false;
  29160. return {
  29161. extraEvents: extraEvents,
  29162. selectFirst: selectFirst
  29163. };
  29164. }();
  29165. var naiveTabHeight = function () {
  29166. var extraEvents = [];
  29167. var selectFirst = true;
  29168. return {
  29169. extraEvents: extraEvents,
  29170. selectFirst: selectFirst
  29171. };
  29172. }();
  29173. return {
  29174. smartTabHeight: smartTabHeight,
  29175. naiveTabHeight: naiveTabHeight
  29176. };
  29177. };
  29178. var SendDataToSectionChannel = 'send-data-to-section';
  29179. var SendDataToViewChannel = 'send-data-to-view';
  29180. var renderTabPanel = function (spec, backstage) {
  29181. var storedValue = Cell({});
  29182. var updateDataWithForm = function (form) {
  29183. var formData = Representing.getValue(form);
  29184. var validData = toValidValues(formData).getOr({});
  29185. var currentData = storedValue.get();
  29186. var newData = deepMerge(currentData, validData);
  29187. storedValue.set(newData);
  29188. };
  29189. var setDataOnForm = function (form) {
  29190. var tabData = storedValue.get();
  29191. Representing.setValue(form, tabData);
  29192. };
  29193. var oldTab = Cell(null);
  29194. var allTabs = map(spec.tabs, function (tab) {
  29195. return {
  29196. value: tab.name,
  29197. dom: {
  29198. tag: 'div',
  29199. classes: ['tox-dialog__body-nav-item'],
  29200. innerHtml: backstage.shared.providers.translate(tab.title)
  29201. },
  29202. view: function () {
  29203. return [Form.sketch(function (parts) {
  29204. return {
  29205. dom: {
  29206. tag: 'div',
  29207. classes: ['tox-form']
  29208. },
  29209. components: map(tab.items, function (item) {
  29210. return interpretInForm(parts, item, backstage);
  29211. }),
  29212. formBehaviours: derive$1([
  29213. Keying.config({
  29214. mode: 'acyclic',
  29215. useTabstopAt: not(NavigableObject.isPseudoStop)
  29216. }),
  29217. config('TabView.form.events', [
  29218. runOnAttached(setDataOnForm),
  29219. runOnDetached(updateDataWithForm)
  29220. ]),
  29221. Receiving.config({
  29222. channels: wrapAll$1([
  29223. {
  29224. key: SendDataToSectionChannel,
  29225. value: { onReceive: updateDataWithForm }
  29226. },
  29227. {
  29228. key: SendDataToViewChannel,
  29229. value: { onReceive: setDataOnForm }
  29230. }
  29231. ])
  29232. })
  29233. ])
  29234. };
  29235. })];
  29236. }
  29237. };
  29238. });
  29239. var tabMode = setMode(allTabs).smartTabHeight;
  29240. return TabSection.sketch({
  29241. dom: {
  29242. tag: 'div',
  29243. classes: ['tox-dialog__body']
  29244. },
  29245. onChangeTab: function (section, button, _viewItems) {
  29246. var name = Representing.getValue(button);
  29247. emitWith(section, formTabChangeEvent, {
  29248. name: name,
  29249. oldName: oldTab.get()
  29250. });
  29251. oldTab.set(name);
  29252. },
  29253. tabs: allTabs,
  29254. components: [
  29255. TabSection.parts().tabbar({
  29256. dom: {
  29257. tag: 'div',
  29258. classes: ['tox-dialog__body-nav']
  29259. },
  29260. components: [Tabbar.parts().tabs({})],
  29261. markers: {
  29262. tabClass: 'tox-tab',
  29263. selectedClass: 'tox-dialog__body-nav-item--active'
  29264. },
  29265. tabbarBehaviours: derive$1([Tabstopping.config({})])
  29266. }),
  29267. TabSection.parts().tabview({
  29268. dom: {
  29269. tag: 'div',
  29270. classes: ['tox-dialog__body-content']
  29271. }
  29272. })
  29273. ],
  29274. selectFirst: tabMode.selectFirst,
  29275. tabSectionBehaviours: derive$1([
  29276. config('tabpanel', tabMode.extraEvents),
  29277. Keying.config({ mode: 'acyclic' }),
  29278. Composing.config({
  29279. find: function (comp) {
  29280. return head(TabSection.getViewItems(comp));
  29281. }
  29282. }),
  29283. Representing.config({
  29284. store: {
  29285. mode: 'manual',
  29286. getValue: function (tsection) {
  29287. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  29288. return storedValue.get();
  29289. },
  29290. setValue: function (tsection, value) {
  29291. storedValue.set(value);
  29292. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  29293. }
  29294. }
  29295. })
  29296. ])
  29297. });
  29298. };
  29299. var dialogChannel = generate$1('update-dialog');
  29300. var titleChannel = generate$1('update-title');
  29301. var bodyChannel = generate$1('update-body');
  29302. var footerChannel = generate$1('update-footer');
  29303. var bodySendMessageChannel = generate$1('body-send-message');
  29304. var renderBody = function (spec, id, backstage, ariaAttrs) {
  29305. var renderComponents = function (incoming) {
  29306. switch (incoming.body.type) {
  29307. case 'tabpanel': {
  29308. return [renderTabPanel(incoming.body, backstage)];
  29309. }
  29310. default: {
  29311. return [renderBodyPanel(incoming.body, backstage)];
  29312. }
  29313. }
  29314. };
  29315. var updateState = function (_comp, incoming) {
  29316. return Option.some({
  29317. isTabPanel: function () {
  29318. return incoming.body.type === 'tabpanel';
  29319. }
  29320. });
  29321. };
  29322. var ariaAttributes = { 'aria-live': 'polite' };
  29323. return {
  29324. dom: {
  29325. tag: 'div',
  29326. classes: ['tox-dialog__content-js'],
  29327. attributes: __assign(__assign({}, id.map(function (x) {
  29328. return { id: x };
  29329. }).getOr({})), ariaAttrs ? ariaAttributes : {})
  29330. },
  29331. components: [],
  29332. behaviours: derive$1([
  29333. ComposingConfigs.childAt(0),
  29334. Reflecting.config({
  29335. channel: bodyChannel,
  29336. updateState: updateState,
  29337. renderComponents: renderComponents,
  29338. initialData: spec
  29339. })
  29340. ])
  29341. };
  29342. };
  29343. var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  29344. return renderBody(spec, Option.some(contentId), backstage, ariaAttrs);
  29345. };
  29346. var renderModalBody = function (spec, backstage) {
  29347. var bodySpec = renderBody(spec, Option.none(), backstage, false);
  29348. return ModalDialog.parts().body(bodySpec);
  29349. };
  29350. var renderIframeBody = function (spec) {
  29351. var bodySpec = {
  29352. dom: {
  29353. tag: 'div',
  29354. classes: ['tox-dialog__content-js']
  29355. },
  29356. components: [{
  29357. dom: {
  29358. tag: 'div',
  29359. classes: ['tox-dialog__body-iframe']
  29360. },
  29361. components: [NavigableObject.craft({
  29362. dom: {
  29363. tag: 'iframe',
  29364. attributes: { src: spec.url }
  29365. },
  29366. behaviours: derive$1([
  29367. Tabstopping.config({}),
  29368. Focusing.config({})
  29369. ])
  29370. })]
  29371. }],
  29372. behaviours: derive$1([Keying.config({
  29373. mode: 'acyclic',
  29374. useTabstopAt: not(NavigableObject.isPseudoStop)
  29375. })])
  29376. };
  29377. return ModalDialog.parts().body(bodySpec);
  29378. };
  29379. var initCommonEvents = function (fireApiEvent, extras) {
  29380. return [
  29381. runWithTarget(focusin(), NavigableObject.onFocus),
  29382. fireApiEvent(formCloseEvent, function (api, spec) {
  29383. extras.onClose();
  29384. spec.onClose();
  29385. }),
  29386. fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  29387. spec.onCancel(api);
  29388. emit(self, formCloseEvent);
  29389. }),
  29390. run(formUnblockEvent, function (c, se) {
  29391. return extras.onUnblock();
  29392. }),
  29393. run(formBlockEvent, function (c, se) {
  29394. return extras.onBlock(se.event());
  29395. })
  29396. ];
  29397. };
  29398. var initUrlDialog = function (getInstanceApi, extras) {
  29399. var fireApiEvent = function (eventName, f) {
  29400. return run(eventName, function (c, se) {
  29401. withSpec(c, function (spec, _c) {
  29402. f(getInstanceApi(), spec, se.event(), c);
  29403. });
  29404. });
  29405. };
  29406. var withSpec = function (c, f) {
  29407. Reflecting.getState(c).get().each(function (currentDialog) {
  29408. f(currentDialog, c);
  29409. });
  29410. };
  29411. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [fireApiEvent(formActionEvent, function (api, spec, event) {
  29412. spec.onAction(api, { name: event.name() });
  29413. })]);
  29414. };
  29415. var initDialog = function (getInstanceApi, extras) {
  29416. var fireApiEvent = function (eventName, f) {
  29417. return run(eventName, function (c, se) {
  29418. withSpec(c, function (spec, _c) {
  29419. f(getInstanceApi(), spec, se.event(), c);
  29420. });
  29421. });
  29422. };
  29423. var withSpec = function (c, f) {
  29424. Reflecting.getState(c).get().each(function (currentDialogInit) {
  29425. f(currentDialogInit.internalDialog, c);
  29426. });
  29427. };
  29428. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [
  29429. fireApiEvent(formSubmitEvent, function (api, spec) {
  29430. return spec.onSubmit(api);
  29431. }),
  29432. fireApiEvent(formChangeEvent, function (api, spec, event) {
  29433. spec.onChange(api, { name: event.name() });
  29434. }),
  29435. fireApiEvent(formActionEvent, function (api, spec, event, component) {
  29436. var focusIn = function () {
  29437. return Keying.focusIn(component);
  29438. };
  29439. var current = active();
  29440. spec.onAction(api, {
  29441. name: event.name(),
  29442. value: event.value()
  29443. });
  29444. active().fold(function () {
  29445. focusIn();
  29446. }, function (focused) {
  29447. if (!contains$2(component.element(), focused) || has$1(focused, 'disabled')) {
  29448. focusIn();
  29449. } else if (contains$2(focused, current.getOrNull()) && has$1(current.getOrDie(), 'disabled')) {
  29450. focusIn();
  29451. }
  29452. });
  29453. }),
  29454. fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  29455. spec.onTabChange(api, {
  29456. newTabName: event.name(),
  29457. oldTabName: event.oldName()
  29458. });
  29459. }),
  29460. runOnDetached(function (component) {
  29461. var api = getInstanceApi();
  29462. Representing.setValue(component, api.getData());
  29463. })
  29464. ]);
  29465. };
  29466. var SilverDialogEvents = {
  29467. initUrlDialog: initUrlDialog,
  29468. initDialog: initDialog
  29469. };
  29470. var makeButton = function (button, backstage) {
  29471. return renderFooterButton(button, button.type, backstage);
  29472. };
  29473. var lookup$2 = function (compInSystem, footerButtons, buttonName) {
  29474. return find(footerButtons, function (button) {
  29475. return button.name === buttonName;
  29476. }).bind(function (memButton) {
  29477. return memButton.memento.getOpt(compInSystem);
  29478. });
  29479. };
  29480. var renderComponents = function (_data, state) {
  29481. var footerButtons = state.map(function (s) {
  29482. return s.footerButtons;
  29483. }).getOr([]);
  29484. var buttonGroups = partition(footerButtons, function (button) {
  29485. return button.align === 'start';
  29486. });
  29487. var makeGroup = function (edge, buttons) {
  29488. return Container.sketch({
  29489. dom: {
  29490. tag: 'div',
  29491. classes: ['tox-dialog__footer-' + edge]
  29492. },
  29493. components: map(buttons, function (button) {
  29494. return button.memento.asSpec();
  29495. })
  29496. });
  29497. };
  29498. var startButtons = makeGroup('start', buttonGroups.pass);
  29499. var endButtons = makeGroup('end', buttonGroups.fail);
  29500. return [
  29501. startButtons,
  29502. endButtons
  29503. ];
  29504. };
  29505. var renderFooter = function (initSpec, backstage) {
  29506. var updateState = function (_comp, data) {
  29507. var footerButtons = map(data.buttons, function (button) {
  29508. var memButton = record(makeButton(button, backstage));
  29509. return {
  29510. name: button.name,
  29511. align: button.align,
  29512. memento: memButton
  29513. };
  29514. });
  29515. var lookupByName = function (compInSystem, buttonName) {
  29516. return lookup$2(compInSystem, footerButtons, buttonName);
  29517. };
  29518. return Option.some({
  29519. lookupByName: lookupByName,
  29520. footerButtons: footerButtons
  29521. });
  29522. };
  29523. return {
  29524. dom: fromHtml$2('<div class="tox-dialog__footer"></div>'),
  29525. components: [],
  29526. behaviours: derive$1([Reflecting.config({
  29527. channel: footerChannel,
  29528. initialData: initSpec,
  29529. updateState: updateState,
  29530. renderComponents: renderComponents
  29531. })])
  29532. };
  29533. };
  29534. var renderInlineFooter = function (initSpec, backstage) {
  29535. return renderFooter(initSpec, backstage);
  29536. };
  29537. var renderModalFooter = function (initSpec, backstage) {
  29538. return ModalDialog.parts().footer(renderFooter(initSpec, backstage));
  29539. };
  29540. var getCompByName = function (access, name) {
  29541. var root = access.getRoot();
  29542. if (root.getSystem().isConnected()) {
  29543. var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  29544. return Form.getField(form_1, name).fold(function () {
  29545. var footer = access.getFooter();
  29546. var footerState = Reflecting.getState(footer);
  29547. return footerState.get().bind(function (f) {
  29548. return f.lookupByName(form_1, name);
  29549. });
  29550. }, function (comp) {
  29551. return Option.some(comp);
  29552. });
  29553. } else {
  29554. return Option.none();
  29555. }
  29556. };
  29557. var validateData = function (access, data) {
  29558. var root = access.getRoot();
  29559. return Reflecting.getState(root).get().map(function (dialogState) {
  29560. return getOrDie(asRaw('data', dialogState.dataValidator, data));
  29561. }).getOr(data);
  29562. };
  29563. var getDialogApi = function (access, doRedial, menuItemStates) {
  29564. var withRoot = function (f) {
  29565. var root = access.getRoot();
  29566. if (root.getSystem().isConnected()) {
  29567. f(root);
  29568. }
  29569. };
  29570. var getData = function () {
  29571. var root = access.getRoot();
  29572. var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  29573. var representedValues = Representing.getValue(valueComp);
  29574. var menuItemCurrentState = map$1(menuItemStates, function (cell) {
  29575. return cell.get();
  29576. });
  29577. return __assign(__assign({}, representedValues), menuItemCurrentState);
  29578. };
  29579. var setData = function (newData) {
  29580. withRoot(function (_) {
  29581. var prevData = instanceApi.getData();
  29582. var mergedData = __assign(__assign({}, prevData), newData);
  29583. var newInternalData = validateData(access, mergedData);
  29584. var form = access.getFormWrapper();
  29585. Representing.setValue(form, newInternalData);
  29586. each$1(menuItemStates, function (v, k) {
  29587. if (has(mergedData, k)) {
  29588. v.set(mergedData[k]);
  29589. }
  29590. });
  29591. });
  29592. };
  29593. var disable = function (name) {
  29594. getCompByName(access, name).each(Disabling.disable);
  29595. };
  29596. var enable = function (name) {
  29597. getCompByName(access, name).each(Disabling.enable);
  29598. };
  29599. var focus = function (name) {
  29600. getCompByName(access, name).each(Focusing.focus);
  29601. };
  29602. var block = function (message) {
  29603. if (!isString(message)) {
  29604. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  29605. }
  29606. withRoot(function (root) {
  29607. emitWith(root, formBlockEvent, { message: message });
  29608. });
  29609. };
  29610. var unblock = function () {
  29611. withRoot(function (root) {
  29612. emit(root, formUnblockEvent);
  29613. });
  29614. };
  29615. var showTab = function (name) {
  29616. withRoot(function (_) {
  29617. var body = access.getBody();
  29618. var bodyState = Reflecting.getState(body);
  29619. if (bodyState.get().exists(function (b) {
  29620. return b.isTabPanel();
  29621. })) {
  29622. Composing.getCurrent(body).each(function (tabSection) {
  29623. TabSection.showTab(tabSection, name);
  29624. });
  29625. }
  29626. });
  29627. };
  29628. var redial = function (d) {
  29629. withRoot(function (root) {
  29630. var dialogInit = doRedial(d);
  29631. root.getSystem().broadcastOn([dialogChannel], dialogInit);
  29632. root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  29633. root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  29634. root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  29635. instanceApi.setData(dialogInit.initialData);
  29636. });
  29637. };
  29638. var close = function () {
  29639. withRoot(function (root) {
  29640. emit(root, formCloseEvent);
  29641. });
  29642. };
  29643. var instanceApi = {
  29644. getData: getData,
  29645. setData: setData,
  29646. disable: disable,
  29647. enable: enable,
  29648. focus: focus,
  29649. block: block,
  29650. unblock: unblock,
  29651. showTab: showTab,
  29652. redial: redial,
  29653. close: close
  29654. };
  29655. return instanceApi;
  29656. };
  29657. var isTouch = global$8.deviceType.isTouch();
  29658. var hiddenHeader = function (title, close) {
  29659. return {
  29660. dom: {
  29661. tag: 'div',
  29662. styles: { display: 'none' },
  29663. classes: ['tox-dialog__header']
  29664. },
  29665. components: [
  29666. title,
  29667. close
  29668. ]
  29669. };
  29670. };
  29671. var pClose = function (onClose, providersBackstage) {
  29672. return ModalDialog.parts().close(Button.sketch({
  29673. dom: {
  29674. tag: 'button',
  29675. classes: [
  29676. 'tox-button',
  29677. 'tox-button--icon',
  29678. 'tox-button--naked'
  29679. ],
  29680. attributes: {
  29681. 'type': 'button',
  29682. 'aria-label': providersBackstage.translate('Close')
  29683. }
  29684. },
  29685. action: onClose,
  29686. buttonBehaviours: derive$1([Tabstopping.config({})])
  29687. }));
  29688. };
  29689. var pUntitled = function () {
  29690. return ModalDialog.parts().title({
  29691. dom: {
  29692. tag: 'div',
  29693. classes: ['tox-dialog__title'],
  29694. innerHtml: '',
  29695. styles: { display: 'none' }
  29696. }
  29697. });
  29698. };
  29699. var pBodyMessage = function (message, providersBackstage) {
  29700. return ModalDialog.parts().body({
  29701. dom: {
  29702. tag: 'div',
  29703. classes: ['tox-dialog__body']
  29704. },
  29705. components: [{
  29706. dom: {
  29707. tag: 'div',
  29708. classes: ['tox-dialog__body-content']
  29709. },
  29710. components: [{ dom: fromHtml$2('<p>' + providersBackstage.translate(message) + '</p>') }]
  29711. }]
  29712. });
  29713. };
  29714. var pFooter = function (buttons) {
  29715. return ModalDialog.parts().footer({
  29716. dom: {
  29717. tag: 'div',
  29718. classes: ['tox-dialog__footer']
  29719. },
  29720. components: buttons
  29721. });
  29722. };
  29723. var pFooterGroup = function (startButtons, endButtons) {
  29724. return [
  29725. Container.sketch({
  29726. dom: {
  29727. tag: 'div',
  29728. classes: ['tox-dialog__footer-start']
  29729. },
  29730. components: startButtons
  29731. }),
  29732. Container.sketch({
  29733. dom: {
  29734. tag: 'div',
  29735. classes: ['tox-dialog__footer-end']
  29736. },
  29737. components: endButtons
  29738. })
  29739. ];
  29740. };
  29741. var renderDialog = function (spec) {
  29742. var _a;
  29743. var dialogClass = 'tox-dialog';
  29744. var blockerClass = dialogClass + '-wrap';
  29745. var blockerBackdropClass = blockerClass + '__backdrop';
  29746. var scrollLockClass = dialogClass + '__disable-scroll';
  29747. return ModalDialog.sketch({
  29748. lazySink: spec.lazySink,
  29749. onEscape: function (comp) {
  29750. spec.onEscape(comp);
  29751. return Option.some(true);
  29752. },
  29753. useTabstopAt: function (elem) {
  29754. return !NavigableObject.isPseudoStop(elem);
  29755. },
  29756. dom: {
  29757. tag: 'div',
  29758. classes: [dialogClass].concat(spec.extraClasses),
  29759. styles: __assign({ position: 'relative' }, spec.extraStyles)
  29760. },
  29761. components: __spreadArrays([
  29762. spec.header,
  29763. spec.body
  29764. ], spec.footer.toArray()),
  29765. parts: {
  29766. blocker: {
  29767. dom: fromHtml$2('<div class="' + blockerClass + '"></div>'),
  29768. components: [{
  29769. dom: {
  29770. tag: 'div',
  29771. classes: isTouch ? [
  29772. blockerBackdropClass,
  29773. blockerBackdropClass + '--opaque'
  29774. ] : [blockerBackdropClass]
  29775. }
  29776. }]
  29777. }
  29778. },
  29779. dragBlockClass: blockerClass,
  29780. modalBehaviours: derive$1(__spreadArrays([
  29781. Focusing.config({}),
  29782. config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, se) {
  29783. Keying.focusIn(comp);
  29784. })])),
  29785. config('scroll-lock', [
  29786. runOnAttached(function () {
  29787. add$2(body(), scrollLockClass);
  29788. }),
  29789. runOnDetached(function () {
  29790. remove$4(body(), scrollLockClass);
  29791. })
  29792. ])
  29793. ], spec.extraBehaviours)),
  29794. eventOrder: __assign((_a = {}, _a[execute()] = ['dialog-events'], _a[attachedToDom()] = [
  29795. 'scroll-lock',
  29796. 'dialog-events',
  29797. 'alloy.base.behaviour'
  29798. ], _a[detachedFromDom()] = [
  29799. 'alloy.base.behaviour',
  29800. 'dialog-events',
  29801. 'scroll-lock'
  29802. ], _a), spec.eventOrder)
  29803. });
  29804. };
  29805. var renderClose = function (providersBackstage) {
  29806. return Button.sketch({
  29807. dom: {
  29808. tag: 'button',
  29809. classes: [
  29810. 'tox-button',
  29811. 'tox-button--icon',
  29812. 'tox-button--naked'
  29813. ],
  29814. attributes: {
  29815. 'type': 'button',
  29816. 'aria-label': providersBackstage.translate('Close'),
  29817. 'title': providersBackstage.translate('Close')
  29818. }
  29819. },
  29820. components: [{
  29821. dom: {
  29822. tag: 'div',
  29823. classes: ['tox-icon'],
  29824. 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>'
  29825. }
  29826. }],
  29827. action: function (comp) {
  29828. emit(comp, formCancelEvent);
  29829. }
  29830. });
  29831. };
  29832. var renderTitle = function (spec, id, providersBackstage) {
  29833. var renderComponents = function (data) {
  29834. return [text(providersBackstage.translate(data.title))];
  29835. };
  29836. return {
  29837. dom: {
  29838. tag: 'div',
  29839. classes: ['tox-dialog__title'],
  29840. attributes: __assign({}, id.map(function (x) {
  29841. return { id: x };
  29842. }).getOr({}))
  29843. },
  29844. components: renderComponents(spec),
  29845. behaviours: derive$1([Reflecting.config({
  29846. channel: titleChannel,
  29847. renderComponents: renderComponents
  29848. })])
  29849. };
  29850. };
  29851. var renderDragHandle = function () {
  29852. return { dom: fromHtml$2('<div class="tox-dialog__draghandle"></div>') };
  29853. };
  29854. var renderInlineHeader = function (spec, titleId, providersBackstage) {
  29855. return Container.sketch({
  29856. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  29857. components: [
  29858. renderTitle(spec, Option.some(titleId), providersBackstage),
  29859. renderDragHandle(),
  29860. renderClose(providersBackstage)
  29861. ],
  29862. containerBehaviours: derive$1([Dragging.config({
  29863. mode: 'mouse',
  29864. blockerClass: 'blocker',
  29865. getTarget: function (handle) {
  29866. return closest$3(handle, '[role="dialog"]').getOrDie();
  29867. },
  29868. snaps: {
  29869. getSnapPoints: function () {
  29870. return [];
  29871. },
  29872. leftAttr: 'data-drag-left',
  29873. topAttr: 'data-drag-top'
  29874. }
  29875. })])
  29876. });
  29877. };
  29878. var renderModalHeader = function (spec, providersBackstage) {
  29879. var pTitle = ModalDialog.parts().title(renderTitle(spec, Option.none(), providersBackstage));
  29880. var pHandle = ModalDialog.parts().draghandle(renderDragHandle());
  29881. var pClose = ModalDialog.parts().close(renderClose(providersBackstage));
  29882. var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  29883. return Container.sketch({
  29884. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  29885. components: components
  29886. });
  29887. };
  29888. var getHeader = function (title, backstage) {
  29889. return renderModalHeader({
  29890. title: backstage.shared.providers.translate(title),
  29891. draggable: backstage.dialog.isDraggableModal()
  29892. }, backstage.shared.providers);
  29893. };
  29894. var getEventExtras = function (lazyDialog, extra) {
  29895. return {
  29896. onClose: function () {
  29897. return extra.closeWindow();
  29898. },
  29899. onBlock: function (blockEvent) {
  29900. ModalDialog.setBusy(lazyDialog(), function (d, bs) {
  29901. return {
  29902. dom: {
  29903. tag: 'div',
  29904. classes: ['tox-dialog__busy-spinner'],
  29905. attributes: { 'aria-label': blockEvent.message() },
  29906. styles: {
  29907. left: '0px',
  29908. right: '0px',
  29909. bottom: '0px',
  29910. top: '0px',
  29911. position: 'absolute'
  29912. }
  29913. },
  29914. behaviours: bs,
  29915. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  29916. };
  29917. });
  29918. },
  29919. onUnblock: function () {
  29920. ModalDialog.setIdle(lazyDialog());
  29921. }
  29922. };
  29923. };
  29924. var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  29925. var _a;
  29926. var updateState = function (_comp, incoming) {
  29927. return Option.some(incoming);
  29928. };
  29929. return build$1(renderDialog(__assign(__assign({}, spec), {
  29930. lazySink: backstage.shared.getSink,
  29931. extraBehaviours: __spreadArrays([
  29932. Reflecting.config({
  29933. channel: dialogChannel,
  29934. updateState: updateState,
  29935. initialData: initialData
  29936. }),
  29937. RepresentingConfigs.memory({})
  29938. ], spec.extraBehaviours),
  29939. onEscape: function (comp) {
  29940. emit(comp, formCancelEvent);
  29941. },
  29942. dialogEvents: dialogEvents,
  29943. eventOrder: (_a = {}, _a[receive()] = [
  29944. 'reflecting',
  29945. 'receiving'
  29946. ], _a[attachedToDom()] = [
  29947. 'scroll-lock',
  29948. 'reflecting',
  29949. 'messages',
  29950. 'dialog-events',
  29951. 'alloy.base.behaviour'
  29952. ], _a[detachedFromDom()] = [
  29953. 'alloy.base.behaviour',
  29954. 'dialog-events',
  29955. 'messages',
  29956. 'reflecting',
  29957. 'scroll-lock'
  29958. ], _a)
  29959. })));
  29960. };
  29961. var mapMenuButtons = function (buttons) {
  29962. var mapItems = function (button) {
  29963. var items = map(button.items, function (item) {
  29964. var cell = Cell(false);
  29965. return __assign(__assign({}, item), { storage: cell });
  29966. });
  29967. return __assign(__assign({}, button), { items: items });
  29968. };
  29969. return map(buttons, function (button) {
  29970. if (button.type === 'menu') {
  29971. return mapItems(button);
  29972. }
  29973. return button;
  29974. });
  29975. };
  29976. var extractCellsToObject = function (buttons) {
  29977. return foldl(buttons, function (acc, button) {
  29978. if (button.type === 'menu') {
  29979. var menuButton = button;
  29980. return foldl(menuButton.items, function (innerAcc, item) {
  29981. innerAcc[item.name] = item.storage;
  29982. return innerAcc;
  29983. }, acc);
  29984. }
  29985. return acc;
  29986. }, {});
  29987. };
  29988. var renderDialog$1 = function (dialogInit, extra, backstage) {
  29989. var header = getHeader(dialogInit.internalDialog.title, backstage);
  29990. var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  29991. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  29992. var objOfCells = extractCellsToObject(storagedMenuButtons);
  29993. var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  29994. var dialogEvents = SilverDialogEvents.initDialog(function () {
  29995. return instanceApi;
  29996. }, getEventExtras(function () {
  29997. return dialog;
  29998. }, extra));
  29999. var dialogSize = dialogInit.internalDialog.size !== 'normal' ? dialogInit.internalDialog.size === 'large' ? ['tox-dialog--width-lg'] : ['tox-dialog--width-md'] : [];
  30000. var spec = {
  30001. header: header,
  30002. body: body,
  30003. footer: Option.some(footer),
  30004. extraClasses: dialogSize,
  30005. extraBehaviours: [],
  30006. extraStyles: {}
  30007. };
  30008. var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  30009. var modalAccess = function () {
  30010. var getForm = function () {
  30011. var outerForm = ModalDialog.getBody(dialog);
  30012. return Composing.getCurrent(outerForm).getOr(outerForm);
  30013. };
  30014. return {
  30015. getRoot: function () {
  30016. return dialog;
  30017. },
  30018. getBody: function () {
  30019. return ModalDialog.getBody(dialog);
  30020. },
  30021. getFooter: function () {
  30022. return ModalDialog.getFooter(dialog);
  30023. },
  30024. getFormWrapper: getForm
  30025. };
  30026. }();
  30027. var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  30028. return {
  30029. dialog: dialog,
  30030. instanceApi: instanceApi
  30031. };
  30032. };
  30033. var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  30034. var _a, _b;
  30035. var dialogLabelId = generate$1('dialog-label');
  30036. var dialogContentId = generate$1('dialog-content');
  30037. var updateState = function (_comp, incoming) {
  30038. return Option.some(incoming);
  30039. };
  30040. var memHeader = record(renderInlineHeader({
  30041. title: dialogInit.internalDialog.title,
  30042. draggable: true
  30043. }, dialogLabelId, backstage.shared.providers));
  30044. var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  30045. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  30046. var objOfCells = extractCellsToObject(storagedMenuButtons);
  30047. var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  30048. var dialogEvents = SilverDialogEvents.initDialog(function () {
  30049. return instanceApi;
  30050. }, {
  30051. onBlock: function () {
  30052. },
  30053. onUnblock: function () {
  30054. },
  30055. onClose: function () {
  30056. return extra.closeWindow();
  30057. }
  30058. });
  30059. var dialog = build$1({
  30060. dom: {
  30061. tag: 'div',
  30062. classes: [
  30063. 'tox-dialog',
  30064. 'tox-dialog-inline'
  30065. ],
  30066. attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = '' + dialogContentId, _a)
  30067. },
  30068. eventOrder: (_b = {}, _b[receive()] = [
  30069. Reflecting.name(),
  30070. Receiving.name()
  30071. ], _b[execute()] = ['execute-on-form'], _b[attachedToDom()] = [
  30072. 'reflecting',
  30073. 'execute-on-form'
  30074. ], _b),
  30075. behaviours: derive$1([
  30076. Keying.config({
  30077. mode: 'cyclic',
  30078. onEscape: function (c) {
  30079. emit(c, formCloseEvent);
  30080. return Option.some(true);
  30081. },
  30082. useTabstopAt: function (elem) {
  30083. return !NavigableObject.isPseudoStop(elem) && (name(elem) !== 'button' || get$2(elem, 'disabled') !== 'disabled');
  30084. }
  30085. }),
  30086. Reflecting.config({
  30087. channel: dialogChannel,
  30088. updateState: updateState,
  30089. initialData: dialogInit
  30090. }),
  30091. Focusing.config({}),
  30092. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, se) {
  30093. Keying.focusIn(comp);
  30094. })])),
  30095. RepresentingConfigs.memory({})
  30096. ]),
  30097. components: [
  30098. memHeader.asSpec(),
  30099. memBody.asSpec(),
  30100. memFooter.asSpec()
  30101. ]
  30102. });
  30103. var instanceApi = getDialogApi({
  30104. getRoot: function () {
  30105. return dialog;
  30106. },
  30107. getFooter: function () {
  30108. return memFooter.get(dialog);
  30109. },
  30110. getBody: function () {
  30111. return memBody.get(dialog);
  30112. },
  30113. getFormWrapper: function () {
  30114. var body = memBody.get(dialog);
  30115. return Composing.getCurrent(body).getOr(body);
  30116. }
  30117. }, extra.redial, objOfCells);
  30118. return {
  30119. dialog: dialog,
  30120. instanceApi: instanceApi
  30121. };
  30122. };
  30123. var global$g = tinymce.util.Tools.resolve('tinymce.util.URI');
  30124. var getUrlDialogApi = function (root) {
  30125. var withRoot = function (f) {
  30126. if (root.getSystem().isConnected()) {
  30127. f(root);
  30128. }
  30129. };
  30130. var block = function (message) {
  30131. if (!isString(message)) {
  30132. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  30133. }
  30134. withRoot(function (root) {
  30135. emitWith(root, formBlockEvent, { message: message });
  30136. });
  30137. };
  30138. var unblock = function () {
  30139. withRoot(function (root) {
  30140. emit(root, formUnblockEvent);
  30141. });
  30142. };
  30143. var close = function () {
  30144. withRoot(function (root) {
  30145. emit(root, formCloseEvent);
  30146. });
  30147. };
  30148. var sendMessage = function (data) {
  30149. withRoot(function (root) {
  30150. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  30151. });
  30152. };
  30153. return {
  30154. block: block,
  30155. unblock: unblock,
  30156. close: close,
  30157. sendMessage: sendMessage
  30158. };
  30159. };
  30160. var SUPPORTED_MESSAGE_ACTIONS = [
  30161. 'insertContent',
  30162. 'setContent',
  30163. 'execCommand',
  30164. 'close',
  30165. 'block',
  30166. 'unblock'
  30167. ];
  30168. var isSupportedMessage = function (data) {
  30169. return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  30170. };
  30171. var isCustomMessage = function (data) {
  30172. return !isSupportedMessage(data) && isObject(data) && has(data, 'mceAction');
  30173. };
  30174. var handleMessage = function (editor, api, data) {
  30175. switch (data.mceAction) {
  30176. case 'insertContent':
  30177. editor.insertContent(data.content);
  30178. break;
  30179. case 'setContent':
  30180. editor.setContent(data.content);
  30181. break;
  30182. case 'execCommand':
  30183. var ui = isBoolean(data.ui) ? data.ui : false;
  30184. editor.execCommand(data.cmd, ui, data.value);
  30185. break;
  30186. case 'close':
  30187. api.close();
  30188. break;
  30189. case 'block':
  30190. api.block(data.message);
  30191. break;
  30192. case 'unblock':
  30193. api.unblock();
  30194. break;
  30195. }
  30196. };
  30197. var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  30198. var _a;
  30199. var header = getHeader(internalDialog.title, backstage);
  30200. var body = renderIframeBody(internalDialog);
  30201. var footer = internalDialog.buttons.bind(function (buttons) {
  30202. if (buttons.length === 0) {
  30203. return Option.none();
  30204. } else {
  30205. return Option.some(renderModalFooter({ buttons: buttons }, backstage));
  30206. }
  30207. });
  30208. var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  30209. return instanceApi;
  30210. }, getEventExtras(function () {
  30211. return dialog;
  30212. }, extra));
  30213. var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  30214. return {};
  30215. }, function (height) {
  30216. return {
  30217. 'height': height + 'px',
  30218. 'max-height': height + 'px'
  30219. };
  30220. })), internalDialog.width.fold(function () {
  30221. return {};
  30222. }, function (width) {
  30223. return {
  30224. 'width': width + 'px',
  30225. 'max-width': width + 'px'
  30226. };
  30227. }));
  30228. var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  30229. var iframeUri = new global$g(internalDialog.url, { base_uri: new global$g(domGlobals.window.location.href) });
  30230. var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  30231. var messageHandlerUnbinder = Cell(Option.none());
  30232. var extraBehaviours = [
  30233. config('messages', [
  30234. runOnAttached(function () {
  30235. var unbind = bind$3(Element.fromDom(domGlobals.window), 'message', function (e) {
  30236. if (iframeUri.isSameOrigin(new global$g(e.raw().origin))) {
  30237. var data = e.raw().data;
  30238. if (isSupportedMessage(data)) {
  30239. handleMessage(editor, instanceApi, data);
  30240. } else if (isCustomMessage(data)) {
  30241. internalDialog.onMessage(instanceApi, data);
  30242. }
  30243. }
  30244. });
  30245. messageHandlerUnbinder.set(Option.some(unbind));
  30246. }),
  30247. runOnDetached(function () {
  30248. messageHandlerUnbinder.get().each(function (unbinder) {
  30249. return unbinder.unbind();
  30250. });
  30251. })
  30252. ]),
  30253. Receiving.config({
  30254. channels: (_a = {}, _a[bodySendMessageChannel] = {
  30255. onReceive: function (comp, data) {
  30256. descendant$1(comp.element(), 'iframe').each(function (iframeEle) {
  30257. var iframeWin = iframeEle.dom().contentWindow;
  30258. iframeWin.postMessage(data, iframeDomain);
  30259. });
  30260. }
  30261. }, _a)
  30262. })
  30263. ];
  30264. var spec = {
  30265. header: header,
  30266. body: body,
  30267. footer: footer,
  30268. extraClasses: classes,
  30269. extraBehaviours: extraBehaviours,
  30270. extraStyles: styles
  30271. };
  30272. var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  30273. var instanceApi = getUrlDialogApi(dialog);
  30274. return {
  30275. dialog: dialog,
  30276. instanceApi: instanceApi
  30277. };
  30278. };
  30279. var setup$c = function (extras) {
  30280. var sharedBackstage = extras.backstage.shared;
  30281. var open = function (message, callback) {
  30282. var closeDialog = function () {
  30283. ModalDialog.hide(alertDialog);
  30284. callback();
  30285. };
  30286. var memFooterClose = record(renderFooterButton({
  30287. name: 'close-alert',
  30288. text: 'OK',
  30289. primary: true,
  30290. align: 'end',
  30291. disabled: false,
  30292. icon: Option.none()
  30293. }, 'cancel', extras.backstage));
  30294. var titleSpec = pUntitled();
  30295. var closeSpec = pClose(closeDialog, sharedBackstage.providers);
  30296. var alertDialog = build$1(renderDialog({
  30297. lazySink: function () {
  30298. return sharedBackstage.getSink();
  30299. },
  30300. header: hiddenHeader(titleSpec, closeSpec),
  30301. body: pBodyMessage(message, sharedBackstage.providers),
  30302. footer: Option.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  30303. onEscape: closeDialog,
  30304. extraClasses: ['tox-alert-dialog'],
  30305. extraBehaviours: [],
  30306. extraStyles: {},
  30307. dialogEvents: [run(formCancelEvent, closeDialog)],
  30308. eventOrder: {}
  30309. }));
  30310. ModalDialog.show(alertDialog);
  30311. var footerCloseButton = memFooterClose.get(alertDialog);
  30312. Focusing.focus(footerCloseButton);
  30313. };
  30314. return { open: open };
  30315. };
  30316. var setup$d = function (extras) {
  30317. var sharedBackstage = extras.backstage.shared;
  30318. var open = function (message, callback) {
  30319. var closeDialog = function (state) {
  30320. ModalDialog.hide(confirmDialog);
  30321. callback(state);
  30322. };
  30323. var memFooterYes = record(renderFooterButton({
  30324. name: 'yes',
  30325. text: 'Yes',
  30326. primary: true,
  30327. align: 'end',
  30328. disabled: false,
  30329. icon: Option.none()
  30330. }, 'submit', extras.backstage));
  30331. var footerNo = renderFooterButton({
  30332. name: 'no',
  30333. text: 'No',
  30334. primary: false,
  30335. align: 'end',
  30336. disabled: false,
  30337. icon: Option.none()
  30338. }, 'cancel', extras.backstage);
  30339. var titleSpec = pUntitled();
  30340. var closeSpec = pClose(function () {
  30341. return closeDialog(false);
  30342. }, sharedBackstage.providers);
  30343. var confirmDialog = build$1(renderDialog({
  30344. lazySink: function () {
  30345. return sharedBackstage.getSink();
  30346. },
  30347. header: hiddenHeader(titleSpec, closeSpec),
  30348. body: pBodyMessage(message, sharedBackstage.providers),
  30349. footer: Option.some(pFooter(pFooterGroup([], [
  30350. footerNo,
  30351. memFooterYes.asSpec()
  30352. ]))),
  30353. onEscape: function () {
  30354. return closeDialog(false);
  30355. },
  30356. extraClasses: ['tox-confirm-dialog'],
  30357. extraBehaviours: [],
  30358. extraStyles: {},
  30359. dialogEvents: [
  30360. run(formCancelEvent, function () {
  30361. return closeDialog(false);
  30362. }),
  30363. run(formSubmitEvent, function () {
  30364. return closeDialog(true);
  30365. })
  30366. ],
  30367. eventOrder: {}
  30368. }));
  30369. ModalDialog.show(confirmDialog);
  30370. var footerYesButton = memFooterYes.get(confirmDialog);
  30371. Focusing.focus(footerYesButton);
  30372. };
  30373. return { open: open };
  30374. };
  30375. var validateData$1 = function (data, validator) {
  30376. return getOrDie(asRaw('data', validator, data));
  30377. };
  30378. var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
  30379. if (isStickyToolbar && isToolbarLocationTop) {
  30380. return [];
  30381. } else {
  30382. return [Docking.config({
  30383. contextual: {
  30384. lazyContext: function () {
  30385. return Option.some(box(Element.fromDom(editor.getContentAreaContainer())));
  30386. },
  30387. fadeInClass: 'tox-dialog-dock-fadein',
  30388. fadeOutClass: 'tox-dialog-dock-fadeout',
  30389. transitionClass: 'tox-dialog-dock-transition'
  30390. },
  30391. modes: ['top']
  30392. })];
  30393. }
  30394. };
  30395. var setup$e = function (extras) {
  30396. var backstage = extras.backstage;
  30397. var editor = extras.editor;
  30398. var isStickyToolbar$1 = isStickyToolbar(editor);
  30399. var isToolbarLocationTop$1 = isToolbarLocationTop(editor);
  30400. var alertDialog = setup$c(extras);
  30401. var confirmDialog = setup$d(extras);
  30402. var open = function (config, params, closeWindow) {
  30403. if (params !== undefined && params.inline === 'toolbar') {
  30404. return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  30405. } else if (params !== undefined && params.inline === 'cursor') {
  30406. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  30407. } else {
  30408. return openModalDialog(config, closeWindow);
  30409. }
  30410. };
  30411. var openUrl = function (config, closeWindow) {
  30412. return openModalUrlDialog(config, closeWindow);
  30413. };
  30414. var openModalUrlDialog = function (config, closeWindow) {
  30415. var factory = function (contents) {
  30416. var dialog = renderUrlDialog(contents, {
  30417. closeWindow: function () {
  30418. ModalDialog.hide(dialog.dialog);
  30419. closeWindow(dialog.instanceApi);
  30420. }
  30421. }, editor, backstage);
  30422. ModalDialog.show(dialog.dialog);
  30423. return dialog.instanceApi;
  30424. };
  30425. return DialogManager.openUrl(factory, config);
  30426. };
  30427. var openModalDialog = function (config, closeWindow) {
  30428. var factory = function (contents, internalInitialData, dataValidator) {
  30429. var initialData = internalInitialData;
  30430. var dialogInit = {
  30431. dataValidator: dataValidator,
  30432. initialData: initialData,
  30433. internalDialog: contents
  30434. };
  30435. var dialog = renderDialog$1(dialogInit, {
  30436. redial: DialogManager.redial,
  30437. closeWindow: function () {
  30438. ModalDialog.hide(dialog.dialog);
  30439. closeWindow(dialog.instanceApi);
  30440. }
  30441. }, backstage);
  30442. ModalDialog.show(dialog.dialog);
  30443. dialog.instanceApi.setData(initialData);
  30444. return dialog.instanceApi;
  30445. };
  30446. return DialogManager.open(factory, config);
  30447. };
  30448. var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  30449. var factory = function (contents, internalInitialData, dataValidator) {
  30450. var initialData = validateData$1(internalInitialData, dataValidator);
  30451. var inlineDialog = value$3();
  30452. var dialogInit = {
  30453. dataValidator: dataValidator,
  30454. initialData: initialData,
  30455. internalDialog: contents
  30456. };
  30457. var refreshDocking = function () {
  30458. return inlineDialog.on(function (dialog) {
  30459. InlineView.reposition(dialog);
  30460. Docking.refresh(dialog);
  30461. });
  30462. };
  30463. var dialogUi = renderInlineDialog(dialogInit, {
  30464. redial: DialogManager.redial,
  30465. closeWindow: function () {
  30466. inlineDialog.on(InlineView.hide);
  30467. editor.off('ResizeEditor', refreshDocking);
  30468. inlineDialog.clear();
  30469. closeWindow(dialogUi.instanceApi);
  30470. }
  30471. }, backstage, ariaAttrs);
  30472. var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
  30473. lazySink: backstage.shared.getSink,
  30474. dom: {
  30475. tag: 'div',
  30476. classes: []
  30477. },
  30478. fireDismissalEventInstead: {}
  30479. }, isToolbarLocationTop$1 ? {} : { fireRepositionEventInstead: {} }), {
  30480. inlineBehaviours: derive$1(__spreadArrays([config('window-manager-inline-events', [run(dismissRequested(), function (comp, se) {
  30481. emit(dialogUi.dialog, formCancelEvent);
  30482. })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop$1)))
  30483. })));
  30484. inlineDialog.set(inlineDialogComp);
  30485. InlineView.showWithin(inlineDialogComp, anchor, premade$1(dialogUi.dialog), Option.some(body()));
  30486. if (!isStickyToolbar$1 || !isToolbarLocationTop$1) {
  30487. Docking.refresh(inlineDialogComp);
  30488. editor.on('ResizeEditor', refreshDocking);
  30489. }
  30490. dialogUi.instanceApi.setData(initialData);
  30491. Keying.focusIn(dialogUi.dialog);
  30492. return dialogUi.instanceApi;
  30493. };
  30494. return DialogManager.open(factory, config$1);
  30495. };
  30496. var confirm = function (message, callback) {
  30497. confirmDialog.open(message, function (state) {
  30498. callback(state);
  30499. });
  30500. };
  30501. var alert = function (message, callback) {
  30502. alertDialog.open(message, function () {
  30503. callback();
  30504. });
  30505. };
  30506. var close = function (instanceApi) {
  30507. instanceApi.close();
  30508. };
  30509. return {
  30510. open: open,
  30511. openUrl: openUrl,
  30512. alert: alert,
  30513. close: close,
  30514. confirm: confirm
  30515. };
  30516. };
  30517. var WindowManager = { setup: setup$e };
  30518. function Theme () {
  30519. global$1.add('silver', function (editor) {
  30520. var _a = Render.setup(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  30521. Autocompleter.register(editor, backstage.shared);
  30522. var windowMgr = WindowManager.setup({
  30523. editor: editor,
  30524. backstage: backstage
  30525. });
  30526. return {
  30527. renderUI: renderUI,
  30528. getWindowManagerImpl: constant(windowMgr),
  30529. getNotificationManagerImpl: function () {
  30530. return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  30531. },
  30532. ui: getUi()
  30533. };
  30534. });
  30535. }
  30536. Theme();
  30537. }(window));