theme.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221
  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.1.0 (2019-10-17)
  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. var output = map(xs, f);
  471. return flatten(output);
  472. };
  473. var forall = function (xs, pred) {
  474. for (var i = 0, len = xs.length; i < len; ++i) {
  475. var x = xs[i];
  476. if (pred(x, i) !== true) {
  477. return false;
  478. }
  479. }
  480. return true;
  481. };
  482. var reverse = function (xs) {
  483. var r = nativeSlice.call(xs, 0);
  484. r.reverse();
  485. return r;
  486. };
  487. var difference = function (a1, a2) {
  488. return filter(a1, function (x) {
  489. return !contains(a2, x);
  490. });
  491. };
  492. var pure = function (x) {
  493. return [x];
  494. };
  495. var sort = function (xs, comparator) {
  496. var copy = nativeSlice.call(xs, 0);
  497. copy.sort(comparator);
  498. return copy;
  499. };
  500. var head = function (xs) {
  501. return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  502. };
  503. var last = function (xs) {
  504. return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  505. };
  506. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  507. return nativeSlice.call(x);
  508. };
  509. var keys = Object.keys;
  510. var hasOwnProperty = Object.hasOwnProperty;
  511. var each$1 = function (obj, f) {
  512. var props = keys(obj);
  513. for (var k = 0, len = props.length; k < len; k++) {
  514. var i = props[k];
  515. var x = obj[i];
  516. f(x, i);
  517. }
  518. };
  519. var map$1 = function (obj, f) {
  520. return tupleMap(obj, function (x, i) {
  521. return {
  522. k: i,
  523. v: f(x, i)
  524. };
  525. });
  526. };
  527. var tupleMap = function (obj, f) {
  528. var r = {};
  529. each$1(obj, function (x, i) {
  530. var tuple = f(x, i);
  531. r[tuple.k] = tuple.v;
  532. });
  533. return r;
  534. };
  535. var mapToArray = function (obj, f) {
  536. var r = [];
  537. each$1(obj, function (value, name) {
  538. r.push(f(value, name));
  539. });
  540. return r;
  541. };
  542. var find$1 = function (obj, pred) {
  543. var props = keys(obj);
  544. for (var k = 0, len = props.length; k < len; k++) {
  545. var i = props[k];
  546. var x = obj[i];
  547. if (pred(x, i, obj)) {
  548. return Option.some(x);
  549. }
  550. }
  551. return Option.none();
  552. };
  553. var values = function (obj) {
  554. return mapToArray(obj, function (v) {
  555. return v;
  556. });
  557. };
  558. var get = function (obj, key) {
  559. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  560. };
  561. var has = function (obj, key) {
  562. return hasOwnProperty.call(obj, key);
  563. };
  564. var generate = function (cases) {
  565. if (!isArray(cases)) {
  566. throw new Error('cases must be an array');
  567. }
  568. if (cases.length === 0) {
  569. throw new Error('there must be at least one case');
  570. }
  571. var constructors = [];
  572. var adt = {};
  573. each(cases, function (acase, count) {
  574. var keys$1 = keys(acase);
  575. if (keys$1.length !== 1) {
  576. throw new Error('one and only one name per case');
  577. }
  578. var key = keys$1[0];
  579. var value = acase[key];
  580. if (adt[key] !== undefined) {
  581. throw new Error('duplicate key detected:' + key);
  582. } else if (key === 'cata') {
  583. throw new Error('cannot have a case named cata (sorry)');
  584. } else if (!isArray(value)) {
  585. throw new Error('case arguments must be an array');
  586. }
  587. constructors.push(key);
  588. adt[key] = function () {
  589. var argLength = arguments.length;
  590. if (argLength !== value.length) {
  591. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  592. }
  593. var args = new Array(argLength);
  594. for (var i = 0; i < args.length; i++) {
  595. args[i] = arguments[i];
  596. }
  597. var match = function (branches) {
  598. var branchKeys = keys(branches);
  599. if (constructors.length !== branchKeys.length) {
  600. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  601. }
  602. var allReqd = forall(constructors, function (reqKey) {
  603. return contains(branchKeys, reqKey);
  604. });
  605. if (!allReqd) {
  606. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  607. }
  608. return branches[key].apply(null, args);
  609. };
  610. return {
  611. fold: function () {
  612. if (arguments.length !== cases.length) {
  613. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  614. }
  615. var target = arguments[count];
  616. return target.apply(null, args);
  617. },
  618. match: match,
  619. log: function (label) {
  620. domGlobals.console.log(label, {
  621. constructors: constructors,
  622. constructor: key,
  623. params: args
  624. });
  625. }
  626. };
  627. };
  628. });
  629. return adt;
  630. };
  631. var Adt = { generate: generate };
  632. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  633. var shallow = function (old, nu) {
  634. return nu;
  635. };
  636. var deep = function (old, nu) {
  637. var bothObjects = isObject(old) && isObject(nu);
  638. return bothObjects ? deepMerge(old, nu) : nu;
  639. };
  640. var baseMerge = function (merger) {
  641. return function () {
  642. var objects = new Array(arguments.length);
  643. for (var i = 0; i < objects.length; i++) {
  644. objects[i] = arguments[i];
  645. }
  646. if (objects.length === 0) {
  647. throw new Error('Can\'t merge zero objects');
  648. }
  649. var ret = {};
  650. for (var j = 0; j < objects.length; j++) {
  651. var curObject = objects[j];
  652. for (var key in curObject) {
  653. if (hasOwnProperty$1.call(curObject, key)) {
  654. ret[key] = merger(ret[key], curObject[key]);
  655. }
  656. }
  657. }
  658. return ret;
  659. };
  660. };
  661. var deepMerge = baseMerge(deep);
  662. var merge = baseMerge(shallow);
  663. var cached = function (f) {
  664. var called = false;
  665. var r;
  666. return function () {
  667. var args = [];
  668. for (var _i = 0; _i < arguments.length; _i++) {
  669. args[_i] = arguments[_i];
  670. }
  671. if (!called) {
  672. called = true;
  673. r = f.apply(null, args);
  674. }
  675. return r;
  676. };
  677. };
  678. var adt = Adt.generate([
  679. { strict: [] },
  680. { defaultedThunk: ['fallbackThunk'] },
  681. { asOption: [] },
  682. { asDefaultedOptionThunk: ['fallbackThunk'] },
  683. { mergeWithThunk: ['baseThunk'] }
  684. ]);
  685. var defaulted = function (fallback) {
  686. return adt.defaultedThunk(constant(fallback));
  687. };
  688. var mergeWith = function (base) {
  689. return adt.mergeWithThunk(constant(base));
  690. };
  691. var strict = adt.strict;
  692. var asOption = adt.asOption;
  693. var defaultedThunk = adt.defaultedThunk;
  694. var mergeWithThunk = adt.mergeWithThunk;
  695. var exclude = function (obj, fields) {
  696. var r = {};
  697. each$1(obj, function (v, k) {
  698. if (!contains(fields, k)) {
  699. r[k] = v;
  700. }
  701. });
  702. return r;
  703. };
  704. var readOpt = function (key) {
  705. return function (obj) {
  706. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  707. };
  708. };
  709. var readOr = function (key, fallback) {
  710. return function (obj) {
  711. return has(obj, key) ? obj[key] : fallback;
  712. };
  713. };
  714. var readOptFrom = function (obj, key) {
  715. return readOpt(key)(obj);
  716. };
  717. var hasKey = function (obj, key) {
  718. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  719. };
  720. var wrap = function (key, value) {
  721. var r = {};
  722. r[key] = value;
  723. return r;
  724. };
  725. var wrapAll = function (keyvalues) {
  726. var r = {};
  727. each(keyvalues, function (kv) {
  728. r[kv.key] = kv.value;
  729. });
  730. return r;
  731. };
  732. var comparison = Adt.generate([
  733. {
  734. bothErrors: [
  735. 'error1',
  736. 'error2'
  737. ]
  738. },
  739. {
  740. firstError: [
  741. 'error1',
  742. 'value2'
  743. ]
  744. },
  745. {
  746. secondError: [
  747. 'value1',
  748. 'error2'
  749. ]
  750. },
  751. {
  752. bothValues: [
  753. 'value1',
  754. 'value2'
  755. ]
  756. }
  757. ]);
  758. var partition$1 = function (results) {
  759. var errors = [];
  760. var values = [];
  761. each(results, function (result) {
  762. result.fold(function (err) {
  763. errors.push(err);
  764. }, function (value) {
  765. values.push(value);
  766. });
  767. });
  768. return {
  769. errors: errors,
  770. values: values
  771. };
  772. };
  773. var exclude$1 = function (obj, fields) {
  774. return exclude(obj, fields);
  775. };
  776. var readOpt$1 = function (key) {
  777. return readOpt(key);
  778. };
  779. var readOr$1 = function (key, fallback) {
  780. return readOr(key, fallback);
  781. };
  782. var readOptFrom$1 = function (obj, key) {
  783. return readOptFrom(obj, key);
  784. };
  785. var wrap$1 = function (key, value) {
  786. return wrap(key, value);
  787. };
  788. var wrapAll$1 = function (keyvalues) {
  789. return wrapAll(keyvalues);
  790. };
  791. var mergeValues = function (values, base) {
  792. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  793. };
  794. var mergeErrors = function (errors) {
  795. return Result.error(flatten(errors));
  796. };
  797. var consolidate = function (objs, base) {
  798. var partitions = partition$1(objs);
  799. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  800. };
  801. var hasKey$1 = function (obj, key) {
  802. return hasKey(obj, key);
  803. };
  804. var SimpleResultType;
  805. (function (SimpleResultType) {
  806. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  807. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  808. }(SimpleResultType || (SimpleResultType = {})));
  809. var fold = function (res, onError, onValue) {
  810. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  811. };
  812. var partition$2 = function (results) {
  813. var values = [];
  814. var errors = [];
  815. each(results, function (obj) {
  816. fold(obj, function (err) {
  817. return errors.push(err);
  818. }, function (val) {
  819. return values.push(val);
  820. });
  821. });
  822. return {
  823. values: values,
  824. errors: errors
  825. };
  826. };
  827. var mapError = function (res, f) {
  828. if (res.stype === SimpleResultType.Error) {
  829. return {
  830. stype: SimpleResultType.Error,
  831. serror: f(res.serror)
  832. };
  833. } else {
  834. return res;
  835. }
  836. };
  837. var map$2 = function (res, f) {
  838. if (res.stype === SimpleResultType.Value) {
  839. return {
  840. stype: SimpleResultType.Value,
  841. svalue: f(res.svalue)
  842. };
  843. } else {
  844. return res;
  845. }
  846. };
  847. var bind$1 = function (res, f) {
  848. if (res.stype === SimpleResultType.Value) {
  849. return f(res.svalue);
  850. } else {
  851. return res;
  852. }
  853. };
  854. var bindError = function (res, f) {
  855. if (res.stype === SimpleResultType.Error) {
  856. return f(res.serror);
  857. } else {
  858. return res;
  859. }
  860. };
  861. var svalue = function (v) {
  862. return {
  863. stype: SimpleResultType.Value,
  864. svalue: v
  865. };
  866. };
  867. var serror = function (e) {
  868. return {
  869. stype: SimpleResultType.Error,
  870. serror: e
  871. };
  872. };
  873. var toResult = function (res) {
  874. return fold(res, Result.error, Result.value);
  875. };
  876. var fromResult = function (res) {
  877. return res.fold(serror, svalue);
  878. };
  879. var SimpleResult = {
  880. fromResult: fromResult,
  881. toResult: toResult,
  882. svalue: svalue,
  883. partition: partition$2,
  884. serror: serror,
  885. bind: bind$1,
  886. bindError: bindError,
  887. map: map$2,
  888. mapError: mapError,
  889. fold: fold
  890. };
  891. var mergeValues$1 = function (values, base) {
  892. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  893. };
  894. var mergeErrors$1 = function (errors) {
  895. return compose(SimpleResult.serror, flatten)(errors);
  896. };
  897. var consolidateObj = function (objects, base) {
  898. var partition = SimpleResult.partition(objects);
  899. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  900. };
  901. var consolidateArr = function (objects) {
  902. var partitions = SimpleResult.partition(objects);
  903. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  904. };
  905. var ResultCombine = {
  906. consolidateObj: consolidateObj,
  907. consolidateArr: consolidateArr
  908. };
  909. var typeAdt = Adt.generate([
  910. {
  911. setOf: [
  912. 'validator',
  913. 'valueType'
  914. ]
  915. },
  916. { arrOf: ['valueType'] },
  917. { objOf: ['fields'] },
  918. { itemOf: ['validator'] },
  919. {
  920. choiceOf: [
  921. 'key',
  922. 'branches'
  923. ]
  924. },
  925. { thunk: ['description'] },
  926. {
  927. func: [
  928. 'args',
  929. 'outputSchema'
  930. ]
  931. }
  932. ]);
  933. var fieldAdt = Adt.generate([
  934. {
  935. field: [
  936. 'name',
  937. 'presence',
  938. 'type'
  939. ]
  940. },
  941. { state: ['name'] }
  942. ]);
  943. var formatObj = function (input) {
  944. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  945. };
  946. var formatErrors = function (errors) {
  947. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  948. path: [],
  949. getErrorInfo: function () {
  950. return '... (only showing first ten failures)';
  951. }
  952. }]) : errors;
  953. return map(es, function (e) {
  954. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  955. });
  956. };
  957. var nu = function (path, getErrorInfo) {
  958. return SimpleResult.serror([{
  959. path: path,
  960. getErrorInfo: getErrorInfo
  961. }]);
  962. };
  963. var missingStrict = function (path, key, obj) {
  964. return nu(path, function () {
  965. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  966. });
  967. };
  968. var missingKey = function (path, key) {
  969. return nu(path, function () {
  970. return 'Choice schema did not contain choice key: "' + key + '"';
  971. });
  972. };
  973. var missingBranch = function (path, branches, branch) {
  974. return nu(path, function () {
  975. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  976. });
  977. };
  978. var unsupportedFields = function (path, unsupported) {
  979. return nu(path, function () {
  980. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  981. });
  982. };
  983. var custom = function (path, err) {
  984. return nu(path, function () {
  985. return err;
  986. });
  987. };
  988. var adt$1 = Adt.generate([
  989. {
  990. field: [
  991. 'key',
  992. 'okey',
  993. 'presence',
  994. 'prop'
  995. ]
  996. },
  997. {
  998. state: [
  999. 'okey',
  1000. 'instantiator'
  1001. ]
  1002. }
  1003. ]);
  1004. var strictAccess = function (path, obj, key) {
  1005. return readOptFrom(obj, key).fold(function () {
  1006. return missingStrict(path, key, obj);
  1007. }, SimpleResult.svalue);
  1008. };
  1009. var fallbackAccess = function (obj, key, fallbackThunk) {
  1010. var v = readOptFrom(obj, key).fold(function () {
  1011. return fallbackThunk(obj);
  1012. }, identity);
  1013. return SimpleResult.svalue(v);
  1014. };
  1015. var optionAccess = function (obj, key) {
  1016. return SimpleResult.svalue(readOptFrom(obj, key));
  1017. };
  1018. var optionDefaultedAccess = function (obj, key, fallback) {
  1019. var opt = readOptFrom(obj, key).map(function (val) {
  1020. return val === true ? fallback(obj) : val;
  1021. });
  1022. return SimpleResult.svalue(opt);
  1023. };
  1024. var cExtractOne = function (path, obj, field, strength) {
  1025. return field.fold(function (key, okey, presence, prop) {
  1026. var bundle = function (av) {
  1027. var result = prop.extract(path.concat([key]), strength, av);
  1028. return SimpleResult.map(result, function (res) {
  1029. return wrap(okey, strength(res));
  1030. });
  1031. };
  1032. var bundleAsOption = function (optValue) {
  1033. return optValue.fold(function () {
  1034. var outcome = wrap(okey, strength(Option.none()));
  1035. return SimpleResult.svalue(outcome);
  1036. }, function (ov) {
  1037. var result = prop.extract(path.concat([key]), strength, ov);
  1038. return SimpleResult.map(result, function (res) {
  1039. return wrap(okey, strength(Option.some(res)));
  1040. });
  1041. });
  1042. };
  1043. return function () {
  1044. return presence.fold(function () {
  1045. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1046. }, function (fallbackThunk) {
  1047. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1048. }, function () {
  1049. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1050. }, function (fallbackThunk) {
  1051. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1052. }, function (baseThunk) {
  1053. var base = baseThunk(obj);
  1054. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1055. return deepMerge(base, v);
  1056. });
  1057. return SimpleResult.bind(result, bundle);
  1058. });
  1059. }();
  1060. }, function (okey, instantiator) {
  1061. var state = instantiator(obj);
  1062. return SimpleResult.svalue(wrap(okey, strength(state)));
  1063. });
  1064. };
  1065. var cExtract = function (path, obj, fields, strength) {
  1066. var results = map(fields, function (field) {
  1067. return cExtractOne(path, obj, field, strength);
  1068. });
  1069. return ResultCombine.consolidateObj(results, {});
  1070. };
  1071. var valueThunk = function (getDelegate) {
  1072. var extract = function (path, strength, val) {
  1073. return getDelegate().extract(path, strength, val);
  1074. };
  1075. var toString = function () {
  1076. return getDelegate().toString();
  1077. };
  1078. var toDsl = function () {
  1079. return getDelegate().toDsl();
  1080. };
  1081. return {
  1082. extract: extract,
  1083. toString: toString,
  1084. toDsl: toDsl
  1085. };
  1086. };
  1087. var value$1 = function (validator) {
  1088. var extract = function (path, strength, val) {
  1089. return SimpleResult.bindError(validator(val, strength), function (err) {
  1090. return custom(path, err);
  1091. });
  1092. };
  1093. var toString = function () {
  1094. return 'val';
  1095. };
  1096. var toDsl = function () {
  1097. return typeAdt.itemOf(validator);
  1098. };
  1099. return {
  1100. extract: extract,
  1101. toString: toString,
  1102. toDsl: toDsl
  1103. };
  1104. };
  1105. var getSetKeys = function (obj) {
  1106. var keys$1 = keys(obj);
  1107. return filter(keys$1, function (k) {
  1108. return hasKey$1(obj, k);
  1109. });
  1110. };
  1111. var objOfOnly = function (fields) {
  1112. var delegate = objOf(fields);
  1113. var fieldNames = foldr(fields, function (acc, f) {
  1114. return f.fold(function (key) {
  1115. return deepMerge(acc, wrap$1(key, true));
  1116. }, constant(acc));
  1117. }, {});
  1118. var extract = function (path, strength, o) {
  1119. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1120. var extra = filter(keys, function (k) {
  1121. return !hasKey$1(fieldNames, k);
  1122. });
  1123. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1124. };
  1125. return {
  1126. extract: extract,
  1127. toString: delegate.toString,
  1128. toDsl: delegate.toDsl
  1129. };
  1130. };
  1131. var objOf = function (fields) {
  1132. var extract = function (path, strength, o) {
  1133. return cExtract(path, o, fields, strength);
  1134. };
  1135. var toString = function () {
  1136. var fieldStrings = map(fields, function (field) {
  1137. return field.fold(function (key, okey, presence, prop) {
  1138. return key + ' -> ' + prop.toString();
  1139. }, function (okey, instantiator) {
  1140. return 'state(' + okey + ')';
  1141. });
  1142. });
  1143. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1144. };
  1145. var toDsl = function () {
  1146. return typeAdt.objOf(map(fields, function (f) {
  1147. return f.fold(function (key, okey, presence, prop) {
  1148. return fieldAdt.field(key, presence, prop);
  1149. }, function (okey, instantiator) {
  1150. return fieldAdt.state(okey);
  1151. });
  1152. }));
  1153. };
  1154. return {
  1155. extract: extract,
  1156. toString: toString,
  1157. toDsl: toDsl
  1158. };
  1159. };
  1160. var arrOf = function (prop) {
  1161. var extract = function (path, strength, array) {
  1162. var results = map(array, function (a, i) {
  1163. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1164. });
  1165. return ResultCombine.consolidateArr(results);
  1166. };
  1167. var toString = function () {
  1168. return 'array(' + prop.toString() + ')';
  1169. };
  1170. var toDsl = function () {
  1171. return typeAdt.arrOf(prop);
  1172. };
  1173. return {
  1174. extract: extract,
  1175. toString: toString,
  1176. toDsl: toDsl
  1177. };
  1178. };
  1179. var setOf = function (validator, prop) {
  1180. var validateKeys = function (path, keys) {
  1181. return arrOf(value$1(validator)).extract(path, identity, keys);
  1182. };
  1183. var extract = function (path, strength, o) {
  1184. var keys$1 = keys(o);
  1185. var validatedKeys = validateKeys(path, keys$1);
  1186. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1187. var schema = map(validKeys, function (vk) {
  1188. return adt$1.field(vk, vk, strict(), prop);
  1189. });
  1190. return objOf(schema).extract(path, strength, o);
  1191. });
  1192. };
  1193. var toString = function () {
  1194. return 'setOf(' + prop.toString() + ')';
  1195. };
  1196. var toDsl = function () {
  1197. return typeAdt.setOf(validator, prop);
  1198. };
  1199. return {
  1200. extract: extract,
  1201. toString: toString,
  1202. toDsl: toDsl
  1203. };
  1204. };
  1205. var anyValue = constant(value$1(SimpleResult.svalue));
  1206. var arrOfObj = compose(arrOf, objOf);
  1207. var state = adt$1.state;
  1208. var field = adt$1.field;
  1209. var chooseFrom = function (path, strength, input, branches, ch) {
  1210. var fields = readOptFrom$1(branches, ch);
  1211. return fields.fold(function () {
  1212. return missingBranch(path, branches, ch);
  1213. }, function (vp) {
  1214. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1215. });
  1216. };
  1217. var choose = function (key, branches) {
  1218. var extract = function (path, strength, input) {
  1219. var choice = readOptFrom$1(input, key);
  1220. return choice.fold(function () {
  1221. return missingKey(path, key);
  1222. }, function (chosen) {
  1223. return chooseFrom(path, strength, input, branches, chosen);
  1224. });
  1225. };
  1226. var toString = function () {
  1227. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1228. };
  1229. var toDsl = function () {
  1230. return typeAdt.choiceOf(key, branches);
  1231. };
  1232. return {
  1233. extract: extract,
  1234. toString: toString,
  1235. toDsl: toDsl
  1236. };
  1237. };
  1238. var _anyValue = value$1(SimpleResult.svalue);
  1239. var arrOfObj$1 = function (objFields) {
  1240. return arrOfObj(objFields);
  1241. };
  1242. var arrOfVal = function () {
  1243. return arrOf(_anyValue);
  1244. };
  1245. var valueThunkOf = valueThunk;
  1246. var valueOf = function (validator) {
  1247. return value$1(function (v) {
  1248. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1249. });
  1250. };
  1251. var setOf$1 = function (validator, prop) {
  1252. return setOf(function (v) {
  1253. return SimpleResult.fromResult(validator(v));
  1254. }, prop);
  1255. };
  1256. var extract = function (label, prop, strength, obj) {
  1257. var res = prop.extract([label], strength, obj);
  1258. return SimpleResult.mapError(res, function (errs) {
  1259. return {
  1260. input: obj,
  1261. errors: errs
  1262. };
  1263. });
  1264. };
  1265. var asRaw = function (label, prop, obj) {
  1266. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1267. };
  1268. var getOrDie = function (extraction) {
  1269. return extraction.fold(function (errInfo) {
  1270. throw new Error(formatError(errInfo));
  1271. }, identity);
  1272. };
  1273. var asRawOrDie = function (label, prop, obj) {
  1274. return getOrDie(asRaw(label, prop, obj));
  1275. };
  1276. var formatError = function (errInfo) {
  1277. return 'Errors: \n' + formatErrors(errInfo.errors) + '\n\nInput object: ' + formatObj(errInfo.input);
  1278. };
  1279. var chooseProcessor = function (key, branches) {
  1280. return choose(key, branches);
  1281. };
  1282. var choose$1 = function (key, branches) {
  1283. return choose(key, map$1(branches, objOf));
  1284. };
  1285. var anyValue$1 = constant(_anyValue);
  1286. var typedValue = function (validator, expectedType) {
  1287. return value$1(function (a) {
  1288. var actualType = typeof a;
  1289. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1290. });
  1291. };
  1292. var number = typedValue(isNumber, 'number');
  1293. var string = typedValue(isString, 'string');
  1294. var boolean = typedValue(isBoolean, 'boolean');
  1295. var functionProcessor = typedValue(isFunction, 'function');
  1296. var isPostMessageable = function (val) {
  1297. var every = function (iter, callbackFn) {
  1298. var result = iter.next();
  1299. while (!result.done) {
  1300. if (!callbackFn(result.value)) {
  1301. return false;
  1302. }
  1303. result = iter.next();
  1304. }
  1305. return true;
  1306. };
  1307. if (Object(val) !== val) {
  1308. return true;
  1309. }
  1310. switch ({}.toString.call(val).slice(8, -1)) {
  1311. case 'Boolean':
  1312. case 'Number':
  1313. case 'String':
  1314. case 'Date':
  1315. case 'RegExp':
  1316. case 'Blob':
  1317. case 'FileList':
  1318. case 'ImageData':
  1319. case 'ImageBitmap':
  1320. case 'ArrayBuffer':
  1321. return true;
  1322. case 'Array':
  1323. case 'Object':
  1324. return Object.keys(val).every(function (prop) {
  1325. return isPostMessageable(val[prop]);
  1326. });
  1327. case 'Map':
  1328. return every(val.keys(), isPostMessageable) && every(val.values(), isPostMessageable);
  1329. case 'Set':
  1330. return every(val.keys(), isPostMessageable);
  1331. default:
  1332. return false;
  1333. }
  1334. };
  1335. var postMessageable = value$1(function (a) {
  1336. return isPostMessageable(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  1337. });
  1338. var validateEnum = function (values) {
  1339. return valueOf(function (value) {
  1340. return contains(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  1341. });
  1342. };
  1343. var strict$1 = function (key) {
  1344. return field(key, key, strict(), anyValue());
  1345. };
  1346. var strictOf = function (key, schema) {
  1347. return field(key, key, strict(), schema);
  1348. };
  1349. var strictNumber = function (key) {
  1350. return strictOf(key, number);
  1351. };
  1352. var strictString = function (key) {
  1353. return strictOf(key, string);
  1354. };
  1355. var strictStringEnum = function (key, values) {
  1356. return field(key, key, strict(), validateEnum(values));
  1357. };
  1358. var strictBoolean = function (key) {
  1359. return strictOf(key, boolean);
  1360. };
  1361. var strictFunction = function (key) {
  1362. return strictOf(key, functionProcessor);
  1363. };
  1364. var forbid = function (key, message) {
  1365. return field(key, key, asOption(), value$1(function (v) {
  1366. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1367. }));
  1368. };
  1369. var strictObjOf = function (key, objSchema) {
  1370. return field(key, key, strict(), objOf(objSchema));
  1371. };
  1372. var strictArrayOfObj = function (key, objFields) {
  1373. return field(key, key, strict(), arrOfObj(objFields));
  1374. };
  1375. var strictArrayOf = function (key, schema) {
  1376. return field(key, key, strict(), arrOf(schema));
  1377. };
  1378. var option = function (key) {
  1379. return field(key, key, asOption(), anyValue());
  1380. };
  1381. var optionOf = function (key, schema) {
  1382. return field(key, key, asOption(), schema);
  1383. };
  1384. var optionNumber = function (key) {
  1385. return optionOf(key, number);
  1386. };
  1387. var optionString = function (key) {
  1388. return optionOf(key, string);
  1389. };
  1390. var optionFunction = function (key) {
  1391. return optionOf(key, functionProcessor);
  1392. };
  1393. var optionArrayOf = function (key, schema) {
  1394. return optionOf(key, arrOf(schema));
  1395. };
  1396. var optionObjOf = function (key, objSchema) {
  1397. return optionOf(key, objOf(objSchema));
  1398. };
  1399. var optionObjOfOnly = function (key, objSchema) {
  1400. return optionOf(key, objOfOnly(objSchema));
  1401. };
  1402. var defaulted$1 = function (key, fallback) {
  1403. return field(key, key, defaulted(fallback), anyValue());
  1404. };
  1405. var defaultedOf = function (key, fallback, schema) {
  1406. return field(key, key, defaulted(fallback), schema);
  1407. };
  1408. var defaultedNumber = function (key, fallback) {
  1409. return defaultedOf(key, fallback, number);
  1410. };
  1411. var defaultedString = function (key, fallback) {
  1412. return defaultedOf(key, fallback, string);
  1413. };
  1414. var defaultedStringEnum = function (key, fallback, values) {
  1415. return defaultedOf(key, fallback, validateEnum(values));
  1416. };
  1417. var defaultedBoolean = function (key, fallback) {
  1418. return defaultedOf(key, fallback, boolean);
  1419. };
  1420. var defaultedFunction = function (key, fallback) {
  1421. return defaultedOf(key, fallback, functionProcessor);
  1422. };
  1423. var defaultedPostMsg = function (key, fallback) {
  1424. return defaultedOf(key, fallback, postMessageable);
  1425. };
  1426. var defaultedArrayOf = function (key, fallback, schema) {
  1427. return defaultedOf(key, fallback, arrOf(schema));
  1428. };
  1429. var defaultedObjOf = function (key, fallback, objSchema) {
  1430. return defaultedOf(key, fallback, objOf(objSchema));
  1431. };
  1432. var state$1 = function (okey, instantiator) {
  1433. return state(okey, instantiator);
  1434. };
  1435. var Cell = function (initial) {
  1436. var value = initial;
  1437. var get = function () {
  1438. return value;
  1439. };
  1440. var set = function (v) {
  1441. value = v;
  1442. };
  1443. var clone = function () {
  1444. return Cell(get());
  1445. };
  1446. return {
  1447. get: get,
  1448. set: set,
  1449. clone: clone
  1450. };
  1451. };
  1452. var fromHtml = function (html, scope) {
  1453. var doc = scope || domGlobals.document;
  1454. var div = doc.createElement('div');
  1455. div.innerHTML = html;
  1456. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1457. domGlobals.console.error('HTML does not have a single root node', html);
  1458. throw new Error('HTML must have a single root node');
  1459. }
  1460. return fromDom(div.childNodes[0]);
  1461. };
  1462. var fromTag = function (tag, scope) {
  1463. var doc = scope || domGlobals.document;
  1464. var node = doc.createElement(tag);
  1465. return fromDom(node);
  1466. };
  1467. var fromText = function (text, scope) {
  1468. var doc = scope || domGlobals.document;
  1469. var node = doc.createTextNode(text);
  1470. return fromDom(node);
  1471. };
  1472. var fromDom = function (node) {
  1473. if (node === null || node === undefined) {
  1474. throw new Error('Node cannot be null or undefined');
  1475. }
  1476. return { dom: constant(node) };
  1477. };
  1478. var fromPoint = function (docElm, x, y) {
  1479. var doc = docElm.dom();
  1480. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  1481. };
  1482. var Element = {
  1483. fromHtml: fromHtml,
  1484. fromTag: fromTag,
  1485. fromText: fromText,
  1486. fromDom: fromDom,
  1487. fromPoint: fromPoint
  1488. };
  1489. var compareDocumentPosition = function (a, b, match) {
  1490. return (a.compareDocumentPosition(b) & match) !== 0;
  1491. };
  1492. var documentPositionPreceding = function (a, b) {
  1493. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_PRECEDING);
  1494. };
  1495. var documentPositionContainedBy = function (a, b) {
  1496. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY);
  1497. };
  1498. var Node = {
  1499. documentPositionPreceding: documentPositionPreceding,
  1500. documentPositionContainedBy: documentPositionContainedBy
  1501. };
  1502. var firstMatch = function (regexes, s) {
  1503. for (var i = 0; i < regexes.length; i++) {
  1504. var x = regexes[i];
  1505. if (x.test(s)) {
  1506. return x;
  1507. }
  1508. }
  1509. return undefined;
  1510. };
  1511. var find$2 = function (regexes, agent) {
  1512. var r = firstMatch(regexes, agent);
  1513. if (!r) {
  1514. return {
  1515. major: 0,
  1516. minor: 0
  1517. };
  1518. }
  1519. var group = function (i) {
  1520. return Number(agent.replace(r, '$' + i));
  1521. };
  1522. return nu$1(group(1), group(2));
  1523. };
  1524. var detect = function (versionRegexes, agent) {
  1525. var cleanedAgent = String(agent).toLowerCase();
  1526. if (versionRegexes.length === 0) {
  1527. return unknown();
  1528. }
  1529. return find$2(versionRegexes, cleanedAgent);
  1530. };
  1531. var unknown = function () {
  1532. return nu$1(0, 0);
  1533. };
  1534. var nu$1 = function (major, minor) {
  1535. return {
  1536. major: major,
  1537. minor: minor
  1538. };
  1539. };
  1540. var Version = {
  1541. nu: nu$1,
  1542. detect: detect,
  1543. unknown: unknown
  1544. };
  1545. var edge = 'Edge';
  1546. var chrome = 'Chrome';
  1547. var ie = 'IE';
  1548. var opera = 'Opera';
  1549. var firefox = 'Firefox';
  1550. var safari = 'Safari';
  1551. var isBrowser = function (name, current) {
  1552. return function () {
  1553. return current === name;
  1554. };
  1555. };
  1556. var unknown$1 = function () {
  1557. return nu$2({
  1558. current: undefined,
  1559. version: Version.unknown()
  1560. });
  1561. };
  1562. var nu$2 = function (info) {
  1563. var current = info.current;
  1564. var version = info.version;
  1565. return {
  1566. current: current,
  1567. version: version,
  1568. isEdge: isBrowser(edge, current),
  1569. isChrome: isBrowser(chrome, current),
  1570. isIE: isBrowser(ie, current),
  1571. isOpera: isBrowser(opera, current),
  1572. isFirefox: isBrowser(firefox, current),
  1573. isSafari: isBrowser(safari, current)
  1574. };
  1575. };
  1576. var Browser = {
  1577. unknown: unknown$1,
  1578. nu: nu$2,
  1579. edge: constant(edge),
  1580. chrome: constant(chrome),
  1581. ie: constant(ie),
  1582. opera: constant(opera),
  1583. firefox: constant(firefox),
  1584. safari: constant(safari)
  1585. };
  1586. var windows = 'Windows';
  1587. var ios = 'iOS';
  1588. var android = 'Android';
  1589. var linux = 'Linux';
  1590. var osx = 'OSX';
  1591. var solaris = 'Solaris';
  1592. var freebsd = 'FreeBSD';
  1593. var isOS = function (name, current) {
  1594. return function () {
  1595. return current === name;
  1596. };
  1597. };
  1598. var unknown$2 = function () {
  1599. return nu$3({
  1600. current: undefined,
  1601. version: Version.unknown()
  1602. });
  1603. };
  1604. var nu$3 = function (info) {
  1605. var current = info.current;
  1606. var version = info.version;
  1607. return {
  1608. current: current,
  1609. version: version,
  1610. isWindows: isOS(windows, current),
  1611. isiOS: isOS(ios, current),
  1612. isAndroid: isOS(android, current),
  1613. isOSX: isOS(osx, current),
  1614. isLinux: isOS(linux, current),
  1615. isSolaris: isOS(solaris, current),
  1616. isFreeBSD: isOS(freebsd, current)
  1617. };
  1618. };
  1619. var OperatingSystem = {
  1620. unknown: unknown$2,
  1621. nu: nu$3,
  1622. windows: constant(windows),
  1623. ios: constant(ios),
  1624. android: constant(android),
  1625. linux: constant(linux),
  1626. osx: constant(osx),
  1627. solaris: constant(solaris),
  1628. freebsd: constant(freebsd)
  1629. };
  1630. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  1631. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  1632. var isiPhone = os.isiOS() && !isiPad;
  1633. var isMobile = os.isiOS() || os.isAndroid();
  1634. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  1635. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  1636. var isPhone = isiPhone || isMobile && !isTablet;
  1637. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  1638. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  1639. return {
  1640. isiPad: constant(isiPad),
  1641. isiPhone: constant(isiPhone),
  1642. isTablet: constant(isTablet),
  1643. isPhone: constant(isPhone),
  1644. isTouch: constant(isTouch),
  1645. isAndroid: os.isAndroid,
  1646. isiOS: os.isiOS,
  1647. isWebView: constant(iOSwebview),
  1648. isDesktop: constant(isDesktop)
  1649. };
  1650. };
  1651. var detect$1 = function (candidates, userAgent) {
  1652. var agent = String(userAgent).toLowerCase();
  1653. return find(candidates, function (candidate) {
  1654. return candidate.search(agent);
  1655. });
  1656. };
  1657. var detectBrowser = function (browsers, userAgent) {
  1658. return detect$1(browsers, userAgent).map(function (browser) {
  1659. var version = Version.detect(browser.versionRegexes, userAgent);
  1660. return {
  1661. current: browser.name,
  1662. version: version
  1663. };
  1664. });
  1665. };
  1666. var detectOs = function (oses, userAgent) {
  1667. return detect$1(oses, userAgent).map(function (os) {
  1668. var version = Version.detect(os.versionRegexes, userAgent);
  1669. return {
  1670. current: os.name,
  1671. version: version
  1672. };
  1673. });
  1674. };
  1675. var UaString = {
  1676. detectBrowser: detectBrowser,
  1677. detectOs: detectOs
  1678. };
  1679. var checkRange = function (str, substr, start) {
  1680. if (substr === '') {
  1681. return true;
  1682. }
  1683. if (str.length < substr.length) {
  1684. return false;
  1685. }
  1686. var x = str.substr(start, start + substr.length);
  1687. return x === substr;
  1688. };
  1689. var contains$1 = function (str, substr) {
  1690. return str.indexOf(substr) !== -1;
  1691. };
  1692. var endsWith = function (str, suffix) {
  1693. return checkRange(str, suffix, str.length - suffix.length);
  1694. };
  1695. var trim = function (str) {
  1696. return str.replace(/^\s+|\s+$/g, '');
  1697. };
  1698. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  1699. var checkContains = function (target) {
  1700. return function (uastring) {
  1701. return contains$1(uastring, target);
  1702. };
  1703. };
  1704. var browsers = [
  1705. {
  1706. name: 'Edge',
  1707. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  1708. search: function (uastring) {
  1709. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  1710. }
  1711. },
  1712. {
  1713. name: 'Chrome',
  1714. versionRegexes: [
  1715. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  1716. normalVersionRegex
  1717. ],
  1718. search: function (uastring) {
  1719. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  1720. }
  1721. },
  1722. {
  1723. name: 'IE',
  1724. versionRegexes: [
  1725. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  1726. /.*?rv:([0-9]+)\.([0-9]+).*/
  1727. ],
  1728. search: function (uastring) {
  1729. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  1730. }
  1731. },
  1732. {
  1733. name: 'Opera',
  1734. versionRegexes: [
  1735. normalVersionRegex,
  1736. /.*?opera\/([0-9]+)\.([0-9]+).*/
  1737. ],
  1738. search: checkContains('opera')
  1739. },
  1740. {
  1741. name: 'Firefox',
  1742. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1743. search: checkContains('firefox')
  1744. },
  1745. {
  1746. name: 'Safari',
  1747. versionRegexes: [
  1748. normalVersionRegex,
  1749. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1750. ],
  1751. search: function (uastring) {
  1752. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1753. }
  1754. }
  1755. ];
  1756. var oses = [
  1757. {
  1758. name: 'Windows',
  1759. search: checkContains('win'),
  1760. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1761. },
  1762. {
  1763. name: 'iOS',
  1764. search: function (uastring) {
  1765. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1766. },
  1767. versionRegexes: [
  1768. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1769. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1770. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1771. ]
  1772. },
  1773. {
  1774. name: 'Android',
  1775. search: checkContains('android'),
  1776. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1777. },
  1778. {
  1779. name: 'OSX',
  1780. search: checkContains('os x'),
  1781. versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
  1782. },
  1783. {
  1784. name: 'Linux',
  1785. search: checkContains('linux'),
  1786. versionRegexes: []
  1787. },
  1788. {
  1789. name: 'Solaris',
  1790. search: checkContains('sunos'),
  1791. versionRegexes: []
  1792. },
  1793. {
  1794. name: 'FreeBSD',
  1795. search: checkContains('freebsd'),
  1796. versionRegexes: []
  1797. }
  1798. ];
  1799. var PlatformInfo = {
  1800. browsers: constant(browsers),
  1801. oses: constant(oses)
  1802. };
  1803. var detect$2 = function (userAgent, mediaMatch) {
  1804. var browsers = PlatformInfo.browsers();
  1805. var oses = PlatformInfo.oses();
  1806. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  1807. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1808. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1809. return {
  1810. browser: browser,
  1811. os: os,
  1812. deviceType: deviceType
  1813. };
  1814. };
  1815. var PlatformDetection = { detect: detect$2 };
  1816. var mediaMatch = function (query) {
  1817. return domGlobals.window.matchMedia(query).matches;
  1818. };
  1819. var platform = Cell(PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch));
  1820. var detect$3 = function () {
  1821. return platform.get();
  1822. };
  1823. var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE;
  1824. var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE;
  1825. var COMMENT = domGlobals.Node.COMMENT_NODE;
  1826. var DOCUMENT = domGlobals.Node.DOCUMENT_NODE;
  1827. var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE;
  1828. var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE;
  1829. var ELEMENT = domGlobals.Node.ELEMENT_NODE;
  1830. var TEXT = domGlobals.Node.TEXT_NODE;
  1831. var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE;
  1832. var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE;
  1833. var ENTITY = domGlobals.Node.ENTITY_NODE;
  1834. var NOTATION = domGlobals.Node.NOTATION_NODE;
  1835. var ELEMENT$1 = ELEMENT;
  1836. var DOCUMENT$1 = DOCUMENT;
  1837. var is = function (element, selector) {
  1838. var dom = element.dom();
  1839. if (dom.nodeType !== ELEMENT$1) {
  1840. return false;
  1841. } else {
  1842. var elem = dom;
  1843. if (elem.matches !== undefined) {
  1844. return elem.matches(selector);
  1845. } else if (elem.msMatchesSelector !== undefined) {
  1846. return elem.msMatchesSelector(selector);
  1847. } else if (elem.webkitMatchesSelector !== undefined) {
  1848. return elem.webkitMatchesSelector(selector);
  1849. } else if (elem.mozMatchesSelector !== undefined) {
  1850. return elem.mozMatchesSelector(selector);
  1851. } else {
  1852. throw new Error('Browser lacks native selectors');
  1853. }
  1854. }
  1855. };
  1856. var bypassSelector = function (dom) {
  1857. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  1858. };
  1859. var all = function (selector, scope) {
  1860. var base = scope === undefined ? domGlobals.document : scope.dom();
  1861. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), Element.fromDom);
  1862. };
  1863. var one = function (selector, scope) {
  1864. var base = scope === undefined ? domGlobals.document : scope.dom();
  1865. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1866. };
  1867. var eq = function (e1, e2) {
  1868. return e1.dom() === e2.dom();
  1869. };
  1870. var regularContains = function (e1, e2) {
  1871. var d1 = e1.dom();
  1872. var d2 = e2.dom();
  1873. return d1 === d2 ? false : d1.contains(d2);
  1874. };
  1875. var ieContains = function (e1, e2) {
  1876. return Node.documentPositionContainedBy(e1.dom(), e2.dom());
  1877. };
  1878. var browser = detect$3().browser;
  1879. var contains$2 = browser.isIE() ? ieContains : regularContains;
  1880. var isSource = function (component, simulatedEvent) {
  1881. return eq(component.element(), simulatedEvent.event().target());
  1882. };
  1883. var nu$4 = function (parts) {
  1884. if (!hasKey$1(parts, 'can') && !hasKey$1(parts, 'abort') && !hasKey$1(parts, 'run')) {
  1885. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  1886. }
  1887. return asRawOrDie('Extracting event.handler', objOfOnly([
  1888. defaulted$1('can', constant(true)),
  1889. defaulted$1('abort', constant(false)),
  1890. defaulted$1('run', noop)
  1891. ]), parts);
  1892. };
  1893. var all$1 = function (handlers, f) {
  1894. return function () {
  1895. var args = [];
  1896. for (var _i = 0; _i < arguments.length; _i++) {
  1897. args[_i] = arguments[_i];
  1898. }
  1899. return foldl(handlers, function (acc, handler) {
  1900. return acc && f(handler).apply(undefined, args);
  1901. }, true);
  1902. };
  1903. };
  1904. var any = function (handlers, f) {
  1905. return function () {
  1906. var args = [];
  1907. for (var _i = 0; _i < arguments.length; _i++) {
  1908. args[_i] = arguments[_i];
  1909. }
  1910. return foldl(handlers, function (acc, handler) {
  1911. return acc || f(handler).apply(undefined, args);
  1912. }, false);
  1913. };
  1914. };
  1915. var read = function (handler) {
  1916. return isFunction(handler) ? {
  1917. can: constant(true),
  1918. abort: constant(false),
  1919. run: handler
  1920. } : handler;
  1921. };
  1922. var fuse = function (handlers) {
  1923. var can = all$1(handlers, function (handler) {
  1924. return handler.can;
  1925. });
  1926. var abort = any(handlers, function (handler) {
  1927. return handler.abort;
  1928. });
  1929. var run = function () {
  1930. var args = [];
  1931. for (var _i = 0; _i < arguments.length; _i++) {
  1932. args[_i] = arguments[_i];
  1933. }
  1934. each(handlers, function (handler) {
  1935. handler.run.apply(undefined, args);
  1936. });
  1937. };
  1938. return nu$4({
  1939. can: can,
  1940. abort: abort,
  1941. run: run
  1942. });
  1943. };
  1944. var touchstart = constant('touchstart');
  1945. var touchmove = constant('touchmove');
  1946. var touchend = constant('touchend');
  1947. var mousedown = constant('mousedown');
  1948. var mousemove = constant('mousemove');
  1949. var mouseout = constant('mouseout');
  1950. var mouseup = constant('mouseup');
  1951. var mouseover = constant('mouseover');
  1952. var focusin = constant('focusin');
  1953. var focusout = constant('focusout');
  1954. var keydown = constant('keydown');
  1955. var keyup = constant('keyup');
  1956. var input = constant('input');
  1957. var change = constant('change');
  1958. var click = constant('click');
  1959. var transitionend = constant('transitionend');
  1960. var selectstart = constant('selectstart');
  1961. var alloy = { tap: constant('alloy.tap') };
  1962. var focus = constant('alloy.focus');
  1963. var postBlur = constant('alloy.blur.post');
  1964. var postPaste = constant('alloy.paste.post');
  1965. var receive = constant('alloy.receive');
  1966. var execute = constant('alloy.execute');
  1967. var focusItem = constant('alloy.focus.item');
  1968. var tap = alloy.tap;
  1969. var tapOrClick = detect$3().deviceType.isTouch() ? alloy.tap : click;
  1970. var longpress = constant('alloy.longpress');
  1971. var sandboxClose = constant('alloy.sandbox.close');
  1972. var typeaheadCancel = constant('alloy.typeahead.cancel');
  1973. var systemInit = constant('alloy.system.init');
  1974. var documentTouchmove = constant('alloy.system.touchmove');
  1975. var documentTouchend = constant('alloy.system.touchend');
  1976. var windowScroll = constant('alloy.system.scroll');
  1977. var windowResize = constant('alloy.system.resize');
  1978. var attachedToDom = constant('alloy.system.attached');
  1979. var detachedFromDom = constant('alloy.system.detached');
  1980. var dismissRequested = constant('alloy.system.dismissRequested');
  1981. var repositionRequested = constant('alloy.system.repositionRequested');
  1982. var focusShifted = constant('alloy.focusmanager.shifted');
  1983. var slotVisibility = constant('alloy.slotcontainer.visibility');
  1984. var changeTab = constant('alloy.change.tab');
  1985. var dismissTab = constant('alloy.dismiss.tab');
  1986. var highlight = constant('alloy.highlight');
  1987. var dehighlight = constant('alloy.dehighlight');
  1988. var emit = function (component, event) {
  1989. dispatchWith(component, component.element(), event, {});
  1990. };
  1991. var emitWith = function (component, event, properties) {
  1992. dispatchWith(component, component.element(), event, properties);
  1993. };
  1994. var emitExecute = function (component) {
  1995. emit(component, execute());
  1996. };
  1997. var dispatch = function (component, target, event) {
  1998. dispatchWith(component, target, event, {});
  1999. };
  2000. var dispatchWith = function (component, target, event, properties) {
  2001. var data = __assign({ target: target }, properties);
  2002. component.getSystem().triggerEvent(event, target, map$1(data, constant));
  2003. };
  2004. var dispatchEvent = function (component, target, event, simulatedEvent) {
  2005. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  2006. };
  2007. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2008. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  2009. }
  2010. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  2011. var name = function (element) {
  2012. var r = element.dom().nodeName;
  2013. return r.toLowerCase();
  2014. };
  2015. var type = function (element) {
  2016. return element.dom().nodeType;
  2017. };
  2018. var isType$1 = function (t) {
  2019. return function (element) {
  2020. return type(element) === t;
  2021. };
  2022. };
  2023. var isElement = isType$1(ELEMENT);
  2024. var isText = isType$1(TEXT);
  2025. var inBody = function (element) {
  2026. var dom = isText(element) ? element.dom().parentNode : element.dom();
  2027. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  2028. };
  2029. var body = cached(function () {
  2030. return getBody(Element.fromDom(domGlobals.document));
  2031. });
  2032. var getBody = function (doc) {
  2033. var b = doc.dom().body;
  2034. if (b === null || b === undefined) {
  2035. throw new Error('Body is not available yet');
  2036. }
  2037. return Element.fromDom(b);
  2038. };
  2039. var ancestor = function (scope, predicate, isRoot) {
  2040. var element = scope.dom();
  2041. var stop = isFunction(isRoot) ? isRoot : constant(false);
  2042. while (element.parentNode) {
  2043. element = element.parentNode;
  2044. var el = Element.fromDom(element);
  2045. if (predicate(el)) {
  2046. return Option.some(el);
  2047. } else if (stop(el)) {
  2048. break;
  2049. }
  2050. }
  2051. return Option.none();
  2052. };
  2053. var closest = function (scope, predicate, isRoot) {
  2054. var is = function (s, test) {
  2055. return test(s);
  2056. };
  2057. return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  2058. };
  2059. var descendant = function (scope, predicate) {
  2060. var descend = function (node) {
  2061. for (var i = 0; i < node.childNodes.length; i++) {
  2062. var child_1 = Element.fromDom(node.childNodes[i]);
  2063. if (predicate(child_1)) {
  2064. return Option.some(child_1);
  2065. }
  2066. var res = descend(node.childNodes[i]);
  2067. if (res.isSome()) {
  2068. return res;
  2069. }
  2070. }
  2071. return Option.none();
  2072. };
  2073. return descend(scope.dom());
  2074. };
  2075. var closest$1 = function (target, transform, isRoot) {
  2076. var delegate = closest(target, function (elem) {
  2077. return transform(elem).isSome();
  2078. }, isRoot);
  2079. return delegate.bind(transform);
  2080. };
  2081. var derive = function (configs) {
  2082. return wrapAll$1(configs);
  2083. };
  2084. var abort = function (name, predicate) {
  2085. return {
  2086. key: name,
  2087. value: nu$4({ abort: predicate })
  2088. };
  2089. };
  2090. var can = function (name, predicate) {
  2091. return {
  2092. key: name,
  2093. value: nu$4({ can: predicate })
  2094. };
  2095. };
  2096. var preventDefault = function (name) {
  2097. return {
  2098. key: name,
  2099. value: nu$4({
  2100. run: function (component, simulatedEvent) {
  2101. simulatedEvent.event().prevent();
  2102. }
  2103. })
  2104. };
  2105. };
  2106. var run = function (name, handler) {
  2107. return {
  2108. key: name,
  2109. value: nu$4({ run: handler })
  2110. };
  2111. };
  2112. var runActionExtra = function (name, action, extra) {
  2113. return {
  2114. key: name,
  2115. value: nu$4({
  2116. run: function (component) {
  2117. action.apply(undefined, [component].concat(extra));
  2118. }
  2119. })
  2120. };
  2121. };
  2122. var runOnName = function (name) {
  2123. return function (handler) {
  2124. return run(name, handler);
  2125. };
  2126. };
  2127. var runOnSourceName = function (name) {
  2128. return function (handler) {
  2129. return {
  2130. key: name,
  2131. value: nu$4({
  2132. run: function (component, simulatedEvent) {
  2133. if (isSource(component, simulatedEvent)) {
  2134. handler(component, simulatedEvent);
  2135. }
  2136. }
  2137. })
  2138. };
  2139. };
  2140. };
  2141. var redirectToUid = function (name, uid) {
  2142. return run(name, function (component, simulatedEvent) {
  2143. component.getSystem().getByUid(uid).each(function (redirectee) {
  2144. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2145. });
  2146. });
  2147. };
  2148. var redirectToPart = function (name, detail, partName) {
  2149. var uid = detail.partUids[partName];
  2150. return redirectToUid(name, uid);
  2151. };
  2152. var runWithTarget = function (name, f) {
  2153. return run(name, function (component, simulatedEvent) {
  2154. var ev = simulatedEvent.event();
  2155. var target = component.getSystem().getByDom(ev.target()).fold(function () {
  2156. var closest = closest$1(ev.target(), function (el) {
  2157. return component.getSystem().getByDom(el).toOption();
  2158. }, constant(false));
  2159. return closest.getOr(component);
  2160. }, function (c) {
  2161. return c;
  2162. });
  2163. f(component, target, simulatedEvent);
  2164. });
  2165. };
  2166. var cutter = function (name) {
  2167. return run(name, function (component, simulatedEvent) {
  2168. simulatedEvent.cut();
  2169. });
  2170. };
  2171. var stopper = function (name) {
  2172. return run(name, function (component, simulatedEvent) {
  2173. simulatedEvent.stop();
  2174. });
  2175. };
  2176. var runOnSource = function (name, f) {
  2177. return runOnSourceName(name)(f);
  2178. };
  2179. var runOnAttached = runOnSourceName(attachedToDom());
  2180. var runOnDetached = runOnSourceName(detachedFromDom());
  2181. var runOnInit = runOnSourceName(systemInit());
  2182. var runOnExecute = runOnName(execute());
  2183. var Immutable = function () {
  2184. var fields = [];
  2185. for (var _i = 0; _i < arguments.length; _i++) {
  2186. fields[_i] = arguments[_i];
  2187. }
  2188. return function () {
  2189. var values = [];
  2190. for (var _i = 0; _i < arguments.length; _i++) {
  2191. values[_i] = arguments[_i];
  2192. }
  2193. if (fields.length !== values.length) {
  2194. throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
  2195. }
  2196. var struct = {};
  2197. each(fields, function (name, i) {
  2198. struct[name] = constant(values[i]);
  2199. });
  2200. return struct;
  2201. };
  2202. };
  2203. var sort$1 = function (arr) {
  2204. return arr.slice(0).sort();
  2205. };
  2206. var reqMessage = function (required, keys) {
  2207. throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  2208. };
  2209. var unsuppMessage = function (unsupported) {
  2210. throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  2211. };
  2212. var validateStrArr = function (label, array) {
  2213. if (!isArray(array)) {
  2214. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  2215. }
  2216. each(array, function (a) {
  2217. if (!isString(a)) {
  2218. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  2219. }
  2220. });
  2221. };
  2222. var checkDupes = function (everything) {
  2223. var sorted = sort$1(everything);
  2224. var dupe = find(sorted, function (s, i) {
  2225. return i < sorted.length - 1 && s === sorted[i + 1];
  2226. });
  2227. dupe.each(function (d) {
  2228. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  2229. });
  2230. };
  2231. var MixedBag = function (required, optional) {
  2232. var everything = required.concat(optional);
  2233. if (everything.length === 0) {
  2234. throw new Error('You must specify at least one required or optional field.');
  2235. }
  2236. validateStrArr('required', required);
  2237. validateStrArr('optional', optional);
  2238. checkDupes(everything);
  2239. return function (obj) {
  2240. var keys$1 = keys(obj);
  2241. var allReqd = forall(required, function (req) {
  2242. return contains(keys$1, req);
  2243. });
  2244. if (!allReqd) {
  2245. reqMessage(required, keys$1);
  2246. }
  2247. var unsupported = filter(keys$1, function (key) {
  2248. return !contains(everything, key);
  2249. });
  2250. if (unsupported.length > 0) {
  2251. unsuppMessage(unsupported);
  2252. }
  2253. var r = {};
  2254. each(required, function (req) {
  2255. r[req] = constant(obj[req]);
  2256. });
  2257. each(optional, function (opt) {
  2258. r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
  2259. });
  2260. return r;
  2261. };
  2262. };
  2263. var owner = function (element) {
  2264. return Element.fromDom(element.dom().ownerDocument);
  2265. };
  2266. var documentElement = function (element) {
  2267. return Element.fromDom(element.dom().ownerDocument.documentElement);
  2268. };
  2269. var defaultView = function (element) {
  2270. return Element.fromDom(element.dom().ownerDocument.defaultView);
  2271. };
  2272. var parent = function (element) {
  2273. return Option.from(element.dom().parentNode).map(Element.fromDom);
  2274. };
  2275. var offsetParent = function (element) {
  2276. return Option.from(element.dom().offsetParent).map(Element.fromDom);
  2277. };
  2278. var nextSibling = function (element) {
  2279. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  2280. };
  2281. var children = function (element) {
  2282. return map(element.dom().childNodes, Element.fromDom);
  2283. };
  2284. var child = function (element, index) {
  2285. var cs = element.dom().childNodes;
  2286. return Option.from(cs[index]).map(Element.fromDom);
  2287. };
  2288. var firstChild = function (element) {
  2289. return child(element, 0);
  2290. };
  2291. var spot = Immutable('element', 'offset');
  2292. var fromHtml$1 = function (html, scope) {
  2293. var doc = scope || domGlobals.document;
  2294. var div = doc.createElement('div');
  2295. div.innerHTML = html;
  2296. return children(Element.fromDom(div));
  2297. };
  2298. var before = function (marker, element) {
  2299. var parent$1 = parent(marker);
  2300. parent$1.each(function (v) {
  2301. v.dom().insertBefore(element.dom(), marker.dom());
  2302. });
  2303. };
  2304. var after = function (marker, element) {
  2305. var sibling = nextSibling(marker);
  2306. sibling.fold(function () {
  2307. var parent$1 = parent(marker);
  2308. parent$1.each(function (v) {
  2309. append(v, element);
  2310. });
  2311. }, function (v) {
  2312. before(v, element);
  2313. });
  2314. };
  2315. var prepend = function (parent, element) {
  2316. var firstChild$1 = firstChild(parent);
  2317. firstChild$1.fold(function () {
  2318. append(parent, element);
  2319. }, function (v) {
  2320. parent.dom().insertBefore(element.dom(), v.dom());
  2321. });
  2322. };
  2323. var append = function (parent, element) {
  2324. parent.dom().appendChild(element.dom());
  2325. };
  2326. var appendAt = function (parent, element, index) {
  2327. child(parent, index).fold(function () {
  2328. append(parent, element);
  2329. }, function (v) {
  2330. before(v, element);
  2331. });
  2332. };
  2333. var before$1 = function (marker, elements) {
  2334. each(elements, function (x) {
  2335. before(marker, x);
  2336. });
  2337. };
  2338. var append$1 = function (parent, elements) {
  2339. each(elements, function (x) {
  2340. append(parent, x);
  2341. });
  2342. };
  2343. var empty = function (element) {
  2344. element.dom().textContent = '';
  2345. each(children(element), function (rogue) {
  2346. remove(rogue);
  2347. });
  2348. };
  2349. var remove = function (element) {
  2350. var dom = element.dom();
  2351. if (dom.parentNode !== null) {
  2352. dom.parentNode.removeChild(dom);
  2353. }
  2354. };
  2355. var unwrap = function (wrapper) {
  2356. var children$1 = children(wrapper);
  2357. if (children$1.length > 0) {
  2358. before$1(wrapper, children$1);
  2359. }
  2360. remove(wrapper);
  2361. };
  2362. var get$1 = function (element) {
  2363. return element.dom().innerHTML;
  2364. };
  2365. var set = function (element, content) {
  2366. var owner$1 = owner(element);
  2367. var docDom = owner$1.dom();
  2368. var fragment = Element.fromDom(docDom.createDocumentFragment());
  2369. var contentElements = fromHtml$1(content, docDom);
  2370. append$1(fragment, contentElements);
  2371. empty(element);
  2372. append(element, fragment);
  2373. };
  2374. var getOuter = function (element) {
  2375. var container = Element.fromTag('div');
  2376. var clone = Element.fromDom(element.dom().cloneNode(true));
  2377. append(container, clone);
  2378. return get$1(container);
  2379. };
  2380. var rawSet = function (dom, key, value) {
  2381. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2382. dom.setAttribute(key, value + '');
  2383. } else {
  2384. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2385. throw new Error('Attribute value was not simple');
  2386. }
  2387. };
  2388. var set$1 = function (element, key, value) {
  2389. rawSet(element.dom(), key, value);
  2390. };
  2391. var setAll = function (element, attrs) {
  2392. var dom = element.dom();
  2393. each$1(attrs, function (v, k) {
  2394. rawSet(dom, k, v);
  2395. });
  2396. };
  2397. var get$2 = function (element, key) {
  2398. var v = element.dom().getAttribute(key);
  2399. return v === null ? undefined : v;
  2400. };
  2401. var has$1 = function (element, key) {
  2402. var dom = element.dom();
  2403. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2404. };
  2405. var remove$1 = function (element, key) {
  2406. element.dom().removeAttribute(key);
  2407. };
  2408. var clone = function (original, isDeep) {
  2409. return Element.fromDom(original.dom().cloneNode(isDeep));
  2410. };
  2411. var shallow$1 = function (original) {
  2412. return clone(original, false);
  2413. };
  2414. var getHtml = function (element) {
  2415. var clone = shallow$1(element);
  2416. return getOuter(clone);
  2417. };
  2418. var element = function (elem) {
  2419. return getHtml(elem);
  2420. };
  2421. var isRecursive = function (component, originator, target) {
  2422. return eq(originator, component.element()) && !eq(originator, target);
  2423. };
  2424. var events = derive([can(focus(), function (component, simulatedEvent) {
  2425. var originator = simulatedEvent.event().originator();
  2426. var target = simulatedEvent.event().target();
  2427. if (isRecursive(component, originator, target)) {
  2428. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  2429. return false;
  2430. } else {
  2431. return true;
  2432. }
  2433. })]);
  2434. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2435. events: events
  2436. });
  2437. var unique = 0;
  2438. var generate$1 = function (prefix) {
  2439. var date = new Date();
  2440. var time = date.getTime();
  2441. var random = Math.floor(Math.random() * 1000000000);
  2442. unique++;
  2443. return prefix + '_' + random + unique + String(time);
  2444. };
  2445. var prefix = constant('alloy-id-');
  2446. var idAttr = constant('data-alloy-id');
  2447. var prefix$1 = prefix();
  2448. var idAttr$1 = idAttr();
  2449. var write = function (label, elem) {
  2450. var id = generate$1(prefix$1 + label);
  2451. writeOnly(elem, id);
  2452. return id;
  2453. };
  2454. var writeOnly = function (elem, uid) {
  2455. Object.defineProperty(elem.dom(), idAttr$1, {
  2456. value: uid,
  2457. writable: true
  2458. });
  2459. };
  2460. var read$1 = function (elem) {
  2461. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  2462. return Option.from(id);
  2463. };
  2464. var generate$2 = function (prefix) {
  2465. return generate$1(prefix);
  2466. };
  2467. var make = identity;
  2468. var NoContextApi = function (getComp) {
  2469. var fail = function (event) {
  2470. return function () {
  2471. throw new Error('The component must be in a context to send: ' + event + '\n' + element(getComp().element()) + ' is not in context.');
  2472. };
  2473. };
  2474. return {
  2475. debugInfo: constant('fake'),
  2476. triggerEvent: fail('triggerEvent'),
  2477. triggerFocus: fail('triggerFocus'),
  2478. triggerEscape: fail('triggerEscape'),
  2479. build: fail('build'),
  2480. addToWorld: fail('addToWorld'),
  2481. removeFromWorld: fail('removeFromWorld'),
  2482. addToGui: fail('addToGui'),
  2483. removeFromGui: fail('removeFromGui'),
  2484. getByUid: fail('getByUid'),
  2485. getByDom: fail('getByDom'),
  2486. broadcast: fail('broadcast'),
  2487. broadcastOn: fail('broadcastOn'),
  2488. broadcastEvent: fail('broadcastEvent'),
  2489. isConnected: constant(false)
  2490. };
  2491. };
  2492. var singleton = NoContextApi();
  2493. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2494. var delegate = apiFunction.toString();
  2495. var endIndex = delegate.indexOf(')') + 1;
  2496. var openBracketIndex = delegate.indexOf('(');
  2497. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2498. f.toFunctionAnnotation = function () {
  2499. return {
  2500. name: apiName,
  2501. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2502. };
  2503. };
  2504. return f;
  2505. };
  2506. var cleanParameters = function (parameters) {
  2507. return map(parameters, function (p) {
  2508. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2509. });
  2510. };
  2511. var markAsExtraApi = function (f, extraName) {
  2512. var delegate = f.toString();
  2513. var endIndex = delegate.indexOf(')') + 1;
  2514. var openBracketIndex = delegate.indexOf('(');
  2515. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2516. f.toFunctionAnnotation = function () {
  2517. return {
  2518. name: extraName,
  2519. parameters: cleanParameters(parameters)
  2520. };
  2521. };
  2522. return f;
  2523. };
  2524. var markAsSketchApi = function (f, apiFunction) {
  2525. var delegate = apiFunction.toString();
  2526. var endIndex = delegate.indexOf(')') + 1;
  2527. var openBracketIndex = delegate.indexOf('(');
  2528. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2529. f.toFunctionAnnotation = function () {
  2530. return {
  2531. name: 'OVERRIDE',
  2532. parameters: cleanParameters(parameters.slice(1))
  2533. };
  2534. };
  2535. return f;
  2536. };
  2537. var premadeTag = generate$1('alloy-premade');
  2538. var premade = function (comp) {
  2539. return wrap$1(premadeTag, comp);
  2540. };
  2541. var getPremade = function (spec) {
  2542. return readOptFrom$1(spec, premadeTag);
  2543. };
  2544. var makeApi = function (f) {
  2545. return markAsSketchApi(function (component) {
  2546. var rest = [];
  2547. for (var _i = 1; _i < arguments.length; _i++) {
  2548. rest[_i - 1] = arguments[_i];
  2549. }
  2550. return f.apply(undefined, [component.getApis()].concat([component].concat(rest)));
  2551. }, f);
  2552. };
  2553. var NoState = {
  2554. init: function () {
  2555. return nu$5({
  2556. readState: function () {
  2557. return 'No State required';
  2558. }
  2559. });
  2560. }
  2561. };
  2562. var nu$5 = function (spec) {
  2563. return spec;
  2564. };
  2565. var generateFrom = function (spec, all) {
  2566. var schema = map(all, function (a) {
  2567. return optionObjOf(a.name(), [
  2568. strict$1('config'),
  2569. defaulted$1('state', NoState)
  2570. ]);
  2571. });
  2572. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  2573. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2574. }, function (v) {
  2575. return v;
  2576. });
  2577. return {
  2578. list: all,
  2579. data: map$1(validated, function (optBlobThunk) {
  2580. var optBlob = optBlobThunk;
  2581. var output = optBlob.map(function (blob) {
  2582. return {
  2583. config: blob.config,
  2584. state: blob.state.init(blob.config)
  2585. };
  2586. });
  2587. return function () {
  2588. return output;
  2589. };
  2590. })
  2591. };
  2592. };
  2593. var getBehaviours = function (bData) {
  2594. return bData.list;
  2595. };
  2596. var getData = function (bData) {
  2597. return bData.data;
  2598. };
  2599. var byInnerKey = function (data, tuple) {
  2600. var r = {};
  2601. each$1(data, function (detail, key) {
  2602. each$1(detail, function (value, indexKey) {
  2603. var chain = readOr$1(indexKey, [])(r);
  2604. r[indexKey] = chain.concat([tuple(key, value)]);
  2605. });
  2606. });
  2607. return r;
  2608. };
  2609. var nu$6 = function (s) {
  2610. return {
  2611. classes: s.classes !== undefined ? s.classes : [],
  2612. attributes: s.attributes !== undefined ? s.attributes : {},
  2613. styles: s.styles !== undefined ? s.styles : {}
  2614. };
  2615. };
  2616. var merge$1 = function (defnA, mod) {
  2617. return __assign(__assign({}, defnA), {
  2618. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2619. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2620. classes: defnA.classes.concat(mod.classes)
  2621. });
  2622. };
  2623. var combine = function (info, baseMod, behaviours, base) {
  2624. var modsByBehaviour = __assign({}, baseMod);
  2625. each(behaviours, function (behaviour) {
  2626. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  2627. });
  2628. var nameAndMod = function (name, modification) {
  2629. return {
  2630. name: name,
  2631. modification: modification
  2632. };
  2633. };
  2634. var byAspect = byInnerKey(modsByBehaviour, nameAndMod);
  2635. var combineObjects = function (objects) {
  2636. return foldr(objects, function (b, a) {
  2637. return __assign(__assign({}, a.modification), b);
  2638. }, {});
  2639. };
  2640. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  2641. return a.modification.concat(b);
  2642. }, []);
  2643. var combinedAttributes = combineObjects(byAspect.attributes);
  2644. var combinedStyles = combineObjects(byAspect.styles);
  2645. return nu$6({
  2646. classes: combinedClasses,
  2647. attributes: combinedAttributes,
  2648. styles: combinedStyles
  2649. });
  2650. };
  2651. var sortKeys = function (label, keyName, array, order) {
  2652. var sliced = array.slice(0);
  2653. try {
  2654. var sorted = sliced.sort(function (a, b) {
  2655. var aKey = a[keyName]();
  2656. var bKey = b[keyName]();
  2657. var aIndex = order.indexOf(aKey);
  2658. var bIndex = order.indexOf(bKey);
  2659. if (aIndex === -1) {
  2660. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2661. }
  2662. if (bIndex === -1) {
  2663. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2664. }
  2665. if (aIndex < bIndex) {
  2666. return -1;
  2667. } else if (bIndex < aIndex) {
  2668. return 1;
  2669. } else {
  2670. return 0;
  2671. }
  2672. });
  2673. return Result.value(sorted);
  2674. } catch (err) {
  2675. return Result.error([err]);
  2676. }
  2677. };
  2678. var uncurried = function (handler, purpose) {
  2679. return {
  2680. handler: handler,
  2681. purpose: constant(purpose)
  2682. };
  2683. };
  2684. var curried = function (handler, purpose) {
  2685. return {
  2686. cHandler: handler,
  2687. purpose: constant(purpose)
  2688. };
  2689. };
  2690. var curryArgs = function (descHandler, extraArgs) {
  2691. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  2692. };
  2693. var getCurried = function (descHandler) {
  2694. return descHandler.cHandler;
  2695. };
  2696. var behaviourTuple = function (name, handler) {
  2697. return {
  2698. name: constant(name),
  2699. handler: constant(handler)
  2700. };
  2701. };
  2702. var nameToHandlers = function (behaviours, info) {
  2703. var r = {};
  2704. each(behaviours, function (behaviour) {
  2705. r[behaviour.name()] = behaviour.handlers(info);
  2706. });
  2707. return r;
  2708. };
  2709. var groupByEvents = function (info, behaviours, base) {
  2710. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  2711. return byInnerKey(behaviourEvents, behaviourTuple);
  2712. };
  2713. var combine$1 = function (info, eventOrder, behaviours, base) {
  2714. var byEventName = groupByEvents(info, behaviours, base);
  2715. return combineGroups(byEventName, eventOrder);
  2716. };
  2717. var assemble = function (rawHandler) {
  2718. var handler = read(rawHandler);
  2719. return function (component, simulatedEvent) {
  2720. var rest = [];
  2721. for (var _i = 2; _i < arguments.length; _i++) {
  2722. rest[_i - 2] = arguments[_i];
  2723. }
  2724. var args = [
  2725. component,
  2726. simulatedEvent
  2727. ].concat(rest);
  2728. if (handler.abort.apply(undefined, args)) {
  2729. simulatedEvent.stop();
  2730. } else if (handler.can.apply(undefined, args)) {
  2731. handler.run.apply(undefined, args);
  2732. }
  2733. };
  2734. };
  2735. var missingOrderError = function (eventName, tuples) {
  2736. 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) {
  2737. return c.name();
  2738. }), null, 2)]);
  2739. };
  2740. var fuse$1 = function (tuples, eventOrder, eventName) {
  2741. var order = eventOrder[eventName];
  2742. if (!order) {
  2743. return missingOrderError(eventName, tuples);
  2744. } else {
  2745. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  2746. var handlers = map(sortedTuples, function (tuple) {
  2747. return tuple.handler();
  2748. });
  2749. return fuse(handlers);
  2750. });
  2751. }
  2752. };
  2753. var combineGroups = function (byEventName, eventOrder) {
  2754. var r = mapToArray(byEventName, function (tuples, eventName) {
  2755. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  2756. return combined.map(function (handler) {
  2757. var assembled = assemble(handler);
  2758. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  2759. return exists(tuples, function (t) {
  2760. return t.name() === o;
  2761. });
  2762. }).join(' > ') : tuples[0].name();
  2763. return wrap$1(eventName, uncurried(assembled, purpose));
  2764. });
  2765. });
  2766. return consolidate(r, {});
  2767. };
  2768. var toInfo = function (spec) {
  2769. return asRaw('custom.definition', objOf([
  2770. field('dom', 'dom', strict(), objOf([
  2771. strict$1('tag'),
  2772. defaulted$1('styles', {}),
  2773. defaulted$1('classes', []),
  2774. defaulted$1('attributes', {}),
  2775. option('value'),
  2776. option('innerHtml')
  2777. ])),
  2778. strict$1('components'),
  2779. strict$1('uid'),
  2780. defaulted$1('events', {}),
  2781. defaulted$1('apis', {}),
  2782. field('eventOrder', 'eventOrder', mergeWith({
  2783. 'alloy.execute': [
  2784. 'disabling',
  2785. 'alloy.base.behaviour',
  2786. 'toggling',
  2787. 'typeaheadevents'
  2788. ],
  2789. 'alloy.focus': [
  2790. 'alloy.base.behaviour',
  2791. 'focusing',
  2792. 'keying'
  2793. ],
  2794. 'alloy.system.init': [
  2795. 'alloy.base.behaviour',
  2796. 'disabling',
  2797. 'toggling',
  2798. 'representing'
  2799. ],
  2800. 'input': [
  2801. 'alloy.base.behaviour',
  2802. 'representing',
  2803. 'streaming',
  2804. 'invalidating'
  2805. ],
  2806. 'alloy.system.detached': [
  2807. 'alloy.base.behaviour',
  2808. 'representing',
  2809. 'item-events',
  2810. 'tooltipping'
  2811. ],
  2812. 'mousedown': [
  2813. 'focusing',
  2814. 'alloy.base.behaviour',
  2815. 'item-type-events'
  2816. ],
  2817. 'mouseover': [
  2818. 'item-type-events',
  2819. 'tooltipping'
  2820. ]
  2821. }), anyValue$1()),
  2822. option('domModification')
  2823. ]), spec);
  2824. };
  2825. var toDefinition = function (detail) {
  2826. return __assign(__assign({}, detail.dom), {
  2827. uid: detail.uid,
  2828. domChildren: map(detail.components, function (comp) {
  2829. return comp.element();
  2830. })
  2831. });
  2832. };
  2833. var toModification = function (detail) {
  2834. return detail.domModification.fold(function () {
  2835. return nu$6({});
  2836. }, nu$6);
  2837. };
  2838. var toEvents = function (info) {
  2839. return info.events;
  2840. };
  2841. var read$2 = function (element, attr) {
  2842. var value = get$2(element, attr);
  2843. return value === undefined || value === '' ? [] : value.split(' ');
  2844. };
  2845. var add = function (element, attr, id) {
  2846. var old = read$2(element, attr);
  2847. var nu = old.concat([id]);
  2848. set$1(element, attr, nu.join(' '));
  2849. return true;
  2850. };
  2851. var remove$2 = function (element, attr, id) {
  2852. var nu = filter(read$2(element, attr), function (v) {
  2853. return v !== id;
  2854. });
  2855. if (nu.length > 0) {
  2856. set$1(element, attr, nu.join(' '));
  2857. } else {
  2858. remove$1(element, attr);
  2859. }
  2860. return false;
  2861. };
  2862. var supports = function (element) {
  2863. return element.dom().classList !== undefined;
  2864. };
  2865. var get$3 = function (element) {
  2866. return read$2(element, 'class');
  2867. };
  2868. var add$1 = function (element, clazz) {
  2869. return add(element, 'class', clazz);
  2870. };
  2871. var remove$3 = function (element, clazz) {
  2872. return remove$2(element, 'class', clazz);
  2873. };
  2874. var add$2 = function (element, clazz) {
  2875. if (supports(element)) {
  2876. element.dom().classList.add(clazz);
  2877. } else {
  2878. add$1(element, clazz);
  2879. }
  2880. };
  2881. var cleanClass = function (element) {
  2882. var classList = supports(element) ? element.dom().classList : get$3(element);
  2883. if (classList.length === 0) {
  2884. remove$1(element, 'class');
  2885. }
  2886. };
  2887. var remove$4 = function (element, clazz) {
  2888. if (supports(element)) {
  2889. var classList = element.dom().classList;
  2890. classList.remove(clazz);
  2891. } else {
  2892. remove$3(element, clazz);
  2893. }
  2894. cleanClass(element);
  2895. };
  2896. var has$2 = function (element, clazz) {
  2897. return supports(element) && element.dom().classList.contains(clazz);
  2898. };
  2899. var add$3 = function (element, classes) {
  2900. each(classes, function (x) {
  2901. add$2(element, x);
  2902. });
  2903. };
  2904. var remove$5 = function (element, classes) {
  2905. each(classes, function (x) {
  2906. remove$4(element, x);
  2907. });
  2908. };
  2909. var isSupported = function (dom) {
  2910. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  2911. };
  2912. var internalSet = function (dom, property, value) {
  2913. if (!isString(value)) {
  2914. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  2915. throw new Error('CSS value must be a string: ' + value);
  2916. }
  2917. if (isSupported(dom)) {
  2918. dom.style.setProperty(property, value);
  2919. }
  2920. };
  2921. var internalRemove = function (dom, property) {
  2922. if (isSupported(dom)) {
  2923. dom.style.removeProperty(property);
  2924. }
  2925. };
  2926. var set$2 = function (element, property, value) {
  2927. var dom = element.dom();
  2928. internalSet(dom, property, value);
  2929. };
  2930. var setAll$1 = function (element, css) {
  2931. var dom = element.dom();
  2932. each$1(css, function (v, k) {
  2933. internalSet(dom, k, v);
  2934. });
  2935. };
  2936. var setOptions = function (element, css) {
  2937. var dom = element.dom();
  2938. each$1(css, function (v, k) {
  2939. v.fold(function () {
  2940. internalRemove(dom, k);
  2941. }, function (value) {
  2942. internalSet(dom, k, value);
  2943. });
  2944. });
  2945. };
  2946. var get$4 = function (element, property) {
  2947. var dom = element.dom();
  2948. var styles = domGlobals.window.getComputedStyle(dom);
  2949. var r = styles.getPropertyValue(property);
  2950. var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  2951. return v === null ? undefined : v;
  2952. };
  2953. var getUnsafeProperty = function (dom, property) {
  2954. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  2955. };
  2956. var getRaw = function (element, property) {
  2957. var dom = element.dom();
  2958. var raw = getUnsafeProperty(dom, property);
  2959. return Option.from(raw).filter(function (r) {
  2960. return r.length > 0;
  2961. });
  2962. };
  2963. var isValidValue = function (tag, property, value) {
  2964. var element = Element.fromTag(tag);
  2965. set$2(element, property, value);
  2966. var style = getRaw(element, property);
  2967. return style.isSome();
  2968. };
  2969. var remove$6 = function (element, property) {
  2970. var dom = element.dom();
  2971. internalRemove(dom, property);
  2972. if (has$1(element, 'style') && trim(get$2(element, 'style')) === '') {
  2973. remove$1(element, 'style');
  2974. }
  2975. };
  2976. var reflow = function (e) {
  2977. return e.dom().offsetWidth;
  2978. };
  2979. var get$5 = function (element) {
  2980. return element.dom().value;
  2981. };
  2982. var set$3 = function (element, value) {
  2983. if (value === undefined) {
  2984. throw new Error('Value.set was undefined');
  2985. }
  2986. element.dom().value = value;
  2987. };
  2988. var renderToDom = function (definition) {
  2989. var subject = Element.fromTag(definition.tag);
  2990. setAll(subject, definition.attributes);
  2991. add$3(subject, definition.classes);
  2992. setAll$1(subject, definition.styles);
  2993. definition.innerHtml.each(function (html) {
  2994. return set(subject, html);
  2995. });
  2996. var children = definition.domChildren;
  2997. append$1(subject, children);
  2998. definition.value.each(function (value) {
  2999. set$3(subject, value);
  3000. });
  3001. if (!definition.uid) {
  3002. debugger;
  3003. }
  3004. writeOnly(subject, definition.uid);
  3005. return subject;
  3006. };
  3007. var getBehaviours$1 = function (spec) {
  3008. var behaviours = readOr$1('behaviours', {})(spec);
  3009. var keys$1 = filter(keys(behaviours), function (k) {
  3010. return behaviours[k] !== undefined;
  3011. });
  3012. return map(keys$1, function (k) {
  3013. return behaviours[k].me;
  3014. });
  3015. };
  3016. var generateFrom$1 = function (spec, all) {
  3017. return generateFrom(spec, all);
  3018. };
  3019. var generate$3 = function (spec) {
  3020. var all = getBehaviours$1(spec);
  3021. return generateFrom$1(spec, all);
  3022. };
  3023. var getDomDefinition = function (info, bList, bData) {
  3024. var definition = toDefinition(info);
  3025. var infoModification = toModification(info);
  3026. var baseModification = { 'alloy.base.modification': infoModification };
  3027. var modification = bList.length > 0 ? combine(bData, baseModification, bList, definition) : infoModification;
  3028. return merge$1(definition, modification);
  3029. };
  3030. var getEvents = function (info, bList, bData) {
  3031. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  3032. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  3033. };
  3034. var build = function (spec) {
  3035. var getMe = function () {
  3036. return me;
  3037. };
  3038. var systemApi = Cell(singleton);
  3039. var info = getOrDie(toInfo(spec));
  3040. var bBlob = generate$3(spec);
  3041. var bList = getBehaviours(bBlob);
  3042. var bData = getData(bBlob);
  3043. var modDefinition = getDomDefinition(info, bList, bData);
  3044. var item = renderToDom(modDefinition);
  3045. var events = getEvents(info, bList, bData);
  3046. var subcomponents = Cell(info.components);
  3047. var connect = function (newApi) {
  3048. systemApi.set(newApi);
  3049. };
  3050. var disconnect = function () {
  3051. systemApi.set(NoContextApi(getMe));
  3052. };
  3053. var syncComponents = function () {
  3054. var children$1 = children(item);
  3055. var subs = bind(children$1, function (child) {
  3056. return systemApi.get().getByDom(child).fold(function () {
  3057. return [];
  3058. }, function (c) {
  3059. return [c];
  3060. });
  3061. });
  3062. subcomponents.set(subs);
  3063. };
  3064. var config = function (behaviour) {
  3065. var b = bData;
  3066. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  3067. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  3068. };
  3069. return f();
  3070. };
  3071. var hasConfigured = function (behaviour) {
  3072. return isFunction(bData[behaviour.name()]);
  3073. };
  3074. var getApis = function () {
  3075. return info.apis;
  3076. };
  3077. var readState = function (behaviourName) {
  3078. return bData[behaviourName]().map(function (b) {
  3079. return b.state.readState();
  3080. }).getOr('not enabled');
  3081. };
  3082. var me = {
  3083. getSystem: systemApi.get,
  3084. config: config,
  3085. hasConfigured: hasConfigured,
  3086. spec: constant(spec),
  3087. readState: readState,
  3088. getApis: getApis,
  3089. connect: connect,
  3090. disconnect: disconnect,
  3091. element: constant(item),
  3092. syncComponents: syncComponents,
  3093. components: subcomponents.get,
  3094. events: constant(events)
  3095. };
  3096. return me;
  3097. };
  3098. var buildSubcomponents = function (spec) {
  3099. var components = readOr$1('components', [])(spec);
  3100. return map(components, build$1);
  3101. };
  3102. var buildFromSpec = function (userSpec) {
  3103. var _a = make(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  3104. var components = buildSubcomponents(spec);
  3105. var completeSpec = __assign(__assign({}, spec), {
  3106. events: __assign(__assign({}, DefaultEvents), specEvents),
  3107. components: components
  3108. });
  3109. return Result.value(build(completeSpec));
  3110. };
  3111. var text = function (textContent) {
  3112. var element = Element.fromText(textContent);
  3113. return external({ element: element });
  3114. };
  3115. var external = function (spec) {
  3116. var extSpec = asRawOrDie('external.component', objOfOnly([
  3117. strict$1('element'),
  3118. option('uid')
  3119. ]), spec);
  3120. var systemApi = Cell(NoContextApi());
  3121. var connect = function (newApi) {
  3122. systemApi.set(newApi);
  3123. };
  3124. var disconnect = function () {
  3125. systemApi.set(NoContextApi(function () {
  3126. return me;
  3127. }));
  3128. };
  3129. extSpec.uid.each(function (uid) {
  3130. writeOnly(extSpec.element, uid);
  3131. });
  3132. var me = {
  3133. getSystem: systemApi.get,
  3134. config: Option.none,
  3135. hasConfigured: constant(false),
  3136. connect: connect,
  3137. disconnect: disconnect,
  3138. getApis: function () {
  3139. return {};
  3140. },
  3141. element: constant(extSpec.element),
  3142. spec: constant(spec),
  3143. readState: constant('No state'),
  3144. syncComponents: noop,
  3145. components: constant([]),
  3146. events: constant({})
  3147. };
  3148. return premade(me);
  3149. };
  3150. var uids = generate$2;
  3151. var build$1 = function (spec) {
  3152. return getPremade(spec).fold(function () {
  3153. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  3154. return buildFromSpec(userSpecWithUid).getOrDie();
  3155. }, function (prebuilt) {
  3156. return prebuilt;
  3157. });
  3158. };
  3159. var premade$1 = premade;
  3160. function Dimension (name, getOffset) {
  3161. var set = function (element, h) {
  3162. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3163. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3164. }
  3165. var dom = element.dom();
  3166. if (isSupported(dom)) {
  3167. dom.style[name] = h + 'px';
  3168. }
  3169. };
  3170. var get = function (element) {
  3171. var r = getOffset(element);
  3172. if (r <= 0 || r === null) {
  3173. var css = get$4(element, name);
  3174. return parseFloat(css) || 0;
  3175. }
  3176. return r;
  3177. };
  3178. var getOuter = get;
  3179. var aggregate = function (element, properties) {
  3180. return foldl(properties, function (acc, property) {
  3181. var val = get$4(element, property);
  3182. var value = val === undefined ? 0 : parseInt(val, 10);
  3183. return isNaN(value) ? acc : acc + value;
  3184. }, 0);
  3185. };
  3186. var max = function (element, value, properties) {
  3187. var cumulativeInclusions = aggregate(element, properties);
  3188. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3189. return absoluteMax;
  3190. };
  3191. return {
  3192. set: set,
  3193. get: get,
  3194. getOuter: getOuter,
  3195. aggregate: aggregate,
  3196. max: max
  3197. };
  3198. }
  3199. var api = Dimension('height', function (element) {
  3200. var dom = element.dom();
  3201. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3202. });
  3203. var get$6 = function (element) {
  3204. return api.get(element);
  3205. };
  3206. var getOuter$1 = function (element) {
  3207. return api.getOuter(element);
  3208. };
  3209. var setMax = function (element, value) {
  3210. var inclusions = [
  3211. 'margin-top',
  3212. 'border-top-width',
  3213. 'padding-top',
  3214. 'padding-bottom',
  3215. 'border-bottom-width',
  3216. 'margin-bottom'
  3217. ];
  3218. var absMax = api.max(element, value, inclusions);
  3219. set$2(element, 'max-height', absMax + 'px');
  3220. };
  3221. var r = function (left, top) {
  3222. var translate = function (x, y) {
  3223. return r(left + x, top + y);
  3224. };
  3225. return {
  3226. left: constant(left),
  3227. top: constant(top),
  3228. translate: translate
  3229. };
  3230. };
  3231. var Position = r;
  3232. var boxPosition = function (dom) {
  3233. var box = dom.getBoundingClientRect();
  3234. return Position(box.left, box.top);
  3235. };
  3236. var firstDefinedOrZero = function (a, b) {
  3237. return a !== undefined ? a : b !== undefined ? b : 0;
  3238. };
  3239. var absolute = function (element) {
  3240. var doc = element.dom().ownerDocument;
  3241. var body = doc.body;
  3242. var win = doc.defaultView;
  3243. var html = doc.documentElement;
  3244. if (body === element.dom()) {
  3245. return Position(body.offsetLeft, body.offsetTop);
  3246. }
  3247. var scrollTop = firstDefinedOrZero(win.pageYOffset, html.scrollTop);
  3248. var scrollLeft = firstDefinedOrZero(win.pageXOffset, html.scrollLeft);
  3249. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  3250. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  3251. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  3252. };
  3253. var viewport = function (element) {
  3254. var dom = element.dom();
  3255. var doc = dom.ownerDocument;
  3256. var body = doc.body;
  3257. if (body === dom) {
  3258. return Position(body.offsetLeft, body.offsetTop);
  3259. }
  3260. if (!inBody(element)) {
  3261. return Position(0, 0);
  3262. }
  3263. return boxPosition(dom);
  3264. };
  3265. var api$1 = Dimension('width', function (element) {
  3266. return element.dom().offsetWidth;
  3267. });
  3268. var set$4 = function (element, h) {
  3269. api$1.set(element, h);
  3270. };
  3271. var get$7 = function (element) {
  3272. return api$1.get(element);
  3273. };
  3274. var getOuter$2 = function (element) {
  3275. return api$1.getOuter(element);
  3276. };
  3277. var setMax$1 = function (element, value) {
  3278. var inclusions = [
  3279. 'margin-left',
  3280. 'border-left-width',
  3281. 'padding-left',
  3282. 'padding-right',
  3283. 'border-right-width',
  3284. 'margin-right'
  3285. ];
  3286. var absMax = api$1.max(element, value, inclusions);
  3287. set$2(element, 'max-width', absMax + 'px');
  3288. };
  3289. var isSafari = detect$3().browser.isSafari();
  3290. var get$8 = function (_DOC) {
  3291. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  3292. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  3293. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  3294. return Position(x, y);
  3295. };
  3296. var bounds = function (x, y, width, height) {
  3297. return {
  3298. x: constant(x),
  3299. y: constant(y),
  3300. width: constant(width),
  3301. height: constant(height),
  3302. right: constant(x + width),
  3303. bottom: constant(y + height)
  3304. };
  3305. };
  3306. var getBounds = function (_win) {
  3307. var win = _win === undefined ? domGlobals.window : _win;
  3308. var visualViewport = win['visualViewport'];
  3309. if (visualViewport !== undefined) {
  3310. return bounds(visualViewport.pageLeft, visualViewport.pageTop, visualViewport.width, visualViewport.height);
  3311. } else {
  3312. var doc = Element.fromDom(win.document);
  3313. var html = win.document.documentElement;
  3314. var scroll = get$8(doc);
  3315. var width = html.clientWidth;
  3316. var height = html.clientHeight;
  3317. return bounds(scroll.left(), scroll.top(), width, height);
  3318. }
  3319. };
  3320. var walkUp = function (navigation, doc) {
  3321. var frame = navigation.view(doc);
  3322. return frame.fold(constant([]), function (f) {
  3323. var parent = navigation.owner(f);
  3324. var rest = walkUp(navigation, parent);
  3325. return [f].concat(rest);
  3326. });
  3327. };
  3328. var pathTo = function (element, navigation) {
  3329. var d = navigation.owner(element);
  3330. var paths = walkUp(navigation, d);
  3331. return Option.some(paths);
  3332. };
  3333. var view = function (doc) {
  3334. var element = doc.dom() === domGlobals.document ? Option.none() : Option.from(doc.dom().defaultView.frameElement);
  3335. return element.map(Element.fromDom);
  3336. };
  3337. var owner$1 = function (element) {
  3338. return owner(element);
  3339. };
  3340. var Navigation = /*#__PURE__*/Object.freeze({
  3341. view: view,
  3342. owner: owner$1
  3343. });
  3344. var find$3 = function (element) {
  3345. var doc = Element.fromDom(domGlobals.document);
  3346. var scroll = get$8(doc);
  3347. var path = pathTo(element, Navigation);
  3348. return path.fold(curry(absolute, element), function (frames) {
  3349. var offset = viewport(element);
  3350. var r = foldr(frames, function (b, a) {
  3351. var loc = viewport(a);
  3352. return {
  3353. left: b.left + loc.left(),
  3354. top: b.top + loc.top()
  3355. };
  3356. }, {
  3357. left: 0,
  3358. top: 0
  3359. });
  3360. return Position(r.left + offset.left() + scroll.left(), r.top + offset.top() + scroll.top());
  3361. });
  3362. };
  3363. var pointed = Immutable('point', 'width', 'height');
  3364. var rect = Immutable('x', 'y', 'width', 'height');
  3365. var bounds$1 = function (x, y, width, height) {
  3366. return {
  3367. x: constant(x),
  3368. y: constant(y),
  3369. width: constant(width),
  3370. height: constant(height),
  3371. right: constant(x + width),
  3372. bottom: constant(y + height)
  3373. };
  3374. };
  3375. var box = function (element) {
  3376. var xy = absolute(element);
  3377. var w = getOuter$2(element);
  3378. var h = getOuter$1(element);
  3379. return bounds$1(xy.left(), xy.top(), w, h);
  3380. };
  3381. var absolute$1 = function (element) {
  3382. var position = find$3(element);
  3383. var width = getOuter$2(element);
  3384. var height = getOuter$1(element);
  3385. return bounds$1(position.left(), position.top(), width, height);
  3386. };
  3387. var win = function () {
  3388. return getBounds(domGlobals.window);
  3389. };
  3390. var closest$2 = function (scope, predicate, isRoot) {
  3391. return closest(scope, predicate, isRoot).isSome();
  3392. };
  3393. var ancestor$1 = function (scope, selector, isRoot) {
  3394. return ancestor(scope, function (e) {
  3395. return is(e, selector);
  3396. }, isRoot);
  3397. };
  3398. var descendant$1 = function (scope, selector) {
  3399. return one(selector, scope);
  3400. };
  3401. var closest$3 = function (scope, selector, isRoot) {
  3402. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  3403. };
  3404. var find$4 = function (queryElem) {
  3405. var dependent = closest(queryElem, function (elem) {
  3406. if (!isElement(elem)) {
  3407. return false;
  3408. }
  3409. var id = get$2(elem, 'id');
  3410. return id !== undefined && id.indexOf('aria-owns') > -1;
  3411. });
  3412. return dependent.bind(function (dep) {
  3413. var id = get$2(dep, 'id');
  3414. var doc = owner(dep);
  3415. return descendant$1(doc, '[aria-owns="' + id + '"]');
  3416. });
  3417. };
  3418. var manager = function () {
  3419. var ariaId = generate$1('aria-owns');
  3420. var link = function (elem) {
  3421. set$1(elem, 'aria-owns', ariaId);
  3422. };
  3423. var unlink = function (elem) {
  3424. remove$1(elem, 'aria-owns');
  3425. };
  3426. return {
  3427. id: constant(ariaId),
  3428. link: link,
  3429. unlink: unlink
  3430. };
  3431. };
  3432. var isAriaPartOf = function (component, queryElem) {
  3433. return find$4(queryElem).exists(function (owner) {
  3434. return isPartOf(component, owner);
  3435. });
  3436. };
  3437. var isPartOf = function (component, queryElem) {
  3438. return closest$2(queryElem, function (el) {
  3439. return eq(el, component.element());
  3440. }, constant(false)) || isAriaPartOf(component, queryElem);
  3441. };
  3442. var cat = function (arr) {
  3443. var r = [];
  3444. var push = function (x) {
  3445. r.push(x);
  3446. };
  3447. for (var i = 0; i < arr.length; i++) {
  3448. arr[i].each(push);
  3449. }
  3450. return r;
  3451. };
  3452. var sequence = function (arr) {
  3453. var r = [];
  3454. for (var i = 0; i < arr.length; i++) {
  3455. var x = arr[i];
  3456. if (x.isSome()) {
  3457. r.push(x.getOrDie());
  3458. } else {
  3459. return Option.none();
  3460. }
  3461. }
  3462. return Option.some(r);
  3463. };
  3464. var findMap = function (arr, f) {
  3465. for (var i = 0; i < arr.length; i++) {
  3466. var r = f(arr[i], i);
  3467. if (r.isSome()) {
  3468. return r;
  3469. }
  3470. }
  3471. return Option.none();
  3472. };
  3473. var lift2 = function (oa, ob, f) {
  3474. return oa.isSome() && ob.isSome() ? Option.some(f(oa.getOrDie(), ob.getOrDie())) : Option.none();
  3475. };
  3476. var unknown$3 = 'unknown';
  3477. var EventConfiguration;
  3478. (function (EventConfiguration) {
  3479. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3480. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3481. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3482. }(EventConfiguration || (EventConfiguration = {})));
  3483. var eventConfig = Cell({});
  3484. var makeEventLogger = function (eventName, initialTarget) {
  3485. var sequence = [];
  3486. var startTime = new Date().getTime();
  3487. return {
  3488. logEventCut: function (name, target, purpose) {
  3489. sequence.push({
  3490. outcome: 'cut',
  3491. target: target,
  3492. purpose: purpose
  3493. });
  3494. },
  3495. logEventStopped: function (name, target, purpose) {
  3496. sequence.push({
  3497. outcome: 'stopped',
  3498. target: target,
  3499. purpose: purpose
  3500. });
  3501. },
  3502. logNoParent: function (name, target, purpose) {
  3503. sequence.push({
  3504. outcome: 'no-parent',
  3505. target: target,
  3506. purpose: purpose
  3507. });
  3508. },
  3509. logEventNoHandlers: function (name, target) {
  3510. sequence.push({
  3511. outcome: 'no-handlers-left',
  3512. target: target
  3513. });
  3514. },
  3515. logEventResponse: function (name, target, purpose) {
  3516. sequence.push({
  3517. outcome: 'response',
  3518. purpose: purpose,
  3519. target: target
  3520. });
  3521. },
  3522. write: function () {
  3523. var finishTime = new Date().getTime();
  3524. if (contains([
  3525. 'mousemove',
  3526. 'mouseover',
  3527. 'mouseout',
  3528. systemInit()
  3529. ], eventName)) {
  3530. return;
  3531. }
  3532. domGlobals.console.log(eventName, {
  3533. event: eventName,
  3534. time: finishTime - startTime,
  3535. target: initialTarget.dom(),
  3536. sequence: map(sequence, function (s) {
  3537. if (!contains([
  3538. 'cut',
  3539. 'stopped',
  3540. 'response'
  3541. ], s.outcome)) {
  3542. return s.outcome;
  3543. } else {
  3544. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3545. }
  3546. })
  3547. });
  3548. }
  3549. };
  3550. };
  3551. var processEvent = function (eventName, initialTarget, f) {
  3552. var status = readOptFrom$1(eventConfig.get(), eventName).orThunk(function () {
  3553. var patterns = keys(eventConfig.get());
  3554. return findMap(patterns, function (p) {
  3555. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  3556. });
  3557. }).getOr(EventConfiguration.NORMAL);
  3558. switch (status) {
  3559. case EventConfiguration.NORMAL:
  3560. return f(noLogger());
  3561. case EventConfiguration.LOGGING: {
  3562. var logger = makeEventLogger(eventName, initialTarget);
  3563. var output = f(logger);
  3564. logger.write();
  3565. return output;
  3566. }
  3567. case EventConfiguration.STOP:
  3568. return true;
  3569. }
  3570. };
  3571. var path = [
  3572. 'alloy/data/Fields',
  3573. 'alloy/debugging/Debugging'
  3574. ];
  3575. var getTrace = function () {
  3576. var err = new Error();
  3577. if (err.stack !== undefined) {
  3578. var lines = err.stack.split('\n');
  3579. return find(lines, function (line) {
  3580. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3581. return line.indexOf(p) > -1;
  3582. });
  3583. }).getOr(unknown$3);
  3584. } else {
  3585. return unknown$3;
  3586. }
  3587. };
  3588. var ignoreEvent = {
  3589. logEventCut: noop,
  3590. logEventStopped: noop,
  3591. logNoParent: noop,
  3592. logEventNoHandlers: noop,
  3593. logEventResponse: noop,
  3594. write: noop
  3595. };
  3596. var monitorEvent = function (eventName, initialTarget, f) {
  3597. return processEvent(eventName, initialTarget, f);
  3598. };
  3599. var noLogger = constant(ignoreEvent);
  3600. var menuFields = constant([
  3601. strict$1('menu'),
  3602. strict$1('selectedMenu')
  3603. ]);
  3604. var itemFields = constant([
  3605. strict$1('item'),
  3606. strict$1('selectedItem')
  3607. ]);
  3608. var schema = constant(objOf(itemFields().concat(menuFields())));
  3609. var itemSchema = constant(objOf(itemFields()));
  3610. var _initSize = strictObjOf('initSize', [
  3611. strict$1('numColumns'),
  3612. strict$1('numRows')
  3613. ]);
  3614. var itemMarkers = function () {
  3615. return strictOf('markers', itemSchema());
  3616. };
  3617. var tieredMenuMarkers = function () {
  3618. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3619. };
  3620. var markers = function (required) {
  3621. return strictObjOf('markers', map(required, strict$1));
  3622. };
  3623. var onPresenceHandler = function (label, fieldName, presence) {
  3624. var trace = getTrace();
  3625. return field(fieldName, fieldName, presence, valueOf(function (f) {
  3626. return Result.value(function () {
  3627. var args = [];
  3628. for (var _i = 0; _i < arguments.length; _i++) {
  3629. args[_i] = arguments[_i];
  3630. }
  3631. return f.apply(undefined, args);
  3632. });
  3633. }));
  3634. };
  3635. var onHandler = function (fieldName) {
  3636. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  3637. };
  3638. var onKeyboardHandler = function (fieldName) {
  3639. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  3640. };
  3641. var onStrictHandler = function (fieldName) {
  3642. return onPresenceHandler('onHandler', fieldName, strict());
  3643. };
  3644. var onStrictKeyboardHandler = function (fieldName) {
  3645. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  3646. };
  3647. var output = function (name, value) {
  3648. return state$1(name, constant(value));
  3649. };
  3650. var snapshot = function (name) {
  3651. return state$1(name, identity);
  3652. };
  3653. var initSize = constant(_initSize);
  3654. var nu$7 = Immutable('x', 'y', 'bubble', 'direction', 'label');
  3655. var adt$2 = Adt.generate([
  3656. { southeast: [] },
  3657. { southwest: [] },
  3658. { northeast: [] },
  3659. { northwest: [] },
  3660. { south: [] },
  3661. { north: [] },
  3662. { east: [] },
  3663. { west: [] }
  3664. ]);
  3665. var cata = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3666. return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3667. };
  3668. var cataVertical = function (subject, south, middle, north) {
  3669. return subject.fold(south, south, north, north, south, north, middle, middle);
  3670. };
  3671. var cataHorizontal = function (subject, east, middle, west) {
  3672. return subject.fold(east, west, east, west, middle, middle, east, west);
  3673. };
  3674. var southeast = adt$2.southeast;
  3675. var southwest = adt$2.southwest;
  3676. var northeast = adt$2.northeast;
  3677. var northwest = adt$2.northwest;
  3678. var south = adt$2.south;
  3679. var north = adt$2.north;
  3680. var east = adt$2.east;
  3681. var west = adt$2.west;
  3682. var eastX = function (anchor) {
  3683. return anchor.x();
  3684. };
  3685. var middleX = function (anchor, element) {
  3686. return anchor.x() + anchor.width() / 2 - element.width() / 2;
  3687. };
  3688. var westX = function (anchor, element) {
  3689. return anchor.x() + anchor.width() - element.width();
  3690. };
  3691. var northY = function (anchor, element) {
  3692. return anchor.y() - element.height();
  3693. };
  3694. var southY = function (anchor) {
  3695. return anchor.y() + anchor.height();
  3696. };
  3697. var centreY = function (anchor, element) {
  3698. return anchor.y() + anchor.height() / 2 - element.height() / 2;
  3699. };
  3700. var eastEdgeX = function (anchor) {
  3701. return anchor.x() + anchor.width();
  3702. };
  3703. var westEdgeX = function (anchor, element) {
  3704. return anchor.x() - element.width();
  3705. };
  3706. var southeast$1 = function (anchor, element, bubbles) {
  3707. return nu$7(eastX(anchor), southY(anchor), bubbles.southeast(), southeast(), 'layout-se');
  3708. };
  3709. var southwest$1 = function (anchor, element, bubbles) {
  3710. return nu$7(westX(anchor, element), southY(anchor), bubbles.southwest(), southwest(), 'layout-sw');
  3711. };
  3712. var northeast$1 = function (anchor, element, bubbles) {
  3713. return nu$7(eastX(anchor), northY(anchor, element), bubbles.northeast(), northeast(), 'layout-ne');
  3714. };
  3715. var northwest$1 = function (anchor, element, bubbles) {
  3716. return nu$7(westX(anchor, element), northY(anchor, element), bubbles.northwest(), northwest(), 'layout-nw');
  3717. };
  3718. var north$1 = function (anchor, element, bubbles) {
  3719. return nu$7(middleX(anchor, element), northY(anchor, element), bubbles.north(), north(), 'layout-n');
  3720. };
  3721. var south$1 = function (anchor, element, bubbles) {
  3722. return nu$7(middleX(anchor, element), southY(anchor), bubbles.south(), south(), 'layout-s');
  3723. };
  3724. var east$1 = function (anchor, element, bubbles) {
  3725. return nu$7(eastEdgeX(anchor), centreY(anchor, element), bubbles.east(), east(), 'layout-e');
  3726. };
  3727. var west$1 = function (anchor, element, bubbles) {
  3728. return nu$7(westEdgeX(anchor, element), centreY(anchor, element), bubbles.west(), west(), 'layout-w');
  3729. };
  3730. var all$2 = function () {
  3731. return [
  3732. southeast$1,
  3733. southwest$1,
  3734. northeast$1,
  3735. northwest$1,
  3736. south$1,
  3737. north$1,
  3738. east$1,
  3739. west$1
  3740. ];
  3741. };
  3742. var allRtl = function () {
  3743. return [
  3744. southwest$1,
  3745. southeast$1,
  3746. northwest$1,
  3747. northeast$1,
  3748. south$1,
  3749. north$1,
  3750. east$1,
  3751. west$1
  3752. ];
  3753. };
  3754. var belowOrAbove = function () {
  3755. return [
  3756. southeast$1,
  3757. southwest$1,
  3758. northeast$1,
  3759. northwest$1,
  3760. south$1,
  3761. north$1
  3762. ];
  3763. };
  3764. var belowOrAboveRtl = function () {
  3765. return [
  3766. southwest$1,
  3767. southeast$1,
  3768. northwest$1,
  3769. northeast$1,
  3770. south$1,
  3771. north$1
  3772. ];
  3773. };
  3774. var executeEvent = function (bConfig, bState, executor) {
  3775. return runOnExecute(function (component) {
  3776. executor(component, bConfig, bState);
  3777. });
  3778. };
  3779. var loadEvent = function (bConfig, bState, f) {
  3780. return runOnInit(function (component, simulatedEvent) {
  3781. f(component, bConfig, bState);
  3782. });
  3783. };
  3784. var create = function (schema, name, active, apis, extra, state) {
  3785. var configSchema = objOfOnly(schema);
  3786. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  3787. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3788. };
  3789. var createModes = function (modes, name, active, apis, extra, state) {
  3790. var configSchema = modes;
  3791. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  3792. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3793. };
  3794. var wrapApi = function (bName, apiFunction, apiName) {
  3795. var f = function (component) {
  3796. var rest = [];
  3797. for (var _i = 1; _i < arguments.length; _i++) {
  3798. rest[_i - 1] = arguments[_i];
  3799. }
  3800. var args = [component].concat(rest);
  3801. return component.config({ name: constant(bName) }).fold(function () {
  3802. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  3803. }, function (info) {
  3804. var rest = Array.prototype.slice.call(args, 1);
  3805. return apiFunction.apply(undefined, [
  3806. component,
  3807. info.config,
  3808. info.state
  3809. ].concat(rest));
  3810. });
  3811. };
  3812. return markAsBehaviourApi(f, apiName, apiFunction);
  3813. };
  3814. var revokeBehaviour = function (name) {
  3815. return {
  3816. key: name,
  3817. value: undefined
  3818. };
  3819. };
  3820. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  3821. var getConfig = function (info) {
  3822. return hasKey$1(info, name) ? info[name]() : Option.none();
  3823. };
  3824. var wrappedApis = map$1(apis, function (apiF, apiName) {
  3825. return wrapApi(name, apiF, apiName);
  3826. });
  3827. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  3828. return markAsExtraApi(extraF, extraName);
  3829. });
  3830. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  3831. revoke: curry(revokeBehaviour, name),
  3832. config: function (spec) {
  3833. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  3834. return {
  3835. key: name,
  3836. value: {
  3837. config: prepared,
  3838. me: me,
  3839. configAsRaw: cached(function () {
  3840. return asRawOrDie(name + '-config', configSchema, spec);
  3841. }),
  3842. initialConfig: spec,
  3843. state: state
  3844. }
  3845. };
  3846. },
  3847. schema: function () {
  3848. return schemaSchema;
  3849. },
  3850. exhibit: function (info, base) {
  3851. return getConfig(info).bind(function (behaviourInfo) {
  3852. return readOptFrom$1(active, 'exhibit').map(function (exhibitor) {
  3853. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  3854. });
  3855. }).getOr(nu$6({}));
  3856. },
  3857. name: function () {
  3858. return name;
  3859. },
  3860. handlers: function (info) {
  3861. return getConfig(info).map(function (behaviourInfo) {
  3862. var getEvents = readOr$1('events', function (a, b) {
  3863. return {};
  3864. })(active);
  3865. return getEvents(behaviourInfo.config, behaviourInfo.state);
  3866. }).getOr({});
  3867. }
  3868. });
  3869. return me;
  3870. };
  3871. var derive$1 = function (capabilities) {
  3872. return wrapAll$1(capabilities);
  3873. };
  3874. var simpleSchema = objOfOnly([
  3875. strict$1('fields'),
  3876. strict$1('name'),
  3877. defaulted$1('active', {}),
  3878. defaulted$1('apis', {}),
  3879. defaulted$1('state', NoState),
  3880. defaulted$1('extra', {})
  3881. ]);
  3882. var create$1 = function (data) {
  3883. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  3884. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  3885. };
  3886. var modeSchema = objOfOnly([
  3887. strict$1('branchKey'),
  3888. strict$1('branches'),
  3889. strict$1('name'),
  3890. defaulted$1('active', {}),
  3891. defaulted$1('apis', {}),
  3892. defaulted$1('state', NoState),
  3893. defaulted$1('extra', {})
  3894. ]);
  3895. var createModes$1 = function (data) {
  3896. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  3897. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  3898. };
  3899. var revoke = constant(undefined);
  3900. var chooseChannels = function (channels, message) {
  3901. return message.universal() ? channels : filter(channels, function (ch) {
  3902. return contains(message.channels(), ch);
  3903. });
  3904. };
  3905. var events$1 = function (receiveConfig) {
  3906. return derive([run(receive(), function (component, message) {
  3907. var channelMap = receiveConfig.channels;
  3908. var channels = keys(channelMap);
  3909. var targetChannels = chooseChannels(channels, message);
  3910. each(targetChannels, function (ch) {
  3911. var channelInfo = channelMap[ch];
  3912. var channelSchema = channelInfo.schema;
  3913. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, message.data());
  3914. channelInfo.onReceive(component, data);
  3915. });
  3916. })]);
  3917. };
  3918. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  3919. events: events$1
  3920. });
  3921. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  3922. onStrictHandler('onReceive'),
  3923. defaulted$1('schema', anyValue$1())
  3924. ])))];
  3925. var Receiving = create$1({
  3926. fields: ReceivingSchema,
  3927. name: 'receiving',
  3928. active: ActiveReceiving
  3929. });
  3930. var exhibit = function (base, posConfig) {
  3931. return nu$6({
  3932. classes: [],
  3933. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  3934. });
  3935. };
  3936. var ActivePosition = /*#__PURE__*/Object.freeze({
  3937. exhibit: exhibit
  3938. });
  3939. var focus$1 = function (element) {
  3940. element.dom().focus();
  3941. };
  3942. var blur = function (element) {
  3943. element.dom().blur();
  3944. };
  3945. var hasFocus = function (element) {
  3946. var doc = owner(element).dom();
  3947. return element.dom() === doc.activeElement;
  3948. };
  3949. var active = function (_doc) {
  3950. var doc = _doc !== undefined ? _doc.dom() : domGlobals.document;
  3951. return Option.from(doc.activeElement).map(Element.fromDom);
  3952. };
  3953. var search = function (element) {
  3954. return active(owner(element)).filter(function (e) {
  3955. return element.dom().contains(e.dom());
  3956. });
  3957. };
  3958. var preserve = function (f, container) {
  3959. var ownerDoc = owner(container);
  3960. var refocus = active(ownerDoc).bind(function (focused) {
  3961. var hasFocus = function (elem) {
  3962. return eq(focused, elem);
  3963. };
  3964. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  3965. });
  3966. var result = f(container);
  3967. refocus.each(function (oldFocus) {
  3968. active(ownerDoc).filter(function (newFocus) {
  3969. return eq(newFocus, oldFocus);
  3970. }).fold(function () {
  3971. focus$1(oldFocus);
  3972. }, noop);
  3973. });
  3974. return result;
  3975. };
  3976. var allAlignments = [
  3977. 'valignCentre',
  3978. 'alignLeft',
  3979. 'alignRight',
  3980. 'alignCentre',
  3981. 'top',
  3982. 'bottom',
  3983. 'left',
  3984. 'right'
  3985. ];
  3986. var nu$8 = function (width, yoffset, classes) {
  3987. var getClasses = function (prop) {
  3988. return readOptFrom$1(classes, prop).getOr([]);
  3989. };
  3990. var make = function (xDelta, yDelta, alignmentsOn) {
  3991. var alignmentsOff = difference(allAlignments, alignmentsOn);
  3992. return {
  3993. offset: function () {
  3994. return Position(xDelta, yDelta);
  3995. },
  3996. classesOn: function () {
  3997. return bind(alignmentsOn, getClasses);
  3998. },
  3999. classesOff: function () {
  4000. return bind(alignmentsOff, getClasses);
  4001. }
  4002. };
  4003. };
  4004. return {
  4005. southeast: function () {
  4006. return make(-width, yoffset, [
  4007. 'top',
  4008. 'alignLeft'
  4009. ]);
  4010. },
  4011. southwest: function () {
  4012. return make(width, yoffset, [
  4013. 'top',
  4014. 'alignRight'
  4015. ]);
  4016. },
  4017. south: function () {
  4018. return make(-width / 2, yoffset, [
  4019. 'top',
  4020. 'alignCentre'
  4021. ]);
  4022. },
  4023. northeast: function () {
  4024. return make(-width, -yoffset, [
  4025. 'bottom',
  4026. 'alignLeft'
  4027. ]);
  4028. },
  4029. northwest: function () {
  4030. return make(width, -yoffset, [
  4031. 'bottom',
  4032. 'alignRight'
  4033. ]);
  4034. },
  4035. north: function () {
  4036. return make(-width / 2, -yoffset, [
  4037. 'bottom',
  4038. 'alignCentre'
  4039. ]);
  4040. },
  4041. east: function () {
  4042. return make(width, -yoffset / 2, [
  4043. 'valignCentre',
  4044. 'left'
  4045. ]);
  4046. },
  4047. west: function () {
  4048. return make(-width, -yoffset / 2, [
  4049. 'valignCentre',
  4050. 'right'
  4051. ]);
  4052. },
  4053. innerNorthwest: function () {
  4054. return make(-width, yoffset, [
  4055. 'top',
  4056. 'alignRight'
  4057. ]);
  4058. },
  4059. innerNortheast: function () {
  4060. return make(width, yoffset, [
  4061. 'top',
  4062. 'alignLeft'
  4063. ]);
  4064. },
  4065. innerNorth: function () {
  4066. return make(-width / 2, yoffset, [
  4067. 'top',
  4068. 'alignCentre'
  4069. ]);
  4070. },
  4071. innerSouthwest: function () {
  4072. return make(-width, -yoffset, [
  4073. 'bottom',
  4074. 'alignRight'
  4075. ]);
  4076. },
  4077. innerSoutheast: function () {
  4078. return make(width, -yoffset, [
  4079. 'bottom',
  4080. 'alignLeft'
  4081. ]);
  4082. },
  4083. innerSouth: function () {
  4084. return make(-width / 2, -yoffset, [
  4085. 'bottom',
  4086. 'alignCentre'
  4087. ]);
  4088. },
  4089. innerWest: function () {
  4090. return make(width, -yoffset / 2, [
  4091. 'valignCentre',
  4092. 'right'
  4093. ]);
  4094. },
  4095. innerEast: function () {
  4096. return make(-width, -yoffset / 2, [
  4097. 'valignCentre',
  4098. 'left'
  4099. ]);
  4100. }
  4101. };
  4102. };
  4103. var fallback = function () {
  4104. return nu$8(0, 0, {});
  4105. };
  4106. var decision = MixedBag([
  4107. 'x',
  4108. 'y',
  4109. 'width',
  4110. 'height',
  4111. 'maxHeight',
  4112. 'maxWidth',
  4113. 'direction',
  4114. 'classes',
  4115. 'label',
  4116. 'candidateYforTest'
  4117. ], []);
  4118. var css = Immutable('position', 'left', 'top', 'right', 'bottom');
  4119. var adt$3 = Adt.generate([
  4120. { none: [] },
  4121. {
  4122. relative: [
  4123. 'x',
  4124. 'y',
  4125. 'width',
  4126. 'height'
  4127. ]
  4128. },
  4129. {
  4130. fixed: [
  4131. 'x',
  4132. 'y',
  4133. 'width',
  4134. 'height'
  4135. ]
  4136. }
  4137. ]);
  4138. var positionWithDirection = function (posName, decision, x, y, width, height) {
  4139. var decisionX = decision.x() - x;
  4140. var decisionY = decision.y() - y;
  4141. var decisionWidth = decision.width();
  4142. var decisionHeight = decision.height();
  4143. var decisionRight = width - (decisionX + decisionWidth);
  4144. var decisionBottom = height - (decisionY + decisionHeight);
  4145. var left = Option.some(decisionX);
  4146. var top = Option.some(decisionY);
  4147. var right = Option.some(decisionRight);
  4148. var bottom = Option.some(decisionBottom);
  4149. var none = Option.none();
  4150. return cata(decision.direction(), function () {
  4151. return css(posName, left, top, none, none);
  4152. }, function () {
  4153. return css(posName, none, top, right, none);
  4154. }, function () {
  4155. return css(posName, left, none, none, bottom);
  4156. }, function () {
  4157. return css(posName, none, none, right, bottom);
  4158. }, function () {
  4159. return css(posName, left, top, none, none);
  4160. }, function () {
  4161. return css(posName, left, none, none, bottom);
  4162. }, function () {
  4163. return css(posName, left, top, none, none);
  4164. }, function () {
  4165. return css(posName, none, top, right, none);
  4166. });
  4167. };
  4168. var reposition = function (origin, decision) {
  4169. return origin.fold(function () {
  4170. return css('absolute', Option.some(decision.x()), Option.some(decision.y()), Option.none(), Option.none());
  4171. }, function (x, y, width, height) {
  4172. return positionWithDirection('absolute', decision, x, y, width, height);
  4173. }, function (x, y, width, height) {
  4174. return positionWithDirection('fixed', decision, x, y, width, height);
  4175. });
  4176. };
  4177. var toBox = function (origin, element) {
  4178. var rel = curry(find$3, element);
  4179. var position = origin.fold(rel, rel, function () {
  4180. var scroll = get$8();
  4181. return find$3(element).translate(-scroll.left(), -scroll.top());
  4182. });
  4183. var width = getOuter$2(element);
  4184. var height = getOuter$1(element);
  4185. return bounds$1(position.left(), position.top(), width, height);
  4186. };
  4187. var viewport$1 = function (origin, getBounds) {
  4188. return getBounds.fold(function () {
  4189. return origin.fold(win, win, bounds$1);
  4190. }, function (b) {
  4191. return origin.fold(b, b, function () {
  4192. var bounds = b();
  4193. var pos = translate(origin, bounds.x(), bounds.y());
  4194. return bounds$1(pos.left(), pos.top(), bounds.width(), bounds.height());
  4195. });
  4196. });
  4197. };
  4198. var translate = function (origin, x, y) {
  4199. var pos = Position(x, y);
  4200. var removeScroll = function () {
  4201. var outerScroll = get$8();
  4202. return pos.translate(-outerScroll.left(), -outerScroll.top());
  4203. };
  4204. return origin.fold(constant(pos), constant(pos), removeScroll);
  4205. };
  4206. var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4207. return subject.fold(onNone, onRelative, onFixed);
  4208. };
  4209. var relative = adt$3.relative;
  4210. var fixed = adt$3.fixed;
  4211. var nu$9 = function (x) {
  4212. return x;
  4213. };
  4214. var onDirection = function (isLtr, isRtl) {
  4215. return function (element) {
  4216. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4217. };
  4218. };
  4219. var getDirection = function (element) {
  4220. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4221. };
  4222. var schema$1 = function () {
  4223. return optionObjOf('layouts', [
  4224. strict$1('onLtr'),
  4225. strict$1('onRtl')
  4226. ]);
  4227. };
  4228. var get$9 = function (elem, info, defaultLtr, defaultRtl) {
  4229. var ltr = info.layouts.map(function (ls) {
  4230. return ls.onLtr(elem);
  4231. }).getOr(defaultLtr);
  4232. var rtl = info.layouts.map(function (ls) {
  4233. return ls.onRtl(elem);
  4234. }).getOr(defaultRtl);
  4235. var f = onDirection(ltr, rtl);
  4236. return f(elem);
  4237. };
  4238. var placement = function (component, anchorInfo, origin) {
  4239. var hotspot = anchorInfo.hotspot;
  4240. var anchorBox = toBox(origin, hotspot.element());
  4241. var layouts = get$9(component.element(), anchorInfo, belowOrAbove(), belowOrAboveRtl());
  4242. return Option.some(nu$9({
  4243. anchorBox: anchorBox,
  4244. bubble: anchorInfo.bubble.getOr(fallback()),
  4245. overrides: anchorInfo.overrides,
  4246. layouts: layouts,
  4247. placer: Option.none()
  4248. }));
  4249. };
  4250. var HotspotAnchor = [
  4251. strict$1('hotspot'),
  4252. option('bubble'),
  4253. defaulted$1('overrides', {}),
  4254. schema$1(),
  4255. output('placement', placement)
  4256. ];
  4257. var placement$1 = function (component, anchorInfo, origin) {
  4258. var pos = translate(origin, anchorInfo.x, anchorInfo.y);
  4259. var anchorBox = bounds$1(pos.left(), pos.top(), anchorInfo.width, anchorInfo.height);
  4260. var layouts = get$9(component.element(), anchorInfo, all$2(), allRtl());
  4261. return Option.some(nu$9({
  4262. anchorBox: anchorBox,
  4263. bubble: anchorInfo.bubble,
  4264. overrides: anchorInfo.overrides,
  4265. layouts: layouts,
  4266. placer: Option.none()
  4267. }));
  4268. };
  4269. var MakeshiftAnchor = [
  4270. strict$1('x'),
  4271. strict$1('y'),
  4272. defaulted$1('height', 0),
  4273. defaulted$1('width', 0),
  4274. defaulted$1('bubble', fallback()),
  4275. defaulted$1('overrides', {}),
  4276. schema$1(),
  4277. output('placement', placement$1)
  4278. ];
  4279. var zeroWidth = function () {
  4280. return '\uFEFF';
  4281. };
  4282. var create$2 = Immutable('start', 'soffset', 'finish', 'foffset');
  4283. var SimRange = { create: create$2 };
  4284. var adt$4 = Adt.generate([
  4285. { before: ['element'] },
  4286. {
  4287. on: [
  4288. 'element',
  4289. 'offset'
  4290. ]
  4291. },
  4292. { after: ['element'] }
  4293. ]);
  4294. var cata$2 = function (subject, onBefore, onOn, onAfter) {
  4295. return subject.fold(onBefore, onOn, onAfter);
  4296. };
  4297. var getStart = function (situ) {
  4298. return situ.fold(identity, identity, identity);
  4299. };
  4300. var before$2 = adt$4.before;
  4301. var on = adt$4.on;
  4302. var after$1 = adt$4.after;
  4303. var Situ = {
  4304. before: before$2,
  4305. on: on,
  4306. after: after$1,
  4307. cata: cata$2,
  4308. getStart: getStart
  4309. };
  4310. var adt$5 = Adt.generate([
  4311. { domRange: ['rng'] },
  4312. {
  4313. relative: [
  4314. 'startSitu',
  4315. 'finishSitu'
  4316. ]
  4317. },
  4318. {
  4319. exact: [
  4320. 'start',
  4321. 'soffset',
  4322. 'finish',
  4323. 'foffset'
  4324. ]
  4325. }
  4326. ]);
  4327. var exactFromRange = function (simRange) {
  4328. return adt$5.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  4329. };
  4330. var getStart$1 = function (selection) {
  4331. return selection.match({
  4332. domRange: function (rng) {
  4333. return Element.fromDom(rng.startContainer);
  4334. },
  4335. relative: function (startSitu, finishSitu) {
  4336. return Situ.getStart(startSitu);
  4337. },
  4338. exact: function (start, soffset, finish, foffset) {
  4339. return start;
  4340. }
  4341. });
  4342. };
  4343. var domRange = adt$5.domRange;
  4344. var relative$1 = adt$5.relative;
  4345. var exact = adt$5.exact;
  4346. var getWin = function (selection) {
  4347. var start = getStart$1(selection);
  4348. return defaultView(start);
  4349. };
  4350. var range$1 = SimRange.create;
  4351. var Selection = {
  4352. domRange: domRange,
  4353. relative: relative$1,
  4354. exact: exact,
  4355. exactFromRange: exactFromRange,
  4356. getWin: getWin,
  4357. range: range$1
  4358. };
  4359. var setStart = function (rng, situ) {
  4360. situ.fold(function (e) {
  4361. rng.setStartBefore(e.dom());
  4362. }, function (e, o) {
  4363. rng.setStart(e.dom(), o);
  4364. }, function (e) {
  4365. rng.setStartAfter(e.dom());
  4366. });
  4367. };
  4368. var setFinish = function (rng, situ) {
  4369. situ.fold(function (e) {
  4370. rng.setEndBefore(e.dom());
  4371. }, function (e, o) {
  4372. rng.setEnd(e.dom(), o);
  4373. }, function (e) {
  4374. rng.setEndAfter(e.dom());
  4375. });
  4376. };
  4377. var relativeToNative = function (win, startSitu, finishSitu) {
  4378. var range = win.document.createRange();
  4379. setStart(range, startSitu);
  4380. setFinish(range, finishSitu);
  4381. return range;
  4382. };
  4383. var exactToNative = function (win, start, soffset, finish, foffset) {
  4384. var rng = win.document.createRange();
  4385. rng.setStart(start.dom(), soffset);
  4386. rng.setEnd(finish.dom(), foffset);
  4387. return rng;
  4388. };
  4389. var toRect = function (rect) {
  4390. return {
  4391. left: constant(rect.left),
  4392. top: constant(rect.top),
  4393. right: constant(rect.right),
  4394. bottom: constant(rect.bottom),
  4395. width: constant(rect.width),
  4396. height: constant(rect.height)
  4397. };
  4398. };
  4399. var getFirstRect = function (rng) {
  4400. var rects = rng.getClientRects();
  4401. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  4402. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  4403. };
  4404. var adt$6 = Adt.generate([
  4405. {
  4406. ltr: [
  4407. 'start',
  4408. 'soffset',
  4409. 'finish',
  4410. 'foffset'
  4411. ]
  4412. },
  4413. {
  4414. rtl: [
  4415. 'start',
  4416. 'soffset',
  4417. 'finish',
  4418. 'foffset'
  4419. ]
  4420. }
  4421. ]);
  4422. var fromRange = function (win, type, range) {
  4423. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  4424. };
  4425. var getRanges = function (win, selection) {
  4426. return selection.match({
  4427. domRange: function (rng) {
  4428. return {
  4429. ltr: constant(rng),
  4430. rtl: Option.none
  4431. };
  4432. },
  4433. relative: function (startSitu, finishSitu) {
  4434. return {
  4435. ltr: cached(function () {
  4436. return relativeToNative(win, startSitu, finishSitu);
  4437. }),
  4438. rtl: cached(function () {
  4439. return Option.some(relativeToNative(win, finishSitu, startSitu));
  4440. })
  4441. };
  4442. },
  4443. exact: function (start, soffset, finish, foffset) {
  4444. return {
  4445. ltr: cached(function () {
  4446. return exactToNative(win, start, soffset, finish, foffset);
  4447. }),
  4448. rtl: cached(function () {
  4449. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  4450. })
  4451. };
  4452. }
  4453. });
  4454. };
  4455. var doDiagnose = function (win, ranges) {
  4456. var rng = ranges.ltr();
  4457. if (rng.collapsed) {
  4458. var reversed = ranges.rtl().filter(function (rev) {
  4459. return rev.collapsed === false;
  4460. });
  4461. return reversed.map(function (rev) {
  4462. return adt$6.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  4463. }).getOrThunk(function () {
  4464. return fromRange(win, adt$6.ltr, rng);
  4465. });
  4466. } else {
  4467. return fromRange(win, adt$6.ltr, rng);
  4468. }
  4469. };
  4470. var diagnose = function (win, selection) {
  4471. var ranges = getRanges(win, selection);
  4472. return doDiagnose(win, ranges);
  4473. };
  4474. var asLtrRange = function (win, selection) {
  4475. var diagnosis = diagnose(win, selection);
  4476. return diagnosis.match({
  4477. ltr: function (start, soffset, finish, foffset) {
  4478. var rng = win.document.createRange();
  4479. rng.setStart(start.dom(), soffset);
  4480. rng.setEnd(finish.dom(), foffset);
  4481. return rng;
  4482. },
  4483. rtl: function (start, soffset, finish, foffset) {
  4484. var rng = win.document.createRange();
  4485. rng.setStart(finish.dom(), foffset);
  4486. rng.setEnd(start.dom(), soffset);
  4487. return rng;
  4488. }
  4489. });
  4490. };
  4491. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  4492. if (length === 0) {
  4493. return 0;
  4494. } else if (x === maxX) {
  4495. return length - 1;
  4496. }
  4497. var xDelta = maxX;
  4498. for (var i = 1; i < length; i++) {
  4499. var rect = rectForOffset(i);
  4500. var curDeltaX = Math.abs(x - rect.left);
  4501. if (y <= rect.bottom) {
  4502. if (y < rect.top || curDeltaX > xDelta) {
  4503. return i - 1;
  4504. } else {
  4505. xDelta = curDeltaX;
  4506. }
  4507. }
  4508. }
  4509. return 0;
  4510. };
  4511. var inRect = function (rect, x, y) {
  4512. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  4513. };
  4514. function NodeValue (is, name) {
  4515. var get = function (element) {
  4516. if (!is(element)) {
  4517. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  4518. }
  4519. return getOption(element).getOr('');
  4520. };
  4521. var getOption = function (element) {
  4522. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  4523. };
  4524. var set = function (element, value) {
  4525. if (!is(element)) {
  4526. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  4527. }
  4528. element.dom().nodeValue = value;
  4529. };
  4530. return {
  4531. get: get,
  4532. getOption: getOption,
  4533. set: set
  4534. };
  4535. }
  4536. var api$2 = NodeValue(isText, 'text');
  4537. var get$a = function (element) {
  4538. return api$2.get(element);
  4539. };
  4540. var getOption = function (element) {
  4541. return api$2.getOption(element);
  4542. };
  4543. var locateOffset = function (doc, textnode, x, y, rect) {
  4544. var rangeForOffset = function (o) {
  4545. var r = doc.dom().createRange();
  4546. r.setStart(textnode.dom(), o);
  4547. r.collapse(true);
  4548. return r;
  4549. };
  4550. var rectForOffset = function (o) {
  4551. var r = rangeForOffset(o);
  4552. return r.getBoundingClientRect();
  4553. };
  4554. var length = get$a(textnode).length;
  4555. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  4556. return rangeForOffset(offset);
  4557. };
  4558. var locate = function (doc, node, x, y) {
  4559. var r = doc.dom().createRange();
  4560. r.selectNode(node.dom());
  4561. var rects = r.getClientRects();
  4562. var foundRect = findMap(rects, function (rect) {
  4563. return inRect(rect, x, y) ? Option.some(rect) : Option.none();
  4564. });
  4565. return foundRect.map(function (rect) {
  4566. return locateOffset(doc, node, x, y, rect);
  4567. });
  4568. };
  4569. var searchInChildren = function (doc, node, x, y) {
  4570. var r = doc.dom().createRange();
  4571. var nodes = children(node);
  4572. return findMap(nodes, function (n) {
  4573. r.selectNode(n.dom());
  4574. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none();
  4575. });
  4576. };
  4577. var locateNode = function (doc, node, x, y) {
  4578. return isText(node) ? locate(doc, node, x, y) : searchInChildren(doc, node, x, y);
  4579. };
  4580. var locate$1 = function (doc, node, x, y) {
  4581. var r = doc.dom().createRange();
  4582. r.selectNode(node.dom());
  4583. var rect = r.getBoundingClientRect();
  4584. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  4585. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  4586. return locateNode(doc, node, boundedX, boundedY);
  4587. };
  4588. var getEnd = function (element) {
  4589. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  4590. return children(element).length;
  4591. }, function (v) {
  4592. return v.length;
  4593. });
  4594. };
  4595. var NBSP = '\xA0';
  4596. var isTextNodeWithCursorPosition = function (el) {
  4597. return getOption(el).filter(function (text) {
  4598. return text.trim().length !== 0 || text.indexOf(NBSP) > -1;
  4599. }).isSome();
  4600. };
  4601. var elementsWithCursorPosition = [
  4602. 'img',
  4603. 'br'
  4604. ];
  4605. var isCursorPosition = function (elem) {
  4606. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  4607. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  4608. };
  4609. var first = function (element) {
  4610. return descendant(element, isCursorPosition);
  4611. };
  4612. var last$1 = function (element) {
  4613. return descendantRtl(element, isCursorPosition);
  4614. };
  4615. var descendantRtl = function (scope, predicate) {
  4616. var descend = function (element) {
  4617. var children$1 = children(element);
  4618. for (var i = children$1.length - 1; i >= 0; i--) {
  4619. var child = children$1[i];
  4620. if (predicate(child)) {
  4621. return Option.some(child);
  4622. }
  4623. var res = descend(child);
  4624. if (res.isSome()) {
  4625. return res;
  4626. }
  4627. }
  4628. return Option.none();
  4629. };
  4630. return descend(scope);
  4631. };
  4632. var COLLAPSE_TO_LEFT = true;
  4633. var COLLAPSE_TO_RIGHT = false;
  4634. var getCollapseDirection = function (rect, x) {
  4635. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  4636. };
  4637. var createCollapsedNode = function (doc, target, collapseDirection) {
  4638. var r = doc.dom().createRange();
  4639. r.selectNode(target.dom());
  4640. r.collapse(collapseDirection);
  4641. return r;
  4642. };
  4643. var locateInElement = function (doc, node, x) {
  4644. var cursorRange = doc.dom().createRange();
  4645. cursorRange.selectNode(node.dom());
  4646. var rect = cursorRange.getBoundingClientRect();
  4647. var collapseDirection = getCollapseDirection(rect, x);
  4648. var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
  4649. return f(node).map(function (target) {
  4650. return createCollapsedNode(doc, target, collapseDirection);
  4651. });
  4652. };
  4653. var locateInEmpty = function (doc, node, x) {
  4654. var rect = node.dom().getBoundingClientRect();
  4655. var collapseDirection = getCollapseDirection(rect, x);
  4656. return Option.some(createCollapsedNode(doc, node, collapseDirection));
  4657. };
  4658. var search$1 = function (doc, node, x) {
  4659. var f = children(node).length === 0 ? locateInEmpty : locateInElement;
  4660. return f(doc, node, x);
  4661. };
  4662. var caretPositionFromPoint = function (doc, x, y) {
  4663. return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) {
  4664. if (pos.offsetNode === null) {
  4665. return Option.none();
  4666. }
  4667. var r = doc.dom().createRange();
  4668. r.setStart(pos.offsetNode, pos.offset);
  4669. r.collapse();
  4670. return Option.some(r);
  4671. });
  4672. };
  4673. var caretRangeFromPoint = function (doc, x, y) {
  4674. return Option.from(doc.dom().caretRangeFromPoint(x, y));
  4675. };
  4676. var searchTextNodes = function (doc, node, x, y) {
  4677. var r = doc.dom().createRange();
  4678. r.selectNode(node.dom());
  4679. var rect = r.getBoundingClientRect();
  4680. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  4681. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  4682. return locate$1(doc, node, boundedX, boundedY);
  4683. };
  4684. var searchFromPoint = function (doc, x, y) {
  4685. return Element.fromPoint(doc, x, y).bind(function (elem) {
  4686. var fallback = function () {
  4687. return search$1(doc, elem, x);
  4688. };
  4689. return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  4690. });
  4691. };
  4692. var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
  4693. var descendants = function (scope, selector) {
  4694. return all(selector, scope);
  4695. };
  4696. var makeRange = function (start, soffset, finish, foffset) {
  4697. var doc = owner(start);
  4698. var rng = doc.dom().createRange();
  4699. rng.setStart(start.dom(), soffset);
  4700. rng.setEnd(finish.dom(), foffset);
  4701. return rng;
  4702. };
  4703. var after$2 = function (start, soffset, finish, foffset) {
  4704. var r = makeRange(start, soffset, finish, foffset);
  4705. var same = eq(start, finish) && soffset === foffset;
  4706. return r.collapsed && !same;
  4707. };
  4708. var readRange = function (selection) {
  4709. if (selection.rangeCount > 0) {
  4710. var firstRng = selection.getRangeAt(0);
  4711. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  4712. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  4713. } else {
  4714. return Option.none();
  4715. }
  4716. };
  4717. var doGetExact = function (selection) {
  4718. var anchor = Element.fromDom(selection.anchorNode);
  4719. var focus = Element.fromDom(selection.focusNode);
  4720. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  4721. };
  4722. var getExact = function (win) {
  4723. return Option.from(win.getSelection()).filter(function (sel) {
  4724. return sel.rangeCount > 0;
  4725. }).bind(doGetExact);
  4726. };
  4727. var getFirstRect$1 = function (win, selection) {
  4728. var rng = asLtrRange(win, selection);
  4729. return getFirstRect(rng);
  4730. };
  4731. var point = Immutable('element', 'offset');
  4732. var descendOnce = function (element, offset) {
  4733. var children$1 = children(element);
  4734. if (children$1.length === 0) {
  4735. return point(element, offset);
  4736. } else if (offset < children$1.length) {
  4737. return point(children$1[offset], 0);
  4738. } else {
  4739. var last = children$1[children$1.length - 1];
  4740. var len = isText(last) ? get$a(last).length : children(last).length;
  4741. return point(last, len);
  4742. }
  4743. };
  4744. var adt$7 = Adt.generate([
  4745. { screen: ['point'] },
  4746. {
  4747. absolute: [
  4748. 'point',
  4749. 'scrollLeft',
  4750. 'scrollTop'
  4751. ]
  4752. }
  4753. ]);
  4754. var toFixed = function (pos) {
  4755. return pos.fold(function (point) {
  4756. return point;
  4757. }, function (point, scrollLeft, scrollTop) {
  4758. return point.translate(-scrollLeft, -scrollTop);
  4759. });
  4760. };
  4761. var toAbsolute = function (pos) {
  4762. return pos.fold(function (point) {
  4763. return point;
  4764. }, function (point, scrollLeft, scrollTop) {
  4765. return point;
  4766. });
  4767. };
  4768. var sum = function (points) {
  4769. return foldl(points, function (b, a) {
  4770. return b.translate(a.left(), a.top());
  4771. }, Position(0, 0));
  4772. };
  4773. var sumAsFixed = function (positions) {
  4774. var points = map(positions, toFixed);
  4775. return sum(points);
  4776. };
  4777. var sumAsAbsolute = function (positions) {
  4778. var points = map(positions, toAbsolute);
  4779. return sum(points);
  4780. };
  4781. var screen = adt$7.screen;
  4782. var absolute$2 = adt$7.absolute;
  4783. var getOffset = function (component, origin, anchorInfo) {
  4784. var win = defaultView(anchorInfo.root).dom();
  4785. var hasSameOwner = function (frame) {
  4786. var frameOwner = owner(frame);
  4787. var compOwner = owner(component.element());
  4788. return eq(frameOwner, compOwner);
  4789. };
  4790. return Option.from(win.frameElement).map(Element.fromDom).filter(hasSameOwner).map(absolute);
  4791. };
  4792. var getRootPoint = function (component, origin, anchorInfo) {
  4793. var doc = owner(component.element());
  4794. var outerScroll = get$8(doc);
  4795. var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  4796. return absolute$2(offset, outerScroll.left(), outerScroll.top());
  4797. };
  4798. var capRect = function (left, top, width, height) {
  4799. var newLeft = left, newTop = top, newWidth = width, newHeight = height;
  4800. if (left < 0) {
  4801. newLeft = 0;
  4802. newWidth = width + left;
  4803. }
  4804. if (top < 0) {
  4805. newTop = 0;
  4806. newHeight = height + top;
  4807. }
  4808. var point = screen(Position(newLeft, newTop));
  4809. return Option.some(pointed(point, newWidth, newHeight));
  4810. };
  4811. var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  4812. return optBox.map(function (box) {
  4813. var points = [
  4814. rootPoint,
  4815. box.point()
  4816. ];
  4817. var topLeft = cata$1(origin, function () {
  4818. return sumAsAbsolute(points);
  4819. }, function () {
  4820. return sumAsAbsolute(points);
  4821. }, function () {
  4822. return sumAsFixed(points);
  4823. });
  4824. var anchorBox = rect(topLeft.left(), topLeft.top(), box.width(), box.height());
  4825. var layoutsLtr = function () {
  4826. return anchorInfo.showAbove ? [
  4827. northeast$1,
  4828. northwest$1,
  4829. southeast$1,
  4830. southwest$1,
  4831. north$1,
  4832. south$1
  4833. ] : [
  4834. southeast$1,
  4835. southwest$1,
  4836. northeast$1,
  4837. northwest$1,
  4838. south$1,
  4839. south$1
  4840. ];
  4841. };
  4842. var layoutsRtl = function () {
  4843. return anchorInfo.showAbove ? [
  4844. northwest$1,
  4845. northeast$1,
  4846. southwest$1,
  4847. southeast$1,
  4848. north$1,
  4849. south$1
  4850. ] : [
  4851. southwest$1,
  4852. southeast$1,
  4853. northwest$1,
  4854. northeast$1,
  4855. south$1,
  4856. north$1
  4857. ];
  4858. };
  4859. var layouts = get$9(elem, anchorInfo, layoutsLtr(), layoutsRtl());
  4860. return nu$9({
  4861. anchorBox: anchorBox,
  4862. bubble: anchorInfo.bubble.getOr(fallback()),
  4863. overrides: anchorInfo.overrides,
  4864. layouts: layouts,
  4865. placer: Option.none()
  4866. });
  4867. });
  4868. };
  4869. var ContentAnchorCommon = {
  4870. capRect: capRect,
  4871. calcNewAnchor: calcNewAnchor
  4872. };
  4873. var point$1 = Immutable('element', 'offset');
  4874. var descendOnce$1 = function (element, offset) {
  4875. return isText(element) ? point$1(element, offset) : descendOnce(element, offset);
  4876. };
  4877. var getAnchorSelection = function (win, anchorInfo) {
  4878. var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  4879. return function () {
  4880. return getExact(win);
  4881. };
  4882. });
  4883. return getSelection().map(function (sel) {
  4884. var modStart = descendOnce$1(sel.start(), sel.soffset());
  4885. var modFinish = descendOnce$1(sel.finish(), sel.foffset());
  4886. return Selection.range(modStart.element(), modStart.offset(), modFinish.element(), modFinish.offset());
  4887. });
  4888. };
  4889. var placement$2 = function (component, anchorInfo, origin) {
  4890. var win = defaultView(anchorInfo.root).dom();
  4891. var rootPoint = getRootPoint(component, origin, anchorInfo);
  4892. var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  4893. var optRect = getFirstRect$1(win, Selection.exactFromRange(sel)).orThunk(function () {
  4894. var x = Element.fromText(zeroWidth());
  4895. before(sel.start(), x);
  4896. return getFirstRect$1(win, Selection.exact(x, 0, x, 1)).map(function (rect) {
  4897. remove(x);
  4898. return rect;
  4899. });
  4900. });
  4901. return optRect.bind(function (rawRect) {
  4902. return ContentAnchorCommon.capRect(rawRect.left(), rawRect.top(), rawRect.width(), rawRect.height());
  4903. });
  4904. });
  4905. var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  4906. return isElement(sel.start()) ? Option.some(sel.start()) : parent(sel.start());
  4907. });
  4908. var elem = targetElement.getOr(component.element());
  4909. return ContentAnchorCommon.calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  4910. };
  4911. var SelectionAnchor = [
  4912. option('getSelection'),
  4913. strict$1('root'),
  4914. option('bubble'),
  4915. schema$1(),
  4916. defaulted$1('overrides', {}),
  4917. defaulted$1('showAbove', false),
  4918. output('placement', placement$2)
  4919. ];
  4920. var placement$3 = function (component, anchorInfo, origin) {
  4921. var rootPoint = getRootPoint(component, origin, anchorInfo);
  4922. return anchorInfo.node.bind(function (target) {
  4923. var rect = target.dom().getBoundingClientRect();
  4924. var nodeBox = ContentAnchorCommon.capRect(rect.left, rect.top, rect.width, rect.height);
  4925. var elem = anchorInfo.node.getOr(component.element());
  4926. return ContentAnchorCommon.calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  4927. });
  4928. };
  4929. var NodeAnchor = [
  4930. strict$1('node'),
  4931. strict$1('root'),
  4932. option('bubble'),
  4933. schema$1(),
  4934. defaulted$1('overrides', {}),
  4935. defaulted$1('showAbove', false),
  4936. output('placement', placement$3)
  4937. ];
  4938. var eastX$1 = function (anchor) {
  4939. return anchor.x() + anchor.width();
  4940. };
  4941. var westX$1 = function (anchor, element) {
  4942. return anchor.x() - element.width();
  4943. };
  4944. var northY$1 = function (anchor, element) {
  4945. return anchor.y() - element.height() + anchor.height();
  4946. };
  4947. var southY$1 = function (anchor) {
  4948. return anchor.y();
  4949. };
  4950. var southeast$2 = function (anchor, element, bubbles) {
  4951. return nu$7(eastX$1(anchor), southY$1(anchor), bubbles.southeast(), southeast(), 'link-layout-se');
  4952. };
  4953. var southwest$2 = function (anchor, element, bubbles) {
  4954. return nu$7(westX$1(anchor, element), southY$1(anchor), bubbles.southwest(), southwest(), 'link-layout-sw');
  4955. };
  4956. var northeast$2 = function (anchor, element, bubbles) {
  4957. return nu$7(eastX$1(anchor), northY$1(anchor, element), bubbles.northeast(), northeast(), 'link-layout-ne');
  4958. };
  4959. var northwest$2 = function (anchor, element, bubbles) {
  4960. return nu$7(westX$1(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest(), 'link-layout-nw');
  4961. };
  4962. var all$3 = function () {
  4963. return [
  4964. southeast$2,
  4965. southwest$2,
  4966. northeast$2,
  4967. northwest$2
  4968. ];
  4969. };
  4970. var allRtl$1 = function () {
  4971. return [
  4972. southwest$2,
  4973. southeast$2,
  4974. northwest$2,
  4975. northeast$2
  4976. ];
  4977. };
  4978. var placement$4 = function (component, submenuInfo, origin) {
  4979. var anchorBox = toBox(origin, submenuInfo.item.element());
  4980. var layouts = get$9(component.element(), submenuInfo, all$3(), allRtl$1());
  4981. return Option.some(nu$9({
  4982. anchorBox: anchorBox,
  4983. bubble: fallback(),
  4984. overrides: submenuInfo.overrides,
  4985. layouts: layouts,
  4986. placer: Option.none()
  4987. }));
  4988. };
  4989. var SubmenuAnchor = [
  4990. strict$1('item'),
  4991. schema$1(),
  4992. defaulted$1('overrides', {}),
  4993. output('placement', placement$4)
  4994. ];
  4995. var AnchorSchema = choose$1('anchor', {
  4996. selection: SelectionAnchor,
  4997. node: NodeAnchor,
  4998. hotspot: HotspotAnchor,
  4999. submenu: SubmenuAnchor,
  5000. makeshift: MakeshiftAnchor
  5001. });
  5002. var anchor = Immutable('anchorBox', 'origin');
  5003. var box$1 = function (anchorBox, origin) {
  5004. return anchor(anchorBox, origin);
  5005. };
  5006. var cycleBy = function (value, delta, min, max) {
  5007. var r = value + delta;
  5008. if (r > max) {
  5009. return min;
  5010. } else {
  5011. return r < min ? max : r;
  5012. }
  5013. };
  5014. var cap = function (value, min, max) {
  5015. if (value <= min) {
  5016. return min;
  5017. } else {
  5018. return value >= max ? max : value;
  5019. }
  5020. };
  5021. var adt$8 = Adt.generate([
  5022. { fit: ['reposition'] },
  5023. {
  5024. nofit: [
  5025. 'reposition',
  5026. 'deltaW',
  5027. 'deltaH'
  5028. ]
  5029. }
  5030. ]);
  5031. var calcReposition = function (newX, newY, width, height, bounds) {
  5032. var boundsX = bounds.x();
  5033. var boundsY = bounds.y();
  5034. var boundsWidth = bounds.width();
  5035. var boundsHeight = bounds.height();
  5036. var xInBounds = newX >= boundsX;
  5037. var yInBounds = newY >= boundsY;
  5038. var originInBounds = xInBounds && yInBounds;
  5039. var xFit = newX + width <= boundsX + boundsWidth;
  5040. var yFit = newY + height <= boundsY + boundsHeight;
  5041. var sizeInBounds = xFit && yFit;
  5042. var deltaW = Math.abs(Math.min(width, xInBounds ? boundsX + boundsWidth - newX : boundsX - (newX + width)));
  5043. var deltaH = Math.abs(Math.min(height, yInBounds ? boundsY + boundsHeight - newY : boundsY - (newY + height)));
  5044. var limitX = cap(newX, bounds.x(), bounds.right());
  5045. var limitY = cap(newY, bounds.y(), bounds.bottom());
  5046. return {
  5047. originInBounds: originInBounds,
  5048. sizeInBounds: sizeInBounds,
  5049. limitX: limitX,
  5050. limitY: limitY,
  5051. deltaW: deltaW,
  5052. deltaH: deltaH
  5053. };
  5054. };
  5055. var attempt = function (candidate, width, height, bounds) {
  5056. var candidateX = candidate.x();
  5057. var candidateY = candidate.y();
  5058. var bubbleLeft = candidate.bubble().offset().left();
  5059. var bubbleTop = candidate.bubble().offset().top();
  5060. var boundsY = bounds.y();
  5061. var boundsBottom = bounds.bottom();
  5062. var boundsX = bounds.x();
  5063. var boundsRight = bounds.right();
  5064. var newX = candidateX + bubbleLeft;
  5065. var newY = candidateY + bubbleTop;
  5066. 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;
  5067. var upAvailable = constant(limitY + deltaH - boundsY);
  5068. var downAvailable = constant(boundsBottom - limitY);
  5069. var maxHeight = cataVertical(candidate.direction(), downAvailable, downAvailable, upAvailable);
  5070. var westAvailable = constant(limitX + deltaW - boundsX);
  5071. var eastAvailable = constant(boundsRight - limitX);
  5072. var maxWidth = cataHorizontal(candidate.direction(), eastAvailable, eastAvailable, westAvailable);
  5073. var reposition = decision({
  5074. x: limitX,
  5075. y: limitY,
  5076. width: deltaW,
  5077. height: deltaH,
  5078. maxHeight: maxHeight,
  5079. maxWidth: maxWidth,
  5080. direction: candidate.direction(),
  5081. classes: {
  5082. on: candidate.bubble().classesOn(),
  5083. off: candidate.bubble().classesOff()
  5084. },
  5085. label: candidate.label(),
  5086. candidateYforTest: newY
  5087. });
  5088. return originInBounds && sizeInBounds ? adt$8.fit(reposition) : adt$8.nofit(reposition, deltaW, deltaH);
  5089. };
  5090. var attempts = function (candidates, anchorBox, elementBox, bubbles, bounds) {
  5091. var panelWidth = elementBox.width();
  5092. var panelHeight = elementBox.height();
  5093. var attemptBestFit = function (layout, reposition, deltaW, deltaH) {
  5094. var next = layout(anchorBox, elementBox, bubbles);
  5095. var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  5096. return attemptLayout.fold(adt$8.fit, function (newReposition, newDeltaW, newDeltaH) {
  5097. var improved = newDeltaH > deltaH || newDeltaW > deltaW;
  5098. return improved ? adt$8.nofit(newReposition, newDeltaW, newDeltaH) : adt$8.nofit(reposition, deltaW, deltaH);
  5099. });
  5100. };
  5101. var abc = foldl(candidates, function (b, a) {
  5102. var bestNext = curry(attemptBestFit, a);
  5103. return b.fold(adt$8.fit, bestNext);
  5104. }, adt$8.nofit(decision({
  5105. x: anchorBox.x(),
  5106. y: anchorBox.y(),
  5107. width: elementBox.width(),
  5108. height: elementBox.height(),
  5109. maxHeight: elementBox.height(),
  5110. maxWidth: elementBox.width(),
  5111. direction: southeast(),
  5112. classes: {
  5113. on: [],
  5114. off: []
  5115. },
  5116. label: 'none',
  5117. candidateYforTest: anchorBox.y()
  5118. }), -1, -1));
  5119. return abc.fold(identity, identity);
  5120. };
  5121. var elementSize = function (p) {
  5122. return {
  5123. width: constant(getOuter$2(p)),
  5124. height: constant(getOuter$1(p))
  5125. };
  5126. };
  5127. var layout = function (anchorBox, element, bubbles, options) {
  5128. remove$6(element, 'max-height');
  5129. remove$6(element, 'max-width');
  5130. var elementBox = elementSize(element);
  5131. return attempts(options.preference(), anchorBox, elementBox, bubbles, options.bounds());
  5132. };
  5133. var setClasses = function (element, decision) {
  5134. var classInfo = decision.classes();
  5135. remove$5(element, classInfo.off);
  5136. add$3(element, classInfo.on);
  5137. };
  5138. var setHeight = function (element, decision, options) {
  5139. var maxHeightFunction = options.maxHeightFunction();
  5140. maxHeightFunction(element, decision.maxHeight());
  5141. };
  5142. var setWidth = function (element, decision, options) {
  5143. var maxWidthFunction = options.maxWidthFunction();
  5144. maxWidthFunction(element, decision.maxWidth());
  5145. };
  5146. var position = function (element, decision, options) {
  5147. var addPx = function (num) {
  5148. return num + 'px';
  5149. };
  5150. var newPosition = reposition(options.origin(), decision);
  5151. setOptions(element, {
  5152. position: Option.some(newPosition.position()),
  5153. left: newPosition.left().map(addPx),
  5154. top: newPosition.top().map(addPx),
  5155. right: newPosition.right().map(addPx),
  5156. bottom: newPosition.bottom().map(addPx)
  5157. });
  5158. };
  5159. var setMaxHeight = function (element, maxHeight) {
  5160. setMax(element, Math.floor(maxHeight));
  5161. };
  5162. var anchored = constant(function (element, available) {
  5163. setMaxHeight(element, available);
  5164. setAll$1(element, {
  5165. 'overflow-x': 'hidden',
  5166. 'overflow-y': 'auto'
  5167. });
  5168. });
  5169. var expandable = constant(function (element, available) {
  5170. setMaxHeight(element, available);
  5171. });
  5172. var reparteeOptions = MixedBag([
  5173. 'bounds',
  5174. 'origin',
  5175. 'preference',
  5176. 'maxHeightFunction',
  5177. 'maxWidthFunction'
  5178. ], []);
  5179. var defaultOr = function (options, key, dephault) {
  5180. return options[key] === undefined ? dephault : options[key];
  5181. };
  5182. var simple = function (anchor, element, bubble, layouts, getBounds, overrideOptions) {
  5183. var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  5184. var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  5185. var anchorBox = anchor.anchorBox();
  5186. var origin = anchor.origin();
  5187. var options = reparteeOptions({
  5188. bounds: viewport$1(origin, getBounds),
  5189. origin: origin,
  5190. preference: layouts,
  5191. maxHeightFunction: maxHeightFunction,
  5192. maxWidthFunction: maxWidthFunction
  5193. });
  5194. go(anchorBox, element, bubble, options);
  5195. };
  5196. var go = function (anchorBox, element, bubble, options) {
  5197. var decision = layout(anchorBox, element, bubble, options);
  5198. position(element, decision, options);
  5199. setClasses(element, decision);
  5200. setHeight(element, decision, options);
  5201. setWidth(element, decision, options);
  5202. };
  5203. var getFixedOrigin = function () {
  5204. var html = domGlobals.document.documentElement;
  5205. return fixed(0, 0, html.clientWidth, html.clientHeight);
  5206. };
  5207. var getRelativeOrigin = function (component) {
  5208. var position = absolute(component.element());
  5209. var bounds = component.element().dom().getBoundingClientRect();
  5210. return relative(position.left(), position.top(), bounds.width, bounds.height);
  5211. };
  5212. var place = function (component, origin, anchoring, getBounds, placee) {
  5213. var anchor = box$1(anchoring.anchorBox, origin);
  5214. simple(anchor, placee.element(), anchoring.bubble, anchoring.layouts, getBounds, anchoring.overrides);
  5215. };
  5216. var position$1 = function (component, posConfig, posState, anchor, placee) {
  5217. positionWithin(component, posConfig, posState, anchor, placee, Option.none());
  5218. };
  5219. var positionWithin = function (component, posConfig, posState, anchor, placee, boxElement) {
  5220. var boundsBox = boxElement.map(box);
  5221. return positionWithinBounds(component, posConfig, posState, anchor, placee, boundsBox);
  5222. };
  5223. var positionWithinBounds = function (component, posConfig, posState, anchor, placee, bounds) {
  5224. var anchorage = asRawOrDie('positioning anchor.info', AnchorSchema, anchor);
  5225. preserve(function () {
  5226. set$2(placee.element(), 'position', 'fixed');
  5227. var oldVisibility = getRaw(placee.element(), 'visibility');
  5228. set$2(placee.element(), 'visibility', 'hidden');
  5229. var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5230. var placer = anchorage.placement;
  5231. var getBounds = bounds.map(constant).or(posConfig.getBounds);
  5232. placer(component, anchorage, origin).each(function (anchoring) {
  5233. var doPlace = anchoring.placer.getOr(place);
  5234. doPlace(component, origin, anchoring, getBounds, placee);
  5235. });
  5236. oldVisibility.fold(function () {
  5237. remove$6(placee.element(), 'visibility');
  5238. }, function (vis) {
  5239. set$2(placee.element(), 'visibility', vis);
  5240. });
  5241. 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')) {
  5242. remove$6(placee.element(), 'position');
  5243. }
  5244. }, placee.element());
  5245. };
  5246. var getMode = function (component, pConfig, pState) {
  5247. return pConfig.useFixed() ? 'fixed' : 'absolute';
  5248. };
  5249. var PositionApis = /*#__PURE__*/Object.freeze({
  5250. position: position$1,
  5251. positionWithin: positionWithin,
  5252. positionWithinBounds: positionWithinBounds,
  5253. getMode: getMode
  5254. });
  5255. var PositionSchema = [
  5256. defaulted$1('useFixed', never),
  5257. option('getBounds')
  5258. ];
  5259. var Positioning = create$1({
  5260. fields: PositionSchema,
  5261. name: 'positioning',
  5262. active: ActivePosition,
  5263. apis: PositionApis
  5264. });
  5265. var fireDetaching = function (component) {
  5266. emit(component, detachedFromDom());
  5267. var children = component.components();
  5268. each(children, fireDetaching);
  5269. };
  5270. var fireAttaching = function (component) {
  5271. var children = component.components();
  5272. each(children, fireAttaching);
  5273. emit(component, attachedToDom());
  5274. };
  5275. var attach = function (parent, child) {
  5276. append(parent.element(), child.element());
  5277. };
  5278. var detachChildren = function (component) {
  5279. each(component.components(), function (childComp) {
  5280. return remove(childComp.element());
  5281. });
  5282. empty(component.element());
  5283. component.syncComponents();
  5284. };
  5285. var replaceChildren = function (component, newChildren) {
  5286. var subs = component.components();
  5287. detachChildren(component);
  5288. var deleted = difference(subs, newChildren);
  5289. each(deleted, function (comp) {
  5290. fireDetaching(comp);
  5291. component.getSystem().removeFromWorld(comp);
  5292. });
  5293. each(newChildren, function (childComp) {
  5294. if (!childComp.getSystem().isConnected()) {
  5295. component.getSystem().addToWorld(childComp);
  5296. attach(component, childComp);
  5297. if (inBody(component.element())) {
  5298. fireAttaching(childComp);
  5299. }
  5300. } else {
  5301. attach(component, childComp);
  5302. }
  5303. component.syncComponents();
  5304. });
  5305. };
  5306. var attach$1 = function (parent, child) {
  5307. attachWith(parent, child, append);
  5308. };
  5309. var attachWith = function (parent, child, insertion) {
  5310. parent.getSystem().addToWorld(child);
  5311. insertion(parent.element(), child.element());
  5312. if (inBody(parent.element())) {
  5313. fireAttaching(child);
  5314. }
  5315. parent.syncComponents();
  5316. };
  5317. var doDetach = function (component) {
  5318. fireDetaching(component);
  5319. remove(component.element());
  5320. component.getSystem().removeFromWorld(component);
  5321. };
  5322. var detach = function (component) {
  5323. var parent$1 = parent(component.element()).bind(function (p) {
  5324. return component.getSystem().getByDom(p).toOption();
  5325. });
  5326. doDetach(component);
  5327. parent$1.each(function (p) {
  5328. p.syncComponents();
  5329. });
  5330. };
  5331. var detachChildren$1 = function (component) {
  5332. var subs = component.components();
  5333. each(subs, doDetach);
  5334. empty(component.element());
  5335. component.syncComponents();
  5336. };
  5337. var attachSystem = function (element, guiSystem) {
  5338. attachSystemWith(element, guiSystem, append);
  5339. };
  5340. var attachSystemAfter = function (element, guiSystem) {
  5341. attachSystemWith(element, guiSystem, after);
  5342. };
  5343. var attachSystemWith = function (element, guiSystem, inserter) {
  5344. inserter(element, guiSystem.element());
  5345. var children$1 = children(guiSystem.element());
  5346. each(children$1, function (child) {
  5347. guiSystem.getByDom(child).each(fireAttaching);
  5348. });
  5349. };
  5350. var detachSystem = function (guiSystem) {
  5351. var children$1 = children(guiSystem.element());
  5352. each(children$1, function (child) {
  5353. guiSystem.getByDom(child).each(fireDetaching);
  5354. });
  5355. remove(guiSystem.element());
  5356. };
  5357. var rebuild = function (sandbox, sConfig, sState, data) {
  5358. sState.get().each(function (data) {
  5359. detachChildren$1(sandbox);
  5360. });
  5361. var point = sConfig.getAttachPoint(sandbox);
  5362. attach$1(point, sandbox);
  5363. var built = sandbox.getSystem().build(data);
  5364. attach$1(sandbox, built);
  5365. sState.set(built);
  5366. return built;
  5367. };
  5368. var open = function (sandbox, sConfig, sState, data) {
  5369. var newState = rebuild(sandbox, sConfig, sState, data);
  5370. sConfig.onOpen(sandbox, newState);
  5371. return newState;
  5372. };
  5373. var setContent = function (sandbox, sConfig, sState, data) {
  5374. return sState.get().map(function () {
  5375. return rebuild(sandbox, sConfig, sState, data);
  5376. });
  5377. };
  5378. var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5379. cloak(sandbox, sConfig);
  5380. open(sandbox, sConfig, sState, data);
  5381. transaction();
  5382. decloak(sandbox, sConfig);
  5383. };
  5384. var close = function (sandbox, sConfig, sState) {
  5385. sState.get().each(function (data) {
  5386. detachChildren$1(sandbox);
  5387. detach(sandbox);
  5388. sConfig.onClose(sandbox, data);
  5389. sState.clear();
  5390. });
  5391. };
  5392. var isOpen = function (sandbox, sConfig, sState) {
  5393. return sState.isOpen();
  5394. };
  5395. var isPartOf$1 = function (sandbox, sConfig, sState, queryElem) {
  5396. return isOpen(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5397. return sConfig.isPartOf(sandbox, data, queryElem);
  5398. });
  5399. };
  5400. var getState = function (sandbox, sConfig, sState) {
  5401. return sState.get();
  5402. };
  5403. var store = function (sandbox, cssKey, attr, newValue) {
  5404. getRaw(sandbox.element(), cssKey).fold(function () {
  5405. remove$1(sandbox.element(), attr);
  5406. }, function (v) {
  5407. set$1(sandbox.element(), attr, v);
  5408. });
  5409. set$2(sandbox.element(), cssKey, newValue);
  5410. };
  5411. var restore = function (sandbox, cssKey, attr) {
  5412. if (has$1(sandbox.element(), attr)) {
  5413. var oldValue = get$2(sandbox.element(), attr);
  5414. set$2(sandbox.element(), cssKey, oldValue);
  5415. } else {
  5416. remove$6(sandbox.element(), cssKey);
  5417. }
  5418. };
  5419. var cloak = function (sandbox, sConfig, sState) {
  5420. var sink = sConfig.getAttachPoint(sandbox);
  5421. set$2(sandbox.element(), 'position', Positioning.getMode(sink));
  5422. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5423. };
  5424. var hasPosition = function (element) {
  5425. return exists([
  5426. 'top',
  5427. 'left',
  5428. 'right',
  5429. 'bottom'
  5430. ], function (pos) {
  5431. return getRaw(element, pos).isSome();
  5432. });
  5433. };
  5434. var decloak = function (sandbox, sConfig, sState) {
  5435. if (!hasPosition(sandbox.element())) {
  5436. remove$6(sandbox.element(), 'position');
  5437. }
  5438. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  5439. };
  5440. var SandboxApis = /*#__PURE__*/Object.freeze({
  5441. cloak: cloak,
  5442. decloak: decloak,
  5443. open: open,
  5444. openWhileCloaked: openWhileCloaked,
  5445. close: close,
  5446. isOpen: isOpen,
  5447. isPartOf: isPartOf$1,
  5448. getState: getState,
  5449. setContent: setContent
  5450. });
  5451. var events$2 = function (sandboxConfig, sandboxState) {
  5452. return derive([run(sandboxClose(), function (sandbox, simulatedEvent) {
  5453. close(sandbox, sandboxConfig, sandboxState);
  5454. })]);
  5455. };
  5456. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  5457. events: events$2
  5458. });
  5459. var SandboxSchema = [
  5460. onHandler('onOpen'),
  5461. onHandler('onClose'),
  5462. strict$1('isPartOf'),
  5463. strict$1('getAttachPoint'),
  5464. defaulted$1('cloakVisibilityAttr', 'data-precloak-visibility')
  5465. ];
  5466. var init = function () {
  5467. var contents = Cell(Option.none());
  5468. var readState = constant('not-implemented');
  5469. var isOpen = function () {
  5470. return contents.get().isSome();
  5471. };
  5472. var set = function (c) {
  5473. contents.set(Option.some(c));
  5474. };
  5475. var get = function (c) {
  5476. return contents.get();
  5477. };
  5478. var clear = function () {
  5479. contents.set(Option.none());
  5480. };
  5481. return nu$5({
  5482. readState: readState,
  5483. isOpen: isOpen,
  5484. clear: clear,
  5485. set: set,
  5486. get: get
  5487. });
  5488. };
  5489. var SandboxState = /*#__PURE__*/Object.freeze({
  5490. init: init
  5491. });
  5492. var Sandboxing = create$1({
  5493. fields: SandboxSchema,
  5494. name: 'sandboxing',
  5495. active: ActiveSandbox,
  5496. apis: SandboxApis,
  5497. state: SandboxState
  5498. });
  5499. var dismissPopups = constant('dismiss.popups');
  5500. var repositionPopups = constant('reposition.popups');
  5501. var mouseReleased = constant('mouse.released');
  5502. var schema$2 = objOfOnly([
  5503. defaulted$1('isExtraPart', constant(false)),
  5504. optionObjOf('fireEventInstead', [defaulted$1('event', dismissRequested())])
  5505. ]);
  5506. var receivingChannel = function (rawSpec) {
  5507. var _a;
  5508. var detail = asRawOrDie('Dismissal', schema$2, rawSpec);
  5509. return _a = {}, _a[dismissPopups()] = {
  5510. schema: objOfOnly([strict$1('target')]),
  5511. onReceive: function (sandbox, data) {
  5512. if (Sandboxing.isOpen(sandbox)) {
  5513. var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  5514. if (!isPart) {
  5515. detail.fireEventInstead.fold(function () {
  5516. return Sandboxing.close(sandbox);
  5517. }, function (fe) {
  5518. return emit(sandbox, fe.event);
  5519. });
  5520. }
  5521. }
  5522. }
  5523. }, _a;
  5524. };
  5525. var schema$3 = objOfOnly([
  5526. defaulted$1('isExtraPart', constant(false)),
  5527. optionObjOf('fireEventInstead', [defaulted$1('event', repositionRequested())]),
  5528. strictFunction('doReposition')
  5529. ]);
  5530. var receivingChannel$1 = function (rawSpec) {
  5531. var _a;
  5532. var detail = asRawOrDie('Reposition', schema$3, rawSpec);
  5533. return _a = {}, _a[repositionPopups()] = {
  5534. onReceive: function (sandbox) {
  5535. if (Sandboxing.isOpen(sandbox)) {
  5536. detail.fireEventInstead.fold(function () {
  5537. return detail.doReposition(sandbox);
  5538. }, function (fe) {
  5539. return emit(sandbox, fe.event);
  5540. });
  5541. }
  5542. }
  5543. }, _a;
  5544. };
  5545. var onLoad = function (component, repConfig, repState) {
  5546. repConfig.store.manager.onLoad(component, repConfig, repState);
  5547. };
  5548. var onUnload = function (component, repConfig, repState) {
  5549. repConfig.store.manager.onUnload(component, repConfig, repState);
  5550. };
  5551. var setValue = function (component, repConfig, repState, data) {
  5552. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5553. };
  5554. var getValue = function (component, repConfig, repState) {
  5555. return repConfig.store.manager.getValue(component, repConfig, repState);
  5556. };
  5557. var getState$1 = function (component, repConfig, repState) {
  5558. return repState;
  5559. };
  5560. var RepresentApis = /*#__PURE__*/Object.freeze({
  5561. onLoad: onLoad,
  5562. onUnload: onUnload,
  5563. setValue: setValue,
  5564. getValue: getValue,
  5565. getState: getState$1
  5566. });
  5567. var events$3 = function (repConfig, repState) {
  5568. var es = repConfig.resetOnDom ? [
  5569. runOnAttached(function (comp, se) {
  5570. onLoad(comp, repConfig, repState);
  5571. }),
  5572. runOnDetached(function (comp, se) {
  5573. onUnload(comp, repConfig, repState);
  5574. })
  5575. ] : [loadEvent(repConfig, repState, onLoad)];
  5576. return derive(es);
  5577. };
  5578. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5579. events: events$3
  5580. });
  5581. var memory = function () {
  5582. var data = Cell(null);
  5583. var readState = function () {
  5584. return {
  5585. mode: 'memory',
  5586. value: data.get()
  5587. };
  5588. };
  5589. var isNotSet = function () {
  5590. return data.get() === null;
  5591. };
  5592. var clear = function () {
  5593. data.set(null);
  5594. };
  5595. return nu$5({
  5596. set: data.set,
  5597. get: data.get,
  5598. isNotSet: isNotSet,
  5599. clear: clear,
  5600. readState: readState
  5601. });
  5602. };
  5603. var manual = function () {
  5604. var readState = function () {
  5605. };
  5606. return nu$5({ readState: readState });
  5607. };
  5608. var dataset = function () {
  5609. var dataByValue = Cell({});
  5610. var dataByText = Cell({});
  5611. var readState = function () {
  5612. return {
  5613. mode: 'dataset',
  5614. dataByValue: dataByValue.get(),
  5615. dataByText: dataByText.get()
  5616. };
  5617. };
  5618. var clear = function () {
  5619. dataByValue.set({});
  5620. dataByText.set({});
  5621. };
  5622. var lookup = function (itemString) {
  5623. return readOptFrom$1(dataByValue.get(), itemString).orThunk(function () {
  5624. return readOptFrom$1(dataByText.get(), itemString);
  5625. });
  5626. };
  5627. var update = function (items) {
  5628. var currentDataByValue = dataByValue.get();
  5629. var currentDataByText = dataByText.get();
  5630. var newDataByValue = {};
  5631. var newDataByText = {};
  5632. each(items, function (item) {
  5633. newDataByValue[item.value] = item;
  5634. readOptFrom$1(item, 'meta').each(function (meta) {
  5635. readOptFrom$1(meta, 'text').each(function (text) {
  5636. newDataByText[text] = item;
  5637. });
  5638. });
  5639. });
  5640. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5641. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5642. };
  5643. return nu$5({
  5644. readState: readState,
  5645. lookup: lookup,
  5646. update: update,
  5647. clear: clear
  5648. });
  5649. };
  5650. var init$1 = function (spec) {
  5651. return spec.store.manager.state(spec);
  5652. };
  5653. var RepresentState = /*#__PURE__*/Object.freeze({
  5654. memory: memory,
  5655. dataset: dataset,
  5656. manual: manual,
  5657. init: init$1
  5658. });
  5659. var setValue$1 = function (component, repConfig, repState, data) {
  5660. var store = repConfig.store;
  5661. repState.update([data]);
  5662. store.setValue(component, data);
  5663. repConfig.onSetValue(component, data);
  5664. };
  5665. var getValue$1 = function (component, repConfig, repState) {
  5666. var store = repConfig.store;
  5667. var key = store.getDataKey(component);
  5668. return repState.lookup(key).fold(function () {
  5669. return store.getFallbackEntry(key);
  5670. }, function (data) {
  5671. return data;
  5672. });
  5673. };
  5674. var onLoad$1 = function (component, repConfig, repState) {
  5675. var store = repConfig.store;
  5676. store.initialValue.each(function (data) {
  5677. setValue$1(component, repConfig, repState, data);
  5678. });
  5679. };
  5680. var onUnload$1 = function (component, repConfig, repState) {
  5681. repState.clear();
  5682. };
  5683. var DatasetStore = [
  5684. option('initialValue'),
  5685. strict$1('getFallbackEntry'),
  5686. strict$1('getDataKey'),
  5687. strict$1('setValue'),
  5688. output('manager', {
  5689. setValue: setValue$1,
  5690. getValue: getValue$1,
  5691. onLoad: onLoad$1,
  5692. onUnload: onUnload$1,
  5693. state: dataset
  5694. })
  5695. ];
  5696. var getValue$2 = function (component, repConfig, repState) {
  5697. return repConfig.store.getValue(component);
  5698. };
  5699. var setValue$2 = function (component, repConfig, repState, data) {
  5700. repConfig.store.setValue(component, data);
  5701. repConfig.onSetValue(component, data);
  5702. };
  5703. var onLoad$2 = function (component, repConfig, repState) {
  5704. repConfig.store.initialValue.each(function (data) {
  5705. repConfig.store.setValue(component, data);
  5706. });
  5707. };
  5708. var ManualStore = [
  5709. strict$1('getValue'),
  5710. defaulted$1('setValue', noop),
  5711. option('initialValue'),
  5712. output('manager', {
  5713. setValue: setValue$2,
  5714. getValue: getValue$2,
  5715. onLoad: onLoad$2,
  5716. onUnload: noop,
  5717. state: NoState.init
  5718. })
  5719. ];
  5720. var setValue$3 = function (component, repConfig, repState, data) {
  5721. repState.set(data);
  5722. repConfig.onSetValue(component, data);
  5723. };
  5724. var getValue$3 = function (component, repConfig, repState) {
  5725. return repState.get();
  5726. };
  5727. var onLoad$3 = function (component, repConfig, repState) {
  5728. repConfig.store.initialValue.each(function (initVal) {
  5729. if (repState.isNotSet()) {
  5730. repState.set(initVal);
  5731. }
  5732. });
  5733. };
  5734. var onUnload$2 = function (component, repConfig, repState) {
  5735. repState.clear();
  5736. };
  5737. var MemoryStore = [
  5738. option('initialValue'),
  5739. output('manager', {
  5740. setValue: setValue$3,
  5741. getValue: getValue$3,
  5742. onLoad: onLoad$3,
  5743. onUnload: onUnload$2,
  5744. state: memory
  5745. })
  5746. ];
  5747. var RepresentSchema = [
  5748. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5749. memory: MemoryStore,
  5750. manual: ManualStore,
  5751. dataset: DatasetStore
  5752. })),
  5753. onHandler('onSetValue'),
  5754. defaulted$1('resetOnDom', false)
  5755. ];
  5756. var Representing = create$1({
  5757. fields: RepresentSchema,
  5758. name: 'representing',
  5759. active: ActiveRepresenting,
  5760. apis: RepresentApis,
  5761. extra: {
  5762. setValueFrom: function (component, source) {
  5763. var value = Representing.getValue(source);
  5764. Representing.setValue(component, value);
  5765. }
  5766. },
  5767. state: RepresentState
  5768. });
  5769. var field$1 = function (name, forbidden) {
  5770. return defaultedObjOf(name, {}, map(forbidden, function (f) {
  5771. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  5772. }).concat([state$1('dump', identity)]));
  5773. };
  5774. var get$b = function (data) {
  5775. return data.dump;
  5776. };
  5777. var augment = function (data, original) {
  5778. return __assign(__assign({}, data.dump), derive$1(original));
  5779. };
  5780. var SketchBehaviours = {
  5781. field: field$1,
  5782. augment: augment,
  5783. get: get$b
  5784. };
  5785. var _placeholder = 'placeholder';
  5786. var adt$9 = Adt.generate([
  5787. {
  5788. single: [
  5789. 'required',
  5790. 'valueThunk'
  5791. ]
  5792. },
  5793. {
  5794. multiple: [
  5795. 'required',
  5796. 'valueThunks'
  5797. ]
  5798. }
  5799. ]);
  5800. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  5801. if (owner.exists(function (o) {
  5802. return o !== compSpec.owner;
  5803. })) {
  5804. return adt$9.single(true, constant(compSpec));
  5805. }
  5806. return readOptFrom$1(placeholders, compSpec.name).fold(function () {
  5807. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  5808. }, function (newSpec) {
  5809. return newSpec.replace();
  5810. });
  5811. };
  5812. var scan = function (owner, detail, compSpec, placeholders) {
  5813. if (compSpec.uiType === _placeholder) {
  5814. return subPlaceholder(owner, detail, compSpec, placeholders);
  5815. } else {
  5816. return adt$9.single(false, constant(compSpec));
  5817. }
  5818. };
  5819. var substitute = function (owner, detail, compSpec, placeholders) {
  5820. var base = scan(owner, detail, compSpec, placeholders);
  5821. return base.fold(function (req, valueThunk) {
  5822. var value = valueThunk(detail, compSpec.config, compSpec.validated);
  5823. var childSpecs = readOptFrom$1(value, 'components').getOr([]);
  5824. var substituted = bind(childSpecs, function (c) {
  5825. return substitute(owner, detail, c, placeholders);
  5826. });
  5827. return [__assign(__assign({}, value), { components: substituted })];
  5828. }, function (req, valuesThunk) {
  5829. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  5830. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  5831. return preprocessor(values);
  5832. });
  5833. };
  5834. var substituteAll = function (owner, detail, components, placeholders) {
  5835. return bind(components, function (c) {
  5836. return substitute(owner, detail, c, placeholders);
  5837. });
  5838. };
  5839. var oneReplace = function (label, replacements) {
  5840. var called = false;
  5841. var used = function () {
  5842. return called;
  5843. };
  5844. var replace = function () {
  5845. if (called === true) {
  5846. throw new Error('Trying to use the same placeholder more than once: ' + label);
  5847. }
  5848. called = true;
  5849. return replacements;
  5850. };
  5851. var required = function () {
  5852. return replacements.fold(function (req, _) {
  5853. return req;
  5854. }, function (req, _) {
  5855. return req;
  5856. });
  5857. };
  5858. return {
  5859. name: constant(label),
  5860. required: required,
  5861. used: used,
  5862. replace: replace
  5863. };
  5864. };
  5865. var substitutePlaces = function (owner, detail, components, placeholders) {
  5866. var ps = map$1(placeholders, function (ph, name) {
  5867. return oneReplace(name, ph);
  5868. });
  5869. var outcome = substituteAll(owner, detail, components, ps);
  5870. each$1(ps, function (p) {
  5871. if (p.used() === false && p.required()) {
  5872. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  5873. }
  5874. });
  5875. return outcome;
  5876. };
  5877. var single = adt$9.single;
  5878. var multiple = adt$9.multiple;
  5879. var placeholder = constant(_placeholder);
  5880. var adt$a = Adt.generate([
  5881. { required: ['data'] },
  5882. { external: ['data'] },
  5883. { optional: ['data'] },
  5884. { group: ['data'] }
  5885. ]);
  5886. var fFactory = defaulted$1('factory', { sketch: identity });
  5887. var fSchema = defaulted$1('schema', []);
  5888. var fName = strict$1('name');
  5889. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  5890. return '<alloy.' + generate$1(typeSpec.name) + '>';
  5891. }), anyValue$1());
  5892. var fGroupSchema = state$1('schema', function () {
  5893. return [option('preprocess')];
  5894. });
  5895. var fDefaults = defaulted$1('defaults', constant({}));
  5896. var fOverrides = defaulted$1('overrides', constant({}));
  5897. var requiredSpec = objOf([
  5898. fFactory,
  5899. fSchema,
  5900. fName,
  5901. fPname,
  5902. fDefaults,
  5903. fOverrides
  5904. ]);
  5905. var externalSpec = objOf([
  5906. fFactory,
  5907. fSchema,
  5908. fName,
  5909. fDefaults,
  5910. fOverrides
  5911. ]);
  5912. var optionalSpec = objOf([
  5913. fFactory,
  5914. fSchema,
  5915. fName,
  5916. fPname,
  5917. fDefaults,
  5918. fOverrides
  5919. ]);
  5920. var groupSpec = objOf([
  5921. fFactory,
  5922. fGroupSchema,
  5923. fName,
  5924. strict$1('unit'),
  5925. fPname,
  5926. fDefaults,
  5927. fOverrides
  5928. ]);
  5929. var asNamedPart = function (part) {
  5930. return part.fold(Option.some, Option.none, Option.some, Option.some);
  5931. };
  5932. var name$1 = function (part) {
  5933. var get = function (data) {
  5934. return data.name;
  5935. };
  5936. return part.fold(get, get, get, get);
  5937. };
  5938. var asCommon = function (part) {
  5939. return part.fold(identity, identity, identity, identity);
  5940. };
  5941. var convert = function (adtConstructor, partSchema) {
  5942. return function (spec) {
  5943. var data = asRawOrDie('Converting part type', partSchema, spec);
  5944. return adtConstructor(data);
  5945. };
  5946. };
  5947. var required = convert(adt$a.required, requiredSpec);
  5948. var external$1 = convert(adt$a.external, externalSpec);
  5949. var optional = convert(adt$a.optional, optionalSpec);
  5950. var group = convert(adt$a.group, groupSpec);
  5951. var original = constant('entirety');
  5952. var PartType = /*#__PURE__*/Object.freeze({
  5953. required: required,
  5954. external: external$1,
  5955. optional: optional,
  5956. group: group,
  5957. asNamedPart: asNamedPart,
  5958. name: name$1,
  5959. asCommon: asCommon,
  5960. original: original
  5961. });
  5962. var combine$2 = function (detail, data, partSpec, partValidated) {
  5963. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  5964. };
  5965. var subs = function (owner, detail, parts) {
  5966. var internals = {};
  5967. var externals = {};
  5968. each(parts, function (part) {
  5969. part.fold(function (data) {
  5970. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  5971. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5972. });
  5973. }, function (data) {
  5974. var partSpec = detail.parts[data.name];
  5975. externals[data.name] = constant(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  5976. }, function (data) {
  5977. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  5978. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5979. });
  5980. }, function (data) {
  5981. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  5982. var units = detail[data.name];
  5983. return map(units, function (u) {
  5984. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  5985. });
  5986. });
  5987. });
  5988. });
  5989. return {
  5990. internals: constant(internals),
  5991. externals: constant(externals)
  5992. };
  5993. };
  5994. var generate$4 = function (owner, parts) {
  5995. var r = {};
  5996. each(parts, function (part) {
  5997. asNamedPart(part).each(function (np) {
  5998. var g = doGenerateOne(owner, np.pname);
  5999. r[np.name] = function (config) {
  6000. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  6001. return __assign(__assign({}, g), {
  6002. config: config,
  6003. validated: validated
  6004. });
  6005. };
  6006. });
  6007. });
  6008. return r;
  6009. };
  6010. var doGenerateOne = function (owner, pname) {
  6011. return {
  6012. uiType: placeholder(),
  6013. owner: owner,
  6014. name: pname
  6015. };
  6016. };
  6017. var generateOne = function (owner, pname, config) {
  6018. return {
  6019. uiType: placeholder(),
  6020. owner: owner,
  6021. name: pname,
  6022. config: config,
  6023. validated: {}
  6024. };
  6025. };
  6026. var schemas = function (parts) {
  6027. return bind(parts, function (part) {
  6028. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  6029. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  6030. }).toArray();
  6031. });
  6032. };
  6033. var names = function (parts) {
  6034. return map(parts, name$1);
  6035. };
  6036. var substitutes = function (owner, detail, parts) {
  6037. return subs(owner, detail, parts);
  6038. };
  6039. var components = function (owner, detail, internals) {
  6040. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  6041. };
  6042. var getPart = function (component, detail, partKey) {
  6043. var uid = detail.partUids[partKey];
  6044. return component.getSystem().getByUid(uid).toOption();
  6045. };
  6046. var getPartOrDie = function (component, detail, partKey) {
  6047. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  6048. };
  6049. var getParts = function (component, detail, partKeys) {
  6050. var r = {};
  6051. var uids = detail.partUids;
  6052. var system = component.getSystem();
  6053. each(partKeys, function (pk) {
  6054. r[pk] = constant(system.getByUid(uids[pk]));
  6055. });
  6056. return r;
  6057. };
  6058. var getAllParts = function (component, detail) {
  6059. var system = component.getSystem();
  6060. return map$1(detail.partUids, function (pUid, k) {
  6061. return constant(system.getByUid(pUid));
  6062. });
  6063. };
  6064. var getAllPartNames = function (detail) {
  6065. return keys(detail.partUids);
  6066. };
  6067. var getPartsOrDie = function (component, detail, partKeys) {
  6068. var r = {};
  6069. var uids = detail.partUids;
  6070. var system = component.getSystem();
  6071. each(partKeys, function (pk) {
  6072. r[pk] = constant(system.getByUid(uids[pk]).getOrDie());
  6073. });
  6074. return r;
  6075. };
  6076. var defaultUids = function (baseUid, partTypes) {
  6077. var partNames = names(partTypes);
  6078. return wrapAll$1(map(partNames, function (pn) {
  6079. return {
  6080. key: pn,
  6081. value: baseUid + '-' + pn
  6082. };
  6083. }));
  6084. };
  6085. var defaultUidsSchema = function (partTypes) {
  6086. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  6087. return defaultUids(spec.uid, partTypes);
  6088. }), anyValue$1());
  6089. };
  6090. var AlloyParts = /*#__PURE__*/Object.freeze({
  6091. generate: generate$4,
  6092. generateOne: generateOne,
  6093. schemas: schemas,
  6094. names: names,
  6095. substitutes: substitutes,
  6096. components: components,
  6097. defaultUids: defaultUids,
  6098. defaultUidsSchema: defaultUidsSchema,
  6099. getAllParts: getAllParts,
  6100. getAllPartNames: getAllPartNames,
  6101. getPart: getPart,
  6102. getPartOrDie: getPartOrDie,
  6103. getParts: getParts,
  6104. getPartsOrDie: getPartsOrDie
  6105. });
  6106. var base = function (partSchemas, partUidsSchemas) {
  6107. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  6108. return ps.concat([
  6109. strict$1('uid'),
  6110. defaulted$1('dom', {}),
  6111. defaulted$1('components', []),
  6112. snapshot('originalSpec'),
  6113. defaulted$1('debug.sketcher', {})
  6114. ]).concat(partUidsSchemas);
  6115. };
  6116. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6117. var baseS = base(partSchemas, partUidsSchemas);
  6118. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6119. };
  6120. var single$1 = function (owner, schema, factory, spec) {
  6121. var specWithUid = supplyUid(spec);
  6122. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  6123. return factory(detail, specWithUid);
  6124. };
  6125. var composite = function (owner, schema, partTypes, factory, spec) {
  6126. var specWithUid = supplyUid(spec);
  6127. var partSchemas = schemas(partTypes);
  6128. var partUidsSchema = defaultUidsSchema(partTypes);
  6129. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6130. var subs = substitutes(owner, detail, partTypes);
  6131. var components$1 = components(owner, detail, subs.internals());
  6132. return factory(detail, components$1, specWithUid, subs.externals());
  6133. };
  6134. var supplyUid = function (spec) {
  6135. return spec.hasOwnProperty('uid') ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  6136. };
  6137. function isSketchSpec(spec) {
  6138. return spec.uid !== undefined;
  6139. }
  6140. var singleSchema = objOfOnly([
  6141. strict$1('name'),
  6142. strict$1('factory'),
  6143. strict$1('configFields'),
  6144. defaulted$1('apis', {}),
  6145. defaulted$1('extraApis', {})
  6146. ]);
  6147. var compositeSchema = objOfOnly([
  6148. strict$1('name'),
  6149. strict$1('factory'),
  6150. strict$1('configFields'),
  6151. strict$1('partFields'),
  6152. defaulted$1('apis', {}),
  6153. defaulted$1('extraApis', {})
  6154. ]);
  6155. var single$2 = function (rawConfig) {
  6156. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6157. var sketch = function (spec) {
  6158. return single$1(config.name, config.configFields, config.factory, spec);
  6159. };
  6160. var apis = map$1(config.apis, makeApi);
  6161. var extraApis = map$1(config.extraApis, function (f, k) {
  6162. return markAsExtraApi(f, k);
  6163. });
  6164. return __assign(__assign({
  6165. name: constant(config.name),
  6166. partFields: constant([]),
  6167. configFields: constant(config.configFields),
  6168. sketch: sketch
  6169. }, apis), extraApis);
  6170. };
  6171. var composite$1 = function (rawConfig) {
  6172. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6173. var sketch = function (spec) {
  6174. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  6175. };
  6176. var parts = generate$4(config.name, config.partFields);
  6177. var apis = map$1(config.apis, makeApi);
  6178. var extraApis = map$1(config.extraApis, function (f, k) {
  6179. return markAsExtraApi(f, k);
  6180. });
  6181. return __assign(__assign({
  6182. name: constant(config.name),
  6183. partFields: constant(config.partFields),
  6184. configFields: constant(config.configFields),
  6185. sketch: sketch,
  6186. parts: constant(parts)
  6187. }, apis), extraApis);
  6188. };
  6189. var inside = function (target) {
  6190. return name(target) === 'input' && get$2(target, 'type') !== 'radio' || name(target) === 'textarea';
  6191. };
  6192. var getCurrent = function (component, composeConfig, composeState) {
  6193. return composeConfig.find(component);
  6194. };
  6195. var ComposeApis = /*#__PURE__*/Object.freeze({
  6196. getCurrent: getCurrent
  6197. });
  6198. var ComposeSchema = [strict$1('find')];
  6199. var Composing = create$1({
  6200. fields: ComposeSchema,
  6201. name: 'composing',
  6202. apis: ComposeApis
  6203. });
  6204. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6205. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  6206. each(highlighted, function (h) {
  6207. if (!exists(skip, function (skipComp) {
  6208. return skipComp.element() === h;
  6209. })) {
  6210. remove$4(h, hConfig.highlightClass);
  6211. component.getSystem().getByDom(h).each(function (target) {
  6212. hConfig.onDehighlight(component, target);
  6213. emit(target, dehighlight());
  6214. });
  6215. }
  6216. });
  6217. };
  6218. var dehighlightAll = function (component, hConfig, hState) {
  6219. return dehighlightAllExcept(component, hConfig, hState, []);
  6220. };
  6221. var dehighlight$1 = function (component, hConfig, hState, target) {
  6222. if (isHighlighted(component, hConfig, hState, target)) {
  6223. remove$4(target.element(), hConfig.highlightClass);
  6224. hConfig.onDehighlight(component, target);
  6225. emit(target, dehighlight());
  6226. }
  6227. };
  6228. var highlight$1 = function (component, hConfig, hState, target) {
  6229. dehighlightAllExcept(component, hConfig, hState, [target]);
  6230. if (!isHighlighted(component, hConfig, hState, target)) {
  6231. add$2(target.element(), hConfig.highlightClass);
  6232. hConfig.onHighlight(component, target);
  6233. emit(target, highlight());
  6234. }
  6235. };
  6236. var highlightFirst = function (component, hConfig, hState) {
  6237. getFirst(component, hConfig).each(function (firstComp) {
  6238. highlight$1(component, hConfig, hState, firstComp);
  6239. });
  6240. };
  6241. var highlightLast = function (component, hConfig, hState) {
  6242. getLast(component, hConfig).each(function (lastComp) {
  6243. highlight$1(component, hConfig, hState, lastComp);
  6244. });
  6245. };
  6246. var highlightAt = function (component, hConfig, hState, index) {
  6247. getByIndex(component, hConfig, hState, index).fold(function (err) {
  6248. throw new Error(err);
  6249. }, function (firstComp) {
  6250. highlight$1(component, hConfig, hState, firstComp);
  6251. });
  6252. };
  6253. var highlightBy = function (component, hConfig, hState, predicate) {
  6254. var candidates = getCandidates(component, hConfig);
  6255. var targetComp = find(candidates, predicate);
  6256. targetComp.each(function (c) {
  6257. highlight$1(component, hConfig, hState, c);
  6258. });
  6259. };
  6260. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6261. return has$2(queryTarget.element(), hConfig.highlightClass);
  6262. };
  6263. var getHighlighted = function (component, hConfig, hState) {
  6264. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  6265. return component.getSystem().getByDom(e).toOption();
  6266. });
  6267. };
  6268. var getByIndex = function (component, hConfig, hState, index) {
  6269. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6270. return Option.from(items[index]).fold(function () {
  6271. return Result.error('No element found with index ' + index);
  6272. }, component.getSystem().getByDom);
  6273. };
  6274. var getFirst = function (component, hConfig, hState) {
  6275. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  6276. return component.getSystem().getByDom(e).toOption();
  6277. });
  6278. };
  6279. var getLast = function (component, hConfig, hState) {
  6280. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6281. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  6282. return last.bind(function (c) {
  6283. return component.getSystem().getByDom(c).toOption();
  6284. });
  6285. };
  6286. var getDelta = function (component, hConfig, hState, delta) {
  6287. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6288. var current = findIndex(items, function (item) {
  6289. return has$2(item, hConfig.highlightClass);
  6290. });
  6291. return current.bind(function (selected) {
  6292. var dest = cycleBy(selected, delta, 0, items.length - 1);
  6293. return component.getSystem().getByDom(items[dest]).toOption();
  6294. });
  6295. };
  6296. var getPrevious = function (component, hConfig, hState) {
  6297. return getDelta(component, hConfig, hState, -1);
  6298. };
  6299. var getNext = function (component, hConfig, hState) {
  6300. return getDelta(component, hConfig, hState, +1);
  6301. };
  6302. var getCandidates = function (component, hConfig, hState) {
  6303. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6304. return cat(map(items, function (i) {
  6305. return component.getSystem().getByDom(i).toOption();
  6306. }));
  6307. };
  6308. var HighlightApis = /*#__PURE__*/Object.freeze({
  6309. dehighlightAll: dehighlightAll,
  6310. dehighlight: dehighlight$1,
  6311. highlight: highlight$1,
  6312. highlightFirst: highlightFirst,
  6313. highlightLast: highlightLast,
  6314. highlightAt: highlightAt,
  6315. highlightBy: highlightBy,
  6316. isHighlighted: isHighlighted,
  6317. getHighlighted: getHighlighted,
  6318. getFirst: getFirst,
  6319. getLast: getLast,
  6320. getPrevious: getPrevious,
  6321. getNext: getNext,
  6322. getCandidates: getCandidates
  6323. });
  6324. var HighlightSchema = [
  6325. strict$1('highlightClass'),
  6326. strict$1('itemClass'),
  6327. onHandler('onHighlight'),
  6328. onHandler('onDehighlight')
  6329. ];
  6330. var Highlighting = create$1({
  6331. fields: HighlightSchema,
  6332. name: 'highlighting',
  6333. apis: HighlightApis
  6334. });
  6335. var BACKSPACE = function () {
  6336. return [8];
  6337. };
  6338. var TAB = function () {
  6339. return [9];
  6340. };
  6341. var ENTER = function () {
  6342. return [13];
  6343. };
  6344. var ESCAPE = function () {
  6345. return [27];
  6346. };
  6347. var SPACE = function () {
  6348. return [32];
  6349. };
  6350. var LEFT = function () {
  6351. return [37];
  6352. };
  6353. var UP = function () {
  6354. return [38];
  6355. };
  6356. var RIGHT = function () {
  6357. return [39];
  6358. };
  6359. var DOWN = function () {
  6360. return [40];
  6361. };
  6362. var cyclePrev = function (values, index, predicate) {
  6363. var before = reverse(values.slice(0, index));
  6364. var after = reverse(values.slice(index + 1));
  6365. return find(before.concat(after), predicate);
  6366. };
  6367. var tryPrev = function (values, index, predicate) {
  6368. var before = reverse(values.slice(0, index));
  6369. return find(before, predicate);
  6370. };
  6371. var cycleNext = function (values, index, predicate) {
  6372. var before = values.slice(0, index);
  6373. var after = values.slice(index + 1);
  6374. return find(after.concat(before), predicate);
  6375. };
  6376. var tryNext = function (values, index, predicate) {
  6377. var after = values.slice(index + 1);
  6378. return find(after, predicate);
  6379. };
  6380. var inSet = function (keys) {
  6381. return function (event) {
  6382. var raw = event.raw();
  6383. return contains(keys, raw.which);
  6384. };
  6385. };
  6386. var and = function (preds) {
  6387. return function (event) {
  6388. return forall(preds, function (pred) {
  6389. return pred(event);
  6390. });
  6391. };
  6392. };
  6393. var isShift = function (event) {
  6394. var raw = event.raw();
  6395. return raw.shiftKey === true;
  6396. };
  6397. var isControl = function (event) {
  6398. var raw = event.raw();
  6399. return raw.ctrlKey === true;
  6400. };
  6401. var isNotShift = not(isShift);
  6402. var rule = function (matches, action) {
  6403. return {
  6404. matches: matches,
  6405. classification: action
  6406. };
  6407. };
  6408. var choose$2 = function (transitions, event) {
  6409. var transition = find(transitions, function (t) {
  6410. return t.matches(event);
  6411. });
  6412. return transition.map(function (t) {
  6413. return t.classification;
  6414. });
  6415. };
  6416. var reportFocusShifting = function (component, prevFocus, newFocus) {
  6417. var noChange = prevFocus.exists(function (p) {
  6418. return newFocus.exists(function (n) {
  6419. return eq(n, p);
  6420. });
  6421. });
  6422. if (!noChange) {
  6423. emitWith(component, focusShifted(), {
  6424. prevFocus: prevFocus,
  6425. newFocus: newFocus
  6426. });
  6427. }
  6428. };
  6429. var dom = function () {
  6430. var get = function (component) {
  6431. return search(component.element());
  6432. };
  6433. var set = function (component, focusee) {
  6434. var prevFocus = get(component);
  6435. component.getSystem().triggerFocus(focusee, component.element());
  6436. var newFocus = get(component);
  6437. reportFocusShifting(component, prevFocus, newFocus);
  6438. };
  6439. return {
  6440. get: get,
  6441. set: set
  6442. };
  6443. };
  6444. var highlights = function () {
  6445. var get = function (component) {
  6446. return Highlighting.getHighlighted(component).map(function (item) {
  6447. return item.element();
  6448. });
  6449. };
  6450. var set = function (component, element) {
  6451. var prevFocus = get(component);
  6452. component.getSystem().getByDom(element).fold(noop, function (item) {
  6453. Highlighting.highlight(component, item);
  6454. });
  6455. var newFocus = get(component);
  6456. reportFocusShifting(component, prevFocus, newFocus);
  6457. };
  6458. return {
  6459. get: get,
  6460. set: set
  6461. };
  6462. };
  6463. var FocusInsideModes;
  6464. (function (FocusInsideModes) {
  6465. FocusInsideModes['OnFocusMode'] = 'onFocus';
  6466. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  6467. FocusInsideModes['OnApiMode'] = 'onApi';
  6468. }(FocusInsideModes || (FocusInsideModes = {})));
  6469. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  6470. var schema = function () {
  6471. return infoSchema.concat([
  6472. defaulted$1('focusManager', dom()),
  6473. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  6474. return contains([
  6475. 'onFocus',
  6476. 'onEnterOrSpace',
  6477. 'onApi'
  6478. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  6479. })),
  6480. output('handler', me),
  6481. output('state', stateInit),
  6482. output('sendFocusIn', optFocusIn)
  6483. ]);
  6484. };
  6485. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  6486. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  6487. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  6488. return rule(component, simulatedEvent, keyingConfig, keyingState);
  6489. });
  6490. };
  6491. var toEvents = function (keyingConfig, keyingState) {
  6492. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  6493. return run(focus(), function (component, simulatedEvent) {
  6494. focusIn(component, keyingConfig, keyingState);
  6495. simulatedEvent.stop();
  6496. });
  6497. });
  6498. var tryGoInsideComponent = function (component, simulatedEvent) {
  6499. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  6500. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  6501. optFocusIn(keyingConfig).each(function (focusIn) {
  6502. focusIn(component, keyingConfig, keyingState);
  6503. simulatedEvent.stop();
  6504. });
  6505. }
  6506. };
  6507. return derive(onFocusHandler.toArray().concat([
  6508. run(keydown(), function (component, simulatedEvent) {
  6509. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  6510. tryGoInsideComponent(component, simulatedEvent);
  6511. }, function (_) {
  6512. simulatedEvent.stop();
  6513. });
  6514. }),
  6515. run(keyup(), function (component, simulatedEvent) {
  6516. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  6517. simulatedEvent.stop();
  6518. });
  6519. })
  6520. ]));
  6521. };
  6522. var me = {
  6523. schema: schema,
  6524. processKey: processKey,
  6525. toEvents: toEvents
  6526. };
  6527. return me;
  6528. };
  6529. var create$3 = function (cyclicField) {
  6530. var schema = [
  6531. option('onEscape'),
  6532. option('onEnter'),
  6533. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  6534. defaulted$1('firstTabstop', 0),
  6535. defaulted$1('useTabstopAt', constant(true)),
  6536. option('visibilitySelector')
  6537. ].concat([cyclicField]);
  6538. var isVisible = function (tabbingConfig, element) {
  6539. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  6540. return closest$3(element, sel);
  6541. }).getOr(element);
  6542. return get$6(target) > 0;
  6543. };
  6544. var findInitial = function (component, tabbingConfig) {
  6545. var tabstops = descendants(component.element(), tabbingConfig.selector);
  6546. var visibles = filter(tabstops, function (elem) {
  6547. return isVisible(tabbingConfig, elem);
  6548. });
  6549. return Option.from(visibles[tabbingConfig.firstTabstop]);
  6550. };
  6551. var findCurrent = function (component, tabbingConfig) {
  6552. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  6553. return closest$3(elem, tabbingConfig.selector);
  6554. });
  6555. };
  6556. var isTabstop = function (tabbingConfig, element) {
  6557. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  6558. };
  6559. var focusIn = function (component, tabbingConfig) {
  6560. findInitial(component, tabbingConfig).each(function (target) {
  6561. tabbingConfig.focusManager.set(component, target);
  6562. });
  6563. };
  6564. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  6565. return cycle(tabstops, stopIndex, function (elem) {
  6566. return isTabstop(tabbingConfig, elem);
  6567. }).fold(function () {
  6568. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  6569. }, function (target) {
  6570. tabbingConfig.focusManager.set(component, target);
  6571. return Option.some(true);
  6572. });
  6573. };
  6574. var go = function (component, simulatedEvent, tabbingConfig, cycle) {
  6575. var tabstops = descendants(component.element(), tabbingConfig.selector);
  6576. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  6577. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  6578. return optStopIndex.bind(function (stopIndex) {
  6579. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  6580. });
  6581. });
  6582. };
  6583. var goBackwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  6584. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  6585. return go(component, simulatedEvent, tabbingConfig, navigate);
  6586. };
  6587. var goForwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  6588. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  6589. return go(component, simulatedEvent, tabbingConfig, navigate);
  6590. };
  6591. var execute = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  6592. return tabbingConfig.onEnter.bind(function (f) {
  6593. return f(component, simulatedEvent);
  6594. });
  6595. };
  6596. var exit = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  6597. return tabbingConfig.onEscape.bind(function (f) {
  6598. return f(component, simulatedEvent);
  6599. });
  6600. };
  6601. var getKeydownRules = constant([
  6602. rule(and([
  6603. isShift,
  6604. inSet(TAB())
  6605. ]), goBackwards),
  6606. rule(inSet(TAB()), goForwards),
  6607. rule(inSet(ESCAPE()), exit),
  6608. rule(and([
  6609. isNotShift,
  6610. inSet(ENTER())
  6611. ]), execute)
  6612. ]);
  6613. var getKeyupRules = constant([]);
  6614. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  6615. return Option.some(focusIn);
  6616. });
  6617. };
  6618. var AcyclicType = create$3(state$1('cyclic', constant(false)));
  6619. var CyclicType = create$3(state$1('cyclic', constant(true)));
  6620. var doDefaultExecute = function (component, simulatedEvent, focused) {
  6621. dispatch(component, focused, execute());
  6622. return Option.some(true);
  6623. };
  6624. var defaultExecute = function (component, simulatedEvent, focused) {
  6625. return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  6626. };
  6627. var stopEventForFirefox = function (component, simulatedEvent) {
  6628. return Option.some(true);
  6629. };
  6630. var schema$4 = [
  6631. defaulted$1('execute', defaultExecute),
  6632. defaulted$1('useSpace', false),
  6633. defaulted$1('useEnter', true),
  6634. defaulted$1('useControlEnter', false),
  6635. defaulted$1('useDown', false)
  6636. ];
  6637. var execute$1 = function (component, simulatedEvent, executeConfig) {
  6638. return executeConfig.execute(component, simulatedEvent, component.element());
  6639. };
  6640. var getKeydownRules = function (component, simulatedEvent, executeConfig, executeState) {
  6641. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  6642. var enterExec = executeConfig.useEnter ? ENTER() : [];
  6643. var downExec = executeConfig.useDown ? DOWN() : [];
  6644. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  6645. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  6646. isControl,
  6647. inSet(ENTER())
  6648. ]), execute$1)] : []);
  6649. };
  6650. var getKeyupRules = function (component, simulatedEvent, executeConfig, executeState) {
  6651. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  6652. };
  6653. var ExecutionType = typical(schema$4, NoState.init, getKeydownRules, getKeyupRules, function () {
  6654. return Option.none();
  6655. });
  6656. var flatgrid = function (spec) {
  6657. var dimensions = Cell(Option.none());
  6658. var setGridSize = function (numRows, numColumns) {
  6659. dimensions.set(Option.some({
  6660. numRows: constant(numRows),
  6661. numColumns: constant(numColumns)
  6662. }));
  6663. };
  6664. var getNumRows = function () {
  6665. return dimensions.get().map(function (d) {
  6666. return d.numRows();
  6667. });
  6668. };
  6669. var getNumColumns = function () {
  6670. return dimensions.get().map(function (d) {
  6671. return d.numColumns();
  6672. });
  6673. };
  6674. return nu$5({
  6675. readState: function () {
  6676. return dimensions.get().map(function (d) {
  6677. return {
  6678. numRows: d.numRows(),
  6679. numColumns: d.numColumns()
  6680. };
  6681. }).getOr({
  6682. numRows: '?',
  6683. numColumns: '?'
  6684. });
  6685. },
  6686. setGridSize: setGridSize,
  6687. getNumRows: getNumRows,
  6688. getNumColumns: getNumColumns
  6689. });
  6690. };
  6691. var init$2 = function (spec) {
  6692. return spec.state(spec);
  6693. };
  6694. var KeyingState = /*#__PURE__*/Object.freeze({
  6695. flatgrid: flatgrid,
  6696. init: init$2
  6697. });
  6698. var useH = function (movement) {
  6699. return function (component, simulatedEvent, config, state) {
  6700. var move = movement(component.element());
  6701. return use(move, component, simulatedEvent, config, state);
  6702. };
  6703. };
  6704. var west$2 = function (moveLeft, moveRight) {
  6705. var movement = onDirection(moveLeft, moveRight);
  6706. return useH(movement);
  6707. };
  6708. var east$2 = function (moveLeft, moveRight) {
  6709. var movement = onDirection(moveRight, moveLeft);
  6710. return useH(movement);
  6711. };
  6712. var useV = function (move) {
  6713. return function (component, simulatedEvent, config, state) {
  6714. return use(move, component, simulatedEvent, config, state);
  6715. };
  6716. };
  6717. var use = function (move, component, simulatedEvent, config, state) {
  6718. var outcome = config.focusManager.get(component).bind(function (focused) {
  6719. return move(component.element(), focused, config, state);
  6720. });
  6721. return outcome.map(function (newFocus) {
  6722. config.focusManager.set(component, newFocus);
  6723. return true;
  6724. });
  6725. };
  6726. var north$2 = useV;
  6727. var south$2 = useV;
  6728. var move = useV;
  6729. var isHidden = function (dom) {
  6730. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  6731. };
  6732. var isVisible = function (element) {
  6733. var dom = element.dom();
  6734. return !isHidden(dom);
  6735. };
  6736. var indexInfo = MixedBag([
  6737. 'index',
  6738. 'candidates'
  6739. ], []);
  6740. var locate$2 = function (candidates, predicate) {
  6741. return findIndex(candidates, predicate).map(function (index) {
  6742. return indexInfo({
  6743. index: index,
  6744. candidates: candidates
  6745. });
  6746. });
  6747. };
  6748. var locateVisible = function (container, current, selector) {
  6749. var predicate = curry(eq, current);
  6750. var candidates = descendants(container, selector);
  6751. var visible = filter(candidates, isVisible);
  6752. return locate$2(visible, predicate);
  6753. };
  6754. var findIndex$1 = function (elements, target) {
  6755. return findIndex(elements, function (elem) {
  6756. return eq(target, elem);
  6757. });
  6758. };
  6759. var withGrid = function (values, index, numCols, f) {
  6760. var oldRow = Math.floor(index / numCols);
  6761. var oldColumn = index % numCols;
  6762. return f(oldRow, oldColumn).bind(function (address) {
  6763. var newIndex = address.row() * numCols + address.column();
  6764. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  6765. });
  6766. };
  6767. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  6768. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6769. var onLastRow = oldRow === numRows - 1;
  6770. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  6771. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  6772. return Option.some({
  6773. row: constant(oldRow),
  6774. column: constant(newColumn)
  6775. });
  6776. });
  6777. };
  6778. var cycleVertical = function (values, index, numRows, numCols, delta) {
  6779. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6780. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  6781. var onLastRow = newRow === numRows - 1;
  6782. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  6783. var newCol = cap(oldColumn, 0, colsInRow - 1);
  6784. return Option.some({
  6785. row: constant(newRow),
  6786. column: constant(newCol)
  6787. });
  6788. });
  6789. };
  6790. var cycleRight = function (values, index, numRows, numCols) {
  6791. return cycleHorizontal(values, index, numRows, numCols, +1);
  6792. };
  6793. var cycleLeft = function (values, index, numRows, numCols) {
  6794. return cycleHorizontal(values, index, numRows, numCols, -1);
  6795. };
  6796. var cycleUp = function (values, index, numRows, numCols) {
  6797. return cycleVertical(values, index, numRows, numCols, -1);
  6798. };
  6799. var cycleDown = function (values, index, numRows, numCols) {
  6800. return cycleVertical(values, index, numRows, numCols, +1);
  6801. };
  6802. var schema$5 = [
  6803. strict$1('selector'),
  6804. defaulted$1('execute', defaultExecute),
  6805. onKeyboardHandler('onEscape'),
  6806. defaulted$1('captureTab', false),
  6807. initSize()
  6808. ];
  6809. var focusIn = function (component, gridConfig, gridState) {
  6810. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  6811. gridConfig.focusManager.set(component, first);
  6812. });
  6813. };
  6814. var findCurrent = function (component, gridConfig) {
  6815. return gridConfig.focusManager.get(component).bind(function (elem) {
  6816. return closest$3(elem, gridConfig.selector);
  6817. });
  6818. };
  6819. var execute$2 = function (component, simulatedEvent, gridConfig, gridState) {
  6820. return findCurrent(component, gridConfig).bind(function (focused) {
  6821. return gridConfig.execute(component, simulatedEvent, focused);
  6822. });
  6823. };
  6824. var doMove = function (cycle) {
  6825. return function (element, focused, gridConfig, gridState) {
  6826. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  6827. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  6828. });
  6829. };
  6830. };
  6831. var handleTab = function (component, simulatedEvent, gridConfig, gridState) {
  6832. return gridConfig.captureTab ? Option.some(true) : Option.none();
  6833. };
  6834. var doEscape = function (component, simulatedEvent, gridConfig, gridState) {
  6835. return gridConfig.onEscape(component, simulatedEvent);
  6836. };
  6837. var moveLeft = doMove(cycleLeft);
  6838. var moveRight = doMove(cycleRight);
  6839. var moveNorth = doMove(cycleUp);
  6840. var moveSouth = doMove(cycleDown);
  6841. var getKeydownRules$1 = constant([
  6842. rule(inSet(LEFT()), west$2(moveLeft, moveRight)),
  6843. rule(inSet(RIGHT()), east$2(moveLeft, moveRight)),
  6844. rule(inSet(UP()), north$2(moveNorth)),
  6845. rule(inSet(DOWN()), south$2(moveSouth)),
  6846. rule(and([
  6847. isShift,
  6848. inSet(TAB())
  6849. ]), handleTab),
  6850. rule(and([
  6851. isNotShift,
  6852. inSet(TAB())
  6853. ]), handleTab),
  6854. rule(inSet(ESCAPE()), doEscape),
  6855. rule(inSet(SPACE().concat(ENTER())), execute$2)
  6856. ]);
  6857. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6858. var FlatgridType = typical(schema$5, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  6859. return Option.some(focusIn);
  6860. });
  6861. var horizontal = function (container, selector, current, delta) {
  6862. var isDisabledButton = function (candidate) {
  6863. return name(candidate) === 'button' && get$2(candidate, 'disabled') === 'disabled';
  6864. };
  6865. var tryCycle = function (initial, index, candidates) {
  6866. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  6867. if (newIndex === initial) {
  6868. return Option.none();
  6869. } else {
  6870. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  6871. }
  6872. };
  6873. return locateVisible(container, current, selector).bind(function (identified) {
  6874. var index = identified.index();
  6875. var candidates = identified.candidates();
  6876. return tryCycle(index, index, candidates);
  6877. });
  6878. };
  6879. var schema$6 = [
  6880. strict$1('selector'),
  6881. defaulted$1('getInitial', Option.none),
  6882. defaulted$1('execute', defaultExecute),
  6883. onKeyboardHandler('onEscape'),
  6884. defaulted$1('executeOnMove', false),
  6885. defaulted$1('allowVertical', true)
  6886. ];
  6887. var findCurrent$1 = function (component, flowConfig) {
  6888. return flowConfig.focusManager.get(component).bind(function (elem) {
  6889. return closest$3(elem, flowConfig.selector);
  6890. });
  6891. };
  6892. var execute$3 = function (component, simulatedEvent, flowConfig) {
  6893. return findCurrent$1(component, flowConfig).bind(function (focused) {
  6894. return flowConfig.execute(component, simulatedEvent, focused);
  6895. });
  6896. };
  6897. var focusIn$1 = function (component, flowConfig) {
  6898. flowConfig.getInitial(component).orThunk(function () {
  6899. return descendant$1(component.element(), flowConfig.selector);
  6900. }).each(function (first) {
  6901. flowConfig.focusManager.set(component, first);
  6902. });
  6903. };
  6904. var moveLeft$1 = function (element, focused, info) {
  6905. return horizontal(element, info.selector, focused, -1);
  6906. };
  6907. var moveRight$1 = function (element, focused, info) {
  6908. return horizontal(element, info.selector, focused, +1);
  6909. };
  6910. var doMove$1 = function (movement) {
  6911. return function (component, simulatedEvent, flowConfig) {
  6912. return movement(component, simulatedEvent, flowConfig).bind(function () {
  6913. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  6914. });
  6915. };
  6916. };
  6917. var doEscape$1 = function (component, simulatedEvent, flowConfig, _flowState) {
  6918. return flowConfig.onEscape(component, simulatedEvent);
  6919. };
  6920. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  6921. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  6922. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  6923. return [
  6924. rule(inSet(westMovers), doMove$1(west$2(moveLeft$1, moveRight$1))),
  6925. rule(inSet(eastMovers), doMove$1(east$2(moveLeft$1, moveRight$1))),
  6926. rule(inSet(ENTER()), execute$3),
  6927. rule(inSet(SPACE()), execute$3),
  6928. rule(inSet(ESCAPE()), doEscape$1)
  6929. ];
  6930. };
  6931. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6932. var FlowType = typical(schema$6, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  6933. return Option.some(focusIn$1);
  6934. });
  6935. var outcome = MixedBag([
  6936. 'rowIndex',
  6937. 'columnIndex',
  6938. 'cell'
  6939. ], []);
  6940. var toCell = function (matrix, rowIndex, columnIndex) {
  6941. return Option.from(matrix[rowIndex]).bind(function (row) {
  6942. return Option.from(row[columnIndex]).map(function (cell) {
  6943. return outcome({
  6944. rowIndex: rowIndex,
  6945. columnIndex: columnIndex,
  6946. cell: cell
  6947. });
  6948. });
  6949. });
  6950. };
  6951. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  6952. var row = matrix[rowIndex];
  6953. var colsInRow = row.length;
  6954. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  6955. return toCell(matrix, rowIndex, newColIndex);
  6956. };
  6957. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  6958. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  6959. var colsInNextRow = matrix[nextRowIndex].length;
  6960. var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
  6961. return toCell(matrix, nextRowIndex, nextColIndex);
  6962. };
  6963. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  6964. var row = matrix[rowIndex];
  6965. var colsInRow = row.length;
  6966. var newColIndex = cap(startCol + deltaCol, 0, colsInRow - 1);
  6967. return toCell(matrix, rowIndex, newColIndex);
  6968. };
  6969. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  6970. var nextRowIndex = cap(startRow + deltaRow, 0, matrix.length - 1);
  6971. var colsInNextRow = matrix[nextRowIndex].length;
  6972. var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
  6973. return toCell(matrix, nextRowIndex, nextColIndex);
  6974. };
  6975. var cycleRight$1 = function (matrix, startRow, startCol) {
  6976. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  6977. };
  6978. var cycleLeft$1 = function (matrix, startRow, startCol) {
  6979. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  6980. };
  6981. var cycleUp$1 = function (matrix, startRow, startCol) {
  6982. return cycleVertical$1(matrix, startCol, startRow, -1);
  6983. };
  6984. var cycleDown$1 = function (matrix, startRow, startCol) {
  6985. return cycleVertical$1(matrix, startCol, startRow, +1);
  6986. };
  6987. var moveLeft$2 = function (matrix, startRow, startCol) {
  6988. return moveHorizontal(matrix, startRow, startCol, -1);
  6989. };
  6990. var moveRight$2 = function (matrix, startRow, startCol) {
  6991. return moveHorizontal(matrix, startRow, startCol, +1);
  6992. };
  6993. var moveUp = function (matrix, startRow, startCol) {
  6994. return moveVertical(matrix, startCol, startRow, -1);
  6995. };
  6996. var moveDown = function (matrix, startRow, startCol) {
  6997. return moveVertical(matrix, startCol, startRow, +1);
  6998. };
  6999. var schema$7 = [
  7000. strictObjOf('selectors', [
  7001. strict$1('row'),
  7002. strict$1('cell')
  7003. ]),
  7004. defaulted$1('cycles', true),
  7005. defaulted$1('previousSelector', Option.none),
  7006. defaulted$1('execute', defaultExecute)
  7007. ];
  7008. var focusIn$2 = function (component, matrixConfig) {
  7009. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  7010. var selectors = matrixConfig.selectors;
  7011. return descendant$1(component.element(), selectors.cell);
  7012. });
  7013. focused.each(function (cell) {
  7014. matrixConfig.focusManager.set(component, cell);
  7015. });
  7016. };
  7017. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  7018. return search(component.element()).bind(function (focused) {
  7019. return matrixConfig.execute(component, simulatedEvent, focused);
  7020. });
  7021. };
  7022. var toMatrix = function (rows, matrixConfig) {
  7023. return map(rows, function (row) {
  7024. return descendants(row, matrixConfig.selectors.cell);
  7025. });
  7026. };
  7027. var doMove$2 = function (ifCycle, ifMove) {
  7028. return function (element, focused, matrixConfig) {
  7029. var move = matrixConfig.cycles ? ifCycle : ifMove;
  7030. return closest$3(focused, matrixConfig.selectors.row).bind(function (inRow) {
  7031. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  7032. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  7033. var allRows = descendants(element, matrixConfig.selectors.row);
  7034. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  7035. var matrix = toMatrix(allRows, matrixConfig);
  7036. return move(matrix, rowIndex, colIndex).map(function (next) {
  7037. return next.cell();
  7038. });
  7039. });
  7040. });
  7041. });
  7042. };
  7043. };
  7044. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  7045. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  7046. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  7047. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  7048. var getKeydownRules$3 = constant([
  7049. rule(inSet(LEFT()), west$2(moveLeft$3, moveRight$3)),
  7050. rule(inSet(RIGHT()), east$2(moveLeft$3, moveRight$3)),
  7051. rule(inSet(UP()), north$2(moveNorth$1)),
  7052. rule(inSet(DOWN()), south$2(moveSouth$1)),
  7053. rule(inSet(SPACE().concat(ENTER())), execute$4)
  7054. ]);
  7055. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  7056. var MatrixType = typical(schema$7, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  7057. return Option.some(focusIn$2);
  7058. });
  7059. var schema$8 = [
  7060. strict$1('selector'),
  7061. defaulted$1('execute', defaultExecute),
  7062. defaulted$1('moveOnTab', false)
  7063. ];
  7064. var execute$5 = function (component, simulatedEvent, menuConfig) {
  7065. return menuConfig.focusManager.get(component).bind(function (focused) {
  7066. return menuConfig.execute(component, simulatedEvent, focused);
  7067. });
  7068. };
  7069. var focusIn$3 = function (component, menuConfig) {
  7070. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  7071. menuConfig.focusManager.set(component, first);
  7072. });
  7073. };
  7074. var moveUp$1 = function (element, focused, info) {
  7075. return horizontal(element, info.selector, focused, -1);
  7076. };
  7077. var moveDown$1 = function (element, focused, info) {
  7078. return horizontal(element, info.selector, focused, +1);
  7079. };
  7080. var fireShiftTab = function (component, simulatedEvent, menuConfig) {
  7081. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig) : Option.none();
  7082. };
  7083. var fireTab = function (component, simulatedEvent, menuConfig) {
  7084. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig) : Option.none();
  7085. };
  7086. var getKeydownRules$4 = constant([
  7087. rule(inSet(UP()), move(moveUp$1)),
  7088. rule(inSet(DOWN()), move(moveDown$1)),
  7089. rule(and([
  7090. isShift,
  7091. inSet(TAB())
  7092. ]), fireShiftTab),
  7093. rule(and([
  7094. isNotShift,
  7095. inSet(TAB())
  7096. ]), fireTab),
  7097. rule(inSet(ENTER()), execute$5),
  7098. rule(inSet(SPACE()), execute$5)
  7099. ]);
  7100. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  7101. var MenuType = typical(schema$8, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  7102. return Option.some(focusIn$3);
  7103. });
  7104. var schema$9 = [
  7105. onKeyboardHandler('onSpace'),
  7106. onKeyboardHandler('onEnter'),
  7107. onKeyboardHandler('onShiftEnter'),
  7108. onKeyboardHandler('onLeft'),
  7109. onKeyboardHandler('onRight'),
  7110. onKeyboardHandler('onTab'),
  7111. onKeyboardHandler('onShiftTab'),
  7112. onKeyboardHandler('onUp'),
  7113. onKeyboardHandler('onDown'),
  7114. onKeyboardHandler('onEscape'),
  7115. defaulted$1('stopSpaceKeyup', false),
  7116. option('focusIn')
  7117. ];
  7118. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  7119. return [
  7120. rule(inSet(SPACE()), specialInfo.onSpace),
  7121. rule(and([
  7122. isNotShift,
  7123. inSet(ENTER())
  7124. ]), specialInfo.onEnter),
  7125. rule(and([
  7126. isShift,
  7127. inSet(ENTER())
  7128. ]), specialInfo.onShiftEnter),
  7129. rule(and([
  7130. isShift,
  7131. inSet(TAB())
  7132. ]), specialInfo.onShiftTab),
  7133. rule(and([
  7134. isNotShift,
  7135. inSet(TAB())
  7136. ]), specialInfo.onTab),
  7137. rule(inSet(UP()), specialInfo.onUp),
  7138. rule(inSet(DOWN()), specialInfo.onDown),
  7139. rule(inSet(LEFT()), specialInfo.onLeft),
  7140. rule(inSet(RIGHT()), specialInfo.onRight),
  7141. rule(inSet(SPACE()), specialInfo.onSpace),
  7142. rule(inSet(ESCAPE()), specialInfo.onEscape)
  7143. ];
  7144. };
  7145. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  7146. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  7147. };
  7148. var SpecialType = typical(schema$9, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  7149. return specialInfo.focusIn;
  7150. });
  7151. var acyclic = AcyclicType.schema();
  7152. var cyclic = CyclicType.schema();
  7153. var flow = FlowType.schema();
  7154. var flatgrid$1 = FlatgridType.schema();
  7155. var matrix = MatrixType.schema();
  7156. var execution = ExecutionType.schema();
  7157. var menu = MenuType.schema();
  7158. var special = SpecialType.schema();
  7159. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7160. acyclic: acyclic,
  7161. cyclic: cyclic,
  7162. flow: flow,
  7163. flatgrid: flatgrid$1,
  7164. matrix: matrix,
  7165. execution: execution,
  7166. menu: menu,
  7167. special: special
  7168. });
  7169. var Keying = createModes$1({
  7170. branchKey: 'mode',
  7171. branches: KeyboardBranches,
  7172. name: 'keying',
  7173. active: {
  7174. events: function (keyingConfig, keyingState) {
  7175. var handler = keyingConfig.handler;
  7176. return handler.toEvents(keyingConfig, keyingState);
  7177. }
  7178. },
  7179. apis: {
  7180. focusIn: function (component, keyConfig, keyState) {
  7181. keyConfig.sendFocusIn(keyConfig).fold(function () {
  7182. component.getSystem().triggerFocus(component.element(), component.element());
  7183. }, function (sendFocusIn) {
  7184. sendFocusIn(component, keyConfig, keyState);
  7185. });
  7186. },
  7187. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7188. if (!hasKey$1(keyState, 'setGridSize')) {
  7189. domGlobals.console.error('Layout does not support setGridSize');
  7190. } else {
  7191. keyState.setGridSize(numRows, numColumns);
  7192. }
  7193. }
  7194. },
  7195. state: KeyingState
  7196. });
  7197. var set$5 = function (component, replaceConfig, replaceState, data) {
  7198. preserve(function () {
  7199. var newChildren = map(data, component.getSystem().build);
  7200. replaceChildren(component, newChildren);
  7201. }, component.element());
  7202. };
  7203. var insert = function (component, replaceConfig, insertion, childSpec) {
  7204. var child = component.getSystem().build(childSpec);
  7205. attachWith(component, child, insertion);
  7206. };
  7207. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  7208. insert(component, replaceConfig, append, appendee);
  7209. };
  7210. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  7211. insert(component, replaceConfig, prepend, prependee);
  7212. };
  7213. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  7214. var children = contents(component);
  7215. var foundChild = find(children, function (child) {
  7216. return eq(removee.element(), child.element());
  7217. });
  7218. foundChild.each(detach);
  7219. };
  7220. var contents = function (component, replaceConfig) {
  7221. return component.components();
  7222. };
  7223. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7224. var children = contents(component);
  7225. return Option.from(children[replaceeIndex]).map(function (replacee) {
  7226. remove$7(component, replaceConfig, replaceState, replacee);
  7227. replacer.each(function (r) {
  7228. insert(component, replaceConfig, function (p, c) {
  7229. appendAt(p, c, replaceeIndex);
  7230. }, r);
  7231. });
  7232. return replacee;
  7233. });
  7234. };
  7235. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7236. var children = contents(component);
  7237. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  7238. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7239. });
  7240. };
  7241. var ReplaceApis = /*#__PURE__*/Object.freeze({
  7242. append: append$2,
  7243. prepend: prepend$1,
  7244. remove: remove$7,
  7245. replaceAt: replaceAt,
  7246. replaceBy: replaceBy,
  7247. set: set$5,
  7248. contents: contents
  7249. });
  7250. var Replacing = create$1({
  7251. fields: [],
  7252. name: 'replacing',
  7253. apis: ReplaceApis
  7254. });
  7255. var events$4 = function (name, eventHandlers) {
  7256. var events = derive(eventHandlers);
  7257. return create$1({
  7258. fields: [strict$1('enabled')],
  7259. name: name,
  7260. active: { events: constant(events) }
  7261. });
  7262. };
  7263. var config = function (name, eventHandlers) {
  7264. var me = events$4(name, eventHandlers);
  7265. return {
  7266. key: name,
  7267. value: {
  7268. config: {},
  7269. me: me,
  7270. configAsRaw: constant({}),
  7271. initialConfig: {},
  7272. state: NoState
  7273. }
  7274. };
  7275. };
  7276. var focus$2 = function (component, focusConfig) {
  7277. if (!focusConfig.ignore) {
  7278. focus$1(component.element());
  7279. focusConfig.onFocus(component);
  7280. }
  7281. };
  7282. var blur$1 = function (component, focusConfig) {
  7283. if (!focusConfig.ignore) {
  7284. blur(component.element());
  7285. }
  7286. };
  7287. var isFocused = function (component) {
  7288. return hasFocus(component.element());
  7289. };
  7290. var FocusApis = /*#__PURE__*/Object.freeze({
  7291. focus: focus$2,
  7292. blur: blur$1,
  7293. isFocused: isFocused
  7294. });
  7295. var exhibit$1 = function (base, focusConfig) {
  7296. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  7297. return nu$6(mod);
  7298. };
  7299. var events$5 = function (focusConfig) {
  7300. return derive([run(focus(), function (component, simulatedEvent) {
  7301. focus$2(component, focusConfig);
  7302. simulatedEvent.stop();
  7303. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  7304. simulatedEvent.event().prevent();
  7305. })] : []));
  7306. };
  7307. var ActiveFocus = /*#__PURE__*/Object.freeze({
  7308. exhibit: exhibit$1,
  7309. events: events$5
  7310. });
  7311. var FocusSchema = [
  7312. onHandler('onFocus'),
  7313. defaulted$1('stopMousedown', false),
  7314. defaulted$1('ignore', false)
  7315. ];
  7316. var Focusing = create$1({
  7317. fields: FocusSchema,
  7318. name: 'focusing',
  7319. active: ActiveFocus,
  7320. apis: FocusApis
  7321. });
  7322. var updateAriaState = function (component, toggleConfig, toggleState) {
  7323. var ariaInfo = toggleConfig.aria;
  7324. ariaInfo.update(component, ariaInfo, toggleState.get());
  7325. };
  7326. var updateClass = function (component, toggleConfig, toggleState) {
  7327. toggleConfig.toggleClass.each(function (toggleClass) {
  7328. if (toggleState.get()) {
  7329. add$2(component.element(), toggleClass);
  7330. } else {
  7331. remove$4(component.element(), toggleClass);
  7332. }
  7333. });
  7334. };
  7335. var toggle = function (component, toggleConfig, toggleState) {
  7336. set$6(component, toggleConfig, toggleState, !toggleState.get());
  7337. };
  7338. var on$1 = function (component, toggleConfig, toggleState) {
  7339. toggleState.set(true);
  7340. updateClass(component, toggleConfig, toggleState);
  7341. updateAriaState(component, toggleConfig, toggleState);
  7342. };
  7343. var off = function (component, toggleConfig, toggleState) {
  7344. toggleState.set(false);
  7345. updateClass(component, toggleConfig, toggleState);
  7346. updateAriaState(component, toggleConfig, toggleState);
  7347. };
  7348. var set$6 = function (component, toggleConfig, toggleState, state) {
  7349. var action = state ? on$1 : off;
  7350. action(component, toggleConfig, toggleState);
  7351. };
  7352. var isOn = function (component, toggleConfig, toggleState) {
  7353. return toggleState.get();
  7354. };
  7355. var onLoad$4 = function (component, toggleConfig, toggleState) {
  7356. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  7357. };
  7358. var ToggleApis = /*#__PURE__*/Object.freeze({
  7359. onLoad: onLoad$4,
  7360. toggle: toggle,
  7361. isOn: isOn,
  7362. on: on$1,
  7363. off: off,
  7364. set: set$6
  7365. });
  7366. var exhibit$2 = function (base, toggleConfig, toggleState) {
  7367. return nu$6({});
  7368. };
  7369. var events$6 = function (toggleConfig, toggleState) {
  7370. var execute = executeEvent(toggleConfig, toggleState, toggle);
  7371. var load = loadEvent(toggleConfig, toggleState, onLoad$4);
  7372. return derive(flatten([
  7373. toggleConfig.toggleOnExecute ? [execute] : [],
  7374. [load]
  7375. ]));
  7376. };
  7377. var ActiveToggle = /*#__PURE__*/Object.freeze({
  7378. exhibit: exhibit$2,
  7379. events: events$6
  7380. });
  7381. var SetupBehaviourCellState = function (initialState) {
  7382. var init = function () {
  7383. var cell = Cell(initialState);
  7384. var get = function () {
  7385. return cell.get();
  7386. };
  7387. var set = function (newState) {
  7388. return cell.set(newState);
  7389. };
  7390. var clear = function () {
  7391. return cell.set(initialState);
  7392. };
  7393. var readState = function () {
  7394. return cell.get();
  7395. };
  7396. return {
  7397. get: get,
  7398. set: set,
  7399. clear: clear,
  7400. readState: readState
  7401. };
  7402. };
  7403. return { init: init };
  7404. };
  7405. var updatePressed = function (component, ariaInfo, status) {
  7406. set$1(component.element(), 'aria-pressed', status);
  7407. if (ariaInfo.syncWithExpanded) {
  7408. updateExpanded(component, ariaInfo, status);
  7409. }
  7410. };
  7411. var updateSelected = function (component, ariaInfo, status) {
  7412. set$1(component.element(), 'aria-selected', status);
  7413. };
  7414. var updateChecked = function (component, ariaInfo, status) {
  7415. set$1(component.element(), 'aria-checked', status);
  7416. };
  7417. var updateExpanded = function (component, ariaInfo, status) {
  7418. set$1(component.element(), 'aria-expanded', status);
  7419. };
  7420. var ToggleSchema = [
  7421. defaulted$1('selected', false),
  7422. option('toggleClass'),
  7423. defaulted$1('toggleOnExecute', true),
  7424. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  7425. pressed: [
  7426. defaulted$1('syncWithExpanded', false),
  7427. output('update', updatePressed)
  7428. ],
  7429. checked: [output('update', updateChecked)],
  7430. expanded: [output('update', updateExpanded)],
  7431. selected: [output('update', updateSelected)],
  7432. none: [output('update', noop)]
  7433. }))
  7434. ];
  7435. var Toggling = create$1({
  7436. fields: ToggleSchema,
  7437. name: 'toggling',
  7438. active: ActiveToggle,
  7439. apis: ToggleApis,
  7440. state: SetupBehaviourCellState(false)
  7441. });
  7442. var hoverEvent = 'alloy.item-hover';
  7443. var focusEvent = 'alloy.item-focus';
  7444. var onHover = function (item) {
  7445. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  7446. if (!Focusing.isFocused(item)) {
  7447. Focusing.focus(item);
  7448. }
  7449. emitWith(item, hoverEvent, { item: item });
  7450. }
  7451. };
  7452. var onFocus = function (item) {
  7453. emitWith(item, focusEvent, { item: item });
  7454. };
  7455. var hover = constant(hoverEvent);
  7456. var focus$3 = constant(focusEvent);
  7457. var builder = function (detail) {
  7458. return {
  7459. dom: detail.dom,
  7460. 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 } : {}) }),
  7461. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7462. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7463. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7464. }),
  7465. Focusing.config({
  7466. ignore: detail.ignoreFocus,
  7467. stopMousedown: detail.ignoreFocus,
  7468. onFocus: function (component) {
  7469. onFocus(component);
  7470. }
  7471. }),
  7472. Keying.config({ mode: 'execution' }),
  7473. Representing.config({
  7474. store: {
  7475. mode: 'memory',
  7476. initialValue: detail.data
  7477. }
  7478. }),
  7479. config('item-type-events', [
  7480. run(tapOrClick(), emitExecute),
  7481. cutter(mousedown()),
  7482. run(mouseover(), onHover),
  7483. run(focusItem(), Focusing.focus)
  7484. ])
  7485. ]),
  7486. components: detail.components,
  7487. eventOrder: detail.eventOrder
  7488. };
  7489. };
  7490. var schema$a = [
  7491. strict$1('data'),
  7492. strict$1('components'),
  7493. strict$1('dom'),
  7494. defaulted$1('hasSubmenu', false),
  7495. option('toggling'),
  7496. SketchBehaviours.field('itemBehaviours', [
  7497. Toggling,
  7498. Focusing,
  7499. Keying,
  7500. Representing
  7501. ]),
  7502. defaulted$1('ignoreFocus', false),
  7503. defaulted$1('domModification', {}),
  7504. output('builder', builder),
  7505. defaulted$1('eventOrder', {})
  7506. ];
  7507. var builder$1 = function (detail) {
  7508. return {
  7509. dom: detail.dom,
  7510. components: detail.components,
  7511. events: derive([stopper(focusItem())])
  7512. };
  7513. };
  7514. var schema$b = [
  7515. strict$1('dom'),
  7516. strict$1('components'),
  7517. output('builder', builder$1)
  7518. ];
  7519. var owner$2 = function () {
  7520. return 'item-widget';
  7521. };
  7522. var parts = constant([required({
  7523. name: 'widget',
  7524. overrides: function (detail) {
  7525. return {
  7526. behaviours: derive$1([Representing.config({
  7527. store: {
  7528. mode: 'manual',
  7529. getValue: function (component) {
  7530. return detail.data;
  7531. },
  7532. setValue: function () {
  7533. }
  7534. }
  7535. })])
  7536. };
  7537. }
  7538. })]);
  7539. var builder$2 = function (detail) {
  7540. var subs = substitutes(owner$2(), detail, parts());
  7541. var components$1 = components(owner$2(), detail, subs.internals());
  7542. var focusWidget = function (component) {
  7543. return getPart(component, detail, 'widget').map(function (widget) {
  7544. Keying.focusIn(widget);
  7545. return widget;
  7546. });
  7547. };
  7548. var onHorizontalArrow = function (component, simulatedEvent) {
  7549. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  7550. if (detail.autofocus) {
  7551. simulatedEvent.setSource(component.element());
  7552. return Option.none();
  7553. } else {
  7554. return Option.none();
  7555. }
  7556. }();
  7557. };
  7558. return {
  7559. dom: detail.dom,
  7560. components: components$1,
  7561. domModification: detail.domModification,
  7562. events: derive([
  7563. runOnExecute(function (component, simulatedEvent) {
  7564. focusWidget(component).each(function (widget) {
  7565. simulatedEvent.stop();
  7566. });
  7567. }),
  7568. run(mouseover(), onHover),
  7569. run(focusItem(), function (component, simulatedEvent) {
  7570. if (detail.autofocus) {
  7571. focusWidget(component);
  7572. } else {
  7573. Focusing.focus(component);
  7574. }
  7575. })
  7576. ]),
  7577. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7578. Representing.config({
  7579. store: {
  7580. mode: 'memory',
  7581. initialValue: detail.data
  7582. }
  7583. }),
  7584. Focusing.config({
  7585. ignore: detail.ignoreFocus,
  7586. onFocus: function (component) {
  7587. onFocus(component);
  7588. }
  7589. }),
  7590. Keying.config({
  7591. mode: 'special',
  7592. focusIn: detail.autofocus ? function (component) {
  7593. focusWidget(component);
  7594. } : revoke(),
  7595. onLeft: onHorizontalArrow,
  7596. onRight: onHorizontalArrow,
  7597. onEscape: function (component, simulatedEvent) {
  7598. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7599. Focusing.focus(component);
  7600. return Option.some(true);
  7601. } else if (detail.autofocus) {
  7602. simulatedEvent.setSource(component.element());
  7603. return Option.none();
  7604. } else {
  7605. return Option.none();
  7606. }
  7607. }
  7608. })
  7609. ])
  7610. };
  7611. };
  7612. var schema$c = [
  7613. strict$1('uid'),
  7614. strict$1('data'),
  7615. strict$1('components'),
  7616. strict$1('dom'),
  7617. defaulted$1('autofocus', false),
  7618. defaulted$1('ignoreFocus', false),
  7619. SketchBehaviours.field('widgetBehaviours', [
  7620. Representing,
  7621. Focusing,
  7622. Keying
  7623. ]),
  7624. defaulted$1('domModification', {}),
  7625. defaultUidsSchema(parts()),
  7626. output('builder', builder$2)
  7627. ];
  7628. var itemSchema$1 = choose$1('type', {
  7629. widget: schema$c,
  7630. item: schema$a,
  7631. separator: schema$b
  7632. });
  7633. var configureGrid = function (detail, movementInfo) {
  7634. return {
  7635. mode: 'flatgrid',
  7636. selector: '.' + detail.markers.item,
  7637. initSize: {
  7638. numColumns: movementInfo.initSize.numColumns,
  7639. numRows: movementInfo.initSize.numRows
  7640. },
  7641. focusManager: detail.focusManager
  7642. };
  7643. };
  7644. var configureMatrix = function (detail, movementInfo) {
  7645. return {
  7646. mode: 'matrix',
  7647. selectors: {
  7648. row: movementInfo.rowSelector,
  7649. cell: '.' + detail.markers.item
  7650. },
  7651. focusManager: detail.focusManager
  7652. };
  7653. };
  7654. var configureMenu = function (detail, movementInfo) {
  7655. return {
  7656. mode: 'menu',
  7657. selector: '.' + detail.markers.item,
  7658. moveOnTab: movementInfo.moveOnTab,
  7659. focusManager: detail.focusManager
  7660. };
  7661. };
  7662. var parts$1 = constant([group({
  7663. factory: {
  7664. sketch: function (spec) {
  7665. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  7666. return itemInfo.builder(itemInfo);
  7667. }
  7668. },
  7669. name: 'items',
  7670. unit: 'item',
  7671. defaults: function (detail, u) {
  7672. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  7673. },
  7674. overrides: function (detail, u) {
  7675. return {
  7676. type: u.type,
  7677. ignoreFocus: detail.fakeFocus,
  7678. domModification: { classes: [detail.markers.item] }
  7679. };
  7680. }
  7681. })]);
  7682. var schema$d = constant([
  7683. strict$1('value'),
  7684. strict$1('items'),
  7685. strict$1('dom'),
  7686. strict$1('components'),
  7687. defaulted$1('eventOrder', {}),
  7688. field$1('menuBehaviours', [
  7689. Highlighting,
  7690. Representing,
  7691. Composing,
  7692. Keying
  7693. ]),
  7694. defaultedOf('movement', {
  7695. mode: 'menu',
  7696. moveOnTab: true
  7697. }, choose$1('mode', {
  7698. grid: [
  7699. initSize(),
  7700. output('config', configureGrid)
  7701. ],
  7702. matrix: [
  7703. output('config', configureMatrix),
  7704. strict$1('rowSelector')
  7705. ],
  7706. menu: [
  7707. defaulted$1('moveOnTab', true),
  7708. output('config', configureMenu)
  7709. ]
  7710. })),
  7711. itemMarkers(),
  7712. defaulted$1('fakeFocus', false),
  7713. defaulted$1('focusManager', dom()),
  7714. onHandler('onHighlight')
  7715. ]);
  7716. var focus$4 = constant('alloy.menu-focus');
  7717. var make$1 = function (detail, components, spec, externals) {
  7718. return {
  7719. uid: detail.uid,
  7720. dom: detail.dom,
  7721. markers: detail.markers,
  7722. behaviours: augment(detail.menuBehaviours, [
  7723. Highlighting.config({
  7724. highlightClass: detail.markers.selectedItem,
  7725. itemClass: detail.markers.item,
  7726. onHighlight: detail.onHighlight
  7727. }),
  7728. Representing.config({
  7729. store: {
  7730. mode: 'memory',
  7731. initialValue: detail.value
  7732. }
  7733. }),
  7734. Composing.config({ find: Option.some }),
  7735. Keying.config(detail.movement.config(detail, detail.movement))
  7736. ]),
  7737. events: derive([
  7738. run(focus$3(), function (menu, simulatedEvent) {
  7739. var event = simulatedEvent.event();
  7740. menu.getSystem().getByDom(event.target()).each(function (item) {
  7741. Highlighting.highlight(menu, item);
  7742. simulatedEvent.stop();
  7743. emitWith(menu, focus$4(), {
  7744. menu: menu,
  7745. item: item
  7746. });
  7747. });
  7748. }),
  7749. run(hover(), function (menu, simulatedEvent) {
  7750. var item = simulatedEvent.event().item();
  7751. Highlighting.highlight(menu, item);
  7752. })
  7753. ]),
  7754. components: components,
  7755. eventOrder: detail.eventOrder,
  7756. domModification: { attributes: { role: 'menu' } }
  7757. };
  7758. };
  7759. var Menu = composite$1({
  7760. name: 'Menu',
  7761. configFields: schema$d(),
  7762. partFields: parts$1(),
  7763. factory: make$1
  7764. });
  7765. var transpose = function (obj) {
  7766. return tupleMap(obj, function (v, k) {
  7767. return {
  7768. k: v,
  7769. v: k
  7770. };
  7771. });
  7772. };
  7773. var trace = function (items, byItem, byMenu, finish) {
  7774. return readOptFrom$1(byMenu, finish).bind(function (triggerItem) {
  7775. return readOptFrom$1(items, triggerItem).bind(function (triggerMenu) {
  7776. var rest = trace(items, byItem, byMenu, triggerMenu);
  7777. return Option.some([triggerMenu].concat(rest));
  7778. });
  7779. }).getOr([]);
  7780. };
  7781. var generate$5 = function (menus, expansions) {
  7782. var items = {};
  7783. each$1(menus, function (menuItems, menu) {
  7784. each(menuItems, function (item) {
  7785. items[item] = menu;
  7786. });
  7787. });
  7788. var byItem = expansions;
  7789. var byMenu = transpose(expansions);
  7790. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  7791. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  7792. });
  7793. return map$1(items, function (menu) {
  7794. return readOptFrom$1(menuPaths, menu).getOr([menu]);
  7795. });
  7796. };
  7797. var init$3 = function () {
  7798. var expansions = Cell({});
  7799. var menus = Cell({});
  7800. var paths = Cell({});
  7801. var primary = Cell(Option.none());
  7802. var directory = Cell({});
  7803. var clear = function () {
  7804. expansions.set({});
  7805. menus.set({});
  7806. paths.set({});
  7807. primary.set(Option.none());
  7808. };
  7809. var isClear = function () {
  7810. return primary.get().isNone();
  7811. };
  7812. var setMenuBuilt = function (menuName, built) {
  7813. var _a;
  7814. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  7815. type: 'prepared',
  7816. menu: built
  7817. }, _a)));
  7818. };
  7819. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  7820. primary.set(Option.some(sPrimary));
  7821. expansions.set(sExpansions);
  7822. menus.set(sMenus);
  7823. directory.set(dir);
  7824. var sPaths = generate$5(dir, sExpansions);
  7825. paths.set(sPaths);
  7826. };
  7827. var getTriggeringItem = function (menuValue) {
  7828. return find$1(expansions.get(), function (v, k) {
  7829. return v === menuValue;
  7830. });
  7831. };
  7832. var getTriggerData = function (menuValue, getItemByValue, path) {
  7833. return getPreparedMenu(menuValue).bind(function (menu) {
  7834. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  7835. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  7836. return {
  7837. triggeredMenu: menu,
  7838. triggeringItem: triggeredItem,
  7839. triggeringPath: path
  7840. };
  7841. });
  7842. });
  7843. });
  7844. };
  7845. var getTriggeringPath = function (itemValue, getItemByValue) {
  7846. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  7847. return getPreparedMenu(menuValue).isSome();
  7848. });
  7849. return readOptFrom$1(paths.get(), itemValue).bind(function (path) {
  7850. var revPath = reverse(extraPath.concat(path));
  7851. var triggers = bind(revPath, function (menuValue, menuIndex) {
  7852. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  7853. return primary.get().is(menuValue) ? [] : [Option.none()];
  7854. }, function (data) {
  7855. return [Option.some(data)];
  7856. });
  7857. });
  7858. return sequence(triggers);
  7859. });
  7860. };
  7861. var expand = function (itemValue) {
  7862. return readOptFrom$1(expansions.get(), itemValue).map(function (menu) {
  7863. var current = readOptFrom$1(paths.get(), itemValue).getOr([]);
  7864. return [menu].concat(current);
  7865. });
  7866. };
  7867. var collapse = function (itemValue) {
  7868. return readOptFrom$1(paths.get(), itemValue).bind(function (path) {
  7869. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  7870. });
  7871. };
  7872. var refresh = function (itemValue) {
  7873. return readOptFrom$1(paths.get(), itemValue);
  7874. };
  7875. var getPreparedMenu = function (menuValue) {
  7876. return lookupMenu(menuValue).bind(extractPreparedMenu);
  7877. };
  7878. var lookupMenu = function (menuValue) {
  7879. return readOptFrom$1(menus.get(), menuValue);
  7880. };
  7881. var lookupItem = function (itemValue) {
  7882. return readOptFrom$1(expansions.get(), itemValue);
  7883. };
  7884. var otherMenus = function (path) {
  7885. var menuValues = directory.get();
  7886. return difference(keys(menuValues), path);
  7887. };
  7888. var getPrimary = function () {
  7889. return primary.get().bind(getPreparedMenu);
  7890. };
  7891. var getMenus = function () {
  7892. return menus.get();
  7893. };
  7894. return {
  7895. setMenuBuilt: setMenuBuilt,
  7896. setContents: setContents,
  7897. expand: expand,
  7898. refresh: refresh,
  7899. collapse: collapse,
  7900. lookupMenu: lookupMenu,
  7901. lookupItem: lookupItem,
  7902. otherMenus: otherMenus,
  7903. getPrimary: getPrimary,
  7904. getMenus: getMenus,
  7905. clear: clear,
  7906. isClear: isClear,
  7907. getTriggeringPath: getTriggeringPath
  7908. };
  7909. };
  7910. var extractPreparedMenu = function (prep) {
  7911. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  7912. };
  7913. var LayeredState = {
  7914. init: init$3,
  7915. extractPreparedMenu: extractPreparedMenu
  7916. };
  7917. var make$2 = function (detail, rawUiSpec) {
  7918. var submenuParentItems = Cell(Option.none());
  7919. var buildMenus = function (container, primaryName, menus) {
  7920. return map$1(menus, function (spec, name) {
  7921. var makeSketch = function () {
  7922. return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), {
  7923. value: name,
  7924. items: spec.items,
  7925. markers: detail.markers,
  7926. fakeFocus: detail.fakeFocus,
  7927. onHighlight: detail.onHighlight,
  7928. focusManager: detail.fakeFocus ? highlights() : dom()
  7929. }));
  7930. };
  7931. return name === primaryName ? {
  7932. type: 'prepared',
  7933. menu: container.getSystem().build(makeSketch())
  7934. } : {
  7935. type: 'notbuilt',
  7936. nbMenu: makeSketch
  7937. };
  7938. });
  7939. };
  7940. var layeredState = LayeredState.init();
  7941. var setup = function (container) {
  7942. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  7943. var directory = toDirectory();
  7944. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  7945. return layeredState.getPrimary();
  7946. };
  7947. var getItemValue = function (item) {
  7948. return Representing.getValue(item).value;
  7949. };
  7950. var getItemByValue = function (container, menus, itemValue) {
  7951. return findMap(menus, function (menu) {
  7952. if (!menu.getSystem().isConnected()) {
  7953. return Option.none();
  7954. }
  7955. var candidates = Highlighting.getCandidates(menu);
  7956. return find(candidates, function (c) {
  7957. return getItemValue(c) === itemValue;
  7958. });
  7959. });
  7960. };
  7961. var toDirectory = function (container) {
  7962. return map$1(detail.data.menus, function (data, menuName) {
  7963. return bind(data.items, function (item) {
  7964. return item.type === 'separator' ? [] : [item.data.value];
  7965. });
  7966. });
  7967. };
  7968. var setActiveMenu = function (container, menu) {
  7969. Highlighting.highlight(container, menu);
  7970. Highlighting.getHighlighted(menu).orThunk(function () {
  7971. return Highlighting.getFirst(menu);
  7972. }).each(function (item) {
  7973. dispatch(container, item.element(), focusItem());
  7974. });
  7975. };
  7976. var getMenus = function (state, menuValues) {
  7977. return cat(map(menuValues, function (mv) {
  7978. return state.lookupMenu(mv).bind(function (prep) {
  7979. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  7980. });
  7981. }));
  7982. };
  7983. var closeOthers = function (container, state, path) {
  7984. var others = getMenus(state, state.otherMenus(path));
  7985. each(others, function (o) {
  7986. remove$5(o.element(), [detail.markers.backgroundMenu]);
  7987. if (!detail.stayInDom) {
  7988. Replacing.remove(container, o);
  7989. }
  7990. });
  7991. };
  7992. var getSubmenuParents = function (container) {
  7993. return submenuParentItems.get().getOrThunk(function () {
  7994. var r = {};
  7995. var items = descendants(container.element(), '.' + detail.markers.item);
  7996. var parentItems = filter(items, function (i) {
  7997. return get$2(i, 'aria-haspopup') === 'true';
  7998. });
  7999. each(parentItems, function (i) {
  8000. container.getSystem().getByDom(i).each(function (itemComp) {
  8001. var key = getItemValue(itemComp);
  8002. r[key] = itemComp;
  8003. });
  8004. });
  8005. submenuParentItems.set(Option.some(r));
  8006. return r;
  8007. });
  8008. };
  8009. var updateAriaExpansions = function (container, path) {
  8010. var parentItems = getSubmenuParents(container);
  8011. each$1(parentItems, function (v, k) {
  8012. var expanded = contains(path, k);
  8013. set$1(v.element(), 'aria-expanded', expanded);
  8014. });
  8015. };
  8016. var updateMenuPath = function (container, state, path) {
  8017. return Option.from(path[0]).bind(function (latestMenuName) {
  8018. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8019. if (menuPrep.type === 'notbuilt') {
  8020. return Option.none();
  8021. } else {
  8022. var activeMenu = menuPrep.menu;
  8023. var rest = getMenus(state, path.slice(1));
  8024. each(rest, function (r) {
  8025. add$2(r.element(), detail.markers.backgroundMenu);
  8026. });
  8027. if (!inBody(activeMenu.element())) {
  8028. Replacing.append(container, premade$1(activeMenu));
  8029. }
  8030. remove$5(activeMenu.element(), [detail.markers.backgroundMenu]);
  8031. setActiveMenu(container, activeMenu);
  8032. closeOthers(container, state, path);
  8033. return Option.some(activeMenu);
  8034. }
  8035. });
  8036. });
  8037. };
  8038. var ExpandHighlightDecision;
  8039. (function (ExpandHighlightDecision) {
  8040. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8041. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8042. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8043. var buildIfRequired = function (container, menuName, menuPrep) {
  8044. if (menuPrep.type === 'notbuilt') {
  8045. var menu = container.getSystem().build(menuPrep.nbMenu());
  8046. layeredState.setMenuBuilt(menuName, menu);
  8047. return menu;
  8048. } else {
  8049. return menuPrep.menu;
  8050. }
  8051. };
  8052. var expandRight = function (container, item, decision) {
  8053. if (decision === void 0) {
  8054. decision = ExpandHighlightDecision.HighlightSubmenu;
  8055. }
  8056. var value = getItemValue(item);
  8057. return layeredState.expand(value).bind(function (path) {
  8058. updateAriaExpansions(container, path);
  8059. return Option.from(path[0]).bind(function (menuName) {
  8060. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8061. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8062. if (!inBody(activeMenu.element())) {
  8063. Replacing.append(container, premade$1(activeMenu));
  8064. }
  8065. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8066. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8067. Highlighting.highlightFirst(activeMenu);
  8068. return updateMenuPath(container, layeredState, path);
  8069. } else {
  8070. Highlighting.dehighlightAll(activeMenu);
  8071. return Option.some(item);
  8072. }
  8073. });
  8074. });
  8075. });
  8076. };
  8077. var collapseLeft = function (container, item) {
  8078. var value = getItemValue(item);
  8079. return layeredState.collapse(value).bind(function (path) {
  8080. updateAriaExpansions(container, path);
  8081. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8082. detail.onCollapseMenu(container, item, activeMenu);
  8083. return activeMenu;
  8084. });
  8085. });
  8086. };
  8087. var updateView = function (container, item) {
  8088. var value = getItemValue(item);
  8089. return layeredState.refresh(value).bind(function (path) {
  8090. updateAriaExpansions(container, path);
  8091. return updateMenuPath(container, layeredState, path);
  8092. });
  8093. };
  8094. var onRight = function (container, item) {
  8095. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8096. };
  8097. var onLeft = function (container, item) {
  8098. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  8099. };
  8100. var onEscape = function (container, item) {
  8101. return collapseLeft(container, item).orThunk(function () {
  8102. return detail.onEscape(container, item).map(function () {
  8103. return container;
  8104. });
  8105. });
  8106. };
  8107. var keyOnItem = function (f) {
  8108. return function (container, simulatedEvent) {
  8109. return closest$3(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8110. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  8111. return f(container, item).map(function () {
  8112. return true;
  8113. });
  8114. });
  8115. });
  8116. };
  8117. };
  8118. var events = derive([
  8119. run(focus$4(), function (sandbox, simulatedEvent) {
  8120. var item = simulatedEvent.event().item();
  8121. layeredState.lookupItem(getItemValue(item)).each(function () {
  8122. var menu = simulatedEvent.event().menu();
  8123. Highlighting.highlight(sandbox, menu);
  8124. var value = getItemValue(simulatedEvent.event().item());
  8125. layeredState.refresh(value).each(function (path) {
  8126. return closeOthers(sandbox, layeredState, path);
  8127. });
  8128. });
  8129. }),
  8130. runOnExecute(function (component, simulatedEvent) {
  8131. var target = simulatedEvent.event().target();
  8132. component.getSystem().getByDom(target).each(function (item) {
  8133. var itemValue = getItemValue(item);
  8134. if (itemValue.indexOf('collapse-item') === 0) {
  8135. collapseLeft(component, item);
  8136. }
  8137. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8138. detail.onExecute(component, item);
  8139. }, function () {
  8140. });
  8141. });
  8142. }),
  8143. runOnAttached(function (container, simulatedEvent) {
  8144. setup(container).each(function (primary) {
  8145. Replacing.append(container, premade$1(primary));
  8146. detail.onOpenMenu(container, primary);
  8147. if (detail.highlightImmediately) {
  8148. setActiveMenu(container, primary);
  8149. }
  8150. });
  8151. })
  8152. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8153. var item = simulatedEvent.event().item();
  8154. updateView(sandbox, item);
  8155. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8156. detail.onHover(sandbox, item);
  8157. })] : []));
  8158. var getActiveItem = function (container) {
  8159. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8160. };
  8161. var collapseMenuApi = function (container) {
  8162. getActiveItem(container).each(function (currentItem) {
  8163. collapseLeft(container, currentItem);
  8164. });
  8165. };
  8166. var highlightPrimary = function (container) {
  8167. layeredState.getPrimary().each(function (primary) {
  8168. setActiveMenu(container, primary);
  8169. });
  8170. };
  8171. var extractMenuFromContainer = function (container) {
  8172. return Option.from(container.components()[0]).filter(function (comp) {
  8173. return get$2(comp.element(), 'role') === 'menu';
  8174. });
  8175. };
  8176. var repositionMenus = function (container) {
  8177. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8178. return getActiveItem(container).bind(function (currentItem) {
  8179. var itemValue = getItemValue(currentItem);
  8180. var allMenus = values(layeredState.getMenus());
  8181. var preparedMenus = cat(map(allMenus, LayeredState.extractPreparedMenu));
  8182. return layeredState.getTriggeringPath(itemValue, function (v) {
  8183. return getItemByValue(container, preparedMenus, v);
  8184. });
  8185. }).map(function (triggeringPath) {
  8186. return {
  8187. primary: primary,
  8188. triggeringPath: triggeringPath
  8189. };
  8190. });
  8191. });
  8192. maybeActivePrimary.fold(function () {
  8193. extractMenuFromContainer(container).each(function (primaryMenu) {
  8194. detail.onRepositionMenu(container, primaryMenu, []);
  8195. });
  8196. }, function (_a) {
  8197. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8198. detail.onRepositionMenu(container, primary, triggeringPath);
  8199. });
  8200. };
  8201. var apis = {
  8202. collapseMenu: collapseMenuApi,
  8203. highlightPrimary: highlightPrimary,
  8204. repositionMenus: repositionMenus
  8205. };
  8206. return {
  8207. uid: detail.uid,
  8208. dom: detail.dom,
  8209. markers: detail.markers,
  8210. behaviours: augment(detail.tmenuBehaviours, [
  8211. Keying.config({
  8212. mode: 'special',
  8213. onRight: keyOnItem(onRight),
  8214. onLeft: keyOnItem(onLeft),
  8215. onEscape: keyOnItem(onEscape),
  8216. focusIn: function (container, keyInfo) {
  8217. layeredState.getPrimary().each(function (primary) {
  8218. dispatch(container, primary.element(), focusItem());
  8219. });
  8220. }
  8221. }),
  8222. Highlighting.config({
  8223. highlightClass: detail.markers.selectedMenu,
  8224. itemClass: detail.markers.menu
  8225. }),
  8226. Composing.config({
  8227. find: function (container) {
  8228. return Highlighting.getHighlighted(container);
  8229. }
  8230. }),
  8231. Replacing.config({})
  8232. ]),
  8233. eventOrder: detail.eventOrder,
  8234. apis: apis,
  8235. events: events
  8236. };
  8237. };
  8238. var collapseItem = constant('collapse-item');
  8239. var tieredData = function (primary, menus, expansions) {
  8240. return {
  8241. primary: primary,
  8242. menus: menus,
  8243. expansions: expansions
  8244. };
  8245. };
  8246. var singleData = function (name, menu) {
  8247. return {
  8248. primary: name,
  8249. menus: wrap$1(name, menu),
  8250. expansions: {}
  8251. };
  8252. };
  8253. var collapseItem$1 = function (text) {
  8254. return {
  8255. value: generate$1(collapseItem()),
  8256. meta: { text: text }
  8257. };
  8258. };
  8259. var tieredMenu = single$2({
  8260. name: 'TieredMenu',
  8261. configFields: [
  8262. onStrictKeyboardHandler('onExecute'),
  8263. onStrictKeyboardHandler('onEscape'),
  8264. onStrictHandler('onOpenMenu'),
  8265. onStrictHandler('onOpenSubmenu'),
  8266. onStrictHandler('onRepositionMenu'),
  8267. onHandler('onCollapseMenu'),
  8268. defaulted$1('highlightImmediately', true),
  8269. strictObjOf('data', [
  8270. strict$1('primary'),
  8271. strict$1('menus'),
  8272. strict$1('expansions')
  8273. ]),
  8274. defaulted$1('fakeFocus', false),
  8275. onHandler('onHighlight'),
  8276. onHandler('onHover'),
  8277. tieredMenuMarkers(),
  8278. strict$1('dom'),
  8279. defaulted$1('navigateOnHover', true),
  8280. defaulted$1('stayInDom', false),
  8281. field$1('tmenuBehaviours', [
  8282. Keying,
  8283. Highlighting,
  8284. Composing,
  8285. Replacing
  8286. ]),
  8287. defaulted$1('eventOrder', {})
  8288. ],
  8289. apis: {
  8290. collapseMenu: function (apis, tmenu) {
  8291. apis.collapseMenu(tmenu);
  8292. },
  8293. highlightPrimary: function (apis, tmenu) {
  8294. apis.highlightPrimary(tmenu);
  8295. },
  8296. repositionMenus: function (apis, tmenu) {
  8297. apis.repositionMenus(tmenu);
  8298. }
  8299. },
  8300. factory: make$2,
  8301. extraApis: {
  8302. tieredData: tieredData,
  8303. singleData: singleData,
  8304. collapseItem: collapseItem$1
  8305. }
  8306. });
  8307. var makeMenu = function (detail, menuSandbox, anchor, menuSpec, getBounds) {
  8308. var lazySink = function () {
  8309. return detail.lazySink(menuSandbox);
  8310. };
  8311. var layouts = menuSpec.type === 'horizontal' ? {
  8312. layouts: {
  8313. onLtr: function () {
  8314. return belowOrAbove();
  8315. },
  8316. onRtl: function () {
  8317. return belowOrAboveRtl();
  8318. }
  8319. }
  8320. } : {};
  8321. var isFirstTierSubmenu = function (triggeringPaths) {
  8322. return triggeringPaths.length === 2;
  8323. };
  8324. var getSubmenuLayouts = function (triggeringPaths) {
  8325. return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  8326. };
  8327. return tieredMenu.sketch({
  8328. dom: { tag: 'div' },
  8329. data: menuSpec.data,
  8330. markers: menuSpec.menu.markers,
  8331. onEscape: function () {
  8332. Sandboxing.close(menuSandbox);
  8333. detail.onEscape.map(function (handler) {
  8334. return handler(menuSandbox);
  8335. });
  8336. return Option.some(true);
  8337. },
  8338. onExecute: function () {
  8339. return Option.some(true);
  8340. },
  8341. onOpenMenu: function (tmenu, menu) {
  8342. Positioning.positionWithinBounds(lazySink().getOrDie(), anchor, menu, getBounds());
  8343. },
  8344. onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  8345. var sink = lazySink().getOrDie();
  8346. Positioning.position(sink, __assign({
  8347. anchor: 'submenu',
  8348. item: item
  8349. }, getSubmenuLayouts(triggeringPaths)), submenu);
  8350. },
  8351. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  8352. var sink = lazySink().getOrDie();
  8353. Positioning.positionWithinBounds(sink, anchor, primaryMenu, getBounds());
  8354. each(submenuTriggers, function (st) {
  8355. var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  8356. Positioning.position(sink, __assign({
  8357. anchor: 'submenu',
  8358. item: st.triggeringItem
  8359. }, submenuLayouts), st.triggeredMenu);
  8360. });
  8361. }
  8362. });
  8363. };
  8364. var factory = function (detail, spec) {
  8365. var isPartOfRelated = function (sandbox, queryElem) {
  8366. var related = detail.getRelated(sandbox);
  8367. return related.exists(function (rel) {
  8368. return isPartOf(rel, queryElem);
  8369. });
  8370. };
  8371. var setContent = function (sandbox, thing) {
  8372. Sandboxing.setContent(sandbox, thing);
  8373. };
  8374. var showAt = function (sandbox, anchor, thing) {
  8375. showWithin(sandbox, anchor, thing, Option.none());
  8376. };
  8377. var showWithin = function (sandbox, anchor, thing, boxElement) {
  8378. showWithinBounds(sandbox, anchor, thing, function () {
  8379. return boxElement.map(function (elem) {
  8380. return box(elem);
  8381. });
  8382. });
  8383. };
  8384. var showWithinBounds = function (sandbox, anchor, thing, getBounds) {
  8385. var sink = detail.lazySink(sandbox).getOrDie();
  8386. Sandboxing.openWhileCloaked(sandbox, thing, function () {
  8387. return Positioning.positionWithinBounds(sink, anchor, sandbox, getBounds());
  8388. });
  8389. Representing.setValue(sandbox, Option.some({
  8390. mode: 'position',
  8391. anchor: anchor,
  8392. getBounds: getBounds
  8393. }));
  8394. };
  8395. var showMenuAt = function (sandbox, anchor, menuSpec) {
  8396. showMenuWithinBounds(sandbox, anchor, menuSpec, function () {
  8397. return Option.none();
  8398. });
  8399. };
  8400. var showMenuWithinBounds = function (sandbox, anchor, menuSpec, getBounds) {
  8401. var menu = makeMenu(detail, sandbox, anchor, menuSpec, getBounds);
  8402. Sandboxing.open(sandbox, menu);
  8403. Representing.setValue(sandbox, Option.some({
  8404. mode: 'menu',
  8405. menu: menu
  8406. }));
  8407. };
  8408. var hide = function (sandbox) {
  8409. Representing.setValue(sandbox, Option.none());
  8410. Sandboxing.close(sandbox);
  8411. };
  8412. var getContent = function (sandbox) {
  8413. return Sandboxing.getState(sandbox);
  8414. };
  8415. var reposition = function (sandbox) {
  8416. if (Sandboxing.isOpen(sandbox)) {
  8417. Representing.getValue(sandbox).each(function (state) {
  8418. switch (state.mode) {
  8419. case 'menu':
  8420. Sandboxing.getState(sandbox).each(function (tmenu) {
  8421. tieredMenu.repositionMenus(tmenu);
  8422. });
  8423. break;
  8424. case 'position':
  8425. var sink = detail.lazySink(sandbox).getOrDie();
  8426. Positioning.positionWithinBounds(sink, state.anchor, sandbox, state.getBounds());
  8427. break;
  8428. }
  8429. });
  8430. }
  8431. };
  8432. var apis = {
  8433. setContent: setContent,
  8434. showAt: showAt,
  8435. showWithin: showWithin,
  8436. showWithinBounds: showWithinBounds,
  8437. showMenuAt: showMenuAt,
  8438. showMenuWithinBounds: showMenuWithinBounds,
  8439. hide: hide,
  8440. getContent: getContent,
  8441. reposition: reposition,
  8442. isOpen: Sandboxing.isOpen
  8443. };
  8444. return {
  8445. uid: detail.uid,
  8446. dom: detail.dom,
  8447. behaviours: augment(detail.inlineBehaviours, [
  8448. Sandboxing.config({
  8449. isPartOf: function (sandbox, data, queryElem) {
  8450. return isPartOf(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  8451. },
  8452. getAttachPoint: function (sandbox) {
  8453. return detail.lazySink(sandbox).getOrDie();
  8454. },
  8455. onOpen: function (sandbox) {
  8456. detail.onShow(sandbox);
  8457. },
  8458. onClose: function (sandbox) {
  8459. detail.onHide(sandbox);
  8460. }
  8461. }),
  8462. Representing.config({
  8463. store: {
  8464. mode: 'memory',
  8465. initialValue: Option.none()
  8466. }
  8467. }),
  8468. Receiving.config({
  8469. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: constant(false) }, detail.fireDismissalEventInstead.map(function (fe) {
  8470. return { fireEventInstead: { event: fe.event } };
  8471. }).getOr({})))), receivingChannel$1(__assign(__assign({ isExtraPart: constant(false) }, detail.fireRepositionEventInstead.map(function (fe) {
  8472. return { fireEventInstead: { event: fe.event } };
  8473. }).getOr({})), { doReposition: reposition })))
  8474. })
  8475. ]),
  8476. eventOrder: detail.eventOrder,
  8477. apis: apis
  8478. };
  8479. };
  8480. var InlineView = single$2({
  8481. name: 'InlineView',
  8482. configFields: [
  8483. strict$1('lazySink'),
  8484. onHandler('onShow'),
  8485. onHandler('onHide'),
  8486. optionFunction('onEscape'),
  8487. field$1('inlineBehaviours', [
  8488. Sandboxing,
  8489. Representing,
  8490. Receiving
  8491. ]),
  8492. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  8493. optionObjOf('fireRepositionEventInstead', [defaulted$1('event', repositionRequested())]),
  8494. defaulted$1('getRelated', Option.none),
  8495. defaulted$1('eventOrder', Option.none)
  8496. ],
  8497. factory: factory,
  8498. apis: {
  8499. showAt: function (apis, component, anchor, thing) {
  8500. apis.showAt(component, anchor, thing);
  8501. },
  8502. showWithin: function (apis, component, anchor, thing, boxElement) {
  8503. apis.showWithin(component, anchor, thing, boxElement);
  8504. },
  8505. showWithinBounds: function (apis, component, anchor, thing, bounds) {
  8506. apis.showWithinBounds(component, anchor, thing, bounds);
  8507. },
  8508. showMenuAt: function (apis, component, anchor, menuSpec) {
  8509. apis.showMenuAt(component, anchor, menuSpec);
  8510. },
  8511. showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  8512. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  8513. },
  8514. hide: function (apis, component) {
  8515. apis.hide(component);
  8516. },
  8517. isOpen: function (apis, component) {
  8518. return apis.isOpen(component);
  8519. },
  8520. getContent: function (apis, component) {
  8521. return apis.getContent(component);
  8522. },
  8523. setContent: function (apis, component, thing) {
  8524. apis.setContent(component, thing);
  8525. },
  8526. reposition: function (apis, component) {
  8527. apis.reposition(component);
  8528. }
  8529. }
  8530. });
  8531. var westEdgeX$1 = function (anchor) {
  8532. return anchor.x();
  8533. };
  8534. var middleX$1 = function (anchor, element) {
  8535. return anchor.x() + anchor.width() / 2 - element.width() / 2;
  8536. };
  8537. var eastEdgeX$1 = function (anchor, element) {
  8538. return anchor.x() + anchor.width() - element.width();
  8539. };
  8540. var northY$2 = function (anchor) {
  8541. return anchor.y();
  8542. };
  8543. var southY$2 = function (anchor, element) {
  8544. return anchor.y() + anchor.height() - element.height();
  8545. };
  8546. var southeast$3 = function (anchor, element, bubbles) {
  8547. return nu$7(westEdgeX$1(anchor), southY$2(anchor, element), bubbles.innerSoutheast(), southeast(), 'layout-se');
  8548. };
  8549. var southwest$3 = function (anchor, element, bubbles) {
  8550. return nu$7(eastEdgeX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouthwest(), southwest(), 'layout-sw');
  8551. };
  8552. var northeast$3 = function (anchor, element, bubbles) {
  8553. return nu$7(westEdgeX$1(anchor), northY$2(anchor), bubbles.innerNortheast(), northeast(), 'layout-ne');
  8554. };
  8555. var northwest$3 = function (anchor, element, bubbles) {
  8556. return nu$7(eastEdgeX$1(anchor, element), northY$2(anchor), bubbles.innerNorthwest(), northwest(), 'layout-nw');
  8557. };
  8558. var north$3 = function (anchor, element, bubbles) {
  8559. return nu$7(middleX$1(anchor, element), northY$2(anchor), bubbles.innerNorth(), north(), 'layout-n');
  8560. };
  8561. var south$3 = function (anchor, element, bubbles) {
  8562. return nu$7(middleX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouth(), south(), 'layout-s');
  8563. };
  8564. var events$7 = function (optAction) {
  8565. var executeHandler = function (action) {
  8566. return run(execute(), function (component, simulatedEvent) {
  8567. action(component);
  8568. simulatedEvent.stop();
  8569. });
  8570. };
  8571. var onClick = function (component, simulatedEvent) {
  8572. simulatedEvent.stop();
  8573. emitExecute(component);
  8574. };
  8575. var onMousedown = function (component, simulatedEvent) {
  8576. simulatedEvent.cut();
  8577. };
  8578. var pointerEvents = detect$3().deviceType.isTouch() ? [run(tap(), onClick)] : [
  8579. run(click(), onClick),
  8580. run(mousedown(), onMousedown)
  8581. ];
  8582. return derive(flatten([
  8583. optAction.map(executeHandler).toArray(),
  8584. pointerEvents
  8585. ]));
  8586. };
  8587. var factory$1 = function (detail) {
  8588. var events = events$7(detail.action);
  8589. var tag = detail.dom.tag;
  8590. var lookupAttr = function (attr) {
  8591. return readOptFrom$1(detail.dom, 'attributes').bind(function (attrs) {
  8592. return readOptFrom$1(attrs, attr);
  8593. });
  8594. };
  8595. var getModAttributes = function () {
  8596. if (tag === 'button') {
  8597. var type = lookupAttr('type').getOr('button');
  8598. var roleAttrs = lookupAttr('role').map(function (role) {
  8599. return { role: role };
  8600. }).getOr({});
  8601. return __assign({ type: type }, roleAttrs);
  8602. } else {
  8603. var role = lookupAttr('role').getOr('button');
  8604. return { role: role };
  8605. }
  8606. };
  8607. return {
  8608. uid: detail.uid,
  8609. dom: detail.dom,
  8610. components: detail.components,
  8611. events: events,
  8612. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  8613. Focusing.config({}),
  8614. Keying.config({
  8615. mode: 'execution',
  8616. useSpace: true,
  8617. useEnter: true
  8618. })
  8619. ]),
  8620. domModification: { attributes: getModAttributes() },
  8621. eventOrder: detail.eventOrder
  8622. };
  8623. };
  8624. var Button = single$2({
  8625. name: 'Button',
  8626. factory: factory$1,
  8627. configFields: [
  8628. defaulted$1('uid', undefined),
  8629. strict$1('dom'),
  8630. defaulted$1('components', []),
  8631. SketchBehaviours.field('buttonBehaviours', [
  8632. Focusing,
  8633. Keying
  8634. ]),
  8635. option('action'),
  8636. option('role'),
  8637. defaulted$1('eventOrder', {})
  8638. ]
  8639. });
  8640. var record = function (spec) {
  8641. var uid = isSketchSpec(spec) && hasKey$1(spec, 'uid') ? spec.uid : generate$2('memento');
  8642. var get = function (anyInSystem) {
  8643. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  8644. };
  8645. var getOpt = function (anyInSystem) {
  8646. return anyInSystem.getSystem().getByUid(uid).toOption();
  8647. };
  8648. var asSpec = function () {
  8649. return __assign(__assign({}, spec), { uid: uid });
  8650. };
  8651. return {
  8652. get: get,
  8653. getOpt: getOpt,
  8654. asSpec: asSpec
  8655. };
  8656. };
  8657. var defaultIcon = function (icons) {
  8658. return Option.from(icons()['temporary-placeholder']).getOr('!not found!');
  8659. };
  8660. var get$c = function (name, icons) {
  8661. return Option.from(icons()[name]).getOrThunk(function () {
  8662. return defaultIcon(icons);
  8663. });
  8664. };
  8665. var getOr = function (name, icons, fallback) {
  8666. return Option.from(icons()[name]).or(fallback).getOrThunk(function () {
  8667. return defaultIcon(icons);
  8668. });
  8669. };
  8670. var getFirst$1 = function (names, icons) {
  8671. return findMap(names, function (name) {
  8672. return Option.from(icons()[name]);
  8673. }).getOrThunk(function () {
  8674. return defaultIcon(icons);
  8675. });
  8676. };
  8677. var notificationIconMap = {
  8678. success: 'checkmark',
  8679. error: 'warning',
  8680. err: 'error',
  8681. warning: 'warning',
  8682. warn: 'warning',
  8683. info: 'info'
  8684. };
  8685. var factory$2 = function (detail) {
  8686. var memBannerText = record({
  8687. dom: {
  8688. tag: 'p',
  8689. innerHtml: detail.translationProvider(detail.text)
  8690. },
  8691. behaviours: derive$1([Replacing.config({})])
  8692. });
  8693. var renderPercentBar = function (percent) {
  8694. return {
  8695. dom: {
  8696. tag: 'div',
  8697. classes: ['tox-bar'],
  8698. attributes: { style: 'width: ' + percent + '%' }
  8699. }
  8700. };
  8701. };
  8702. var renderPercentText = function (percent) {
  8703. return {
  8704. dom: {
  8705. tag: 'div',
  8706. classes: ['tox-text'],
  8707. innerHtml: percent + '%'
  8708. }
  8709. };
  8710. };
  8711. var memBannerProgress = record({
  8712. dom: {
  8713. tag: 'div',
  8714. classes: detail.progress ? [
  8715. 'tox-progress-bar',
  8716. 'tox-progress-indicator'
  8717. ] : ['tox-progress-bar']
  8718. },
  8719. components: [
  8720. {
  8721. dom: {
  8722. tag: 'div',
  8723. classes: ['tox-bar-container']
  8724. },
  8725. components: [renderPercentBar(0)]
  8726. },
  8727. renderPercentText(0)
  8728. ],
  8729. behaviours: derive$1([Replacing.config({})])
  8730. });
  8731. var updateProgress = function (comp, percent) {
  8732. if (comp.getSystem().isConnected()) {
  8733. memBannerProgress.getOpt(comp).each(function (progress) {
  8734. Replacing.set(progress, [
  8735. {
  8736. dom: {
  8737. tag: 'div',
  8738. classes: ['tox-bar-container']
  8739. },
  8740. components: [renderPercentBar(percent)]
  8741. },
  8742. renderPercentText(percent)
  8743. ]);
  8744. });
  8745. }
  8746. };
  8747. var updateText = function (comp, text$1) {
  8748. if (comp.getSystem().isConnected()) {
  8749. var banner = memBannerText.get(comp);
  8750. Replacing.set(banner, [text(text$1)]);
  8751. }
  8752. };
  8753. var apis = {
  8754. updateProgress: updateProgress,
  8755. updateText: updateText
  8756. };
  8757. var iconChoices = flatten([
  8758. detail.icon.toArray(),
  8759. detail.level.toArray(),
  8760. detail.level.bind(function (level) {
  8761. return Option.from(notificationIconMap[level]);
  8762. }).toArray()
  8763. ]);
  8764. return {
  8765. uid: detail.uid,
  8766. dom: {
  8767. tag: 'div',
  8768. attributes: { role: 'alert' },
  8769. classes: detail.level.map(function (level) {
  8770. return [
  8771. 'tox-notification',
  8772. 'tox-notification--in',
  8773. 'tox-notification--' + level
  8774. ];
  8775. }).getOr([
  8776. 'tox-notification',
  8777. 'tox-notification--in'
  8778. ])
  8779. },
  8780. components: [
  8781. {
  8782. dom: {
  8783. tag: 'div',
  8784. classes: ['tox-notification__icon'],
  8785. innerHtml: getFirst$1(iconChoices, detail.iconProvider)
  8786. }
  8787. },
  8788. {
  8789. dom: {
  8790. tag: 'div',
  8791. classes: ['tox-notification__body']
  8792. },
  8793. components: [memBannerText.asSpec()],
  8794. behaviours: derive$1([Replacing.config({})])
  8795. }
  8796. ].concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(Button.sketch({
  8797. dom: {
  8798. tag: 'button',
  8799. classes: [
  8800. 'tox-notification__dismiss',
  8801. 'tox-button',
  8802. 'tox-button--naked',
  8803. 'tox-button--icon'
  8804. ]
  8805. },
  8806. components: [{
  8807. dom: {
  8808. tag: 'div',
  8809. classes: ['tox-icon'],
  8810. innerHtml: get$c('close', detail.iconProvider),
  8811. attributes: { 'aria-label': detail.translationProvider('Close') }
  8812. }
  8813. }],
  8814. action: function (comp) {
  8815. detail.onAction(comp);
  8816. }
  8817. })),
  8818. apis: apis
  8819. };
  8820. };
  8821. var Notification = single$2({
  8822. name: 'Notification',
  8823. factory: factory$2,
  8824. configFields: [
  8825. option('level'),
  8826. strict$1('progress'),
  8827. strict$1('icon'),
  8828. strict$1('onAction'),
  8829. strict$1('text'),
  8830. strict$1('iconProvider'),
  8831. strict$1('translationProvider')
  8832. ],
  8833. apis: {
  8834. updateProgress: function (apis, comp, percent) {
  8835. apis.updateProgress(comp, percent);
  8836. },
  8837. updateText: function (apis, comp, text) {
  8838. apis.updateText(comp, text);
  8839. }
  8840. }
  8841. });
  8842. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  8843. function NotificationManagerImpl (editor, extras, uiMothership) {
  8844. var backstage = extras.backstage;
  8845. var getLayoutDirection = function (rel) {
  8846. switch (rel) {
  8847. case 'bc-bc':
  8848. return south$3;
  8849. case 'tc-tc':
  8850. return north$3;
  8851. case 'tc-bc':
  8852. return north$1;
  8853. case 'bc-tc':
  8854. default:
  8855. return south$1;
  8856. }
  8857. };
  8858. var prePositionNotifications = function (notifications) {
  8859. each(notifications, function (notification) {
  8860. return notification.moveTo(0, 0);
  8861. });
  8862. };
  8863. var positionNotifications = function (notifications) {
  8864. if (notifications.length > 0) {
  8865. head(notifications).each(function (firstItem) {
  8866. return firstItem.moveRel(null, 'banner');
  8867. });
  8868. each(notifications, function (notification, index) {
  8869. if (index > 0) {
  8870. notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  8871. }
  8872. });
  8873. }
  8874. };
  8875. var reposition = function (notifications) {
  8876. prePositionNotifications(notifications);
  8877. positionNotifications(notifications);
  8878. };
  8879. var open = function (settings, closeCallback) {
  8880. var close = function () {
  8881. closeCallback();
  8882. InlineView.hide(notificationWrapper);
  8883. };
  8884. var notification = build$1(Notification.sketch({
  8885. text: settings.text,
  8886. level: contains([
  8887. 'success',
  8888. 'error',
  8889. 'warning',
  8890. 'warn',
  8891. 'info'
  8892. ], settings.type) ? settings.type : undefined,
  8893. progress: settings.progressBar === true,
  8894. icon: Option.from(settings.icon),
  8895. onAction: close,
  8896. iconProvider: backstage.shared.providers.icons,
  8897. translationProvider: backstage.shared.providers.translate
  8898. }));
  8899. var notificationWrapper = build$1(InlineView.sketch({
  8900. dom: {
  8901. tag: 'div',
  8902. classes: ['tox-notifications-container']
  8903. },
  8904. lazySink: extras.backstage.shared.getSink,
  8905. fireDismissalEventInstead: {}
  8906. }));
  8907. uiMothership.add(notificationWrapper);
  8908. if (settings.timeout > 0) {
  8909. global$2.setTimeout(function () {
  8910. close();
  8911. }, settings.timeout);
  8912. }
  8913. return {
  8914. close: close,
  8915. moveTo: function (x, y) {
  8916. InlineView.showAt(notificationWrapper, {
  8917. anchor: 'makeshift',
  8918. x: x,
  8919. y: y
  8920. }, premade$1(notification));
  8921. },
  8922. moveRel: function (element, rel) {
  8923. if (rel !== 'banner') {
  8924. var layoutDirection_1 = getLayoutDirection(rel);
  8925. var nodeAnchor = {
  8926. anchor: 'node',
  8927. root: body(),
  8928. node: Option.some(Element.fromDom(element)),
  8929. layouts: {
  8930. onRtl: function () {
  8931. return [layoutDirection_1];
  8932. },
  8933. onLtr: function () {
  8934. return [layoutDirection_1];
  8935. }
  8936. }
  8937. };
  8938. InlineView.showAt(notificationWrapper, nodeAnchor, premade$1(notification));
  8939. } else {
  8940. InlineView.showAt(notificationWrapper, extras.backstage.shared.anchors.banner(), premade$1(notification));
  8941. }
  8942. },
  8943. text: function (nuText) {
  8944. Notification.updateText(notification, nuText);
  8945. },
  8946. settings: settings,
  8947. getEl: function () {
  8948. return notification.element().dom();
  8949. },
  8950. progressBar: {
  8951. value: function (percent) {
  8952. Notification.updateProgress(notification, percent);
  8953. }
  8954. }
  8955. };
  8956. };
  8957. var close = function (notification) {
  8958. notification.close();
  8959. };
  8960. var getArgs = function (notification) {
  8961. return notification.settings;
  8962. };
  8963. return {
  8964. open: open,
  8965. close: close,
  8966. reposition: reposition,
  8967. getArgs: getArgs
  8968. };
  8969. }
  8970. var first$1 = function (fn, rate) {
  8971. var timer = null;
  8972. var cancel = function () {
  8973. if (timer !== null) {
  8974. domGlobals.clearTimeout(timer);
  8975. timer = null;
  8976. }
  8977. };
  8978. var throttle = function () {
  8979. var args = [];
  8980. for (var _i = 0; _i < arguments.length; _i++) {
  8981. args[_i] = arguments[_i];
  8982. }
  8983. if (timer === null) {
  8984. timer = domGlobals.setTimeout(function () {
  8985. fn.apply(null, args);
  8986. timer = null;
  8987. }, rate);
  8988. }
  8989. };
  8990. return {
  8991. cancel: cancel,
  8992. throttle: throttle
  8993. };
  8994. };
  8995. var last$2 = function (fn, rate) {
  8996. var timer = null;
  8997. var cancel = function () {
  8998. if (timer !== null) {
  8999. domGlobals.clearTimeout(timer);
  9000. timer = null;
  9001. }
  9002. };
  9003. var throttle = function () {
  9004. var args = [];
  9005. for (var _i = 0; _i < arguments.length; _i++) {
  9006. args[_i] = arguments[_i];
  9007. }
  9008. if (timer !== null) {
  9009. domGlobals.clearTimeout(timer);
  9010. }
  9011. timer = domGlobals.setTimeout(function () {
  9012. fn.apply(null, args);
  9013. timer = null;
  9014. }, rate);
  9015. };
  9016. return {
  9017. cancel: cancel,
  9018. throttle: throttle
  9019. };
  9020. };
  9021. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
  9022. var isText$1 = function (node) {
  9023. return node.nodeType === domGlobals.Node.TEXT_NODE;
  9024. };
  9025. var isBoundary = function (dom, node) {
  9026. return dom.isBlock(node) || contains([
  9027. 'BR',
  9028. 'IMG',
  9029. 'HR',
  9030. 'INPUT'
  9031. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  9032. };
  9033. var outcome$1 = Adt.generate([
  9034. { aborted: [] },
  9035. { edge: ['element'] },
  9036. { success: ['info'] }
  9037. ]);
  9038. var phase = Adt.generate([
  9039. { abort: [] },
  9040. { kontinue: [] },
  9041. { finish: ['info'] }
  9042. ]);
  9043. var repeat = function (dom, node, offset, process, walker, recent) {
  9044. var terminate = function () {
  9045. return recent.fold(outcome$1.aborted, outcome$1.edge);
  9046. };
  9047. var recurse = function () {
  9048. var next = walker();
  9049. if (next) {
  9050. return repeat(dom, next, Option.none(), process, walker, Option.some(node));
  9051. } else {
  9052. return terminate();
  9053. }
  9054. };
  9055. if (isBoundary(dom, node)) {
  9056. return terminate();
  9057. } else if (!isText$1(node)) {
  9058. return recurse();
  9059. } else {
  9060. var text = node.textContent;
  9061. return process(phase, node, text, offset).fold(outcome$1.aborted, function () {
  9062. return recurse();
  9063. }, outcome$1.success);
  9064. }
  9065. };
  9066. var repeatLeft = function (dom, node, offset, process, rootNode) {
  9067. var walker = new global$3(node, rootNode || dom.getRoot());
  9068. return repeat(dom, node, Option.some(offset), process, walker.prev, Option.none());
  9069. };
  9070. var autocompleteSelector = '[data-mce-autocompleter]';
  9071. var create$4 = function (editor, range) {
  9072. return detect$4(Element.fromDom(editor.selection.getNode())).getOrThunk(function () {
  9073. var wrapper = Element.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  9074. append(wrapper, Element.fromDom(range.extractContents()));
  9075. range.insertNode(wrapper.dom());
  9076. parent(wrapper).each(function (elm) {
  9077. return elm.dom().normalize();
  9078. });
  9079. last$1(wrapper).map(function (last) {
  9080. editor.selection.setCursorLocation(last.dom(), getEnd(last));
  9081. });
  9082. return wrapper;
  9083. });
  9084. };
  9085. var detect$4 = function (elm) {
  9086. return closest$3(elm, autocompleteSelector);
  9087. };
  9088. var isValidTextRange = function (rng) {
  9089. return rng.collapsed && rng.startContainer.nodeType === 3;
  9090. };
  9091. var whiteSpace = /[\u00a0 \t\r\n]/;
  9092. var parse = function (text, index, ch, minChars) {
  9093. var i;
  9094. for (i = index - 1; i >= 0; i--) {
  9095. var char = text.charAt(i);
  9096. if (whiteSpace.test(char)) {
  9097. return Option.none();
  9098. }
  9099. if (char === ch) {
  9100. break;
  9101. }
  9102. }
  9103. if (i === -1 || index - i < minChars) {
  9104. return Option.none();
  9105. }
  9106. return Option.some(text.substring(i + 1, index));
  9107. };
  9108. var getText = function (rng, ch) {
  9109. var text = rng.toString().substring(ch.length);
  9110. return text.replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  9111. };
  9112. var findStart = function (dom, initRange, ch, minChars) {
  9113. if (minChars === void 0) {
  9114. minChars = 0;
  9115. }
  9116. if (!isValidTextRange(initRange)) {
  9117. return Option.none();
  9118. }
  9119. var findTriggerCh = function (phase, element, text, optOffset) {
  9120. var index = optOffset.getOr(text.length);
  9121. return parse(text, index, ch, 1).fold(function () {
  9122. return text.match(whiteSpace) ? phase.abort() : phase.kontinue();
  9123. }, function (newText) {
  9124. var range = initRange.cloneRange();
  9125. range.setStart(element, index - newText.length - 1);
  9126. range.setEnd(initRange.endContainer, initRange.endOffset);
  9127. return text.length < minChars ? phase.abort() : phase.finish({
  9128. text: getText(range, ch),
  9129. range: range,
  9130. triggerChar: ch
  9131. });
  9132. });
  9133. };
  9134. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerCh).fold(Option.none, Option.none, Option.some);
  9135. };
  9136. var getContext = function (dom, initRange, ch, minChars) {
  9137. if (minChars === void 0) {
  9138. minChars = 0;
  9139. }
  9140. return detect$4(Element.fromDom(initRange.startContainer)).fold(function () {
  9141. return findStart(dom, initRange, ch, minChars);
  9142. }, function (elm) {
  9143. var range = dom.createRng();
  9144. range.selectNode(elm.dom());
  9145. return Option.some({
  9146. range: range,
  9147. text: getText(range, ch),
  9148. triggerChar: ch
  9149. });
  9150. });
  9151. };
  9152. var setup = function (api, editor) {
  9153. editor.on('keypress compositionend', api.onKeypress.throttle);
  9154. editor.on('remove', api.onKeypress.cancel);
  9155. var redirectKeyToItem = function (item, e) {
  9156. emitWith(item, keydown(), { raw: e });
  9157. };
  9158. editor.on('keydown', function (e) {
  9159. var getItem = function () {
  9160. return api.getView().bind(Highlighting.getHighlighted);
  9161. };
  9162. if (e.which === 8) {
  9163. api.onKeypress.throttle(e);
  9164. }
  9165. if (api.isActive()) {
  9166. if (e.which === 27) {
  9167. api.cancelIfNecessary();
  9168. }
  9169. if (api.isMenuOpen()) {
  9170. if (e.which === 13) {
  9171. getItem().each(emitExecute);
  9172. e.preventDefault();
  9173. } else if (e.which === 40) {
  9174. getItem().fold(function () {
  9175. api.getView().each(Highlighting.highlightFirst);
  9176. }, function (item) {
  9177. redirectKeyToItem(item, e);
  9178. });
  9179. e.preventDefault();
  9180. e.stopImmediatePropagation();
  9181. } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  9182. getItem().each(function (item) {
  9183. redirectKeyToItem(item, e);
  9184. e.preventDefault();
  9185. e.stopImmediatePropagation();
  9186. });
  9187. }
  9188. } else {
  9189. if (e.which === 13 || e.which === 38 || e.which === 40) {
  9190. api.cancelIfNecessary();
  9191. }
  9192. }
  9193. }
  9194. });
  9195. editor.on('NodeChange', function (e) {
  9196. if (api.isActive() && !api.isProcessingAction() && detect$4(Element.fromDom(e.element)).isNone()) {
  9197. api.cancelIfNecessary();
  9198. }
  9199. });
  9200. };
  9201. var AutocompleterEditorEvents = { setup: setup };
  9202. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Promise');
  9203. var point$2 = function (element, offset) {
  9204. return {
  9205. element: element,
  9206. offset: offset
  9207. };
  9208. };
  9209. var isText$2 = function (node) {
  9210. return node.nodeType === domGlobals.Node.TEXT_NODE;
  9211. };
  9212. var isElement$1 = function (node) {
  9213. return node.nodeType === domGlobals.Node.ELEMENT_NODE;
  9214. };
  9215. var toLast = function (node) {
  9216. if (isText$2(node)) {
  9217. return point$2(node, node.data.length);
  9218. } else {
  9219. var children = node.childNodes;
  9220. return children.length > 0 ? toLast(children[children.length - 1]) : point$2(node, children.length);
  9221. }
  9222. };
  9223. var toLeaf = function (node, offset) {
  9224. var children = node.childNodes;
  9225. if (children.length > 0 && offset < children.length) {
  9226. return toLeaf(children[offset], 0);
  9227. } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  9228. return toLast(children[children.length - 1]);
  9229. } else {
  9230. return point$2(node, offset);
  9231. }
  9232. };
  9233. var isStartOfWord = function (dom) {
  9234. var process = function (phase, element, text, optOffset) {
  9235. var index = optOffset.getOr(text.length);
  9236. return index === 0 ? phase.kontinue() : phase.finish(/\s/.test(text.charAt(index - 1)));
  9237. };
  9238. return function (rng) {
  9239. var leaf = toLeaf(rng.startContainer, rng.startOffset);
  9240. return repeatLeft(dom, leaf.element, leaf.offset, process).fold(constant(true), constant(true), identity);
  9241. };
  9242. };
  9243. var getTriggerContext = function (dom, initRange, database) {
  9244. return findMap(database.triggerChars, function (ch) {
  9245. return getContext(dom, initRange, ch);
  9246. });
  9247. };
  9248. var lookup = function (editor, getDatabase) {
  9249. var database = getDatabase();
  9250. var rng = editor.selection.getRng();
  9251. return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  9252. return lookupWithContext(editor, getDatabase, context);
  9253. });
  9254. };
  9255. var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  9256. if (fetchOptions === void 0) {
  9257. fetchOptions = {};
  9258. }
  9259. var database = getDatabase();
  9260. var rng = editor.selection.getRng();
  9261. var startText = rng.startContainer.nodeValue;
  9262. var autocompleters = filter(database.lookupByChar(context.triggerChar), function (autocompleter) {
  9263. return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  9264. return isStartOfWord(editor.dom);
  9265. })(context.range, startText, context.text);
  9266. });
  9267. if (autocompleters.length === 0) {
  9268. return Option.none();
  9269. }
  9270. var lookupData = global$4.all(map(autocompleters, function (ac) {
  9271. var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  9272. return fetchResult.then(function (results) {
  9273. return {
  9274. matchText: context.text,
  9275. items: results,
  9276. columns: ac.columns,
  9277. onAction: ac.onAction
  9278. };
  9279. });
  9280. }));
  9281. return Option.some({
  9282. lookupData: lookupData,
  9283. context: context
  9284. });
  9285. };
  9286. var separatorMenuItemSchema = objOf([
  9287. strictString('type'),
  9288. optionString('text')
  9289. ]);
  9290. var createSeparatorMenuItem = function (spec) {
  9291. return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  9292. };
  9293. var autocompleterItemSchema = objOf([
  9294. state$1('type', function () {
  9295. return 'autocompleteitem';
  9296. }),
  9297. state$1('active', function () {
  9298. return false;
  9299. }),
  9300. state$1('disabled', function () {
  9301. return false;
  9302. }),
  9303. defaulted$1('meta', {}),
  9304. strictString('value'),
  9305. optionString('text'),
  9306. optionString('icon')
  9307. ]);
  9308. var autocompleterSchema = objOf([
  9309. strictString('type'),
  9310. strictString('ch'),
  9311. defaultedNumber('minChars', 1),
  9312. defaulted$1('columns', 1),
  9313. defaultedNumber('maxResults', 10),
  9314. optionFunction('matches'),
  9315. strictFunction('fetch'),
  9316. strictFunction('onAction')
  9317. ]);
  9318. var createSeparatorItem = function (spec) {
  9319. return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  9320. };
  9321. var createAutocompleterItem = function (spec) {
  9322. return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  9323. };
  9324. var createAutocompleter = function (spec) {
  9325. return asRaw('Autocompleter', autocompleterSchema, spec);
  9326. };
  9327. var stringArray = function (a) {
  9328. var all = {};
  9329. each(a, function (key) {
  9330. all[key] = {};
  9331. });
  9332. return keys(all);
  9333. };
  9334. var register = function (editor) {
  9335. var popups = editor.ui.registry.getAll().popups;
  9336. var dataset = map$1(popups, function (popup) {
  9337. return createAutocompleter(popup).fold(function (err) {
  9338. throw new Error(formatError(err));
  9339. }, function (x) {
  9340. return x;
  9341. });
  9342. });
  9343. var triggerChars = stringArray(mapToArray(dataset, function (v) {
  9344. return v.ch;
  9345. }));
  9346. var datasetValues = values(dataset);
  9347. var lookupByChar = function (ch) {
  9348. return filter(datasetValues, function (dv) {
  9349. return dv.ch === ch;
  9350. });
  9351. };
  9352. return {
  9353. dataset: dataset,
  9354. triggerChars: triggerChars,
  9355. lookupByChar: lookupByChar
  9356. };
  9357. };
  9358. var commonMenuItemFields = [
  9359. defaultedBoolean('disabled', false),
  9360. optionString('text'),
  9361. optionString('shortcut'),
  9362. field('value', 'value', defaultedThunk(function () {
  9363. return generate$1('menuitem-value');
  9364. }), anyValue$1()),
  9365. defaulted$1('meta', {})
  9366. ];
  9367. var menuItemSchema = objOf([
  9368. strictString('type'),
  9369. defaultedFunction('onSetup', function () {
  9370. return noop;
  9371. }),
  9372. defaultedFunction('onAction', noop),
  9373. optionString('icon')
  9374. ].concat(commonMenuItemFields));
  9375. var createMenuItem = function (spec) {
  9376. return asRaw('menuitem', menuItemSchema, spec);
  9377. };
  9378. var nestedMenuItemSchema = objOf([
  9379. strictString('type'),
  9380. strictFunction('getSubmenuItems'),
  9381. defaultedFunction('onSetup', function () {
  9382. return noop;
  9383. }),
  9384. optionString('icon')
  9385. ].concat(commonMenuItemFields));
  9386. var createNestedMenuItem = function (spec) {
  9387. return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  9388. };
  9389. var toggleMenuItemSchema = objOf([
  9390. strictString('type'),
  9391. defaultedBoolean('active', false),
  9392. defaultedFunction('onSetup', function () {
  9393. return noop;
  9394. }),
  9395. strictFunction('onAction')
  9396. ].concat(commonMenuItemFields));
  9397. var createToggleMenuItem = function (spec) {
  9398. return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  9399. };
  9400. var choiceMenuItemSchema = objOf([
  9401. strictString('type'),
  9402. defaultedBoolean('active', false),
  9403. optionString('icon')
  9404. ].concat(commonMenuItemFields));
  9405. var createChoiceMenuItem = function (spec) {
  9406. return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  9407. };
  9408. var fancyTypes = [
  9409. 'inserttable',
  9410. 'colorswatch'
  9411. ];
  9412. var fancyMenuItemSchema = objOf([
  9413. strictString('type'),
  9414. strictStringEnum('fancytype', fancyTypes),
  9415. defaultedFunction('onAction', noop)
  9416. ]);
  9417. var createFancyMenuItem = function (spec) {
  9418. return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  9419. };
  9420. var detectSize = function (comp, margin, selectorClass) {
  9421. var descendants$1 = descendants(comp.element(), '.' + selectorClass);
  9422. if (descendants$1.length > 0) {
  9423. var columnLength = findIndex(descendants$1, function (c) {
  9424. var thisTop = c.dom().getBoundingClientRect().top;
  9425. var cTop = descendants$1[0].dom().getBoundingClientRect().top;
  9426. return Math.abs(thisTop - cTop) > margin;
  9427. }).getOr(descendants$1.length);
  9428. return Option.some({
  9429. numColumns: columnLength,
  9430. numRows: Math.ceil(descendants$1.length / columnLength)
  9431. });
  9432. } else {
  9433. return Option.none();
  9434. }
  9435. };
  9436. var namedEvents = function (name, handlers) {
  9437. return derive$1([config(name, handlers)]);
  9438. };
  9439. var unnamedEvents = function (handlers) {
  9440. return namedEvents(generate$1('unnamed-events'), handlers);
  9441. };
  9442. var SimpleBehaviours = {
  9443. namedEvents: namedEvents,
  9444. unnamedEvents: unnamedEvents
  9445. };
  9446. var TooltippingSchema = [
  9447. strict$1('lazySink'),
  9448. strict$1('tooltipDom'),
  9449. defaulted$1('exclusive', true),
  9450. defaulted$1('tooltipComponents', []),
  9451. defaulted$1('delay', 300),
  9452. defaultedStringEnum('mode', 'normal', [
  9453. 'normal',
  9454. 'follow-highlight'
  9455. ]),
  9456. defaulted$1('anchor', function (comp) {
  9457. return {
  9458. anchor: 'hotspot',
  9459. hotspot: comp,
  9460. layouts: {
  9461. onLtr: constant([
  9462. south$1,
  9463. north$1,
  9464. southeast$1,
  9465. northeast$1,
  9466. southwest$1,
  9467. northwest$1
  9468. ]),
  9469. onRtl: constant([
  9470. south$1,
  9471. north$1,
  9472. southeast$1,
  9473. northeast$1,
  9474. southwest$1,
  9475. northwest$1
  9476. ])
  9477. }
  9478. };
  9479. }),
  9480. onHandler('onHide'),
  9481. onHandler('onShow')
  9482. ];
  9483. var init$4 = function () {
  9484. var timer = Cell(Option.none());
  9485. var popup = Cell(Option.none());
  9486. var getTooltip = function () {
  9487. return popup.get();
  9488. };
  9489. var setTooltip = function (s) {
  9490. popup.set(Option.some(s));
  9491. };
  9492. var clearTooltip = function () {
  9493. popup.set(Option.none());
  9494. };
  9495. var clearTimer = function () {
  9496. timer.get().each(function (t) {
  9497. domGlobals.clearTimeout(t);
  9498. });
  9499. };
  9500. var resetTimer = function (f, delay) {
  9501. clearTimer();
  9502. timer.set(Option.some(domGlobals.setTimeout(function () {
  9503. f();
  9504. }, delay)));
  9505. };
  9506. var isShowing = function () {
  9507. return popup.get().isSome();
  9508. };
  9509. var readState = constant('not-implemented');
  9510. return nu$5({
  9511. getTooltip: getTooltip,
  9512. isShowing: isShowing,
  9513. setTooltip: setTooltip,
  9514. clearTooltip: clearTooltip,
  9515. clearTimer: clearTimer,
  9516. resetTimer: resetTimer,
  9517. readState: readState
  9518. });
  9519. };
  9520. var TooltippingState = /*#__PURE__*/Object.freeze({
  9521. init: init$4
  9522. });
  9523. var ExclusivityChannel = generate$1('tooltip.exclusive');
  9524. var ShowTooltipEvent = generate$1('tooltip.show');
  9525. var HideTooltipEvent = generate$1('tooltip.hide');
  9526. var hideAllExclusive = function (component, tConfig, tState) {
  9527. component.getSystem().broadcastOn([ExclusivityChannel], {});
  9528. };
  9529. var setComponents = function (component, tConfig, tState, specs) {
  9530. tState.getTooltip().each(function (tooltip) {
  9531. if (tooltip.getSystem().isConnected()) {
  9532. Replacing.set(tooltip, specs);
  9533. }
  9534. });
  9535. };
  9536. var TooltippingApis = /*#__PURE__*/Object.freeze({
  9537. hideAllExclusive: hideAllExclusive,
  9538. setComponents: setComponents
  9539. });
  9540. var events$8 = function (tooltipConfig, state) {
  9541. var hide = function (comp) {
  9542. state.getTooltip().each(function (p) {
  9543. detach(p);
  9544. tooltipConfig.onHide(comp, p);
  9545. state.clearTooltip();
  9546. });
  9547. state.clearTimer();
  9548. };
  9549. var show = function (comp) {
  9550. if (!state.isShowing()) {
  9551. hideAllExclusive(comp);
  9552. var sink = tooltipConfig.lazySink(comp).getOrDie();
  9553. var popup = comp.getSystem().build({
  9554. dom: tooltipConfig.tooltipDom,
  9555. components: tooltipConfig.tooltipComponents,
  9556. events: derive(tooltipConfig.mode === 'normal' ? [
  9557. run(mouseover(), function (_) {
  9558. emit(comp, ShowTooltipEvent);
  9559. }),
  9560. run(mouseout(), function (_) {
  9561. emit(comp, HideTooltipEvent);
  9562. })
  9563. ] : []),
  9564. behaviours: derive$1([Replacing.config({})])
  9565. });
  9566. state.setTooltip(popup);
  9567. attach$1(sink, popup);
  9568. tooltipConfig.onShow(comp, popup);
  9569. Positioning.position(sink, tooltipConfig.anchor(comp), popup);
  9570. }
  9571. };
  9572. return derive(flatten([
  9573. [
  9574. run(ShowTooltipEvent, function (comp) {
  9575. state.resetTimer(function () {
  9576. show(comp);
  9577. }, tooltipConfig.delay);
  9578. }),
  9579. run(HideTooltipEvent, function (comp) {
  9580. state.resetTimer(function () {
  9581. hide(comp);
  9582. }, tooltipConfig.delay);
  9583. }),
  9584. run(receive(), function (comp, message) {
  9585. var receivingData = message;
  9586. if (contains(receivingData.channels(), ExclusivityChannel)) {
  9587. hide(comp);
  9588. }
  9589. }),
  9590. runOnDetached(function (comp) {
  9591. hide(comp);
  9592. })
  9593. ],
  9594. tooltipConfig.mode === 'normal' ? [
  9595. run(focusin(), function (comp) {
  9596. emit(comp, ShowTooltipEvent);
  9597. }),
  9598. run(postBlur(), function (comp) {
  9599. emit(comp, HideTooltipEvent);
  9600. }),
  9601. run(mouseover(), function (comp) {
  9602. emit(comp, ShowTooltipEvent);
  9603. }),
  9604. run(mouseout(), function (comp) {
  9605. emit(comp, HideTooltipEvent);
  9606. })
  9607. ] : [
  9608. run(highlight(), function (comp, se) {
  9609. emit(comp, ShowTooltipEvent);
  9610. }),
  9611. run(dehighlight(), function (comp) {
  9612. emit(comp, HideTooltipEvent);
  9613. })
  9614. ]
  9615. ]));
  9616. };
  9617. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  9618. events: events$8
  9619. });
  9620. var Tooltipping = create$1({
  9621. fields: TooltippingSchema,
  9622. name: 'tooltipping',
  9623. active: ActiveTooltipping,
  9624. state: TooltippingState,
  9625. apis: TooltippingApis
  9626. });
  9627. var getAttrs = function (elem) {
  9628. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  9629. return foldl(attributes, function (b, attr) {
  9630. var _a;
  9631. if (attr.name === 'class') {
  9632. return b;
  9633. } else {
  9634. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  9635. }
  9636. }, {});
  9637. };
  9638. var getClasses = function (elem) {
  9639. return Array.prototype.slice.call(elem.dom().classList, 0);
  9640. };
  9641. var fromHtml$2 = function (html) {
  9642. var elem = Element.fromHtml(html);
  9643. var children$1 = children(elem);
  9644. var attrs = getAttrs(elem);
  9645. var classes = getClasses(elem);
  9646. var contents = children$1.length === 0 ? {} : { innerHtml: get$1(elem) };
  9647. return __assign({
  9648. tag: name(elem),
  9649. classes: classes,
  9650. attributes: attrs
  9651. }, contents);
  9652. };
  9653. var global$5 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  9654. var navClass = 'tox-menu-nav__js';
  9655. var selectableClass = 'tox-collection__item';
  9656. var colorClass = 'tox-swatch';
  9657. var presetClasses = {
  9658. normal: navClass,
  9659. color: colorClass
  9660. };
  9661. var tickedClass = 'tox-collection__item--enabled';
  9662. var groupHeadingClass = 'tox-collection__group-heading';
  9663. var iconClass = 'tox-collection__item-icon';
  9664. var textClass = 'tox-collection__item-label';
  9665. var accessoryClass = 'tox-collection__item-accessory';
  9666. var caretClass = 'tox-collection__item-caret';
  9667. var checkmarkClass = 'tox-collection__item-checkmark';
  9668. var activeClass = 'tox-collection__item--active';
  9669. var iconClassRtl = 'tox-collection__item-icon-rtl';
  9670. var classForPreset = function (presets) {
  9671. return readOptFrom$1(presetClasses, presets).getOr(navClass);
  9672. };
  9673. var global$6 = tinymce.util.Tools.resolve('tinymce.Env');
  9674. var convertText = function (source) {
  9675. var mac = {
  9676. alt: '&#x2325;',
  9677. ctrl: '&#x2303;',
  9678. shift: '&#x21E7;',
  9679. meta: '&#x2318;',
  9680. access: '&#x2303;&#x2325;'
  9681. };
  9682. var other = {
  9683. meta: 'Ctrl',
  9684. access: 'Shift+Alt'
  9685. };
  9686. var replace = global$6.mac ? mac : other;
  9687. var shortcut = source.split('+');
  9688. var updated = map(shortcut, function (segment) {
  9689. var search = segment.toLowerCase().trim();
  9690. return has(replace, search) ? replace[search] : segment;
  9691. });
  9692. return global$6.mac ? updated.join('') : updated.join('+');
  9693. };
  9694. var ConvertShortcut = { convertText: convertText };
  9695. var renderIcon = function (iconHtml) {
  9696. return {
  9697. dom: {
  9698. tag: 'div',
  9699. classes: [iconClass],
  9700. innerHtml: iconHtml
  9701. }
  9702. };
  9703. };
  9704. var renderText = function (text$1) {
  9705. return {
  9706. dom: {
  9707. tag: 'div',
  9708. classes: [textClass]
  9709. },
  9710. components: [text(global$5.translate(text$1))]
  9711. };
  9712. };
  9713. var renderHtml = function (html) {
  9714. return {
  9715. dom: {
  9716. tag: 'div',
  9717. classes: [textClass],
  9718. innerHtml: html
  9719. }
  9720. };
  9721. };
  9722. var renderStyledText = function (style, text$1) {
  9723. return {
  9724. dom: {
  9725. tag: 'div',
  9726. classes: [textClass]
  9727. },
  9728. components: [{
  9729. dom: {
  9730. tag: style.tag,
  9731. attributes: { style: style.styleAttr }
  9732. },
  9733. components: [text(global$5.translate(text$1))]
  9734. }]
  9735. };
  9736. };
  9737. var renderShortcut = function (shortcut) {
  9738. return {
  9739. dom: {
  9740. tag: 'div',
  9741. classes: [accessoryClass],
  9742. innerHtml: ConvertShortcut.convertText(shortcut)
  9743. }
  9744. };
  9745. };
  9746. var renderCheckmark = function (icons) {
  9747. return {
  9748. dom: {
  9749. tag: 'div',
  9750. classes: [
  9751. iconClass,
  9752. checkmarkClass
  9753. ],
  9754. innerHtml: get$c('checkmark', icons)
  9755. }
  9756. };
  9757. };
  9758. var renderSubmenuCaret = function (icons) {
  9759. return {
  9760. dom: {
  9761. tag: 'div',
  9762. classes: [caretClass],
  9763. innerHtml: get$c('chevron-right', icons)
  9764. }
  9765. };
  9766. };
  9767. var renderDownwardsCaret = function (icons) {
  9768. return {
  9769. dom: {
  9770. tag: 'div',
  9771. classes: [caretClass],
  9772. innerHtml: get$c('chevron-down', icons)
  9773. }
  9774. };
  9775. };
  9776. var renderColorStructure = function (itemText, itemValue, iconSvg, providerBackstage) {
  9777. var colorPickerCommand = 'custom';
  9778. var removeColorCommand = 'remove';
  9779. var getDom = function () {
  9780. var common = colorClass;
  9781. var icon = iconSvg.getOr('');
  9782. var title = itemText.map(function (text) {
  9783. return ' title="' + providerBackstage.translate(text) + '"';
  9784. }).getOr('');
  9785. if (itemValue === colorPickerCommand) {
  9786. return fromHtml$2('<button class="' + common + ' tox-swatches__picker-btn"' + title + '>' + icon + '</button>');
  9787. } else if (itemValue === removeColorCommand) {
  9788. return fromHtml$2('<div class="' + common + ' tox-swatch--remove"' + title + '>' + icon + '</div>');
  9789. } else {
  9790. return fromHtml$2('<div class="' + common + '" style="background-color: ' + itemValue + '" data-mce-color="' + itemValue + '"' + title + '></div>');
  9791. }
  9792. };
  9793. return {
  9794. dom: getDom(),
  9795. optComponents: []
  9796. };
  9797. };
  9798. var renderNormalItemStructure = function (info, icon, renderIcons, textRender, rtlClass) {
  9799. var leftIcon = renderIcons ? info.checkMark.orThunk(function () {
  9800. return icon.or(Option.some('')).map(renderIcon);
  9801. }) : Option.none();
  9802. var domTitle = info.ariaLabel.map(function (label) {
  9803. return { attributes: { title: global$5.translate(label) } };
  9804. }).getOr({});
  9805. var dom = merge({
  9806. tag: 'div',
  9807. classes: [
  9808. navClass,
  9809. selectableClass
  9810. ].concat(rtlClass ? [iconClassRtl] : [])
  9811. }, domTitle);
  9812. var content = info.htmlContent.fold(function () {
  9813. return info.textContent.map(textRender);
  9814. }, function (html) {
  9815. return Option.some(renderHtml(html));
  9816. });
  9817. var menuItem = {
  9818. dom: dom,
  9819. optComponents: [
  9820. leftIcon,
  9821. content,
  9822. info.shortcutContent.map(renderShortcut),
  9823. info.caret
  9824. ]
  9825. };
  9826. return menuItem;
  9827. };
  9828. var rtlIcon = [
  9829. 'list-num-default',
  9830. 'list-num-lower-alpha',
  9831. 'list-num-lower-greek',
  9832. 'list-num-lower-roman',
  9833. 'list-num-upper-alpha',
  9834. 'list-num-upper-roman'
  9835. ];
  9836. var rtlTransform = [
  9837. 'list-bull-circle',
  9838. 'list-bull-default',
  9839. 'list-bull-square'
  9840. ];
  9841. var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  9842. if (fallbackIcon === void 0) {
  9843. fallbackIcon = Option.none();
  9844. }
  9845. var getIconName = function (iconName) {
  9846. return iconName.map(function (name) {
  9847. return global$5.isRtl() && contains(rtlIcon, name) ? name + '-rtl' : name;
  9848. });
  9849. };
  9850. var needRtlClass = global$5.isRtl() && info.iconContent.exists(function (name) {
  9851. return contains(rtlTransform, name);
  9852. });
  9853. var icon = getIconName(info.iconContent).map(function (iconName) {
  9854. return getOr(iconName, providersBackstage.icons, fallbackIcon);
  9855. });
  9856. var textRender = Option.from(info.meta).fold(function () {
  9857. return renderText;
  9858. }, function (meta) {
  9859. return has(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  9860. });
  9861. if (info.presets === 'color') {
  9862. return renderColorStructure(info.ariaLabel, info.value, icon, providersBackstage);
  9863. } else {
  9864. return renderNormalItemStructure(info, icon, renderIcons, textRender, needRtlClass);
  9865. }
  9866. };
  9867. var nativeDisabled = [
  9868. 'input',
  9869. 'button',
  9870. 'textarea',
  9871. 'select'
  9872. ];
  9873. var onLoad$5 = function (component, disableConfig, disableState) {
  9874. if (disableConfig.disabled) {
  9875. disable(component, disableConfig);
  9876. }
  9877. };
  9878. var hasNative = function (component, config) {
  9879. return config.useNative === true && contains(nativeDisabled, name(component.element()));
  9880. };
  9881. var nativeIsDisabled = function (component) {
  9882. return has$1(component.element(), 'disabled');
  9883. };
  9884. var nativeDisable = function (component) {
  9885. set$1(component.element(), 'disabled', 'disabled');
  9886. };
  9887. var nativeEnable = function (component) {
  9888. remove$1(component.element(), 'disabled');
  9889. };
  9890. var ariaIsDisabled = function (component) {
  9891. return get$2(component.element(), 'aria-disabled') === 'true';
  9892. };
  9893. var ariaDisable = function (component) {
  9894. set$1(component.element(), 'aria-disabled', 'true');
  9895. };
  9896. var ariaEnable = function (component) {
  9897. set$1(component.element(), 'aria-disabled', 'false');
  9898. };
  9899. var disable = function (component, disableConfig, disableState) {
  9900. disableConfig.disableClass.each(function (disableClass) {
  9901. add$2(component.element(), disableClass);
  9902. });
  9903. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  9904. f(component);
  9905. disableConfig.onDisabled(component);
  9906. };
  9907. var enable = function (component, disableConfig, disableState) {
  9908. disableConfig.disableClass.each(function (disableClass) {
  9909. remove$4(component.element(), disableClass);
  9910. });
  9911. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  9912. f(component);
  9913. disableConfig.onEnabled(component);
  9914. };
  9915. var isDisabled = function (component, disableConfig) {
  9916. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  9917. };
  9918. var set$7 = function (component, disableConfig, disableState, disabled) {
  9919. var f = disabled ? disable : enable;
  9920. f(component, disableConfig, disableState);
  9921. };
  9922. var DisableApis = /*#__PURE__*/Object.freeze({
  9923. enable: enable,
  9924. disable: disable,
  9925. isDisabled: isDisabled,
  9926. onLoad: onLoad$5,
  9927. set: set$7
  9928. });
  9929. var exhibit$3 = function (base, disableConfig, disableState) {
  9930. return nu$6({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  9931. };
  9932. var events$9 = function (disableConfig, disableState) {
  9933. return derive([
  9934. abort(execute(), function (component, simulatedEvent) {
  9935. return isDisabled(component, disableConfig);
  9936. }),
  9937. loadEvent(disableConfig, disableState, onLoad$5)
  9938. ]);
  9939. };
  9940. var ActiveDisable = /*#__PURE__*/Object.freeze({
  9941. exhibit: exhibit$3,
  9942. events: events$9
  9943. });
  9944. var DisableSchema = [
  9945. defaulted$1('disabled', false),
  9946. defaulted$1('useNative', true),
  9947. option('disableClass'),
  9948. onHandler('onDisabled'),
  9949. onHandler('onEnabled')
  9950. ];
  9951. var Disabling = create$1({
  9952. fields: DisableSchema,
  9953. name: 'disabling',
  9954. active: ActiveDisable,
  9955. apis: DisableApis
  9956. });
  9957. var item = function (disabled) {
  9958. return Disabling.config({
  9959. disabled: disabled,
  9960. disableClass: 'tox-collection__item--state-disabled'
  9961. });
  9962. };
  9963. var button = function (disabled) {
  9964. return Disabling.config({ disabled: disabled });
  9965. };
  9966. var splitButton = function (disabled) {
  9967. return Disabling.config({
  9968. disabled: disabled,
  9969. disableClass: 'tox-tbtn--disabled'
  9970. });
  9971. };
  9972. var toolbarButton = function (disabled) {
  9973. return Disabling.config({
  9974. disabled: disabled,
  9975. disableClass: 'tox-tbtn--disabled',
  9976. useNative: false
  9977. });
  9978. };
  9979. var DisablingConfigs = {
  9980. item: item,
  9981. button: button,
  9982. splitButton: splitButton,
  9983. toolbarButton: toolbarButton
  9984. };
  9985. var runWithApi = function (info, comp) {
  9986. var api = info.getApi(comp);
  9987. return function (f) {
  9988. f(api);
  9989. };
  9990. };
  9991. var onControlAttached = function (info, editorOffCell) {
  9992. return runOnAttached(function (comp) {
  9993. var run = runWithApi(info, comp);
  9994. run(function (api) {
  9995. var onDestroy = info.onSetup(api);
  9996. if (onDestroy !== null && onDestroy !== undefined) {
  9997. editorOffCell.set(onDestroy);
  9998. }
  9999. });
  10000. });
  10001. };
  10002. var onControlDetached = function (getApi, editorOffCell) {
  10003. return runOnDetached(function (comp) {
  10004. return runWithApi(getApi, comp)(editorOffCell.get());
  10005. });
  10006. };
  10007. var ItemResponse;
  10008. (function (ItemResponse) {
  10009. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  10010. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  10011. }(ItemResponse || (ItemResponse = {})));
  10012. var ItemResponse$1 = ItemResponse;
  10013. var onMenuItemExecute = function (info, itemResponse) {
  10014. return runOnExecute(function (comp, simulatedEvent) {
  10015. runWithApi(info, comp)(info.onAction);
  10016. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  10017. emit(comp, sandboxClose());
  10018. simulatedEvent.stop();
  10019. }
  10020. });
  10021. };
  10022. var menuItemEventOrder = {
  10023. 'alloy.execute': [
  10024. 'disabling',
  10025. 'alloy.base.behaviour',
  10026. 'toggling',
  10027. 'item-events'
  10028. ]
  10029. };
  10030. var componentRenderPipeline = function (xs) {
  10031. return bind(xs, function (o) {
  10032. return o.toArray();
  10033. });
  10034. };
  10035. var renderCommonItem = function (spec, structure, itemResponse) {
  10036. var editorOffCell = Cell(noop);
  10037. return {
  10038. type: 'item',
  10039. dom: structure.dom,
  10040. components: componentRenderPipeline(structure.optComponents),
  10041. data: spec.data,
  10042. eventOrder: menuItemEventOrder,
  10043. hasSubmenu: spec.triggersSubmenu,
  10044. itemBehaviours: derive$1([
  10045. config('item-events', [
  10046. onMenuItemExecute(spec, itemResponse),
  10047. onControlAttached(spec, editorOffCell),
  10048. onControlDetached(spec, editorOffCell)
  10049. ]),
  10050. DisablingConfigs.item(spec.disabled),
  10051. Replacing.config({})
  10052. ].concat(spec.itemBehaviours))
  10053. };
  10054. };
  10055. var buildData = function (source) {
  10056. return {
  10057. value: source.value,
  10058. meta: merge({ text: source.text.getOr('') }, source.meta)
  10059. };
  10060. };
  10061. var global$7 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  10062. var tooltipBehaviour = function (meta, sharedBackstage) {
  10063. return get(meta, 'tooltipWorker').map(function (tooltipWorker) {
  10064. return [Tooltipping.config({
  10065. lazySink: sharedBackstage.getSink,
  10066. tooltipDom: {
  10067. tag: 'div',
  10068. classes: ['tox-tooltip-worker-container']
  10069. },
  10070. tooltipComponents: [],
  10071. anchor: function (comp) {
  10072. return {
  10073. anchor: 'submenu',
  10074. item: comp,
  10075. overrides: { maxHeightFunction: expandable }
  10076. };
  10077. },
  10078. mode: 'follow-highlight',
  10079. onShow: function (component, _tooltip) {
  10080. tooltipWorker(function (elm) {
  10081. Tooltipping.setComponents(component, [external({ element: Element.fromDom(elm) })]);
  10082. });
  10083. }
  10084. })];
  10085. }).getOr([]);
  10086. };
  10087. var escapeRegExp = function (text) {
  10088. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  10089. };
  10090. var encodeText = function (text) {
  10091. return global$7.DOM.encode(text);
  10092. };
  10093. var replaceText = function (text, matchText) {
  10094. var translated = global$5.translate(text);
  10095. var encoded = encodeText(translated);
  10096. if (matchText.length > 0) {
  10097. var escapedMatchRegex = new RegExp(escapeRegExp(matchText), 'gi');
  10098. return encoded.replace(escapedMatchRegex, function (match) {
  10099. return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  10100. });
  10101. } else {
  10102. return encoded;
  10103. }
  10104. };
  10105. var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  10106. if (renderIcons === void 0) {
  10107. renderIcons = true;
  10108. }
  10109. var structure = renderItemStructure({
  10110. presets: presets,
  10111. textContent: Option.none(),
  10112. htmlContent: useText ? spec.text.map(function (text) {
  10113. return replaceText(text, matchText);
  10114. }) : Option.none(),
  10115. ariaLabel: spec.text,
  10116. iconContent: spec.icon,
  10117. shortcutContent: Option.none(),
  10118. checkMark: Option.none(),
  10119. caret: Option.none(),
  10120. value: spec.value
  10121. }, sharedBackstage.providers, renderIcons, spec.icon);
  10122. return renderCommonItem({
  10123. data: buildData(spec),
  10124. disabled: spec.disabled,
  10125. getApi: function () {
  10126. return {};
  10127. },
  10128. onAction: function (_api) {
  10129. return onItemValueHandler(spec.value, spec.meta);
  10130. },
  10131. onSetup: function () {
  10132. return function () {
  10133. };
  10134. },
  10135. triggersSubmenu: false,
  10136. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  10137. }, structure, itemResponse);
  10138. };
  10139. var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage) {
  10140. var getApi = function (component) {
  10141. return {
  10142. setActive: function (state) {
  10143. Toggling.set(component, state);
  10144. },
  10145. isActive: function () {
  10146. return Toggling.isOn(component);
  10147. },
  10148. isDisabled: function () {
  10149. return Disabling.isDisabled(component);
  10150. },
  10151. setDisabled: function (state) {
  10152. return Disabling.set(component, state);
  10153. }
  10154. };
  10155. };
  10156. var structure = renderItemStructure({
  10157. presets: presets,
  10158. textContent: useText ? spec.text : Option.none(),
  10159. htmlContent: Option.none(),
  10160. ariaLabel: spec.text,
  10161. iconContent: spec.icon,
  10162. shortcutContent: useText ? spec.shortcut : Option.none(),
  10163. checkMark: useText ? Option.some(renderCheckmark(providersBackstage.icons)) : Option.none(),
  10164. caret: Option.none(),
  10165. value: spec.value
  10166. }, providersBackstage, true);
  10167. return deepMerge(renderCommonItem({
  10168. data: buildData(spec),
  10169. disabled: spec.disabled,
  10170. getApi: getApi,
  10171. onAction: function (_api) {
  10172. return onItemValueHandler(spec.value);
  10173. },
  10174. onSetup: function (api) {
  10175. api.setActive(isSelected);
  10176. return function () {
  10177. };
  10178. },
  10179. triggersSubmenu: false,
  10180. itemBehaviours: []
  10181. }, structure, itemResponse), {
  10182. toggling: {
  10183. toggleClass: tickedClass,
  10184. toggleOnExecute: false,
  10185. selected: spec.active
  10186. }
  10187. });
  10188. };
  10189. var parts$2 = constant(generate$4(owner$2(), parts()));
  10190. var cellOverEvent = generate$1('cell-over');
  10191. var cellExecuteEvent = generate$1('cell-execute');
  10192. var makeCell = function (row, col, labelId) {
  10193. var _a;
  10194. var emitCellOver = function (c) {
  10195. return emitWith(c, cellOverEvent, {
  10196. row: row,
  10197. col: col
  10198. });
  10199. };
  10200. var emitExecute = function (c) {
  10201. return emitWith(c, cellExecuteEvent, {
  10202. row: row,
  10203. col: col
  10204. });
  10205. };
  10206. return build$1({
  10207. dom: {
  10208. tag: 'div',
  10209. attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  10210. },
  10211. behaviours: derive$1([
  10212. config('insert-table-picker-cell', [
  10213. run(mouseover(), Focusing.focus),
  10214. run(execute(), emitExecute),
  10215. run(tapOrClick(), emitExecute)
  10216. ]),
  10217. Toggling.config({
  10218. toggleClass: 'tox-insert-table-picker__selected',
  10219. toggleOnExecute: false
  10220. }),
  10221. Focusing.config({ onFocus: emitCellOver })
  10222. ])
  10223. });
  10224. };
  10225. var makeCells = function (labelId, numRows, numCols) {
  10226. var cells = [];
  10227. for (var i = 0; i < numRows; i++) {
  10228. var row = [];
  10229. for (var j = 0; j < numCols; j++) {
  10230. row.push(makeCell(i, j, labelId));
  10231. }
  10232. cells.push(row);
  10233. }
  10234. return cells;
  10235. };
  10236. var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  10237. for (var i = 0; i < numRows; i++) {
  10238. for (var j = 0; j < numColumns; j++) {
  10239. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  10240. }
  10241. }
  10242. };
  10243. var makeComponents = function (cells) {
  10244. return bind(cells, function (cellRow) {
  10245. return map(cellRow, premade$1);
  10246. });
  10247. };
  10248. var makeLabelText = function (row, col) {
  10249. return text(col + 1 + 'x' + (row + 1));
  10250. };
  10251. function renderInsertTableMenuItem(spec) {
  10252. var numRows = 10;
  10253. var numColumns = 10;
  10254. var sizeLabelId = generate$1('size-label');
  10255. var cells = makeCells(sizeLabelId, numRows, numColumns);
  10256. var memLabel = record({
  10257. dom: {
  10258. tag: 'span',
  10259. classes: ['tox-insert-table-picker__label'],
  10260. attributes: { id: sizeLabelId }
  10261. },
  10262. components: [text('0x0')],
  10263. behaviours: derive$1([Replacing.config({})])
  10264. });
  10265. return {
  10266. type: 'widget',
  10267. data: { value: generate$1('widget-id') },
  10268. dom: {
  10269. tag: 'div',
  10270. classes: ['tox-fancymenuitem']
  10271. },
  10272. autofocus: true,
  10273. components: [parts$2().widget({
  10274. dom: {
  10275. tag: 'div',
  10276. classes: ['tox-insert-table-picker']
  10277. },
  10278. components: makeComponents(cells).concat(memLabel.asSpec()),
  10279. behaviours: derive$1([
  10280. config('insert-table-picker', [
  10281. runWithTarget(cellOverEvent, function (c, t, e) {
  10282. var row = e.event().row();
  10283. var col = e.event().col();
  10284. selectCells(cells, row, col, numRows, numColumns);
  10285. Replacing.set(memLabel.get(c), [makeLabelText(row, col)]);
  10286. }),
  10287. runWithTarget(cellExecuteEvent, function (c, _, e) {
  10288. spec.onAction({
  10289. numRows: e.event().row() + 1,
  10290. numColumns: e.event().col() + 1
  10291. });
  10292. emit(c, sandboxClose());
  10293. })
  10294. ]),
  10295. Keying.config({
  10296. initSize: {
  10297. numRows: numRows,
  10298. numColumns: numColumns
  10299. },
  10300. mode: 'flatgrid',
  10301. selector: '[role="button"]'
  10302. })
  10303. ])
  10304. })]
  10305. };
  10306. }
  10307. var hexColour = function (hexString) {
  10308. return { value: constant(hexString) };
  10309. };
  10310. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  10311. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  10312. var isHexString = function (hex) {
  10313. return shorthandRegex.test(hex) || longformRegex.test(hex);
  10314. };
  10315. var getLongForm = function (hex) {
  10316. var hexString = hex.value().replace(shorthandRegex, function (m, r, g, b) {
  10317. return r + r + g + g + b + b;
  10318. });
  10319. return { value: constant(hexString) };
  10320. };
  10321. var extractValues = function (hex) {
  10322. var longForm = getLongForm(hex);
  10323. var splitForm = longformRegex.exec(longForm.value());
  10324. return splitForm === null ? [
  10325. 'FFFFFF',
  10326. 'FF',
  10327. 'FF',
  10328. 'FF'
  10329. ] : splitForm;
  10330. };
  10331. var toHex = function (component) {
  10332. var hex = component.toString(16);
  10333. return hex.length === 1 ? '0' + hex : hex;
  10334. };
  10335. var fromRgba = function (rgbaColour) {
  10336. var value = toHex(rgbaColour.red()) + toHex(rgbaColour.green()) + toHex(rgbaColour.blue());
  10337. return hexColour(value);
  10338. };
  10339. var min = Math.min;
  10340. var max = Math.max;
  10341. var round = Math.round;
  10342. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  10343. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  10344. var rgbaColour = function (red, green, blue, alpha) {
  10345. return {
  10346. red: constant(red),
  10347. green: constant(green),
  10348. blue: constant(blue),
  10349. alpha: constant(alpha)
  10350. };
  10351. };
  10352. var isRgbaComponent = function (value) {
  10353. var num = parseInt(value, 10);
  10354. return num.toString() === value && num >= 0 && num <= 255;
  10355. };
  10356. var fromHsv = function (hsv) {
  10357. var r;
  10358. var g;
  10359. var b;
  10360. var hue = (hsv.hue() || 0) % 360;
  10361. var saturation = hsv.saturation() / 100;
  10362. var brightness = hsv.value() / 100;
  10363. saturation = max(0, min(saturation, 1));
  10364. brightness = max(0, min(brightness, 1));
  10365. if (saturation === 0) {
  10366. r = g = b = round(255 * brightness);
  10367. return rgbaColour(r, g, b, 1);
  10368. }
  10369. var side = hue / 60;
  10370. var chroma = brightness * saturation;
  10371. var x = chroma * (1 - Math.abs(side % 2 - 1));
  10372. var match = brightness - chroma;
  10373. switch (Math.floor(side)) {
  10374. case 0:
  10375. r = chroma;
  10376. g = x;
  10377. b = 0;
  10378. break;
  10379. case 1:
  10380. r = x;
  10381. g = chroma;
  10382. b = 0;
  10383. break;
  10384. case 2:
  10385. r = 0;
  10386. g = chroma;
  10387. b = x;
  10388. break;
  10389. case 3:
  10390. r = 0;
  10391. g = x;
  10392. b = chroma;
  10393. break;
  10394. case 4:
  10395. r = x;
  10396. g = 0;
  10397. b = chroma;
  10398. break;
  10399. case 5:
  10400. r = chroma;
  10401. g = 0;
  10402. b = x;
  10403. break;
  10404. default:
  10405. r = g = b = 0;
  10406. }
  10407. r = round(255 * (r + match));
  10408. g = round(255 * (g + match));
  10409. b = round(255 * (b + match));
  10410. return rgbaColour(r, g, b, 1);
  10411. };
  10412. var fromHex = function (hexColour) {
  10413. var result = extractValues(hexColour);
  10414. var red = parseInt(result[1], 16);
  10415. var green = parseInt(result[2], 16);
  10416. var blue = parseInt(result[3], 16);
  10417. return rgbaColour(red, green, blue, 1);
  10418. };
  10419. var fromStringValues = function (red, green, blue, alpha) {
  10420. var r = parseInt(red, 10);
  10421. var g = parseInt(green, 10);
  10422. var b = parseInt(blue, 10);
  10423. var a = parseFloat(alpha);
  10424. return rgbaColour(r, g, b, a);
  10425. };
  10426. var fromString = function (rgbaString) {
  10427. if (rgbaString === 'transparent') {
  10428. return Option.some(rgbaColour(0, 0, 0, 0));
  10429. }
  10430. var rgbMatch = rgbRegex.exec(rgbaString);
  10431. if (rgbMatch !== null) {
  10432. return Option.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  10433. }
  10434. var rgbaMatch = rgbaRegex.exec(rgbaString);
  10435. if (rgbaMatch !== null) {
  10436. return Option.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  10437. }
  10438. return Option.none();
  10439. };
  10440. var toString = function (rgba) {
  10441. return 'rgba(' + rgba.red() + ',' + rgba.green() + ',' + rgba.blue() + ',' + rgba.alpha() + ')';
  10442. };
  10443. var redColour = constant(rgbaColour(255, 0, 0, 1));
  10444. var global$8 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  10445. var storageName = 'tinymce-custom-colors';
  10446. function ColorCache (max) {
  10447. if (max === void 0) {
  10448. max = 10;
  10449. }
  10450. var storageString = global$8.getItem(storageName);
  10451. var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  10452. var prune = function (list) {
  10453. var diff = max - list.length;
  10454. return diff < 0 ? list.slice(0, max) : list;
  10455. };
  10456. var cache = prune(localstorage);
  10457. var add = function (key) {
  10458. indexOf(cache, key).each(remove);
  10459. cache.unshift(key);
  10460. if (cache.length > max) {
  10461. cache.pop();
  10462. }
  10463. global$8.setItem(storageName, JSON.stringify(cache));
  10464. };
  10465. var remove = function (idx) {
  10466. cache.splice(idx, 1);
  10467. };
  10468. var state = function () {
  10469. return cache.slice(0);
  10470. };
  10471. return {
  10472. add: add,
  10473. state: state
  10474. };
  10475. }
  10476. var choiceItem = 'choiceitem';
  10477. var defaultColors = [
  10478. {
  10479. type: choiceItem,
  10480. text: 'Light Green',
  10481. value: '#BFEDD2'
  10482. },
  10483. {
  10484. type: choiceItem,
  10485. text: 'Light Yellow',
  10486. value: '#FBEEB8'
  10487. },
  10488. {
  10489. type: choiceItem,
  10490. text: 'Light Red',
  10491. value: '#F8CAC6'
  10492. },
  10493. {
  10494. type: choiceItem,
  10495. text: 'Light Purple',
  10496. value: '#ECCAFA'
  10497. },
  10498. {
  10499. type: choiceItem,
  10500. text: 'Light Blue',
  10501. value: '#C2E0F4'
  10502. },
  10503. {
  10504. type: choiceItem,
  10505. text: 'Green',
  10506. value: '#2DC26B'
  10507. },
  10508. {
  10509. type: choiceItem,
  10510. text: 'Yellow',
  10511. value: '#F1C40F'
  10512. },
  10513. {
  10514. type: choiceItem,
  10515. text: 'Red',
  10516. value: '#E03E2D'
  10517. },
  10518. {
  10519. type: choiceItem,
  10520. text: 'Purple',
  10521. value: '#B96AD9'
  10522. },
  10523. {
  10524. type: choiceItem,
  10525. text: 'Blue',
  10526. value: '#3598DB'
  10527. },
  10528. {
  10529. type: choiceItem,
  10530. text: 'Dark Turquoise',
  10531. value: '#169179'
  10532. },
  10533. {
  10534. type: choiceItem,
  10535. text: 'Orange',
  10536. value: '#E67E23'
  10537. },
  10538. {
  10539. type: choiceItem,
  10540. text: 'Dark Red',
  10541. value: '#BA372A'
  10542. },
  10543. {
  10544. type: choiceItem,
  10545. text: 'Dark Purple',
  10546. value: '#843FA1'
  10547. },
  10548. {
  10549. type: choiceItem,
  10550. text: 'Dark Blue',
  10551. value: '#236FA1'
  10552. },
  10553. {
  10554. type: choiceItem,
  10555. text: 'Light Gray',
  10556. value: '#ECF0F1'
  10557. },
  10558. {
  10559. type: choiceItem,
  10560. text: 'Medium Gray',
  10561. value: '#CED4D9'
  10562. },
  10563. {
  10564. type: choiceItem,
  10565. text: 'Gray',
  10566. value: '#95A5A6'
  10567. },
  10568. {
  10569. type: choiceItem,
  10570. text: 'Dark Gray',
  10571. value: '#7E8C8D'
  10572. },
  10573. {
  10574. type: choiceItem,
  10575. text: 'Navy Blue',
  10576. value: '#34495E'
  10577. },
  10578. {
  10579. type: choiceItem,
  10580. text: 'Black',
  10581. value: '#000000'
  10582. },
  10583. {
  10584. type: choiceItem,
  10585. text: 'White',
  10586. value: '#ffffff'
  10587. }
  10588. ];
  10589. var colorCache = ColorCache(10);
  10590. var mapColors = function (colorMap) {
  10591. var colors = [];
  10592. var canvas = domGlobals.document.createElement('canvas');
  10593. canvas.height = 1;
  10594. canvas.width = 1;
  10595. var ctx = canvas.getContext('2d');
  10596. var byteAsHex = function (colorByte, alphaByte) {
  10597. var bg = 255;
  10598. var alpha = alphaByte / 255;
  10599. var colorByteWithWhiteBg = Math.round(colorByte * alpha + bg * (1 - alpha));
  10600. return ('0' + colorByteWithWhiteBg.toString(16)).slice(-2).toUpperCase();
  10601. };
  10602. var asHexColor = function (color) {
  10603. if (/^[0-9A-Fa-f]{6}$/.test(color)) {
  10604. return '#' + color.toUpperCase();
  10605. }
  10606. ctx.clearRect(0, 0, canvas.width, canvas.height);
  10607. ctx.fillStyle = '#FFFFFF';
  10608. ctx.fillStyle = color;
  10609. ctx.fillRect(0, 0, 1, 1);
  10610. var rgba = ctx.getImageData(0, 0, 1, 1).data;
  10611. var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3];
  10612. return '#' + byteAsHex(r, a) + byteAsHex(g, a) + byteAsHex(b, a);
  10613. };
  10614. for (var i = 0; i < colorMap.length; i += 2) {
  10615. colors.push({
  10616. text: colorMap[i + 1],
  10617. value: asHexColor(colorMap[i]),
  10618. type: 'choiceitem'
  10619. });
  10620. }
  10621. return colors;
  10622. };
  10623. var getColorCols = function (editor, defaultCols) {
  10624. return editor.getParam('color_cols', defaultCols, 'number');
  10625. };
  10626. var hasCustomColors = function (editor) {
  10627. return editor.getParam('custom_colors') !== false;
  10628. };
  10629. var getColorMap = function (editor) {
  10630. return editor.getParam('color_map');
  10631. };
  10632. var getColors = function (editor) {
  10633. var unmapped = getColorMap(editor);
  10634. return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  10635. };
  10636. var getCurrentColors = function () {
  10637. return map(colorCache.state(), function (color) {
  10638. return {
  10639. type: choiceItem,
  10640. text: color,
  10641. value: color
  10642. };
  10643. });
  10644. };
  10645. var addColor = function (color) {
  10646. colorCache.add(color);
  10647. };
  10648. var Settings = {
  10649. mapColors: mapColors,
  10650. getColorCols: getColorCols,
  10651. hasCustomColors: hasCustomColors,
  10652. getColorMap: getColorMap,
  10653. getColors: getColors,
  10654. getCurrentColors: getCurrentColors,
  10655. addColor: addColor
  10656. };
  10657. var fireSkinLoaded = function (editor) {
  10658. return editor.fire('SkinLoaded');
  10659. };
  10660. var fireResizeEditor = function (editor) {
  10661. return editor.fire('ResizeEditor');
  10662. };
  10663. var fireBeforeRenderUI = function (editor) {
  10664. return editor.fire('BeforeRenderUI');
  10665. };
  10666. var fireResizeContent = function (editor, e) {
  10667. return editor.fire('ResizeContent', e);
  10668. };
  10669. var fireScrollContent = function (editor, e) {
  10670. return editor.fire('ScrollContent', e);
  10671. };
  10672. var fireTextColorChange = function (editor, data) {
  10673. return editor.fire('TextColorChange', data);
  10674. };
  10675. var Events = {
  10676. fireSkinLoaded: fireSkinLoaded,
  10677. fireResizeEditor: fireResizeEditor,
  10678. fireScrollContent: fireScrollContent,
  10679. fireBeforeRenderUI: fireBeforeRenderUI,
  10680. fireResizeContent: fireResizeContent,
  10681. fireTextColorChange: fireTextColorChange
  10682. };
  10683. var getCurrentColor = function (editor, format) {
  10684. var color;
  10685. editor.dom.getParents(editor.selection.getStart(), function (elm) {
  10686. var value;
  10687. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  10688. color = color ? color : value;
  10689. }
  10690. });
  10691. return color;
  10692. };
  10693. var applyFormat = function (editor, format, value) {
  10694. editor.undoManager.transact(function () {
  10695. editor.focus();
  10696. editor.formatter.apply(format, { value: value });
  10697. editor.nodeChanged();
  10698. });
  10699. };
  10700. var removeFormat = function (editor, format) {
  10701. editor.undoManager.transact(function () {
  10702. editor.focus();
  10703. editor.formatter.remove(format, { value: null }, null, true);
  10704. editor.nodeChanged();
  10705. });
  10706. };
  10707. var registerCommands = function (editor) {
  10708. editor.addCommand('mceApplyTextcolor', function (format, value) {
  10709. applyFormat(editor, format, value);
  10710. });
  10711. editor.addCommand('mceRemoveTextcolor', function (format) {
  10712. removeFormat(editor, format);
  10713. });
  10714. };
  10715. var calcCols = function (colors) {
  10716. return Math.max(5, Math.ceil(Math.sqrt(colors)));
  10717. };
  10718. var getColorCols$1 = function (editor) {
  10719. var colors = Settings.getColors(editor);
  10720. var defaultCols = calcCols(colors.length);
  10721. return Settings.getColorCols(editor, defaultCols);
  10722. };
  10723. var getAdditionalColors = function (hasCustom) {
  10724. var type = 'choiceitem';
  10725. var remove = {
  10726. type: type,
  10727. text: 'Remove color',
  10728. icon: 'color-swatch-remove-color',
  10729. value: 'remove'
  10730. };
  10731. var custom = {
  10732. type: type,
  10733. text: 'Custom color',
  10734. icon: 'color-picker',
  10735. value: 'custom'
  10736. };
  10737. return hasCustom ? [
  10738. remove,
  10739. custom
  10740. ] : [remove];
  10741. };
  10742. var applyColor = function (editor, format, value, onChoice) {
  10743. if (value === 'custom') {
  10744. var dialog = colorPickerDialog(editor);
  10745. dialog(function (colorOpt) {
  10746. colorOpt.each(function (color) {
  10747. Settings.addColor(color);
  10748. editor.execCommand('mceApplyTextcolor', format, color);
  10749. onChoice(color);
  10750. });
  10751. }, '#000000');
  10752. } else if (value === 'remove') {
  10753. onChoice('');
  10754. editor.execCommand('mceRemoveTextcolor', format);
  10755. } else {
  10756. onChoice(value);
  10757. editor.execCommand('mceApplyTextcolor', format, value);
  10758. }
  10759. };
  10760. var getMenuColors = function (colors, hasCustom) {
  10761. return colors.concat(Settings.getCurrentColors().concat(getAdditionalColors(hasCustom)));
  10762. };
  10763. var getFetch = function (colors, hasCustom) {
  10764. return function (callback) {
  10765. callback(getMenuColors(colors, hasCustom));
  10766. };
  10767. };
  10768. var setIconColor = function (splitButtonApi, name, newColor) {
  10769. var setIconFillAndStroke = function (pathId, color) {
  10770. splitButtonApi.setIconFill(pathId, color);
  10771. splitButtonApi.setIconStroke(pathId, color);
  10772. };
  10773. var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  10774. setIconFillAndStroke(id, newColor);
  10775. };
  10776. var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  10777. editor.ui.registry.addSplitButton(name, {
  10778. tooltip: tooltip,
  10779. presets: 'color',
  10780. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  10781. select: function (value) {
  10782. var optCurrentRgb = Option.from(getCurrentColor(editor, format));
  10783. return optCurrentRgb.bind(function (currentRgb) {
  10784. return fromString(currentRgb).map(function (rgba) {
  10785. var currentHex = fromRgba(rgba).value();
  10786. return contains$1(value.toLowerCase(), currentHex);
  10787. });
  10788. }).getOr(false);
  10789. },
  10790. columns: getColorCols$1(editor),
  10791. fetch: getFetch(Settings.getColors(editor), Settings.hasCustomColors(editor)),
  10792. onAction: function (splitButtonApi) {
  10793. if (lastColor.get() !== null) {
  10794. applyColor(editor, format, lastColor.get(), function () {
  10795. });
  10796. }
  10797. },
  10798. onItemAction: function (splitButtonApi, value) {
  10799. applyColor(editor, format, value, function (newColor) {
  10800. lastColor.set(newColor);
  10801. Events.fireTextColorChange(editor, {
  10802. name: name,
  10803. color: newColor
  10804. });
  10805. });
  10806. },
  10807. onSetup: function (splitButtonApi) {
  10808. if (lastColor.get() !== null) {
  10809. setIconColor(splitButtonApi, name, lastColor.get());
  10810. }
  10811. var handler = function (e) {
  10812. if (e.name === name) {
  10813. setIconColor(splitButtonApi, e.name, e.color);
  10814. }
  10815. };
  10816. editor.on('TextColorChange', handler);
  10817. return function () {
  10818. editor.off('TextColorChange', handler);
  10819. };
  10820. }
  10821. });
  10822. };
  10823. var registerTextColorMenuItem = function (editor, name, format, text) {
  10824. editor.ui.registry.addNestedMenuItem(name, {
  10825. text: text,
  10826. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  10827. getSubmenuItems: function () {
  10828. return [{
  10829. type: 'fancymenuitem',
  10830. fancytype: 'colorswatch',
  10831. onAction: function (data) {
  10832. applyColor(editor, format, data.value, noop);
  10833. }
  10834. }];
  10835. }
  10836. });
  10837. };
  10838. var colorPickerDialog = function (editor) {
  10839. return function (callback, value) {
  10840. var getOnSubmit = function (callback) {
  10841. return function (api) {
  10842. var data = api.getData();
  10843. callback(Option.from(data.colorpicker));
  10844. api.close();
  10845. };
  10846. };
  10847. var onAction = function (api, details) {
  10848. if (details.name === 'hex-valid') {
  10849. if (details.value) {
  10850. api.enable('ok');
  10851. } else {
  10852. api.disable('ok');
  10853. }
  10854. }
  10855. };
  10856. var initialData = { colorpicker: value };
  10857. var submit = getOnSubmit(callback);
  10858. editor.windowManager.open({
  10859. title: 'Color Picker',
  10860. size: 'normal',
  10861. body: {
  10862. type: 'panel',
  10863. items: [{
  10864. type: 'colorpicker',
  10865. name: 'colorpicker',
  10866. label: 'Color'
  10867. }]
  10868. },
  10869. buttons: [
  10870. {
  10871. type: 'cancel',
  10872. name: 'cancel',
  10873. text: 'Cancel'
  10874. },
  10875. {
  10876. type: 'submit',
  10877. name: 'save',
  10878. text: 'Save',
  10879. primary: true
  10880. }
  10881. ],
  10882. initialData: initialData,
  10883. onAction: onAction,
  10884. onSubmit: submit,
  10885. onClose: function () {
  10886. },
  10887. onCancel: function () {
  10888. callback(Option.none());
  10889. }
  10890. });
  10891. };
  10892. };
  10893. var register$1 = function (editor) {
  10894. registerCommands(editor);
  10895. var lastForeColor = Cell(null);
  10896. var lastBackColor = Cell(null);
  10897. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  10898. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  10899. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  10900. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  10901. };
  10902. var ColorSwatch = {
  10903. register: register$1,
  10904. getColors: getMenuColors,
  10905. getFetch: getFetch,
  10906. colorPickerDialog: colorPickerDialog,
  10907. getCurrentColor: getCurrentColor,
  10908. getColorCols: getColorCols$1,
  10909. calcCols: calcCols
  10910. };
  10911. var chunk$1 = function (rowDom, numColumns) {
  10912. return function (items) {
  10913. var chunks = chunk(items, numColumns);
  10914. return map(chunks, function (c) {
  10915. return {
  10916. dom: rowDom,
  10917. components: c
  10918. };
  10919. });
  10920. };
  10921. };
  10922. var forSwatch = function (columns) {
  10923. return {
  10924. dom: {
  10925. tag: 'div',
  10926. classes: [
  10927. 'tox-menu',
  10928. 'tox-swatches-menu'
  10929. ]
  10930. },
  10931. components: [{
  10932. dom: {
  10933. tag: 'div',
  10934. classes: ['tox-swatches']
  10935. },
  10936. components: [Menu.parts().items({
  10937. preprocess: columns !== 'auto' ? chunk$1({
  10938. tag: 'div',
  10939. classes: ['tox-swatches__row']
  10940. }, columns) : identity
  10941. })]
  10942. }]
  10943. };
  10944. };
  10945. var forToolbar = function (columns) {
  10946. return {
  10947. dom: {
  10948. tag: 'div',
  10949. classes: [
  10950. 'tox-menu',
  10951. 'tox-collection',
  10952. 'tox-collection--toolbar',
  10953. 'tox-collection--toolbar-lg'
  10954. ]
  10955. },
  10956. components: [Menu.parts().items({
  10957. preprocess: chunk$1({
  10958. tag: 'div',
  10959. classes: ['tox-collection__group']
  10960. }, columns)
  10961. })]
  10962. };
  10963. };
  10964. var preprocessCollection = function (items, isSeparator) {
  10965. var allSplits = [];
  10966. var currentSplit = [];
  10967. each(items, function (item, i) {
  10968. if (isSeparator(item, i)) {
  10969. if (currentSplit.length > 0) {
  10970. allSplits.push(currentSplit);
  10971. }
  10972. currentSplit = [];
  10973. if (has(item.dom, 'innerHtml')) {
  10974. currentSplit.push(item);
  10975. }
  10976. } else {
  10977. currentSplit.push(item);
  10978. }
  10979. });
  10980. if (currentSplit.length > 0) {
  10981. allSplits.push(currentSplit);
  10982. }
  10983. return map(allSplits, function (s) {
  10984. return {
  10985. dom: {
  10986. tag: 'div',
  10987. classes: ['tox-collection__group']
  10988. },
  10989. components: s
  10990. };
  10991. });
  10992. };
  10993. var forCollection = function (columns, initItems, _hasIcons) {
  10994. return {
  10995. dom: {
  10996. tag: 'div',
  10997. classes: [
  10998. 'tox-menu',
  10999. 'tox-collection'
  11000. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  11001. },
  11002. components: [Menu.parts().items({
  11003. preprocess: function (items) {
  11004. if (columns !== 'auto' && columns > 1) {
  11005. return chunk$1({
  11006. tag: 'div',
  11007. classes: ['tox-collection__group']
  11008. }, columns)(items);
  11009. } else {
  11010. return preprocessCollection(items, function (_item, i) {
  11011. return initItems[i].type === 'separator';
  11012. });
  11013. }
  11014. }
  11015. })]
  11016. };
  11017. };
  11018. var forHorizontalCollection = function (initItems, _hasIcons) {
  11019. return {
  11020. dom: {
  11021. tag: 'div',
  11022. classes: [
  11023. 'tox-collection',
  11024. 'tox-collection--horizontal'
  11025. ]
  11026. },
  11027. components: [Menu.parts().items({
  11028. preprocess: function (items) {
  11029. return preprocessCollection(items, function (_item, i) {
  11030. return initItems[i].type === 'separator';
  11031. });
  11032. }
  11033. })]
  11034. };
  11035. };
  11036. var forMenu = function (presets) {
  11037. if (presets === 'color') {
  11038. return 'tox-swatches';
  11039. } else {
  11040. return 'tox-menu';
  11041. }
  11042. };
  11043. var classes = function (presets) {
  11044. return {
  11045. backgroundMenu: 'tox-background-menu',
  11046. selectedMenu: 'tox-selected-menu',
  11047. selectedItem: 'tox-collection__item--active',
  11048. hasIcons: 'tox-menu--has-icons',
  11049. menu: forMenu(presets),
  11050. tieredMenu: 'tox-tiered-menu'
  11051. };
  11052. };
  11053. var markers$1 = function (presets) {
  11054. var menuClasses = classes(presets);
  11055. return {
  11056. backgroundMenu: menuClasses.backgroundMenu,
  11057. selectedMenu: menuClasses.selectedMenu,
  11058. menu: menuClasses.menu,
  11059. selectedItem: menuClasses.selectedItem,
  11060. item: classForPreset(presets)
  11061. };
  11062. };
  11063. var dom$1 = function (hasIcons, columns, presets) {
  11064. var menuClasses = classes(presets);
  11065. return {
  11066. tag: 'div',
  11067. classes: flatten([
  11068. [
  11069. menuClasses.menu,
  11070. 'tox-menu-' + columns + '-column'
  11071. ],
  11072. hasIcons ? [menuClasses.hasIcons] : []
  11073. ])
  11074. };
  11075. };
  11076. var components$1 = [Menu.parts().items({})];
  11077. var part = function (hasIcons, columns, presets) {
  11078. var menuClasses = classes(presets);
  11079. var d = {
  11080. tag: 'div',
  11081. classes: flatten([[menuClasses.tieredMenu]])
  11082. };
  11083. return {
  11084. dom: d,
  11085. markers: markers$1(presets)
  11086. };
  11087. };
  11088. var hasIcon = function (item) {
  11089. return item.icon !== undefined || item.type === 'togglemenuitem' || item.type === 'choicemenuitem';
  11090. };
  11091. var menuHasIcons = function (xs) {
  11092. return exists(xs, hasIcon);
  11093. };
  11094. var handleError = function (error) {
  11095. domGlobals.console.error(formatError(error));
  11096. domGlobals.console.log(error);
  11097. return Option.none();
  11098. };
  11099. var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  11100. var structure = forHorizontalCollection(items);
  11101. return {
  11102. value: value,
  11103. dom: structure.dom,
  11104. components: structure.components,
  11105. items: items
  11106. };
  11107. };
  11108. var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  11109. if (presets === 'color') {
  11110. var structure = forSwatch(columns);
  11111. return {
  11112. value: value,
  11113. dom: structure.dom,
  11114. components: structure.components,
  11115. items: items
  11116. };
  11117. }
  11118. if (presets === 'normal' && columns === 'auto') {
  11119. var structure = forCollection(columns, items);
  11120. return {
  11121. value: value,
  11122. dom: structure.dom,
  11123. components: structure.components,
  11124. items: items
  11125. };
  11126. }
  11127. if (presets === 'normal' && columns === 1) {
  11128. var structure = forCollection(1, items);
  11129. return {
  11130. value: value,
  11131. dom: structure.dom,
  11132. components: structure.components,
  11133. items: items
  11134. };
  11135. }
  11136. if (presets === 'normal') {
  11137. var structure = forCollection(columns, items);
  11138. return {
  11139. value: value,
  11140. dom: structure.dom,
  11141. components: structure.components,
  11142. items: items
  11143. };
  11144. }
  11145. if (presets === 'listpreview' && columns !== 'auto') {
  11146. var structure = forToolbar(columns);
  11147. return {
  11148. value: value,
  11149. dom: structure.dom,
  11150. components: structure.components,
  11151. items: items
  11152. };
  11153. }
  11154. return {
  11155. value: value,
  11156. dom: dom$1(hasIcons, columns, presets),
  11157. components: components$1,
  11158. items: items
  11159. };
  11160. };
  11161. var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  11162. var hasIcons = menuHasIcons(items);
  11163. var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  11164. var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  11165. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  11166. };
  11167. var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  11168. return cat(map(items, function (item) {
  11169. if (item.type === 'choiceitem') {
  11170. return createChoiceMenuItem(item).fold(handleError, function (d) {
  11171. return Option.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage));
  11172. });
  11173. } else {
  11174. return Option.none();
  11175. }
  11176. }));
  11177. };
  11178. var deriveMenuMovement = function (columns, presets) {
  11179. var menuMarkers = markers$1(presets);
  11180. if (columns === 1) {
  11181. return {
  11182. mode: 'menu',
  11183. moveOnTab: true
  11184. };
  11185. } else if (columns === 'auto') {
  11186. return {
  11187. mode: 'grid',
  11188. selector: '.' + menuMarkers.item,
  11189. initSize: {
  11190. numColumns: 1,
  11191. numRows: 1
  11192. }
  11193. };
  11194. } else {
  11195. var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  11196. return {
  11197. mode: 'matrix',
  11198. rowSelector: '.' + rowClass
  11199. };
  11200. }
  11201. };
  11202. var deriveCollectionMovement = function (columns, presets) {
  11203. if (columns === 1) {
  11204. return {
  11205. mode: 'menu',
  11206. moveOnTab: false,
  11207. selector: '.tox-collection__item'
  11208. };
  11209. } else if (columns === 'auto') {
  11210. return {
  11211. mode: 'flatgrid',
  11212. selector: '.' + 'tox-collection__item',
  11213. initSize: {
  11214. numColumns: 1,
  11215. numRows: 1
  11216. }
  11217. };
  11218. } else {
  11219. return {
  11220. mode: 'matrix',
  11221. selectors: {
  11222. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  11223. cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  11224. }
  11225. };
  11226. }
  11227. };
  11228. function renderColorSwatchItem(spec, backstage) {
  11229. var items = ColorSwatch.getColors(backstage.colorinput.getColors(), backstage.colorinput.hasCustomColors());
  11230. var columns = backstage.colorinput.getColorCols();
  11231. var presets = 'color';
  11232. var menuSpec = createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  11233. spec.onAction({ value: value });
  11234. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  11235. return false;
  11236. }, backstage.shared.providers);
  11237. var widgetSpec = deepMerge(__assign(__assign({}, menuSpec), {
  11238. markers: markers$1(presets),
  11239. movement: deriveMenuMovement(columns, presets)
  11240. }));
  11241. return {
  11242. type: 'widget',
  11243. data: { value: generate$1('widget-id') },
  11244. dom: {
  11245. tag: 'div',
  11246. classes: ['tox-fancymenuitem']
  11247. },
  11248. autofocus: true,
  11249. components: [parts$2().widget(Menu.sketch(widgetSpec))]
  11250. };
  11251. }
  11252. var fancyMenuItems = {
  11253. inserttable: renderInsertTableMenuItem,
  11254. colorswatch: renderColorSwatchItem
  11255. };
  11256. var valueOpt = function (obj, key) {
  11257. return Object.prototype.hasOwnProperty.call(obj, key) ? Option.some(obj[key]) : Option.none();
  11258. };
  11259. var renderFancyMenuItem = function (spec, backstage) {
  11260. return valueOpt(fancyMenuItems, spec.fancytype).map(function (render) {
  11261. return render(spec, backstage);
  11262. });
  11263. };
  11264. var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  11265. if (renderIcons === void 0) {
  11266. renderIcons = true;
  11267. }
  11268. var getApi = function (component) {
  11269. return {
  11270. isDisabled: function () {
  11271. return Disabling.isDisabled(component);
  11272. },
  11273. setDisabled: function (state) {
  11274. return Disabling.set(component, state);
  11275. }
  11276. };
  11277. };
  11278. var structure = renderItemStructure({
  11279. presets: 'normal',
  11280. iconContent: spec.icon,
  11281. textContent: spec.text,
  11282. htmlContent: Option.none(),
  11283. ariaLabel: spec.text,
  11284. caret: Option.none(),
  11285. checkMark: Option.none(),
  11286. shortcutContent: spec.shortcut
  11287. }, providersBackstage, renderIcons);
  11288. return renderCommonItem({
  11289. data: buildData(spec),
  11290. getApi: getApi,
  11291. disabled: spec.disabled,
  11292. onAction: spec.onAction,
  11293. onSetup: spec.onSetup,
  11294. triggersSubmenu: false,
  11295. itemBehaviours: []
  11296. }, structure, itemResponse);
  11297. };
  11298. var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  11299. if (renderIcons === void 0) {
  11300. renderIcons = true;
  11301. }
  11302. if (downwardsCaret === void 0) {
  11303. downwardsCaret = false;
  11304. }
  11305. var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  11306. var getApi = function (component) {
  11307. return {
  11308. isDisabled: function () {
  11309. return Disabling.isDisabled(component);
  11310. },
  11311. setDisabled: function (state) {
  11312. return Disabling.set(component, state);
  11313. }
  11314. };
  11315. };
  11316. var structure = renderItemStructure({
  11317. presets: 'normal',
  11318. iconContent: spec.icon,
  11319. textContent: spec.text,
  11320. htmlContent: Option.none(),
  11321. ariaLabel: spec.text,
  11322. caret: Option.some(caret),
  11323. checkMark: Option.none(),
  11324. shortcutContent: spec.shortcut
  11325. }, providersBackstage, renderIcons);
  11326. return renderCommonItem({
  11327. data: buildData(spec),
  11328. getApi: getApi,
  11329. disabled: spec.disabled,
  11330. onAction: noop,
  11331. onSetup: spec.onSetup,
  11332. triggersSubmenu: true,
  11333. itemBehaviours: []
  11334. }, structure, itemResponse);
  11335. };
  11336. var renderSeparatorItem = function (spec) {
  11337. var innerHtml = spec.text.fold(function () {
  11338. return {};
  11339. }, function (text) {
  11340. return { innerHtml: text };
  11341. });
  11342. return {
  11343. type: 'separator',
  11344. dom: __assign({
  11345. tag: 'div',
  11346. classes: [
  11347. selectableClass,
  11348. groupHeadingClass
  11349. ]
  11350. }, innerHtml),
  11351. components: []
  11352. };
  11353. };
  11354. var renderToggleMenuItem = function (spec, itemResponse, providersBackstage) {
  11355. var getApi = function (component) {
  11356. return {
  11357. setActive: function (state) {
  11358. Toggling.set(component, state);
  11359. },
  11360. isActive: function () {
  11361. return Toggling.isOn(component);
  11362. },
  11363. isDisabled: function () {
  11364. return Disabling.isDisabled(component);
  11365. },
  11366. setDisabled: function (state) {
  11367. return Disabling.set(component, state);
  11368. }
  11369. };
  11370. };
  11371. var structure = renderItemStructure({
  11372. iconContent: Option.none(),
  11373. textContent: spec.text,
  11374. htmlContent: Option.none(),
  11375. ariaLabel: spec.text,
  11376. checkMark: Option.some(renderCheckmark(providersBackstage.icons)),
  11377. caret: Option.none(),
  11378. shortcutContent: spec.shortcut,
  11379. presets: 'normal',
  11380. meta: spec.meta
  11381. }, providersBackstage, true);
  11382. return deepMerge(renderCommonItem({
  11383. data: buildData(spec),
  11384. disabled: spec.disabled,
  11385. getApi: getApi,
  11386. onAction: spec.onAction,
  11387. onSetup: spec.onSetup,
  11388. triggersSubmenu: false,
  11389. itemBehaviours: []
  11390. }, structure, itemResponse), {
  11391. toggling: {
  11392. toggleClass: tickedClass,
  11393. toggleOnExecute: false,
  11394. selected: spec.active
  11395. }
  11396. });
  11397. };
  11398. var autocomplete = renderAutocompleteItem;
  11399. var separator = renderSeparatorItem;
  11400. var normal = renderNormalItem;
  11401. var nested = renderNestedItem;
  11402. var toggle$1 = renderToggleMenuItem;
  11403. var fancy = renderFancyMenuItem;
  11404. var FocusMode;
  11405. (function (FocusMode) {
  11406. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  11407. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  11408. }(FocusMode || (FocusMode = {})));
  11409. var hasIcon$1 = function (item) {
  11410. return item.icon !== undefined || item.type === 'togglemenuitem' || item.type === 'choicemenuitem';
  11411. };
  11412. var menuHasIcons$1 = function (xs) {
  11413. return exists(xs, hasIcon$1);
  11414. };
  11415. var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  11416. var providersBackstage = backstage.shared.providers;
  11417. var parseForHorizontalMenu = function (menuitem) {
  11418. return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  11419. shortcut: Option.none(),
  11420. icon: menuitem.text.isSome() ? Option.none() : menuitem.icon
  11421. });
  11422. };
  11423. switch (item.type) {
  11424. case 'menuitem':
  11425. return createMenuItem(item).fold(handleError, function (d) {
  11426. return Option.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  11427. });
  11428. case 'nestedmenuitem':
  11429. return createNestedMenuItem(item).fold(handleError, function (d) {
  11430. return Option.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  11431. });
  11432. case 'togglemenuitem':
  11433. return createToggleMenuItem(item).fold(handleError, function (d) {
  11434. return Option.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage));
  11435. });
  11436. case 'separator':
  11437. return createSeparatorMenuItem(item).fold(handleError, function (d) {
  11438. return Option.some(separator(d));
  11439. });
  11440. case 'fancymenuitem':
  11441. return createFancyMenuItem(item).fold(handleError, function (d) {
  11442. return fancy(parseForHorizontalMenu(d), backstage);
  11443. });
  11444. default: {
  11445. domGlobals.console.error('Unknown item in general menu', item);
  11446. return Option.none();
  11447. }
  11448. }
  11449. };
  11450. var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage) {
  11451. var renderText = columns === 1;
  11452. var renderIcons = !renderText || menuHasIcons$1(items);
  11453. return cat(map(items, function (item) {
  11454. if (item.type === 'separator') {
  11455. return createSeparatorItem(item).fold(handleError, function (d) {
  11456. return Option.some(separator(d));
  11457. });
  11458. } else {
  11459. return createAutocompleterItem(item).fold(handleError, function (d) {
  11460. return Option.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  11461. });
  11462. }
  11463. }));
  11464. };
  11465. var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  11466. var hasIcons = menuHasIcons$1(items);
  11467. var alloyItems = cat(map(items, function (item) {
  11468. var itemHasIcon = function (i) {
  11469. return isHorizontalMenu ? !i.hasOwnProperty('text') : hasIcons;
  11470. };
  11471. var createItem = function (i) {
  11472. return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  11473. };
  11474. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  11475. return createItem(merge(item, { disabled: true }));
  11476. } else {
  11477. return createItem(item);
  11478. }
  11479. }));
  11480. var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  11481. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  11482. };
  11483. var createTieredDataFrom = function (partialMenu) {
  11484. return tieredMenu.singleData(partialMenu.value, partialMenu);
  11485. };
  11486. var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  11487. var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom();
  11488. var movement = deriveMenuMovement(columns, presets);
  11489. var menuMarkers = markers$1(presets);
  11490. return {
  11491. dom: partialMenu.dom,
  11492. components: partialMenu.components,
  11493. items: partialMenu.items,
  11494. value: partialMenu.value,
  11495. markers: {
  11496. selectedItem: menuMarkers.selectedItem,
  11497. item: menuMarkers.item
  11498. },
  11499. movement: movement,
  11500. fakeFocus: focusMode === FocusMode.ContentFocus,
  11501. focusManager: focusManager,
  11502. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, se) {
  11503. detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  11504. var numColumns = _a.numColumns, numRows = _a.numRows;
  11505. Keying.setGridSize(comp, numRows, numColumns);
  11506. });
  11507. })])
  11508. };
  11509. };
  11510. var register$2 = function (editor, sharedBackstage) {
  11511. var activeAutocompleter = Cell(Option.none());
  11512. var processingAction = Cell(false);
  11513. var autocompleter = build$1(InlineView.sketch({
  11514. dom: {
  11515. tag: 'div',
  11516. classes: ['tox-autocompleter']
  11517. },
  11518. components: [],
  11519. fireDismissalEventInstead: {},
  11520. inlineBehaviours: derive$1([config('dismissAutocompleter', [run(dismissRequested(), function () {
  11521. return cancelIfNecessary();
  11522. })])]),
  11523. lazySink: sharedBackstage.getSink
  11524. }));
  11525. var isMenuOpen = function () {
  11526. return InlineView.isOpen(autocompleter);
  11527. };
  11528. var isActive = function () {
  11529. return activeAutocompleter.get().isSome();
  11530. };
  11531. var hideIfNecessary = function () {
  11532. if (isActive()) {
  11533. InlineView.hide(autocompleter);
  11534. }
  11535. };
  11536. var cancelIfNecessary = function () {
  11537. if (isActive()) {
  11538. var lastElement = activeAutocompleter.get().map(function (ac) {
  11539. return ac.element;
  11540. });
  11541. detect$4(lastElement.getOr(Element.fromDom(editor.selection.getNode()))).each(unwrap);
  11542. hideIfNecessary();
  11543. activeAutocompleter.set(Option.none());
  11544. processingAction.set(false);
  11545. }
  11546. };
  11547. var getAutocompleters = cached(function () {
  11548. return register(editor);
  11549. });
  11550. var getCombinedItems = function (triggerChar, matches) {
  11551. var columns = findMap(matches, function (m) {
  11552. return Option.from(m.columns);
  11553. }).getOr(1);
  11554. return bind(matches, function (match) {
  11555. var choices = match.items;
  11556. return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  11557. var nr = editor.selection.getRng();
  11558. getContext(editor.dom, nr, triggerChar).fold(function () {
  11559. return domGlobals.console.error('Lost context. Cursor probably moved');
  11560. }, function (_a) {
  11561. var range = _a.range;
  11562. var autocompleterApi = {
  11563. hide: function () {
  11564. cancelIfNecessary();
  11565. },
  11566. reload: function (fetchOptions) {
  11567. hideIfNecessary();
  11568. load(fetchOptions);
  11569. }
  11570. };
  11571. processingAction.set(true);
  11572. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  11573. processingAction.set(false);
  11574. });
  11575. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage);
  11576. });
  11577. };
  11578. var commenceIfNecessary = function (context) {
  11579. if (!isActive()) {
  11580. var wrapper = create$4(editor, context.range);
  11581. activeAutocompleter.set(Option.some({
  11582. triggerChar: context.triggerChar,
  11583. element: wrapper,
  11584. matchLength: context.text.length
  11585. }));
  11586. processingAction.set(false);
  11587. }
  11588. };
  11589. var display = function (ac, context, lookupData, items) {
  11590. ac.matchLength = context.text.length;
  11591. var columns = findMap(lookupData, function (ld) {
  11592. return Option.from(ld.columns);
  11593. }).getOr(1);
  11594. InlineView.showAt(autocompleter, {
  11595. anchor: 'node',
  11596. root: Element.fromDom(editor.getBody()),
  11597. node: Option.from(ac.element)
  11598. }, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')));
  11599. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  11600. };
  11601. var doLookup = function (fetchOptions) {
  11602. return activeAutocompleter.get().map(function (ac) {
  11603. return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  11604. return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  11605. });
  11606. }).getOrThunk(function () {
  11607. return lookup(editor, getAutocompleters);
  11608. });
  11609. };
  11610. var load = function (fetchOptions) {
  11611. doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  11612. commenceIfNecessary(lookupInfo.context);
  11613. lookupInfo.lookupData.then(function (lookupData) {
  11614. activeAutocompleter.get().map(function (ac) {
  11615. var context = lookupInfo.context;
  11616. if (ac.triggerChar === context.triggerChar) {
  11617. var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  11618. if (combinedItems.length > 0) {
  11619. display(ac, context, lookupData, combinedItems);
  11620. } else if (context.text.length - ac.matchLength >= 10) {
  11621. cancelIfNecessary();
  11622. } else {
  11623. hideIfNecessary();
  11624. }
  11625. }
  11626. });
  11627. });
  11628. });
  11629. };
  11630. var onKeypress = last$2(function (e) {
  11631. if (e.which === 27) {
  11632. return;
  11633. }
  11634. load();
  11635. }, 50);
  11636. var autocompleterUiApi = {
  11637. onKeypress: onKeypress,
  11638. cancelIfNecessary: cancelIfNecessary,
  11639. isMenuOpen: isMenuOpen,
  11640. isActive: isActive,
  11641. isProcessingAction: processingAction.get,
  11642. getView: function () {
  11643. return InlineView.getContent(autocompleter);
  11644. }
  11645. };
  11646. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  11647. };
  11648. var Autocompleter = { register: register$2 };
  11649. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  11650. return {
  11651. target: constant(target),
  11652. x: constant(x),
  11653. y: constant(y),
  11654. stop: stop,
  11655. prevent: prevent,
  11656. kill: kill,
  11657. raw: constant(raw)
  11658. };
  11659. };
  11660. var fromRawEvent = function (rawEvent) {
  11661. var target = Element.fromDom(rawEvent.target);
  11662. var stop = function () {
  11663. rawEvent.stopPropagation();
  11664. };
  11665. var prevent = function () {
  11666. rawEvent.preventDefault();
  11667. };
  11668. var kill = compose(prevent, stop);
  11669. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  11670. };
  11671. var handle = function (filter, handler) {
  11672. return function (rawEvent) {
  11673. if (!filter(rawEvent)) {
  11674. return;
  11675. }
  11676. handler(fromRawEvent(rawEvent));
  11677. };
  11678. };
  11679. var binder = function (element, event, filter, handler, useCapture) {
  11680. var wrapped = handle(filter, handler);
  11681. element.dom().addEventListener(event, wrapped, useCapture);
  11682. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  11683. };
  11684. var bind$2 = function (element, event, filter, handler) {
  11685. return binder(element, event, filter, handler, false);
  11686. };
  11687. var capture = function (element, event, filter, handler) {
  11688. return binder(element, event, filter, handler, true);
  11689. };
  11690. var unbind = function (element, event, handler, useCapture) {
  11691. element.dom().removeEventListener(event, handler, useCapture);
  11692. };
  11693. var filter$1 = constant(true);
  11694. var bind$3 = function (element, event, handler) {
  11695. return bind$2(element, event, filter$1, handler);
  11696. };
  11697. var capture$1 = function (element, event, handler) {
  11698. return capture(element, event, filter$1, handler);
  11699. };
  11700. var fromRawEvent$1 = fromRawEvent;
  11701. var closest$4 = function (scope, selector, isRoot) {
  11702. return closest$3(scope, selector, isRoot).isSome();
  11703. };
  11704. function DelayedFunction (fun, delay) {
  11705. var ref = null;
  11706. var schedule = function () {
  11707. var args = [];
  11708. for (var _i = 0; _i < arguments.length; _i++) {
  11709. args[_i] = arguments[_i];
  11710. }
  11711. ref = domGlobals.setTimeout(function () {
  11712. fun.apply(null, args);
  11713. ref = null;
  11714. }, delay);
  11715. };
  11716. var cancel = function () {
  11717. if (ref !== null) {
  11718. domGlobals.clearTimeout(ref);
  11719. ref = null;
  11720. }
  11721. };
  11722. return {
  11723. cancel: cancel,
  11724. schedule: schedule
  11725. };
  11726. }
  11727. var SIGNIFICANT_MOVE = 5;
  11728. var LONGPRESS_DELAY = 400;
  11729. var getTouch = function (event) {
  11730. var raw = event.raw();
  11731. if (raw.touches === undefined || raw.touches.length !== 1) {
  11732. return Option.none();
  11733. }
  11734. return Option.some(raw.touches[0]);
  11735. };
  11736. var isFarEnough = function (touch, data) {
  11737. var distX = Math.abs(touch.clientX - data.x());
  11738. var distY = Math.abs(touch.clientY - data.y());
  11739. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  11740. };
  11741. var monitor = function (settings) {
  11742. var startData = Cell(Option.none());
  11743. var longpressFired = Cell(false);
  11744. var longpress$1 = DelayedFunction(function (event) {
  11745. settings.triggerEvent(longpress(), event);
  11746. longpressFired.set(true);
  11747. }, LONGPRESS_DELAY);
  11748. var handleTouchstart = function (event) {
  11749. getTouch(event).each(function (touch) {
  11750. longpress$1.cancel();
  11751. var data = {
  11752. x: constant(touch.clientX),
  11753. y: constant(touch.clientY),
  11754. target: event.target
  11755. };
  11756. longpress$1.schedule(event);
  11757. longpressFired.set(false);
  11758. startData.set(Option.some(data));
  11759. });
  11760. return Option.none();
  11761. };
  11762. var handleTouchmove = function (event) {
  11763. longpress$1.cancel();
  11764. getTouch(event).each(function (touch) {
  11765. startData.get().each(function (data) {
  11766. if (isFarEnough(touch, data)) {
  11767. startData.set(Option.none());
  11768. }
  11769. });
  11770. });
  11771. return Option.none();
  11772. };
  11773. var handleTouchend = function (event) {
  11774. longpress$1.cancel();
  11775. var isSame = function (data) {
  11776. return eq(data.target(), event.target());
  11777. };
  11778. return startData.get().filter(isSame).map(function (data) {
  11779. if (longpressFired.get()) {
  11780. event.prevent();
  11781. return false;
  11782. } else {
  11783. return settings.triggerEvent(tap(), event);
  11784. }
  11785. });
  11786. };
  11787. var handlers = wrapAll$1([
  11788. {
  11789. key: touchstart(),
  11790. value: handleTouchstart
  11791. },
  11792. {
  11793. key: touchmove(),
  11794. value: handleTouchmove
  11795. },
  11796. {
  11797. key: touchend(),
  11798. value: handleTouchend
  11799. }
  11800. ]);
  11801. var fireIfReady = function (event, type) {
  11802. return readOptFrom$1(handlers, type).bind(function (handler) {
  11803. return handler(event);
  11804. });
  11805. };
  11806. return { fireIfReady: fireIfReady };
  11807. };
  11808. var isDangerous = function (event) {
  11809. var keyEv = event.raw();
  11810. return keyEv.which === BACKSPACE()[0] && !contains([
  11811. 'input',
  11812. 'textarea'
  11813. ], name(event.target())) && !closest$4(event.target(), '[contenteditable="true"]');
  11814. };
  11815. var isFirefox = detect$3().browser.isFirefox();
  11816. var settingsSchema = objOfOnly([
  11817. strictFunction('triggerEvent'),
  11818. defaulted$1('stopBackspace', true)
  11819. ]);
  11820. var bindFocus = function (container, handler) {
  11821. if (isFirefox) {
  11822. return capture$1(container, 'focus', handler);
  11823. } else {
  11824. return bind$3(container, 'focusin', handler);
  11825. }
  11826. };
  11827. var bindBlur = function (container, handler) {
  11828. if (isFirefox) {
  11829. return capture$1(container, 'blur', handler);
  11830. } else {
  11831. return bind$3(container, 'focusout', handler);
  11832. }
  11833. };
  11834. var setup$1 = function (container, rawSettings) {
  11835. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  11836. var pointerEvents = detect$3().deviceType.isTouch() ? [
  11837. 'touchstart',
  11838. 'touchmove',
  11839. 'touchend',
  11840. 'gesturestart'
  11841. ] : [
  11842. 'mousedown',
  11843. 'mouseup',
  11844. 'mouseover',
  11845. 'mousemove',
  11846. 'mouseout',
  11847. 'click'
  11848. ];
  11849. var tapEvent = monitor(settings);
  11850. var simpleEvents = map(pointerEvents.concat([
  11851. 'selectstart',
  11852. 'input',
  11853. 'contextmenu',
  11854. 'change',
  11855. 'transitionend',
  11856. 'drag',
  11857. 'dragstart',
  11858. 'dragend',
  11859. 'dragenter',
  11860. 'dragleave',
  11861. 'dragover',
  11862. 'drop',
  11863. 'keyup'
  11864. ]), function (type) {
  11865. return bind$3(container, type, function (event) {
  11866. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  11867. if (tapStopped) {
  11868. event.kill();
  11869. }
  11870. });
  11871. var stopped = settings.triggerEvent(type, event);
  11872. if (stopped) {
  11873. event.kill();
  11874. }
  11875. });
  11876. });
  11877. var pasteTimeout = Cell(Option.none());
  11878. var onPaste = bind$3(container, 'paste', function (event) {
  11879. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11880. if (tapStopped) {
  11881. event.kill();
  11882. }
  11883. });
  11884. var stopped = settings.triggerEvent('paste', event);
  11885. if (stopped) {
  11886. event.kill();
  11887. }
  11888. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11889. settings.triggerEvent(postPaste(), event);
  11890. }, 0)));
  11891. });
  11892. var onKeydown = bind$3(container, 'keydown', function (event) {
  11893. var stopped = settings.triggerEvent('keydown', event);
  11894. if (stopped) {
  11895. event.kill();
  11896. } else if (settings.stopBackspace === true && isDangerous(event)) {
  11897. event.prevent();
  11898. }
  11899. });
  11900. var onFocusIn = bindFocus(container, function (event) {
  11901. var stopped = settings.triggerEvent('focusin', event);
  11902. if (stopped) {
  11903. event.kill();
  11904. }
  11905. });
  11906. var focusoutTimeout = Cell(Option.none());
  11907. var onFocusOut = bindBlur(container, function (event) {
  11908. var stopped = settings.triggerEvent('focusout', event);
  11909. if (stopped) {
  11910. event.kill();
  11911. }
  11912. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11913. settings.triggerEvent(postBlur(), event);
  11914. }, 0)));
  11915. });
  11916. var unbind = function () {
  11917. each(simpleEvents, function (e) {
  11918. e.unbind();
  11919. });
  11920. onKeydown.unbind();
  11921. onFocusIn.unbind();
  11922. onFocusOut.unbind();
  11923. onPaste.unbind();
  11924. pasteTimeout.get().each(domGlobals.clearTimeout);
  11925. focusoutTimeout.get().each(domGlobals.clearTimeout);
  11926. };
  11927. return { unbind: unbind };
  11928. };
  11929. var derive$2 = function (rawEvent, rawTarget) {
  11930. var source = readOptFrom$1(rawEvent, 'target').map(function (getTarget) {
  11931. return getTarget();
  11932. }).getOr(rawTarget);
  11933. return Cell(source);
  11934. };
  11935. var fromSource = function (event, source) {
  11936. var stopper = Cell(false);
  11937. var cutter = Cell(false);
  11938. var stop = function () {
  11939. stopper.set(true);
  11940. };
  11941. var cut = function () {
  11942. cutter.set(true);
  11943. };
  11944. return {
  11945. stop: stop,
  11946. cut: cut,
  11947. isStopped: stopper.get,
  11948. isCut: cutter.get,
  11949. event: constant(event),
  11950. setSource: source.set,
  11951. getSource: source.get
  11952. };
  11953. };
  11954. var fromExternal = function (event) {
  11955. var stopper = Cell(false);
  11956. var stop = function () {
  11957. stopper.set(true);
  11958. };
  11959. return {
  11960. stop: stop,
  11961. cut: noop,
  11962. isStopped: stopper.get,
  11963. isCut: constant(false),
  11964. event: constant(event),
  11965. setSource: die('Cannot set source of a broadcasted event'),
  11966. getSource: die('Cannot get source of a broadcasted event')
  11967. };
  11968. };
  11969. var adt$b = Adt.generate([
  11970. { stopped: [] },
  11971. { resume: ['element'] },
  11972. { complete: [] }
  11973. ]);
  11974. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11975. var handler = lookup(eventType, target);
  11976. var simulatedEvent = fromSource(rawEvent, source);
  11977. return handler.fold(function () {
  11978. logger.logEventNoHandlers(eventType, target);
  11979. return adt$b.complete();
  11980. }, function (handlerInfo) {
  11981. var descHandler = handlerInfo.descHandler();
  11982. var eventHandler = getCurried(descHandler);
  11983. eventHandler(simulatedEvent);
  11984. if (simulatedEvent.isStopped()) {
  11985. logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose());
  11986. return adt$b.stopped();
  11987. } else if (simulatedEvent.isCut()) {
  11988. logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose());
  11989. return adt$b.complete();
  11990. } else {
  11991. return parent(handlerInfo.element()).fold(function () {
  11992. logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose());
  11993. return adt$b.complete();
  11994. }, function (parent) {
  11995. logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose());
  11996. return adt$b.resume(parent);
  11997. });
  11998. }
  11999. });
  12000. };
  12001. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12002. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  12003. return true;
  12004. }, function (parent) {
  12005. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12006. }, function () {
  12007. return false;
  12008. });
  12009. };
  12010. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12011. var source = derive$2(rawEvent, target);
  12012. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12013. };
  12014. var broadcast = function (listeners, rawEvent, logger) {
  12015. var simulatedEvent = fromExternal(rawEvent);
  12016. each(listeners, function (listener) {
  12017. var descHandler = listener.descHandler();
  12018. var handler = getCurried(descHandler);
  12019. handler(simulatedEvent);
  12020. });
  12021. return simulatedEvent.isStopped();
  12022. };
  12023. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12024. var rawTarget = rawEvent.target();
  12025. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  12026. };
  12027. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12028. var source = derive$2(rawEvent, rawTarget);
  12029. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12030. };
  12031. var eventHandler = Immutable('element', 'descHandler');
  12032. var broadcastHandler = function (id, handler) {
  12033. return {
  12034. id: constant(id),
  12035. descHandler: constant(handler)
  12036. };
  12037. };
  12038. function EventRegistry () {
  12039. var registry = {};
  12040. var registerId = function (extraArgs, id, events) {
  12041. each$1(events, function (v, k) {
  12042. var handlers = registry[k] !== undefined ? registry[k] : {};
  12043. handlers[id] = curryArgs(v, extraArgs);
  12044. registry[k] = handlers;
  12045. });
  12046. };
  12047. var findHandler = function (handlers, elem) {
  12048. return read$1(elem).fold(function () {
  12049. return Option.none();
  12050. }, function (id) {
  12051. var reader = readOpt$1(id);
  12052. return handlers.bind(reader).map(function (descHandler) {
  12053. return eventHandler(elem, descHandler);
  12054. });
  12055. });
  12056. };
  12057. var filterByType = function (type) {
  12058. return readOptFrom$1(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 readType = readOpt$1(type);
  12066. var handlers = readType(registry);
  12067. return closest$1(target, function (elem) {
  12068. return findHandler(handlers, elem);
  12069. }, isAboveRoot);
  12070. };
  12071. var unregisterId = function (id) {
  12072. each$1(registry, function (handlersById, eventName) {
  12073. if (handlersById.hasOwnProperty(id)) {
  12074. delete handlersById[id];
  12075. }
  12076. });
  12077. };
  12078. return {
  12079. registerId: registerId,
  12080. unregisterId: unregisterId,
  12081. filterByType: filterByType,
  12082. find: find
  12083. };
  12084. }
  12085. function Registry () {
  12086. var events = EventRegistry();
  12087. var components = {};
  12088. var readOrTag = function (component) {
  12089. var elem = component.element();
  12090. return read$1(elem).fold(function () {
  12091. return write('uid-', component.element());
  12092. }, function (uid) {
  12093. return uid;
  12094. });
  12095. };
  12096. var failOnDuplicate = function (component, tagId) {
  12097. var conflict = components[tagId];
  12098. if (conflict === component) {
  12099. unregister(component);
  12100. } else {
  12101. 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');
  12102. }
  12103. };
  12104. var register = function (component) {
  12105. var tagId = readOrTag(component);
  12106. if (hasKey$1(components, tagId)) {
  12107. failOnDuplicate(component, tagId);
  12108. }
  12109. var extraArgs = [component];
  12110. events.registerId(extraArgs, tagId, component.events());
  12111. components[tagId] = component;
  12112. };
  12113. var unregister = function (component) {
  12114. read$1(component.element()).each(function (tagId) {
  12115. delete components[tagId];
  12116. events.unregisterId(tagId);
  12117. });
  12118. };
  12119. var filter = function (type) {
  12120. return events.filterByType(type);
  12121. };
  12122. var find = function (isAboveRoot, type, target) {
  12123. return events.find(isAboveRoot, type, target);
  12124. };
  12125. var getById = function (id) {
  12126. return readOpt$1(id)(components);
  12127. };
  12128. return {
  12129. find: find,
  12130. filter: filter,
  12131. register: register,
  12132. unregister: unregister,
  12133. getById: getById
  12134. };
  12135. }
  12136. var factory$3 = function (detail) {
  12137. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  12138. return {
  12139. uid: detail.uid,
  12140. dom: __assign({
  12141. tag: 'div',
  12142. attributes: __assign({ role: 'presentation' }, attributes)
  12143. }, domWithoutAttributes),
  12144. components: detail.components,
  12145. behaviours: get$b(detail.containerBehaviours),
  12146. events: detail.events,
  12147. domModification: detail.domModification,
  12148. eventOrder: detail.eventOrder
  12149. };
  12150. };
  12151. var Container = single$2({
  12152. name: 'Container',
  12153. factory: factory$3,
  12154. configFields: [
  12155. defaulted$1('components', []),
  12156. field$1('containerBehaviours', []),
  12157. defaulted$1('events', {}),
  12158. defaulted$1('domModification', {}),
  12159. defaulted$1('eventOrder', {})
  12160. ]
  12161. });
  12162. var takeover = function (root) {
  12163. var isAboveRoot = function (el) {
  12164. return parent(root.element()).fold(function () {
  12165. return true;
  12166. }, function (parent) {
  12167. return eq(el, parent);
  12168. });
  12169. };
  12170. var registry = Registry();
  12171. var lookup = function (eventName, target) {
  12172. return registry.find(isAboveRoot, eventName, target);
  12173. };
  12174. var domEvents = setup$1(root.element(), {
  12175. triggerEvent: function (eventName, event) {
  12176. return monitorEvent(eventName, event.target(), function (logger) {
  12177. return triggerUntilStopped(lookup, eventName, event, logger);
  12178. });
  12179. }
  12180. });
  12181. var systemApi = {
  12182. debugInfo: constant('real'),
  12183. triggerEvent: function (eventName, target, data) {
  12184. monitorEvent(eventName, target, function (logger) {
  12185. triggerOnUntilStopped(lookup, eventName, data, target, logger);
  12186. });
  12187. },
  12188. triggerFocus: function (target, originator) {
  12189. read$1(target).fold(function () {
  12190. focus$1(target);
  12191. }, function (_alloyId) {
  12192. monitorEvent(focus(), target, function (logger) {
  12193. triggerHandler(lookup, focus(), {
  12194. originator: constant(originator),
  12195. kill: noop,
  12196. prevent: noop,
  12197. target: constant(target)
  12198. }, target, logger);
  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 global$9 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12311. var getSkinUrl = function (editor) {
  12312. var settings = editor.settings;
  12313. var skin = settings.skin;
  12314. var skinUrl = settings.skin_url;
  12315. if (skin !== false) {
  12316. var skinName = skin ? skin : 'oxide';
  12317. if (skinUrl) {
  12318. skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  12319. } else {
  12320. skinUrl = global$9.baseURL + '/skins/ui/' + skinName;
  12321. }
  12322. }
  12323. return skinUrl;
  12324. };
  12325. var isReadOnly = function (editor) {
  12326. return editor.getParam('readonly', false, 'boolean');
  12327. };
  12328. var isSkinDisabled = function (editor) {
  12329. return editor.getParam('skin') === false;
  12330. };
  12331. var getHeightSetting = function (editor) {
  12332. return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  12333. };
  12334. var getMinWidthSetting = function (editor) {
  12335. return Option.from(editor.settings.min_width).filter(isNumber);
  12336. };
  12337. var getMinHeightSetting = function (editor) {
  12338. return Option.from(editor.settings.min_height).filter(isNumber);
  12339. };
  12340. var getMaxWidthSetting = function (editor) {
  12341. return Option.from(editor.getParam('max_width')).filter(isNumber);
  12342. };
  12343. var getMaxHeightSetting = function (editor) {
  12344. return Option.from(editor.getParam('max_height')).filter(isNumber);
  12345. };
  12346. var getUserStyleFormats = function (editor) {
  12347. return Option.from(editor.getParam('style_formats')).filter(isArray);
  12348. };
  12349. var isMergeStyleFormats = function (editor) {
  12350. return editor.getParam('style_formats_merge', false, 'boolean');
  12351. };
  12352. var getRemovedMenuItems = function (editor) {
  12353. return editor.getParam('removed_menuitems', '');
  12354. };
  12355. var isMenubarEnabled = function (editor) {
  12356. return editor.getParam('menubar', true, 'boolean') !== false;
  12357. };
  12358. var isToolbarEnabled = function (editor) {
  12359. var toolbar = editor.getParam('toolbar', true);
  12360. var isToolbarTrue = toolbar === true;
  12361. var isToolbarString = isString(toolbar);
  12362. var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  12363. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  12364. };
  12365. var getMultipleToolbarsSetting = function (editor) {
  12366. var keys$1 = keys(editor.settings);
  12367. var toolbarKeys = filter(keys$1, function (key) {
  12368. return /^toolbar([1-9])$/.test(key);
  12369. });
  12370. var toolbars = map(toolbarKeys, function (key) {
  12371. return editor.getParam(key, false, 'string');
  12372. });
  12373. var toolbarArray = filter(toolbars, function (toolbar) {
  12374. return typeof toolbar === 'string';
  12375. });
  12376. return toolbarArray.length > 0 ? Option.some(toolbarArray) : Option.none();
  12377. };
  12378. var isMultipleToolbars = function (editor) {
  12379. return getMultipleToolbarsSetting(editor).fold(function () {
  12380. var toolbar = editor.getParam('toolbar', [], 'string[]');
  12381. return toolbar.length > 0;
  12382. }, function () {
  12383. return true;
  12384. });
  12385. };
  12386. var ToolbarDrawer;
  12387. (function (ToolbarDrawer) {
  12388. ToolbarDrawer['default'] = '';
  12389. ToolbarDrawer['floating'] = 'floating';
  12390. ToolbarDrawer['sliding'] = 'sliding';
  12391. }(ToolbarDrawer || (ToolbarDrawer = {})));
  12392. var getToolbarDrawer = function (editor) {
  12393. return editor.getParam('toolbar_drawer', '', 'string');
  12394. };
  12395. var fixedContainerSelector = function (editor) {
  12396. return editor.getParam('fixed_toolbar_container', '', 'string');
  12397. };
  12398. var fixedContainerElement = function (editor) {
  12399. var selector = fixedContainerSelector(editor);
  12400. return selector.length > 0 && editor.inline ? descendant$1(body(), selector) : Option.none();
  12401. };
  12402. var useFixedContainer = function (editor) {
  12403. return editor.inline && fixedContainerElement(editor).isSome();
  12404. };
  12405. var getUiContainer = function (editor) {
  12406. var fixedContainer = fixedContainerElement(editor);
  12407. return fixedContainer.getOr(body());
  12408. };
  12409. var isDistractionFree = function (editor) {
  12410. return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  12411. };
  12412. var isStickyToolbar = function (editor) {
  12413. var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  12414. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  12415. };
  12416. var isDraggableModal = function (editor) {
  12417. return editor.getParam('draggable_modal', false, 'boolean');
  12418. };
  12419. var formChangeEvent = generate$1('form-component-change');
  12420. var formCloseEvent = generate$1('form-close');
  12421. var formCancelEvent = generate$1('form-cancel');
  12422. var formActionEvent = generate$1('form-action');
  12423. var formSubmitEvent = generate$1('form-submit');
  12424. var formBlockEvent = generate$1('form-block');
  12425. var formUnblockEvent = generate$1('form-unblock');
  12426. var formTabChangeEvent = generate$1('form-tabchange');
  12427. var formResizeEvent = generate$1('form-resize');
  12428. var renderAlertBanner = function (spec, providersBackstage) {
  12429. return Container.sketch({
  12430. dom: {
  12431. tag: 'div',
  12432. attributes: { role: 'alert' },
  12433. classes: [
  12434. 'tox-notification',
  12435. 'tox-notification--in',
  12436. 'tox-notification--' + spec.level
  12437. ]
  12438. },
  12439. components: [
  12440. {
  12441. dom: {
  12442. tag: 'div',
  12443. classes: ['tox-notification__icon']
  12444. },
  12445. components: [Button.sketch({
  12446. dom: {
  12447. tag: 'button',
  12448. classes: [
  12449. 'tox-button',
  12450. 'tox-button--naked',
  12451. 'tox-button--icon'
  12452. ],
  12453. innerHtml: get$c(spec.icon, providersBackstage.icons),
  12454. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  12455. },
  12456. action: function (comp) {
  12457. emitWith(comp, formActionEvent, {
  12458. name: 'alert-banner',
  12459. value: spec.url
  12460. });
  12461. }
  12462. })]
  12463. },
  12464. {
  12465. dom: {
  12466. tag: 'div',
  12467. classes: ['tox-notification__body'],
  12468. innerHtml: providersBackstage.translate(spec.text)
  12469. }
  12470. }
  12471. ]
  12472. });
  12473. };
  12474. var renderBar = function (spec, backstage) {
  12475. return {
  12476. dom: {
  12477. tag: 'div',
  12478. classes: [
  12479. 'tox-bar',
  12480. 'tox-form__controls-h-stack'
  12481. ]
  12482. },
  12483. components: map(spec.items, backstage.interpreter)
  12484. };
  12485. };
  12486. var schema$e = constant([
  12487. defaulted$1('prefix', 'form-field'),
  12488. field$1('fieldBehaviours', [
  12489. Composing,
  12490. Representing
  12491. ])
  12492. ]);
  12493. var parts$3 = constant([
  12494. optional({
  12495. schema: [strict$1('dom')],
  12496. name: 'label'
  12497. }),
  12498. optional({
  12499. factory: {
  12500. sketch: function (spec) {
  12501. return {
  12502. uid: spec.uid,
  12503. dom: {
  12504. tag: 'span',
  12505. styles: { display: 'none' },
  12506. attributes: { 'aria-hidden': 'true' },
  12507. innerHtml: spec.text
  12508. }
  12509. };
  12510. }
  12511. },
  12512. schema: [strict$1('text')],
  12513. name: 'aria-descriptor'
  12514. }),
  12515. required({
  12516. factory: {
  12517. sketch: function (spec) {
  12518. var excludeFactory = exclude$1(spec, ['factory']);
  12519. return spec.factory.sketch(excludeFactory);
  12520. }
  12521. },
  12522. schema: [strict$1('factory')],
  12523. name: 'field'
  12524. })
  12525. ]);
  12526. var factory$4 = function (detail, components, spec, externals) {
  12527. var behaviours = augment(detail.fieldBehaviours, [
  12528. Composing.config({
  12529. find: function (container) {
  12530. return getPart(container, detail, 'field');
  12531. }
  12532. }),
  12533. Representing.config({
  12534. store: {
  12535. mode: 'manual',
  12536. getValue: function (field) {
  12537. return Composing.getCurrent(field).bind(Representing.getValue);
  12538. },
  12539. setValue: function (field, value) {
  12540. Composing.getCurrent(field).each(function (current) {
  12541. Representing.setValue(current, value);
  12542. });
  12543. }
  12544. }
  12545. })
  12546. ]);
  12547. var events = derive([runOnAttached(function (component, simulatedEvent) {
  12548. var ps = getParts(component, detail, [
  12549. 'label',
  12550. 'field',
  12551. 'aria-descriptor'
  12552. ]);
  12553. ps.field().each(function (field) {
  12554. var id = generate$1(detail.prefix);
  12555. ps.label().each(function (label) {
  12556. set$1(label.element(), 'for', id);
  12557. set$1(field.element(), 'id', id);
  12558. });
  12559. ps['aria-descriptor']().each(function (descriptor) {
  12560. var descriptorId = generate$1(detail.prefix);
  12561. set$1(descriptor.element(), 'id', descriptorId);
  12562. set$1(field.element(), 'aria-describedby', descriptorId);
  12563. });
  12564. });
  12565. })]);
  12566. var apis = {
  12567. getField: function (container) {
  12568. return getPart(container, detail, 'field');
  12569. },
  12570. getLabel: function (container) {
  12571. return getPart(container, detail, 'label');
  12572. }
  12573. };
  12574. return {
  12575. uid: detail.uid,
  12576. dom: detail.dom,
  12577. components: components,
  12578. behaviours: behaviours,
  12579. events: events,
  12580. apis: apis
  12581. };
  12582. };
  12583. var FormField = composite$1({
  12584. name: 'FormField',
  12585. configFields: schema$e(),
  12586. partFields: parts$3(),
  12587. factory: factory$4,
  12588. apis: {
  12589. getField: function (apis, comp) {
  12590. return apis.getField(comp);
  12591. },
  12592. getLabel: function (apis, comp) {
  12593. return apis.getLabel(comp);
  12594. }
  12595. }
  12596. });
  12597. var schema$f = constant([
  12598. option('data'),
  12599. defaulted$1('inputAttributes', {}),
  12600. defaulted$1('inputStyles', {}),
  12601. defaulted$1('tag', 'input'),
  12602. defaulted$1('inputClasses', []),
  12603. onHandler('onSetValue'),
  12604. defaulted$1('styles', {}),
  12605. defaulted$1('eventOrder', {}),
  12606. field$1('inputBehaviours', [
  12607. Representing,
  12608. Focusing
  12609. ]),
  12610. defaulted$1('selectOnFocus', true)
  12611. ]);
  12612. var focusBehaviours = function (detail) {
  12613. return derive$1([Focusing.config({
  12614. onFocus: detail.selectOnFocus === false ? noop : function (component) {
  12615. var input = component.element();
  12616. var value = get$5(input);
  12617. input.dom().setSelectionRange(0, value.length);
  12618. }
  12619. })]);
  12620. };
  12621. var behaviours = function (detail) {
  12622. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  12623. store: {
  12624. mode: 'manual',
  12625. initialValue: detail.data.getOr(undefined),
  12626. getValue: function (input) {
  12627. return get$5(input.element());
  12628. },
  12629. setValue: function (input, data) {
  12630. var current = get$5(input.element());
  12631. if (current !== data) {
  12632. set$3(input.element(), data);
  12633. }
  12634. }
  12635. },
  12636. onSetValue: detail.onSetValue
  12637. })]));
  12638. };
  12639. var dom$2 = function (detail) {
  12640. return {
  12641. tag: detail.tag,
  12642. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  12643. styles: detail.inputStyles,
  12644. classes: detail.inputClasses
  12645. };
  12646. };
  12647. var factory$5 = function (detail, spec) {
  12648. return {
  12649. uid: detail.uid,
  12650. dom: dom$2(detail),
  12651. components: [],
  12652. behaviours: behaviours(detail),
  12653. eventOrder: detail.eventOrder
  12654. };
  12655. };
  12656. var Input = single$2({
  12657. name: 'Input',
  12658. configFields: schema$f(),
  12659. factory: factory$5
  12660. });
  12661. var exports$1 = {}, module = { exports: exports$1 };
  12662. (function (define, exports, module, require) {
  12663. (function (f) {
  12664. if (typeof exports === 'object' && typeof module !== 'undefined') {
  12665. module.exports = f();
  12666. } else if (typeof define === 'function' && define.amd) {
  12667. define([], f);
  12668. } else {
  12669. var g;
  12670. if (typeof window !== 'undefined') {
  12671. g = window;
  12672. } else if (typeof global !== 'undefined') {
  12673. g = global;
  12674. } else if (typeof self !== 'undefined') {
  12675. g = self;
  12676. } else {
  12677. g = this;
  12678. }
  12679. g.EphoxContactWrapper = f();
  12680. }
  12681. }(function () {
  12682. return function () {
  12683. function r(e, n, t) {
  12684. function o(i, f) {
  12685. if (!n[i]) {
  12686. if (!e[i]) {
  12687. var c = 'function' == typeof require && require;
  12688. if (!f && c)
  12689. return c(i, !0);
  12690. if (u)
  12691. return u(i, !0);
  12692. var a = new Error('Cannot find module \'' + i + '\'');
  12693. throw a.code = 'MODULE_NOT_FOUND', a;
  12694. }
  12695. var p = n[i] = { exports: {} };
  12696. e[i][0].call(p.exports, function (r) {
  12697. var n = e[i][1][r];
  12698. return o(n || r);
  12699. }, p, p.exports, r, e, n, t);
  12700. }
  12701. return n[i].exports;
  12702. }
  12703. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  12704. o(t[i]);
  12705. return o;
  12706. }
  12707. return r;
  12708. }()({
  12709. 1: [
  12710. function (require, module, exports) {
  12711. var process = module.exports = {};
  12712. var cachedSetTimeout;
  12713. var cachedClearTimeout;
  12714. function defaultSetTimout() {
  12715. throw new Error('setTimeout has not been defined');
  12716. }
  12717. function defaultClearTimeout() {
  12718. throw new Error('clearTimeout has not been defined');
  12719. }
  12720. (function () {
  12721. try {
  12722. if (typeof setTimeout === 'function') {
  12723. cachedSetTimeout = setTimeout;
  12724. } else {
  12725. cachedSetTimeout = defaultSetTimout;
  12726. }
  12727. } catch (e) {
  12728. cachedSetTimeout = defaultSetTimout;
  12729. }
  12730. try {
  12731. if (typeof clearTimeout === 'function') {
  12732. cachedClearTimeout = clearTimeout;
  12733. } else {
  12734. cachedClearTimeout = defaultClearTimeout;
  12735. }
  12736. } catch (e) {
  12737. cachedClearTimeout = defaultClearTimeout;
  12738. }
  12739. }());
  12740. function runTimeout(fun) {
  12741. if (cachedSetTimeout === setTimeout) {
  12742. return setTimeout(fun, 0);
  12743. }
  12744. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12745. cachedSetTimeout = setTimeout;
  12746. return setTimeout(fun, 0);
  12747. }
  12748. try {
  12749. return cachedSetTimeout(fun, 0);
  12750. } catch (e) {
  12751. try {
  12752. return cachedSetTimeout.call(null, fun, 0);
  12753. } catch (e) {
  12754. return cachedSetTimeout.call(this, fun, 0);
  12755. }
  12756. }
  12757. }
  12758. function runClearTimeout(marker) {
  12759. if (cachedClearTimeout === clearTimeout) {
  12760. return clearTimeout(marker);
  12761. }
  12762. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12763. cachedClearTimeout = clearTimeout;
  12764. return clearTimeout(marker);
  12765. }
  12766. try {
  12767. return cachedClearTimeout(marker);
  12768. } catch (e) {
  12769. try {
  12770. return cachedClearTimeout.call(null, marker);
  12771. } catch (e) {
  12772. return cachedClearTimeout.call(this, marker);
  12773. }
  12774. }
  12775. }
  12776. var queue = [];
  12777. var draining = false;
  12778. var currentQueue;
  12779. var queueIndex = -1;
  12780. function cleanUpNextTick() {
  12781. if (!draining || !currentQueue) {
  12782. return;
  12783. }
  12784. draining = false;
  12785. if (currentQueue.length) {
  12786. queue = currentQueue.concat(queue);
  12787. } else {
  12788. queueIndex = -1;
  12789. }
  12790. if (queue.length) {
  12791. drainQueue();
  12792. }
  12793. }
  12794. function drainQueue() {
  12795. if (draining) {
  12796. return;
  12797. }
  12798. var timeout = runTimeout(cleanUpNextTick);
  12799. draining = true;
  12800. var len = queue.length;
  12801. while (len) {
  12802. currentQueue = queue;
  12803. queue = [];
  12804. while (++queueIndex < len) {
  12805. if (currentQueue) {
  12806. currentQueue[queueIndex].run();
  12807. }
  12808. }
  12809. queueIndex = -1;
  12810. len = queue.length;
  12811. }
  12812. currentQueue = null;
  12813. draining = false;
  12814. runClearTimeout(timeout);
  12815. }
  12816. process.nextTick = function (fun) {
  12817. var args = new Array(arguments.length - 1);
  12818. if (arguments.length > 1) {
  12819. for (var i = 1; i < arguments.length; i++) {
  12820. args[i - 1] = arguments[i];
  12821. }
  12822. }
  12823. queue.push(new Item(fun, args));
  12824. if (queue.length === 1 && !draining) {
  12825. runTimeout(drainQueue);
  12826. }
  12827. };
  12828. function Item(fun, array) {
  12829. this.fun = fun;
  12830. this.array = array;
  12831. }
  12832. Item.prototype.run = function () {
  12833. this.fun.apply(null, this.array);
  12834. };
  12835. process.title = 'browser';
  12836. process.browser = true;
  12837. process.env = {};
  12838. process.argv = [];
  12839. process.version = '';
  12840. process.versions = {};
  12841. function noop() {
  12842. }
  12843. process.on = noop;
  12844. process.addListener = noop;
  12845. process.once = noop;
  12846. process.off = noop;
  12847. process.removeListener = noop;
  12848. process.removeAllListeners = noop;
  12849. process.emit = noop;
  12850. process.prependListener = noop;
  12851. process.prependOnceListener = noop;
  12852. process.listeners = function (name) {
  12853. return [];
  12854. };
  12855. process.binding = function (name) {
  12856. throw new Error('process.binding is not supported');
  12857. };
  12858. process.cwd = function () {
  12859. return '/';
  12860. };
  12861. process.chdir = function (dir) {
  12862. throw new Error('process.chdir is not supported');
  12863. };
  12864. process.umask = function () {
  12865. return 0;
  12866. };
  12867. },
  12868. {}
  12869. ],
  12870. 2: [
  12871. function (require, module, exports) {
  12872. (function (setImmediate) {
  12873. (function (root) {
  12874. var setTimeoutFunc = setTimeout;
  12875. function noop() {
  12876. }
  12877. function bind(fn, thisArg) {
  12878. return function () {
  12879. fn.apply(thisArg, arguments);
  12880. };
  12881. }
  12882. function Promise(fn) {
  12883. if (typeof this !== 'object')
  12884. throw new TypeError('Promises must be constructed via new');
  12885. if (typeof fn !== 'function')
  12886. throw new TypeError('not a function');
  12887. this._state = 0;
  12888. this._handled = false;
  12889. this._value = undefined;
  12890. this._deferreds = [];
  12891. doResolve(fn, this);
  12892. }
  12893. function handle(self, deferred) {
  12894. while (self._state === 3) {
  12895. self = self._value;
  12896. }
  12897. if (self._state === 0) {
  12898. self._deferreds.push(deferred);
  12899. return;
  12900. }
  12901. self._handled = true;
  12902. Promise._immediateFn(function () {
  12903. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  12904. if (cb === null) {
  12905. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  12906. return;
  12907. }
  12908. var ret;
  12909. try {
  12910. ret = cb(self._value);
  12911. } catch (e) {
  12912. reject(deferred.promise, e);
  12913. return;
  12914. }
  12915. resolve(deferred.promise, ret);
  12916. });
  12917. }
  12918. function resolve(self, newValue) {
  12919. try {
  12920. if (newValue === self)
  12921. throw new TypeError('A promise cannot be resolved with itself.');
  12922. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  12923. var then = newValue.then;
  12924. if (newValue instanceof Promise) {
  12925. self._state = 3;
  12926. self._value = newValue;
  12927. finale(self);
  12928. return;
  12929. } else if (typeof then === 'function') {
  12930. doResolve(bind(then, newValue), self);
  12931. return;
  12932. }
  12933. }
  12934. self._state = 1;
  12935. self._value = newValue;
  12936. finale(self);
  12937. } catch (e) {
  12938. reject(self, e);
  12939. }
  12940. }
  12941. function reject(self, newValue) {
  12942. self._state = 2;
  12943. self._value = newValue;
  12944. finale(self);
  12945. }
  12946. function finale(self) {
  12947. if (self._state === 2 && self._deferreds.length === 0) {
  12948. Promise._immediateFn(function () {
  12949. if (!self._handled) {
  12950. Promise._unhandledRejectionFn(self._value);
  12951. }
  12952. });
  12953. }
  12954. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  12955. handle(self, self._deferreds[i]);
  12956. }
  12957. self._deferreds = null;
  12958. }
  12959. function Handler(onFulfilled, onRejected, promise) {
  12960. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  12961. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  12962. this.promise = promise;
  12963. }
  12964. function doResolve(fn, self) {
  12965. var done = false;
  12966. try {
  12967. fn(function (value) {
  12968. if (done)
  12969. return;
  12970. done = true;
  12971. resolve(self, value);
  12972. }, function (reason) {
  12973. if (done)
  12974. return;
  12975. done = true;
  12976. reject(self, reason);
  12977. });
  12978. } catch (ex) {
  12979. if (done)
  12980. return;
  12981. done = true;
  12982. reject(self, ex);
  12983. }
  12984. }
  12985. Promise.prototype['catch'] = function (onRejected) {
  12986. return this.then(null, onRejected);
  12987. };
  12988. Promise.prototype.then = function (onFulfilled, onRejected) {
  12989. var prom = new this.constructor(noop);
  12990. handle(this, new Handler(onFulfilled, onRejected, prom));
  12991. return prom;
  12992. };
  12993. Promise.all = function (arr) {
  12994. var args = Array.prototype.slice.call(arr);
  12995. return new Promise(function (resolve, reject) {
  12996. if (args.length === 0)
  12997. return resolve([]);
  12998. var remaining = args.length;
  12999. function res(i, val) {
  13000. try {
  13001. if (val && (typeof val === 'object' || typeof val === 'function')) {
  13002. var then = val.then;
  13003. if (typeof then === 'function') {
  13004. then.call(val, function (val) {
  13005. res(i, val);
  13006. }, reject);
  13007. return;
  13008. }
  13009. }
  13010. args[i] = val;
  13011. if (--remaining === 0) {
  13012. resolve(args);
  13013. }
  13014. } catch (ex) {
  13015. reject(ex);
  13016. }
  13017. }
  13018. for (var i = 0; i < args.length; i++) {
  13019. res(i, args[i]);
  13020. }
  13021. });
  13022. };
  13023. Promise.resolve = function (value) {
  13024. if (value && typeof value === 'object' && value.constructor === Promise) {
  13025. return value;
  13026. }
  13027. return new Promise(function (resolve) {
  13028. resolve(value);
  13029. });
  13030. };
  13031. Promise.reject = function (value) {
  13032. return new Promise(function (resolve, reject) {
  13033. reject(value);
  13034. });
  13035. };
  13036. Promise.race = function (values) {
  13037. return new Promise(function (resolve, reject) {
  13038. for (var i = 0, len = values.length; i < len; i++) {
  13039. values[i].then(resolve, reject);
  13040. }
  13041. });
  13042. };
  13043. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  13044. setImmediate(fn);
  13045. } : function (fn) {
  13046. setTimeoutFunc(fn, 0);
  13047. };
  13048. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  13049. if (typeof console !== 'undefined' && console) {
  13050. console.warn('Possible Unhandled Promise Rejection:', err);
  13051. }
  13052. };
  13053. Promise._setImmediateFn = function _setImmediateFn(fn) {
  13054. Promise._immediateFn = fn;
  13055. };
  13056. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  13057. Promise._unhandledRejectionFn = fn;
  13058. };
  13059. if (typeof module !== 'undefined' && module.exports) {
  13060. module.exports = Promise;
  13061. } else if (!root.Promise) {
  13062. root.Promise = Promise;
  13063. }
  13064. }(this));
  13065. }.call(this, require('timers').setImmediate));
  13066. },
  13067. { 'timers': 3 }
  13068. ],
  13069. 3: [
  13070. function (require, module, exports) {
  13071. (function (setImmediate, clearImmediate) {
  13072. var nextTick = require('process/browser.js').nextTick;
  13073. var apply = Function.prototype.apply;
  13074. var slice = Array.prototype.slice;
  13075. var immediateIds = {};
  13076. var nextImmediateId = 0;
  13077. exports.setTimeout = function () {
  13078. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  13079. };
  13080. exports.setInterval = function () {
  13081. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  13082. };
  13083. exports.clearTimeout = exports.clearInterval = function (timeout) {
  13084. timeout.close();
  13085. };
  13086. function Timeout(id, clearFn) {
  13087. this._id = id;
  13088. this._clearFn = clearFn;
  13089. }
  13090. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  13091. };
  13092. Timeout.prototype.close = function () {
  13093. this._clearFn.call(window, this._id);
  13094. };
  13095. exports.enroll = function (item, msecs) {
  13096. clearTimeout(item._idleTimeoutId);
  13097. item._idleTimeout = msecs;
  13098. };
  13099. exports.unenroll = function (item) {
  13100. clearTimeout(item._idleTimeoutId);
  13101. item._idleTimeout = -1;
  13102. };
  13103. exports._unrefActive = exports.active = function (item) {
  13104. clearTimeout(item._idleTimeoutId);
  13105. var msecs = item._idleTimeout;
  13106. if (msecs >= 0) {
  13107. item._idleTimeoutId = setTimeout(function onTimeout() {
  13108. if (item._onTimeout)
  13109. item._onTimeout();
  13110. }, msecs);
  13111. }
  13112. };
  13113. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  13114. var id = nextImmediateId++;
  13115. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  13116. immediateIds[id] = true;
  13117. nextTick(function onNextTick() {
  13118. if (immediateIds[id]) {
  13119. if (args) {
  13120. fn.apply(null, args);
  13121. } else {
  13122. fn.call(null);
  13123. }
  13124. exports.clearImmediate(id);
  13125. }
  13126. });
  13127. return id;
  13128. };
  13129. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  13130. delete immediateIds[id];
  13131. };
  13132. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  13133. },
  13134. {
  13135. 'process/browser.js': 1,
  13136. 'timers': 3
  13137. }
  13138. ],
  13139. 4: [
  13140. function (require, module, exports) {
  13141. var promisePolyfill = require('promise-polyfill');
  13142. var Global = function () {
  13143. if (typeof window !== 'undefined') {
  13144. return window;
  13145. } else {
  13146. return Function('return this;')();
  13147. }
  13148. }();
  13149. module.exports = { boltExport: Global.Promise || promisePolyfill };
  13150. },
  13151. { 'promise-polyfill': 2 }
  13152. ]
  13153. }, {}, [4])(4);
  13154. }));
  13155. }(undefined, exports$1, module, undefined));
  13156. var Promise = module.exports.boltExport;
  13157. var nu$a = function (baseFn) {
  13158. var data = Option.none();
  13159. var callbacks = [];
  13160. var map = function (f) {
  13161. return nu$a(function (nCallback) {
  13162. get(function (data) {
  13163. nCallback(f(data));
  13164. });
  13165. });
  13166. };
  13167. var get = function (nCallback) {
  13168. if (isReady()) {
  13169. call(nCallback);
  13170. } else {
  13171. callbacks.push(nCallback);
  13172. }
  13173. };
  13174. var set = function (x) {
  13175. data = Option.some(x);
  13176. run(callbacks);
  13177. callbacks = [];
  13178. };
  13179. var isReady = function () {
  13180. return data.isSome();
  13181. };
  13182. var run = function (cbs) {
  13183. each(cbs, call);
  13184. };
  13185. var call = function (cb) {
  13186. data.each(function (x) {
  13187. domGlobals.setTimeout(function () {
  13188. cb(x);
  13189. }, 0);
  13190. });
  13191. };
  13192. baseFn(set);
  13193. return {
  13194. get: get,
  13195. map: map,
  13196. isReady: isReady
  13197. };
  13198. };
  13199. var pure$1 = function (a) {
  13200. return nu$a(function (callback) {
  13201. callback(a);
  13202. });
  13203. };
  13204. var LazyValue = {
  13205. nu: nu$a,
  13206. pure: pure$1
  13207. };
  13208. var errorReporter = function (err) {
  13209. domGlobals.setTimeout(function () {
  13210. throw err;
  13211. }, 0);
  13212. };
  13213. var make$3 = function (run) {
  13214. var get = function (callback) {
  13215. run().then(callback, errorReporter);
  13216. };
  13217. var map = function (fab) {
  13218. return make$3(function () {
  13219. return run().then(fab);
  13220. });
  13221. };
  13222. var bind = function (aFutureB) {
  13223. return make$3(function () {
  13224. return run().then(function (v) {
  13225. return aFutureB(v).toPromise();
  13226. });
  13227. });
  13228. };
  13229. var anonBind = function (futureB) {
  13230. return make$3(function () {
  13231. return run().then(function () {
  13232. return futureB.toPromise();
  13233. });
  13234. });
  13235. };
  13236. var toLazy = function () {
  13237. return LazyValue.nu(get);
  13238. };
  13239. var toCached = function () {
  13240. var cache = null;
  13241. return make$3(function () {
  13242. if (cache === null) {
  13243. cache = run();
  13244. }
  13245. return cache;
  13246. });
  13247. };
  13248. var toPromise = run;
  13249. return {
  13250. map: map,
  13251. bind: bind,
  13252. anonBind: anonBind,
  13253. toLazy: toLazy,
  13254. toCached: toCached,
  13255. toPromise: toPromise,
  13256. get: get
  13257. };
  13258. };
  13259. var nu$b = function (baseFn) {
  13260. return make$3(function () {
  13261. return new Promise(baseFn);
  13262. });
  13263. };
  13264. var pure$2 = function (a) {
  13265. return make$3(function () {
  13266. return Promise.resolve(a);
  13267. });
  13268. };
  13269. var Future = {
  13270. nu: nu$b,
  13271. pure: pure$2
  13272. };
  13273. var ariaElements = [
  13274. 'input',
  13275. 'textarea'
  13276. ];
  13277. var isAriaElement = function (elem) {
  13278. var name$1 = name(elem);
  13279. return contains(ariaElements, name$1);
  13280. };
  13281. var markValid = function (component, invalidConfig) {
  13282. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13283. remove$4(elem, invalidConfig.invalidClass);
  13284. invalidConfig.notify.each(function (notifyInfo) {
  13285. if (isAriaElement(component.element())) {
  13286. set$1(component.element(), 'aria-invalid', false);
  13287. }
  13288. notifyInfo.getContainer(component).each(function (container) {
  13289. set(container, notifyInfo.validHtml);
  13290. });
  13291. notifyInfo.onValid(component);
  13292. });
  13293. };
  13294. var markInvalid = function (component, invalidConfig, invalidState, text) {
  13295. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13296. add$2(elem, invalidConfig.invalidClass);
  13297. invalidConfig.notify.each(function (notifyInfo) {
  13298. if (isAriaElement(component.element())) {
  13299. set$1(component.element(), 'aria-invalid', true);
  13300. }
  13301. notifyInfo.getContainer(component).each(function (container) {
  13302. set(container, text);
  13303. });
  13304. notifyInfo.onInvalid(component, text);
  13305. });
  13306. };
  13307. var query = function (component, invalidConfig, invalidState) {
  13308. return invalidConfig.validator.fold(function () {
  13309. return Future.pure(Result.value(true));
  13310. }, function (validatorInfo) {
  13311. return validatorInfo.validate(component);
  13312. });
  13313. };
  13314. var run$1 = function (component, invalidConfig, invalidState) {
  13315. invalidConfig.notify.each(function (notifyInfo) {
  13316. notifyInfo.onValidate(component);
  13317. });
  13318. return query(component, invalidConfig).map(function (valid) {
  13319. if (component.getSystem().isConnected()) {
  13320. return valid.fold(function (err) {
  13321. markInvalid(component, invalidConfig, invalidState, err);
  13322. return Result.error(err);
  13323. }, function (v) {
  13324. markValid(component, invalidConfig);
  13325. return Result.value(v);
  13326. });
  13327. } else {
  13328. return Result.error('No longer in system');
  13329. }
  13330. });
  13331. };
  13332. var isInvalid = function (component, invalidConfig) {
  13333. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13334. return has$2(elem, invalidConfig.invalidClass);
  13335. };
  13336. var InvalidateApis = /*#__PURE__*/Object.freeze({
  13337. markValid: markValid,
  13338. markInvalid: markInvalid,
  13339. query: query,
  13340. run: run$1,
  13341. isInvalid: isInvalid
  13342. });
  13343. var events$a = function (invalidConfig, invalidState) {
  13344. return invalidConfig.validator.map(function (validatorInfo) {
  13345. return derive([run(validatorInfo.onEvent, function (component) {
  13346. run$1(component, invalidConfig, invalidState).get(identity);
  13347. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  13348. run$1(component, invalidConfig, invalidState).get(noop);
  13349. })] : []));
  13350. }).getOr({});
  13351. };
  13352. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  13353. events: events$a
  13354. });
  13355. var InvalidateSchema = [
  13356. strict$1('invalidClass'),
  13357. defaulted$1('getRoot', Option.none),
  13358. optionObjOf('notify', [
  13359. defaulted$1('aria', 'alert'),
  13360. defaulted$1('getContainer', Option.none),
  13361. defaulted$1('validHtml', ''),
  13362. onHandler('onValid'),
  13363. onHandler('onInvalid'),
  13364. onHandler('onValidate')
  13365. ]),
  13366. optionObjOf('validator', [
  13367. strict$1('validate'),
  13368. defaulted$1('onEvent', 'input'),
  13369. defaulted$1('validateOnLoad', true)
  13370. ])
  13371. ];
  13372. var Invalidating = create$1({
  13373. fields: InvalidateSchema,
  13374. name: 'invalidating',
  13375. active: ActiveInvalidate,
  13376. apis: InvalidateApis,
  13377. extra: {
  13378. validation: function (validator) {
  13379. return function (component) {
  13380. var v = Representing.getValue(component);
  13381. return Future.pure(validator(v));
  13382. };
  13383. }
  13384. }
  13385. });
  13386. var exhibit$4 = function (base, tabConfig) {
  13387. return nu$6({
  13388. attributes: wrapAll$1([{
  13389. key: tabConfig.tabAttr,
  13390. value: 'true'
  13391. }])
  13392. });
  13393. };
  13394. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  13395. exhibit: exhibit$4
  13396. });
  13397. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  13398. var Tabstopping = create$1({
  13399. fields: TabstopSchema,
  13400. name: 'tabstopping',
  13401. active: ActiveTabstopping
  13402. });
  13403. var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13404. var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  13405. return FormField.sketch(spec);
  13406. };
  13407. var renderFormField = function (pLabel, pField) {
  13408. return renderFormFieldWith(pLabel, pField, [], []);
  13409. };
  13410. var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13411. return {
  13412. dom: renderFormFieldDomWith(extraClasses),
  13413. components: pLabel.toArray().concat([pField]),
  13414. fieldBehaviours: derive$1(extraBehaviours)
  13415. };
  13416. };
  13417. var renderFormFieldDom = function () {
  13418. return renderFormFieldDomWith([]);
  13419. };
  13420. var renderFormFieldDomWith = function (extraClasses) {
  13421. return {
  13422. tag: 'div',
  13423. classes: ['tox-form__group'].concat(extraClasses)
  13424. };
  13425. };
  13426. var renderLabel = function (label, providersBackstage) {
  13427. return FormField.parts().label({
  13428. dom: {
  13429. tag: 'label',
  13430. classes: ['tox-label'],
  13431. innerHtml: providersBackstage.translate(label)
  13432. }
  13433. });
  13434. };
  13435. var getCoupled = function (component, coupleConfig, coupleState, name) {
  13436. return coupleState.getOrCreate(component, coupleConfig, name);
  13437. };
  13438. var CouplingApis = /*#__PURE__*/Object.freeze({
  13439. getCoupled: getCoupled
  13440. });
  13441. var CouplingSchema = [strictOf('others', setOf$1(Result.value, anyValue$1()))];
  13442. var init$5 = function (spec) {
  13443. var coupled = {};
  13444. var getOrCreate = function (component, coupleConfig, name) {
  13445. var available = keys(coupleConfig.others);
  13446. if (!available) {
  13447. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  13448. } else {
  13449. return readOptFrom$1(coupled, name).getOrThunk(function () {
  13450. var builder = readOptFrom$1(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  13451. var spec = builder(component);
  13452. var built = component.getSystem().build(spec);
  13453. coupled[name] = built;
  13454. return built;
  13455. });
  13456. }
  13457. };
  13458. var readState = constant({});
  13459. return nu$5({
  13460. readState: readState,
  13461. getOrCreate: getOrCreate
  13462. });
  13463. };
  13464. var CouplingState = /*#__PURE__*/Object.freeze({
  13465. init: init$5
  13466. });
  13467. var Coupling = create$1({
  13468. fields: CouplingSchema,
  13469. name: 'coupling',
  13470. apis: CouplingApis,
  13471. state: CouplingState
  13472. });
  13473. var suffix = constant('sink');
  13474. var partType = constant(optional({
  13475. name: suffix(),
  13476. overrides: constant({
  13477. dom: { tag: 'div' },
  13478. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  13479. events: derive([
  13480. cutter(keydown()),
  13481. cutter(mousedown()),
  13482. cutter(click())
  13483. ])
  13484. })
  13485. }));
  13486. var HighlightOnOpen;
  13487. (function (HighlightOnOpen) {
  13488. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  13489. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  13490. }(HighlightOnOpen || (HighlightOnOpen = {})));
  13491. var getAnchor = function (detail, component) {
  13492. var hotspot = detail.getHotspot(component).getOr(component);
  13493. var anchor = 'hotspot';
  13494. var overrides = detail.getAnchorOverrides();
  13495. return detail.layouts.fold(function () {
  13496. return {
  13497. anchor: anchor,
  13498. hotspot: hotspot,
  13499. overrides: overrides
  13500. };
  13501. }, function (layouts) {
  13502. return {
  13503. anchor: anchor,
  13504. hotspot: hotspot,
  13505. overrides: overrides,
  13506. layouts: layouts
  13507. };
  13508. });
  13509. };
  13510. var fetch = function (detail, mapFetch, component) {
  13511. var fetcher = detail.fetch;
  13512. return fetcher(component).map(mapFetch);
  13513. };
  13514. var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  13515. var futureData = fetch(detail, mapFetch, component);
  13516. var getLazySink = getSink(component, detail);
  13517. return futureData.map(function (tdata) {
  13518. return tdata.bind(function (data) {
  13519. return Option.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  13520. uid: generate$2(''),
  13521. data: data,
  13522. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  13523. onOpenMenu: function (tmenu, menu) {
  13524. var sink = getLazySink().getOrDie();
  13525. Positioning.position(sink, anchor, menu);
  13526. Sandboxing.decloak(sandbox);
  13527. },
  13528. onOpenSubmenu: function (tmenu, item, submenu) {
  13529. var sink = getLazySink().getOrDie();
  13530. Positioning.position(sink, {
  13531. anchor: 'submenu',
  13532. item: item
  13533. }, submenu);
  13534. Sandboxing.decloak(sandbox);
  13535. },
  13536. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  13537. var sink = getLazySink().getOrDie();
  13538. Positioning.position(sink, anchor, primaryMenu);
  13539. each(submenuTriggers, function (st) {
  13540. Positioning.position(sink, {
  13541. anchor: 'submenu',
  13542. item: st.triggeringItem
  13543. }, st.triggeredMenu);
  13544. });
  13545. },
  13546. onEscape: function () {
  13547. Focusing.focus(component);
  13548. Sandboxing.close(sandbox);
  13549. return Option.some(true);
  13550. }
  13551. })));
  13552. });
  13553. });
  13554. };
  13555. var open$1 = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  13556. var anchor = getAnchor(detail, hotspot);
  13557. var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  13558. return processed.map(function (tdata) {
  13559. tdata.fold(function () {
  13560. if (Sandboxing.isOpen(sandbox)) {
  13561. Sandboxing.close(sandbox);
  13562. }
  13563. }, function (data) {
  13564. Sandboxing.cloak(sandbox);
  13565. Sandboxing.open(sandbox, data);
  13566. onOpenSync(sandbox);
  13567. });
  13568. return sandbox;
  13569. });
  13570. };
  13571. var close$1 = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  13572. Sandboxing.close(sandbox);
  13573. return Future.pure(sandbox);
  13574. };
  13575. var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  13576. var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  13577. var showing = Sandboxing.isOpen(sandbox);
  13578. var action = showing ? close$1 : open$1;
  13579. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  13580. };
  13581. var matchWidth = function (hotspot, container, useMinWidth) {
  13582. var menu = Composing.getCurrent(container).getOr(container);
  13583. var buttonWidth = get$7(hotspot.element());
  13584. if (useMinWidth) {
  13585. set$2(menu.element(), 'min-width', buttonWidth + 'px');
  13586. } else {
  13587. set$4(menu.element(), buttonWidth);
  13588. }
  13589. };
  13590. var getSink = function (anyInSystem, sinkDetail) {
  13591. return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  13592. return function () {
  13593. return Result.value(internalSink);
  13594. };
  13595. }).getOrThunk(function () {
  13596. return sinkDetail.lazySink.fold(function () {
  13597. return function () {
  13598. return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  13599. };
  13600. }, function (lazySinkFn) {
  13601. return function () {
  13602. return lazySinkFn(anyInSystem);
  13603. };
  13604. });
  13605. });
  13606. };
  13607. var doRepositionMenus = function (sandbox) {
  13608. Sandboxing.getState(sandbox).each(function (tmenu) {
  13609. tieredMenu.repositionMenus(tmenu);
  13610. });
  13611. };
  13612. var makeSandbox = function (detail, hotspot, extras) {
  13613. var ariaOwner = manager();
  13614. var onOpen = function (component, menu) {
  13615. var anchor = getAnchor(detail, hotspot);
  13616. ariaOwner.link(hotspot.element());
  13617. if (detail.matchWidth) {
  13618. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  13619. }
  13620. detail.onOpen(anchor, component, menu);
  13621. if (extras !== undefined && extras.onOpen !== undefined) {
  13622. extras.onOpen(component, menu);
  13623. }
  13624. };
  13625. var onClose = function (component, menu) {
  13626. ariaOwner.unlink(hotspot.element());
  13627. if (extras !== undefined && extras.onClose !== undefined) {
  13628. extras.onClose(component, menu);
  13629. }
  13630. };
  13631. var lazySink = getSink(hotspot, detail);
  13632. return {
  13633. dom: {
  13634. tag: 'div',
  13635. classes: detail.sandboxClasses,
  13636. attributes: {
  13637. id: ariaOwner.id(),
  13638. role: 'listbox'
  13639. }
  13640. },
  13641. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  13642. Representing.config({
  13643. store: {
  13644. mode: 'memory',
  13645. initialValue: hotspot
  13646. }
  13647. }),
  13648. Sandboxing.config({
  13649. onOpen: onOpen,
  13650. onClose: onClose,
  13651. isPartOf: function (container, data, queryElem) {
  13652. return isPartOf(data, queryElem) || isPartOf(hotspot, queryElem);
  13653. },
  13654. getAttachPoint: function () {
  13655. return lazySink().getOrDie();
  13656. }
  13657. }),
  13658. Composing.config({
  13659. find: function (sandbox) {
  13660. return Sandboxing.getState(sandbox).bind(function (menu) {
  13661. return Composing.getCurrent(menu);
  13662. });
  13663. }
  13664. }),
  13665. Receiving.config({
  13666. channels: __assign(__assign({}, receivingChannel({ isExtraPart: constant(false) })), receivingChannel$1({
  13667. isExtraPart: constant(false),
  13668. doReposition: doRepositionMenus
  13669. }))
  13670. })
  13671. ])
  13672. };
  13673. };
  13674. var repositionMenus = function (comp) {
  13675. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13676. doRepositionMenus(sandbox);
  13677. };
  13678. var sandboxFields = function () {
  13679. return [
  13680. defaulted$1('sandboxClasses', []),
  13681. SketchBehaviours.field('sandboxBehaviours', [
  13682. Composing,
  13683. Receiving,
  13684. Sandboxing,
  13685. Representing
  13686. ])
  13687. ];
  13688. };
  13689. var schema$g = constant([
  13690. strict$1('dom'),
  13691. strict$1('fetch'),
  13692. onHandler('onOpen'),
  13693. onKeyboardHandler('onExecute'),
  13694. defaulted$1('getHotspot', Option.some),
  13695. defaulted$1('getAnchorOverrides', constant({})),
  13696. defaulted$1('layouts', Option.none()),
  13697. field$1('dropdownBehaviours', [
  13698. Toggling,
  13699. Coupling,
  13700. Keying,
  13701. Focusing
  13702. ]),
  13703. strict$1('toggleClass'),
  13704. defaulted$1('eventOrder', {}),
  13705. option('lazySink'),
  13706. defaulted$1('matchWidth', false),
  13707. defaulted$1('useMinWidth', false),
  13708. option('role')
  13709. ].concat(sandboxFields()));
  13710. var parts$4 = constant([
  13711. external$1({
  13712. schema: [tieredMenuMarkers()],
  13713. name: 'menu',
  13714. defaults: function (detail) {
  13715. return { onExecute: detail.onExecute };
  13716. }
  13717. }),
  13718. partType()
  13719. ]);
  13720. var factory$6 = function (detail, components, _spec, externals) {
  13721. var _a;
  13722. var lookupAttr = function (attr) {
  13723. return readOptFrom$1(detail.dom, 'attributes').bind(function (attrs) {
  13724. return readOptFrom$1(attrs, attr);
  13725. });
  13726. };
  13727. var switchToMenu = function (sandbox) {
  13728. Sandboxing.getState(sandbox).each(function (tmenu) {
  13729. tieredMenu.highlightPrimary(tmenu);
  13730. });
  13731. };
  13732. var action = function (component) {
  13733. var onOpenSync = switchToMenu;
  13734. togglePopup(detail, function (x) {
  13735. return x;
  13736. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  13737. };
  13738. var apis = {
  13739. expand: function (comp) {
  13740. if (!Toggling.isOn(comp)) {
  13741. togglePopup(detail, function (x) {
  13742. return x;
  13743. }, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  13744. }
  13745. },
  13746. open: function (comp) {
  13747. if (!Toggling.isOn(comp)) {
  13748. togglePopup(detail, function (x) {
  13749. return x;
  13750. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13751. }
  13752. },
  13753. isOpen: Toggling.isOn,
  13754. close: function (comp) {
  13755. if (Toggling.isOn(comp)) {
  13756. togglePopup(detail, function (x) {
  13757. return x;
  13758. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13759. }
  13760. },
  13761. repositionMenus: function (comp) {
  13762. if (Toggling.isOn(comp)) {
  13763. repositionMenus(comp);
  13764. }
  13765. }
  13766. };
  13767. var triggerExecute = function (comp, se) {
  13768. emitExecute(comp);
  13769. return Option.some(true);
  13770. };
  13771. return {
  13772. uid: detail.uid,
  13773. dom: detail.dom,
  13774. components: components,
  13775. behaviours: augment(detail.dropdownBehaviours, [
  13776. Toggling.config({
  13777. toggleClass: detail.toggleClass,
  13778. aria: { mode: 'expanded' }
  13779. }),
  13780. Coupling.config({
  13781. others: {
  13782. sandbox: function (hotspot) {
  13783. return makeSandbox(detail, hotspot, {
  13784. onOpen: function () {
  13785. Toggling.on(hotspot);
  13786. },
  13787. onClose: function () {
  13788. Toggling.off(hotspot);
  13789. }
  13790. });
  13791. }
  13792. }
  13793. }),
  13794. Keying.config({
  13795. mode: 'special',
  13796. onSpace: triggerExecute,
  13797. onEnter: triggerExecute,
  13798. onDown: function (comp, se) {
  13799. if (Dropdown.isOpen(comp)) {
  13800. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13801. switchToMenu(sandbox);
  13802. } else {
  13803. Dropdown.open(comp);
  13804. }
  13805. return Option.some(true);
  13806. },
  13807. onEscape: function (comp, se) {
  13808. if (Dropdown.isOpen(comp)) {
  13809. Dropdown.close(comp);
  13810. return Option.some(true);
  13811. } else {
  13812. return Option.none();
  13813. }
  13814. }
  13815. }),
  13816. Focusing.config({})
  13817. ]),
  13818. events: events$7(Option.some(action)),
  13819. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [
  13820. 'disabling',
  13821. 'toggling',
  13822. 'alloy.base.behaviour'
  13823. ], _a)),
  13824. apis: apis,
  13825. domModification: {
  13826. attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  13827. return {};
  13828. }, function (role) {
  13829. return { role: role };
  13830. })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  13831. }
  13832. };
  13833. };
  13834. var Dropdown = composite$1({
  13835. name: 'Dropdown',
  13836. configFields: schema$g(),
  13837. partFields: parts$4(),
  13838. factory: factory$6,
  13839. apis: {
  13840. open: function (apis, comp) {
  13841. return apis.open(comp);
  13842. },
  13843. expand: function (apis, comp) {
  13844. return apis.expand(comp);
  13845. },
  13846. close: function (apis, comp) {
  13847. return apis.close(comp);
  13848. },
  13849. isOpen: function (apis, comp) {
  13850. return apis.isOpen(comp);
  13851. },
  13852. repositionMenus: function (apis, comp) {
  13853. return apis.repositionMenus(comp);
  13854. }
  13855. }
  13856. });
  13857. var exhibit$5 = function (base, unselectConfig) {
  13858. return nu$6({
  13859. styles: {
  13860. '-webkit-user-select': 'none',
  13861. 'user-select': 'none',
  13862. '-ms-user-select': 'none',
  13863. '-moz-user-select': '-moz-none'
  13864. },
  13865. attributes: { unselectable: 'on' }
  13866. });
  13867. };
  13868. var events$b = function (unselectConfig) {
  13869. return derive([abort(selectstart(), constant(true))]);
  13870. };
  13871. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  13872. events: events$b,
  13873. exhibit: exhibit$5
  13874. });
  13875. var Unselecting = create$1({
  13876. fields: [],
  13877. name: 'unselecting',
  13878. active: ActiveUnselecting
  13879. });
  13880. var renderPanelButton = function (spec, sharedBackstage) {
  13881. return Dropdown.sketch({
  13882. dom: spec.dom,
  13883. components: spec.components,
  13884. toggleClass: 'mce-active',
  13885. dropdownBehaviours: derive$1([
  13886. Unselecting.config({}),
  13887. Tabstopping.config({})
  13888. ]),
  13889. layouts: spec.layouts,
  13890. sandboxClasses: ['tox-dialog__popups'],
  13891. lazySink: sharedBackstage.getSink,
  13892. fetch: function (comp) {
  13893. return Future.nu(function (callback) {
  13894. return spec.fetch(callback);
  13895. }).map(function (items) {
  13896. return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  13897. spec.onItemAction(comp, value);
  13898. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  13899. return false;
  13900. }, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  13901. });
  13902. },
  13903. parts: { menu: part(false, 1, spec.presets) }
  13904. });
  13905. };
  13906. var colorInputChangeEvent = generate$1('color-input-change');
  13907. var colorSwatchChangeEvent = generate$1('color-swatch-change');
  13908. var colorPickerCancelEvent = generate$1('color-picker-cancel');
  13909. var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  13910. var pField = FormField.parts().field({
  13911. factory: Input,
  13912. inputClasses: ['tox-textfield'],
  13913. onSetValue: function (c) {
  13914. return Invalidating.run(c).get(function () {
  13915. });
  13916. },
  13917. inputBehaviours: derive$1([
  13918. Tabstopping.config({}),
  13919. Invalidating.config({
  13920. invalidClass: 'tox-textbox-field-invalid',
  13921. getRoot: function (comp) {
  13922. return parent(comp.element());
  13923. },
  13924. notify: {
  13925. onValid: function (comp) {
  13926. var val = Representing.getValue(comp);
  13927. emitWith(comp, colorInputChangeEvent, { color: val });
  13928. }
  13929. },
  13930. validator: {
  13931. validateOnLoad: false,
  13932. validate: function (input) {
  13933. var inputValue = Representing.getValue(input);
  13934. if (inputValue.length === 0) {
  13935. return Future.pure(Result.value(true));
  13936. } else {
  13937. var span = Element.fromTag('span');
  13938. set$2(span, 'background-color', inputValue);
  13939. var res = getRaw(span, 'background-color').fold(function () {
  13940. return Result.error('blah');
  13941. }, function (_) {
  13942. return Result.value(inputValue);
  13943. });
  13944. return Future.pure(res);
  13945. }
  13946. }
  13947. }
  13948. })
  13949. ]),
  13950. selectOnFocus: false
  13951. });
  13952. var pLabel = spec.label.map(function (label) {
  13953. return renderLabel(label, sharedBackstage.providers);
  13954. });
  13955. var emitSwatchChange = function (colorBit, value) {
  13956. emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  13957. };
  13958. var onItemAction = function (comp, value) {
  13959. memColorButton.getOpt(comp).each(function (colorBit) {
  13960. if (value === 'custom') {
  13961. colorInputBackstage.colorPicker(function (valueOpt) {
  13962. valueOpt.fold(function () {
  13963. return emit(colorBit, colorPickerCancelEvent);
  13964. }, function (value) {
  13965. emitSwatchChange(colorBit, value);
  13966. Settings.addColor(value);
  13967. });
  13968. }, '#ffffff');
  13969. } else if (value === 'remove') {
  13970. emitSwatchChange(colorBit, '');
  13971. } else {
  13972. emitSwatchChange(colorBit, value);
  13973. }
  13974. });
  13975. };
  13976. var memColorButton = record(renderPanelButton({
  13977. dom: {
  13978. tag: 'span',
  13979. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  13980. },
  13981. layouts: Option.some({
  13982. onRtl: function () {
  13983. return [southeast$1];
  13984. },
  13985. onLtr: function () {
  13986. return [southwest$1];
  13987. }
  13988. }),
  13989. components: [],
  13990. fetch: ColorSwatch.getFetch(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  13991. columns: colorInputBackstage.getColorCols(),
  13992. presets: 'color',
  13993. onItemAction: onItemAction
  13994. }, sharedBackstage));
  13995. return FormField.sketch({
  13996. dom: {
  13997. tag: 'div',
  13998. classes: ['tox-form__group']
  13999. },
  14000. components: pLabel.toArray().concat([{
  14001. dom: {
  14002. tag: 'div',
  14003. classes: ['tox-color-input']
  14004. },
  14005. components: [
  14006. pField,
  14007. memColorButton.asSpec()
  14008. ]
  14009. }]),
  14010. fieldBehaviours: derive$1([config('form-field-events', [
  14011. run(colorInputChangeEvent, function (comp, se) {
  14012. memColorButton.getOpt(comp).each(function (colorButton) {
  14013. set$2(colorButton.element(), 'background-color', se.event().color());
  14014. });
  14015. emitWith(comp, formChangeEvent, { name: spec.name });
  14016. }),
  14017. run(colorSwatchChangeEvent, function (comp, se) {
  14018. FormField.getField(comp).each(function (field) {
  14019. Representing.setValue(field, se.event().value());
  14020. Composing.getCurrent(comp).each(Focusing.focus);
  14021. });
  14022. }),
  14023. run(colorPickerCancelEvent, function (comp, se) {
  14024. FormField.getField(comp).each(function (field) {
  14025. Composing.getCurrent(comp).each(Focusing.focus);
  14026. });
  14027. })
  14028. ])])
  14029. });
  14030. };
  14031. var hsvColour = function (hue, saturation, value) {
  14032. return {
  14033. hue: constant(hue),
  14034. saturation: constant(saturation),
  14035. value: constant(value)
  14036. };
  14037. };
  14038. var fromRgb = function (rgbaColour) {
  14039. var h = 0;
  14040. var s = 0;
  14041. var v = 0;
  14042. var r = rgbaColour.red() / 255;
  14043. var g = rgbaColour.green() / 255;
  14044. var b = rgbaColour.blue() / 255;
  14045. var minRGB = Math.min(r, Math.min(g, b));
  14046. var maxRGB = Math.max(r, Math.max(g, b));
  14047. if (minRGB === maxRGB) {
  14048. v = minRGB;
  14049. return hsvColour(0, 0, v * 100);
  14050. }
  14051. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  14052. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  14053. h = 60 * (h - d / (maxRGB - minRGB));
  14054. s = (maxRGB - minRGB) / maxRGB;
  14055. v = maxRGB;
  14056. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  14057. };
  14058. var calcHex = function (value) {
  14059. var hue = (100 - value) / 100 * 360;
  14060. var hsv = hsvColour(hue, 100, 100);
  14061. var rgb = fromHsv(hsv);
  14062. return fromRgba(rgb);
  14063. };
  14064. var fieldsUpdate = constant(generate$1('rgb-hex-update'));
  14065. var sliderUpdate = constant(generate$1('slider-update'));
  14066. var paletteUpdate = constant(generate$1('palette-update'));
  14067. var platform$1 = detect$3();
  14068. var isTouch = platform$1.deviceType.isTouch();
  14069. var labelPart = optional({
  14070. schema: [strict$1('dom')],
  14071. name: 'label'
  14072. });
  14073. var edgePart = function (name) {
  14074. return optional({
  14075. name: '' + name + '-edge',
  14076. overrides: function (detail) {
  14077. var action = detail.model.manager.edgeActions[name];
  14078. return action.fold(function () {
  14079. return {};
  14080. }, function (a) {
  14081. var touchEvents = derive([runActionExtra(touchstart(), a, [detail])]);
  14082. var mouseEvents = derive([
  14083. runActionExtra(mousedown(), a, [detail]),
  14084. runActionExtra(mousemove(), function (l, det) {
  14085. if (det.mouseIsDown.get()) {
  14086. a(l, det);
  14087. }
  14088. }, [detail])
  14089. ]);
  14090. return { events: isTouch ? touchEvents : mouseEvents };
  14091. });
  14092. }
  14093. });
  14094. };
  14095. var tlEdgePart = edgePart('top-left');
  14096. var tedgePart = edgePart('top');
  14097. var trEdgePart = edgePart('top-right');
  14098. var redgePart = edgePart('right');
  14099. var brEdgePart = edgePart('bottom-right');
  14100. var bedgePart = edgePart('bottom');
  14101. var blEdgePart = edgePart('bottom-left');
  14102. var ledgePart = edgePart('left');
  14103. var thumbPart = required({
  14104. name: 'thumb',
  14105. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  14106. overrides: function (detail) {
  14107. return {
  14108. events: derive([
  14109. redirectToPart(touchstart(), detail, 'spectrum'),
  14110. redirectToPart(touchmove(), detail, 'spectrum'),
  14111. redirectToPart(touchend(), detail, 'spectrum'),
  14112. redirectToPart(mousedown(), detail, 'spectrum'),
  14113. redirectToPart(mousemove(), detail, 'spectrum'),
  14114. redirectToPart(mouseup(), detail, 'spectrum')
  14115. ])
  14116. };
  14117. }
  14118. });
  14119. var spectrumPart = required({
  14120. schema: [state$1('mouseIsDown', function () {
  14121. return Cell(false);
  14122. })],
  14123. name: 'spectrum',
  14124. overrides: function (detail) {
  14125. var modelDetail = detail.model;
  14126. var model = modelDetail.manager;
  14127. var setValueFrom = function (component, simulatedEvent) {
  14128. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  14129. return model.setValueFrom(component, detail, value);
  14130. });
  14131. };
  14132. var touchEvents = derive([
  14133. run(touchstart(), setValueFrom),
  14134. run(touchmove(), setValueFrom)
  14135. ]);
  14136. var mouseEvents = derive([
  14137. run(mousedown(), setValueFrom),
  14138. run(mousemove(), function (spectrum, se) {
  14139. if (detail.mouseIsDown.get()) {
  14140. setValueFrom(spectrum, se);
  14141. }
  14142. })
  14143. ]);
  14144. return {
  14145. behaviours: derive$1(isTouch ? [] : [
  14146. Keying.config({
  14147. mode: 'special',
  14148. onLeft: function (spectrum) {
  14149. return model.onLeft(spectrum, detail);
  14150. },
  14151. onRight: function (spectrum) {
  14152. return model.onRight(spectrum, detail);
  14153. },
  14154. onUp: function (spectrum) {
  14155. return model.onUp(spectrum, detail);
  14156. },
  14157. onDown: function (spectrum) {
  14158. return model.onDown(spectrum, detail);
  14159. }
  14160. }),
  14161. Focusing.config({})
  14162. ]),
  14163. events: isTouch ? touchEvents : mouseEvents
  14164. };
  14165. }
  14166. });
  14167. var SliderParts = [
  14168. labelPart,
  14169. ledgePart,
  14170. redgePart,
  14171. tedgePart,
  14172. bedgePart,
  14173. tlEdgePart,
  14174. trEdgePart,
  14175. blEdgePart,
  14176. brEdgePart,
  14177. thumbPart,
  14178. spectrumPart
  14179. ];
  14180. var isTouch$1 = detect$3().deviceType.isTouch();
  14181. var _sliderChangeEvent = 'slider.change.value';
  14182. var sliderChangeEvent = constant(_sliderChangeEvent);
  14183. var getEventSource = function (simulatedEvent) {
  14184. var evt = simulatedEvent.event().raw();
  14185. if (isTouch$1) {
  14186. var touchEvent = evt;
  14187. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  14188. return Position(t.clientX, t.clientY);
  14189. }) : Option.none();
  14190. } else {
  14191. var mouseEvent = evt;
  14192. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  14193. return Position(me.clientX, me.clientY);
  14194. }) : Option.none();
  14195. }
  14196. };
  14197. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  14198. var minX = function (detail) {
  14199. return detail.model.minX;
  14200. };
  14201. var minY = function (detail) {
  14202. return detail.model.minY;
  14203. };
  14204. var min1X = function (detail) {
  14205. return detail.model.minX - 1;
  14206. };
  14207. var min1Y = function (detail) {
  14208. return detail.model.minY - 1;
  14209. };
  14210. var maxX = function (detail) {
  14211. return detail.model.maxX;
  14212. };
  14213. var maxY = function (detail) {
  14214. return detail.model.maxY;
  14215. };
  14216. var max1X = function (detail) {
  14217. return detail.model.maxX + 1;
  14218. };
  14219. var max1Y = function (detail) {
  14220. return detail.model.maxY + 1;
  14221. };
  14222. var range$2 = function (detail, max, min) {
  14223. return max(detail) - min(detail);
  14224. };
  14225. var xRange = function (detail) {
  14226. return range$2(detail, maxX, minX);
  14227. };
  14228. var yRange = function (detail) {
  14229. return range$2(detail, maxY, minY);
  14230. };
  14231. var halfX = function (detail) {
  14232. return xRange(detail) / 2;
  14233. };
  14234. var halfY = function (detail) {
  14235. return yRange(detail) / 2;
  14236. };
  14237. var step = function (detail) {
  14238. return detail.stepSize;
  14239. };
  14240. var snap = function (detail) {
  14241. return detail.snapToGrid;
  14242. };
  14243. var snapStart = function (detail) {
  14244. return detail.snapStart;
  14245. };
  14246. var rounded = function (detail) {
  14247. return detail.rounded;
  14248. };
  14249. var hasEdge = function (detail, edgeName) {
  14250. return detail[edgeName + '-edge'] !== undefined;
  14251. };
  14252. var hasLEdge = function (detail) {
  14253. return hasEdge(detail, l);
  14254. };
  14255. var hasREdge = function (detail) {
  14256. return hasEdge(detail, r$1);
  14257. };
  14258. var hasTEdge = function (detail) {
  14259. return hasEdge(detail, t);
  14260. };
  14261. var hasBEdge = function (detail) {
  14262. return hasEdge(detail, b);
  14263. };
  14264. var currentValue = function (detail) {
  14265. return detail.model.value.get();
  14266. };
  14267. var xValue = function (x) {
  14268. return { x: constant(x) };
  14269. };
  14270. var yValue = function (y) {
  14271. return { y: constant(y) };
  14272. };
  14273. var xyValue = function (x, y) {
  14274. return {
  14275. x: constant(x),
  14276. y: constant(y)
  14277. };
  14278. };
  14279. var fireSliderChange = function (component, value) {
  14280. emitWith(component, sliderChangeEvent(), { value: value });
  14281. };
  14282. var setToTLEdgeXY = function (edge, detail) {
  14283. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  14284. };
  14285. var setToTEdge = function (edge, detail) {
  14286. fireSliderChange(edge, yValue(min1Y(detail)));
  14287. };
  14288. var setToTEdgeXY = function (edge, detail) {
  14289. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  14290. };
  14291. var setToTREdgeXY = function (edge, detail) {
  14292. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  14293. };
  14294. var setToREdge = function (edge, detail) {
  14295. fireSliderChange(edge, xValue(max1X(detail)));
  14296. };
  14297. var setToREdgeXY = function (edge, detail) {
  14298. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  14299. };
  14300. var setToBREdgeXY = function (edge, detail) {
  14301. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  14302. };
  14303. var setToBEdge = function (edge, detail) {
  14304. fireSliderChange(edge, yValue(max1Y(detail)));
  14305. };
  14306. var setToBEdgeXY = function (edge, detail) {
  14307. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  14308. };
  14309. var setToBLEdgeXY = function (edge, detail) {
  14310. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  14311. };
  14312. var setToLEdge = function (edge, detail) {
  14313. fireSliderChange(edge, xValue(min1X(detail)));
  14314. };
  14315. var setToLEdgeXY = function (edge, detail) {
  14316. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  14317. };
  14318. var reduceBy = function (value, min, max, step) {
  14319. if (value < min) {
  14320. return value;
  14321. } else if (value > max) {
  14322. return max;
  14323. } else if (value === min) {
  14324. return min - 1;
  14325. } else {
  14326. return Math.max(min, value - step);
  14327. }
  14328. };
  14329. var increaseBy = function (value, min, max, step) {
  14330. if (value > max) {
  14331. return value;
  14332. } else if (value < min) {
  14333. return min;
  14334. } else if (value === max) {
  14335. return max + 1;
  14336. } else {
  14337. return Math.min(max, value + step);
  14338. }
  14339. };
  14340. var capValue = function (value, min, max) {
  14341. return Math.max(min, Math.min(max, value));
  14342. };
  14343. var snapValueOf = function (value, min, max, step, snapStart) {
  14344. return snapStart.fold(function () {
  14345. var initValue = value - min;
  14346. var extraValue = Math.round(initValue / step) * step;
  14347. return capValue(min + extraValue, min - 1, max + 1);
  14348. }, function (start) {
  14349. var remainder = (value - start) % step;
  14350. var adjustment = Math.round(remainder / step);
  14351. var rawSteps = Math.floor((value - start) / step);
  14352. var maxSteps = Math.floor((max - start) / step);
  14353. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  14354. var r = start + numSteps * step;
  14355. return Math.max(start, r);
  14356. });
  14357. };
  14358. var findOffsetOf = function (value, min, max) {
  14359. return Math.min(max, Math.max(value, min)) - min;
  14360. };
  14361. var findValueOf = function (args) {
  14362. 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;
  14363. var capMin = hasMinEdge ? min - 1 : min;
  14364. var capMax = hasMaxEdge ? max + 1 : max;
  14365. if (value < minBound) {
  14366. return capMin;
  14367. } else if (value > maxBound) {
  14368. return capMax;
  14369. } else {
  14370. var offset = findOffsetOf(value, minBound, maxBound);
  14371. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  14372. if (snap && newValue >= min && newValue <= max) {
  14373. return snapValueOf(newValue, min, max, step, snapStart);
  14374. } else if (rounded) {
  14375. return Math.round(newValue);
  14376. } else {
  14377. return newValue;
  14378. }
  14379. }
  14380. };
  14381. var findOffsetOfValue = function (args) {
  14382. 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;
  14383. if (value < min) {
  14384. return hasMinEdge ? 0 : centerMinEdge;
  14385. } else if (value > max) {
  14386. return hasMaxEdge ? maxBound : centerMaxEdge;
  14387. } else {
  14388. return (value - min) / range * maxOffset;
  14389. }
  14390. };
  14391. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  14392. var getBounds$1 = function (component) {
  14393. return component.element().dom().getBoundingClientRect();
  14394. };
  14395. var getBoundsProperty = function (bounds, property) {
  14396. return bounds[property];
  14397. };
  14398. var getMinXBounds = function (component) {
  14399. var bounds = getBounds$1(component);
  14400. return getBoundsProperty(bounds, left);
  14401. };
  14402. var getMaxXBounds = function (component) {
  14403. var bounds = getBounds$1(component);
  14404. return getBoundsProperty(bounds, right);
  14405. };
  14406. var getMinYBounds = function (component) {
  14407. var bounds = getBounds$1(component);
  14408. return getBoundsProperty(bounds, top);
  14409. };
  14410. var getMaxYBounds = function (component) {
  14411. var bounds = getBounds$1(component);
  14412. return getBoundsProperty(bounds, bottom);
  14413. };
  14414. var getXScreenRange = function (component) {
  14415. var bounds = getBounds$1(component);
  14416. return getBoundsProperty(bounds, width);
  14417. };
  14418. var getYScreenRange = function (component) {
  14419. var bounds = getBounds$1(component);
  14420. return getBoundsProperty(bounds, height);
  14421. };
  14422. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  14423. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  14424. };
  14425. var getXCenterOffSetOf = function (component, spectrum) {
  14426. var componentBounds = getBounds$1(component);
  14427. var spectrumBounds = getBounds$1(spectrum);
  14428. var componentMinEdge = getBoundsProperty(componentBounds, left);
  14429. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  14430. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  14431. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14432. };
  14433. var getYCenterOffSetOf = function (component, spectrum) {
  14434. var componentBounds = getBounds$1(component);
  14435. var spectrumBounds = getBounds$1(spectrum);
  14436. var componentMinEdge = getBoundsProperty(componentBounds, top);
  14437. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  14438. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  14439. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14440. };
  14441. var fireSliderChange$1 = function (spectrum, value) {
  14442. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14443. };
  14444. var sliderValue = function (x) {
  14445. return { x: constant(x) };
  14446. };
  14447. var findValueOfOffset = function (spectrum, detail, left) {
  14448. var args = {
  14449. min: minX(detail),
  14450. max: maxX(detail),
  14451. range: xRange(detail),
  14452. value: left,
  14453. step: step(detail),
  14454. snap: snap(detail),
  14455. snapStart: snapStart(detail),
  14456. rounded: rounded(detail),
  14457. hasMinEdge: hasLEdge(detail),
  14458. hasMaxEdge: hasREdge(detail),
  14459. minBound: getMinXBounds(spectrum),
  14460. maxBound: getMaxXBounds(spectrum),
  14461. screenRange: getXScreenRange(spectrum)
  14462. };
  14463. return findValueOf(args);
  14464. };
  14465. var setValueFrom = function (spectrum, detail, value) {
  14466. var xValue = findValueOfOffset(spectrum, detail, value);
  14467. var sliderVal = sliderValue(xValue);
  14468. fireSliderChange$1(spectrum, sliderVal);
  14469. return xValue;
  14470. };
  14471. var setToMin = function (spectrum, detail) {
  14472. var min = minX(detail);
  14473. fireSliderChange$1(spectrum, sliderValue(min));
  14474. };
  14475. var setToMax = function (spectrum, detail) {
  14476. var max = maxX(detail);
  14477. fireSliderChange$1(spectrum, sliderValue(max));
  14478. };
  14479. var moveBy = function (direction, spectrum, detail) {
  14480. var f = direction > 0 ? increaseBy : reduceBy;
  14481. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  14482. fireSliderChange$1(spectrum, sliderValue(xValue));
  14483. return Option.some(xValue);
  14484. };
  14485. var handleMovement = function (direction) {
  14486. return function (spectrum, detail) {
  14487. return moveBy(direction, spectrum, detail).map(function () {
  14488. return true;
  14489. });
  14490. };
  14491. };
  14492. var getValueFromEvent = function (simulatedEvent) {
  14493. var pos = getEventSource(simulatedEvent);
  14494. return pos.map(function (p) {
  14495. return p.left();
  14496. });
  14497. };
  14498. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  14499. var minOffset = 0;
  14500. var maxOffset = getXScreenRange(spectrum);
  14501. var centerMinEdge = minEdge.bind(function (edge) {
  14502. return Option.some(getXCenterOffSetOf(edge, spectrum));
  14503. }).getOr(minOffset);
  14504. var centerMaxEdge = maxEdge.bind(function (edge) {
  14505. return Option.some(getXCenterOffSetOf(edge, spectrum));
  14506. }).getOr(maxOffset);
  14507. var args = {
  14508. min: minX(detail),
  14509. max: maxX(detail),
  14510. range: xRange(detail),
  14511. value: value,
  14512. hasMinEdge: hasLEdge(detail),
  14513. hasMaxEdge: hasREdge(detail),
  14514. minBound: getMinXBounds(spectrum),
  14515. minOffset: minOffset,
  14516. maxBound: getMaxXBounds(spectrum),
  14517. maxOffset: maxOffset,
  14518. centerMinEdge: centerMinEdge,
  14519. centerMaxEdge: centerMaxEdge
  14520. };
  14521. return findOffsetOfValue(args);
  14522. };
  14523. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14524. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  14525. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  14526. };
  14527. var setPositionFromValue = function (slider, thumb, detail, edges) {
  14528. var value = currentValue(detail);
  14529. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14530. var thumbRadius = get$7(thumb.element()) / 2;
  14531. set$2(thumb.element(), 'left', pos - thumbRadius + 'px');
  14532. };
  14533. var onLeft = handleMovement(-1);
  14534. var onRight = handleMovement(1);
  14535. var onUp = Option.none;
  14536. var onDown = Option.none;
  14537. var edgeActions = {
  14538. 'top-left': Option.none(),
  14539. 'top': Option.none(),
  14540. 'top-right': Option.none(),
  14541. 'right': Option.some(setToREdge),
  14542. 'bottom-right': Option.none(),
  14543. 'bottom': Option.none(),
  14544. 'bottom-left': Option.none(),
  14545. 'left': Option.some(setToLEdge)
  14546. };
  14547. var HorizontalModel = /*#__PURE__*/Object.freeze({
  14548. setValueFrom: setValueFrom,
  14549. setToMin: setToMin,
  14550. setToMax: setToMax,
  14551. findValueOfOffset: findValueOfOffset,
  14552. getValueFromEvent: getValueFromEvent,
  14553. findPositionOfValue: findPositionOfValue,
  14554. setPositionFromValue: setPositionFromValue,
  14555. onLeft: onLeft,
  14556. onRight: onRight,
  14557. onUp: onUp,
  14558. onDown: onDown,
  14559. edgeActions: edgeActions
  14560. });
  14561. var fireSliderChange$2 = function (spectrum, value) {
  14562. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14563. };
  14564. var sliderValue$1 = function (y) {
  14565. return { y: constant(y) };
  14566. };
  14567. var findValueOfOffset$1 = function (spectrum, detail, top) {
  14568. var args = {
  14569. min: minY(detail),
  14570. max: maxY(detail),
  14571. range: yRange(detail),
  14572. value: top,
  14573. step: step(detail),
  14574. snap: snap(detail),
  14575. snapStart: snapStart(detail),
  14576. rounded: rounded(detail),
  14577. hasMinEdge: hasTEdge(detail),
  14578. hasMaxEdge: hasBEdge(detail),
  14579. minBound: getMinYBounds(spectrum),
  14580. maxBound: getMaxYBounds(spectrum),
  14581. screenRange: getYScreenRange(spectrum)
  14582. };
  14583. return findValueOf(args);
  14584. };
  14585. var setValueFrom$1 = function (spectrum, detail, value) {
  14586. var yValue = findValueOfOffset$1(spectrum, detail, value);
  14587. var sliderVal = sliderValue$1(yValue);
  14588. fireSliderChange$2(spectrum, sliderVal);
  14589. return yValue;
  14590. };
  14591. var setToMin$1 = function (spectrum, detail) {
  14592. var min = minY(detail);
  14593. fireSliderChange$2(spectrum, sliderValue$1(min));
  14594. };
  14595. var setToMax$1 = function (spectrum, detail) {
  14596. var max = maxY(detail);
  14597. fireSliderChange$2(spectrum, sliderValue$1(max));
  14598. };
  14599. var moveBy$1 = function (direction, spectrum, detail) {
  14600. var f = direction > 0 ? increaseBy : reduceBy;
  14601. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  14602. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  14603. return Option.some(yValue);
  14604. };
  14605. var handleMovement$1 = function (direction) {
  14606. return function (spectrum, detail) {
  14607. return moveBy$1(direction, spectrum, detail).map(function () {
  14608. return true;
  14609. });
  14610. };
  14611. };
  14612. var getValueFromEvent$1 = function (simulatedEvent) {
  14613. var pos = getEventSource(simulatedEvent);
  14614. return pos.map(function (p) {
  14615. return p.top();
  14616. });
  14617. };
  14618. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  14619. var minOffset = 0;
  14620. var maxOffset = getYScreenRange(spectrum);
  14621. var centerMinEdge = minEdge.bind(function (edge) {
  14622. return Option.some(getYCenterOffSetOf(edge, spectrum));
  14623. }).getOr(minOffset);
  14624. var centerMaxEdge = maxEdge.bind(function (edge) {
  14625. return Option.some(getYCenterOffSetOf(edge, spectrum));
  14626. }).getOr(maxOffset);
  14627. var args = {
  14628. min: minY(detail),
  14629. max: maxY(detail),
  14630. range: yRange(detail),
  14631. value: value,
  14632. hasMinEdge: hasTEdge(detail),
  14633. hasMaxEdge: hasBEdge(detail),
  14634. minBound: getMinYBounds(spectrum),
  14635. minOffset: minOffset,
  14636. maxBound: getMaxYBounds(spectrum),
  14637. maxOffset: maxOffset,
  14638. centerMinEdge: centerMinEdge,
  14639. centerMaxEdge: centerMaxEdge
  14640. };
  14641. return findOffsetOfValue(args);
  14642. };
  14643. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14644. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  14645. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  14646. };
  14647. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  14648. var value = currentValue(detail);
  14649. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14650. var thumbRadius = get$6(thumb.element()) / 2;
  14651. set$2(thumb.element(), 'top', pos - thumbRadius + 'px');
  14652. };
  14653. var onLeft$1 = Option.none;
  14654. var onRight$1 = Option.none;
  14655. var onUp$1 = handleMovement$1(-1);
  14656. var onDown$1 = handleMovement$1(1);
  14657. var edgeActions$1 = {
  14658. 'top-left': Option.none(),
  14659. 'top': Option.some(setToTEdge),
  14660. 'top-right': Option.none(),
  14661. 'right': Option.none(),
  14662. 'bottom-right': Option.none(),
  14663. 'bottom': Option.some(setToBEdge),
  14664. 'bottom-left': Option.none(),
  14665. 'left': Option.none()
  14666. };
  14667. var VerticalModel = /*#__PURE__*/Object.freeze({
  14668. setValueFrom: setValueFrom$1,
  14669. setToMin: setToMin$1,
  14670. setToMax: setToMax$1,
  14671. findValueOfOffset: findValueOfOffset$1,
  14672. getValueFromEvent: getValueFromEvent$1,
  14673. findPositionOfValue: findPositionOfValue$1,
  14674. setPositionFromValue: setPositionFromValue$1,
  14675. onLeft: onLeft$1,
  14676. onRight: onRight$1,
  14677. onUp: onUp$1,
  14678. onDown: onDown$1,
  14679. edgeActions: edgeActions$1
  14680. });
  14681. var fireSliderChange$3 = function (spectrum, value) {
  14682. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14683. };
  14684. var sliderValue$2 = function (x, y) {
  14685. return {
  14686. x: constant(x),
  14687. y: constant(y)
  14688. };
  14689. };
  14690. var setValueFrom$2 = function (spectrum, detail, value) {
  14691. var xValue = findValueOfOffset(spectrum, detail, value.left());
  14692. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  14693. var val = sliderValue$2(xValue, yValue);
  14694. fireSliderChange$3(spectrum, val);
  14695. return val;
  14696. };
  14697. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  14698. var f = direction > 0 ? increaseBy : reduceBy;
  14699. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  14700. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  14701. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  14702. return Option.some(xValue);
  14703. };
  14704. var handleMovement$2 = function (direction, isVerticalMovement) {
  14705. return function (spectrum, detail) {
  14706. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  14707. return true;
  14708. });
  14709. };
  14710. };
  14711. var setToMin$2 = function (spectrum, detail) {
  14712. var mX = minX(detail);
  14713. var mY = minY(detail);
  14714. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14715. };
  14716. var setToMax$2 = function (spectrum, detail) {
  14717. var mX = maxX(detail);
  14718. var mY = maxY(detail);
  14719. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14720. };
  14721. var getValueFromEvent$2 = function (simulatedEvent) {
  14722. return getEventSource(simulatedEvent);
  14723. };
  14724. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  14725. var value = currentValue(detail);
  14726. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14727. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14728. var thumbXRadius = get$7(thumb.element()) / 2;
  14729. var thumbYRadius = get$6(thumb.element()) / 2;
  14730. set$2(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  14731. set$2(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  14732. };
  14733. var onLeft$2 = handleMovement$2(-1, false);
  14734. var onRight$2 = handleMovement$2(1, false);
  14735. var onUp$2 = handleMovement$2(-1, true);
  14736. var onDown$2 = handleMovement$2(1, true);
  14737. var edgeActions$2 = {
  14738. 'top-left': Option.some(setToTLEdgeXY),
  14739. 'top': Option.some(setToTEdgeXY),
  14740. 'top-right': Option.some(setToTREdgeXY),
  14741. 'right': Option.some(setToREdgeXY),
  14742. 'bottom-right': Option.some(setToBREdgeXY),
  14743. 'bottom': Option.some(setToBEdgeXY),
  14744. 'bottom-left': Option.some(setToBLEdgeXY),
  14745. 'left': Option.some(setToLEdgeXY)
  14746. };
  14747. var TwoDModel = /*#__PURE__*/Object.freeze({
  14748. setValueFrom: setValueFrom$2,
  14749. setToMin: setToMin$2,
  14750. setToMax: setToMax$2,
  14751. getValueFromEvent: getValueFromEvent$2,
  14752. setPositionFromValue: setPositionFromValue$2,
  14753. onLeft: onLeft$2,
  14754. onRight: onRight$2,
  14755. onUp: onUp$2,
  14756. onDown: onDown$2,
  14757. edgeActions: edgeActions$2
  14758. });
  14759. var isTouch$2 = detect$3().deviceType.isTouch();
  14760. var SliderSchema = [
  14761. defaulted$1('stepSize', 1),
  14762. defaulted$1('onChange', noop),
  14763. defaulted$1('onChoose', noop),
  14764. defaulted$1('onInit', noop),
  14765. defaulted$1('onDragStart', noop),
  14766. defaulted$1('onDragEnd', noop),
  14767. defaulted$1('snapToGrid', false),
  14768. defaulted$1('rounded', true),
  14769. option('snapStart'),
  14770. strictOf('model', choose$1('mode', {
  14771. x: [
  14772. defaulted$1('minX', 0),
  14773. defaulted$1('maxX', 100),
  14774. state$1('value', function (spec) {
  14775. return Cell(spec.mode.minX);
  14776. }),
  14777. strict$1('getInitialValue'),
  14778. output('manager', HorizontalModel)
  14779. ],
  14780. y: [
  14781. defaulted$1('minY', 0),
  14782. defaulted$1('maxY', 100),
  14783. state$1('value', function (spec) {
  14784. return Cell(spec.mode.minY);
  14785. }),
  14786. strict$1('getInitialValue'),
  14787. output('manager', VerticalModel)
  14788. ],
  14789. xy: [
  14790. defaulted$1('minX', 0),
  14791. defaulted$1('maxX', 100),
  14792. defaulted$1('minY', 0),
  14793. defaulted$1('maxY', 100),
  14794. state$1('value', function (spec) {
  14795. return Cell({
  14796. x: constant(spec.mode.minX),
  14797. y: constant(spec.mode.minY)
  14798. });
  14799. }),
  14800. strict$1('getInitialValue'),
  14801. output('manager', TwoDModel)
  14802. ]
  14803. })),
  14804. field$1('sliderBehaviours', [
  14805. Keying,
  14806. Representing
  14807. ])
  14808. ].concat(!isTouch$2 ? [state$1('mouseIsDown', function () {
  14809. return Cell(false);
  14810. })] : []);
  14811. var isTouch$3 = detect$3().deviceType.isTouch();
  14812. var sketch = function (detail, components, _spec, _externals) {
  14813. var getThumb = function (component) {
  14814. return getPartOrDie(component, detail, 'thumb');
  14815. };
  14816. var getSpectrum = function (component) {
  14817. return getPartOrDie(component, detail, 'spectrum');
  14818. };
  14819. var getLeftEdge = function (component) {
  14820. return getPart(component, detail, 'left-edge');
  14821. };
  14822. var getRightEdge = function (component) {
  14823. return getPart(component, detail, 'right-edge');
  14824. };
  14825. var getTopEdge = function (component) {
  14826. return getPart(component, detail, 'top-edge');
  14827. };
  14828. var getBottomEdge = function (component) {
  14829. return getPart(component, detail, 'bottom-edge');
  14830. };
  14831. var modelDetail = detail.model;
  14832. var model = modelDetail.manager;
  14833. var refresh = function (slider, thumb) {
  14834. model.setPositionFromValue(slider, thumb, detail, {
  14835. getLeftEdge: getLeftEdge,
  14836. getRightEdge: getRightEdge,
  14837. getTopEdge: getTopEdge,
  14838. getBottomEdge: getBottomEdge,
  14839. getSpectrum: getSpectrum
  14840. });
  14841. };
  14842. var changeValue = function (slider, newValue) {
  14843. modelDetail.value.set(newValue);
  14844. var thumb = getThumb(slider);
  14845. refresh(slider, thumb);
  14846. detail.onChange(slider, thumb, newValue);
  14847. return Option.some(true);
  14848. };
  14849. var resetToMin = function (slider) {
  14850. model.setToMin(slider, detail);
  14851. };
  14852. var resetToMax = function (slider) {
  14853. model.setToMax(slider, detail);
  14854. };
  14855. var touchEvents = [
  14856. run(touchstart(), function (slider, _simulatedEvent) {
  14857. detail.onDragStart(slider, getThumb(slider));
  14858. }),
  14859. run(touchend(), function (slider, _simulatedEvent) {
  14860. detail.onDragEnd(slider, getThumb(slider));
  14861. })
  14862. ];
  14863. var mouseEvents = [
  14864. run(mousedown(), function (slider, simulatedEvent) {
  14865. simulatedEvent.stop();
  14866. detail.onDragStart(slider, getThumb(slider));
  14867. detail.mouseIsDown.set(true);
  14868. }),
  14869. run(mouseup(), function (slider, _simulatedEvent) {
  14870. detail.onDragEnd(slider, getThumb(slider));
  14871. })
  14872. ];
  14873. var uiEventsArr = isTouch$3 ? touchEvents : mouseEvents;
  14874. return {
  14875. uid: detail.uid,
  14876. dom: detail.dom,
  14877. components: components,
  14878. behaviours: augment(detail.sliderBehaviours, flatten([
  14879. !isTouch$3 ? [Keying.config({
  14880. mode: 'special',
  14881. focusIn: function (slider) {
  14882. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  14883. }
  14884. })] : [],
  14885. [
  14886. Representing.config({
  14887. store: {
  14888. mode: 'manual',
  14889. getValue: function (_) {
  14890. return modelDetail.value.get();
  14891. }
  14892. }
  14893. }),
  14894. Receiving.config({
  14895. channels: {
  14896. 'mouse.released': {
  14897. onReceive: function (slider, se) {
  14898. var fireOnChoose = function () {
  14899. getPart(slider, detail, 'thumb').each(function (thumb) {
  14900. var value = modelDetail.value.get();
  14901. detail.onChoose(slider, thumb, value);
  14902. });
  14903. };
  14904. if (isTouch$3) {
  14905. fireOnChoose();
  14906. } else {
  14907. var wasDown = detail.mouseIsDown.get();
  14908. detail.mouseIsDown.set(false);
  14909. if (wasDown) {
  14910. fireOnChoose();
  14911. }
  14912. }
  14913. }
  14914. }
  14915. }
  14916. })
  14917. ]
  14918. ])),
  14919. events: derive([
  14920. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  14921. changeValue(slider, simulatedEvent.event().value());
  14922. }),
  14923. runOnAttached(function (slider, simulatedEvent) {
  14924. var getInitial = modelDetail.getInitialValue();
  14925. modelDetail.value.set(getInitial);
  14926. var thumb = getThumb(slider);
  14927. refresh(slider, thumb);
  14928. var spectrum = getSpectrum(slider);
  14929. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  14930. })
  14931. ].concat(uiEventsArr)),
  14932. apis: {
  14933. resetToMin: resetToMin,
  14934. resetToMax: resetToMax,
  14935. changeValue: changeValue,
  14936. refresh: refresh
  14937. },
  14938. domModification: { styles: { position: 'relative' } }
  14939. };
  14940. };
  14941. var Slider = composite$1({
  14942. name: 'Slider',
  14943. configFields: SliderSchema,
  14944. partFields: SliderParts,
  14945. factory: sketch,
  14946. apis: {
  14947. resetToMin: function (apis, slider) {
  14948. apis.resetToMin(slider);
  14949. },
  14950. resetToMax: function (apis, slider) {
  14951. apis.resetToMax(slider);
  14952. },
  14953. refresh: function (apis, slider) {
  14954. apis.refresh(slider);
  14955. }
  14956. }
  14957. });
  14958. var sliderFactory = function (translate, getClass) {
  14959. var spectrum = Slider.parts().spectrum({
  14960. dom: {
  14961. tag: 'div',
  14962. classes: [getClass('hue-slider-spectrum')],
  14963. attributes: { role: 'presentation' }
  14964. }
  14965. });
  14966. var thumb = Slider.parts().thumb({
  14967. dom: {
  14968. tag: 'div',
  14969. classes: [getClass('hue-slider-thumb')],
  14970. attributes: { role: 'presentation' }
  14971. }
  14972. });
  14973. return Slider.sketch({
  14974. dom: {
  14975. tag: 'div',
  14976. classes: [getClass('hue-slider')],
  14977. attributes: { role: 'presentation' }
  14978. },
  14979. rounded: false,
  14980. model: {
  14981. mode: 'y',
  14982. getInitialValue: constant({ y: constant(0) })
  14983. },
  14984. components: [
  14985. spectrum,
  14986. thumb
  14987. ],
  14988. sliderBehaviours: derive$1([Focusing.config({})]),
  14989. onChange: function (slider, _thumb, value) {
  14990. emitWith(slider, sliderUpdate(), { value: value });
  14991. }
  14992. });
  14993. };
  14994. var HueSlider = { sliderFactory: sliderFactory };
  14995. var owner$3 = 'form';
  14996. var schema$h = [field$1('formBehaviours', [Representing])];
  14997. var getPartName = function (name) {
  14998. return '<alloy.field.' + name + '>';
  14999. };
  15000. var sketch$1 = function (fSpec) {
  15001. var parts = function () {
  15002. var record = [];
  15003. var field = function (name, config) {
  15004. record.push(name);
  15005. return generateOne(owner$3, getPartName(name), config);
  15006. };
  15007. return {
  15008. field: field,
  15009. record: function () {
  15010. return record;
  15011. }
  15012. };
  15013. }();
  15014. var spec = fSpec(parts);
  15015. var partNames = parts.record();
  15016. var fieldParts = map(partNames, function (n) {
  15017. return required({
  15018. name: n,
  15019. pname: getPartName(n)
  15020. });
  15021. });
  15022. return composite(owner$3, schema$h, fieldParts, make$4, spec);
  15023. };
  15024. var toResult$1 = function (o, e) {
  15025. return o.fold(function () {
  15026. return Result.error(e);
  15027. }, Result.value);
  15028. };
  15029. var make$4 = function (detail, components, spec) {
  15030. return {
  15031. uid: detail.uid,
  15032. dom: detail.dom,
  15033. components: components,
  15034. behaviours: augment(detail.formBehaviours, [Representing.config({
  15035. store: {
  15036. mode: 'manual',
  15037. getValue: function (form) {
  15038. var resPs = getAllParts(form, detail);
  15039. return map$1(resPs, function (resPThunk, pName) {
  15040. return resPThunk().bind(function (v) {
  15041. var opt = Composing.getCurrent(v);
  15042. return toResult$1(opt, 'missing current');
  15043. }).map(Representing.getValue);
  15044. });
  15045. },
  15046. setValue: function (form, values) {
  15047. each$1(values, function (newValue, key) {
  15048. getPart(form, detail, key).each(function (wrapper) {
  15049. Composing.getCurrent(wrapper).each(function (field) {
  15050. Representing.setValue(field, newValue);
  15051. });
  15052. });
  15053. });
  15054. }
  15055. }
  15056. })]),
  15057. apis: {
  15058. getField: function (form, key) {
  15059. return getPart(form, detail, key).bind(Composing.getCurrent);
  15060. }
  15061. }
  15062. };
  15063. };
  15064. var Form = {
  15065. getField: makeApi(function (apis, component, key) {
  15066. return apis.getField(component, key);
  15067. }),
  15068. sketch: sketch$1
  15069. };
  15070. var validInput = generate$1('valid-input');
  15071. var invalidInput = generate$1('invalid-input');
  15072. var validatingInput = generate$1('validating-input');
  15073. var translatePrefix = 'colorcustom.rgb.';
  15074. var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  15075. var invalidation = function (label, isValid) {
  15076. return Invalidating.config({
  15077. invalidClass: getClass('invalid'),
  15078. notify: {
  15079. onValidate: function (comp) {
  15080. emitWith(comp, validatingInput, { type: label });
  15081. },
  15082. onValid: function (comp) {
  15083. emitWith(comp, validInput, {
  15084. type: label,
  15085. value: Representing.getValue(comp)
  15086. });
  15087. },
  15088. onInvalid: function (comp) {
  15089. emitWith(comp, invalidInput, {
  15090. type: label,
  15091. value: Representing.getValue(comp)
  15092. });
  15093. }
  15094. },
  15095. validator: {
  15096. validate: function (comp) {
  15097. var value = Representing.getValue(comp);
  15098. var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  15099. return Future.pure(res);
  15100. },
  15101. validateOnLoad: false
  15102. }
  15103. });
  15104. };
  15105. var renderTextField = function (isValid, name, label, description, data) {
  15106. var helptext = translate(translatePrefix + 'range');
  15107. var pLabel = FormField.parts().label({
  15108. dom: {
  15109. tag: 'label',
  15110. innerHtml: label,
  15111. attributes: { 'aria-label': description }
  15112. }
  15113. });
  15114. var pField = FormField.parts().field({
  15115. data: data,
  15116. factory: Input,
  15117. inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  15118. inputClasses: [getClass('textfield')],
  15119. inputBehaviours: derive$1([
  15120. invalidation(name, isValid),
  15121. Tabstopping.config({})
  15122. ]),
  15123. onSetValue: function (input) {
  15124. if (Invalidating.isInvalid(input)) {
  15125. var run = Invalidating.run(input);
  15126. run.get(noop);
  15127. }
  15128. }
  15129. });
  15130. var comps = [
  15131. pLabel,
  15132. pField
  15133. ];
  15134. var concats = name !== 'hex' ? [FormField.parts()['aria-descriptor']({ text: helptext })] : [];
  15135. var components = comps.concat(concats);
  15136. return {
  15137. dom: {
  15138. tag: 'div',
  15139. attributes: { role: 'presentation' }
  15140. },
  15141. components: components
  15142. };
  15143. };
  15144. var copyRgbToHex = function (form, rgba) {
  15145. var hex = fromRgba(rgba);
  15146. Form.getField(form, 'hex').each(function (hexField) {
  15147. if (!Focusing.isFocused(hexField)) {
  15148. Representing.setValue(form, { hex: hex.value() });
  15149. }
  15150. });
  15151. return hex;
  15152. };
  15153. var copyRgbToForm = function (form, rgb) {
  15154. var red = rgb.red();
  15155. var green = rgb.green();
  15156. var blue = rgb.blue();
  15157. Representing.setValue(form, {
  15158. red: red,
  15159. green: green,
  15160. blue: blue
  15161. });
  15162. };
  15163. var memPreview = record({
  15164. dom: {
  15165. tag: 'div',
  15166. classes: [getClass('rgba-preview')],
  15167. styles: { 'background-color': 'white' },
  15168. attributes: { role: 'presentation' }
  15169. }
  15170. });
  15171. var updatePreview = function (anyInSystem, hex) {
  15172. memPreview.getOpt(anyInSystem).each(function (preview) {
  15173. set$2(preview.element(), 'background-color', '#' + hex.value());
  15174. });
  15175. };
  15176. var factory = function () {
  15177. var state = {
  15178. red: constant(Cell(Option.some(255))),
  15179. green: constant(Cell(Option.some(255))),
  15180. blue: constant(Cell(Option.some(255))),
  15181. hex: constant(Cell(Option.some('ffffff')))
  15182. };
  15183. var copyHexToRgb = function (form, hex) {
  15184. var rgb = fromHex(hex);
  15185. copyRgbToForm(form, rgb);
  15186. setValueRgb(rgb);
  15187. };
  15188. var get = function (prop) {
  15189. return state[prop]().get();
  15190. };
  15191. var set = function (prop, value) {
  15192. state[prop]().set(value);
  15193. };
  15194. var getValueRgb = function () {
  15195. return get('red').bind(function (red) {
  15196. return get('green').bind(function (green) {
  15197. return get('blue').map(function (blue) {
  15198. return rgbaColour(red, green, blue, 1);
  15199. });
  15200. });
  15201. });
  15202. };
  15203. var setValueRgb = function (rgb) {
  15204. var red = rgb.red();
  15205. var green = rgb.green();
  15206. var blue = rgb.blue();
  15207. set('red', Option.some(red));
  15208. set('green', Option.some(green));
  15209. set('blue', Option.some(blue));
  15210. };
  15211. var onInvalidInput = function (form, simulatedEvent) {
  15212. var data = simulatedEvent.event();
  15213. if (data.type() !== 'hex') {
  15214. set(data.type(), Option.none());
  15215. } else {
  15216. onInvalidHexx(form);
  15217. }
  15218. };
  15219. var onValidHex = function (form, value) {
  15220. onValidHexx(form);
  15221. var hex = hexColour(value);
  15222. set('hex', Option.some(value));
  15223. var rgb = fromHex(hex);
  15224. copyRgbToForm(form, rgb);
  15225. setValueRgb(rgb);
  15226. emitWith(form, fieldsUpdate(), { hex: hex });
  15227. updatePreview(form, hex);
  15228. };
  15229. var onValidRgb = function (form, prop, value) {
  15230. var val = parseInt(value, 10);
  15231. set(prop, Option.some(val));
  15232. getValueRgb().each(function (rgb) {
  15233. var hex = copyRgbToHex(form, rgb);
  15234. updatePreview(form, hex);
  15235. });
  15236. };
  15237. var isHexInputEvent = function (data) {
  15238. return data.type() === 'hex';
  15239. };
  15240. var onValidInput = function (form, simulatedEvent) {
  15241. var data = simulatedEvent.event();
  15242. if (isHexInputEvent(data)) {
  15243. onValidHex(form, data.value());
  15244. } else {
  15245. onValidRgb(form, data.type(), data.value());
  15246. }
  15247. };
  15248. var formPartStrings = function (key) {
  15249. return {
  15250. label: translate(translatePrefix + key + '.label'),
  15251. description: translate(translatePrefix + key + '.description')
  15252. };
  15253. };
  15254. var redStrings = formPartStrings('red');
  15255. var greenStrings = formPartStrings('green');
  15256. var blueStrings = formPartStrings('blue');
  15257. var hexStrings = formPartStrings('hex');
  15258. return deepMerge(Form.sketch(function (parts) {
  15259. return {
  15260. dom: {
  15261. tag: 'form',
  15262. classes: [getClass('rgb-form')],
  15263. attributes: { 'aria-label': translate('aria.color.picker') }
  15264. },
  15265. components: [
  15266. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  15267. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  15268. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  15269. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  15270. memPreview.asSpec()
  15271. ],
  15272. formBehaviours: derive$1([
  15273. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  15274. config('rgb-form-events', [
  15275. run(validInput, onValidInput),
  15276. run(invalidInput, onInvalidInput),
  15277. run(validatingInput, onInvalidInput)
  15278. ])
  15279. ])
  15280. };
  15281. }), {
  15282. apis: {
  15283. updateHex: function (form, hex) {
  15284. Representing.setValue(form, { hex: hex.value() });
  15285. copyHexToRgb(form, hex);
  15286. updatePreview(form, hex);
  15287. }
  15288. }
  15289. });
  15290. };
  15291. var rgbFormSketcher = single$2({
  15292. factory: factory,
  15293. name: 'RgbForm',
  15294. configFields: [],
  15295. apis: {
  15296. updateHex: function (apis, form, hex) {
  15297. apis.updateHex(form, hex);
  15298. }
  15299. },
  15300. extraApis: {}
  15301. });
  15302. return rgbFormSketcher;
  15303. };
  15304. var RgbForm = { rgbFormFactory: rgbFormFactory };
  15305. var paletteFactory = function (_translate, getClass) {
  15306. var spectrumPart = Slider.parts().spectrum({
  15307. dom: {
  15308. tag: 'canvas',
  15309. attributes: { role: 'presentation' },
  15310. classes: [getClass('sv-palette-spectrum')]
  15311. }
  15312. });
  15313. var thumbPart = Slider.parts().thumb({
  15314. dom: {
  15315. tag: 'div',
  15316. attributes: { role: 'presentation' },
  15317. classes: [getClass('sv-palette-thumb')],
  15318. innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  15319. }
  15320. });
  15321. var setColour = function (canvas, rgba) {
  15322. var width = canvas.width, height = canvas.height;
  15323. var ctx = canvas.getContext('2d');
  15324. if (ctx === null) {
  15325. return;
  15326. }
  15327. ctx.fillStyle = rgba;
  15328. ctx.fillRect(0, 0, width, height);
  15329. var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  15330. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  15331. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  15332. ctx.fillStyle = grdWhite;
  15333. ctx.fillRect(0, 0, width, height);
  15334. var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  15335. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  15336. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  15337. ctx.fillStyle = grdBlack;
  15338. ctx.fillRect(0, 0, width, height);
  15339. };
  15340. var setSliderColour = function (slider, rgba) {
  15341. var canvas = slider.components()[0].element().dom();
  15342. setColour(canvas, toString(rgba));
  15343. };
  15344. var factory = function (_detail) {
  15345. var getInitialValue = constant({
  15346. x: constant(0),
  15347. y: constant(0)
  15348. });
  15349. var onChange = function (slider, _thumb, value) {
  15350. emitWith(slider, paletteUpdate(), { value: value });
  15351. };
  15352. var onInit = function (_slider, _thumb, spectrum, _value) {
  15353. setColour(spectrum.element().dom(), toString(redColour()));
  15354. };
  15355. var sliderBehaviours = derive$1([
  15356. Composing.config({ find: Option.some }),
  15357. Focusing.config({})
  15358. ]);
  15359. return Slider.sketch({
  15360. dom: {
  15361. tag: 'div',
  15362. attributes: { role: 'presentation' },
  15363. classes: [getClass('sv-palette')]
  15364. },
  15365. model: {
  15366. mode: 'xy',
  15367. getInitialValue: getInitialValue
  15368. },
  15369. rounded: false,
  15370. components: [
  15371. spectrumPart,
  15372. thumbPart
  15373. ],
  15374. onChange: onChange,
  15375. onInit: onInit,
  15376. sliderBehaviours: sliderBehaviours
  15377. });
  15378. };
  15379. var saturationBrightnessPaletteSketcher = single$2({
  15380. factory: factory,
  15381. name: 'SaturationBrightnessPalette',
  15382. configFields: [],
  15383. apis: {
  15384. setRgba: function (_apis, slider, rgba) {
  15385. setSliderColour(slider, rgba);
  15386. }
  15387. },
  15388. extraApis: {}
  15389. });
  15390. return saturationBrightnessPaletteSketcher;
  15391. };
  15392. var SaturationBrightnessPalette = { paletteFactory: paletteFactory };
  15393. var makeFactory = function (translate, getClass) {
  15394. var factory = function (detail) {
  15395. var rgbForm = RgbForm.rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  15396. var sbPalette = SaturationBrightnessPalette.paletteFactory(translate, getClass);
  15397. var state = { paletteRgba: constant(Cell(redColour())) };
  15398. var memPalette = record(sbPalette.sketch({}));
  15399. var memRgb = record(rgbForm.sketch({}));
  15400. var updatePalette = function (anyInSystem, hex) {
  15401. memPalette.getOpt(anyInSystem).each(function (palette) {
  15402. var rgba = fromHex(hex);
  15403. state.paletteRgba().set(rgba);
  15404. sbPalette.setRgba(palette, rgba);
  15405. });
  15406. };
  15407. var updateFields = function (anyInSystem, hex) {
  15408. memRgb.getOpt(anyInSystem).each(function (form) {
  15409. rgbForm.updateHex(form, hex);
  15410. });
  15411. };
  15412. var runUpdates = function (anyInSystem, hex, updates) {
  15413. each(updates, function (update) {
  15414. update(anyInSystem, hex);
  15415. });
  15416. };
  15417. var paletteUpdates = function () {
  15418. var updates = [updateFields];
  15419. return function (form, simulatedEvent) {
  15420. var value = simulatedEvent.event().value();
  15421. var oldRgb = state.paletteRgba().get();
  15422. var hsvColour$1 = fromRgb(oldRgb);
  15423. var newHsvColour = hsvColour(hsvColour$1.hue(), value.x(), 100 - value.y());
  15424. var rgb = fromHsv(newHsvColour);
  15425. var nuHex = fromRgba(rgb);
  15426. runUpdates(form, nuHex, updates);
  15427. };
  15428. };
  15429. var sliderUpdates = function () {
  15430. var updates = [
  15431. updatePalette,
  15432. updateFields
  15433. ];
  15434. return function (form, simulatedEvent) {
  15435. var value = simulatedEvent.event().value();
  15436. var hex = calcHex(value.y());
  15437. runUpdates(form, hex, updates);
  15438. };
  15439. };
  15440. return {
  15441. uid: detail.uid,
  15442. dom: detail.dom,
  15443. components: [
  15444. memPalette.asSpec(),
  15445. HueSlider.sliderFactory(translate, getClass),
  15446. memRgb.asSpec()
  15447. ],
  15448. behaviours: derive$1([
  15449. config('colour-picker-events', [
  15450. run(paletteUpdate(), paletteUpdates()),
  15451. run(sliderUpdate(), sliderUpdates())
  15452. ]),
  15453. Composing.config({
  15454. find: function (comp) {
  15455. return memRgb.getOpt(comp);
  15456. }
  15457. }),
  15458. Keying.config({ mode: 'acyclic' })
  15459. ])
  15460. };
  15461. };
  15462. var colourPickerSketcher = single$2({
  15463. name: 'ColourPicker',
  15464. configFields: [
  15465. strict$1('dom'),
  15466. defaulted$1('onValidHex', noop),
  15467. defaulted$1('onInvalidHex', noop)
  15468. ],
  15469. factory: factory
  15470. });
  15471. return colourPickerSketcher;
  15472. };
  15473. var ColourPicker = { makeFactory: makeFactory };
  15474. var self$1 = function () {
  15475. return Composing.config({ find: Option.some });
  15476. };
  15477. var memento = function (mem) {
  15478. return Composing.config({ find: mem.getOpt });
  15479. };
  15480. var childAt = function (index) {
  15481. return Composing.config({
  15482. find: function (comp) {
  15483. return child(comp.element(), index).bind(function (element) {
  15484. return comp.getSystem().getByDom(element).toOption();
  15485. });
  15486. }
  15487. });
  15488. };
  15489. var ComposingConfigs = {
  15490. self: self$1,
  15491. memento: memento,
  15492. childAt: childAt
  15493. };
  15494. var english = {
  15495. 'colorcustom.rgb.red.label': 'R',
  15496. 'colorcustom.rgb.red.description': 'Red component',
  15497. 'colorcustom.rgb.green.label': 'G',
  15498. 'colorcustom.rgb.green.description': 'Green component',
  15499. 'colorcustom.rgb.blue.label': 'B',
  15500. 'colorcustom.rgb.blue.description': 'Blue component',
  15501. 'colorcustom.rgb.hex.label': '#',
  15502. 'colorcustom.rgb.hex.description': 'Hex color code',
  15503. 'colorcustom.rgb.range': 'Range 0 to 255',
  15504. 'colorcustom.sb.saturation': 'Saturation',
  15505. 'colorcustom.sb.brightness': 'Brightness',
  15506. 'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  15507. 'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  15508. 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  15509. 'colorcustom.hue.hue': 'Hue',
  15510. 'colorcustom.hue.slider': 'Hue Slider',
  15511. 'colorcustom.hue.palette': 'Hue Palette',
  15512. 'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  15513. 'aria.color.picker': 'Color Picker',
  15514. 'aria.input.invalid': 'Invalid input'
  15515. };
  15516. var getEnglishText = function (key) {
  15517. return english[key];
  15518. };
  15519. var translate$1 = function (key) {
  15520. return getEnglishText(key);
  15521. };
  15522. var renderColorPicker = function (spec) {
  15523. var getClass = function (key) {
  15524. return 'tox-' + key;
  15525. };
  15526. var colourPickerFactory = ColourPicker.makeFactory(translate$1, getClass);
  15527. var onValidHex = function (form) {
  15528. emitWith(form, formActionEvent, {
  15529. name: 'hex-valid',
  15530. value: true
  15531. });
  15532. };
  15533. var onInvalidHex = function (form) {
  15534. emitWith(form, formActionEvent, {
  15535. name: 'hex-valid',
  15536. value: false
  15537. });
  15538. };
  15539. var memPicker = record(colourPickerFactory.sketch({
  15540. dom: {
  15541. tag: 'div',
  15542. classes: [getClass('color-picker-container')],
  15543. attributes: { role: 'presentation' }
  15544. },
  15545. onValidHex: onValidHex,
  15546. onInvalidHex: onInvalidHex
  15547. }));
  15548. return {
  15549. dom: { tag: 'div' },
  15550. components: [memPicker.asSpec()],
  15551. behaviours: derive$1([
  15552. Representing.config({
  15553. store: {
  15554. mode: 'manual',
  15555. getValue: function (comp) {
  15556. var picker = memPicker.get(comp);
  15557. var optRgbForm = Composing.getCurrent(picker);
  15558. var optHex = optRgbForm.bind(function (rgbForm) {
  15559. var formValues = Representing.getValue(rgbForm);
  15560. return formValues.hex;
  15561. });
  15562. return optHex.map(function (hex) {
  15563. return '#' + hex;
  15564. }).getOr('');
  15565. },
  15566. setValue: function (comp, newValue) {
  15567. var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  15568. var m = pattern.exec(newValue);
  15569. var picker = memPicker.get(comp);
  15570. var optRgbForm = Composing.getCurrent(picker);
  15571. optRgbForm.fold(function () {
  15572. domGlobals.console.log('Can not find form');
  15573. }, function (rgbForm) {
  15574. Representing.setValue(rgbForm, { hex: Option.from(m[1]).getOr('') });
  15575. Form.getField(rgbForm, 'hex').each(function (hexField) {
  15576. emit(hexField, input());
  15577. });
  15578. });
  15579. }
  15580. }
  15581. }),
  15582. ComposingConfigs.self()
  15583. ])
  15584. };
  15585. };
  15586. var global$a = tinymce.util.Tools.resolve('tinymce.Resource');
  15587. var isOldCustomEditor = function (spec) {
  15588. return Object.prototype.hasOwnProperty.call(spec, 'init');
  15589. };
  15590. var renderCustomEditor = function (spec) {
  15591. var editorApi = Cell(Option.none());
  15592. var memReplaced = record({ dom: { tag: spec.tag } });
  15593. var initialValue = Cell(Option.none());
  15594. return {
  15595. dom: {
  15596. tag: 'div',
  15597. classes: ['tox-custom-editor']
  15598. },
  15599. behaviours: derive$1([
  15600. config('editor-foo-events', [runOnAttached(function (component) {
  15601. memReplaced.getOpt(component).each(function (ta) {
  15602. (isOldCustomEditor(spec) ? spec.init(ta.element().dom()) : global$a.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  15603. return init(ta.element().dom(), spec.settings);
  15604. })).then(function (ea) {
  15605. initialValue.get().each(function (cvalue) {
  15606. ea.setValue(cvalue);
  15607. });
  15608. initialValue.set(Option.none());
  15609. editorApi.set(Option.some(ea));
  15610. });
  15611. });
  15612. })]),
  15613. Representing.config({
  15614. store: {
  15615. mode: 'manual',
  15616. getValue: function () {
  15617. return editorApi.get().fold(function () {
  15618. return initialValue.get().getOr('');
  15619. }, function (ed) {
  15620. return ed.getValue();
  15621. });
  15622. },
  15623. setValue: function (component, value) {
  15624. editorApi.get().fold(function () {
  15625. initialValue.set(Option.some(value));
  15626. }, function (ed) {
  15627. return ed.setValue(value);
  15628. });
  15629. }
  15630. }
  15631. }),
  15632. ComposingConfigs.self()
  15633. ]),
  15634. components: [memReplaced.asSpec()]
  15635. };
  15636. };
  15637. var processors = objOf([
  15638. defaulted$1('preprocess', identity),
  15639. defaulted$1('postprocess', identity)
  15640. ]);
  15641. var memento$1 = function (mem, rawProcessors) {
  15642. var ps = asRawOrDie('RepresentingConfigs.memento processors', processors, rawProcessors);
  15643. return Representing.config({
  15644. store: {
  15645. mode: 'manual',
  15646. getValue: function (comp) {
  15647. var other = mem.get(comp);
  15648. var rawValue = Representing.getValue(other);
  15649. return ps.postprocess(rawValue);
  15650. },
  15651. setValue: function (comp, rawValue) {
  15652. var newValue = ps.preprocess(rawValue);
  15653. var other = mem.get(comp);
  15654. Representing.setValue(other, newValue);
  15655. }
  15656. }
  15657. });
  15658. };
  15659. var withComp = function (optInitialValue, getter, setter) {
  15660. return Representing.config(deepMerge({
  15661. store: {
  15662. mode: 'manual',
  15663. getValue: getter,
  15664. setValue: setter
  15665. }
  15666. }, optInitialValue.map(function (initialValue) {
  15667. return { store: { initialValue: initialValue } };
  15668. }).getOr({})));
  15669. };
  15670. var withElement = function (initialValue, getter, setter) {
  15671. return withComp(initialValue, function (c) {
  15672. return getter(c.element());
  15673. }, function (c, v) {
  15674. return setter(c.element(), v);
  15675. });
  15676. };
  15677. var domValue = function (optInitialValue) {
  15678. return withElement(optInitialValue, get$5, set$3);
  15679. };
  15680. var domHtml = function (optInitialValue) {
  15681. return withElement(optInitialValue, get$1, set);
  15682. };
  15683. var memory$1 = function (initialValue) {
  15684. return Representing.config({
  15685. store: {
  15686. mode: 'memory',
  15687. initialValue: initialValue
  15688. }
  15689. });
  15690. };
  15691. var RepresentingConfigs = {
  15692. memento: memento$1,
  15693. withElement: withElement,
  15694. withComp: withComp,
  15695. domValue: domValue,
  15696. domHtml: domHtml,
  15697. memory: memory$1
  15698. };
  15699. var extensionsAccepted = '.jpg,.jpeg,.png,.gif';
  15700. var filterByExtension = function (files) {
  15701. var re = new RegExp('(' + extensionsAccepted.split(/\s*,\s*/).join('|') + ')$', 'i');
  15702. return filter(from$1(files), function (file) {
  15703. return re.test(file.name);
  15704. });
  15705. };
  15706. var renderDropZone = function (spec, providersBackstage) {
  15707. var stopper = function (_, se) {
  15708. se.stop();
  15709. };
  15710. var sequence = function (actions) {
  15711. return function (comp, se) {
  15712. each(actions, function (a) {
  15713. a(comp, se);
  15714. });
  15715. };
  15716. };
  15717. var onDrop = function (comp, se) {
  15718. if (!Disabling.isDisabled(comp)) {
  15719. var transferEvent = se.event().raw();
  15720. handleFiles(comp, transferEvent.dataTransfer.files);
  15721. }
  15722. };
  15723. var onSelect = function (component, simulatedEvent) {
  15724. var files = simulatedEvent.event().raw().target.files;
  15725. handleFiles(component, files);
  15726. };
  15727. var handleFiles = function (component, files) {
  15728. Representing.setValue(component, filterByExtension(files));
  15729. emitWith(component, formChangeEvent, { name: spec.name });
  15730. };
  15731. var memInput = record({
  15732. dom: {
  15733. tag: 'input',
  15734. attributes: {
  15735. type: 'file',
  15736. accept: 'image/*'
  15737. },
  15738. styles: { display: 'none' }
  15739. },
  15740. behaviours: derive$1([config('input-file-events', [cutter(tapOrClick())])])
  15741. });
  15742. var renderField = function (s) {
  15743. return {
  15744. uid: s.uid,
  15745. dom: {
  15746. tag: 'div',
  15747. classes: ['tox-dropzone-container']
  15748. },
  15749. behaviours: derive$1([
  15750. RepresentingConfigs.memory([]),
  15751. ComposingConfigs.self(),
  15752. Disabling.config({}),
  15753. Toggling.config({
  15754. toggleClass: 'dragenter',
  15755. toggleOnExecute: false
  15756. }),
  15757. config('dropzone-events', [
  15758. run('dragenter', sequence([
  15759. stopper,
  15760. Toggling.toggle
  15761. ])),
  15762. run('dragleave', sequence([
  15763. stopper,
  15764. Toggling.toggle
  15765. ])),
  15766. run('dragover', stopper),
  15767. run('drop', sequence([
  15768. stopper,
  15769. onDrop
  15770. ])),
  15771. run(change(), onSelect)
  15772. ])
  15773. ]),
  15774. components: [{
  15775. dom: {
  15776. tag: 'div',
  15777. classes: ['tox-dropzone'],
  15778. styles: {}
  15779. },
  15780. components: [
  15781. {
  15782. dom: {
  15783. tag: 'p',
  15784. innerHtml: providersBackstage.translate('Drop an image here')
  15785. }
  15786. },
  15787. Button.sketch({
  15788. dom: {
  15789. tag: 'button',
  15790. innerHtml: providersBackstage.translate('Browse for an image'),
  15791. styles: { position: 'relative' },
  15792. classes: [
  15793. 'tox-button',
  15794. 'tox-button--secondary'
  15795. ]
  15796. },
  15797. components: [memInput.asSpec()],
  15798. action: function (comp) {
  15799. var inputComp = memInput.get(comp);
  15800. inputComp.element().dom().click();
  15801. },
  15802. buttonBehaviours: derive$1([Tabstopping.config({})])
  15803. })
  15804. ]
  15805. }]
  15806. };
  15807. };
  15808. var pLabel = spec.label.map(function (label) {
  15809. return renderLabel(label, providersBackstage);
  15810. });
  15811. var pField = FormField.parts().field({ factory: { sketch: renderField } });
  15812. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  15813. };
  15814. var renderGrid = function (spec, backstage) {
  15815. return {
  15816. dom: {
  15817. tag: 'div',
  15818. classes: [
  15819. 'tox-form__grid',
  15820. 'tox-form__grid--' + spec.columns + 'col'
  15821. ]
  15822. },
  15823. components: map(spec.items, backstage.interpreter)
  15824. };
  15825. };
  15826. var beforeObject = generate$1('alloy-fake-before-tabstop');
  15827. var afterObject = generate$1('alloy-fake-after-tabstop');
  15828. var craftWithClasses = function (classes) {
  15829. return {
  15830. dom: {
  15831. tag: 'div',
  15832. styles: {
  15833. width: '1px',
  15834. height: '1px',
  15835. outline: 'none'
  15836. },
  15837. attributes: { tabindex: '0' },
  15838. classes: classes
  15839. },
  15840. behaviours: derive$1([
  15841. Focusing.config({ ignore: true }),
  15842. Tabstopping.config({})
  15843. ])
  15844. };
  15845. };
  15846. var craft = function (spec) {
  15847. return {
  15848. dom: {
  15849. tag: 'div',
  15850. classes: ['tox-navobj']
  15851. },
  15852. components: [
  15853. craftWithClasses([beforeObject]),
  15854. spec,
  15855. craftWithClasses([afterObject])
  15856. ],
  15857. behaviours: derive$1([ComposingConfigs.childAt(1)])
  15858. };
  15859. };
  15860. var triggerTab = function (placeholder, shiftKey) {
  15861. emitWith(placeholder, keydown(), {
  15862. raw: {
  15863. which: 9,
  15864. shiftKey: shiftKey
  15865. }
  15866. });
  15867. };
  15868. var onFocus$1 = function (container, targetComp) {
  15869. var target = targetComp.element();
  15870. if (has$2(target, beforeObject)) {
  15871. triggerTab(container, true);
  15872. } else if (has$2(target, afterObject)) {
  15873. triggerTab(container, false);
  15874. }
  15875. };
  15876. var isPseudoStop = function (element) {
  15877. return closest$4(element, [
  15878. '.' + beforeObject,
  15879. '.' + afterObject
  15880. ].join(','), constant(false));
  15881. };
  15882. var NavigableObject = {
  15883. isPseudoStop: isPseudoStop,
  15884. onFocus: onFocus$1,
  15885. craft: craft
  15886. };
  15887. var platformNeedsSandboxing = !(detect$3().browser.isIE() || detect$3().browser.isEdge());
  15888. var getDynamicSource = function (isSandbox) {
  15889. var cachedValue = Cell('');
  15890. return {
  15891. getValue: function (frameComponent) {
  15892. return cachedValue.get();
  15893. },
  15894. setValue: function (frameComponent, html) {
  15895. if (!isSandbox) {
  15896. set$1(frameComponent.element(), 'src', 'javascript:\'\'');
  15897. var doc = frameComponent.element().dom().contentWindow.document;
  15898. doc.open();
  15899. doc.write(html);
  15900. doc.close();
  15901. } else {
  15902. set$1(frameComponent.element(), 'srcdoc', html);
  15903. }
  15904. cachedValue.set(html);
  15905. }
  15906. };
  15907. };
  15908. var renderIFrame = function (spec, providersBackstage) {
  15909. var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  15910. var attributes = __assign(__assign({}, spec.label.map(function (title) {
  15911. return { title: title };
  15912. }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  15913. var sourcing = getDynamicSource(isSandbox);
  15914. var pLabel = spec.label.map(function (label) {
  15915. return renderLabel(label, providersBackstage);
  15916. });
  15917. var factory = function (newSpec) {
  15918. return NavigableObject.craft({
  15919. uid: newSpec.uid,
  15920. dom: {
  15921. tag: 'iframe',
  15922. attributes: attributes
  15923. },
  15924. behaviours: derive$1([
  15925. Tabstopping.config({}),
  15926. Focusing.config({}),
  15927. RepresentingConfigs.withComp(Option.none(), sourcing.getValue, sourcing.setValue)
  15928. ])
  15929. });
  15930. };
  15931. var pField = FormField.parts().field({ factory: { sketch: factory } });
  15932. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  15933. };
  15934. function create$5(width, height) {
  15935. return resize(domGlobals.document.createElement('canvas'), width, height);
  15936. }
  15937. function clone$1(canvas) {
  15938. var tCanvas = create$5(canvas.width, canvas.height);
  15939. var ctx = get2dContext(tCanvas);
  15940. ctx.drawImage(canvas, 0, 0);
  15941. return tCanvas;
  15942. }
  15943. function get2dContext(canvas) {
  15944. return canvas.getContext('2d');
  15945. }
  15946. function resize(canvas, width, height) {
  15947. canvas.width = width;
  15948. canvas.height = height;
  15949. return canvas;
  15950. }
  15951. function getWidth(image) {
  15952. return image.naturalWidth || image.width;
  15953. }
  15954. function getHeight(image) {
  15955. return image.naturalHeight || image.height;
  15956. }
  15957. var promise = function () {
  15958. var Promise = function (fn) {
  15959. if (typeof this !== 'object') {
  15960. throw new TypeError('Promises must be constructed via new');
  15961. }
  15962. if (typeof fn !== 'function') {
  15963. throw new TypeError('not a function');
  15964. }
  15965. this._state = null;
  15966. this._value = null;
  15967. this._deferreds = [];
  15968. doResolve(fn, bind(resolve, this), bind(reject, this));
  15969. };
  15970. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  15971. domGlobals.setTimeout(fn, 1);
  15972. };
  15973. function bind(fn, thisArg) {
  15974. return function () {
  15975. return fn.apply(thisArg, arguments);
  15976. };
  15977. }
  15978. var isArray = Array.isArray || function (value) {
  15979. return Object.prototype.toString.call(value) === '[object Array]';
  15980. };
  15981. function handle(deferred) {
  15982. var me = this;
  15983. if (this._state === null) {
  15984. this._deferreds.push(deferred);
  15985. return;
  15986. }
  15987. asap(function () {
  15988. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  15989. if (cb === null) {
  15990. (me._state ? deferred.resolve : deferred.reject)(me._value);
  15991. return;
  15992. }
  15993. var ret;
  15994. try {
  15995. ret = cb(me._value);
  15996. } catch (e) {
  15997. deferred.reject(e);
  15998. return;
  15999. }
  16000. deferred.resolve(ret);
  16001. });
  16002. }
  16003. function resolve(newValue) {
  16004. try {
  16005. if (newValue === this) {
  16006. throw new TypeError('A promise cannot be resolved with itself.');
  16007. }
  16008. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  16009. var then = newValue.then;
  16010. if (typeof then === 'function') {
  16011. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  16012. return;
  16013. }
  16014. }
  16015. this._state = true;
  16016. this._value = newValue;
  16017. finale.call(this);
  16018. } catch (e) {
  16019. reject.call(this, e);
  16020. }
  16021. }
  16022. function reject(newValue) {
  16023. this._state = false;
  16024. this._value = newValue;
  16025. finale.call(this);
  16026. }
  16027. function finale() {
  16028. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  16029. var deferred = _a[_i];
  16030. handle.call(this, deferred);
  16031. }
  16032. this._deferreds = [];
  16033. }
  16034. function Handler(onFulfilled, onRejected, resolve, reject) {
  16035. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  16036. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  16037. this.resolve = resolve;
  16038. this.reject = reject;
  16039. }
  16040. function doResolve(fn, onFulfilled, onRejected) {
  16041. var done = false;
  16042. try {
  16043. fn(function (value) {
  16044. if (done) {
  16045. return;
  16046. }
  16047. done = true;
  16048. onFulfilled(value);
  16049. }, function (reason) {
  16050. if (done) {
  16051. return;
  16052. }
  16053. done = true;
  16054. onRejected(reason);
  16055. });
  16056. } catch (ex) {
  16057. if (done) {
  16058. return;
  16059. }
  16060. done = true;
  16061. onRejected(ex);
  16062. }
  16063. }
  16064. Promise.prototype.catch = function (onRejected) {
  16065. return this.then(null, onRejected);
  16066. };
  16067. Promise.prototype.then = function (onFulfilled, onRejected) {
  16068. var me = this;
  16069. return new Promise(function (resolve, reject) {
  16070. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  16071. });
  16072. };
  16073. Promise.all = function () {
  16074. var values = [];
  16075. for (var _i = 0; _i < arguments.length; _i++) {
  16076. values[_i] = arguments[_i];
  16077. }
  16078. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  16079. return new Promise(function (resolve, reject) {
  16080. if (args.length === 0) {
  16081. return resolve([]);
  16082. }
  16083. var remaining = args.length;
  16084. function res(i, val) {
  16085. try {
  16086. if (val && (typeof val === 'object' || typeof val === 'function')) {
  16087. var then = val.then;
  16088. if (typeof then === 'function') {
  16089. then.call(val, function (val) {
  16090. res(i, val);
  16091. }, reject);
  16092. return;
  16093. }
  16094. }
  16095. args[i] = val;
  16096. if (--remaining === 0) {
  16097. resolve(args);
  16098. }
  16099. } catch (ex) {
  16100. reject(ex);
  16101. }
  16102. }
  16103. for (var i = 0; i < args.length; i++) {
  16104. res(i, args[i]);
  16105. }
  16106. });
  16107. };
  16108. Promise.resolve = function (value) {
  16109. if (value && typeof value === 'object' && value.constructor === Promise) {
  16110. return value;
  16111. }
  16112. return new Promise(function (resolve) {
  16113. resolve(value);
  16114. });
  16115. };
  16116. Promise.reject = function (reason) {
  16117. return new Promise(function (resolve, reject) {
  16118. reject(reason);
  16119. });
  16120. };
  16121. Promise.race = function (values) {
  16122. return new Promise(function (resolve, reject) {
  16123. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  16124. var value = values_1[_i];
  16125. value.then(resolve, reject);
  16126. }
  16127. });
  16128. };
  16129. return Promise;
  16130. };
  16131. var Promise$1 = window.Promise ? window.Promise : promise();
  16132. function blobToImage(blob) {
  16133. return new Promise$1(function (resolve, reject) {
  16134. var blobUrl = domGlobals.URL.createObjectURL(blob);
  16135. var image = new domGlobals.Image();
  16136. var removeListeners = function () {
  16137. image.removeEventListener('load', loaded);
  16138. image.removeEventListener('error', error);
  16139. };
  16140. function loaded() {
  16141. removeListeners();
  16142. resolve(image);
  16143. }
  16144. function error() {
  16145. removeListeners();
  16146. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  16147. }
  16148. image.addEventListener('load', loaded);
  16149. image.addEventListener('error', error);
  16150. image.src = blobUrl;
  16151. if (image.complete) {
  16152. loaded();
  16153. }
  16154. });
  16155. }
  16156. function dataUriToBlobSync(uri) {
  16157. var data = uri.split(',');
  16158. var matches = /data:([^;]+)/.exec(data[0]);
  16159. if (!matches) {
  16160. return Option.none();
  16161. }
  16162. var mimetype = matches[1];
  16163. var base64 = data[1];
  16164. var sliceSize = 1024;
  16165. var byteCharacters = domGlobals.atob(base64);
  16166. var bytesLength = byteCharacters.length;
  16167. var slicesCount = Math.ceil(bytesLength / sliceSize);
  16168. var byteArrays = new Array(slicesCount);
  16169. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  16170. var begin = sliceIndex * sliceSize;
  16171. var end = Math.min(begin + sliceSize, bytesLength);
  16172. var bytes = new Array(end - begin);
  16173. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  16174. bytes[i] = byteCharacters[offset].charCodeAt(0);
  16175. }
  16176. byteArrays[sliceIndex] = new Uint8Array(bytes);
  16177. }
  16178. return Option.some(new domGlobals.Blob(byteArrays, { type: mimetype }));
  16179. }
  16180. function dataUriToBlob(uri) {
  16181. return new Promise$1(function (resolve, reject) {
  16182. dataUriToBlobSync(uri).fold(function () {
  16183. reject('uri is not base64: ' + uri);
  16184. }, resolve);
  16185. });
  16186. }
  16187. function canvasToBlob(canvas, type, quality) {
  16188. type = type || 'image/png';
  16189. if (domGlobals.HTMLCanvasElement.prototype.toBlob) {
  16190. return new Promise$1(function (resolve, reject) {
  16191. canvas.toBlob(function (blob) {
  16192. if (blob) {
  16193. resolve(blob);
  16194. } else {
  16195. reject();
  16196. }
  16197. }, type, quality);
  16198. });
  16199. } else {
  16200. return dataUriToBlob(canvas.toDataURL(type, quality));
  16201. }
  16202. }
  16203. function canvasToDataURL(canvas, type, quality) {
  16204. type = type || 'image/png';
  16205. return canvas.toDataURL(type, quality);
  16206. }
  16207. function blobToCanvas(blob) {
  16208. return blobToImage(blob).then(function (image) {
  16209. revokeImageUrl(image);
  16210. var canvas = create$5(getWidth(image), getHeight(image));
  16211. var context = get2dContext(canvas);
  16212. context.drawImage(image, 0, 0);
  16213. return canvas;
  16214. });
  16215. }
  16216. function blobToDataUri(blob) {
  16217. return new Promise$1(function (resolve) {
  16218. var reader = new domGlobals.FileReader();
  16219. reader.onloadend = function () {
  16220. resolve(reader.result);
  16221. };
  16222. reader.readAsDataURL(blob);
  16223. });
  16224. }
  16225. function revokeImageUrl(image) {
  16226. domGlobals.URL.revokeObjectURL(image.src);
  16227. }
  16228. function create$6(getCanvas, blob, uri) {
  16229. var initialType = blob.type;
  16230. var getType = constant(initialType);
  16231. function toBlob() {
  16232. return Promise$1.resolve(blob);
  16233. }
  16234. function toDataURL() {
  16235. return uri;
  16236. }
  16237. function toBase64() {
  16238. return uri.split(',')[1];
  16239. }
  16240. function toAdjustedBlob(type, quality) {
  16241. return getCanvas.then(function (canvas) {
  16242. return canvasToBlob(canvas, type, quality);
  16243. });
  16244. }
  16245. function toAdjustedDataURL(type, quality) {
  16246. return getCanvas.then(function (canvas) {
  16247. return canvasToDataURL(canvas, type, quality);
  16248. });
  16249. }
  16250. function toAdjustedBase64(type, quality) {
  16251. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  16252. return dataurl.split(',')[1];
  16253. });
  16254. }
  16255. function toCanvas() {
  16256. return getCanvas.then(clone$1);
  16257. }
  16258. return {
  16259. getType: getType,
  16260. toBlob: toBlob,
  16261. toDataURL: toDataURL,
  16262. toBase64: toBase64,
  16263. toAdjustedBlob: toAdjustedBlob,
  16264. toAdjustedDataURL: toAdjustedDataURL,
  16265. toAdjustedBase64: toAdjustedBase64,
  16266. toCanvas: toCanvas
  16267. };
  16268. }
  16269. function fromBlob(blob) {
  16270. return blobToDataUri(blob).then(function (uri) {
  16271. return create$6(blobToCanvas(blob), blob, uri);
  16272. });
  16273. }
  16274. function fromCanvas(canvas, type) {
  16275. return canvasToBlob(canvas, type).then(function (blob) {
  16276. return create$6(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  16277. });
  16278. }
  16279. var blobToImageResult = function (blob) {
  16280. return fromBlob(blob);
  16281. };
  16282. function clamp(value, min, max) {
  16283. var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  16284. if (parsedValue > max) {
  16285. parsedValue = max;
  16286. } else if (parsedValue < min) {
  16287. parsedValue = min;
  16288. }
  16289. return parsedValue;
  16290. }
  16291. function identity$1() {
  16292. return [
  16293. 1,
  16294. 0,
  16295. 0,
  16296. 0,
  16297. 0,
  16298. 0,
  16299. 1,
  16300. 0,
  16301. 0,
  16302. 0,
  16303. 0,
  16304. 0,
  16305. 1,
  16306. 0,
  16307. 0,
  16308. 0,
  16309. 0,
  16310. 0,
  16311. 1,
  16312. 0,
  16313. 0,
  16314. 0,
  16315. 0,
  16316. 0,
  16317. 1
  16318. ];
  16319. }
  16320. var DELTA_INDEX = [
  16321. 0,
  16322. 0.01,
  16323. 0.02,
  16324. 0.04,
  16325. 0.05,
  16326. 0.06,
  16327. 0.07,
  16328. 0.08,
  16329. 0.1,
  16330. 0.11,
  16331. 0.12,
  16332. 0.14,
  16333. 0.15,
  16334. 0.16,
  16335. 0.17,
  16336. 0.18,
  16337. 0.2,
  16338. 0.21,
  16339. 0.22,
  16340. 0.24,
  16341. 0.25,
  16342. 0.27,
  16343. 0.28,
  16344. 0.3,
  16345. 0.32,
  16346. 0.34,
  16347. 0.36,
  16348. 0.38,
  16349. 0.4,
  16350. 0.42,
  16351. 0.44,
  16352. 0.46,
  16353. 0.48,
  16354. 0.5,
  16355. 0.53,
  16356. 0.56,
  16357. 0.59,
  16358. 0.62,
  16359. 0.65,
  16360. 0.68,
  16361. 0.71,
  16362. 0.74,
  16363. 0.77,
  16364. 0.8,
  16365. 0.83,
  16366. 0.86,
  16367. 0.89,
  16368. 0.92,
  16369. 0.95,
  16370. 0.98,
  16371. 1,
  16372. 1.06,
  16373. 1.12,
  16374. 1.18,
  16375. 1.24,
  16376. 1.3,
  16377. 1.36,
  16378. 1.42,
  16379. 1.48,
  16380. 1.54,
  16381. 1.6,
  16382. 1.66,
  16383. 1.72,
  16384. 1.78,
  16385. 1.84,
  16386. 1.9,
  16387. 1.96,
  16388. 2,
  16389. 2.12,
  16390. 2.25,
  16391. 2.37,
  16392. 2.5,
  16393. 2.62,
  16394. 2.75,
  16395. 2.87,
  16396. 3,
  16397. 3.2,
  16398. 3.4,
  16399. 3.6,
  16400. 3.8,
  16401. 4,
  16402. 4.3,
  16403. 4.7,
  16404. 4.9,
  16405. 5,
  16406. 5.5,
  16407. 6,
  16408. 6.5,
  16409. 6.8,
  16410. 7,
  16411. 7.3,
  16412. 7.5,
  16413. 7.8,
  16414. 8,
  16415. 8.4,
  16416. 8.7,
  16417. 9,
  16418. 9.4,
  16419. 9.6,
  16420. 9.8,
  16421. 10
  16422. ];
  16423. function multiply(matrix1, matrix2) {
  16424. var col = [];
  16425. var out = new Array(25);
  16426. var val;
  16427. for (var i = 0; i < 5; i++) {
  16428. for (var j = 0; j < 5; j++) {
  16429. col[j] = matrix2[j + i * 5];
  16430. }
  16431. for (var j = 0; j < 5; j++) {
  16432. val = 0;
  16433. for (var k = 0; k < 5; k++) {
  16434. val += matrix1[j + k * 5] * col[k];
  16435. }
  16436. out[j + i * 5] = val;
  16437. }
  16438. }
  16439. return out;
  16440. }
  16441. function adjustContrast(matrix, value) {
  16442. var x;
  16443. value = clamp(value, -1, 1);
  16444. value *= 100;
  16445. if (value < 0) {
  16446. x = 127 + value / 100 * 127;
  16447. } else {
  16448. x = value % 1;
  16449. if (x === 0) {
  16450. x = DELTA_INDEX[value];
  16451. } else {
  16452. x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  16453. }
  16454. x = x * 127 + 127;
  16455. }
  16456. return multiply(matrix, [
  16457. x / 127,
  16458. 0,
  16459. 0,
  16460. 0,
  16461. 0.5 * (127 - x),
  16462. 0,
  16463. x / 127,
  16464. 0,
  16465. 0,
  16466. 0.5 * (127 - x),
  16467. 0,
  16468. 0,
  16469. x / 127,
  16470. 0,
  16471. 0.5 * (127 - x),
  16472. 0,
  16473. 0,
  16474. 0,
  16475. 1,
  16476. 0,
  16477. 0,
  16478. 0,
  16479. 0,
  16480. 0,
  16481. 1
  16482. ]);
  16483. }
  16484. function adjustBrightness(matrix, value) {
  16485. value = clamp(255 * value, -255, 255);
  16486. return multiply(matrix, [
  16487. 1,
  16488. 0,
  16489. 0,
  16490. 0,
  16491. value,
  16492. 0,
  16493. 1,
  16494. 0,
  16495. 0,
  16496. value,
  16497. 0,
  16498. 0,
  16499. 1,
  16500. 0,
  16501. value,
  16502. 0,
  16503. 0,
  16504. 0,
  16505. 1,
  16506. 0,
  16507. 0,
  16508. 0,
  16509. 0,
  16510. 0,
  16511. 1
  16512. ]);
  16513. }
  16514. function adjustColors(matrix, adjustR, adjustG, adjustB) {
  16515. adjustR = clamp(adjustR, 0, 2);
  16516. adjustG = clamp(adjustG, 0, 2);
  16517. adjustB = clamp(adjustB, 0, 2);
  16518. return multiply(matrix, [
  16519. adjustR,
  16520. 0,
  16521. 0,
  16522. 0,
  16523. 0,
  16524. 0,
  16525. adjustG,
  16526. 0,
  16527. 0,
  16528. 0,
  16529. 0,
  16530. 0,
  16531. adjustB,
  16532. 0,
  16533. 0,
  16534. 0,
  16535. 0,
  16536. 0,
  16537. 1,
  16538. 0,
  16539. 0,
  16540. 0,
  16541. 0,
  16542. 0,
  16543. 1
  16544. ]);
  16545. }
  16546. function colorFilter(ir, matrix) {
  16547. return ir.toCanvas().then(function (canvas) {
  16548. return applyColorFilter(canvas, ir.getType(), matrix);
  16549. });
  16550. }
  16551. function applyColorFilter(canvas, type, matrix) {
  16552. var context = get2dContext(canvas);
  16553. function applyMatrix(pixelsData, m) {
  16554. var r, g, b, a;
  16555. 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];
  16556. for (var i = 0; i < data.length; i += 4) {
  16557. r = data[i];
  16558. g = data[i + 1];
  16559. b = data[i + 2];
  16560. a = data[i + 3];
  16561. data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  16562. data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  16563. data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  16564. data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  16565. }
  16566. return pixelsData;
  16567. }
  16568. var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  16569. context.putImageData(pixels, 0, 0);
  16570. return fromCanvas(canvas, type);
  16571. }
  16572. function convoluteFilter(ir, matrix) {
  16573. return ir.toCanvas().then(function (canvas) {
  16574. return applyConvoluteFilter(canvas, ir.getType(), matrix);
  16575. });
  16576. }
  16577. function applyConvoluteFilter(canvas, type, matrix) {
  16578. var context = get2dContext(canvas);
  16579. function applyMatrix(pIn, pOut, aMatrix) {
  16580. function clamp(value, min, max) {
  16581. if (value > max) {
  16582. value = max;
  16583. } else if (value < min) {
  16584. value = min;
  16585. }
  16586. return value;
  16587. }
  16588. var side = Math.round(Math.sqrt(aMatrix.length));
  16589. var halfSide = Math.floor(side / 2);
  16590. var rgba = pIn.data;
  16591. var drgba = pOut.data;
  16592. var w = pIn.width;
  16593. var h = pIn.height;
  16594. for (var y = 0; y < h; y++) {
  16595. for (var x = 0; x < w; x++) {
  16596. var r = 0;
  16597. var g = 0;
  16598. var b = 0;
  16599. for (var cy = 0; cy < side; cy++) {
  16600. for (var cx = 0; cx < side; cx++) {
  16601. var scx = clamp(x + cx - halfSide, 0, w - 1);
  16602. var scy = clamp(y + cy - halfSide, 0, h - 1);
  16603. var innerOffset = (scy * w + scx) * 4;
  16604. var wt = aMatrix[cy * side + cx];
  16605. r += rgba[innerOffset] * wt;
  16606. g += rgba[innerOffset + 1] * wt;
  16607. b += rgba[innerOffset + 2] * wt;
  16608. }
  16609. }
  16610. var offset = (y * w + x) * 4;
  16611. drgba[offset] = clamp(r, 0, 255);
  16612. drgba[offset + 1] = clamp(g, 0, 255);
  16613. drgba[offset + 2] = clamp(b, 0, 255);
  16614. }
  16615. }
  16616. return pOut;
  16617. }
  16618. var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  16619. var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  16620. pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  16621. context.putImageData(pixelsOut, 0, 0);
  16622. return fromCanvas(canvas, type);
  16623. }
  16624. function functionColorFilter(colorFn) {
  16625. var filterImpl = function (canvas, type, value) {
  16626. var context = get2dContext(canvas);
  16627. var lookup = new Array(256);
  16628. function applyLookup(pixelsData, lookupData) {
  16629. var data = pixelsData.data;
  16630. for (var i = 0; i < data.length; i += 4) {
  16631. data[i] = lookupData[data[i]];
  16632. data[i + 1] = lookupData[data[i + 1]];
  16633. data[i + 2] = lookupData[data[i + 2]];
  16634. }
  16635. return pixelsData;
  16636. }
  16637. for (var i = 0; i < lookup.length; i++) {
  16638. lookup[i] = colorFn(i, value);
  16639. }
  16640. var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  16641. context.putImageData(pixels, 0, 0);
  16642. return fromCanvas(canvas, type);
  16643. };
  16644. return function (ir, value) {
  16645. return ir.toCanvas().then(function (canvas) {
  16646. return filterImpl(canvas, ir.getType(), value);
  16647. });
  16648. };
  16649. }
  16650. function complexAdjustableColorFilter(matrixAdjustFn) {
  16651. return function (ir, adjust) {
  16652. return colorFilter(ir, matrixAdjustFn(identity$1(), adjust));
  16653. };
  16654. }
  16655. function basicColorFilter(matrix) {
  16656. return function (ir) {
  16657. return colorFilter(ir, matrix);
  16658. };
  16659. }
  16660. function basicConvolutionFilter(kernel) {
  16661. return function (ir) {
  16662. return convoluteFilter(ir, kernel);
  16663. };
  16664. }
  16665. var invert = basicColorFilter([
  16666. -1,
  16667. 0,
  16668. 0,
  16669. 0,
  16670. 255,
  16671. 0,
  16672. -1,
  16673. 0,
  16674. 0,
  16675. 255,
  16676. 0,
  16677. 0,
  16678. -1,
  16679. 0,
  16680. 255,
  16681. 0,
  16682. 0,
  16683. 0,
  16684. 1,
  16685. 0,
  16686. 0,
  16687. 0,
  16688. 0,
  16689. 0,
  16690. 1
  16691. ]);
  16692. var brightness = complexAdjustableColorFilter(adjustBrightness);
  16693. var contrast = complexAdjustableColorFilter(adjustContrast);
  16694. var colorize = function (ir, adjustR, adjustG, adjustB) {
  16695. return colorFilter(ir, adjustColors(identity$1(), adjustR, adjustG, adjustB));
  16696. };
  16697. var sharpen = basicConvolutionFilter([
  16698. 0,
  16699. -1,
  16700. 0,
  16701. -1,
  16702. 5,
  16703. -1,
  16704. 0,
  16705. -1,
  16706. 0
  16707. ]);
  16708. var gamma = functionColorFilter(function (color, value) {
  16709. return Math.pow(color / 255, 1 - value) * 255;
  16710. });
  16711. function scale(image, dW, dH) {
  16712. var sW = getWidth(image);
  16713. var sH = getHeight(image);
  16714. var wRatio = dW / sW;
  16715. var hRatio = dH / sH;
  16716. var scaleCapped = false;
  16717. if (wRatio < 0.5 || wRatio > 2) {
  16718. wRatio = wRatio < 0.5 ? 0.5 : 2;
  16719. scaleCapped = true;
  16720. }
  16721. if (hRatio < 0.5 || hRatio > 2) {
  16722. hRatio = hRatio < 0.5 ? 0.5 : 2;
  16723. scaleCapped = true;
  16724. }
  16725. var scaled = _scale(image, wRatio, hRatio);
  16726. return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  16727. return scale(tCanvas, dW, dH);
  16728. });
  16729. }
  16730. function _scale(image, wRatio, hRatio) {
  16731. return new Promise$1(function (resolve) {
  16732. var sW = getWidth(image);
  16733. var sH = getHeight(image);
  16734. var dW = Math.floor(sW * wRatio);
  16735. var dH = Math.floor(sH * hRatio);
  16736. var canvas = create$5(dW, dH);
  16737. var context = get2dContext(canvas);
  16738. context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  16739. resolve(canvas);
  16740. });
  16741. }
  16742. function rotate(ir, angle) {
  16743. return ir.toCanvas().then(function (canvas) {
  16744. return applyRotate(canvas, ir.getType(), angle);
  16745. });
  16746. }
  16747. function applyRotate(image, type, angle) {
  16748. var canvas = create$5(image.width, image.height);
  16749. var context = get2dContext(canvas);
  16750. var translateX = 0;
  16751. var translateY = 0;
  16752. angle = angle < 0 ? 360 + angle : angle;
  16753. if (angle === 90 || angle === 270) {
  16754. resize(canvas, canvas.height, canvas.width);
  16755. }
  16756. if (angle === 90 || angle === 180) {
  16757. translateX = canvas.width;
  16758. }
  16759. if (angle === 270 || angle === 180) {
  16760. translateY = canvas.height;
  16761. }
  16762. context.translate(translateX, translateY);
  16763. context.rotate(angle * Math.PI / 180);
  16764. context.drawImage(image, 0, 0);
  16765. return fromCanvas(canvas, type);
  16766. }
  16767. function flip(ir, axis) {
  16768. return ir.toCanvas().then(function (canvas) {
  16769. return applyFlip(canvas, ir.getType(), axis);
  16770. });
  16771. }
  16772. function applyFlip(image, type, axis) {
  16773. var canvas = create$5(image.width, image.height);
  16774. var context = get2dContext(canvas);
  16775. if (axis === 'v') {
  16776. context.scale(1, -1);
  16777. context.drawImage(image, 0, -canvas.height);
  16778. } else {
  16779. context.scale(-1, 1);
  16780. context.drawImage(image, -canvas.width, 0);
  16781. }
  16782. return fromCanvas(canvas, type);
  16783. }
  16784. function crop(ir, x, y, w, h) {
  16785. return ir.toCanvas().then(function (canvas) {
  16786. return applyCrop(canvas, ir.getType(), x, y, w, h);
  16787. });
  16788. }
  16789. function applyCrop(image, type, x, y, w, h) {
  16790. var canvas = create$5(w, h);
  16791. var context = get2dContext(canvas);
  16792. context.drawImage(image, -x, -y);
  16793. return fromCanvas(canvas, type);
  16794. }
  16795. function resize$1(ir, w, h) {
  16796. return ir.toCanvas().then(function (canvas) {
  16797. return scale(canvas, w, h).then(function (newCanvas) {
  16798. return fromCanvas(newCanvas, ir.getType());
  16799. });
  16800. });
  16801. }
  16802. var invert$1 = function (ir) {
  16803. return invert(ir);
  16804. };
  16805. var sharpen$1 = function (ir) {
  16806. return sharpen(ir);
  16807. };
  16808. var gamma$1 = function (ir, value) {
  16809. return gamma(ir, value);
  16810. };
  16811. var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  16812. return colorize(ir, adjustR, adjustG, adjustB);
  16813. };
  16814. var brightness$1 = function (ir, adjust) {
  16815. return brightness(ir, adjust);
  16816. };
  16817. var contrast$1 = function (ir, adjust) {
  16818. return contrast(ir, adjust);
  16819. };
  16820. var flip$1 = function (ir, axis) {
  16821. return flip(ir, axis);
  16822. };
  16823. var crop$1 = function (ir, x, y, w, h) {
  16824. return crop(ir, x, y, w, h);
  16825. };
  16826. var resize$2 = function (ir, w, h) {
  16827. return resize$1(ir, w, h);
  16828. };
  16829. var rotate$1 = function (ir, angle) {
  16830. return rotate(ir, angle);
  16831. };
  16832. var renderIcon$1 = function (iconHtml, behaviours) {
  16833. return __assign({
  16834. dom: {
  16835. tag: 'span',
  16836. innerHtml: iconHtml,
  16837. classes: [
  16838. 'tox-icon',
  16839. 'tox-tbtn__icon-wrap'
  16840. ]
  16841. }
  16842. }, behaviours);
  16843. };
  16844. var renderIconFromPack = function (iconName, iconsProvider) {
  16845. return renderIcon$1(get$c(iconName, iconsProvider), {});
  16846. };
  16847. var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  16848. return renderIcon$1(get$c(iconName, iconsProvider), { behaviours: derive$1([Replacing.config({})]) });
  16849. };
  16850. var renderLabel$1 = function (text, prefix, providersBackstage) {
  16851. return {
  16852. dom: {
  16853. tag: 'span',
  16854. innerHtml: providersBackstage.translate(text),
  16855. classes: [prefix + '__select-label']
  16856. },
  16857. behaviours: derive$1([Replacing.config({})])
  16858. };
  16859. };
  16860. var internalToolbarButtonExecute = generate$1('toolbar.button.execute');
  16861. var onToolbarButtonExecute = function (info) {
  16862. return runOnExecute(function (comp, simulatedEvent) {
  16863. runWithApi(info, comp)(function (itemApi) {
  16864. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  16865. info.onAction(itemApi);
  16866. });
  16867. });
  16868. };
  16869. var toolbarButtonEventOrder = {
  16870. 'alloy.execute': [
  16871. 'disabling',
  16872. 'alloy.base.behaviour',
  16873. 'toggling',
  16874. 'toolbar-button-events'
  16875. ]
  16876. };
  16877. var updateMenuText = generate$1('update-menu-text');
  16878. var updateMenuIcon = generate$1('update-menu-icon');
  16879. var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  16880. var editorOffCell = Cell(noop);
  16881. var optMemDisplayText = spec.text.map(function (text) {
  16882. return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  16883. });
  16884. var optMemDisplayIcon = spec.icon.map(function (iconName) {
  16885. return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  16886. });
  16887. var onLeftOrRightInMenu = function (comp, se) {
  16888. var dropdown = Representing.getValue(comp);
  16889. Focusing.focus(dropdown);
  16890. emitWith(dropdown, 'keydown', { raw: se.event().raw() });
  16891. Dropdown.close(dropdown);
  16892. return Option.some(true);
  16893. };
  16894. var role = spec.role.fold(function () {
  16895. return {};
  16896. }, function (role) {
  16897. return { role: role };
  16898. });
  16899. var tooltipAttributes = spec.tooltip.fold(function () {
  16900. return {};
  16901. }, function (tooltip) {
  16902. var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  16903. return {
  16904. 'title': translatedTooltip,
  16905. 'aria-label': translatedTooltip
  16906. };
  16907. });
  16908. var memDropdown = record(Dropdown.sketch(__assign(__assign({}, role), {
  16909. dom: {
  16910. tag: 'button',
  16911. classes: [
  16912. prefix,
  16913. prefix + '--select'
  16914. ].concat(map(spec.classes, function (c) {
  16915. return prefix + '--' + c;
  16916. })),
  16917. attributes: __assign({}, tooltipAttributes)
  16918. },
  16919. components: componentRenderPipeline([
  16920. optMemDisplayIcon.map(function (mem) {
  16921. return mem.asSpec();
  16922. }),
  16923. optMemDisplayText.map(function (mem) {
  16924. return mem.asSpec();
  16925. }),
  16926. Option.some({
  16927. dom: {
  16928. tag: 'div',
  16929. classes: [prefix + '__select-chevron'],
  16930. innerHtml: get$c('chevron-down', sharedBackstage.providers.icons)
  16931. }
  16932. })
  16933. ]),
  16934. matchWidth: true,
  16935. useMinWidth: true,
  16936. dropdownBehaviours: derive$1(__spreadArrays(spec.dropdownBehaviours, [
  16937. DisablingConfigs.button(spec.disabled),
  16938. Unselecting.config({}),
  16939. Replacing.config({}),
  16940. config('dropdown-events', [
  16941. onControlAttached(spec, editorOffCell),
  16942. onControlDetached(spec, editorOffCell)
  16943. ]),
  16944. config('menubutton-update-display-text', [
  16945. run(updateMenuText, function (comp, se) {
  16946. optMemDisplayText.bind(function (mem) {
  16947. return mem.getOpt(comp);
  16948. }).each(function (displayText) {
  16949. Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event().text()))]);
  16950. });
  16951. }),
  16952. run(updateMenuIcon, function (comp, se) {
  16953. optMemDisplayIcon.bind(function (mem) {
  16954. return mem.getOpt(comp);
  16955. }).each(function (displayIcon) {
  16956. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event().icon(), sharedBackstage.providers.icons)]);
  16957. });
  16958. })
  16959. ])
  16960. ])),
  16961. eventOrder: deepMerge(toolbarButtonEventOrder, {
  16962. mousedown: [
  16963. 'focusing',
  16964. 'alloy.base.behaviour',
  16965. 'item-type-events',
  16966. 'normal-dropdown-events'
  16967. ]
  16968. }),
  16969. sandboxBehaviours: derive$1([Keying.config({
  16970. mode: 'special',
  16971. onLeft: onLeftOrRightInMenu,
  16972. onRight: onLeftOrRightInMenu
  16973. })]),
  16974. lazySink: sharedBackstage.getSink,
  16975. toggleClass: prefix + '--active',
  16976. parts: { menu: part(false, spec.columns, spec.presets) },
  16977. fetch: function () {
  16978. return Future.nu(spec.fetch);
  16979. }
  16980. })));
  16981. return memDropdown.asSpec();
  16982. };
  16983. var isMenuItemReference = function (item) {
  16984. return isString(item);
  16985. };
  16986. var isSeparator = function (item) {
  16987. return item.type === 'separator';
  16988. };
  16989. var isExpandingMenuItem = function (item) {
  16990. return has(item, 'getSubmenuItems');
  16991. };
  16992. var separator$1 = { type: 'separator' };
  16993. var unwrapReferences = function (items, menuItems) {
  16994. var realItems = foldl(items, function (acc, item) {
  16995. if (isMenuItemReference(item)) {
  16996. if (item === '') {
  16997. return acc;
  16998. } else if (item === '|') {
  16999. return acc.length > 0 && !isSeparator(acc[acc.length - 1]) ? acc.concat([separator$1]) : acc;
  17000. } else if (has(menuItems, item.toLowerCase())) {
  17001. return acc.concat([menuItems[item.toLowerCase()]]);
  17002. } else {
  17003. return acc;
  17004. }
  17005. } else {
  17006. return acc.concat([item]);
  17007. }
  17008. }, []);
  17009. if (realItems.length > 0 && isSeparator(realItems[realItems.length - 1])) {
  17010. realItems.pop();
  17011. }
  17012. return realItems;
  17013. };
  17014. var getFromExpandingItem = function (item, menuItems) {
  17015. var submenuItems = item.getSubmenuItems();
  17016. var rest = expand(submenuItems, menuItems);
  17017. var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  17018. var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  17019. return {
  17020. item: item,
  17021. menus: newMenus,
  17022. expansions: newExpansions
  17023. };
  17024. };
  17025. var getFromItem = function (item, menuItems) {
  17026. return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  17027. item: item,
  17028. menus: {},
  17029. expansions: {}
  17030. };
  17031. };
  17032. var generateValueIfRequired = function (item) {
  17033. if (isSeparator(item)) {
  17034. return item;
  17035. } else {
  17036. var itemValue = readOptFrom$1(item, 'value').getOrThunk(function () {
  17037. return generate$1('generated-menu-item');
  17038. });
  17039. return deepMerge({ value: itemValue }, item);
  17040. }
  17041. };
  17042. var expand = function (items, menuItems) {
  17043. var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  17044. return foldr(realItems, function (acc, item) {
  17045. var itemWithValue = generateValueIfRequired(item);
  17046. var newData = getFromItem(itemWithValue, menuItems);
  17047. return {
  17048. menus: deepMerge(acc.menus, newData.menus),
  17049. items: [newData.item].concat(acc.items),
  17050. expansions: deepMerge(acc.expansions, newData.expansions)
  17051. };
  17052. }, {
  17053. menus: {},
  17054. expansions: {},
  17055. items: []
  17056. });
  17057. };
  17058. var build$2 = function (items, itemResponse, backstage, isHorizontalMenu) {
  17059. var primary = generate$1('primary-menu');
  17060. var data = expand(items, backstage.shared.providers.menuItems());
  17061. if (data.items.length === 0) {
  17062. return Option.none();
  17063. }
  17064. var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  17065. var submenus = map$1(data.menus, function (menuItems, menuName) {
  17066. return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  17067. });
  17068. var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  17069. return Option.from(tieredMenu.tieredData(primary, menus, data.expansions));
  17070. };
  17071. var getMenuButtonApi = function (component) {
  17072. return {
  17073. isDisabled: function () {
  17074. return Disabling.isDisabled(component);
  17075. },
  17076. setDisabled: function (state) {
  17077. return Disabling.set(component, state);
  17078. },
  17079. setActive: function (state) {
  17080. var elm = component.element();
  17081. if (state) {
  17082. add$2(elm, 'tox-tbtn--enabled');
  17083. set$1(elm, 'aria-pressed', true);
  17084. } else {
  17085. remove$4(elm, 'tox-tbtn--enabled');
  17086. remove$1(elm, 'aria-pressed');
  17087. }
  17088. },
  17089. isActive: function () {
  17090. return has$2(component.element(), 'tox-tbtn--enabled');
  17091. }
  17092. };
  17093. };
  17094. var renderMenuButton = function (spec, prefix, backstage, role) {
  17095. return renderCommonDropdown({
  17096. text: spec.text,
  17097. icon: spec.icon,
  17098. tooltip: spec.tooltip,
  17099. role: role,
  17100. fetch: function (callback) {
  17101. spec.fetch(function (items) {
  17102. callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  17103. });
  17104. },
  17105. onSetup: spec.onSetup,
  17106. getApi: getMenuButtonApi,
  17107. columns: 1,
  17108. presets: 'normal',
  17109. classes: [],
  17110. dropdownBehaviours: [Tabstopping.config({})]
  17111. }, prefix, backstage.shared);
  17112. };
  17113. var getFetch$1 = function (items, getButton, backstage) {
  17114. var getMenuItemAction = function (item) {
  17115. return function (api) {
  17116. backstage.shared.getSink().each(function (sink) {
  17117. getButton().getOpt(sink).each(function (orig) {
  17118. focus$1(orig.element());
  17119. emitWith(orig, formActionEvent, {
  17120. name: item.name,
  17121. value: item.storage.get()
  17122. });
  17123. });
  17124. });
  17125. var newValue = !api.isActive();
  17126. api.setActive(newValue);
  17127. item.storage.set(newValue);
  17128. };
  17129. };
  17130. var getMenuItemSetup = function (item) {
  17131. return function (api) {
  17132. api.setActive(item.storage.get());
  17133. };
  17134. };
  17135. return function (success) {
  17136. success(map(items, function (item) {
  17137. var text = item.text.fold(function () {
  17138. return {};
  17139. }, function (text) {
  17140. return { text: text };
  17141. });
  17142. return __assign(__assign({ type: item.type }, text), {
  17143. onAction: getMenuItemAction(item),
  17144. onSetup: getMenuItemSetup(item)
  17145. });
  17146. }));
  17147. };
  17148. };
  17149. var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components) {
  17150. if (extraBehaviours === void 0) {
  17151. extraBehaviours = [];
  17152. }
  17153. var action = actionOpt.fold(function () {
  17154. return {};
  17155. }, function (action) {
  17156. return { action: action };
  17157. });
  17158. var common = __assign({
  17159. buttonBehaviours: derive$1([
  17160. DisablingConfigs.button(spec.disabled),
  17161. Tabstopping.config({}),
  17162. config('button press', [
  17163. preventDefault('click'),
  17164. preventDefault('mousedown')
  17165. ])
  17166. ].concat(extraBehaviours)),
  17167. eventOrder: {
  17168. click: [
  17169. 'button press',
  17170. 'alloy.base.behaviour'
  17171. ],
  17172. mousedown: [
  17173. 'button press',
  17174. 'alloy.base.behaviour'
  17175. ]
  17176. }
  17177. }, action);
  17178. var domFinal = deepMerge(common, { dom: dom });
  17179. return deepMerge(domFinal, { components: components });
  17180. };
  17181. var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  17182. if (extraBehaviours === void 0) {
  17183. extraBehaviours = [];
  17184. }
  17185. var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  17186. return {
  17187. 'aria-label': providersBackstage.translate(tooltip),
  17188. 'title': providersBackstage.translate(tooltip)
  17189. };
  17190. }).getOr({});
  17191. var dom = {
  17192. tag: 'button',
  17193. classes: ['tox-tbtn'],
  17194. attributes: tooltipAttributes
  17195. };
  17196. var icon = spec.icon.map(function (iconName) {
  17197. return renderIconFromPack(iconName, providersBackstage.icons);
  17198. });
  17199. var components = componentRenderPipeline([icon]);
  17200. return renderCommonSpec(spec, action, extraBehaviours, dom, components);
  17201. };
  17202. var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  17203. if (extraBehaviours === void 0) {
  17204. extraBehaviours = [];
  17205. }
  17206. var iconButtonSpec = renderIconButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours);
  17207. return Button.sketch(iconButtonSpec);
  17208. };
  17209. var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17210. if (extraBehaviours === void 0) {
  17211. extraBehaviours = [];
  17212. }
  17213. if (extraClasses === void 0) {
  17214. extraClasses = [];
  17215. }
  17216. var translatedText = providersBackstage.translate(spec.text);
  17217. var icon = spec.icon ? spec.icon.map(function (iconName) {
  17218. return renderIconFromPack(iconName, providersBackstage.icons);
  17219. }) : Option.none();
  17220. var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  17221. var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  17222. var classes = __spreadArrays(!spec.primary && !spec.borderless ? [
  17223. 'tox-button',
  17224. 'tox-button--secondary'
  17225. ] : ['tox-button'], icon.isSome() ? ['tox-button--icon'] : [], spec.borderless ? ['tox-button--naked'] : [], extraClasses);
  17226. var dom = __assign(__assign({
  17227. tag: 'button',
  17228. classes: classes
  17229. }, innerHtml), { attributes: { title: translatedText } });
  17230. return renderCommonSpec(spec, action, extraBehaviours, dom, components);
  17231. };
  17232. var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17233. if (extraBehaviours === void 0) {
  17234. extraBehaviours = [];
  17235. }
  17236. if (extraClasses === void 0) {
  17237. extraClasses = [];
  17238. }
  17239. var buttonSpec = renderButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours, extraClasses);
  17240. return Button.sketch(buttonSpec);
  17241. };
  17242. var getAction = function (name, buttonType) {
  17243. return function (comp) {
  17244. if (buttonType === 'custom') {
  17245. emitWith(comp, formActionEvent, {
  17246. name: name,
  17247. value: {}
  17248. });
  17249. } else if (buttonType === 'submit') {
  17250. emit(comp, formSubmitEvent);
  17251. } else if (buttonType === 'cancel') {
  17252. emit(comp, formCancelEvent);
  17253. } else {
  17254. domGlobals.console.error('Unknown button type: ', buttonType);
  17255. }
  17256. };
  17257. };
  17258. var isMenuFooterButtonSpec = function (spec, buttonType) {
  17259. return buttonType === 'menu';
  17260. };
  17261. var isNormalFooterButtonSpec = function (spec, buttonType) {
  17262. return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  17263. };
  17264. var renderFooterButton = function (spec, buttonType, backstage) {
  17265. if (isMenuFooterButtonSpec(spec, buttonType)) {
  17266. var getButton = function () {
  17267. return memButton_1;
  17268. };
  17269. var menuButtonSpec = spec;
  17270. var fixedSpec = __assign(__assign({}, spec), { fetch: getFetch$1(menuButtonSpec.items, getButton, backstage) });
  17271. var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Option.none()));
  17272. return memButton_1.asSpec();
  17273. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  17274. var action = getAction(spec.name, buttonType);
  17275. var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  17276. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  17277. } else {
  17278. domGlobals.console.error('Unknown footer button type: ', buttonType);
  17279. }
  17280. };
  17281. var renderDialogButton = function (spec, providersBackstage) {
  17282. var action = getAction(spec.name, 'custom');
  17283. return renderFormField(Option.none(), FormField.parts().field(__assign({ factory: Button }, renderButtonSpec(spec, Option.some(action), providersBackstage, [
  17284. RepresentingConfigs.memory(''),
  17285. ComposingConfigs.self()
  17286. ]))));
  17287. };
  17288. var schema$i = constant([
  17289. defaulted$1('field1Name', 'field1'),
  17290. defaulted$1('field2Name', 'field2'),
  17291. onStrictHandler('onLockedChange'),
  17292. markers(['lockClass']),
  17293. defaulted$1('locked', false),
  17294. SketchBehaviours.field('coupledFieldBehaviours', [
  17295. Composing,
  17296. Representing
  17297. ])
  17298. ]);
  17299. var getField = function (comp, detail, partName) {
  17300. return getPart(comp, detail, partName).bind(Composing.getCurrent);
  17301. };
  17302. var coupledPart = function (selfName, otherName) {
  17303. return required({
  17304. factory: FormField,
  17305. name: selfName,
  17306. overrides: function (detail) {
  17307. return {
  17308. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run(input(), function (me) {
  17309. getField(me, detail, otherName).each(function (other) {
  17310. getPart(me, detail, 'lock').each(function (lock) {
  17311. if (Toggling.isOn(lock)) {
  17312. detail.onLockedChange(me, other, lock);
  17313. }
  17314. });
  17315. });
  17316. })])])
  17317. };
  17318. }
  17319. });
  17320. };
  17321. var parts$5 = constant([
  17322. coupledPart('field1', 'field2'),
  17323. coupledPart('field2', 'field1'),
  17324. required({
  17325. factory: Button,
  17326. schema: [strict$1('dom')],
  17327. name: 'lock',
  17328. overrides: function (detail) {
  17329. return {
  17330. buttonBehaviours: derive$1([Toggling.config({
  17331. selected: detail.locked,
  17332. toggleClass: detail.markers.lockClass,
  17333. aria: { mode: 'pressed' }
  17334. })])
  17335. };
  17336. }
  17337. })
  17338. ]);
  17339. var factory$7 = function (detail, components, spec, externals) {
  17340. return {
  17341. uid: detail.uid,
  17342. dom: detail.dom,
  17343. components: components,
  17344. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  17345. Composing.config({ find: Option.some }),
  17346. Representing.config({
  17347. store: {
  17348. mode: 'manual',
  17349. getValue: function (comp) {
  17350. var _a;
  17351. var parts = getPartsOrDie(comp, detail, [
  17352. 'field1',
  17353. 'field2'
  17354. ]);
  17355. return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  17356. },
  17357. setValue: function (comp, value) {
  17358. var parts = getPartsOrDie(comp, detail, [
  17359. 'field1',
  17360. 'field2'
  17361. ]);
  17362. if (hasKey$1(value, detail.field1Name)) {
  17363. Representing.setValue(parts.field1(), value[detail.field1Name]);
  17364. }
  17365. if (hasKey$1(value, detail.field2Name)) {
  17366. Representing.setValue(parts.field2(), value[detail.field2Name]);
  17367. }
  17368. }
  17369. }
  17370. })
  17371. ]),
  17372. apis: {
  17373. getField1: function (component) {
  17374. return getPart(component, detail, 'field1');
  17375. },
  17376. getField2: function (component) {
  17377. return getPart(component, detail, 'field2');
  17378. },
  17379. getLock: function (component) {
  17380. return getPart(component, detail, 'lock');
  17381. }
  17382. }
  17383. };
  17384. };
  17385. var FormCoupledInputs = composite$1({
  17386. name: 'FormCoupledInputs',
  17387. configFields: schema$i(),
  17388. partFields: parts$5(),
  17389. factory: factory$7,
  17390. apis: {
  17391. getField1: function (apis, component) {
  17392. return apis.getField1(component);
  17393. },
  17394. getField2: function (apis, component) {
  17395. return apis.getField2(component);
  17396. },
  17397. getLock: function (apis, component) {
  17398. return apis.getLock(component);
  17399. }
  17400. }
  17401. });
  17402. var formatSize = function (size) {
  17403. var unitDec = {
  17404. '': 0,
  17405. 'px': 0,
  17406. 'pt': 1,
  17407. 'mm': 1,
  17408. 'pc': 2,
  17409. 'ex': 2,
  17410. 'em': 2,
  17411. 'ch': 2,
  17412. 'rem': 2,
  17413. 'cm': 3,
  17414. 'in': 4,
  17415. '%': 4
  17416. };
  17417. var maxDecimal = function (unit) {
  17418. return unit in unitDec ? unitDec[unit] : 1;
  17419. };
  17420. var numText = size.value.toFixed(maxDecimal(size.unit));
  17421. if (numText.indexOf('.') !== -1) {
  17422. numText = numText.replace(/\.?0*$/, '');
  17423. }
  17424. return numText + size.unit;
  17425. };
  17426. var parseSize = function (sizeText) {
  17427. var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  17428. var match = numPattern.exec(sizeText);
  17429. if (match !== null) {
  17430. var value = parseFloat(match[1]);
  17431. var unit = match[2];
  17432. return Result.value({
  17433. value: value,
  17434. unit: unit
  17435. });
  17436. } else {
  17437. return Result.error(sizeText);
  17438. }
  17439. };
  17440. var convertUnit = function (size, unit) {
  17441. var inInch = {
  17442. '': 96,
  17443. 'px': 96,
  17444. 'pt': 72,
  17445. 'cm': 2.54,
  17446. 'pc': 12,
  17447. 'mm': 25.4,
  17448. 'in': 1
  17449. };
  17450. var supported = function (u) {
  17451. return Object.prototype.hasOwnProperty.call(inInch, u);
  17452. };
  17453. if (size.unit === unit) {
  17454. return Option.some(size.value);
  17455. } else if (supported(size.unit) && supported(unit)) {
  17456. if (inInch[size.unit] === inInch[unit]) {
  17457. return Option.some(size.value);
  17458. } else {
  17459. return Option.some(size.value / inInch[size.unit] * inInch[unit]);
  17460. }
  17461. } else {
  17462. return Option.none();
  17463. }
  17464. };
  17465. var noSizeConversion = function (input) {
  17466. return Option.none();
  17467. };
  17468. var ratioSizeConversion = function (scale, unit) {
  17469. return function (size) {
  17470. return convertUnit(size, unit).map(function (value) {
  17471. return {
  17472. value: value * scale,
  17473. unit: unit
  17474. };
  17475. });
  17476. };
  17477. };
  17478. var makeRatioConverter = function (currentFieldText, otherFieldText) {
  17479. var cValue = parseSize(currentFieldText).toOption();
  17480. var oValue = parseSize(otherFieldText).toOption();
  17481. return lift2(cValue, oValue, function (cSize, oSize) {
  17482. return convertUnit(cSize, oSize.unit).map(function (val) {
  17483. return oSize.value / val;
  17484. }).map(function (r) {
  17485. return ratioSizeConversion(r, oSize.unit);
  17486. }).getOr(noSizeConversion);
  17487. }).getOr(noSizeConversion);
  17488. };
  17489. var renderSizeInput = function (spec, providersBackstage) {
  17490. var converter = noSizeConversion;
  17491. var ratioEvent = generate$1('ratio-event');
  17492. var pLock = FormCoupledInputs.parts().lock({
  17493. dom: {
  17494. tag: 'button',
  17495. classes: [
  17496. 'tox-lock',
  17497. 'tox-button',
  17498. 'tox-button--naked',
  17499. 'tox-button--icon'
  17500. ],
  17501. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  17502. },
  17503. components: [
  17504. {
  17505. dom: {
  17506. tag: 'span',
  17507. classes: [
  17508. 'tox-icon',
  17509. 'tox-lock-icon__lock'
  17510. ],
  17511. innerHtml: get$c('lock', providersBackstage.icons)
  17512. }
  17513. },
  17514. {
  17515. dom: {
  17516. tag: 'span',
  17517. classes: [
  17518. 'tox-icon',
  17519. 'tox-lock-icon__unlock'
  17520. ],
  17521. innerHtml: get$c('unlock', providersBackstage.icons)
  17522. }
  17523. }
  17524. ],
  17525. buttonBehaviours: derive$1([
  17526. DisablingConfigs.button(spec.disabled),
  17527. Tabstopping.config({})
  17528. ])
  17529. });
  17530. var formGroup = function (components) {
  17531. return {
  17532. dom: {
  17533. tag: 'div',
  17534. classes: ['tox-form__group']
  17535. },
  17536. components: components
  17537. };
  17538. };
  17539. var getFieldPart = function (isField1) {
  17540. return FormField.parts().field({
  17541. factory: Input,
  17542. inputClasses: ['tox-textfield'],
  17543. inputBehaviours: derive$1([
  17544. Disabling.config({ disabled: spec.disabled }),
  17545. Tabstopping.config({}),
  17546. config('size-input-events', [
  17547. run(focusin(), function (component, simulatedEvent) {
  17548. emitWith(component, ratioEvent, { isField1: isField1 });
  17549. }),
  17550. run(change(), function (component, simulatedEvent) {
  17551. emitWith(component, formChangeEvent, { name: spec.name });
  17552. })
  17553. ])
  17554. ]),
  17555. selectOnFocus: false
  17556. });
  17557. };
  17558. var getLabel = function (label) {
  17559. return {
  17560. dom: {
  17561. tag: 'label',
  17562. classes: ['tox-label'],
  17563. innerHtml: providersBackstage.translate(label)
  17564. }
  17565. };
  17566. };
  17567. var widthField = FormCoupledInputs.parts().field1(formGroup([
  17568. FormField.parts().label(getLabel('Width')),
  17569. getFieldPart(true)
  17570. ]));
  17571. var heightField = FormCoupledInputs.parts().field2(formGroup([
  17572. FormField.parts().label(getLabel('Height')),
  17573. getFieldPart(false)
  17574. ]));
  17575. return FormCoupledInputs.sketch({
  17576. dom: {
  17577. tag: 'div',
  17578. classes: ['tox-form__group']
  17579. },
  17580. components: [{
  17581. dom: {
  17582. tag: 'div',
  17583. classes: ['tox-form__controls-h-stack']
  17584. },
  17585. components: [
  17586. widthField,
  17587. heightField,
  17588. formGroup([
  17589. getLabel('&nbsp;'),
  17590. pLock
  17591. ])
  17592. ]
  17593. }],
  17594. field1Name: 'width',
  17595. field2Name: 'height',
  17596. locked: true,
  17597. markers: { lockClass: 'tox-locked' },
  17598. onLockedChange: function (current, other, lock) {
  17599. parseSize(Representing.getValue(current)).each(function (size) {
  17600. converter(size).each(function (newSize) {
  17601. Representing.setValue(other, formatSize(newSize));
  17602. });
  17603. });
  17604. },
  17605. coupledFieldBehaviours: derive$1([
  17606. Disabling.config({
  17607. disabled: spec.disabled,
  17608. onDisabled: function (comp) {
  17609. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  17610. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  17611. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  17612. },
  17613. onEnabled: function (comp) {
  17614. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  17615. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  17616. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  17617. }
  17618. }),
  17619. config('size-input-events2', [run(ratioEvent, function (component, simulatedEvent) {
  17620. var isField1 = simulatedEvent.event().isField1();
  17621. var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  17622. var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  17623. var value1 = optCurrent.map(Representing.getValue).getOr('');
  17624. var value2 = optOther.map(Representing.getValue).getOr('');
  17625. converter = makeRatioConverter(value1, value2);
  17626. })])
  17627. ])
  17628. });
  17629. };
  17630. var undo = constant(generate$1('undo'));
  17631. var redo = constant(generate$1('redo'));
  17632. var zoom = constant(generate$1('zoom'));
  17633. var back = constant(generate$1('back'));
  17634. var apply = constant(generate$1('apply'));
  17635. var swap = constant(generate$1('swap'));
  17636. var transform = constant(generate$1('transform'));
  17637. var tempTransform = constant(generate$1('temp-transform'));
  17638. var transformApply = constant(generate$1('transform-apply'));
  17639. var internal = {
  17640. undo: undo,
  17641. redo: redo,
  17642. zoom: zoom,
  17643. back: back,
  17644. apply: apply,
  17645. swap: swap,
  17646. transform: transform,
  17647. tempTransform: tempTransform,
  17648. transformApply: transformApply
  17649. };
  17650. var saveState = constant('save-state');
  17651. var disable$1 = constant('disable');
  17652. var enable$1 = constant('enable');
  17653. var external$2 = {
  17654. formActionEvent: formActionEvent,
  17655. saveState: saveState,
  17656. disable: disable$1,
  17657. enable: enable$1
  17658. };
  17659. var renderEditPanel = function (imagePanel, providersBackstage) {
  17660. var createButton = function (text, action, disabled, primary) {
  17661. return record(renderButton({
  17662. name: text,
  17663. text: text,
  17664. disabled: disabled,
  17665. primary: primary,
  17666. icon: Option.none(),
  17667. borderless: false
  17668. }, action, providersBackstage));
  17669. };
  17670. var createIconButton = function (icon, tooltip, action, disabled) {
  17671. return record(renderIconButton({
  17672. name: icon,
  17673. icon: Option.some(icon),
  17674. tooltip: Option.some(tooltip),
  17675. disabled: disabled,
  17676. primary: false,
  17677. borderless: false
  17678. }, action, providersBackstage));
  17679. };
  17680. var disableAllComponents = function (comps, eventcomp) {
  17681. comps.map(function (mem) {
  17682. var component = mem.get(eventcomp);
  17683. if (component.hasConfigured(Disabling)) {
  17684. Disabling.disable(component);
  17685. }
  17686. });
  17687. };
  17688. var enableAllComponents = function (comps, eventcomp) {
  17689. comps.map(function (mem) {
  17690. var component = mem.get(eventcomp);
  17691. if (component.hasConfigured(Disabling)) {
  17692. Disabling.enable(component);
  17693. }
  17694. });
  17695. };
  17696. var panelDom = {
  17697. tag: 'div',
  17698. classes: [
  17699. 'tox-image-tools__toolbar',
  17700. 'tox-image-tools-edit-panel'
  17701. ]
  17702. };
  17703. var noop$1 = noop;
  17704. var emit$1 = function (comp, event, data) {
  17705. emitWith(comp, event, data);
  17706. };
  17707. var emitDisable = function (component) {
  17708. return emit(component, external$2.disable());
  17709. };
  17710. var emitEnable = function (component) {
  17711. return emit(component, external$2.enable());
  17712. };
  17713. var emitTransform = function (comp, transform) {
  17714. emitDisable(comp);
  17715. emit$1(comp, internal.transform(), { transform: transform });
  17716. emitEnable(comp);
  17717. };
  17718. var emitTempTransform = function (comp, transform) {
  17719. emitDisable(comp);
  17720. emit$1(comp, internal.tempTransform(), { transform: transform });
  17721. emitEnable(comp);
  17722. };
  17723. var getBackSwap = function (anyInSystem) {
  17724. return function () {
  17725. memContainer.getOpt(anyInSystem).each(function (container) {
  17726. Replacing.set(container, [ButtonPanel]);
  17727. });
  17728. };
  17729. };
  17730. var emitTransformApply = function (comp, transform) {
  17731. emitDisable(comp);
  17732. emit$1(comp, internal.transformApply(), {
  17733. transform: transform,
  17734. swap: getBackSwap(comp)
  17735. });
  17736. emitEnable(comp);
  17737. };
  17738. var createBackButton = function () {
  17739. return createButton('Back', function (button) {
  17740. return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  17741. }, false, false);
  17742. };
  17743. var createSpacer = function () {
  17744. return record({
  17745. dom: {
  17746. tag: 'div',
  17747. classes: ['tox-spacer']
  17748. },
  17749. behaviours: derive$1([Disabling.config({})])
  17750. });
  17751. };
  17752. var createApplyButton = function () {
  17753. return createButton('Apply', function (button) {
  17754. return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  17755. }, true, true);
  17756. };
  17757. var makeCropTransform = function () {
  17758. return function (ir) {
  17759. var rect = imagePanel.getRect();
  17760. return crop$1(ir, rect.x, rect.y, rect.w, rect.h);
  17761. };
  17762. };
  17763. var cropPanelComponents = [
  17764. createBackButton(),
  17765. createSpacer(),
  17766. createButton('Apply', function (button) {
  17767. var transform = makeCropTransform();
  17768. emitTransformApply(button, transform);
  17769. imagePanel.hideCrop();
  17770. }, false, true)
  17771. ];
  17772. var CropPanel = Container.sketch({
  17773. dom: panelDom,
  17774. components: cropPanelComponents.map(function (mem) {
  17775. return mem.asSpec();
  17776. }),
  17777. containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  17778. run(external$2.disable(), function (comp, se) {
  17779. disableAllComponents(cropPanelComponents, comp);
  17780. }),
  17781. run(external$2.enable(), function (comp, se) {
  17782. enableAllComponents(cropPanelComponents, comp);
  17783. })
  17784. ])])
  17785. });
  17786. var memSize = record(renderSizeInput({
  17787. name: 'size',
  17788. label: Option.none(),
  17789. constrain: true,
  17790. disabled: false
  17791. }, providersBackstage));
  17792. var makeResizeTransform = function (width, height) {
  17793. return function (ir) {
  17794. return resize$2(ir, width, height);
  17795. };
  17796. };
  17797. var resizePanelComponents = [
  17798. createBackButton(),
  17799. createSpacer(),
  17800. memSize,
  17801. createSpacer(),
  17802. createButton('Apply', function (button) {
  17803. memSize.getOpt(button).each(function (sizeInput) {
  17804. var value = Representing.getValue(sizeInput);
  17805. var width = parseInt(value.width, 10);
  17806. var height = parseInt(value.height, 10);
  17807. var transform = makeResizeTransform(width, height);
  17808. emitTransformApply(button, transform);
  17809. });
  17810. }, false, true)
  17811. ];
  17812. var ResizePanel = Container.sketch({
  17813. dom: panelDom,
  17814. components: resizePanelComponents.map(function (mem) {
  17815. return mem.asSpec();
  17816. }),
  17817. containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  17818. run(external$2.disable(), function (comp, se) {
  17819. disableAllComponents(resizePanelComponents, comp);
  17820. }),
  17821. run(external$2.enable(), function (comp, se) {
  17822. enableAllComponents(resizePanelComponents, comp);
  17823. })
  17824. ])])
  17825. });
  17826. var makeValueTransform = function (transform, value) {
  17827. return function (ir) {
  17828. return transform(ir, value);
  17829. };
  17830. };
  17831. var horizontalFlip = makeValueTransform(flip$1, 'h');
  17832. var verticalFlip = makeValueTransform(flip$1, 'v');
  17833. var counterclockwiseRotate = makeValueTransform(rotate$1, -90);
  17834. var clockwiseRotate = makeValueTransform(rotate$1, 90);
  17835. var flipRotateOnAction = function (comp, operation) {
  17836. emitTempTransform(comp, operation);
  17837. };
  17838. var flipRotateComponents = [
  17839. createBackButton(),
  17840. createSpacer(),
  17841. createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  17842. flipRotateOnAction(button, horizontalFlip);
  17843. }, false),
  17844. createIconButton('flip-vertically', 'Flip vertically', function (button) {
  17845. flipRotateOnAction(button, verticalFlip);
  17846. }, false),
  17847. createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  17848. flipRotateOnAction(button, counterclockwiseRotate);
  17849. }, false),
  17850. createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  17851. flipRotateOnAction(button, clockwiseRotate);
  17852. }, false),
  17853. createSpacer(),
  17854. createApplyButton()
  17855. ];
  17856. var FlipRotatePanel = Container.sketch({
  17857. dom: panelDom,
  17858. components: flipRotateComponents.map(function (mem) {
  17859. return mem.asSpec();
  17860. }),
  17861. containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  17862. run(external$2.disable(), function (comp, se) {
  17863. disableAllComponents(flipRotateComponents, comp);
  17864. }),
  17865. run(external$2.enable(), function (comp, se) {
  17866. enableAllComponents(flipRotateComponents, comp);
  17867. })
  17868. ])])
  17869. });
  17870. var makeSlider = function (label, onChoose, min, value, max) {
  17871. var labelPart = Slider.parts().label({
  17872. dom: {
  17873. tag: 'label',
  17874. classes: ['tox-label'],
  17875. innerHtml: providersBackstage.translate(label)
  17876. }
  17877. });
  17878. var spectrum = Slider.parts().spectrum({
  17879. dom: {
  17880. tag: 'div',
  17881. classes: ['tox-slider__rail'],
  17882. attributes: { role: 'presentation' }
  17883. }
  17884. });
  17885. var thumb = Slider.parts().thumb({
  17886. dom: {
  17887. tag: 'div',
  17888. classes: ['tox-slider__handle'],
  17889. attributes: { role: 'presentation' }
  17890. }
  17891. });
  17892. return record(Slider.sketch({
  17893. dom: {
  17894. tag: 'div',
  17895. classes: ['tox-slider'],
  17896. attributes: { role: 'presentation' }
  17897. },
  17898. model: {
  17899. mode: 'x',
  17900. minX: min,
  17901. maxX: max,
  17902. getInitialValue: constant({ x: constant(value) })
  17903. },
  17904. components: [
  17905. labelPart,
  17906. spectrum,
  17907. thumb
  17908. ],
  17909. sliderBehaviours: derive$1([Focusing.config({})]),
  17910. onChoose: onChoose
  17911. }));
  17912. };
  17913. var makeVariableSlider = function (label, transform, min, value, max) {
  17914. var onChoose = function (slider, thumb, value) {
  17915. var valTransform = makeValueTransform(transform, value.x() / 100);
  17916. emitTransform(slider, valTransform);
  17917. };
  17918. return makeSlider(label, onChoose, min, value, max);
  17919. };
  17920. var variableFilterPanelComponents = function (label, transform, min, value, max) {
  17921. return [
  17922. createBackButton(),
  17923. makeVariableSlider(label, transform, min, value, max),
  17924. createApplyButton()
  17925. ];
  17926. };
  17927. var createVariableFilterPanel = function (label, transform, min, value, max) {
  17928. var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  17929. return Container.sketch({
  17930. dom: panelDom,
  17931. components: filterPanelComponents.map(function (mem) {
  17932. return mem.asSpec();
  17933. }),
  17934. containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  17935. run(external$2.disable(), function (comp, se) {
  17936. disableAllComponents(filterPanelComponents, comp);
  17937. }),
  17938. run(external$2.enable(), function (comp, se) {
  17939. enableAllComponents(filterPanelComponents, comp);
  17940. })
  17941. ])])
  17942. });
  17943. };
  17944. var filterPanelComponents = [
  17945. createBackButton(),
  17946. createSpacer(),
  17947. createApplyButton()
  17948. ];
  17949. var FilterPanel = Container.sketch({
  17950. dom: panelDom,
  17951. components: filterPanelComponents.map(function (mem) {
  17952. return mem.asSpec();
  17953. })
  17954. });
  17955. var BrightnessPanel = createVariableFilterPanel('Brightness', brightness$1, -100, 0, 100);
  17956. var ContrastPanel = createVariableFilterPanel('Contrast', contrast$1, -100, 0, 100);
  17957. var GammaPanel = createVariableFilterPanel('Gamma', gamma$1, -100, 0, 100);
  17958. var makeColorTransform = function (red, green, blue) {
  17959. return function (ir) {
  17960. return colorize$1(ir, red, green, blue);
  17961. };
  17962. };
  17963. var makeColorSlider = function (label) {
  17964. var onChoose = function (slider, thumb, value) {
  17965. var redOpt = memRed.getOpt(slider);
  17966. var blueOpt = memBlue.getOpt(slider);
  17967. var greenOpt = memGreen.getOpt(slider);
  17968. redOpt.each(function (red) {
  17969. blueOpt.each(function (blue) {
  17970. greenOpt.each(function (green) {
  17971. var r = Representing.getValue(red).x() / 100;
  17972. var g = Representing.getValue(green).x() / 100;
  17973. var b = Representing.getValue(blue).x() / 100;
  17974. var transform = makeColorTransform(r, g, b);
  17975. emitTransform(slider, transform);
  17976. });
  17977. });
  17978. });
  17979. };
  17980. return makeSlider(label, onChoose, 0, 100, 200);
  17981. };
  17982. var memRed = makeColorSlider('R');
  17983. var memGreen = makeColorSlider('G');
  17984. var memBlue = makeColorSlider('B');
  17985. var colorizePanelComponents = [
  17986. createBackButton(),
  17987. memRed,
  17988. memGreen,
  17989. memBlue,
  17990. createApplyButton()
  17991. ];
  17992. var ColorizePanel = Container.sketch({
  17993. dom: panelDom,
  17994. components: colorizePanelComponents.map(function (mem) {
  17995. return mem.asSpec();
  17996. })
  17997. });
  17998. var getTransformPanelEvent = function (panel, transform, update) {
  17999. return function (button) {
  18000. var swap = function () {
  18001. memContainer.getOpt(button).each(function (container) {
  18002. Replacing.set(container, [panel]);
  18003. update(container);
  18004. });
  18005. };
  18006. emit$1(button, internal.swap(), {
  18007. transform: transform,
  18008. swap: swap
  18009. });
  18010. };
  18011. };
  18012. var cropPanelUpdate = function (_anyInSystem) {
  18013. imagePanel.showCrop();
  18014. };
  18015. var resizePanelUpdate = function (anyInSystem) {
  18016. memSize.getOpt(anyInSystem).each(function (sizeInput) {
  18017. var measurements = imagePanel.getMeasurements();
  18018. var width = measurements.width;
  18019. var height = measurements.height;
  18020. Representing.setValue(sizeInput, {
  18021. width: width,
  18022. height: height
  18023. });
  18024. });
  18025. };
  18026. var sharpenTransform = Option.some(sharpen$1);
  18027. var invertTransform = Option.some(invert$1);
  18028. var buttonPanelComponents = [
  18029. createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Option.none(), cropPanelUpdate), false),
  18030. createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Option.none(), resizePanelUpdate), false),
  18031. createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Option.none(), noop$1), false),
  18032. createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Option.none(), noop$1), false),
  18033. createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  18034. createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Option.none(), noop$1), false),
  18035. createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Option.none(), noop$1), false),
  18036. createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Option.none(), noop$1), false),
  18037. createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  18038. ];
  18039. var ButtonPanel = Container.sketch({
  18040. dom: panelDom,
  18041. components: buttonPanelComponents.map(function (mem) {
  18042. return mem.asSpec();
  18043. })
  18044. });
  18045. var container = Container.sketch({
  18046. dom: { tag: 'div' },
  18047. components: [ButtonPanel],
  18048. containerBehaviours: derive$1([Replacing.config({})])
  18049. });
  18050. var memContainer = record(container);
  18051. var getApplyButton = function (anyInSystem) {
  18052. return memContainer.getOpt(anyInSystem).map(function (container) {
  18053. var panel = container.components()[0];
  18054. return panel.components()[panel.components().length - 1];
  18055. });
  18056. };
  18057. return {
  18058. memContainer: memContainer,
  18059. getApplyButton: getApplyButton
  18060. };
  18061. };
  18062. var global$b = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');
  18063. var global$c = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  18064. var global$d = tinymce.util.Tools.resolve('tinymce.util.Observable');
  18065. var global$e = tinymce.util.Tools.resolve('tinymce.util.Tools');
  18066. var global$f = tinymce.util.Tools.resolve('tinymce.util.VK');
  18067. function getDocumentSize(doc) {
  18068. var documentElement, body, scrollWidth, clientWidth;
  18069. var offsetWidth, scrollHeight, clientHeight, offsetHeight;
  18070. var max = Math.max;
  18071. documentElement = doc.documentElement;
  18072. body = doc.body;
  18073. scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  18074. clientWidth = max(documentElement.clientWidth, body.clientWidth);
  18075. offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  18076. scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  18077. clientHeight = max(documentElement.clientHeight, body.clientHeight);
  18078. offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  18079. return {
  18080. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  18081. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  18082. };
  18083. }
  18084. function updateWithTouchData(e) {
  18085. var keys, i;
  18086. if (e.changedTouches) {
  18087. keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  18088. for (i = 0; i < keys.length; i++) {
  18089. e[keys[i]] = e.changedTouches[0][keys[i]];
  18090. }
  18091. }
  18092. }
  18093. function DragHelper (id, settings) {
  18094. var $eventOverlay;
  18095. var doc = settings.document || domGlobals.document;
  18096. var downButton;
  18097. var start, stop, drag, startX, startY;
  18098. settings = settings || {};
  18099. var handleElement = doc.getElementById(settings.handle || id);
  18100. start = function (e) {
  18101. var docSize = getDocumentSize(doc);
  18102. var handleElm, cursor;
  18103. updateWithTouchData(e);
  18104. e.preventDefault();
  18105. downButton = e.button;
  18106. handleElm = handleElement;
  18107. startX = e.screenX;
  18108. startY = e.screenY;
  18109. if (domGlobals.window.getComputedStyle) {
  18110. cursor = domGlobals.window.getComputedStyle(handleElm, null).getPropertyValue('cursor');
  18111. } else {
  18112. cursor = handleElm.runtimeStyle.cursor;
  18113. }
  18114. $eventOverlay = global$b('<div></div>').css({
  18115. position: 'absolute',
  18116. top: 0,
  18117. left: 0,
  18118. width: docSize.width,
  18119. height: docSize.height,
  18120. zIndex: 2147483647,
  18121. opacity: 0.0001,
  18122. cursor: cursor
  18123. }).appendTo(doc.body);
  18124. global$b(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop);
  18125. settings.start(e);
  18126. };
  18127. drag = function (e) {
  18128. updateWithTouchData(e);
  18129. if (e.button !== downButton) {
  18130. return stop(e);
  18131. }
  18132. e.deltaX = e.screenX - startX;
  18133. e.deltaY = e.screenY - startY;
  18134. e.preventDefault();
  18135. settings.drag(e);
  18136. };
  18137. stop = function (e) {
  18138. updateWithTouchData(e);
  18139. global$b(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop);
  18140. $eventOverlay.remove();
  18141. if (settings.stop) {
  18142. settings.stop(e);
  18143. }
  18144. };
  18145. this.destroy = function () {
  18146. global$b(handleElement).off();
  18147. };
  18148. global$b(handleElement).on('mousedown touchstart', start);
  18149. }
  18150. var count = 0;
  18151. var create$7 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  18152. var instance;
  18153. var dragHelpers;
  18154. var blockers;
  18155. var prefix = 'tox-';
  18156. var id = prefix + 'crid-' + count++;
  18157. var handles = [
  18158. {
  18159. name: 'move',
  18160. xMul: 0,
  18161. yMul: 0,
  18162. deltaX: 1,
  18163. deltaY: 1,
  18164. deltaW: 0,
  18165. deltaH: 0,
  18166. label: 'Crop Mask'
  18167. },
  18168. {
  18169. name: 'nw',
  18170. xMul: 0,
  18171. yMul: 0,
  18172. deltaX: 1,
  18173. deltaY: 1,
  18174. deltaW: -1,
  18175. deltaH: -1,
  18176. label: 'Top Left Crop Handle'
  18177. },
  18178. {
  18179. name: 'ne',
  18180. xMul: 1,
  18181. yMul: 0,
  18182. deltaX: 0,
  18183. deltaY: 1,
  18184. deltaW: 1,
  18185. deltaH: -1,
  18186. label: 'Top Right Crop Handle'
  18187. },
  18188. {
  18189. name: 'sw',
  18190. xMul: 0,
  18191. yMul: 1,
  18192. deltaX: 1,
  18193. deltaY: 0,
  18194. deltaW: -1,
  18195. deltaH: 1,
  18196. label: 'Bottom Left Crop Handle'
  18197. },
  18198. {
  18199. name: 'se',
  18200. xMul: 1,
  18201. yMul: 1,
  18202. deltaX: 0,
  18203. deltaY: 0,
  18204. deltaW: 1,
  18205. deltaH: 1,
  18206. label: 'Bottom Right Crop Handle'
  18207. }
  18208. ];
  18209. blockers = [
  18210. 'top',
  18211. 'right',
  18212. 'bottom',
  18213. 'left'
  18214. ];
  18215. var getAbsoluteRect = function (outerRect, relativeRect) {
  18216. return {
  18217. x: relativeRect.x + outerRect.x,
  18218. y: relativeRect.y + outerRect.y,
  18219. w: relativeRect.w,
  18220. h: relativeRect.h
  18221. };
  18222. };
  18223. var getRelativeRect = function (outerRect, innerRect) {
  18224. return {
  18225. x: innerRect.x - outerRect.x,
  18226. y: innerRect.y - outerRect.y,
  18227. w: innerRect.w,
  18228. h: innerRect.h
  18229. };
  18230. };
  18231. var getInnerRect = function () {
  18232. return getRelativeRect(clampRect, currentRect);
  18233. };
  18234. function moveRect(handle, startRect, deltaX, deltaY) {
  18235. var x, y, w, h, rect;
  18236. x = startRect.x;
  18237. y = startRect.y;
  18238. w = startRect.w;
  18239. h = startRect.h;
  18240. x += deltaX * handle.deltaX;
  18241. y += deltaY * handle.deltaY;
  18242. w += deltaX * handle.deltaW;
  18243. h += deltaY * handle.deltaH;
  18244. if (w < 20) {
  18245. w = 20;
  18246. }
  18247. if (h < 20) {
  18248. h = 20;
  18249. }
  18250. rect = currentRect = global$c.clamp({
  18251. x: x,
  18252. y: y,
  18253. w: w,
  18254. h: h
  18255. }, clampRect, handle.name === 'move');
  18256. rect = getRelativeRect(clampRect, rect);
  18257. instance.fire('updateRect', { rect: rect });
  18258. setInnerRect(rect);
  18259. }
  18260. function render() {
  18261. function createDragHelper(handle) {
  18262. var startRect;
  18263. return new DragHelper(id, {
  18264. document: containerElm.ownerDocument,
  18265. handle: id + '-' + handle.name,
  18266. start: function () {
  18267. startRect = currentRect;
  18268. },
  18269. drag: function (e) {
  18270. moveRect(handle, startRect, e.deltaX, e.deltaY);
  18271. }
  18272. });
  18273. }
  18274. global$b('<div id="' + id + '" class="' + prefix + 'croprect-container"' + ' role="grid" aria-dropeffect="execute">').appendTo(containerElm);
  18275. global$e.each(blockers, function (blocker) {
  18276. global$b('#' + id, containerElm).append('<div id="' + id + '-' + blocker + '"class="' + prefix + 'croprect-block" style="display: none" data-mce-bogus="all">');
  18277. });
  18278. global$e.each(handles, function (handle) {
  18279. 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 + '">');
  18280. });
  18281. dragHelpers = global$e.map(handles, createDragHelper);
  18282. repaint(currentRect);
  18283. global$b(containerElm).on('focusin focusout', function (e) {
  18284. global$b(e.target).attr('aria-grabbed', e.type === 'focus' ? 'true' : 'false');
  18285. });
  18286. global$b(containerElm).on('keydown', function (e) {
  18287. var activeHandle;
  18288. global$e.each(handles, function (handle) {
  18289. if (e.target.id === id + '-' + handle.name) {
  18290. activeHandle = handle;
  18291. return false;
  18292. }
  18293. });
  18294. function moveAndBlock(evt, handle, startRect, deltaX, deltaY) {
  18295. evt.stopPropagation();
  18296. evt.preventDefault();
  18297. moveRect(activeHandle, startRect, deltaX, deltaY);
  18298. }
  18299. switch (e.keyCode) {
  18300. case global$f.LEFT:
  18301. moveAndBlock(e, activeHandle, currentRect, -10, 0);
  18302. break;
  18303. case global$f.RIGHT:
  18304. moveAndBlock(e, activeHandle, currentRect, 10, 0);
  18305. break;
  18306. case global$f.UP:
  18307. moveAndBlock(e, activeHandle, currentRect, 0, -10);
  18308. break;
  18309. case global$f.DOWN:
  18310. moveAndBlock(e, activeHandle, currentRect, 0, 10);
  18311. break;
  18312. case global$f.ENTER:
  18313. case global$f.SPACEBAR:
  18314. e.preventDefault();
  18315. action();
  18316. break;
  18317. }
  18318. });
  18319. }
  18320. function toggleVisibility(state) {
  18321. var selectors;
  18322. selectors = global$e.map(handles, function (handle) {
  18323. return '#' + id + '-' + handle.name;
  18324. }).concat(global$e.map(blockers, function (blocker) {
  18325. return '#' + id + '-' + blocker;
  18326. })).join(',');
  18327. if (state) {
  18328. global$b(selectors, containerElm).show();
  18329. } else {
  18330. global$b(selectors, containerElm).hide();
  18331. }
  18332. }
  18333. function repaint(rect) {
  18334. function updateElementRect(name, rect) {
  18335. if (rect.h < 0) {
  18336. rect.h = 0;
  18337. }
  18338. if (rect.w < 0) {
  18339. rect.w = 0;
  18340. }
  18341. global$b('#' + id + '-' + name, containerElm).css({
  18342. left: rect.x,
  18343. top: rect.y,
  18344. width: rect.w,
  18345. height: rect.h
  18346. });
  18347. }
  18348. global$e.each(handles, function (handle) {
  18349. global$b('#' + id + '-' + handle.name, containerElm).css({
  18350. left: rect.w * handle.xMul + rect.x,
  18351. top: rect.h * handle.yMul + rect.y
  18352. });
  18353. });
  18354. updateElementRect('top', {
  18355. x: viewPortRect.x,
  18356. y: viewPortRect.y,
  18357. w: viewPortRect.w,
  18358. h: rect.y - viewPortRect.y
  18359. });
  18360. updateElementRect('right', {
  18361. x: rect.x + rect.w,
  18362. y: rect.y,
  18363. w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  18364. h: rect.h
  18365. });
  18366. updateElementRect('bottom', {
  18367. x: viewPortRect.x,
  18368. y: rect.y + rect.h,
  18369. w: viewPortRect.w,
  18370. h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  18371. });
  18372. updateElementRect('left', {
  18373. x: viewPortRect.x,
  18374. y: rect.y,
  18375. w: rect.x - viewPortRect.x,
  18376. h: rect.h
  18377. });
  18378. updateElementRect('move', rect);
  18379. }
  18380. function setRect(rect) {
  18381. currentRect = rect;
  18382. repaint(currentRect);
  18383. }
  18384. function setViewPortRect(rect) {
  18385. viewPortRect = rect;
  18386. repaint(currentRect);
  18387. }
  18388. function setInnerRect(rect) {
  18389. setRect(getAbsoluteRect(clampRect, rect));
  18390. }
  18391. function setClampRect(rect) {
  18392. clampRect = rect;
  18393. repaint(currentRect);
  18394. }
  18395. function destroy() {
  18396. global$e.each(dragHelpers, function (helper) {
  18397. helper.destroy();
  18398. });
  18399. dragHelpers = [];
  18400. }
  18401. render();
  18402. instance = global$e.extend({
  18403. toggleVisibility: toggleVisibility,
  18404. setClampRect: setClampRect,
  18405. setRect: setRect,
  18406. getInnerRect: getInnerRect,
  18407. setInnerRect: setInnerRect,
  18408. setViewPortRect: setViewPortRect,
  18409. destroy: destroy
  18410. }, global$d);
  18411. return instance;
  18412. };
  18413. var CropRect = { create: create$7 };
  18414. var loadImage = function (image) {
  18415. return new global$4(function (resolve) {
  18416. var loaded = function () {
  18417. image.removeEventListener('load', loaded);
  18418. resolve(image);
  18419. };
  18420. if (image.complete) {
  18421. resolve(image);
  18422. } else {
  18423. image.addEventListener('load', loaded);
  18424. }
  18425. });
  18426. };
  18427. var renderImagePanel = function (initialUrl) {
  18428. var memBg = record({
  18429. dom: {
  18430. tag: 'div',
  18431. classes: ['tox-image-tools__image-bg'],
  18432. attributes: { role: 'presentation' }
  18433. }
  18434. });
  18435. var zoomState = Cell(1);
  18436. var cropRect = Cell(Option.none());
  18437. var rectState = Cell({
  18438. x: 0,
  18439. y: 0,
  18440. w: 1,
  18441. h: 1
  18442. });
  18443. var viewRectState = Cell({
  18444. x: 0,
  18445. y: 0,
  18446. w: 1,
  18447. h: 1
  18448. });
  18449. var repaintImg = function (anyInSystem, img) {
  18450. memContainer.getOpt(anyInSystem).each(function (panel) {
  18451. var zoom = zoomState.get();
  18452. var panelW = get$7(panel.element());
  18453. var panelH = get$6(panel.element());
  18454. var width = img.dom().naturalWidth * zoom;
  18455. var height = img.dom().naturalHeight * zoom;
  18456. var left = Math.max(0, panelW / 2 - width / 2);
  18457. var top = Math.max(0, panelH / 2 - height / 2);
  18458. var css = {
  18459. left: left.toString() + 'px',
  18460. top: top.toString() + 'px',
  18461. width: width.toString() + 'px',
  18462. height: height.toString() + 'px',
  18463. position: 'absolute'
  18464. };
  18465. setAll$1(img, css);
  18466. memBg.getOpt(panel).each(function (bg) {
  18467. setAll$1(bg.element(), css);
  18468. });
  18469. cropRect.get().each(function (cRect) {
  18470. var rect = rectState.get();
  18471. cRect.setRect({
  18472. x: rect.x * zoom + left,
  18473. y: rect.y * zoom + top,
  18474. w: rect.w * zoom,
  18475. h: rect.h * zoom
  18476. });
  18477. cRect.setClampRect({
  18478. x: left,
  18479. y: top,
  18480. w: width,
  18481. h: height
  18482. });
  18483. cRect.setViewPortRect({
  18484. x: 0,
  18485. y: 0,
  18486. w: panelW,
  18487. h: panelH
  18488. });
  18489. });
  18490. });
  18491. };
  18492. var zoomFit = function (anyInSystem, img) {
  18493. memContainer.getOpt(anyInSystem).each(function (panel) {
  18494. var panelW = get$7(panel.element());
  18495. var panelH = get$6(panel.element());
  18496. var width = img.dom().naturalWidth;
  18497. var height = img.dom().naturalHeight;
  18498. var zoom = Math.min(panelW / width, panelH / height);
  18499. if (zoom >= 1) {
  18500. zoomState.set(1);
  18501. } else {
  18502. zoomState.set(zoom);
  18503. }
  18504. });
  18505. };
  18506. var updateSrc = function (anyInSystem, url) {
  18507. var img = Element.fromTag('img');
  18508. set$1(img, 'src', url);
  18509. return loadImage(img.dom()).then(function () {
  18510. return memContainer.getOpt(anyInSystem).map(function (panel) {
  18511. var aImg = external({ element: img });
  18512. Replacing.replaceAt(panel, 1, Option.some(aImg));
  18513. var lastViewRect = viewRectState.get();
  18514. var viewRect = {
  18515. x: 0,
  18516. y: 0,
  18517. w: img.dom().naturalWidth,
  18518. h: img.dom().naturalHeight
  18519. };
  18520. viewRectState.set(viewRect);
  18521. var rect = global$c.inflate(viewRect, -20, -20);
  18522. rectState.set(rect);
  18523. if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  18524. zoomFit(panel, img);
  18525. }
  18526. repaintImg(panel, img);
  18527. return img;
  18528. });
  18529. });
  18530. };
  18531. var zoom = function (anyInSystem, direction) {
  18532. var currentZoom = zoomState.get();
  18533. var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  18534. zoomState.set(newZoom);
  18535. memContainer.getOpt(anyInSystem).each(function (panel) {
  18536. var img = panel.components()[1].element();
  18537. repaintImg(panel, img);
  18538. });
  18539. };
  18540. var showCrop = function () {
  18541. cropRect.get().each(function (cRect) {
  18542. cRect.toggleVisibility(true);
  18543. });
  18544. };
  18545. var hideCrop = function () {
  18546. cropRect.get().each(function (cRect) {
  18547. cRect.toggleVisibility(false);
  18548. });
  18549. };
  18550. var getRect = function () {
  18551. return rectState.get();
  18552. };
  18553. var container = Container.sketch({
  18554. dom: {
  18555. tag: 'div',
  18556. classes: ['tox-image-tools__image']
  18557. },
  18558. components: [
  18559. memBg.asSpec(),
  18560. {
  18561. dom: {
  18562. tag: 'img',
  18563. attributes: { src: initialUrl }
  18564. }
  18565. },
  18566. {
  18567. dom: { tag: 'div' },
  18568. behaviours: derive$1([config('image-panel-crop-events', [runOnAttached(function (comp) {
  18569. memContainer.getOpt(comp).each(function (container) {
  18570. var el = container.element().dom();
  18571. var cRect = CropRect.create({
  18572. x: 10,
  18573. y: 10,
  18574. w: 100,
  18575. h: 100
  18576. }, {
  18577. x: 0,
  18578. y: 0,
  18579. w: 200,
  18580. h: 200
  18581. }, {
  18582. x: 0,
  18583. y: 0,
  18584. w: 200,
  18585. h: 200
  18586. }, el, function () {
  18587. });
  18588. cRect.toggleVisibility(false);
  18589. cRect.on('updateRect', function (e) {
  18590. var rect = e.rect;
  18591. var zoom = zoomState.get();
  18592. var newRect = {
  18593. x: Math.round(rect.x / zoom),
  18594. y: Math.round(rect.y / zoom),
  18595. w: Math.round(rect.w / zoom),
  18596. h: Math.round(rect.h / zoom)
  18597. };
  18598. rectState.set(newRect);
  18599. });
  18600. cropRect.set(Option.some(cRect));
  18601. });
  18602. })])])
  18603. }
  18604. ],
  18605. containerBehaviours: derive$1([
  18606. Replacing.config({}),
  18607. config('image-panel-events', [runOnAttached(function (comp) {
  18608. updateSrc(comp, initialUrl);
  18609. })])
  18610. ])
  18611. });
  18612. var memContainer = record(container);
  18613. var getMeasurements = function () {
  18614. var viewRect = viewRectState.get();
  18615. return {
  18616. width: viewRect.w,
  18617. height: viewRect.h
  18618. };
  18619. };
  18620. return {
  18621. memContainer: memContainer,
  18622. updateSrc: updateSrc,
  18623. zoom: zoom,
  18624. showCrop: showCrop,
  18625. hideCrop: hideCrop,
  18626. getRect: getRect,
  18627. getMeasurements: getMeasurements
  18628. };
  18629. };
  18630. var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  18631. return renderIconButton({
  18632. name: innerHtml,
  18633. icon: Option.some(icon),
  18634. disabled: disabled,
  18635. tooltip: Option.some(innerHtml),
  18636. primary: false,
  18637. borderless: false
  18638. }, action, providersBackstage);
  18639. };
  18640. var setButtonEnabled = function (button, enabled) {
  18641. if (enabled) {
  18642. Disabling.enable(button);
  18643. } else {
  18644. Disabling.disable(button);
  18645. }
  18646. };
  18647. var renderSideBar = function (providersBackstage) {
  18648. var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  18649. memUndo.getOpt(anyInSystem).each(function (undo) {
  18650. setButtonEnabled(undo, undoEnabled);
  18651. });
  18652. memRedo.getOpt(anyInSystem).each(function (redo) {
  18653. setButtonEnabled(redo, redoEnabled);
  18654. });
  18655. };
  18656. var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  18657. emitWith(button, internal.undo(), { direction: 1 });
  18658. }, providersBackstage));
  18659. var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  18660. emitWith(button, internal.redo(), { direction: 1 });
  18661. }, providersBackstage));
  18662. var container = Container.sketch({
  18663. dom: {
  18664. tag: 'div',
  18665. classes: [
  18666. 'tox-image-tools__toolbar',
  18667. 'tox-image-tools__sidebar'
  18668. ]
  18669. },
  18670. components: [
  18671. memUndo.asSpec(),
  18672. memRedo.asSpec(),
  18673. createButton('Zoom in', 'zoom-in', false, function (button) {
  18674. emitWith(button, internal.zoom(), { direction: 1 });
  18675. }, providersBackstage),
  18676. createButton('Zoom out', 'zoom-out', false, function (button) {
  18677. emitWith(button, internal.zoom(), { direction: -1 });
  18678. }, providersBackstage)
  18679. ]
  18680. });
  18681. return {
  18682. container: container,
  18683. updateButtonUndoStates: updateButtonUndoStates
  18684. };
  18685. };
  18686. function UndoStack () {
  18687. var data = [];
  18688. var index = -1;
  18689. function add(state) {
  18690. var removed;
  18691. removed = data.splice(++index);
  18692. data.push(state);
  18693. return {
  18694. state: state,
  18695. removed: removed
  18696. };
  18697. }
  18698. function undo() {
  18699. if (canUndo()) {
  18700. return data[--index];
  18701. }
  18702. }
  18703. function redo() {
  18704. if (canRedo()) {
  18705. return data[++index];
  18706. }
  18707. }
  18708. function canUndo() {
  18709. return index > 0;
  18710. }
  18711. function canRedo() {
  18712. return index !== -1 && index < data.length - 1;
  18713. }
  18714. return {
  18715. data: data,
  18716. add: add,
  18717. undo: undo,
  18718. redo: redo,
  18719. canUndo: canUndo,
  18720. canRedo: canRedo
  18721. };
  18722. }
  18723. var makeState = function (initialState) {
  18724. var blobState = Cell(initialState);
  18725. var tempState = Cell(Option.none());
  18726. var undoStack = UndoStack();
  18727. undoStack.add(initialState);
  18728. var getBlobState = function () {
  18729. return blobState.get();
  18730. };
  18731. var setBlobState = function (state) {
  18732. blobState.set(state);
  18733. };
  18734. var getTempState = function () {
  18735. return tempState.get().fold(function () {
  18736. return blobState.get();
  18737. }, function (temp) {
  18738. return temp;
  18739. });
  18740. };
  18741. var updateTempState = function (blob) {
  18742. var newTempState = createState(blob);
  18743. destroyTempState();
  18744. tempState.set(Option.some(newTempState));
  18745. return newTempState.url;
  18746. };
  18747. var createState = function (blob) {
  18748. return {
  18749. blob: blob,
  18750. url: domGlobals.URL.createObjectURL(blob)
  18751. };
  18752. };
  18753. var destroyState = function (state) {
  18754. domGlobals.URL.revokeObjectURL(state.url);
  18755. };
  18756. var destroyStates = function (states) {
  18757. global$e.each(states, destroyState);
  18758. };
  18759. var destroyTempState = function () {
  18760. tempState.get().each(destroyState);
  18761. tempState.set(Option.none());
  18762. };
  18763. var addBlobState = function (blob) {
  18764. var newState = createState(blob);
  18765. setBlobState(newState);
  18766. var removed = undoStack.add(newState).removed;
  18767. destroyStates(removed);
  18768. return newState.url;
  18769. };
  18770. var addTempState = function (blob) {
  18771. var newState = createState(blob);
  18772. tempState.set(Option.some(newState));
  18773. return newState.url;
  18774. };
  18775. var applyTempState = function (postApply) {
  18776. return tempState.get().fold(function () {
  18777. }, function (temp) {
  18778. addBlobState(temp.blob);
  18779. postApply();
  18780. });
  18781. };
  18782. var undo = function () {
  18783. var currentState = undoStack.undo();
  18784. setBlobState(currentState);
  18785. return currentState.url;
  18786. };
  18787. var redo = function () {
  18788. var currentState = undoStack.redo();
  18789. setBlobState(currentState);
  18790. return currentState.url;
  18791. };
  18792. var getHistoryStates = function () {
  18793. var undoEnabled = undoStack.canUndo();
  18794. var redoEnabled = undoStack.canRedo();
  18795. return {
  18796. undoEnabled: undoEnabled,
  18797. redoEnabled: redoEnabled
  18798. };
  18799. };
  18800. return {
  18801. getBlobState: getBlobState,
  18802. setBlobState: setBlobState,
  18803. addBlobState: addBlobState,
  18804. getTempState: getTempState,
  18805. updateTempState: updateTempState,
  18806. addTempState: addTempState,
  18807. applyTempState: applyTempState,
  18808. destroyTempState: destroyTempState,
  18809. undo: undo,
  18810. redo: redo,
  18811. getHistoryStates: getHistoryStates
  18812. };
  18813. };
  18814. var renderImageTools = function (detail, providersBackstage) {
  18815. var state = makeState(detail.currentState);
  18816. var zoom = function (anyInSystem, simulatedEvent) {
  18817. var direction = simulatedEvent.event().direction();
  18818. imagePanel.zoom(anyInSystem, direction);
  18819. };
  18820. var updateButtonUndoStates = function (anyInSystem) {
  18821. var historyStates = state.getHistoryStates();
  18822. sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  18823. emitWith(anyInSystem, external$2.formActionEvent, {
  18824. name: external$2.saveState(),
  18825. value: historyStates.undoEnabled
  18826. });
  18827. };
  18828. var disableUndoRedo = function (anyInSystem) {
  18829. sideBar.updateButtonUndoStates(anyInSystem, false, false);
  18830. };
  18831. var undo = function (anyInSystem, _simulatedEvent) {
  18832. var url = state.undo();
  18833. updateSrc(anyInSystem, url).then(function (oImg) {
  18834. unblock(anyInSystem);
  18835. updateButtonUndoStates(anyInSystem);
  18836. });
  18837. };
  18838. var redo = function (anyInSystem, _simulatedEvent) {
  18839. var url = state.redo();
  18840. updateSrc(anyInSystem, url).then(function (oImg) {
  18841. unblock(anyInSystem);
  18842. updateButtonUndoStates(anyInSystem);
  18843. });
  18844. };
  18845. var imageResultToBlob = function (ir) {
  18846. return ir.toBlob();
  18847. };
  18848. var block = function (anyInSystem) {
  18849. emitWith(anyInSystem, external$2.formActionEvent, {
  18850. name: external$2.disable(),
  18851. value: {}
  18852. });
  18853. };
  18854. var unblock = function (anyInSystem) {
  18855. editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  18856. Disabling.enable(applyButton);
  18857. });
  18858. emitWith(anyInSystem, external$2.formActionEvent, {
  18859. name: external$2.enable(),
  18860. value: {}
  18861. });
  18862. };
  18863. var updateSrc = function (anyInSystem, src) {
  18864. block(anyInSystem);
  18865. return imagePanel.updateSrc(anyInSystem, src);
  18866. };
  18867. var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  18868. block(anyInSystem);
  18869. return blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  18870. return updateSrc(anyInSystem, url).then(function (oImg) {
  18871. updateButtonUndoStates(anyInSystem);
  18872. swap();
  18873. unblock(anyInSystem);
  18874. return oImg;
  18875. });
  18876. }).catch(function (err) {
  18877. domGlobals.console.log(err);
  18878. unblock(anyInSystem);
  18879. return err;
  18880. });
  18881. };
  18882. var manipulate = function (anyInSystem, filter, swap) {
  18883. var blob = state.getBlobState().blob;
  18884. var action = function (blob) {
  18885. return state.updateTempState(blob);
  18886. };
  18887. blobManipulate(anyInSystem, blob, filter, action, swap);
  18888. };
  18889. var tempManipulate = function (anyInSystem, filter) {
  18890. var blob = state.getTempState().blob;
  18891. var action = function (blob) {
  18892. return state.addTempState(blob);
  18893. };
  18894. blobManipulate(anyInSystem, blob, filter, action, noop);
  18895. };
  18896. var manipulateApply = function (anyInSystem, filter, swap) {
  18897. var blob = state.getBlobState().blob;
  18898. var action = function (blob) {
  18899. var url = state.addBlobState(blob);
  18900. destroyTempState(anyInSystem);
  18901. return url;
  18902. };
  18903. blobManipulate(anyInSystem, blob, filter, action, swap);
  18904. };
  18905. var apply = function (anyInSystem, simulatedEvent) {
  18906. var postApply = function () {
  18907. destroyTempState(anyInSystem);
  18908. var swap = simulatedEvent.event().swap();
  18909. swap();
  18910. };
  18911. state.applyTempState(postApply);
  18912. };
  18913. var destroyTempState = function (anyInSystem) {
  18914. var currentUrl = state.getBlobState().url;
  18915. state.destroyTempState();
  18916. updateButtonUndoStates(anyInSystem);
  18917. return currentUrl;
  18918. };
  18919. var cancel = function (anyInSystem) {
  18920. var currentUrl = destroyTempState(anyInSystem);
  18921. updateSrc(anyInSystem, currentUrl).then(function (oImg) {
  18922. unblock(anyInSystem);
  18923. });
  18924. };
  18925. var back = function (anyInSystem, simulatedEvent) {
  18926. cancel(anyInSystem);
  18927. var swap = simulatedEvent.event().swap();
  18928. swap();
  18929. imagePanel.hideCrop();
  18930. };
  18931. var transform = function (anyInSystem, simulatedEvent) {
  18932. return manipulate(anyInSystem, simulatedEvent.event().transform(), noop);
  18933. };
  18934. var tempTransform = function (anyInSystem, simulatedEvent) {
  18935. return tempManipulate(anyInSystem, simulatedEvent.event().transform());
  18936. };
  18937. var transformApply = function (anyInSystem, simulatedEvent) {
  18938. return manipulateApply(anyInSystem, simulatedEvent.event().transform(), simulatedEvent.event().swap());
  18939. };
  18940. var imagePanel = renderImagePanel(detail.currentState.url);
  18941. var sideBar = renderSideBar(providersBackstage);
  18942. var editPanel = renderEditPanel(imagePanel, providersBackstage);
  18943. var swap = function (anyInSystem, simulatedEvent) {
  18944. disableUndoRedo(anyInSystem);
  18945. var transform = simulatedEvent.event().transform();
  18946. var swap = simulatedEvent.event().swap();
  18947. transform.fold(function () {
  18948. swap();
  18949. }, function (transform) {
  18950. manipulate(anyInSystem, transform, swap);
  18951. });
  18952. };
  18953. return {
  18954. dom: {
  18955. tag: 'div',
  18956. attributes: { role: 'presentation' }
  18957. },
  18958. components: [
  18959. editPanel.memContainer.asSpec(),
  18960. imagePanel.memContainer.asSpec(),
  18961. sideBar.container
  18962. ],
  18963. behaviours: derive$1([
  18964. Representing.config({
  18965. store: {
  18966. mode: 'manual',
  18967. getValue: function () {
  18968. return state.getBlobState();
  18969. }
  18970. }
  18971. }),
  18972. config('image-tools-events', [
  18973. run(internal.undo(), undo),
  18974. run(internal.redo(), redo),
  18975. run(internal.zoom(), zoom),
  18976. run(internal.back(), back),
  18977. run(internal.apply(), apply),
  18978. run(internal.transform(), transform),
  18979. run(internal.tempTransform(), tempTransform),
  18980. run(internal.transformApply(), transformApply),
  18981. run(internal.swap(), swap)
  18982. ]),
  18983. ComposingConfigs.self()
  18984. ])
  18985. };
  18986. };
  18987. var factory$8 = function (detail, spec) {
  18988. var options = map(detail.options, function (option) {
  18989. return {
  18990. dom: {
  18991. tag: 'option',
  18992. value: option.value,
  18993. innerHtml: option.text
  18994. }
  18995. };
  18996. });
  18997. var initialValues = detail.data.map(function (v) {
  18998. return wrap$1('initialValue', v);
  18999. }).getOr({});
  19000. return {
  19001. uid: detail.uid,
  19002. dom: {
  19003. tag: 'select',
  19004. classes: detail.selectClasses,
  19005. attributes: detail.selectAttributes
  19006. },
  19007. components: options,
  19008. behaviours: augment(detail.selectBehaviours, [
  19009. Focusing.config({}),
  19010. Representing.config({
  19011. store: __assign({
  19012. mode: 'manual',
  19013. getValue: function (select) {
  19014. return get$5(select.element());
  19015. },
  19016. setValue: function (select, newValue) {
  19017. var found = find(detail.options, function (opt) {
  19018. return opt.value === newValue;
  19019. });
  19020. if (found.isSome()) {
  19021. set$3(select.element(), newValue);
  19022. }
  19023. }
  19024. }, initialValues)
  19025. })
  19026. ])
  19027. };
  19028. };
  19029. var HtmlSelect = single$2({
  19030. name: 'HtmlSelect',
  19031. configFields: [
  19032. strict$1('options'),
  19033. field$1('selectBehaviours', [
  19034. Focusing,
  19035. Representing
  19036. ]),
  19037. defaulted$1('selectClasses', []),
  19038. defaulted$1('selectAttributes', {}),
  19039. option('data')
  19040. ],
  19041. factory: factory$8
  19042. });
  19043. var renderSelectBox = function (spec, providersBackstage) {
  19044. var translatedOptions = map(spec.items, function (item) {
  19045. return {
  19046. text: providersBackstage.translate(item.text),
  19047. value: item.value
  19048. };
  19049. });
  19050. var pLabel = spec.label.map(function (label) {
  19051. return renderLabel(label, providersBackstage);
  19052. });
  19053. var pField = FormField.parts().field({
  19054. dom: {},
  19055. selectAttributes: { size: spec.size },
  19056. options: translatedOptions,
  19057. factory: HtmlSelect,
  19058. selectBehaviours: derive$1([
  19059. Disabling.config({ disabled: spec.disabled }),
  19060. Tabstopping.config({}),
  19061. config('selectbox-change', [run(change(), function (component, _) {
  19062. emitWith(component, formChangeEvent, { name: spec.name });
  19063. })])
  19064. ])
  19065. });
  19066. var chevron = spec.size > 1 ? Option.none() : Option.some({
  19067. dom: {
  19068. tag: 'div',
  19069. classes: ['tox-selectfield__icon-js'],
  19070. innerHtml: get$c('chevron-down', providersBackstage.icons)
  19071. }
  19072. });
  19073. var selectWrap = {
  19074. dom: {
  19075. tag: 'div',
  19076. classes: ['tox-selectfield']
  19077. },
  19078. components: flatten([
  19079. [pField],
  19080. chevron.toArray()
  19081. ])
  19082. };
  19083. return FormField.sketch({
  19084. dom: {
  19085. tag: 'div',
  19086. classes: ['tox-form__group']
  19087. },
  19088. components: flatten([
  19089. pLabel.toArray(),
  19090. [selectWrap]
  19091. ]),
  19092. fieldBehaviours: derive$1([Disabling.config({
  19093. disabled: spec.disabled,
  19094. onDisabled: function (comp) {
  19095. FormField.getField(comp).each(Disabling.disable);
  19096. },
  19097. onEnabled: function (comp) {
  19098. FormField.getField(comp).each(Disabling.enable);
  19099. }
  19100. })])
  19101. });
  19102. };
  19103. var renderTextField = function (spec, providersBackstage) {
  19104. var pLabel = spec.label.map(function (label) {
  19105. return renderLabel(label, providersBackstage);
  19106. });
  19107. var baseInputBehaviours = [
  19108. Disabling.config({ disabled: spec.disabled }),
  19109. Keying.config({
  19110. mode: 'execution',
  19111. useEnter: spec.multiline !== true,
  19112. useControlEnter: spec.multiline === true,
  19113. execute: function (comp) {
  19114. emit(comp, formSubmitEvent);
  19115. return Option.some(true);
  19116. }
  19117. }),
  19118. config('textfield-change', [
  19119. run(input(), function (component, _) {
  19120. emitWith(component, formChangeEvent, { name: spec.name });
  19121. }),
  19122. run(postPaste(), function (component, _) {
  19123. emitWith(component, formChangeEvent, { name: spec.name });
  19124. })
  19125. ]),
  19126. Tabstopping.config({})
  19127. ];
  19128. var validatingBehaviours = spec.validation.map(function (vl) {
  19129. return Invalidating.config({
  19130. getRoot: function (input) {
  19131. return parent(input.element());
  19132. },
  19133. invalidClass: 'tox-invalid',
  19134. validator: {
  19135. validate: function (input) {
  19136. var v = Representing.getValue(input);
  19137. var result = vl.validator(v);
  19138. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  19139. },
  19140. validateOnLoad: vl.validateOnLoad
  19141. }
  19142. });
  19143. }).toArray();
  19144. var placeholder = spec.placeholder.fold(constant({}), function (p) {
  19145. return { placeholder: providersBackstage.translate(p) };
  19146. });
  19147. var inputMode = spec.inputMode.fold(constant({}), function (mode) {
  19148. return { inputmode: mode };
  19149. });
  19150. var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  19151. var pField = FormField.parts().field({
  19152. tag: spec.multiline === true ? 'textarea' : 'input',
  19153. inputAttributes: inputAttributes,
  19154. inputClasses: [spec.classname],
  19155. inputBehaviours: derive$1(flatten([
  19156. baseInputBehaviours,
  19157. validatingBehaviours
  19158. ])),
  19159. selectOnFocus: false,
  19160. factory: Input
  19161. });
  19162. var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  19163. var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  19164. var extraBehaviours = [Disabling.config({
  19165. disabled: spec.disabled,
  19166. onDisabled: function (comp) {
  19167. FormField.getField(comp).each(Disabling.disable);
  19168. },
  19169. onEnabled: function (comp) {
  19170. FormField.getField(comp).each(Disabling.enable);
  19171. }
  19172. })];
  19173. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  19174. };
  19175. var renderInput = function (spec, providersBackstage) {
  19176. return renderTextField({
  19177. name: spec.name,
  19178. multiline: false,
  19179. label: spec.label,
  19180. inputMode: spec.inputMode,
  19181. placeholder: spec.placeholder,
  19182. flex: false,
  19183. disabled: spec.disabled,
  19184. classname: 'tox-textfield',
  19185. validation: Option.none(),
  19186. maximized: spec.maximized
  19187. }, providersBackstage);
  19188. };
  19189. var renderTextarea = function (spec, providersBackstage) {
  19190. return renderTextField({
  19191. name: spec.name,
  19192. multiline: true,
  19193. label: spec.label,
  19194. inputMode: Option.none(),
  19195. placeholder: spec.placeholder,
  19196. flex: true,
  19197. disabled: spec.disabled,
  19198. classname: 'tox-textarea',
  19199. validation: Option.none(),
  19200. maximized: spec.maximized
  19201. }, providersBackstage);
  19202. };
  19203. var events$c = function (streamConfig, streamState) {
  19204. var streams = streamConfig.stream.streams;
  19205. var processor = streams.setup(streamConfig, streamState);
  19206. return derive([
  19207. run(streamConfig.event, processor),
  19208. runOnDetached(function () {
  19209. return streamState.cancel();
  19210. })
  19211. ].concat(streamConfig.cancelEvent.map(function (e) {
  19212. return [run(e, function () {
  19213. return streamState.cancel();
  19214. })];
  19215. }).getOr([])));
  19216. };
  19217. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  19218. events: events$c
  19219. });
  19220. var throttle = function (_config) {
  19221. var state = Cell(null);
  19222. var readState = function () {
  19223. return { timer: state.get() !== null ? 'set' : 'unset' };
  19224. };
  19225. var setTimer = function (t) {
  19226. state.set(t);
  19227. };
  19228. var cancel = function () {
  19229. var t = state.get();
  19230. if (t !== null) {
  19231. t.cancel();
  19232. }
  19233. };
  19234. return nu$5({
  19235. readState: readState,
  19236. setTimer: setTimer,
  19237. cancel: cancel
  19238. });
  19239. };
  19240. var init$6 = function (spec) {
  19241. return spec.stream.streams.state(spec);
  19242. };
  19243. var StreamingState = /*#__PURE__*/Object.freeze({
  19244. throttle: throttle,
  19245. init: init$6
  19246. });
  19247. var setup$2 = function (streamInfo, streamState) {
  19248. var sInfo = streamInfo.stream;
  19249. var throttler = last$2(streamInfo.onStream, sInfo.delay);
  19250. streamState.setTimer(throttler);
  19251. return function (component, simulatedEvent) {
  19252. throttler.throttle(component, simulatedEvent);
  19253. if (sInfo.stopEvent) {
  19254. simulatedEvent.stop();
  19255. }
  19256. };
  19257. };
  19258. var StreamingSchema = [
  19259. strictOf('stream', choose$1('mode', {
  19260. throttle: [
  19261. strict$1('delay'),
  19262. defaulted$1('stopEvent', true),
  19263. output('streams', {
  19264. setup: setup$2,
  19265. state: throttle
  19266. })
  19267. ]
  19268. })),
  19269. defaulted$1('event', 'input'),
  19270. option('cancelEvent'),
  19271. onStrictHandler('onStream')
  19272. ];
  19273. var Streaming = create$1({
  19274. fields: StreamingSchema,
  19275. name: 'streaming',
  19276. active: ActiveStreaming,
  19277. state: StreamingState
  19278. });
  19279. var setValueFromItem = function (model, input, item) {
  19280. var itemData = Representing.getValue(item);
  19281. Representing.setValue(input, itemData);
  19282. setCursorAtEnd(input);
  19283. };
  19284. var setSelectionOn = function (input, f) {
  19285. var el = input.element();
  19286. var value = get$5(el);
  19287. var node = el.dom();
  19288. if (get$2(el, 'type') !== 'number') {
  19289. f(node, value);
  19290. }
  19291. };
  19292. var setCursorAtEnd = function (input) {
  19293. setSelectionOn(input, function (node, value) {
  19294. return node.setSelectionRange(value.length, value.length);
  19295. });
  19296. };
  19297. var setSelectionToEnd = function (input, startOffset) {
  19298. setSelectionOn(input, function (node, value) {
  19299. return node.setSelectionRange(startOffset, value.length);
  19300. });
  19301. };
  19302. var attemptSelectOver = function (model, input, item) {
  19303. if (!model.selectsOver) {
  19304. return Option.none();
  19305. } else {
  19306. var currentValue = Representing.getValue(input);
  19307. var inputDisplay_1 = model.getDisplayText(currentValue);
  19308. var itemValue = Representing.getValue(item);
  19309. var itemDisplay = model.getDisplayText(itemValue);
  19310. return itemDisplay.indexOf(inputDisplay_1) === 0 ? Option.some(function () {
  19311. setValueFromItem(model, input, item);
  19312. setSelectionToEnd(input, inputDisplay_1.length);
  19313. }) : Option.none();
  19314. }
  19315. };
  19316. var itemExecute = constant('alloy.typeahead.itemexecute');
  19317. var make$5 = function (detail, components, spec, externals) {
  19318. var navigateList = function (comp, simulatedEvent, highlighter) {
  19319. detail.previewing.set(false);
  19320. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19321. if (Sandboxing.isOpen(sandbox)) {
  19322. Composing.getCurrent(sandbox).each(function (menu) {
  19323. Highlighting.getHighlighted(menu).fold(function () {
  19324. highlighter(menu);
  19325. }, function () {
  19326. dispatchEvent(sandbox, menu.element(), 'keydown', simulatedEvent);
  19327. });
  19328. });
  19329. } else {
  19330. var onOpenSync = function (sandbox) {
  19331. Composing.getCurrent(sandbox).each(highlighter);
  19332. };
  19333. open$1(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19334. }
  19335. };
  19336. var focusBehaviours$1 = focusBehaviours(detail);
  19337. var mapFetch = function (comp) {
  19338. return function (tdata) {
  19339. return tdata.map(function (data) {
  19340. var menus = values(data.menus);
  19341. var items = bind(menus, function (menu) {
  19342. return filter(menu.items, function (item) {
  19343. return item.type === 'item';
  19344. });
  19345. });
  19346. var repState = Representing.getState(comp);
  19347. repState.update(map(items, function (item) {
  19348. return item.data;
  19349. }));
  19350. return data;
  19351. });
  19352. };
  19353. };
  19354. var behaviours = [
  19355. Focusing.config({}),
  19356. Representing.config({
  19357. onSetValue: detail.onSetValue,
  19358. store: __assign({
  19359. mode: 'dataset',
  19360. getDataKey: function (comp) {
  19361. return get$5(comp.element());
  19362. },
  19363. getFallbackEntry: function (itemString) {
  19364. return {
  19365. value: itemString,
  19366. meta: {}
  19367. };
  19368. },
  19369. setValue: function (comp, data) {
  19370. set$3(comp.element(), detail.model.getDisplayText(data));
  19371. }
  19372. }, detail.initialData.map(function (d) {
  19373. return wrap$1('initialValue', d);
  19374. }).getOr({}))
  19375. }),
  19376. Streaming.config({
  19377. stream: {
  19378. mode: 'throttle',
  19379. delay: detail.responseTime,
  19380. stopEvent: false
  19381. },
  19382. onStream: function (component, simulatedEvent) {
  19383. var sandbox = Coupling.getCoupled(component, 'sandbox');
  19384. var focusInInput = Focusing.isFocused(component);
  19385. if (focusInInput) {
  19386. if (get$5(component.element()).length >= detail.minChars) {
  19387. var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  19388. return Highlighting.getHighlighted(menu).map(Representing.getValue);
  19389. });
  19390. detail.previewing.set(true);
  19391. var onOpenSync = function (_sandbox) {
  19392. Composing.getCurrent(sandbox).each(function (menu) {
  19393. previousValue_1.fold(function () {
  19394. if (detail.model.selectsOver) {
  19395. Highlighting.highlightFirst(menu);
  19396. }
  19397. }, function (pv) {
  19398. Highlighting.highlightBy(menu, function (item) {
  19399. var itemData = Representing.getValue(item);
  19400. return itemData.value === pv.value;
  19401. });
  19402. Highlighting.getHighlighted(menu).orThunk(function () {
  19403. Highlighting.highlightFirst(menu);
  19404. return Option.none();
  19405. });
  19406. });
  19407. });
  19408. };
  19409. open$1(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19410. }
  19411. }
  19412. },
  19413. cancelEvent: typeaheadCancel()
  19414. }),
  19415. Keying.config({
  19416. mode: 'special',
  19417. onDown: function (comp, simulatedEvent) {
  19418. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  19419. return Option.some(true);
  19420. },
  19421. onEscape: function (comp) {
  19422. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19423. if (Sandboxing.isOpen(sandbox)) {
  19424. Sandboxing.close(sandbox);
  19425. return Option.some(true);
  19426. }
  19427. return Option.none();
  19428. },
  19429. onUp: function (comp, simulatedEvent) {
  19430. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  19431. return Option.some(true);
  19432. },
  19433. onEnter: function (comp) {
  19434. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19435. var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  19436. if (sandboxIsOpen && !detail.previewing.get()) {
  19437. return Composing.getCurrent(sandbox).bind(function (menu) {
  19438. return Highlighting.getHighlighted(menu);
  19439. }).map(function (item) {
  19440. emitWith(comp, itemExecute(), { item: item });
  19441. return true;
  19442. });
  19443. } else {
  19444. var currentValue = Representing.getValue(comp);
  19445. emit(comp, typeaheadCancel());
  19446. detail.onExecute(sandbox, comp, currentValue);
  19447. if (sandboxIsOpen) {
  19448. Sandboxing.close(sandbox);
  19449. }
  19450. return Option.some(true);
  19451. }
  19452. }
  19453. }),
  19454. Toggling.config({
  19455. toggleClass: detail.markers.openClass,
  19456. aria: { mode: 'expanded' }
  19457. }),
  19458. Coupling.config({
  19459. others: {
  19460. sandbox: function (hotspot) {
  19461. return makeSandbox(detail, hotspot, {
  19462. onOpen: function () {
  19463. return Toggling.on(hotspot);
  19464. },
  19465. onClose: function () {
  19466. return Toggling.off(hotspot);
  19467. }
  19468. });
  19469. }
  19470. }
  19471. }),
  19472. config('typeaheadevents', [
  19473. runOnExecute(function (comp) {
  19474. var onOpenSync = noop;
  19475. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19476. }),
  19477. run(itemExecute(), function (comp, se) {
  19478. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19479. setValueFromItem(detail.model, comp, se.event().item());
  19480. emit(comp, typeaheadCancel());
  19481. detail.onItemExecute(comp, sandbox, se.event().item(), Representing.getValue(comp));
  19482. Sandboxing.close(sandbox);
  19483. setCursorAtEnd(comp);
  19484. })
  19485. ].concat(detail.dismissOnBlur ? [run(postBlur(), function (typeahead) {
  19486. var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  19487. if (search(sandbox.element()).isNone()) {
  19488. Sandboxing.close(sandbox);
  19489. }
  19490. })] : []))
  19491. ];
  19492. return {
  19493. uid: detail.uid,
  19494. dom: dom$2(deepMerge(detail, {
  19495. inputAttributes: {
  19496. 'role': 'combobox',
  19497. 'aria-autocomplete': 'list',
  19498. 'aria-haspopup': 'true'
  19499. }
  19500. })),
  19501. behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  19502. eventOrder: detail.eventOrder
  19503. };
  19504. };
  19505. var schema$j = constant([
  19506. option('lazySink'),
  19507. strict$1('fetch'),
  19508. defaulted$1('minChars', 5),
  19509. defaulted$1('responseTime', 1000),
  19510. onHandler('onOpen'),
  19511. defaulted$1('getHotspot', Option.some),
  19512. defaulted$1('getAnchorOverrides', constant({})),
  19513. defaulted$1('layouts', Option.none()),
  19514. defaulted$1('eventOrder', {}),
  19515. defaultedObjOf('model', {}, [
  19516. defaulted$1('getDisplayText', function (itemData) {
  19517. return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  19518. }),
  19519. defaulted$1('selectsOver', true),
  19520. defaulted$1('populateFromBrowse', true)
  19521. ]),
  19522. onHandler('onSetValue'),
  19523. onKeyboardHandler('onExecute'),
  19524. onHandler('onItemExecute'),
  19525. defaulted$1('inputClasses', []),
  19526. defaulted$1('inputAttributes', {}),
  19527. defaulted$1('inputStyles', {}),
  19528. defaulted$1('matchWidth', true),
  19529. defaulted$1('useMinWidth', false),
  19530. defaulted$1('dismissOnBlur', true),
  19531. markers(['openClass']),
  19532. option('initialData'),
  19533. field$1('typeaheadBehaviours', [
  19534. Focusing,
  19535. Representing,
  19536. Streaming,
  19537. Keying,
  19538. Toggling,
  19539. Coupling
  19540. ]),
  19541. state$1('previewing', function () {
  19542. return Cell(true);
  19543. })
  19544. ].concat(schema$f()).concat(sandboxFields()));
  19545. var parts$6 = constant([external$1({
  19546. schema: [tieredMenuMarkers()],
  19547. name: 'menu',
  19548. overrides: function (detail) {
  19549. return {
  19550. fakeFocus: true,
  19551. onHighlight: function (menu, item) {
  19552. if (!detail.previewing.get()) {
  19553. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19554. if (detail.model.populateFromBrowse) {
  19555. setValueFromItem(detail.model, input, item);
  19556. }
  19557. });
  19558. } else {
  19559. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19560. attemptSelectOver(detail.model, input, item).fold(function () {
  19561. return Highlighting.dehighlight(menu, item);
  19562. }, function (fn) {
  19563. return fn();
  19564. });
  19565. });
  19566. }
  19567. detail.previewing.set(false);
  19568. },
  19569. onExecute: function (menu, item) {
  19570. return menu.getSystem().getByUid(detail.uid).toOption().map(function (typeahead) {
  19571. emitWith(typeahead, itemExecute(), { item: item });
  19572. return true;
  19573. });
  19574. },
  19575. onHover: function (menu, item) {
  19576. detail.previewing.set(false);
  19577. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19578. if (detail.model.populateFromBrowse) {
  19579. setValueFromItem(detail.model, input, item);
  19580. }
  19581. });
  19582. }
  19583. };
  19584. }
  19585. })]);
  19586. var Typeahead = composite$1({
  19587. name: 'Typeahead',
  19588. configFields: schema$j(),
  19589. partFields: parts$6(),
  19590. factory: make$5
  19591. });
  19592. var wrap$2 = function (delegate) {
  19593. var toCached = function () {
  19594. return wrap$2(delegate.toCached());
  19595. };
  19596. var bindFuture = function (f) {
  19597. return wrap$2(delegate.bind(function (resA) {
  19598. return resA.fold(function (err) {
  19599. return Future.pure(Result.error(err));
  19600. }, function (a) {
  19601. return f(a);
  19602. });
  19603. }));
  19604. };
  19605. var bindResult = function (f) {
  19606. return wrap$2(delegate.map(function (resA) {
  19607. return resA.bind(f);
  19608. }));
  19609. };
  19610. var mapResult = function (f) {
  19611. return wrap$2(delegate.map(function (resA) {
  19612. return resA.map(f);
  19613. }));
  19614. };
  19615. var mapError = function (f) {
  19616. return wrap$2(delegate.map(function (resA) {
  19617. return resA.mapError(f);
  19618. }));
  19619. };
  19620. var foldResult = function (whenError, whenValue) {
  19621. return delegate.map(function (res) {
  19622. return res.fold(whenError, whenValue);
  19623. });
  19624. };
  19625. var withTimeout = function (timeout, errorThunk) {
  19626. return wrap$2(Future.nu(function (callback) {
  19627. var timedOut = false;
  19628. var timer = domGlobals.setTimeout(function () {
  19629. timedOut = true;
  19630. callback(Result.error(errorThunk()));
  19631. }, timeout);
  19632. delegate.get(function (result) {
  19633. if (!timedOut) {
  19634. domGlobals.clearTimeout(timer);
  19635. callback(result);
  19636. }
  19637. });
  19638. }));
  19639. };
  19640. return __assign(__assign({}, delegate), {
  19641. toCached: toCached,
  19642. bindFuture: bindFuture,
  19643. bindResult: bindResult,
  19644. mapResult: mapResult,
  19645. mapError: mapError,
  19646. foldResult: foldResult,
  19647. withTimeout: withTimeout
  19648. });
  19649. };
  19650. var nu$c = function (worker) {
  19651. return wrap$2(Future.nu(worker));
  19652. };
  19653. var value$2 = function (value) {
  19654. return wrap$2(Future.pure(Result.value(value)));
  19655. };
  19656. var error$1 = function (error) {
  19657. return wrap$2(Future.pure(Result.error(error)));
  19658. };
  19659. var fromResult$1 = function (result) {
  19660. return wrap$2(Future.pure(result));
  19661. };
  19662. var fromFuture = function (future) {
  19663. return wrap$2(future.map(Result.value));
  19664. };
  19665. var fromPromise = function (promise) {
  19666. return nu$c(function (completer) {
  19667. promise.then(function (value) {
  19668. completer(Result.value(value));
  19669. }, function (error) {
  19670. completer(Result.error(error));
  19671. });
  19672. });
  19673. };
  19674. var FutureResult = {
  19675. nu: nu$c,
  19676. wrap: wrap$2,
  19677. pure: value$2,
  19678. value: value$2,
  19679. error: error$1,
  19680. fromResult: fromResult$1,
  19681. fromFuture: fromFuture,
  19682. fromPromise: fromPromise
  19683. };
  19684. var separator$2 = { type: 'separator' };
  19685. var toMenuItem = function (target) {
  19686. return {
  19687. type: 'menuitem',
  19688. value: target.url,
  19689. text: target.title,
  19690. meta: { attach: target.attach },
  19691. onAction: function () {
  19692. }
  19693. };
  19694. };
  19695. var staticMenuItem = function (title, url) {
  19696. return {
  19697. type: 'menuitem',
  19698. value: url,
  19699. text: title,
  19700. meta: { attach: undefined },
  19701. onAction: function () {
  19702. }
  19703. };
  19704. };
  19705. var toMenuItems = function (targets) {
  19706. return map(targets, toMenuItem);
  19707. };
  19708. var filterLinkTargets = function (type, targets) {
  19709. return filter(targets, function (target) {
  19710. return target.type === type;
  19711. });
  19712. };
  19713. var filteredTargets = function (type, targets) {
  19714. return toMenuItems(filterLinkTargets(type, targets));
  19715. };
  19716. var headerTargets = function (linkInfo) {
  19717. return filteredTargets('header', linkInfo.targets);
  19718. };
  19719. var anchorTargets = function (linkInfo) {
  19720. return filteredTargets('anchor', linkInfo.targets);
  19721. };
  19722. var anchorTargetTop = function (linkInfo) {
  19723. return Option.from(linkInfo.anchorTop).map(function (url) {
  19724. return staticMenuItem('<top>', url);
  19725. }).toArray();
  19726. };
  19727. var anchorTargetBottom = function (linkInfo) {
  19728. return Option.from(linkInfo.anchorBottom).map(function (url) {
  19729. return staticMenuItem('<bottom>', url);
  19730. }).toArray();
  19731. };
  19732. var historyTargets = function (history) {
  19733. return map(history, function (url) {
  19734. return staticMenuItem(url, url);
  19735. });
  19736. };
  19737. var joinMenuLists = function (items) {
  19738. return foldl(items, function (a, b) {
  19739. var bothEmpty = a.length === 0 || b.length === 0;
  19740. return bothEmpty ? a.concat(b) : a.concat(separator$2, b);
  19741. }, []);
  19742. };
  19743. var filterByQuery = function (term, menuItems) {
  19744. var lowerCaseTerm = term.toLowerCase();
  19745. return filter(menuItems, function (item) {
  19746. var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  19747. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  19748. });
  19749. };
  19750. var getItems = function (fileType, input, urlBackstage) {
  19751. var urlInputValue = Representing.getValue(input);
  19752. var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  19753. var info = urlBackstage.getLinkInformation();
  19754. return info.fold(function () {
  19755. return [];
  19756. }, function (linkInfo) {
  19757. var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  19758. return fileType === 'file' ? joinMenuLists([
  19759. history,
  19760. filterByQuery(term, headerTargets(linkInfo)),
  19761. filterByQuery(term, flatten([
  19762. anchorTargetTop(linkInfo),
  19763. anchorTargets(linkInfo),
  19764. anchorTargetBottom(linkInfo)
  19765. ]))
  19766. ]) : history;
  19767. });
  19768. };
  19769. var errorId = generate$1('aria-invalid');
  19770. var renderUrlInput = function (spec, backstage, urlBackstage) {
  19771. var _a;
  19772. var providersBackstage = backstage.shared.providers;
  19773. var updateHistory = function (component) {
  19774. var urlEntry = Representing.getValue(component);
  19775. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  19776. };
  19777. var pField = FormField.parts().field({
  19778. factory: Typeahead,
  19779. dismissOnBlur: true,
  19780. inputClasses: ['tox-textfield'],
  19781. sandboxClasses: ['tox-dialog__popups'],
  19782. inputAttributes: {
  19783. 'aria-errormessage': errorId,
  19784. 'type': 'url'
  19785. },
  19786. minChars: 0,
  19787. responseTime: 0,
  19788. fetch: function (input) {
  19789. var items = getItems(spec.filetype, input, urlBackstage);
  19790. var tdata = build$2(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  19791. return Future.pure(tdata);
  19792. },
  19793. getHotspot: function (comp) {
  19794. return memUrlBox.getOpt(comp);
  19795. },
  19796. onSetValue: function (comp, newValue) {
  19797. if (comp.hasConfigured(Invalidating)) {
  19798. Invalidating.run(comp).get(noop);
  19799. }
  19800. },
  19801. typeaheadBehaviours: derive$1(flatten([
  19802. urlBackstage.getValidationHandler().map(function (handler) {
  19803. return Invalidating.config({
  19804. getRoot: function (comp) {
  19805. return parent(comp.element());
  19806. },
  19807. invalidClass: 'tox-control-wrap--status-invalid',
  19808. notify: {
  19809. onInvalid: function (comp, err) {
  19810. memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  19811. set$1(invalidComp.element(), 'title', providersBackstage.translate(err));
  19812. });
  19813. }
  19814. },
  19815. validator: {
  19816. validate: function (input) {
  19817. var urlEntry = Representing.getValue(input);
  19818. return FutureResult.nu(function (completer) {
  19819. handler({
  19820. type: spec.filetype,
  19821. url: urlEntry.value
  19822. }, function (validation) {
  19823. if (validation.status === 'invalid') {
  19824. var err = Result.error(validation.message);
  19825. completer(err);
  19826. } else {
  19827. var val = Result.value(validation.message);
  19828. completer(val);
  19829. }
  19830. });
  19831. });
  19832. },
  19833. validateOnLoad: false
  19834. }
  19835. });
  19836. }).toArray(),
  19837. [
  19838. Disabling.config({ disabled: spec.disabled }),
  19839. Tabstopping.config({}),
  19840. config('urlinput-events', flatten([
  19841. spec.filetype === 'file' ? [run(input(), function (comp) {
  19842. emitWith(comp, formChangeEvent, { name: spec.name });
  19843. })] : [],
  19844. [
  19845. run(change(), function (comp) {
  19846. emitWith(comp, formChangeEvent, { name: spec.name });
  19847. updateHistory(comp);
  19848. }),
  19849. run(postPaste(), function (comp) {
  19850. emitWith(comp, formChangeEvent, { name: spec.name });
  19851. updateHistory(comp);
  19852. })
  19853. ]
  19854. ]))
  19855. ]
  19856. ])),
  19857. eventOrder: (_a = {}, _a[input()] = [
  19858. 'streaming',
  19859. 'urlinput-events',
  19860. 'invalidating'
  19861. ], _a),
  19862. model: {
  19863. getDisplayText: function (itemData) {
  19864. return itemData.value;
  19865. },
  19866. selectsOver: false,
  19867. populateFromBrowse: false
  19868. },
  19869. markers: { openClass: 'tox-textfield--popup-open' },
  19870. lazySink: backstage.shared.getSink,
  19871. parts: { menu: part(false, 1, 'normal') },
  19872. onExecute: function (_menu, component, _entry) {
  19873. emitWith(component, formSubmitEvent, {});
  19874. },
  19875. onItemExecute: function (typeahead, _sandbox, _item, _value) {
  19876. updateHistory(typeahead);
  19877. emitWith(typeahead, formChangeEvent, { name: spec.name });
  19878. }
  19879. });
  19880. var pLabel = spec.label.map(function (label) {
  19881. return renderLabel(label, providersBackstage);
  19882. });
  19883. var makeIcon = function (name, errId, icon, label) {
  19884. if (icon === void 0) {
  19885. icon = name;
  19886. }
  19887. if (label === void 0) {
  19888. label = name;
  19889. }
  19890. return {
  19891. dom: {
  19892. tag: 'div',
  19893. classes: [
  19894. 'tox-icon',
  19895. 'tox-control-wrap__status-icon-' + name
  19896. ],
  19897. innerHtml: get$c(icon, providersBackstage.icons),
  19898. attributes: __assign({
  19899. 'title': providersBackstage.translate(label),
  19900. 'aria-live': 'polite'
  19901. }, errId.fold(function () {
  19902. return {};
  19903. }, function (id) {
  19904. return { id: id };
  19905. }))
  19906. }
  19907. };
  19908. };
  19909. var memInvalidIcon = record(makeIcon('invalid', Option.some(errorId), 'warning'));
  19910. var memStatus = record({
  19911. dom: {
  19912. tag: 'div',
  19913. classes: ['tox-control-wrap__status-icon-wrap']
  19914. },
  19915. components: [memInvalidIcon.asSpec()]
  19916. });
  19917. var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  19918. var browseUrlEvent = generate$1('browser.url.event');
  19919. var memUrlBox = record({
  19920. dom: {
  19921. tag: 'div',
  19922. classes: ['tox-control-wrap']
  19923. },
  19924. components: [
  19925. pField,
  19926. memStatus.asSpec()
  19927. ],
  19928. behaviours: derive$1([Disabling.config({ disabled: spec.disabled })])
  19929. });
  19930. var memUrlPickerButton = record(renderButton({
  19931. name: spec.name,
  19932. icon: Option.some('browse'),
  19933. text: spec.label.getOr(''),
  19934. disabled: spec.disabled,
  19935. primary: false,
  19936. borderless: true
  19937. }, function (component) {
  19938. return emit(component, browseUrlEvent);
  19939. }, providersBackstage, [], ['tox-browse-url']));
  19940. var controlHWrapper = function () {
  19941. return {
  19942. dom: {
  19943. tag: 'div',
  19944. classes: ['tox-form__controls-h-stack']
  19945. },
  19946. components: flatten([
  19947. [memUrlBox.asSpec()],
  19948. optUrlPicker.map(function () {
  19949. return memUrlPickerButton.asSpec();
  19950. }).toArray()
  19951. ])
  19952. };
  19953. };
  19954. var openUrlPicker = function (comp) {
  19955. Composing.getCurrent(comp).each(function (field) {
  19956. var urlData = Representing.getValue(field);
  19957. optUrlPicker.each(function (picker) {
  19958. picker(urlData).get(function (chosenData) {
  19959. Representing.setValue(field, chosenData);
  19960. emitWith(comp, formChangeEvent, { name: spec.name });
  19961. });
  19962. });
  19963. });
  19964. };
  19965. return FormField.sketch({
  19966. dom: renderFormFieldDom(),
  19967. components: pLabel.toArray().concat([controlHWrapper()]),
  19968. fieldBehaviours: derive$1([
  19969. Disabling.config({
  19970. disabled: spec.disabled,
  19971. onDisabled: function (comp) {
  19972. FormField.getField(comp).each(Disabling.disable);
  19973. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  19974. },
  19975. onEnabled: function (comp) {
  19976. FormField.getField(comp).each(Disabling.enable);
  19977. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  19978. }
  19979. }),
  19980. config('url-input-events', [run(browseUrlEvent, openUrlPicker)])
  19981. ])
  19982. });
  19983. };
  19984. var renderCheckbox = function (spec, providerBackstage) {
  19985. var repBehaviour = Representing.config({
  19986. store: {
  19987. mode: 'manual',
  19988. getValue: function (comp) {
  19989. var el = comp.element().dom();
  19990. return el.checked;
  19991. },
  19992. setValue: function (comp, value) {
  19993. var el = comp.element().dom();
  19994. el.checked = value;
  19995. }
  19996. }
  19997. });
  19998. var toggleCheckboxHandler = function (comp) {
  19999. comp.element().dom().click();
  20000. return Option.some(true);
  20001. };
  20002. var pField = FormField.parts().field({
  20003. factory: { sketch: identity },
  20004. dom: {
  20005. tag: 'input',
  20006. classes: ['tox-checkbox__input'],
  20007. attributes: { type: 'checkbox' }
  20008. },
  20009. behaviours: derive$1([
  20010. ComposingConfigs.self(),
  20011. Disabling.config({ disabled: spec.disabled }),
  20012. Tabstopping.config({}),
  20013. Focusing.config({}),
  20014. repBehaviour,
  20015. Keying.config({
  20016. mode: 'special',
  20017. onEnter: toggleCheckboxHandler,
  20018. onSpace: toggleCheckboxHandler,
  20019. stopSpaceKeyup: true
  20020. }),
  20021. config('checkbox-events', [run(change(), function (component, _) {
  20022. emitWith(component, formChangeEvent, { name: spec.name });
  20023. })])
  20024. ])
  20025. });
  20026. var pLabel = FormField.parts().label({
  20027. dom: {
  20028. tag: 'span',
  20029. classes: ['tox-checkbox__label'],
  20030. innerHtml: providerBackstage.translate(spec.label)
  20031. },
  20032. behaviours: derive$1([Unselecting.config({})])
  20033. });
  20034. var makeIcon = function (className) {
  20035. var iconName = className === 'checked' ? 'selected' : 'unselected';
  20036. return {
  20037. dom: {
  20038. tag: 'span',
  20039. classes: [
  20040. 'tox-icon',
  20041. 'tox-checkbox-icon__' + className
  20042. ],
  20043. innerHtml: get$c(iconName, providerBackstage.icons)
  20044. }
  20045. };
  20046. };
  20047. var memIcons = record({
  20048. dom: {
  20049. tag: 'div',
  20050. classes: ['tox-checkbox__icons']
  20051. },
  20052. components: [
  20053. makeIcon('checked'),
  20054. makeIcon('unchecked')
  20055. ]
  20056. });
  20057. return FormField.sketch({
  20058. dom: {
  20059. tag: 'label',
  20060. classes: ['tox-checkbox']
  20061. },
  20062. components: [
  20063. pField,
  20064. memIcons.asSpec(),
  20065. pLabel
  20066. ],
  20067. fieldBehaviours: derive$1([Disabling.config({
  20068. disabled: spec.disabled,
  20069. disableClass: 'tox-checkbox--disabled',
  20070. onDisabled: function (comp) {
  20071. FormField.getField(comp).each(Disabling.disable);
  20072. },
  20073. onEnabled: function (comp) {
  20074. FormField.getField(comp).each(Disabling.enable);
  20075. }
  20076. })])
  20077. });
  20078. };
  20079. var renderHtmlPanel = function (spec) {
  20080. if (spec.presets === 'presentation') {
  20081. return Container.sketch({
  20082. dom: {
  20083. tag: 'div',
  20084. classes: ['tox-form__group'],
  20085. innerHtml: spec.html
  20086. }
  20087. });
  20088. } else {
  20089. return Container.sketch({
  20090. dom: {
  20091. tag: 'div',
  20092. classes: ['tox-form__group'],
  20093. innerHtml: spec.html,
  20094. attributes: { role: 'document' }
  20095. },
  20096. containerBehaviours: derive$1([
  20097. Tabstopping.config({}),
  20098. Focusing.config({})
  20099. ])
  20100. });
  20101. }
  20102. };
  20103. var renderLabel$2 = function (spec, backstageShared) {
  20104. var label = {
  20105. dom: {
  20106. tag: 'label',
  20107. innerHtml: backstageShared.providers.translate(spec.label),
  20108. classes: ['tox-label']
  20109. }
  20110. };
  20111. var comps = map(spec.items, backstageShared.interpreter);
  20112. return {
  20113. dom: {
  20114. tag: 'div',
  20115. classes: ['tox-form__group']
  20116. },
  20117. components: [label].concat(comps),
  20118. behaviours: derive$1([
  20119. ComposingConfigs.self(),
  20120. Replacing.config({}),
  20121. RepresentingConfigs.domHtml(Option.none()),
  20122. Keying.config({ mode: 'acyclic' })
  20123. ])
  20124. };
  20125. };
  20126. var renderCollection = function (spec, providersBackstage) {
  20127. var pLabel = spec.label.map(function (label) {
  20128. return renderLabel(label, providersBackstage);
  20129. });
  20130. var runOnItem = function (f) {
  20131. return function (comp, se) {
  20132. closest$3(se.event().target(), '[data-collection-item-value]').each(function (target) {
  20133. f(comp, target, get$2(target, 'data-collection-item-value'));
  20134. });
  20135. };
  20136. };
  20137. var escapeAttribute = function (ch) {
  20138. if (ch === '"') {
  20139. return '&quot;';
  20140. }
  20141. return ch;
  20142. };
  20143. var setContents = function (comp, items) {
  20144. var htmlLines = map(items, function (item) {
  20145. var itemText = global$5.translate(item.text);
  20146. var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  20147. var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  20148. var mapItemName = {
  20149. '_': ' ',
  20150. ' - ': ' ',
  20151. '-': ' '
  20152. };
  20153. var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  20154. return mapItemName[match];
  20155. });
  20156. return '<div class="tox-collection__item" tabindex="-1" data-collection-item-value="' + escapeAttribute(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  20157. });
  20158. var chunks = spec.columns > 1 && spec.columns !== 'auto' ? chunk(htmlLines, spec.columns) : [htmlLines];
  20159. var html = map(chunks, function (ch) {
  20160. return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  20161. });
  20162. set(comp.element(), html.join(''));
  20163. };
  20164. var collectionEvents = [
  20165. run(mouseover(), runOnItem(function (comp, tgt) {
  20166. focus$1(tgt);
  20167. })),
  20168. run(tapOrClick(), runOnItem(function (comp, tgt, itemValue) {
  20169. emitWith(comp, formActionEvent, {
  20170. name: spec.name,
  20171. value: itemValue
  20172. });
  20173. })),
  20174. run(focusin(), runOnItem(function (comp, tgt, itemValue) {
  20175. descendant$1(comp.element(), '.' + activeClass).each(function (currentActive) {
  20176. remove$4(currentActive, activeClass);
  20177. });
  20178. add$2(tgt, activeClass);
  20179. })),
  20180. run(focusout(), runOnItem(function (comp, tgt, itemValue) {
  20181. descendant$1(comp.element(), '.' + activeClass).each(function (currentActive) {
  20182. remove$4(currentActive, activeClass);
  20183. });
  20184. })),
  20185. runOnExecute(runOnItem(function (comp, tgt, itemValue) {
  20186. emitWith(comp, formActionEvent, {
  20187. name: spec.name,
  20188. value: itemValue
  20189. });
  20190. }))
  20191. ];
  20192. var pField = FormField.parts().field({
  20193. dom: {
  20194. tag: 'div',
  20195. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  20196. },
  20197. components: [],
  20198. factory: { sketch: identity },
  20199. behaviours: derive$1([
  20200. Replacing.config({}),
  20201. Representing.config({
  20202. store: {
  20203. mode: 'memory',
  20204. initialValue: []
  20205. },
  20206. onSetValue: function (comp, items) {
  20207. setContents(comp, items);
  20208. if (spec.columns === 'auto') {
  20209. detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  20210. var numRows = _a.numRows, numColumns = _a.numColumns;
  20211. Keying.setGridSize(comp, numRows, numColumns);
  20212. });
  20213. }
  20214. emit(comp, formResizeEvent);
  20215. }
  20216. }),
  20217. Tabstopping.config({}),
  20218. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  20219. config('collection-events', collectionEvents)
  20220. ])
  20221. });
  20222. var extraClasses = ['tox-form__group--collection'];
  20223. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  20224. };
  20225. var renderTable = function (spec, providersBackstage) {
  20226. var renderTh = function (text) {
  20227. return {
  20228. dom: {
  20229. tag: 'th',
  20230. innerHtml: providersBackstage.translate(text)
  20231. }
  20232. };
  20233. };
  20234. var renderHeader = function (header) {
  20235. return {
  20236. dom: { tag: 'thead' },
  20237. components: [{
  20238. dom: { tag: 'tr' },
  20239. components: map(header, renderTh)
  20240. }]
  20241. };
  20242. };
  20243. var renderTd = function (text) {
  20244. return {
  20245. dom: {
  20246. tag: 'td',
  20247. innerHtml: providersBackstage.translate(text)
  20248. }
  20249. };
  20250. };
  20251. var renderTr = function (row) {
  20252. return {
  20253. dom: { tag: 'tr' },
  20254. components: map(row, renderTd)
  20255. };
  20256. };
  20257. var renderRows = function (rows) {
  20258. return {
  20259. dom: { tag: 'tbody' },
  20260. components: map(rows, renderTr)
  20261. };
  20262. };
  20263. return {
  20264. dom: {
  20265. tag: 'table',
  20266. classes: ['tox-dialog__table']
  20267. },
  20268. components: [
  20269. renderHeader(spec.header),
  20270. renderRows(spec.cells)
  20271. ],
  20272. behaviours: derive$1([
  20273. Tabstopping.config({}),
  20274. Focusing.config({})
  20275. ])
  20276. };
  20277. };
  20278. var renderPanel = function (spec, backstage) {
  20279. return {
  20280. dom: {
  20281. tag: 'div',
  20282. classes: spec.classes
  20283. },
  20284. components: map(spec.items, backstage.shared.interpreter)
  20285. };
  20286. };
  20287. var make$6 = function (render) {
  20288. return function (parts, spec, backstage) {
  20289. return readOptFrom$1(spec, 'name').fold(function () {
  20290. return render(spec, backstage);
  20291. }, function (fieldName) {
  20292. return parts.field(fieldName, render(spec, backstage));
  20293. });
  20294. };
  20295. };
  20296. var makeIframe = function (render) {
  20297. return function (parts, spec, backstage) {
  20298. var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  20299. return make$6(render)(parts, iframeSpec, backstage);
  20300. };
  20301. };
  20302. var factories = {
  20303. bar: make$6(function (spec, backstage) {
  20304. return renderBar(spec, backstage.shared);
  20305. }),
  20306. collection: make$6(function (spec, backstage) {
  20307. return renderCollection(spec, backstage.shared.providers);
  20308. }),
  20309. alertbanner: make$6(function (spec, backstage) {
  20310. return renderAlertBanner(spec, backstage.shared.providers);
  20311. }),
  20312. input: make$6(function (spec, backstage) {
  20313. return renderInput(spec, backstage.shared.providers);
  20314. }),
  20315. textarea: make$6(function (spec, backstage) {
  20316. return renderTextarea(spec, backstage.shared.providers);
  20317. }),
  20318. label: make$6(function (spec, backstage) {
  20319. return renderLabel$2(spec, backstage.shared);
  20320. }),
  20321. iframe: makeIframe(function (spec, backstage) {
  20322. return renderIFrame(spec, backstage.shared.providers);
  20323. }),
  20324. button: make$6(function (spec, backstage) {
  20325. return renderDialogButton(spec, backstage.shared.providers);
  20326. }),
  20327. checkbox: make$6(function (spec, backstage) {
  20328. return renderCheckbox(spec, backstage.shared.providers);
  20329. }),
  20330. colorinput: make$6(function (spec, backstage) {
  20331. return renderColorInput(spec, backstage.shared, backstage.colorinput);
  20332. }),
  20333. colorpicker: make$6(renderColorPicker),
  20334. dropzone: make$6(function (spec, backstage) {
  20335. return renderDropZone(spec, backstage.shared.providers);
  20336. }),
  20337. grid: make$6(function (spec, backstage) {
  20338. return renderGrid(spec, backstage.shared);
  20339. }),
  20340. selectbox: make$6(function (spec, backstage) {
  20341. return renderSelectBox(spec, backstage.shared.providers);
  20342. }),
  20343. sizeinput: make$6(function (spec, backstage) {
  20344. return renderSizeInput(spec, backstage.shared.providers);
  20345. }),
  20346. urlinput: make$6(function (spec, backstage) {
  20347. return renderUrlInput(spec, backstage, backstage.urlinput);
  20348. }),
  20349. customeditor: make$6(renderCustomEditor),
  20350. htmlpanel: make$6(renderHtmlPanel),
  20351. imagetools: make$6(function (spec, backstage) {
  20352. return renderImageTools(spec, backstage.shared.providers);
  20353. }),
  20354. table: make$6(function (spec, backstage) {
  20355. return renderTable(spec, backstage.shared.providers);
  20356. }),
  20357. panel: make$6(function (spec, backstage) {
  20358. return renderPanel(spec, backstage);
  20359. })
  20360. };
  20361. var noFormParts = {
  20362. field: function (_name, spec) {
  20363. return spec;
  20364. }
  20365. };
  20366. var interpretInForm = function (parts, spec, oldBackstage) {
  20367. var newBackstage = deepMerge(oldBackstage, {
  20368. shared: {
  20369. interpreter: function (childSpec) {
  20370. return interpretParts(parts, childSpec, newBackstage);
  20371. }
  20372. }
  20373. });
  20374. return interpretParts(parts, spec, newBackstage);
  20375. };
  20376. var interpretParts = function (parts, spec, backstage) {
  20377. return readOptFrom$1(factories, spec.type).fold(function () {
  20378. domGlobals.console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  20379. return spec;
  20380. }, function (factory) {
  20381. return factory(parts, spec, backstage);
  20382. });
  20383. };
  20384. var interpretWithoutForm = function (spec, backstage) {
  20385. var parts = noFormParts;
  20386. return interpretParts(parts, spec, backstage);
  20387. };
  20388. var expandable$1 = constant(function (element, available) {
  20389. setMax$1(element, Math.floor(available));
  20390. });
  20391. var bubbleAlignments = {
  20392. valignCentre: [],
  20393. alignCentre: [],
  20394. alignLeft: [],
  20395. alignRight: [],
  20396. right: [],
  20397. left: [],
  20398. bottom: [],
  20399. top: []
  20400. };
  20401. var getToolbarAnchor = function (bodyElement, lazyAnchorbar, useFixedToolbarContainer) {
  20402. var fixedToolbarAnchor = function () {
  20403. return {
  20404. anchor: 'node',
  20405. root: bodyElement(),
  20406. node: Option.from(bodyElement()),
  20407. bubble: nu$8(-12, -12, bubbleAlignments),
  20408. layouts: {
  20409. onRtl: function () {
  20410. return [northeast$3];
  20411. },
  20412. onLtr: function () {
  20413. return [northwest$3];
  20414. }
  20415. },
  20416. overrides: { maxHeightFunction: expandable() }
  20417. };
  20418. };
  20419. var standardAnchor = function () {
  20420. return {
  20421. anchor: 'hotspot',
  20422. hotspot: lazyAnchorbar(),
  20423. bubble: nu$8(-12, 12, bubbleAlignments),
  20424. layouts: {
  20425. onRtl: function () {
  20426. return [southeast$1];
  20427. },
  20428. onLtr: function () {
  20429. return [southwest$1];
  20430. }
  20431. },
  20432. overrides: { maxHeightFunction: expandable() }
  20433. };
  20434. };
  20435. return useFixedToolbarContainer ? fixedToolbarAnchor : standardAnchor;
  20436. };
  20437. var getBannerAnchor = function (bodyElement, lazyAnchorbar, useFixedToolbarContainer) {
  20438. var fixedToolbarAnchor = function () {
  20439. return {
  20440. anchor: 'node',
  20441. root: bodyElement(),
  20442. node: Option.from(bodyElement()),
  20443. layouts: {
  20444. onRtl: function () {
  20445. return [north$3];
  20446. },
  20447. onLtr: function () {
  20448. return [north$3];
  20449. }
  20450. }
  20451. };
  20452. };
  20453. var standardAnchor = function () {
  20454. return {
  20455. anchor: 'hotspot',
  20456. hotspot: lazyAnchorbar(),
  20457. layouts: {
  20458. onRtl: function () {
  20459. return [south$1];
  20460. },
  20461. onLtr: function () {
  20462. return [south$1];
  20463. }
  20464. }
  20465. };
  20466. };
  20467. return useFixedToolbarContainer ? fixedToolbarAnchor : standardAnchor;
  20468. };
  20469. var getToolbarOverflowAnchor = function (lazyMoreButton) {
  20470. return function () {
  20471. return {
  20472. anchor: 'hotspot',
  20473. hotspot: lazyMoreButton(),
  20474. overrides: { maxWidthFunction: expandable$1() },
  20475. layouts: {
  20476. onRtl: function () {
  20477. return [
  20478. southeast$1,
  20479. southwest$1
  20480. ];
  20481. },
  20482. onLtr: function () {
  20483. return [
  20484. southwest$1,
  20485. southeast$1
  20486. ];
  20487. }
  20488. }
  20489. };
  20490. };
  20491. };
  20492. var getCursorAnchor = function (editor, bodyElement) {
  20493. return function () {
  20494. return {
  20495. anchor: 'selection',
  20496. root: bodyElement(),
  20497. getSelection: function () {
  20498. var rng = editor.selection.getRng();
  20499. return Option.some(Selection.range(Element.fromDom(rng.startContainer), rng.startOffset, Element.fromDom(rng.endContainer), rng.endOffset));
  20500. }
  20501. };
  20502. };
  20503. };
  20504. var getNodeAnchor = function (bodyElement) {
  20505. return function (element) {
  20506. return {
  20507. anchor: 'node',
  20508. root: bodyElement(),
  20509. node: element
  20510. };
  20511. };
  20512. };
  20513. var getAnchors = function (editor, lazyAnchorbar, lazyMoreButton) {
  20514. var useFixedToolbarContainer = useFixedContainer(editor);
  20515. var bodyElement = function () {
  20516. return Element.fromDom(editor.getBody());
  20517. };
  20518. return {
  20519. toolbar: getToolbarAnchor(bodyElement, lazyAnchorbar, useFixedToolbarContainer),
  20520. toolbarOverflow: getToolbarOverflowAnchor(lazyMoreButton),
  20521. banner: getBannerAnchor(bodyElement, lazyAnchorbar, useFixedToolbarContainer),
  20522. cursor: getCursorAnchor(editor, bodyElement),
  20523. node: getNodeAnchor(bodyElement)
  20524. };
  20525. };
  20526. var Anchors = { getAnchors: getAnchors };
  20527. var colorPicker = function (editor) {
  20528. return function (callback, value) {
  20529. var dialog = ColorSwatch.colorPickerDialog(editor);
  20530. dialog(callback, value);
  20531. };
  20532. };
  20533. var hasCustomColors$1 = function (editor) {
  20534. return function () {
  20535. return Settings.hasCustomColors(editor);
  20536. };
  20537. };
  20538. var getColors$1 = function (editor) {
  20539. return function () {
  20540. return Settings.getColors(editor);
  20541. };
  20542. };
  20543. var getColorCols$2 = function (editor) {
  20544. return function () {
  20545. return ColorSwatch.getColorCols(editor);
  20546. };
  20547. };
  20548. var ColorInputBackstage = function (editor) {
  20549. return {
  20550. colorPicker: colorPicker(editor),
  20551. hasCustomColors: hasCustomColors$1(editor),
  20552. getColors: getColors$1(editor),
  20553. getColorCols: getColorCols$2(editor)
  20554. };
  20555. };
  20556. var isDraggableModal$1 = function (editor) {
  20557. return function () {
  20558. return isDraggableModal(editor);
  20559. };
  20560. };
  20561. var DialogBackstage = function (editor) {
  20562. return { isDraggableModal: isDraggableModal$1(editor) };
  20563. };
  20564. var defaultStyleFormats = [
  20565. {
  20566. title: 'Headings',
  20567. items: [
  20568. {
  20569. title: 'Heading 1',
  20570. format: 'h1'
  20571. },
  20572. {
  20573. title: 'Heading 2',
  20574. format: 'h2'
  20575. },
  20576. {
  20577. title: 'Heading 3',
  20578. format: 'h3'
  20579. },
  20580. {
  20581. title: 'Heading 4',
  20582. format: 'h4'
  20583. },
  20584. {
  20585. title: 'Heading 5',
  20586. format: 'h5'
  20587. },
  20588. {
  20589. title: 'Heading 6',
  20590. format: 'h6'
  20591. }
  20592. ]
  20593. },
  20594. {
  20595. title: 'Inline',
  20596. items: [
  20597. {
  20598. title: 'Bold',
  20599. icon: 'bold',
  20600. format: 'bold'
  20601. },
  20602. {
  20603. title: 'Italic',
  20604. icon: 'italic',
  20605. format: 'italic'
  20606. },
  20607. {
  20608. title: 'Underline',
  20609. icon: 'underline',
  20610. format: 'underline'
  20611. },
  20612. {
  20613. title: 'Strikethrough',
  20614. icon: 'strike-through',
  20615. format: 'strikethrough'
  20616. },
  20617. {
  20618. title: 'Superscript',
  20619. icon: 'superscript',
  20620. format: 'superscript'
  20621. },
  20622. {
  20623. title: 'Subscript',
  20624. icon: 'subscript',
  20625. format: 'subscript'
  20626. },
  20627. {
  20628. title: 'Code',
  20629. icon: 'code',
  20630. format: 'code'
  20631. }
  20632. ]
  20633. },
  20634. {
  20635. title: 'Blocks',
  20636. items: [
  20637. {
  20638. title: 'Paragraph',
  20639. format: 'p'
  20640. },
  20641. {
  20642. title: 'Blockquote',
  20643. format: 'blockquote'
  20644. },
  20645. {
  20646. title: 'Div',
  20647. format: 'div'
  20648. },
  20649. {
  20650. title: 'Pre',
  20651. format: 'pre'
  20652. }
  20653. ]
  20654. },
  20655. {
  20656. title: 'Align',
  20657. items: [
  20658. {
  20659. title: 'Left',
  20660. icon: 'align-left',
  20661. format: 'alignleft'
  20662. },
  20663. {
  20664. title: 'Center',
  20665. icon: 'align-center',
  20666. format: 'aligncenter'
  20667. },
  20668. {
  20669. title: 'Right',
  20670. icon: 'align-right',
  20671. format: 'alignright'
  20672. },
  20673. {
  20674. title: 'Justify',
  20675. icon: 'align-justify',
  20676. format: 'alignjustify'
  20677. }
  20678. ]
  20679. }
  20680. ];
  20681. var isNestedFormat = function (format) {
  20682. return has(format, 'items');
  20683. };
  20684. var isBlockFormat = function (format) {
  20685. return has(format, 'block');
  20686. };
  20687. var isInlineFormat = function (format) {
  20688. return has(format, 'inline');
  20689. };
  20690. var isSelectorFormat = function (format) {
  20691. return has(format, 'selector');
  20692. };
  20693. var mapFormats = function (userFormats) {
  20694. return foldl(userFormats, function (acc, fmt) {
  20695. if (isNestedFormat(fmt)) {
  20696. var result = mapFormats(fmt.items);
  20697. return {
  20698. customFormats: acc.customFormats.concat(result.customFormats),
  20699. formats: acc.formats.concat([{
  20700. title: fmt.title,
  20701. items: result.formats
  20702. }])
  20703. };
  20704. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  20705. var formatName = 'custom-' + fmt.title.toLowerCase();
  20706. return {
  20707. customFormats: acc.customFormats.concat([{
  20708. name: formatName,
  20709. format: fmt
  20710. }]),
  20711. formats: acc.formats.concat([{
  20712. title: fmt.title,
  20713. format: formatName,
  20714. icon: fmt.icon
  20715. }])
  20716. };
  20717. } else {
  20718. return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  20719. }
  20720. }, {
  20721. customFormats: [],
  20722. formats: []
  20723. });
  20724. };
  20725. var registerCustomFormats = function (editor, userFormats) {
  20726. var result = mapFormats(userFormats);
  20727. var registerFormats = function (customFormats) {
  20728. each(customFormats, function (fmt) {
  20729. if (!editor.formatter.has(fmt.name)) {
  20730. editor.formatter.register(fmt.name, fmt.format);
  20731. }
  20732. });
  20733. };
  20734. if (editor.formatter) {
  20735. registerFormats(result.customFormats);
  20736. } else {
  20737. editor.on('init', function () {
  20738. registerFormats(result.customFormats);
  20739. });
  20740. }
  20741. return result.formats;
  20742. };
  20743. var getStyleFormats = function (editor) {
  20744. return getUserStyleFormats(editor).map(function (userFormats) {
  20745. var registeredUserFormats = registerCustomFormats(editor, userFormats);
  20746. return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  20747. }).getOr(defaultStyleFormats);
  20748. };
  20749. var processBasic = function (item, isSelectedFor, getPreviewFor) {
  20750. var formatterSpec = {
  20751. type: 'formatter',
  20752. isSelected: isSelectedFor(item.format),
  20753. getStylePreview: getPreviewFor(item.format)
  20754. };
  20755. return deepMerge(item, formatterSpec);
  20756. };
  20757. var register$3 = function (editor, formats, isSelectedFor, getPreviewFor) {
  20758. var enrichSupported = function (item) {
  20759. return processBasic(item, isSelectedFor, getPreviewFor);
  20760. };
  20761. var enrichMenu = function (item) {
  20762. var submenuSpec = {
  20763. type: 'submenu',
  20764. isSelected: constant(false),
  20765. getStylePreview: function () {
  20766. return Option.none();
  20767. }
  20768. };
  20769. return deepMerge(item, submenuSpec);
  20770. };
  20771. var enrichCustom = function (item) {
  20772. var formatName = generate$1(item.title);
  20773. var customSpec = {
  20774. type: 'formatter',
  20775. format: formatName,
  20776. isSelected: isSelectedFor(formatName),
  20777. getStylePreview: getPreviewFor(formatName)
  20778. };
  20779. var newItem = deepMerge(item, customSpec);
  20780. editor.formatter.register(formatName, newItem);
  20781. return newItem;
  20782. };
  20783. var doEnrich = function (items) {
  20784. return map(items, function (item) {
  20785. var keys$1 = keys(item);
  20786. if (hasKey$1(item, 'items')) {
  20787. var newItems_1 = doEnrich(item.items);
  20788. return deepMerge(enrichMenu(item), {
  20789. getStyleItems: function () {
  20790. return newItems_1;
  20791. }
  20792. });
  20793. } else if (hasKey$1(item, 'format')) {
  20794. return enrichSupported(item);
  20795. } else if (keys$1.length === 1 && contains(keys$1, 'title')) {
  20796. return deepMerge(item, { type: 'separator' });
  20797. } else {
  20798. return enrichCustom(item);
  20799. }
  20800. });
  20801. };
  20802. return doEnrich(formats);
  20803. };
  20804. var init$7 = function (editor) {
  20805. var isSelectedFor = function (format) {
  20806. return function () {
  20807. return editor.formatter.match(format);
  20808. };
  20809. };
  20810. var getPreviewFor = function (format) {
  20811. return function () {
  20812. var fmt = editor.formatter.get(format);
  20813. return fmt !== undefined ? Option.some({
  20814. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  20815. styleAttr: editor.formatter.getCssText(format)
  20816. }) : Option.none();
  20817. };
  20818. };
  20819. var flatten = function (fmt) {
  20820. var subs = fmt.items;
  20821. return subs !== undefined && subs.length > 0 ? bind(subs, flatten) : [fmt.format];
  20822. };
  20823. var settingsFormats = Cell([]);
  20824. var settingsFlattenedFormats = Cell([]);
  20825. var eventsFormats = Cell([]);
  20826. var eventsFlattenedFormats = Cell([]);
  20827. var replaceSettings = Cell(false);
  20828. editor.on('init', function () {
  20829. var formats = getStyleFormats(editor);
  20830. var enriched = register$3(editor, formats, isSelectedFor, getPreviewFor);
  20831. settingsFormats.set(enriched);
  20832. settingsFlattenedFormats.set(bind(enriched, flatten));
  20833. });
  20834. editor.on('addStyleModifications', function (e) {
  20835. var modifications = register$3(editor, e.items, isSelectedFor, getPreviewFor);
  20836. eventsFormats.set(modifications);
  20837. replaceSettings.set(e.replace);
  20838. eventsFlattenedFormats.set(bind(modifications, flatten));
  20839. });
  20840. var getData = function () {
  20841. var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  20842. var fromEvents = eventsFormats.get();
  20843. return fromSettings.concat(fromEvents);
  20844. };
  20845. var getFlattenedKeys = function () {
  20846. var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  20847. var fromEvents = eventsFlattenedFormats.get();
  20848. return fromSettings.concat(fromEvents);
  20849. };
  20850. return {
  20851. getData: getData,
  20852. getFlattenedKeys: getFlattenedKeys
  20853. };
  20854. };
  20855. var trim$1 = global$e.trim;
  20856. var hasContentEditableState = function (value) {
  20857. return function (node) {
  20858. if (node && node.nodeType === 1) {
  20859. if (node.contentEditable === value) {
  20860. return true;
  20861. }
  20862. if (node.getAttribute('data-mce-contenteditable') === value) {
  20863. return true;
  20864. }
  20865. }
  20866. return false;
  20867. };
  20868. };
  20869. var isContentEditableTrue = hasContentEditableState('true');
  20870. var isContentEditableFalse = hasContentEditableState('false');
  20871. var create$8 = function (type, title, url, level, attach) {
  20872. return {
  20873. type: type,
  20874. title: title,
  20875. url: url,
  20876. level: level,
  20877. attach: attach
  20878. };
  20879. };
  20880. var isChildOfContentEditableTrue = function (node) {
  20881. while (node = node.parentNode) {
  20882. var value = node.contentEditable;
  20883. if (value && value !== 'inherit') {
  20884. return isContentEditableTrue(node);
  20885. }
  20886. }
  20887. return false;
  20888. };
  20889. var select = function (selector, root) {
  20890. return map(descendants(Element.fromDom(root), selector), function (element) {
  20891. return element.dom();
  20892. });
  20893. };
  20894. var getElementText = function (elm) {
  20895. return elm.innerText || elm.textContent;
  20896. };
  20897. var getOrGenerateId = function (elm) {
  20898. return elm.id ? elm.id : generate$1('h');
  20899. };
  20900. var isAnchor = function (elm) {
  20901. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  20902. };
  20903. var isValidAnchor = function (elm) {
  20904. return isAnchor(elm) && isEditable(elm);
  20905. };
  20906. var isHeader = function (elm) {
  20907. return elm && /^(H[1-6])$/.test(elm.nodeName);
  20908. };
  20909. var isEditable = function (elm) {
  20910. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  20911. };
  20912. var isValidHeader = function (elm) {
  20913. return isHeader(elm) && isEditable(elm);
  20914. };
  20915. var getLevel = function (elm) {
  20916. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  20917. };
  20918. var headerTarget = function (elm) {
  20919. var headerId = getOrGenerateId(elm);
  20920. var attach = function () {
  20921. elm.id = headerId;
  20922. };
  20923. return create$8('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  20924. };
  20925. var anchorTarget = function (elm) {
  20926. var anchorId = elm.id || elm.name;
  20927. var anchorText = getElementText(elm);
  20928. return create$8('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  20929. };
  20930. var getHeaderTargets = function (elms) {
  20931. return map(filter(elms, isValidHeader), headerTarget);
  20932. };
  20933. var getAnchorTargets = function (elms) {
  20934. return map(filter(elms, isValidAnchor), anchorTarget);
  20935. };
  20936. var getTargetElements = function (elm) {
  20937. var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  20938. return elms;
  20939. };
  20940. var hasTitle = function (target) {
  20941. return trim$1(target.title).length > 0;
  20942. };
  20943. var find$5 = function (elm) {
  20944. var elms = getTargetElements(elm);
  20945. return filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  20946. };
  20947. var LinkTargets = { find: find$5 };
  20948. var STORAGE_KEY = 'tinymce-url-history';
  20949. var HISTORY_LENGTH = 5;
  20950. var isHttpUrl = function (url) {
  20951. return isString(url) && /^https?/.test(url);
  20952. };
  20953. var isArrayOfUrl = function (a) {
  20954. return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  20955. };
  20956. var isRecordOfUrlArray = function (r) {
  20957. return isObject(r) && find$1(r, function (value) {
  20958. return !isArrayOfUrl(value);
  20959. }).isNone();
  20960. };
  20961. var getAllHistory = function () {
  20962. var unparsedHistory = domGlobals.localStorage.getItem(STORAGE_KEY);
  20963. if (unparsedHistory === null) {
  20964. return {};
  20965. }
  20966. var history;
  20967. try {
  20968. history = JSON.parse(unparsedHistory);
  20969. } catch (e) {
  20970. if (e instanceof SyntaxError) {
  20971. domGlobals.console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  20972. return {};
  20973. }
  20974. throw e;
  20975. }
  20976. if (!isRecordOfUrlArray(history)) {
  20977. domGlobals.console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  20978. return {};
  20979. }
  20980. return history;
  20981. };
  20982. var setAllHistory = function (history) {
  20983. if (!isRecordOfUrlArray(history)) {
  20984. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  20985. }
  20986. domGlobals.localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
  20987. };
  20988. var getHistory = function (fileType) {
  20989. var history = getAllHistory();
  20990. return Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  20991. };
  20992. var addToHistory = function (url, fileType) {
  20993. if (!isHttpUrl(url)) {
  20994. return;
  20995. }
  20996. var history = getAllHistory();
  20997. var items = Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  20998. var itemsWithoutUrl = filter(items, function (item) {
  20999. return item !== url;
  21000. });
  21001. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  21002. setAllHistory(history);
  21003. };
  21004. var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  21005. var isTruthy = function (value) {
  21006. return !!value;
  21007. };
  21008. var makeMap = function (value) {
  21009. return map$1(global$e.makeMap(value, /[, ]/), isTruthy);
  21010. };
  21011. var getOpt = function (obj, key) {
  21012. return hasOwnProperty$2.call(obj, key) ? Option.some(obj[key]) : Option.none();
  21013. };
  21014. var getTextSetting = function (settings, name, defaultValue) {
  21015. var value = getOpt(settings, name).getOr(defaultValue);
  21016. return isString(value) ? Option.some(value) : Option.none();
  21017. };
  21018. var getPicker = function (settings) {
  21019. return Option.some(settings.file_picker_callback).filter(isFunction);
  21020. };
  21021. var getPickerTypes = function (settings) {
  21022. var optFileTypes = Option.some(settings.file_picker_types).filter(isTruthy);
  21023. var optLegacyTypes = Option.some(settings.file_browser_callback_types).filter(isTruthy);
  21024. var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  21025. return getPicker(settings).fold(function () {
  21026. return false;
  21027. }, function (_picker) {
  21028. return optTypes.fold(function () {
  21029. return true;
  21030. }, function (types) {
  21031. return keys(types).length > 0 ? types : false;
  21032. });
  21033. });
  21034. };
  21035. var getPickerSetting = function (settings, filetype) {
  21036. var pickerTypes = getPickerTypes(settings);
  21037. if (isBoolean(pickerTypes)) {
  21038. return pickerTypes ? getPicker(settings) : Option.none();
  21039. } else {
  21040. return pickerTypes[filetype] ? getPicker(settings) : Option.none();
  21041. }
  21042. };
  21043. var getUrlPicker = function (editor, filetype) {
  21044. return getPickerSetting(editor.settings, filetype).map(function (picker) {
  21045. return function (entry) {
  21046. return Future.nu(function (completer) {
  21047. var handler = function (value, meta) {
  21048. if (!isString(value)) {
  21049. throw new Error('Expected value to be string');
  21050. }
  21051. if (meta !== undefined && !isObject(meta)) {
  21052. throw new Error('Expected meta to be a object');
  21053. }
  21054. var r = {
  21055. value: value,
  21056. meta: meta
  21057. };
  21058. completer(r);
  21059. };
  21060. var meta = global$e.extend({ filetype: filetype }, Option.from(entry.meta).getOr({}));
  21061. picker.call(editor, handler, entry.value, meta);
  21062. });
  21063. };
  21064. });
  21065. };
  21066. var getLinkInformation = function (editor) {
  21067. if (editor.settings.typeahead_urls === false) {
  21068. return Option.none();
  21069. }
  21070. return Option.some({
  21071. targets: LinkTargets.find(editor.getBody()),
  21072. anchorTop: getTextSetting(editor.settings, 'anchor_top', '#top').getOrUndefined(),
  21073. anchorBottom: getTextSetting(editor.settings, 'anchor_bottom', '#bottom').getOrUndefined()
  21074. });
  21075. };
  21076. var getValidationHandler = function (editor) {
  21077. var optValidator = Option.from(editor.settings.file_picker_validator_handler).filter(isFunction);
  21078. return optValidator.orThunk(function () {
  21079. return Option.from(editor.settings.filepicker_validator_handler).filter(isFunction);
  21080. });
  21081. };
  21082. var UrlInputBackstage = function (editor) {
  21083. return {
  21084. getHistory: getHistory,
  21085. addToHistory: addToHistory,
  21086. getLinkInformation: function () {
  21087. return getLinkInformation(editor);
  21088. },
  21089. getValidationHandler: function () {
  21090. return getValidationHandler(editor);
  21091. },
  21092. getUrlPicker: function (filetype) {
  21093. return getUrlPicker(editor, filetype);
  21094. }
  21095. };
  21096. };
  21097. var init$8 = function (sink, editor, lazyAnchorbar, lazyMoreButton) {
  21098. var contextMenuState = Cell(false);
  21099. var backstage = {
  21100. shared: {
  21101. providers: {
  21102. icons: function () {
  21103. return editor.ui.registry.getAll().icons;
  21104. },
  21105. menuItems: function () {
  21106. return editor.ui.registry.getAll().menuItems;
  21107. },
  21108. translate: global$5.translate
  21109. },
  21110. interpreter: function (s) {
  21111. return interpretWithoutForm(s, backstage);
  21112. },
  21113. anchors: Anchors.getAnchors(editor, lazyAnchorbar, lazyMoreButton),
  21114. getSink: function () {
  21115. return Result.value(sink);
  21116. }
  21117. },
  21118. urlinput: UrlInputBackstage(editor),
  21119. styleselect: init$7(editor),
  21120. colorinput: ColorInputBackstage(editor),
  21121. dialog: DialogBackstage(editor),
  21122. isContextMenuOpen: function () {
  21123. return contextMenuState.get();
  21124. },
  21125. setContextMenuState: function (state) {
  21126. return contextMenuState.set(state);
  21127. }
  21128. };
  21129. return backstage;
  21130. };
  21131. var showContextToolbarEvent = 'contexttoolbar-show';
  21132. var hideContextToolbarEvent = 'contexttoolbar-hide';
  21133. var schema$k = constant([
  21134. strict$1('dom'),
  21135. defaulted$1('shell', true),
  21136. field$1('toolbarBehaviours', [Replacing])
  21137. ]);
  21138. var enhanceGroups = function (detail) {
  21139. return { behaviours: derive$1([Replacing.config({})]) };
  21140. };
  21141. var parts$7 = constant([optional({
  21142. name: 'groups',
  21143. overrides: enhanceGroups
  21144. })]);
  21145. var factory$9 = function (detail, components, spec, _externals) {
  21146. var setGroups = function (toolbar, groups) {
  21147. getGroupContainer(toolbar).fold(function () {
  21148. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21149. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21150. }, function (container) {
  21151. Replacing.set(container, groups);
  21152. });
  21153. };
  21154. var getGroupContainer = function (component) {
  21155. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  21156. };
  21157. var extra = detail.shell ? {
  21158. behaviours: [Replacing.config({})],
  21159. components: []
  21160. } : {
  21161. behaviours: [],
  21162. components: components
  21163. };
  21164. return {
  21165. uid: detail.uid,
  21166. dom: detail.dom,
  21167. components: extra.components,
  21168. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  21169. apis: { setGroups: setGroups },
  21170. domModification: { attributes: { role: 'group' } }
  21171. };
  21172. };
  21173. var Toolbar = composite$1({
  21174. name: 'Toolbar',
  21175. configFields: schema$k(),
  21176. partFields: parts$7(),
  21177. factory: factory$9,
  21178. apis: {
  21179. setGroups: function (apis, toolbar, groups) {
  21180. apis.setGroups(toolbar, groups);
  21181. }
  21182. }
  21183. });
  21184. var generate$6 = function (xs, f) {
  21185. var init = {
  21186. len: 0,
  21187. list: []
  21188. };
  21189. var r = foldl(xs, function (b, a) {
  21190. var value = f(a, b.len);
  21191. return value.fold(constant(b), function (v) {
  21192. return {
  21193. len: v.finish(),
  21194. list: b.list.concat([v])
  21195. };
  21196. });
  21197. }, init);
  21198. return r.list;
  21199. };
  21200. var output$1 = Immutable('within', 'extra', 'withinWidth');
  21201. var apportion = function (units, total, len) {
  21202. var parray = generate$6(units, function (unit, current) {
  21203. var width = len(unit);
  21204. return Option.some({
  21205. element: constant(unit),
  21206. start: constant(current),
  21207. finish: constant(current + width),
  21208. width: constant(width)
  21209. });
  21210. });
  21211. var within = filter(parray, function (unit) {
  21212. return unit.finish() <= total;
  21213. });
  21214. var withinWidth = foldr(within, function (acc, el) {
  21215. return acc + el.width();
  21216. }, 0);
  21217. var extra = parray.slice(within.length);
  21218. return {
  21219. within: constant(within),
  21220. extra: constant(extra),
  21221. withinWidth: constant(withinWidth)
  21222. };
  21223. };
  21224. var toUnit = function (parray) {
  21225. return map(parray, function (unit) {
  21226. return unit.element();
  21227. });
  21228. };
  21229. var fitLast = function (within, extra, withinWidth) {
  21230. var fits = toUnit(within.concat(extra));
  21231. return output$1(fits, [], withinWidth);
  21232. };
  21233. var overflow = function (within, extra, overflower, withinWidth) {
  21234. var fits = toUnit(within).concat([overflower]);
  21235. return output$1(fits, toUnit(extra), withinWidth);
  21236. };
  21237. var fitAll = function (within, extra, withinWidth) {
  21238. return output$1(toUnit(within), [], withinWidth);
  21239. };
  21240. var tryFit = function (total, units, len) {
  21241. var divide = apportion(units, total, len);
  21242. return divide.extra().length === 0 ? Option.some(divide) : Option.none();
  21243. };
  21244. var partition$3 = function (total, units, len, overflower) {
  21245. var divide = tryFit(total, units, len).getOrThunk(function () {
  21246. return apportion(units, total - len(overflower), len);
  21247. });
  21248. var within = divide.within();
  21249. var extra = divide.extra();
  21250. var withinWidth = divide.withinWidth();
  21251. if (extra.length === 1 && extra[0].width() <= len(overflower)) {
  21252. return fitLast(within, extra, withinWidth);
  21253. } else if (extra.length >= 1) {
  21254. return overflow(within, extra, overflower, withinWidth);
  21255. } else {
  21256. return fitAll(within, extra, withinWidth);
  21257. }
  21258. };
  21259. var setStoredGroups = function (toolbar, storedGroups) {
  21260. var bGroups = map(storedGroups, function (g) {
  21261. return premade$1(g);
  21262. });
  21263. Toolbar.setGroups(toolbar, bGroups);
  21264. };
  21265. var findFocusedComp = function (overflow, overflowButton) {
  21266. return overflow.bind(function (overf) {
  21267. return search(overf.element()).bind(function (focusedElm) {
  21268. return overf.getSystem().getByDom(focusedElm).toOption();
  21269. });
  21270. }).orThunk(function () {
  21271. return overflowButton.filter(Focusing.isFocused);
  21272. });
  21273. };
  21274. var refresh = function (toolbar, detail, overflow, isOpen) {
  21275. var primary = getPartOrDie(toolbar, detail, 'primary');
  21276. var overflowButton = getPart(toolbar, detail, 'overflow-button');
  21277. var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  21278. set$2(primary.element(), 'visibility', 'hidden');
  21279. var focusedComp = findFocusedComp(overflow, overflowButton);
  21280. overflow.each(function (overf) {
  21281. Toolbar.setGroups(overf, []);
  21282. });
  21283. var groups = detail.builtGroups.get();
  21284. setStoredGroups(primary, groups.concat([overflowGroup]));
  21285. var total = get$7(primary.element());
  21286. var overflows = partition$3(total, groups, function (comp) {
  21287. return get$7(comp.element());
  21288. }, overflowGroup);
  21289. if (overflows.extra().length === 0) {
  21290. Replacing.remove(primary, overflowGroup);
  21291. overflow.each(function (overf) {
  21292. Toolbar.setGroups(overf, []);
  21293. });
  21294. } else {
  21295. setStoredGroups(primary, overflows.within());
  21296. overflow.each(function (overf) {
  21297. setStoredGroups(overf, overflows.extra());
  21298. });
  21299. }
  21300. remove$6(primary.element(), 'visibility');
  21301. reflow(primary.element());
  21302. overflow.each(function (overf) {
  21303. overflowButton.each(function (button) {
  21304. return Toggling.set(button, isOpen(overf));
  21305. });
  21306. focusedComp.each(Focusing.focus);
  21307. });
  21308. };
  21309. var schema$l = constant([
  21310. strict$1('items'),
  21311. markers(['itemSelector']),
  21312. field$1('tgroupBehaviours', [Keying])
  21313. ]);
  21314. var parts$8 = constant([group({
  21315. name: 'items',
  21316. unit: 'item'
  21317. })]);
  21318. var factory$a = function (detail, components, spec, _externals) {
  21319. return {
  21320. uid: detail.uid,
  21321. dom: detail.dom,
  21322. components: components,
  21323. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  21324. mode: 'flow',
  21325. selector: detail.markers.itemSelector
  21326. })]),
  21327. domModification: { attributes: { role: 'toolbar' } }
  21328. };
  21329. };
  21330. var ToolbarGroup = composite$1({
  21331. name: 'ToolbarGroup',
  21332. configFields: schema$l(),
  21333. partFields: parts$8(),
  21334. factory: factory$a
  21335. });
  21336. var schema$m = constant([
  21337. field$1('splitToolbarBehaviours', [Coupling]),
  21338. state$1('builtGroups', function () {
  21339. return Cell([]);
  21340. })
  21341. ]);
  21342. var spec = function (detail, components, spec, externals, extras) {
  21343. var toolbarToggleEvent = 'alloy.toolbar.toggle';
  21344. var doSetGroups = function (toolbar, groups) {
  21345. var built = map(groups, toolbar.getSystem().build);
  21346. detail.builtGroups.set(built);
  21347. };
  21348. var setGroups = function (toolbar, groups) {
  21349. doSetGroups(toolbar, groups);
  21350. extras.apis.refresh(toolbar);
  21351. };
  21352. var getMoreButton = function (toolbar) {
  21353. return getPart(toolbar, detail, 'overflow-button');
  21354. };
  21355. return {
  21356. uid: detail.uid,
  21357. dom: detail.dom,
  21358. components: components,
  21359. behaviours: augment(detail.splitToolbarBehaviours, [
  21360. Coupling.config({
  21361. others: __assign(__assign({}, extras.coupling), {
  21362. overflowGroup: function (toolbar) {
  21363. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  21364. items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  21365. action: function (_button) {
  21366. emit(toolbar, toolbarToggleEvent);
  21367. }
  21368. }))]
  21369. }));
  21370. }
  21371. })
  21372. }),
  21373. config('toolbar-toggle-events', [run(toolbarToggleEvent, function (toolbar) {
  21374. extras.apis.toggle(toolbar);
  21375. })])
  21376. ]),
  21377. apis: __assign({
  21378. setGroups: setGroups,
  21379. getMoreButton: function (toolbar) {
  21380. return getMoreButton(toolbar);
  21381. }
  21382. }, extras.apis),
  21383. domModification: { attributes: { role: 'group' } }
  21384. };
  21385. };
  21386. var schema$n = constant([
  21387. markers(['overflowToggledClass']),
  21388. strict$1('getAnchor'),
  21389. optionFunction('getOverflowBounds'),
  21390. strict$1('lazySink')
  21391. ].concat(schema$m()));
  21392. var parts$9 = constant([
  21393. required({
  21394. factory: Toolbar,
  21395. schema: schema$k(),
  21396. name: 'primary'
  21397. }),
  21398. external$1({
  21399. factory: Toolbar,
  21400. schema: schema$k(),
  21401. name: 'overflow',
  21402. overrides: function (detail) {
  21403. return {
  21404. toolbarBehaviours: derive$1([Keying.config({
  21405. mode: 'cyclic',
  21406. onEscape: function (comp) {
  21407. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  21408. return Option.none();
  21409. }
  21410. })])
  21411. };
  21412. }
  21413. }),
  21414. external$1({
  21415. name: 'overflow-button',
  21416. overrides: function (detail) {
  21417. return {
  21418. dom: { attributes: { 'aria-haspopup': 'true' } },
  21419. buttonBehaviours: derive$1([Toggling.config({
  21420. toggleClass: detail.markers.overflowToggledClass,
  21421. aria: { mode: 'expanded' },
  21422. toggleOnExecute: false
  21423. })])
  21424. };
  21425. }
  21426. }),
  21427. external$1({ name: 'overflow-group' })
  21428. ]);
  21429. var toggleToolbar = function (toolbar, detail, externals) {
  21430. var sandbox = Coupling.getCoupled(toolbar, 'sandbox');
  21431. if (Sandboxing.isOpen(sandbox)) {
  21432. Sandboxing.close(sandbox);
  21433. } else {
  21434. Sandboxing.open(sandbox, externals.overflow());
  21435. }
  21436. };
  21437. var isOpen$1 = function (over) {
  21438. return over.getSystem().isConnected();
  21439. };
  21440. var position$2 = function (toolbar, detail, overf) {
  21441. var sink = detail.lazySink(toolbar).getOrDie();
  21442. var anchor = detail.getAnchor(toolbar);
  21443. var bounds = detail.getOverflowBounds.map(function (bounder) {
  21444. return bounder();
  21445. });
  21446. Positioning.positionWithinBounds(sink, anchor, overf, bounds);
  21447. };
  21448. var refresh$1 = function (toolbar, detail) {
  21449. var overflow = Sandboxing.getState(Coupling.getCoupled(toolbar, 'sandbox'));
  21450. refresh(toolbar, detail, overflow, isOpen$1);
  21451. overflow.each(function (overf) {
  21452. return position$2(toolbar, detail, overf);
  21453. });
  21454. };
  21455. var reposition$1 = function (toolbar, detail) {
  21456. var overflow = Sandboxing.getState(Coupling.getCoupled(toolbar, 'sandbox'));
  21457. overflow.each(function (overf) {
  21458. return position$2(toolbar, detail, overf);
  21459. });
  21460. };
  21461. var makeSandbox$1 = function (toolbar, detail) {
  21462. var ariaOwner = manager();
  21463. var onOpen = function (sandbox, overf) {
  21464. refresh$1(toolbar, detail);
  21465. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  21466. Toggling.on(button);
  21467. ariaOwner.link(button.element());
  21468. });
  21469. Keying.focusIn(overf);
  21470. };
  21471. var onClose = function () {
  21472. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  21473. Toggling.off(button);
  21474. Focusing.focus(button);
  21475. ariaOwner.unlink(button.element());
  21476. });
  21477. };
  21478. return {
  21479. dom: {
  21480. tag: 'div',
  21481. attributes: { id: ariaOwner.id() }
  21482. },
  21483. behaviours: derive$1([
  21484. Keying.config({
  21485. mode: 'special',
  21486. onEscape: function (comp) {
  21487. Sandboxing.close(comp);
  21488. return Option.some(true);
  21489. }
  21490. }),
  21491. Sandboxing.config({
  21492. onOpen: onOpen,
  21493. onClose: onClose,
  21494. isPartOf: function (container, data, queryElem) {
  21495. return isPartOf(data, queryElem) || isPartOf(toolbar, queryElem);
  21496. },
  21497. getAttachPoint: function () {
  21498. return detail.lazySink(toolbar).getOrDie();
  21499. }
  21500. }),
  21501. Receiving.config({
  21502. channels: __assign({}, receivingChannel$1({
  21503. isExtraPart: constant(false),
  21504. doReposition: function () {
  21505. return reposition$1(toolbar, detail);
  21506. }
  21507. }))
  21508. })
  21509. ])
  21510. };
  21511. };
  21512. var factory$b = function (detail, components, spec$1, externals) {
  21513. return spec(detail, components, spec$1, externals, {
  21514. coupling: {
  21515. sandbox: function (toolbar) {
  21516. return makeSandbox$1(toolbar, detail);
  21517. }
  21518. },
  21519. apis: {
  21520. refresh: function (toolbar) {
  21521. return refresh$1(toolbar, detail);
  21522. },
  21523. toggle: function (toolbar) {
  21524. return toggleToolbar(toolbar, detail, externals);
  21525. },
  21526. getOverflow: function (toolbar) {
  21527. return Sandboxing.getState(Coupling.getCoupled(toolbar, 'sandbox'));
  21528. },
  21529. reposition: function (toolbar) {
  21530. return reposition$1(toolbar, detail);
  21531. }
  21532. }
  21533. });
  21534. };
  21535. var SplitFloatingToolbar = composite$1({
  21536. name: 'SplitFloatingToolbar',
  21537. configFields: schema$n(),
  21538. partFields: parts$9(),
  21539. factory: factory$b,
  21540. apis: {
  21541. setGroups: function (apis, toolbar, groups) {
  21542. apis.setGroups(toolbar, groups);
  21543. },
  21544. refresh: function (apis, toolbar) {
  21545. apis.refresh(toolbar);
  21546. },
  21547. reposition: function (apis, toolbar) {
  21548. apis.reposition(toolbar);
  21549. },
  21550. getMoreButton: function (apis, toolbar) {
  21551. return apis.getMoreButton(toolbar);
  21552. },
  21553. getOverflow: function (apis, toolbar) {
  21554. return apis.getOverflow(toolbar);
  21555. },
  21556. toggle: function (apis, toolbar) {
  21557. apis.toggle(toolbar);
  21558. }
  21559. }
  21560. });
  21561. var getAnimationRoot = function (component, slideConfig) {
  21562. return slideConfig.getAnimationRoot.fold(function () {
  21563. return component.element();
  21564. }, function (get) {
  21565. return get(component);
  21566. });
  21567. };
  21568. var getDimensionProperty = function (slideConfig) {
  21569. return slideConfig.dimension.property;
  21570. };
  21571. var getDimension = function (slideConfig, elem) {
  21572. return slideConfig.dimension.getDimension(elem);
  21573. };
  21574. var disableTransitions = function (component, slideConfig) {
  21575. var root = getAnimationRoot(component, slideConfig);
  21576. remove$5(root, [
  21577. slideConfig.shrinkingClass,
  21578. slideConfig.growingClass
  21579. ]);
  21580. };
  21581. var setShrunk = function (component, slideConfig) {
  21582. remove$4(component.element(), slideConfig.openClass);
  21583. add$2(component.element(), slideConfig.closedClass);
  21584. set$2(component.element(), getDimensionProperty(slideConfig), '0px');
  21585. reflow(component.element());
  21586. };
  21587. var setGrown = function (component, slideConfig) {
  21588. remove$4(component.element(), slideConfig.closedClass);
  21589. add$2(component.element(), slideConfig.openClass);
  21590. remove$6(component.element(), getDimensionProperty(slideConfig));
  21591. };
  21592. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  21593. slideState.setCollapsed();
  21594. set$2(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  21595. reflow(component.element());
  21596. disableTransitions(component, slideConfig);
  21597. setShrunk(component, slideConfig);
  21598. slideConfig.onStartShrink(component);
  21599. slideConfig.onShrunk(component);
  21600. };
  21601. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  21602. var size = calculatedSize.getOrThunk(function () {
  21603. return getDimension(slideConfig, component.element());
  21604. });
  21605. slideState.setCollapsed();
  21606. set$2(component.element(), getDimensionProperty(slideConfig), size);
  21607. reflow(component.element());
  21608. var root = getAnimationRoot(component, slideConfig);
  21609. remove$4(root, slideConfig.growingClass);
  21610. add$2(root, slideConfig.shrinkingClass);
  21611. setShrunk(component, slideConfig);
  21612. slideConfig.onStartShrink(component);
  21613. };
  21614. var doStartSmartShrink = function (component, slideConfig, slideState) {
  21615. var size = getDimension(slideConfig, component.element());
  21616. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  21617. shrinker(component, slideConfig, slideState, Option.some(size));
  21618. };
  21619. var doStartGrow = function (component, slideConfig, slideState) {
  21620. var root = getAnimationRoot(component, slideConfig);
  21621. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  21622. var beforeSize = getDimension(slideConfig, component.element());
  21623. setGrown(component, slideConfig);
  21624. var fullSize = getDimension(slideConfig, component.element());
  21625. var startPartialGrow = function () {
  21626. set$2(component.element(), getDimensionProperty(slideConfig), beforeSize);
  21627. reflow(component.element());
  21628. };
  21629. var startCompleteGrow = function () {
  21630. setShrunk(component, slideConfig);
  21631. };
  21632. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  21633. setStartSize();
  21634. remove$4(root, slideConfig.shrinkingClass);
  21635. add$2(root, slideConfig.growingClass);
  21636. setGrown(component, slideConfig);
  21637. set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
  21638. slideState.setExpanded();
  21639. slideConfig.onStartGrow(component);
  21640. };
  21641. var refresh$2 = function (component, slideConfig, slideState) {
  21642. if (slideState.isExpanded()) {
  21643. remove$6(component.element(), getDimensionProperty(slideConfig));
  21644. var fullSize = getDimension(slideConfig, component.element());
  21645. set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
  21646. }
  21647. };
  21648. var grow = function (component, slideConfig, slideState) {
  21649. if (!slideState.isExpanded()) {
  21650. doStartGrow(component, slideConfig, slideState);
  21651. }
  21652. };
  21653. var shrink = function (component, slideConfig, slideState) {
  21654. if (slideState.isExpanded()) {
  21655. doStartSmartShrink(component, slideConfig, slideState);
  21656. }
  21657. };
  21658. var immediateShrink = function (component, slideConfig, slideState) {
  21659. if (slideState.isExpanded()) {
  21660. doImmediateShrink(component, slideConfig, slideState);
  21661. }
  21662. };
  21663. var hasGrown = function (component, slideConfig, slideState) {
  21664. return slideState.isExpanded();
  21665. };
  21666. var hasShrunk = function (component, slideConfig, slideState) {
  21667. return slideState.isCollapsed();
  21668. };
  21669. var isGrowing = function (component, slideConfig, slideState) {
  21670. var root = getAnimationRoot(component, slideConfig);
  21671. return has$2(root, slideConfig.growingClass) === true;
  21672. };
  21673. var isShrinking = function (component, slideConfig, slideState) {
  21674. var root = getAnimationRoot(component, slideConfig);
  21675. return has$2(root, slideConfig.shrinkingClass) === true;
  21676. };
  21677. var isTransitioning = function (component, slideConfig, slideState) {
  21678. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  21679. };
  21680. var toggleGrow = function (component, slideConfig, slideState) {
  21681. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  21682. f(component, slideConfig, slideState);
  21683. };
  21684. var SlidingApis = /*#__PURE__*/Object.freeze({
  21685. refresh: refresh$2,
  21686. grow: grow,
  21687. shrink: shrink,
  21688. immediateShrink: immediateShrink,
  21689. hasGrown: hasGrown,
  21690. hasShrunk: hasShrunk,
  21691. isGrowing: isGrowing,
  21692. isShrinking: isShrinking,
  21693. isTransitioning: isTransitioning,
  21694. toggleGrow: toggleGrow,
  21695. disableTransitions: disableTransitions
  21696. });
  21697. var exhibit$6 = function (base, slideConfig) {
  21698. var expanded = slideConfig.expanded;
  21699. return expanded ? nu$6({
  21700. classes: [slideConfig.openClass],
  21701. styles: {}
  21702. }) : nu$6({
  21703. classes: [slideConfig.closedClass],
  21704. styles: wrap$1(slideConfig.dimension.property, '0px')
  21705. });
  21706. };
  21707. var events$d = function (slideConfig, slideState) {
  21708. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  21709. var raw = simulatedEvent.event().raw();
  21710. if (raw.propertyName === slideConfig.dimension.property) {
  21711. disableTransitions(component, slideConfig);
  21712. if (slideState.isExpanded()) {
  21713. remove$6(component.element(), slideConfig.dimension.property);
  21714. }
  21715. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  21716. notify(component);
  21717. }
  21718. })]);
  21719. };
  21720. var ActiveSliding = /*#__PURE__*/Object.freeze({
  21721. exhibit: exhibit$6,
  21722. events: events$d
  21723. });
  21724. var SlidingSchema = [
  21725. strict$1('closedClass'),
  21726. strict$1('openClass'),
  21727. strict$1('shrinkingClass'),
  21728. strict$1('growingClass'),
  21729. option('getAnimationRoot'),
  21730. onHandler('onShrunk'),
  21731. onHandler('onStartShrink'),
  21732. onHandler('onGrown'),
  21733. onHandler('onStartGrow'),
  21734. defaulted$1('expanded', false),
  21735. strictOf('dimension', choose$1('property', {
  21736. width: [
  21737. output('property', 'width'),
  21738. output('getDimension', function (elem) {
  21739. return get$7(elem) + 'px';
  21740. })
  21741. ],
  21742. height: [
  21743. output('property', 'height'),
  21744. output('getDimension', function (elem) {
  21745. return get$6(elem) + 'px';
  21746. })
  21747. ]
  21748. }))
  21749. ];
  21750. var init$9 = function (spec) {
  21751. var state = Cell(spec.expanded);
  21752. var readState = function () {
  21753. return 'expanded: ' + state.get();
  21754. };
  21755. return nu$5({
  21756. isExpanded: function () {
  21757. return state.get() === true;
  21758. },
  21759. isCollapsed: function () {
  21760. return state.get() === false;
  21761. },
  21762. setCollapsed: curry(state.set, false),
  21763. setExpanded: curry(state.set, true),
  21764. readState: readState
  21765. });
  21766. };
  21767. var SlidingState = /*#__PURE__*/Object.freeze({
  21768. init: init$9
  21769. });
  21770. var Sliding = create$1({
  21771. fields: SlidingSchema,
  21772. name: 'sliding',
  21773. active: ActiveSliding,
  21774. apis: SlidingApis,
  21775. state: SlidingState
  21776. });
  21777. var schema$o = constant([
  21778. markers([
  21779. 'closedClass',
  21780. 'openClass',
  21781. 'shrinkingClass',
  21782. 'growingClass',
  21783. 'overflowToggledClass'
  21784. ]),
  21785. onHandler('onOpened'),
  21786. onHandler('onClosed')
  21787. ].concat(schema$m()));
  21788. var parts$a = constant([
  21789. required({
  21790. factory: Toolbar,
  21791. schema: schema$k(),
  21792. name: 'primary'
  21793. }),
  21794. required({
  21795. factory: Toolbar,
  21796. schema: schema$k(),
  21797. name: 'overflow',
  21798. overrides: function (detail) {
  21799. return {
  21800. toolbarBehaviours: derive$1([
  21801. Sliding.config({
  21802. dimension: { property: 'height' },
  21803. closedClass: detail.markers.closedClass,
  21804. openClass: detail.markers.openClass,
  21805. shrinkingClass: detail.markers.shrinkingClass,
  21806. growingClass: detail.markers.growingClass,
  21807. onShrunk: function (comp) {
  21808. getPart(comp, detail, 'overflow-button').each(function (button) {
  21809. Toggling.off(button);
  21810. Focusing.focus(button);
  21811. });
  21812. detail.onClosed(comp);
  21813. },
  21814. onGrown: function (comp) {
  21815. Keying.focusIn(comp);
  21816. detail.onOpened(comp);
  21817. },
  21818. onStartGrow: function (comp) {
  21819. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  21820. }
  21821. }),
  21822. Keying.config({
  21823. mode: 'acyclic',
  21824. onEscape: function (comp) {
  21825. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  21826. return Option.some(true);
  21827. }
  21828. })
  21829. ])
  21830. };
  21831. }
  21832. }),
  21833. external$1({
  21834. name: 'overflow-button',
  21835. overrides: function (detail) {
  21836. return {
  21837. buttonBehaviours: derive$1([Toggling.config({
  21838. toggleClass: detail.markers.overflowToggledClass,
  21839. aria: { mode: 'pressed' },
  21840. toggleOnExecute: false
  21841. })])
  21842. };
  21843. }
  21844. }),
  21845. external$1({ name: 'overflow-group' })
  21846. ]);
  21847. var toggleToolbar$1 = function (toolbar, detail) {
  21848. getPart(toolbar, detail, 'overflow').each(function (overf) {
  21849. refresh$3(toolbar, detail);
  21850. Sliding.toggleGrow(overf);
  21851. });
  21852. };
  21853. var isOpen$2 = function (overf) {
  21854. return Sliding.hasGrown(overf);
  21855. };
  21856. var refresh$3 = function (toolbar, detail) {
  21857. var overflow = getPart(toolbar, detail, 'overflow');
  21858. refresh(toolbar, detail, overflow, isOpen$2);
  21859. overflow.each(Sliding.refresh);
  21860. };
  21861. var factory$c = function (detail, components, spec$1, externals) {
  21862. return spec(detail, components, spec$1, externals, {
  21863. coupling: {},
  21864. apis: {
  21865. refresh: function (toolbar) {
  21866. return refresh$3(toolbar, detail);
  21867. },
  21868. toggle: function (toolbar) {
  21869. return toggleToolbar$1(toolbar, detail);
  21870. },
  21871. getOverflow: function (toolbar) {
  21872. return getPart(toolbar, detail, 'overflow');
  21873. }
  21874. }
  21875. });
  21876. };
  21877. var SplitSlidingToolbar = composite$1({
  21878. name: 'SplitSlidingToolbar',
  21879. configFields: schema$o(),
  21880. partFields: parts$a(),
  21881. factory: factory$c,
  21882. apis: {
  21883. setGroups: function (apis, toolbar, groups) {
  21884. apis.setGroups(toolbar, groups);
  21885. },
  21886. refresh: function (apis, toolbar) {
  21887. apis.refresh(toolbar);
  21888. },
  21889. getMoreButton: function (apis, toolbar) {
  21890. return apis.getMoreButton(toolbar);
  21891. },
  21892. getOverflow: function (apis, toolbar) {
  21893. return apis.getOverflow(toolbar);
  21894. },
  21895. toggle: function (apis, toolbar) {
  21896. apis.toggle(toolbar);
  21897. }
  21898. }
  21899. });
  21900. var ReadOnlyChannel = 'silver.readonly';
  21901. var ReadOnlyDataSchema = objOf([strictBoolean('readonly')]);
  21902. var setDisabledAll = function (element, state) {
  21903. all('*', element.element()).forEach(function (elm) {
  21904. element.getSystem().getByDom(elm).each(function (comp) {
  21905. if (comp.hasConfigured(Disabling)) {
  21906. Disabling.set(comp, state);
  21907. }
  21908. });
  21909. });
  21910. };
  21911. var broadcastReadonly = function (uiComponents, readonly) {
  21912. var outerContainer = uiComponents.outerContainer;
  21913. var target = outerContainer.element();
  21914. if (readonly) {
  21915. uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  21916. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  21917. }
  21918. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  21919. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  21920. };
  21921. var toggleToReadOnly = function (uiComponents, readonly) {
  21922. var outerContainer = uiComponents.outerContainer;
  21923. broadcastReadonly(uiComponents, readonly);
  21924. all('*', outerContainer.element()).forEach(function (elm) {
  21925. outerContainer.getSystem().getByDom(elm).each(function (comp) {
  21926. if (comp.hasConfigured(Disabling)) {
  21927. Disabling.set(comp, readonly);
  21928. }
  21929. });
  21930. });
  21931. };
  21932. var setupReadonlyModeSwitch = function (editor, uiComponents) {
  21933. editor.on('init', function () {
  21934. if (editor.readonly) {
  21935. toggleToReadOnly(uiComponents, true);
  21936. }
  21937. });
  21938. editor.on('SwitchMode', function () {
  21939. return toggleToReadOnly(uiComponents, editor.readonly);
  21940. });
  21941. if (isReadOnly(editor)) {
  21942. editor.setMode('readonly');
  21943. }
  21944. };
  21945. var createReadonlyReceivingForOverflow = function (getOverflow) {
  21946. var _a;
  21947. return Receiving.config({
  21948. channels: (_a = {}, _a[ReadOnlyChannel] = {
  21949. schema: ReadOnlyDataSchema,
  21950. onReceive: function (comp, data) {
  21951. getOverflow(comp).each(function (toolbar) {
  21952. setDisabledAll(toolbar, data.readonly);
  21953. });
  21954. }
  21955. }, _a)
  21956. });
  21957. };
  21958. var toolbarHeightChange = constant(generate$1('toolbar-height-change'));
  21959. var renderToolbarGroupCommon = function (toolbarGroup) {
  21960. var attributes = toolbarGroup.title.fold(function () {
  21961. return {};
  21962. }, function (title) {
  21963. return { attributes: { title: title } };
  21964. });
  21965. return {
  21966. dom: __assign({
  21967. tag: 'div',
  21968. classes: ['tox-toolbar__group']
  21969. }, attributes),
  21970. components: [ToolbarGroup.parts().items({})],
  21971. items: toolbarGroup.items,
  21972. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), .tox-split-button:not([disabled]), .tox-toolbar-nav-js:not([disabled])' },
  21973. tgroupBehaviours: derive$1([
  21974. Tabstopping.config({}),
  21975. Focusing.config({})
  21976. ])
  21977. };
  21978. };
  21979. var renderToolbarGroup = function (toolbarGroup) {
  21980. return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  21981. };
  21982. var getToolbarbehaviours = function (toolbarSpec, modeName, getOverflow) {
  21983. var onAttached = runOnAttached(function (component) {
  21984. var groups = map(toolbarSpec.initGroups, renderToolbarGroup);
  21985. Toolbar.setGroups(component, groups);
  21986. });
  21987. return derive$1([
  21988. Keying.config({
  21989. mode: modeName,
  21990. onEscape: toolbarSpec.onEscape,
  21991. selector: '.tox-toolbar__group'
  21992. }),
  21993. config('toolbar-events', [onAttached]),
  21994. createReadonlyReceivingForOverflow(getOverflow)
  21995. ]);
  21996. };
  21997. var renderMoreToolbarCommon = function (toolbarSpec, getOverflow) {
  21998. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  21999. return {
  22000. uid: toolbarSpec.uid,
  22001. dom: {
  22002. tag: 'div',
  22003. classes: ['tox-toolbar-overlord']
  22004. },
  22005. parts: {
  22006. 'overflow-group': renderToolbarGroupCommon({
  22007. title: Option.none(),
  22008. items: []
  22009. }),
  22010. 'overflow-button': renderIconButtonSpec({
  22011. name: 'more',
  22012. icon: Option.some('more-drawer'),
  22013. disabled: false,
  22014. tooltip: Option.some('More...'),
  22015. primary: false,
  22016. borderless: false
  22017. }, Option.none(), toolbarSpec.backstage.shared.providers)
  22018. },
  22019. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName, getOverflow)
  22020. };
  22021. };
  22022. var renderFloatingMoreToolbar = function (toolbarSpec) {
  22023. var baseSpec = renderMoreToolbarCommon(toolbarSpec, SplitFloatingToolbar.getOverflow);
  22024. var overflowXOffset = 4;
  22025. var primary = SplitFloatingToolbar.parts().primary({
  22026. dom: {
  22027. tag: 'div',
  22028. classes: ['tox-toolbar__primary']
  22029. }
  22030. });
  22031. return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22032. lazySink: toolbarSpec.getSink,
  22033. getAnchor: function () {
  22034. return toolbarSpec.backstage.shared.anchors.toolbarOverflow();
  22035. },
  22036. getOverflowBounds: function () {
  22037. var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element();
  22038. var headerBounds = absolute$1(headerElem);
  22039. var docElem = documentElement(headerElem);
  22040. var docBounds = absolute$1(docElem);
  22041. return bounds$1(headerBounds.x() + overflowXOffset, docBounds.y(), headerBounds.width() - overflowXOffset * 2, docBounds.height());
  22042. },
  22043. parts: __assign(__assign({}, baseSpec.parts), {
  22044. overflow: {
  22045. dom: {
  22046. tag: 'div',
  22047. classes: ['tox-toolbar__overflow']
  22048. }
  22049. }
  22050. }),
  22051. components: [primary],
  22052. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  22053. }));
  22054. };
  22055. var renderSlidingMoreToolbar = function (toolbarSpec) {
  22056. var primary = SplitSlidingToolbar.parts().primary({
  22057. dom: {
  22058. tag: 'div',
  22059. classes: ['tox-toolbar__primary']
  22060. }
  22061. });
  22062. var overflow = SplitSlidingToolbar.parts().overflow({
  22063. dom: {
  22064. tag: 'div',
  22065. classes: ['tox-toolbar__overflow']
  22066. }
  22067. });
  22068. var baseSpec = renderMoreToolbarCommon(toolbarSpec, SplitSlidingToolbar.getOverflow);
  22069. return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22070. components: [
  22071. primary,
  22072. overflow
  22073. ],
  22074. markers: {
  22075. openClass: 'tox-toolbar__overflow--open',
  22076. closedClass: 'tox-toolbar__overflow--closed',
  22077. growingClass: 'tox-toolbar__overflow--growing',
  22078. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  22079. overflowToggledClass: 'tox-tbtn--enabled'
  22080. },
  22081. onOpened: function (comp) {
  22082. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  22083. },
  22084. onClosed: function (comp) {
  22085. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  22086. }
  22087. }));
  22088. };
  22089. var renderToolbar = function (toolbarSpec) {
  22090. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  22091. return Toolbar.sketch({
  22092. uid: toolbarSpec.uid,
  22093. dom: {
  22094. tag: 'div',
  22095. classes: ['tox-toolbar']
  22096. },
  22097. components: [Toolbar.parts().groups({})],
  22098. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName, constant(Option.none()))
  22099. });
  22100. };
  22101. var baseToolbarButtonFields = [
  22102. defaultedBoolean('disabled', false),
  22103. optionString('tooltip'),
  22104. optionString('icon'),
  22105. optionString('text'),
  22106. defaultedFunction('onSetup', function () {
  22107. return noop;
  22108. })
  22109. ];
  22110. var toolbarButtonSchema = objOf([
  22111. strictString('type'),
  22112. strictFunction('onAction')
  22113. ].concat(baseToolbarButtonFields));
  22114. var createToolbarButton = function (spec) {
  22115. return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  22116. };
  22117. var baseMenuButtonFields = [
  22118. optionString('text'),
  22119. optionString('tooltip'),
  22120. optionString('icon'),
  22121. strictFunction('fetch'),
  22122. defaultedFunction('onSetup', function () {
  22123. return noop;
  22124. })
  22125. ];
  22126. var MenuButtonSchema = objOf(__spreadArrays([strictString('type')], baseMenuButtonFields));
  22127. var createMenuButton = function (spec) {
  22128. return asRaw('menubutton', MenuButtonSchema, spec);
  22129. };
  22130. var splitButtonSchema = objOf([
  22131. strictString('type'),
  22132. optionString('tooltip'),
  22133. optionString('icon'),
  22134. optionString('text'),
  22135. optionFunction('select'),
  22136. strictFunction('fetch'),
  22137. defaultedFunction('onSetup', function () {
  22138. return noop;
  22139. }),
  22140. defaultedStringEnum('presets', 'normal', [
  22141. 'normal',
  22142. 'color',
  22143. 'listpreview'
  22144. ]),
  22145. defaulted$1('columns', 1),
  22146. strictFunction('onAction'),
  22147. strictFunction('onItemAction')
  22148. ]);
  22149. var createSplitButton = function (spec) {
  22150. return asRaw('SplitButton', splitButtonSchema, spec);
  22151. };
  22152. var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  22153. var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  22154. strictString('type'),
  22155. strictFunction('onAction')
  22156. ]));
  22157. var createToggleButton = function (spec) {
  22158. return asRaw('ToggleButton', toggleButtonSchema, spec);
  22159. };
  22160. var contextBarFields = [
  22161. defaultedFunction('predicate', function () {
  22162. return false;
  22163. }),
  22164. defaultedStringEnum('scope', 'node', [
  22165. 'node',
  22166. 'editor'
  22167. ]),
  22168. defaultedStringEnum('position', 'selection', [
  22169. 'node',
  22170. 'selection',
  22171. 'line'
  22172. ])
  22173. ];
  22174. var contextButtonFields = baseToolbarButtonFields.concat([
  22175. defaulted$1('type', 'contextformbutton'),
  22176. defaulted$1('primary', false),
  22177. strictFunction('onAction'),
  22178. state$1('original', identity)
  22179. ]);
  22180. var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  22181. defaulted$1('type', 'contextformbutton'),
  22182. defaulted$1('primary', false),
  22183. strictFunction('onAction'),
  22184. state$1('original', identity)
  22185. ]);
  22186. var launchButtonFields = baseToolbarButtonFields.concat([defaulted$1('type', 'contextformbutton')]);
  22187. var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted$1('type', 'contextformtogglebutton')]);
  22188. var toggleOrNormal = choose$1('type', {
  22189. contextformbutton: contextButtonFields,
  22190. contextformtogglebutton: contextToggleButtonFields
  22191. });
  22192. var contextFormSchema = objOf([
  22193. defaulted$1('type', 'contextform'),
  22194. defaultedFunction('initValue', function () {
  22195. return '';
  22196. }),
  22197. optionString('label'),
  22198. strictArrayOf('commands', toggleOrNormal),
  22199. optionOf('launch', choose$1('type', {
  22200. contextformbutton: launchButtonFields,
  22201. contextformtogglebutton: launchToggleButtonFields
  22202. }))
  22203. ].concat(contextBarFields));
  22204. var contextToolbarSchema = objOf([
  22205. defaulted$1('type', 'contexttoolbar'),
  22206. strictString('items')
  22207. ].concat(contextBarFields));
  22208. var createContextToolbar = function (spec) {
  22209. return asRaw('ContextToolbar', contextToolbarSchema, spec);
  22210. };
  22211. var createContextForm = function (spec) {
  22212. return asRaw('ContextForm', contextFormSchema, spec);
  22213. };
  22214. var getState$2 = function (component, replaceConfig, reflectState) {
  22215. return reflectState;
  22216. };
  22217. var ReflectingApis = /*#__PURE__*/Object.freeze({
  22218. getState: getState$2
  22219. });
  22220. var events$e = function (reflectingConfig, reflectingState) {
  22221. var update = function (component, data) {
  22222. reflectingConfig.updateState.each(function (updateState) {
  22223. var newState = updateState(component, data);
  22224. reflectingState.set(newState);
  22225. });
  22226. reflectingConfig.renderComponents.each(function (renderComponents) {
  22227. var newComponents = renderComponents(data, reflectingState.get());
  22228. var newChildren = map(newComponents, component.getSystem().build);
  22229. replaceChildren(component, newChildren);
  22230. });
  22231. };
  22232. return derive([
  22233. run(receive(), function (component, message) {
  22234. var channel = reflectingConfig.channel;
  22235. if (contains(message.channels(), channel)) {
  22236. update(component, message.data());
  22237. }
  22238. }),
  22239. runOnAttached(function (comp, se) {
  22240. reflectingConfig.initialData.each(function (rawData) {
  22241. update(comp, rawData);
  22242. });
  22243. })
  22244. ]);
  22245. };
  22246. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  22247. events: events$e
  22248. });
  22249. var init$a = function (spec) {
  22250. var cell = Cell(Option.none());
  22251. var set = function (optS) {
  22252. return cell.set(optS);
  22253. };
  22254. var clear = function () {
  22255. return cell.set(Option.none());
  22256. };
  22257. var get = function () {
  22258. return cell.get();
  22259. };
  22260. var readState = function () {
  22261. return cell.get().fold(function () {
  22262. return 'none';
  22263. }, function (x) {
  22264. return x;
  22265. });
  22266. };
  22267. return {
  22268. readState: readState,
  22269. get: get,
  22270. set: set,
  22271. clear: clear
  22272. };
  22273. };
  22274. var ReflectingState = /*#__PURE__*/Object.freeze({
  22275. init: init$a
  22276. });
  22277. var ReflectingSchema = [
  22278. strict$1('channel'),
  22279. option('renderComponents'),
  22280. option('updateState'),
  22281. option('initialData')
  22282. ];
  22283. var Reflecting = create$1({
  22284. fields: ReflectingSchema,
  22285. name: 'reflecting',
  22286. active: ActiveReflecting,
  22287. apis: ReflectingApis,
  22288. state: ReflectingState
  22289. });
  22290. var schema$p = constant([
  22291. strict$1('toggleClass'),
  22292. strict$1('fetch'),
  22293. onStrictHandler('onExecute'),
  22294. defaulted$1('getHotspot', Option.some),
  22295. defaulted$1('getAnchorOverrides', constant({})),
  22296. defaulted$1('layouts', Option.none()),
  22297. onStrictHandler('onItemExecute'),
  22298. option('lazySink'),
  22299. strict$1('dom'),
  22300. onHandler('onOpen'),
  22301. field$1('splitDropdownBehaviours', [
  22302. Coupling,
  22303. Keying,
  22304. Focusing
  22305. ]),
  22306. defaulted$1('matchWidth', false),
  22307. defaulted$1('useMinWidth', false),
  22308. defaulted$1('eventOrder', {}),
  22309. option('role')
  22310. ].concat(sandboxFields()));
  22311. var arrowPart = required({
  22312. factory: Button,
  22313. schema: [strict$1('dom')],
  22314. name: 'arrow',
  22315. defaults: function (detail) {
  22316. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22317. },
  22318. overrides: function (detail) {
  22319. return {
  22320. dom: {
  22321. tag: 'span',
  22322. attributes: { role: 'presentation' }
  22323. },
  22324. action: function (arrow) {
  22325. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  22326. },
  22327. buttonBehaviours: derive$1([Toggling.config({
  22328. toggleOnExecute: false,
  22329. toggleClass: detail.toggleClass
  22330. })])
  22331. };
  22332. }
  22333. });
  22334. var buttonPart = required({
  22335. factory: Button,
  22336. schema: [strict$1('dom')],
  22337. name: 'button',
  22338. defaults: function (detail) {
  22339. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22340. },
  22341. overrides: function (detail) {
  22342. return {
  22343. dom: {
  22344. tag: 'span',
  22345. attributes: { role: 'presentation' }
  22346. },
  22347. action: function (btn) {
  22348. btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22349. detail.onExecute(splitDropdown, btn);
  22350. });
  22351. }
  22352. };
  22353. }
  22354. });
  22355. var parts$b = constant([
  22356. arrowPart,
  22357. buttonPart,
  22358. optional({
  22359. factory: {
  22360. sketch: function (spec) {
  22361. return {
  22362. uid: spec.uid,
  22363. dom: {
  22364. tag: 'span',
  22365. styles: { display: 'none' },
  22366. attributes: { 'aria-hidden': 'true' },
  22367. innerHtml: spec.text
  22368. }
  22369. };
  22370. }
  22371. },
  22372. schema: [strict$1('text')],
  22373. name: 'aria-descriptor'
  22374. }),
  22375. external$1({
  22376. schema: [tieredMenuMarkers()],
  22377. name: 'menu',
  22378. defaults: function (detail) {
  22379. return {
  22380. onExecute: function (tmenu, item) {
  22381. tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22382. detail.onItemExecute(splitDropdown, tmenu, item);
  22383. });
  22384. }
  22385. };
  22386. }
  22387. }),
  22388. partType()
  22389. ]);
  22390. var factory$d = function (detail, components, spec, externals) {
  22391. var switchToMenu = function (sandbox) {
  22392. Composing.getCurrent(sandbox).each(function (current) {
  22393. Highlighting.highlightFirst(current);
  22394. Keying.focusIn(current);
  22395. });
  22396. };
  22397. var action = function (component) {
  22398. var onOpenSync = switchToMenu;
  22399. togglePopup(detail, function (x) {
  22400. return x;
  22401. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22402. };
  22403. var openMenu = function (comp) {
  22404. action(comp);
  22405. return Option.some(true);
  22406. };
  22407. var executeOnButton = function (comp) {
  22408. var button = getPartOrDie(comp, detail, 'button');
  22409. emitExecute(button);
  22410. return Option.some(true);
  22411. };
  22412. var buttonEvents = merge(derive([runOnAttached(function (component, simulatedEvent) {
  22413. var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  22414. ariaDescriptor.each(function (descriptor) {
  22415. var descriptorId = generate$1('aria');
  22416. set$1(descriptor.element(), 'id', descriptorId);
  22417. set$1(component.element(), 'aria-describedby', descriptorId);
  22418. });
  22419. })]), events$7(Option.some(action)));
  22420. var apis = {
  22421. repositionMenus: function (comp) {
  22422. if (Toggling.isOn(comp)) {
  22423. repositionMenus(comp);
  22424. }
  22425. }
  22426. };
  22427. return {
  22428. uid: detail.uid,
  22429. dom: detail.dom,
  22430. components: components,
  22431. apis: apis,
  22432. eventOrder: __assign(__assign({}, detail.eventOrder), {
  22433. 'alloy.execute': [
  22434. 'disabling',
  22435. 'toggling',
  22436. 'alloy.base.behaviour'
  22437. ]
  22438. }),
  22439. events: buttonEvents,
  22440. behaviours: augment(detail.splitDropdownBehaviours, [
  22441. Coupling.config({
  22442. others: {
  22443. sandbox: function (hotspot) {
  22444. var arrow = getPartOrDie(hotspot, detail, 'arrow');
  22445. var extras = {
  22446. onOpen: function () {
  22447. Toggling.on(arrow);
  22448. Toggling.on(hotspot);
  22449. },
  22450. onClose: function () {
  22451. Toggling.off(arrow);
  22452. Toggling.off(hotspot);
  22453. }
  22454. };
  22455. return makeSandbox(detail, hotspot, extras);
  22456. }
  22457. }
  22458. }),
  22459. Keying.config({
  22460. mode: 'special',
  22461. onSpace: executeOnButton,
  22462. onEnter: executeOnButton,
  22463. onDown: openMenu
  22464. }),
  22465. Focusing.config({}),
  22466. Toggling.config({
  22467. toggleOnExecute: false,
  22468. aria: { mode: 'expanded' }
  22469. })
  22470. ]),
  22471. domModification: {
  22472. attributes: {
  22473. 'role': detail.role.getOr('button'),
  22474. 'aria-haspopup': true
  22475. }
  22476. }
  22477. };
  22478. };
  22479. var SplitDropdown = composite$1({
  22480. name: 'SplitDropdown',
  22481. configFields: schema$p(),
  22482. partFields: parts$b(),
  22483. factory: factory$d,
  22484. apis: {
  22485. repositionMenus: function (apis, comp) {
  22486. return apis.repositionMenus(comp);
  22487. }
  22488. }
  22489. });
  22490. var getButtonApi = function (component) {
  22491. return {
  22492. isDisabled: function () {
  22493. return Disabling.isDisabled(component);
  22494. },
  22495. setDisabled: function (state) {
  22496. return Disabling.set(component, state);
  22497. }
  22498. };
  22499. };
  22500. var getToggleApi = function (component) {
  22501. return {
  22502. setActive: function (state) {
  22503. Toggling.set(component, state);
  22504. },
  22505. isActive: function () {
  22506. return Toggling.isOn(component);
  22507. },
  22508. isDisabled: function () {
  22509. return Disabling.isDisabled(component);
  22510. },
  22511. setDisabled: function (state) {
  22512. return Disabling.set(component, state);
  22513. }
  22514. };
  22515. };
  22516. var getTooltipAttributes = function (tooltip, providersBackstage) {
  22517. return tooltip.map(function (tooltip) {
  22518. return {
  22519. 'aria-label': providersBackstage.translate(tooltip),
  22520. 'title': providersBackstage.translate(tooltip)
  22521. };
  22522. }).getOr({});
  22523. };
  22524. var focusButtonEvent = generate$1('focus-button');
  22525. var rtlIcon$1 = [
  22526. 'checklist',
  22527. 'ordered-list'
  22528. ];
  22529. var rtlTransform$1 = [
  22530. 'indent',
  22531. 'outdent',
  22532. 'table-insert-column-after',
  22533. 'table-insert-column-before',
  22534. 'unordered-list'
  22535. ];
  22536. var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  22537. var _a;
  22538. var getIconName = function (iconName) {
  22539. return global$5.isRtl() && contains(rtlIcon$1, iconName) ? iconName + '-rtl' : iconName;
  22540. };
  22541. var needsRtlClass = global$5.isRtl() && icon.exists(function (name) {
  22542. return contains(rtlTransform$1, name);
  22543. });
  22544. return {
  22545. dom: {
  22546. tag: 'button',
  22547. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []).concat(needsRtlClass ? ['tox-tbtn__icon-rtl'] : []),
  22548. attributes: getTooltipAttributes(tooltip, providersBackstage)
  22549. },
  22550. components: componentRenderPipeline([
  22551. icon.map(function (iconName) {
  22552. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22553. }),
  22554. text.map(function (text) {
  22555. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22556. })
  22557. ]),
  22558. eventOrder: (_a = {}, _a[mousedown()] = [
  22559. 'focusing',
  22560. 'alloy.base.behaviour',
  22561. 'common-button-display-events'
  22562. ], _a),
  22563. buttonBehaviours: derive$1([config('common-button-display-events', [run(mousedown(), function (button, se) {
  22564. se.event().prevent();
  22565. emit(button, focusButtonEvent);
  22566. })])].concat(receiver.map(function (r) {
  22567. return Reflecting.config({
  22568. channel: r,
  22569. initialData: {
  22570. icon: icon,
  22571. text: text
  22572. },
  22573. renderComponents: function (data, _state) {
  22574. return componentRenderPipeline([
  22575. data.icon.map(function (iconName) {
  22576. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22577. }),
  22578. data.text.map(function (text) {
  22579. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22580. })
  22581. ]);
  22582. }
  22583. });
  22584. }).toArray()).concat(behaviours.getOr([])))
  22585. };
  22586. };
  22587. var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  22588. var editorOffCell = Cell(noop);
  22589. var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Option.none(), Option.none(), providersBackstage);
  22590. return Button.sketch({
  22591. dom: structure.dom,
  22592. components: structure.components,
  22593. eventOrder: toolbarButtonEventOrder,
  22594. buttonBehaviours: derive$1([
  22595. config('toolbar-button-events', [
  22596. onToolbarButtonExecute({
  22597. onAction: spec.onAction,
  22598. getApi: specialisation.getApi
  22599. }),
  22600. onControlAttached(specialisation, editorOffCell),
  22601. onControlDetached(specialisation, editorOffCell)
  22602. ]),
  22603. DisablingConfigs.toolbarButton(spec.disabled)
  22604. ].concat(specialisation.toolbarButtonBehaviours))
  22605. });
  22606. };
  22607. var renderToolbarButton = function (spec, providersBackstage) {
  22608. return renderToolbarButtonWith(spec, providersBackstage, []);
  22609. };
  22610. var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  22611. return renderCommonToolbarButton(spec, {
  22612. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  22613. getApi: getButtonApi,
  22614. onSetup: spec.onSetup
  22615. }, providersBackstage);
  22616. };
  22617. var renderToolbarToggleButton = function (spec, providersBackstage) {
  22618. return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  22619. };
  22620. var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  22621. return deepMerge(renderCommonToolbarButton(spec, {
  22622. toolbarButtonBehaviours: [
  22623. Replacing.config({}),
  22624. Toggling.config({
  22625. toggleClass: 'tox-tbtn--enabled',
  22626. aria: { mode: 'pressed' },
  22627. toggleOnExecute: false
  22628. })
  22629. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  22630. getApi: getToggleApi,
  22631. onSetup: spec.onSetup
  22632. }, providersBackstage));
  22633. };
  22634. var fetchChoices = function (getApi, spec, providersBackstage) {
  22635. return function (comp) {
  22636. return Future.nu(function (callback) {
  22637. return spec.fetch(callback);
  22638. }).map(function (items) {
  22639. return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  22640. spec.onItemAction(getApi(comp), value);
  22641. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(function () {
  22642. return false;
  22643. }), providersBackstage), {
  22644. movement: deriveMenuMovement(spec.columns, spec.presets),
  22645. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, se) {
  22646. detectSize(comp, 4, classForPreset(spec.presets)).each(function (_a) {
  22647. var numRows = _a.numRows, numColumns = _a.numColumns;
  22648. Keying.setGridSize(comp, numRows, numColumns);
  22649. });
  22650. })])
  22651. })));
  22652. });
  22653. };
  22654. };
  22655. var renderSplitButton = function (spec, sharedBackstage) {
  22656. var _a;
  22657. var displayChannel = generate$1('channel-update-split-dropdown-display');
  22658. var getApi = function (comp) {
  22659. return {
  22660. isDisabled: function () {
  22661. return Disabling.isDisabled(comp);
  22662. },
  22663. setDisabled: function (state) {
  22664. return Disabling.set(comp, state);
  22665. },
  22666. setIconFill: function (id, value) {
  22667. descendant$1(comp.element(), 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  22668. set$1(underlinePath, 'fill', value);
  22669. });
  22670. },
  22671. setIconStroke: function (id, value) {
  22672. descendant$1(comp.element(), 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  22673. set$1(underlinePath, 'stroke', value);
  22674. });
  22675. },
  22676. setActive: function (state) {
  22677. set$1(comp.element(), 'aria-pressed', state);
  22678. descendant$1(comp.element(), 'span').each(function (button) {
  22679. comp.getSystem().getByDom(button).each(function (buttonComp) {
  22680. return Toggling.set(buttonComp, state);
  22681. });
  22682. });
  22683. },
  22684. isActive: function () {
  22685. return descendant$1(comp.element(), 'span').exists(function (button) {
  22686. return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  22687. });
  22688. }
  22689. };
  22690. };
  22691. var editorOffCell = Cell(noop);
  22692. var specialisation = {
  22693. getApi: getApi,
  22694. onSetup: spec.onSetup
  22695. };
  22696. return SplitDropdown.sketch({
  22697. dom: {
  22698. tag: 'div',
  22699. classes: ['tox-split-button'],
  22700. attributes: merge({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  22701. },
  22702. onExecute: function (button) {
  22703. spec.onAction(getApi(button));
  22704. },
  22705. onItemExecute: function (a, b, c) {
  22706. },
  22707. splitDropdownBehaviours: derive$1([
  22708. DisablingConfigs.splitButton(false),
  22709. config('split-dropdown-events', [
  22710. run(focusButtonEvent, Focusing.focus),
  22711. onControlAttached(specialisation, editorOffCell),
  22712. onControlDetached(specialisation, editorOffCell)
  22713. ]),
  22714. Unselecting.config({})
  22715. ]),
  22716. eventOrder: (_a = {}, _a[attachedToDom()] = [
  22717. 'alloy.base.behaviour',
  22718. 'split-dropdown-events'
  22719. ], _a),
  22720. toggleClass: 'tox-tbtn--enabled',
  22721. lazySink: sharedBackstage.getSink,
  22722. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  22723. parts: { menu: part(false, spec.columns, spec.presets) },
  22724. components: [
  22725. SplitDropdown.parts().button(renderCommonStructure(spec.icon, spec.text, Option.none(), Option.some(displayChannel), Option.some([Toggling.config({
  22726. toggleClass: 'tox-tbtn--enabled',
  22727. toggleOnExecute: false
  22728. })]), sharedBackstage.providers)),
  22729. SplitDropdown.parts().arrow({
  22730. dom: {
  22731. tag: 'button',
  22732. classes: [
  22733. 'tox-tbtn',
  22734. 'tox-split-button__chevron'
  22735. ],
  22736. innerHtml: get$c('chevron-down', sharedBackstage.providers.icons)
  22737. }
  22738. }),
  22739. SplitDropdown.parts()['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  22740. ]
  22741. });
  22742. };
  22743. var getFormApi = function (input) {
  22744. return {
  22745. hide: function () {
  22746. return emit(input, sandboxClose());
  22747. },
  22748. getValue: function () {
  22749. return Representing.getValue(input);
  22750. }
  22751. };
  22752. };
  22753. var runOnExecute$1 = function (memInput, original) {
  22754. return run(internalToolbarButtonExecute, function (comp, se) {
  22755. var input = memInput.get(comp);
  22756. var formApi = getFormApi(input);
  22757. original.onAction(formApi, se.event().buttonApi());
  22758. });
  22759. };
  22760. var renderContextButton = function (memInput, button, extras) {
  22761. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  22762. var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  22763. type: 'button',
  22764. onAction: function () {
  22765. }
  22766. })));
  22767. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  22768. };
  22769. var renderContextToggleButton = function (memInput, button, extras) {
  22770. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  22771. var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  22772. type: 'togglebutton',
  22773. onAction: function () {
  22774. }
  22775. })));
  22776. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  22777. };
  22778. var generateOne$1 = function (memInput, button, providersBackstage) {
  22779. var extras = { backstage: { shared: { providers: providersBackstage } } };
  22780. if (button.type === 'contextformtogglebutton') {
  22781. return renderContextToggleButton(memInput, button, extras);
  22782. } else {
  22783. return renderContextButton(memInput, button, extras);
  22784. }
  22785. };
  22786. var generate$7 = function (memInput, buttons, providersBackstage) {
  22787. var mementos = map(buttons, function (button) {
  22788. return record(generateOne$1(memInput, button, providersBackstage));
  22789. });
  22790. var asSpecs = function () {
  22791. return map(mementos, function (mem) {
  22792. return mem.asSpec();
  22793. });
  22794. };
  22795. var findPrimary = function (compInSystem) {
  22796. return findMap(buttons, function (button, i) {
  22797. if (button.primary) {
  22798. return Option.from(mementos[i]).bind(function (mem) {
  22799. return mem.getOpt(compInSystem);
  22800. }).filter(not(Disabling.isDisabled));
  22801. } else {
  22802. return Option.none();
  22803. }
  22804. });
  22805. };
  22806. return {
  22807. asSpecs: asSpecs,
  22808. findPrimary: findPrimary
  22809. };
  22810. };
  22811. var renderContextForm = function (ctx, backstage) {
  22812. var inputAttributes = ctx.label.fold(function () {
  22813. return {};
  22814. }, function (label) {
  22815. return { 'aria-label': label };
  22816. });
  22817. var memInput = record(Input.sketch({
  22818. inputClasses: [
  22819. 'tox-toolbar-textfield',
  22820. 'tox-toolbar-nav-js'
  22821. ],
  22822. data: ctx.initValue(),
  22823. inputAttributes: inputAttributes,
  22824. selectOnFocus: true,
  22825. inputBehaviours: derive$1([Keying.config({
  22826. mode: 'special',
  22827. onEnter: function (input) {
  22828. return commands.findPrimary(input).map(function (primary) {
  22829. emitExecute(primary);
  22830. return true;
  22831. });
  22832. },
  22833. onLeft: function (comp, se) {
  22834. se.cut();
  22835. return Option.none();
  22836. },
  22837. onRight: function (comp, se) {
  22838. se.cut();
  22839. return Option.none();
  22840. }
  22841. })])
  22842. }));
  22843. var commands = generate$7(memInput, ctx.commands, backstage.shared.providers);
  22844. return renderToolbar({
  22845. uid: generate$1('context-toolbar'),
  22846. initGroups: [
  22847. {
  22848. title: Option.none(),
  22849. items: [memInput.asSpec()]
  22850. },
  22851. {
  22852. title: Option.none(),
  22853. items: commands.asSpecs()
  22854. }
  22855. ],
  22856. onEscape: Option.none,
  22857. cyclicKeying: true,
  22858. backstage: backstage,
  22859. getSink: function () {
  22860. return Result.error('');
  22861. }
  22862. });
  22863. };
  22864. var ContextForm = { renderContextForm: renderContextForm };
  22865. var getHorizontalBounds = function (contentAreaBox, viewportBounds) {
  22866. var x = Math.max(viewportBounds.x(), contentAreaBox.x());
  22867. var contentBoxWidth = contentAreaBox.right() - x;
  22868. var maxViewportWidth = viewportBounds.width() - (x - viewportBounds.x());
  22869. var width = Math.min(contentBoxWidth, maxViewportWidth);
  22870. return {
  22871. x: x,
  22872. width: width
  22873. };
  22874. };
  22875. var getIframeBounds = function (editor, contentAreaBox, viewportBounds) {
  22876. var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
  22877. var container = Element.fromDom(editor.getContainer());
  22878. var header = descendant$1(container, '.tox-editor-header').getOr(container);
  22879. var containerBox = box(container);
  22880. var headerBox = box(header);
  22881. var y = Math.max(viewportBounds.y(), contentAreaBox.y(), headerBox.bottom());
  22882. var contentBoxHeight = containerBox.bottom() - y;
  22883. var maxViewportHeight = viewportBounds.height() - (y - viewportBounds.y());
  22884. var height = Math.min(contentBoxHeight, maxViewportHeight);
  22885. return bounds$1(x, y, width, height);
  22886. };
  22887. var getInlineBounds = function (editor, contentAreaBox, viewportBounds) {
  22888. var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
  22889. var container = Element.fromDom(editor.getContainer());
  22890. var header = descendant$1(container, '.tox-editor-header').getOr(container);
  22891. var headerBox = box(header);
  22892. var vpHeight = viewportBounds.height();
  22893. var vpTop = viewportBounds.y();
  22894. if (headerBox.y() >= contentAreaBox.bottom()) {
  22895. var bottom = Math.min(vpHeight + vpTop, headerBox.y());
  22896. var height = bottom - vpTop;
  22897. return bounds$1(x, vpTop, width, height);
  22898. } else {
  22899. var y = Math.max(vpTop, headerBox.bottom());
  22900. var height = vpHeight - (y - vpTop);
  22901. return bounds$1(x, y, width, height);
  22902. }
  22903. };
  22904. var getDistractionFreeBounds = function (_editor, contentAreaBox, viewportBounds) {
  22905. var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
  22906. return bounds$1(x, viewportBounds.y(), width, viewportBounds.height());
  22907. };
  22908. var getBounds$2 = function (editor, toolbarOrMenubarEnabled) {
  22909. var viewportBounds = getBounds(domGlobals.window);
  22910. var contentAreaBox = box(Element.fromDom(editor.getContentAreaContainer()));
  22911. if (editor.inline && !toolbarOrMenubarEnabled) {
  22912. return Option.some(getDistractionFreeBounds(editor, contentAreaBox, viewportBounds));
  22913. } else if (editor.inline) {
  22914. return Option.some(getInlineBounds(editor, contentAreaBox, viewportBounds));
  22915. } else {
  22916. return Option.some(getIframeBounds(editor, contentAreaBox, viewportBounds));
  22917. }
  22918. };
  22919. var ancestor$2 = function (scope, transform, isRoot) {
  22920. var element = scope.dom();
  22921. var stop = isFunction(isRoot) ? isRoot : constant(false);
  22922. while (element.parentNode) {
  22923. element = element.parentNode;
  22924. var el = Element.fromDom(element);
  22925. var transformed = transform(el);
  22926. if (transformed.isSome()) {
  22927. return transformed;
  22928. } else if (stop(el)) {
  22929. break;
  22930. }
  22931. }
  22932. return Option.none();
  22933. };
  22934. var matchTargetWith = function (elem, toolbars) {
  22935. return findMap(toolbars, function (toolbarApi) {
  22936. return toolbarApi.predicate(elem.dom()) ? Option.some({
  22937. toolbarApi: toolbarApi,
  22938. elem: elem
  22939. }) : Option.none();
  22940. });
  22941. };
  22942. var lookup$1 = function (scopes, editor) {
  22943. var isRoot = function (elem) {
  22944. return elem.dom() === editor.getBody();
  22945. };
  22946. var startNode = Element.fromDom(editor.selection.getNode());
  22947. return matchTargetWith(startNode, scopes.inNodeScope).orThunk(function () {
  22948. return matchTargetWith(startNode, scopes.inEditorScope).orThunk(function () {
  22949. return ancestor$2(startNode, function (elem) {
  22950. return matchTargetWith(elem, scopes.inNodeScope);
  22951. }, isRoot);
  22952. });
  22953. });
  22954. };
  22955. var ToolbarLookup = { lookup: lookup$1 };
  22956. var categorise = function (contextToolbars, navigate) {
  22957. var forms = {};
  22958. var inNodeScope = [];
  22959. var inEditorScope = [];
  22960. var formNavigators = {};
  22961. var lookupTable = {};
  22962. var registerForm = function (key, toolbarApi) {
  22963. var contextForm = getOrDie(createContextForm(toolbarApi));
  22964. forms[key] = contextForm;
  22965. contextForm.launch.map(function (launch) {
  22966. formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarApi.launch), {
  22967. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  22968. onAction: function () {
  22969. navigate(contextForm);
  22970. }
  22971. });
  22972. });
  22973. if (contextForm.scope === 'editor') {
  22974. inEditorScope.push(contextForm);
  22975. } else {
  22976. inNodeScope.push(contextForm);
  22977. }
  22978. lookupTable[key] = contextForm;
  22979. };
  22980. var registerToolbar = function (key, toolbarApi) {
  22981. createContextToolbar(toolbarApi).each(function (contextToolbar) {
  22982. if (toolbarApi.scope === 'editor') {
  22983. inEditorScope.push(contextToolbar);
  22984. } else {
  22985. inNodeScope.push(contextToolbar);
  22986. }
  22987. lookupTable[key] = contextToolbar;
  22988. });
  22989. };
  22990. var keys$1 = keys(contextToolbars);
  22991. each(keys$1, function (key) {
  22992. var toolbarApi = contextToolbars[key];
  22993. if (toolbarApi.type === 'contextform') {
  22994. registerForm(key, toolbarApi);
  22995. } else if (toolbarApi.type === 'contexttoolbar') {
  22996. registerToolbar(key, toolbarApi);
  22997. }
  22998. });
  22999. return {
  23000. forms: forms,
  23001. inNodeScope: inNodeScope,
  23002. inEditorScope: inEditorScope,
  23003. lookupTable: lookupTable,
  23004. formNavigators: formNavigators
  23005. };
  23006. };
  23007. var ToolbarScopes = { categorise: categorise };
  23008. var forwardSlideEvent = generate$1('forward-slide');
  23009. var backSlideEvent = generate$1('backward-slide');
  23010. var changeSlideEvent = generate$1('change-slide-event');
  23011. var resizingClass = 'tox-pop--resizing';
  23012. var renderContextToolbar = function (spec) {
  23013. var stack = Cell([]);
  23014. return InlineView.sketch({
  23015. dom: {
  23016. tag: 'div',
  23017. classes: ['tox-pop']
  23018. },
  23019. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  23020. onShow: function (comp) {
  23021. stack.set([]);
  23022. InlineView.getContent(comp).each(function (c) {
  23023. remove$6(c.element(), 'visibility');
  23024. });
  23025. remove$4(comp.element(), resizingClass);
  23026. remove$6(comp.element(), 'width');
  23027. },
  23028. inlineBehaviours: derive$1([
  23029. config('context-toolbar-events', [
  23030. runOnSource(transitionend(), function (comp, se) {
  23031. InlineView.getContent(comp).each(function (c) {
  23032. });
  23033. remove$4(comp.element(), resizingClass);
  23034. remove$6(comp.element(), 'width');
  23035. }),
  23036. run(changeSlideEvent, function (comp, se) {
  23037. remove$6(comp.element(), 'width');
  23038. var currentWidth = get$7(comp.element());
  23039. InlineView.setContent(comp, se.event().contents());
  23040. add$2(comp.element(), resizingClass);
  23041. var newWidth = get$7(comp.element());
  23042. set$2(comp.element(), 'width', currentWidth + 'px');
  23043. InlineView.getContent(comp).each(function (newContents) {
  23044. se.event().focus().bind(function (f) {
  23045. focus$1(f);
  23046. return search(comp.element());
  23047. }).orThunk(function () {
  23048. Keying.focusIn(newContents);
  23049. return active();
  23050. });
  23051. });
  23052. global$2.setTimeout(function () {
  23053. set$2(comp.element(), 'width', newWidth + 'px');
  23054. }, 0);
  23055. }),
  23056. run(forwardSlideEvent, function (comp, se) {
  23057. InlineView.getContent(comp).each(function (oldContents) {
  23058. stack.set(stack.get().concat([{
  23059. bar: oldContents,
  23060. focus: active()
  23061. }]));
  23062. });
  23063. emitWith(comp, changeSlideEvent, {
  23064. contents: se.event().forwardContents(),
  23065. focus: Option.none()
  23066. });
  23067. }),
  23068. run(backSlideEvent, function (comp, se) {
  23069. last(stack.get()).each(function (last) {
  23070. stack.set(stack.get().slice(0, stack.get().length - 1));
  23071. emitWith(comp, changeSlideEvent, {
  23072. contents: premade$1(last.bar),
  23073. focus: last.focus
  23074. });
  23075. });
  23076. })
  23077. ]),
  23078. Keying.config({
  23079. mode: 'special',
  23080. onEscape: function (comp) {
  23081. return last(stack.get()).fold(function () {
  23082. return spec.onEscape();
  23083. }, function (_) {
  23084. emit(comp, backSlideEvent);
  23085. return Option.some(true);
  23086. });
  23087. }
  23088. })
  23089. ]),
  23090. lazySink: function () {
  23091. return Result.value(spec.sink);
  23092. }
  23093. });
  23094. };
  23095. var onSetupFormatToggle = function (editor, name) {
  23096. return function (api) {
  23097. var unbindCell = Cell(Option.none());
  23098. var init = function () {
  23099. api.setActive(editor.formatter.match(name));
  23100. var unbind = editor.formatter.formatChanged(name, api.setActive).unbind;
  23101. unbindCell.set(Option.some(unbind));
  23102. };
  23103. editor.initialized ? init() : editor.on('init', init);
  23104. return function () {
  23105. return unbindCell.get().each(function (unbind) {
  23106. return unbind();
  23107. });
  23108. };
  23109. };
  23110. };
  23111. var onActionToggleFormat = function (editor) {
  23112. return function (rawItem) {
  23113. return function () {
  23114. editor.undoManager.transact(function () {
  23115. editor.focus();
  23116. editor.execCommand('mceToggleFormat', false, rawItem.format);
  23117. });
  23118. };
  23119. };
  23120. };
  23121. var generateSelectItems = function (_editor, backstage, spec) {
  23122. var generateItem = function (rawItem, response, disabled, value) {
  23123. var translatedText = backstage.shared.providers.translate(rawItem.title);
  23124. if (rawItem.type === 'separator') {
  23125. return Option.some({
  23126. type: 'separator',
  23127. text: translatedText
  23128. });
  23129. } else if (rawItem.type === 'submenu') {
  23130. var items = bind(rawItem.getStyleItems(), function (si) {
  23131. return validate(si, response, value);
  23132. });
  23133. if (response === 0 && items.length <= 0) {
  23134. return Option.none();
  23135. } else {
  23136. return Option.some({
  23137. type: 'nestedmenuitem',
  23138. text: translatedText,
  23139. disabled: items.length <= 0,
  23140. getSubmenuItems: function () {
  23141. return bind(rawItem.getStyleItems(), function (si) {
  23142. return validate(si, response, value);
  23143. });
  23144. }
  23145. });
  23146. }
  23147. } else {
  23148. return Option.some(__assign({
  23149. type: 'togglemenuitem',
  23150. text: translatedText,
  23151. active: rawItem.isSelected(value),
  23152. disabled: disabled,
  23153. onAction: spec.onAction(rawItem)
  23154. }, rawItem.getStylePreview().fold(function () {
  23155. return {};
  23156. }, function (preview) {
  23157. return { meta: { style: preview } };
  23158. })));
  23159. }
  23160. };
  23161. var validate = function (item, response, value) {
  23162. var invalid = item.type === 'formatter' && spec.isInvalid(item);
  23163. if (response === 0) {
  23164. return invalid ? [] : generateItem(item, response, false, value).toArray();
  23165. } else {
  23166. return generateItem(item, response, invalid, value).toArray();
  23167. }
  23168. };
  23169. var validateItems = function (preItems) {
  23170. var value = spec.getCurrentValue();
  23171. var response = spec.shouldHide ? 0 : 1;
  23172. return bind(preItems, function (item) {
  23173. return validate(item, response, value);
  23174. });
  23175. };
  23176. var getFetch = function (backstage, getStyleItems) {
  23177. return function (callback) {
  23178. var preItems = getStyleItems();
  23179. var items = validateItems(preItems);
  23180. var menu = build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  23181. callback(menu);
  23182. };
  23183. };
  23184. return {
  23185. validateItems: validateItems,
  23186. getFetch: getFetch
  23187. };
  23188. };
  23189. var createMenuItems = function (editor, backstage, spec) {
  23190. var dataset = spec.dataset;
  23191. var getStyleItems = dataset.type === 'basic' ? function () {
  23192. return map(dataset.data, function (d) {
  23193. return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  23194. });
  23195. } : dataset.getData;
  23196. return {
  23197. items: generateSelectItems(editor, backstage, spec),
  23198. getStyleItems: getStyleItems
  23199. };
  23200. };
  23201. var createSelectButton = function (editor, backstage, spec) {
  23202. var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  23203. var getApi = function (comp) {
  23204. return {
  23205. getComponent: function () {
  23206. return comp;
  23207. }
  23208. };
  23209. };
  23210. var onSetup = function (api) {
  23211. spec.setInitialValue.each(function (f) {
  23212. return f(api.getComponent());
  23213. });
  23214. return spec.nodeChangeHandler.map(function (f) {
  23215. var handler = f(api.getComponent());
  23216. editor.on('NodeChange', handler);
  23217. return function () {
  23218. editor.off('NodeChange', handler);
  23219. };
  23220. }).getOr(noop);
  23221. };
  23222. return renderCommonDropdown({
  23223. text: spec.icon.isSome() ? Option.none() : Option.some(''),
  23224. icon: spec.icon,
  23225. tooltip: Option.from(spec.tooltip),
  23226. role: Option.none(),
  23227. fetch: items.getFetch(backstage, getStyleItems),
  23228. onSetup: onSetup,
  23229. getApi: getApi,
  23230. columns: 1,
  23231. presets: 'normal',
  23232. classes: spec.icon.isSome() ? [] : ['bespoke'],
  23233. dropdownBehaviours: []
  23234. }, 'tox-tbtn', backstage.shared);
  23235. };
  23236. var process = function (rawFormats) {
  23237. return map(rawFormats, function (item) {
  23238. var title = item, format = item;
  23239. var values = item.split('=');
  23240. if (values.length > 1) {
  23241. title = values[0];
  23242. format = values[1];
  23243. }
  23244. return {
  23245. title: title,
  23246. format: format
  23247. };
  23248. });
  23249. };
  23250. var buildBasicStaticDataset = function (data) {
  23251. return {
  23252. type: 'basic',
  23253. data: data
  23254. };
  23255. };
  23256. var Delimiter;
  23257. (function (Delimiter) {
  23258. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  23259. Delimiter[Delimiter['Space'] = 1] = 'Space';
  23260. }(Delimiter || (Delimiter = {})));
  23261. var split = function (rawFormats, delimiter) {
  23262. if (delimiter === Delimiter.SemiColon) {
  23263. return rawFormats.replace(/;$/, '').split(';');
  23264. } else {
  23265. return rawFormats.split(' ');
  23266. }
  23267. };
  23268. var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  23269. var rawFormats = readOptFrom$1(editor.settings, settingName).getOr(defaults);
  23270. var data = process(split(rawFormats, delimiter));
  23271. return {
  23272. type: 'basic',
  23273. data: data
  23274. };
  23275. };
  23276. var alignMenuItems = [
  23277. {
  23278. title: 'Left',
  23279. icon: 'align-left',
  23280. format: 'alignleft'
  23281. },
  23282. {
  23283. title: 'Center',
  23284. icon: 'align-center',
  23285. format: 'aligncenter'
  23286. },
  23287. {
  23288. title: 'Right',
  23289. icon: 'align-right',
  23290. format: 'alignright'
  23291. },
  23292. {
  23293. title: 'Justify',
  23294. icon: 'align-justify',
  23295. format: 'alignjustify'
  23296. }
  23297. ];
  23298. var getSpec = function (editor) {
  23299. var getMatchingValue = function () {
  23300. return find(alignMenuItems, function (item) {
  23301. return editor.formatter.match(item.format);
  23302. });
  23303. };
  23304. var isSelectedFor = function (format) {
  23305. return function () {
  23306. return editor.formatter.match(format);
  23307. };
  23308. };
  23309. var getPreviewFor = function (_format) {
  23310. return function () {
  23311. return Option.none();
  23312. };
  23313. };
  23314. var updateSelectMenuIcon = function (comp) {
  23315. var match = getMatchingValue();
  23316. var alignment = match.fold(function () {
  23317. return 'left';
  23318. }, function (item) {
  23319. return item.title.toLowerCase();
  23320. });
  23321. emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  23322. };
  23323. var nodeChangeHandler = Option.some(function (comp) {
  23324. return function () {
  23325. return updateSelectMenuIcon(comp);
  23326. };
  23327. });
  23328. var setInitialValue = Option.some(function (comp) {
  23329. return updateSelectMenuIcon(comp);
  23330. });
  23331. var dataset = buildBasicStaticDataset(alignMenuItems);
  23332. return {
  23333. tooltip: 'Align',
  23334. icon: Option.some('align-left'),
  23335. isSelectedFor: isSelectedFor,
  23336. getCurrentValue: constant(Option.none()),
  23337. getPreviewFor: getPreviewFor,
  23338. onAction: onActionToggleFormat(editor),
  23339. setInitialValue: setInitialValue,
  23340. nodeChangeHandler: nodeChangeHandler,
  23341. dataset: dataset,
  23342. shouldHide: false,
  23343. isInvalid: function (item) {
  23344. return !editor.formatter.canApply(item.format);
  23345. }
  23346. };
  23347. };
  23348. var createAlignSelect = function (editor, backstage) {
  23349. return createSelectButton(editor, backstage, getSpec(editor));
  23350. };
  23351. var alignSelectMenu = function (editor, backstage) {
  23352. var menuItems = createMenuItems(editor, backstage, getSpec(editor));
  23353. editor.ui.registry.addNestedMenuItem('align', {
  23354. text: backstage.shared.providers.translate('Align'),
  23355. getSubmenuItems: function () {
  23356. return menuItems.items.validateItems(menuItems.getStyleItems());
  23357. }
  23358. });
  23359. };
  23360. 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';
  23361. var systemStackFonts = [
  23362. '-apple-system',
  23363. 'Segoe UI',
  23364. 'Roboto',
  23365. 'Helvetica Neue',
  23366. 'sans-serif'
  23367. ];
  23368. var splitFonts = function (fontFamily) {
  23369. var fonts = fontFamily.split(/\s*,\s*/);
  23370. return map(fonts, function (font) {
  23371. return font.replace(/^['"]+|['"]+$/g, '');
  23372. });
  23373. };
  23374. var isSystemFontStack = function (fontFamily) {
  23375. var matchesSystemStack = function () {
  23376. var fonts = splitFonts(fontFamily.toLowerCase());
  23377. return forall(systemStackFonts, function (font) {
  23378. return fonts.indexOf(font.toLowerCase()) > -1;
  23379. });
  23380. };
  23381. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  23382. };
  23383. var getSpec$1 = function (editor) {
  23384. var getMatchingValue = function () {
  23385. var getFirstFont = function (fontFamily) {
  23386. return fontFamily ? splitFonts(fontFamily)[0] : '';
  23387. };
  23388. var fontFamily = editor.queryCommandValue('FontName');
  23389. var items = dataset.data;
  23390. var font = fontFamily ? fontFamily.toLowerCase() : '';
  23391. var matchOpt = find(items, function (item) {
  23392. var format = item.format;
  23393. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  23394. }).orThunk(function () {
  23395. if (isSystemFontStack(font)) {
  23396. return Option.from({
  23397. title: 'System Font',
  23398. format: font
  23399. });
  23400. } else {
  23401. return Option.none();
  23402. }
  23403. });
  23404. return {
  23405. matchOpt: matchOpt,
  23406. font: fontFamily
  23407. };
  23408. };
  23409. var isSelectedFor = function (item) {
  23410. return function (valueOpt) {
  23411. return valueOpt.exists(function (value) {
  23412. return value.format === item;
  23413. });
  23414. };
  23415. };
  23416. var getCurrentValue = function () {
  23417. var matchOpt = getMatchingValue().matchOpt;
  23418. return matchOpt;
  23419. };
  23420. var getPreviewFor = function (item) {
  23421. return function () {
  23422. return Option.some({
  23423. tag: 'div',
  23424. styleAttr: item.indexOf('dings') === -1 ? 'font-family:' + item : ''
  23425. });
  23426. };
  23427. };
  23428. var onAction = function (rawItem) {
  23429. return function () {
  23430. editor.undoManager.transact(function () {
  23431. editor.focus();
  23432. editor.execCommand('FontName', false, rawItem.format);
  23433. });
  23434. };
  23435. };
  23436. var updateSelectMenuText = function (comp) {
  23437. var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  23438. var text = matchOpt.fold(function () {
  23439. return font;
  23440. }, function (item) {
  23441. return item.title;
  23442. });
  23443. emitWith(comp, updateMenuText, { text: text });
  23444. };
  23445. var nodeChangeHandler = Option.some(function (comp) {
  23446. return function () {
  23447. return updateSelectMenuText(comp);
  23448. };
  23449. });
  23450. var setInitialValue = Option.some(function (comp) {
  23451. return updateSelectMenuText(comp);
  23452. });
  23453. var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  23454. return {
  23455. tooltip: 'Fonts',
  23456. icon: Option.none(),
  23457. isSelectedFor: isSelectedFor,
  23458. getCurrentValue: getCurrentValue,
  23459. getPreviewFor: getPreviewFor,
  23460. onAction: onAction,
  23461. setInitialValue: setInitialValue,
  23462. nodeChangeHandler: nodeChangeHandler,
  23463. dataset: dataset,
  23464. shouldHide: false,
  23465. isInvalid: function () {
  23466. return false;
  23467. }
  23468. };
  23469. };
  23470. var createFontSelect = function (editor, backstage) {
  23471. return createSelectButton(editor, backstage, getSpec$1(editor));
  23472. };
  23473. var fontSelectMenu = function (editor, backstage) {
  23474. var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  23475. editor.ui.registry.addNestedMenuItem('fontformats', {
  23476. text: backstage.shared.providers.translate('Fonts'),
  23477. getSubmenuItems: function () {
  23478. return menuItems.items.validateItems(menuItems.getStyleItems());
  23479. }
  23480. });
  23481. };
  23482. var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  23483. var legacyFontSizes = {
  23484. '8pt': '1',
  23485. '10pt': '2',
  23486. '12pt': '3',
  23487. '14pt': '4',
  23488. '18pt': '5',
  23489. '24pt': '6',
  23490. '36pt': '7'
  23491. };
  23492. var round$1 = function (number, precision) {
  23493. var factor = Math.pow(10, precision);
  23494. return Math.round(number * factor) / factor;
  23495. };
  23496. var toPt = function (fontSize, precision) {
  23497. if (/[0-9.]+px$/.test(fontSize)) {
  23498. return round$1(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  23499. }
  23500. return fontSize;
  23501. };
  23502. var toLegacy = function (fontSize) {
  23503. return get(legacyFontSizes, fontSize).getOr('');
  23504. };
  23505. var getSpec$2 = function (editor) {
  23506. var getMatchingValue = function () {
  23507. var matchOpt = Option.none();
  23508. var items = dataset.data;
  23509. var px = editor.queryCommandValue('FontSize');
  23510. if (px) {
  23511. var _loop_1 = function (precision) {
  23512. var pt = toPt(px, precision);
  23513. var legacy = toLegacy(pt);
  23514. matchOpt = find(items, function (item) {
  23515. return item.format === px || item.format === pt || item.format === legacy;
  23516. });
  23517. };
  23518. for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  23519. _loop_1(precision);
  23520. }
  23521. }
  23522. return {
  23523. matchOpt: matchOpt,
  23524. px: px
  23525. };
  23526. };
  23527. var isSelectedFor = function (item) {
  23528. return function (valueOpt) {
  23529. return valueOpt.exists(function (value) {
  23530. return value.format === item;
  23531. });
  23532. };
  23533. };
  23534. var getCurrentValue = function () {
  23535. var matchOpt = getMatchingValue().matchOpt;
  23536. return matchOpt;
  23537. };
  23538. var getPreviewFor = constant(constant(Option.none()));
  23539. var onAction = function (rawItem) {
  23540. return function () {
  23541. editor.undoManager.transact(function () {
  23542. editor.focus();
  23543. editor.execCommand('FontSize', false, rawItem.format);
  23544. });
  23545. };
  23546. };
  23547. var updateSelectMenuText = function (comp) {
  23548. var _a = getMatchingValue(), matchOpt = _a.matchOpt, px = _a.px;
  23549. var text = matchOpt.fold(function () {
  23550. return px;
  23551. }, function (match) {
  23552. return match.title;
  23553. });
  23554. emitWith(comp, updateMenuText, { text: text });
  23555. };
  23556. var nodeChangeHandler = Option.some(function (comp) {
  23557. return function () {
  23558. return updateSelectMenuText(comp);
  23559. };
  23560. });
  23561. var setInitialValue = Option.some(function (comp) {
  23562. return updateSelectMenuText(comp);
  23563. });
  23564. var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  23565. return {
  23566. tooltip: 'Font sizes',
  23567. icon: Option.none(),
  23568. isSelectedFor: isSelectedFor,
  23569. getPreviewFor: getPreviewFor,
  23570. getCurrentValue: getCurrentValue,
  23571. onAction: onAction,
  23572. setInitialValue: setInitialValue,
  23573. nodeChangeHandler: nodeChangeHandler,
  23574. dataset: dataset,
  23575. shouldHide: false,
  23576. isInvalid: function () {
  23577. return false;
  23578. }
  23579. };
  23580. };
  23581. var createFontsizeSelect = function (editor, backstage) {
  23582. return createSelectButton(editor, backstage, getSpec$2(editor));
  23583. };
  23584. var fontsizeSelectMenu = function (editor, backstage) {
  23585. var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  23586. editor.ui.registry.addNestedMenuItem('fontsizes', {
  23587. text: 'Font sizes',
  23588. getSubmenuItems: function () {
  23589. return menuItems.items.validateItems(menuItems.getStyleItems());
  23590. }
  23591. });
  23592. };
  23593. var findNearest = function (editor, getStyles, parents) {
  23594. var styles = getStyles();
  23595. return findMap(parents, function (parent) {
  23596. return find(styles, function (fmt) {
  23597. return editor.formatter.matchNode(parent, fmt.format);
  23598. });
  23599. }).orThunk(function () {
  23600. if (editor.formatter.match('p')) {
  23601. return Option.some({
  23602. title: 'Paragraph',
  23603. format: 'p'
  23604. });
  23605. }
  23606. return Option.none();
  23607. });
  23608. };
  23609. var getCurrentSelectionParents = function (editor) {
  23610. var currentNode = editor.selection.getStart(true) || editor.getBody();
  23611. return editor.dom.getParents(currentNode, function () {
  23612. return true;
  23613. }, editor.getBody());
  23614. };
  23615. var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  23616. var getSpec$3 = function (editor) {
  23617. var getMatchingValue = function (nodeChangeEvent) {
  23618. return findNearest(editor, function () {
  23619. return dataset.data;
  23620. }, nodeChangeEvent);
  23621. };
  23622. var isSelectedFor = function (format) {
  23623. return function () {
  23624. return editor.formatter.match(format);
  23625. };
  23626. };
  23627. var getPreviewFor = function (format) {
  23628. return function () {
  23629. var fmt = editor.formatter.get(format);
  23630. return Option.some({
  23631. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23632. styleAttr: editor.formatter.getCssText(format)
  23633. });
  23634. };
  23635. };
  23636. var updateSelectMenuText = function (parents, comp) {
  23637. var detectedFormat = getMatchingValue(parents);
  23638. var text = detectedFormat.fold(function () {
  23639. return 'Paragraph';
  23640. }, function (fmt) {
  23641. return fmt.title;
  23642. });
  23643. emitWith(comp, updateMenuText, { text: text });
  23644. };
  23645. var nodeChangeHandler = Option.some(function (comp) {
  23646. return function (e) {
  23647. return updateSelectMenuText(e.parents, comp);
  23648. };
  23649. });
  23650. var setInitialValue = Option.some(function (comp) {
  23651. var parents = getCurrentSelectionParents(editor);
  23652. updateSelectMenuText(parents, comp);
  23653. });
  23654. var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  23655. return {
  23656. tooltip: 'Blocks',
  23657. icon: Option.none(),
  23658. isSelectedFor: isSelectedFor,
  23659. getCurrentValue: constant(Option.none()),
  23660. getPreviewFor: getPreviewFor,
  23661. onAction: onActionToggleFormat(editor),
  23662. setInitialValue: setInitialValue,
  23663. nodeChangeHandler: nodeChangeHandler,
  23664. dataset: dataset,
  23665. shouldHide: false,
  23666. isInvalid: function (item) {
  23667. return !editor.formatter.canApply(item.format);
  23668. }
  23669. };
  23670. };
  23671. var createFormatSelect = function (editor, backstage) {
  23672. return createSelectButton(editor, backstage, getSpec$3(editor));
  23673. };
  23674. var formatSelectMenu = function (editor, backstage) {
  23675. var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  23676. editor.ui.registry.addNestedMenuItem('blockformats', {
  23677. text: 'Blocks',
  23678. getSubmenuItems: function () {
  23679. return menuItems.items.validateItems(menuItems.getStyleItems());
  23680. }
  23681. });
  23682. };
  23683. var getSpec$4 = function (editor, dataset) {
  23684. var isSelectedFor = function (format) {
  23685. return function () {
  23686. return editor.formatter.match(format);
  23687. };
  23688. };
  23689. var getPreviewFor = function (format) {
  23690. return function () {
  23691. var fmt = editor.formatter.get(format);
  23692. return fmt !== undefined ? Option.some({
  23693. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23694. styleAttr: editor.formatter.getCssText(format)
  23695. }) : Option.none();
  23696. };
  23697. };
  23698. var updateSelectMenuText = function (parents, comp) {
  23699. var getFormatItems = function (fmt) {
  23700. var subs = fmt.items;
  23701. return subs !== undefined && subs.length > 0 ? bind(subs, getFormatItems) : [{
  23702. title: fmt.title,
  23703. format: fmt.format
  23704. }];
  23705. };
  23706. var flattenedItems = bind(getStyleFormats(editor), getFormatItems);
  23707. var detectedFormat = findNearest(editor, function () {
  23708. return flattenedItems;
  23709. }, parents);
  23710. var text = detectedFormat.fold(function () {
  23711. return 'Paragraph';
  23712. }, function (fmt) {
  23713. return fmt.title;
  23714. });
  23715. emitWith(comp, updateMenuText, { text: text });
  23716. };
  23717. var nodeChangeHandler = Option.some(function (comp) {
  23718. return function (e) {
  23719. return updateSelectMenuText(e.parents, comp);
  23720. };
  23721. });
  23722. var setInitialValue = Option.some(function (comp) {
  23723. var parents = getCurrentSelectionParents(editor);
  23724. updateSelectMenuText(parents, comp);
  23725. });
  23726. return {
  23727. tooltip: 'Formats',
  23728. icon: Option.none(),
  23729. isSelectedFor: isSelectedFor,
  23730. getCurrentValue: constant(Option.none()),
  23731. getPreviewFor: getPreviewFor,
  23732. onAction: onActionToggleFormat(editor),
  23733. setInitialValue: setInitialValue,
  23734. nodeChangeHandler: nodeChangeHandler,
  23735. shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  23736. isInvalid: function (item) {
  23737. return !editor.formatter.canApply(item.format);
  23738. },
  23739. dataset: dataset
  23740. };
  23741. };
  23742. var createStyleSelect = function (editor, backstage) {
  23743. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  23744. return createSelectButton(editor, backstage, getSpec$4(editor, dataset));
  23745. };
  23746. var styleSelectMenu = function (editor, backstage) {
  23747. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  23748. var menuItems = createMenuItems(editor, backstage, getSpec$4(editor, dataset));
  23749. editor.ui.registry.addNestedMenuItem('formats', {
  23750. text: 'Formats',
  23751. getSubmenuItems: function () {
  23752. return menuItems.items.validateItems(menuItems.getStyleItems());
  23753. }
  23754. });
  23755. };
  23756. var defaultToolbar = [
  23757. {
  23758. name: 'history',
  23759. items: [
  23760. 'undo',
  23761. 'redo'
  23762. ]
  23763. },
  23764. {
  23765. name: 'styles',
  23766. items: ['styleselect']
  23767. },
  23768. {
  23769. name: 'formatting',
  23770. items: [
  23771. 'bold',
  23772. 'italic'
  23773. ]
  23774. },
  23775. {
  23776. name: 'alignment',
  23777. items: [
  23778. 'alignleft',
  23779. 'aligncenter',
  23780. 'alignright',
  23781. 'alignjustify'
  23782. ]
  23783. },
  23784. {
  23785. name: 'indentation',
  23786. items: [
  23787. 'outdent',
  23788. 'indent'
  23789. ]
  23790. },
  23791. {
  23792. name: 'permanent pen',
  23793. items: ['permanentpen']
  23794. },
  23795. {
  23796. name: 'comments',
  23797. items: ['addcomment']
  23798. }
  23799. ];
  23800. var renderFromBridge = function (bridgeBuilder, render) {
  23801. return function (spec, extras) {
  23802. var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  23803. return formatError(errInfo);
  23804. }).getOrDie();
  23805. return render(internal, extras);
  23806. };
  23807. };
  23808. var types = {
  23809. button: renderFromBridge(createToolbarButton, function (s, extras) {
  23810. return renderToolbarButton(s, extras.backstage.shared.providers);
  23811. }),
  23812. togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  23813. return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  23814. }),
  23815. menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  23816. return renderMenuButton(s, 'tox-tbtn', extras.backstage, Option.none());
  23817. }),
  23818. splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  23819. return renderSplitButton(s, extras.backstage.shared);
  23820. }),
  23821. styleSelectButton: function (editor, extras) {
  23822. return createStyleSelect(editor, extras.backstage);
  23823. },
  23824. fontsizeSelectButton: function (editor, extras) {
  23825. return createFontsizeSelect(editor, extras.backstage);
  23826. },
  23827. fontSelectButton: function (editor, extras) {
  23828. return createFontSelect(editor, extras.backstage);
  23829. },
  23830. formatButton: function (editor, extras) {
  23831. return createFormatSelect(editor, extras.backstage);
  23832. },
  23833. alignMenuButton: function (editor, extras) {
  23834. return createAlignSelect(editor, extras.backstage);
  23835. }
  23836. };
  23837. var extractFrom = function (spec, extras) {
  23838. return get(types, spec.type).fold(function () {
  23839. domGlobals.console.error('skipping button defined by', spec);
  23840. return Option.none();
  23841. }, function (render) {
  23842. return Option.some(render(spec, extras));
  23843. });
  23844. };
  23845. var bespokeButtons = {
  23846. styleselect: types.styleSelectButton,
  23847. fontsizeselect: types.fontsizeSelectButton,
  23848. fontselect: types.fontSelectButton,
  23849. formatselect: types.formatButton,
  23850. align: types.alignMenuButton
  23851. };
  23852. var removeUnusedDefaults = function (buttons) {
  23853. var filteredItemGroups = map(defaultToolbar, function (group) {
  23854. var items = filter(group.items, function (subItem) {
  23855. return has(buttons, subItem) || has(bespokeButtons, subItem);
  23856. });
  23857. return {
  23858. name: group.name,
  23859. items: items
  23860. };
  23861. });
  23862. return filter(filteredItemGroups, function (group) {
  23863. return group.items.length > 0;
  23864. });
  23865. };
  23866. var convertStringToolbar = function (strToolbar) {
  23867. var groupsStrings = strToolbar.split('|');
  23868. return map(groupsStrings, function (g) {
  23869. return { items: g.trim().split(' ') };
  23870. });
  23871. };
  23872. var isToolbarGroupSettingArray = function (toolbar) {
  23873. return isArrayOf(toolbar, function (t) {
  23874. return has(t, 'name') && has(t, 'items');
  23875. });
  23876. };
  23877. var createToolbar = function (toolbarConfig) {
  23878. var toolbar = toolbarConfig.toolbar;
  23879. var buttons = toolbarConfig.buttons;
  23880. if (toolbar === false) {
  23881. return [];
  23882. } else if (toolbar === undefined || toolbar === true) {
  23883. return removeUnusedDefaults(buttons);
  23884. } else if (isString(toolbar)) {
  23885. return convertStringToolbar(toolbar);
  23886. } else if (isToolbarGroupSettingArray(toolbar)) {
  23887. return toolbar;
  23888. } else {
  23889. domGlobals.console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  23890. return [];
  23891. }
  23892. };
  23893. var lookupButton = function (editor, buttons, toolbarItem, extras, prefixes) {
  23894. return get(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  23895. return prefixes.bind(function (ps) {
  23896. return findMap(ps, function (prefix) {
  23897. return get(buttons, prefix + toolbarItem.toLowerCase());
  23898. });
  23899. });
  23900. }).fold(function () {
  23901. return get(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  23902. return r(editor, extras);
  23903. }).orThunk(function () {
  23904. return Option.none();
  23905. });
  23906. }, function (spec) {
  23907. return extractFrom(spec, extras);
  23908. });
  23909. };
  23910. var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  23911. var toolbarGroups = createToolbar(toolbarConfig);
  23912. var groups = map(toolbarGroups, function (group) {
  23913. var items = bind(group.items, function (toolbarItem) {
  23914. return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, extras, prefixes).toArray();
  23915. });
  23916. return {
  23917. title: Option.from(editor.translate(group.name)),
  23918. items: items
  23919. };
  23920. });
  23921. return filter(groups, function (group) {
  23922. return group.items.length > 0;
  23923. });
  23924. };
  23925. var bubbleSize = 12;
  23926. var bubbleAlignments$1 = {
  23927. valignCentre: [],
  23928. alignCentre: [],
  23929. alignLeft: ['tox-pop--align-left'],
  23930. alignRight: ['tox-pop--align-right'],
  23931. right: ['tox-pop--right'],
  23932. left: ['tox-pop--left'],
  23933. bottom: ['tox-pop--bottom'],
  23934. top: ['tox-pop--top']
  23935. };
  23936. var anchorOverrides = {
  23937. maxHeightFunction: expandable(),
  23938. maxWidthFunction: expandable$1()
  23939. };
  23940. var desktopAnchorSpecLayouts = {
  23941. onLtr: function () {
  23942. return [
  23943. north$1,
  23944. south$1,
  23945. northeast$1,
  23946. southeast$1,
  23947. northwest$1,
  23948. southwest$1,
  23949. north$3,
  23950. south$3,
  23951. northeast$3,
  23952. southeast$3,
  23953. northwest$3,
  23954. southwest$3
  23955. ];
  23956. },
  23957. onRtl: function () {
  23958. return [
  23959. north$1,
  23960. south$1,
  23961. northwest$1,
  23962. southwest$1,
  23963. northeast$1,
  23964. southeast$1,
  23965. north$3,
  23966. south$3,
  23967. northwest$3,
  23968. southwest$3,
  23969. northeast$3,
  23970. southeast$3
  23971. ];
  23972. }
  23973. };
  23974. var mobileAnchorSpecLayouts = {
  23975. onLtr: function () {
  23976. return [
  23977. south$1,
  23978. southeast$1,
  23979. southwest$1,
  23980. northeast$1,
  23981. northwest$1,
  23982. north$1,
  23983. north$3,
  23984. south$3,
  23985. northeast$3,
  23986. southeast$3,
  23987. northwest$3,
  23988. southwest$3
  23989. ];
  23990. },
  23991. onRtl: function () {
  23992. return [
  23993. south$1,
  23994. southwest$1,
  23995. southeast$1,
  23996. northwest$1,
  23997. northeast$1,
  23998. north$1,
  23999. north$3,
  24000. south$3,
  24001. northwest$3,
  24002. southwest$3,
  24003. northeast$3,
  24004. southeast$3
  24005. ];
  24006. }
  24007. };
  24008. var getAnchorLayout = function (position, isTouch) {
  24009. if (position === 'line') {
  24010. return {
  24011. bubble: nu$8(bubbleSize, 0, bubbleAlignments$1),
  24012. layouts: {
  24013. onLtr: function () {
  24014. return [east$1];
  24015. },
  24016. onRtl: function () {
  24017. return [west$1];
  24018. }
  24019. },
  24020. overrides: anchorOverrides
  24021. };
  24022. } else {
  24023. return {
  24024. bubble: nu$8(0, bubbleSize, bubbleAlignments$1),
  24025. layouts: isTouch ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts,
  24026. overrides: anchorOverrides
  24027. };
  24028. }
  24029. };
  24030. var register$4 = function (editor, registryContextToolbars, sink, extras) {
  24031. var isTouch = detect$3().deviceType.isTouch;
  24032. var contextbar = build$1(renderContextToolbar({
  24033. sink: sink,
  24034. onEscape: function () {
  24035. editor.focus();
  24036. return Option.some(true);
  24037. }
  24038. }));
  24039. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  24040. var getBounds = function () {
  24041. return getBounds$2(editor, toolbarOrMenubarEnabled);
  24042. };
  24043. var isCompletelyBehindHeader = function (nodeBounds) {
  24044. var headerEle = descendant$1(Element.fromDom(editor.getContainer()), '.tox-editor-header').getOrDie();
  24045. var isHeaderDocked = get$4(headerEle, 'position') === 'fixed';
  24046. if (toolbarOrMenubarEnabled && isHeaderDocked) {
  24047. var headerBounds = headerEle.dom().getBoundingClientRect();
  24048. if (editor.inline) {
  24049. return nodeBounds.bottom < headerBounds.bottom;
  24050. } else {
  24051. var scroll = get$8();
  24052. var bodyBounds = absolute$1(Element.fromDom(editor.getBody()));
  24053. var nodeBottom = nodeBounds.bottom + (bodyBounds.y() - scroll.top());
  24054. return nodeBottom < headerBounds.bottom;
  24055. }
  24056. } else {
  24057. return false;
  24058. }
  24059. };
  24060. var shouldContextToolbarHide = function () {
  24061. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24062. return true;
  24063. }
  24064. var nodeBounds = lastElement.get().map(function (ele) {
  24065. return ele.getBoundingClientRect();
  24066. }).getOrThunk(function () {
  24067. return editor.selection.getRng().getBoundingClientRect();
  24068. });
  24069. var viewportHeight = defaultView(Element.fromDom(editor.getBody())).dom().innerHeight;
  24070. var aboveViewport = nodeBounds.bottom < 0;
  24071. var belowViewport = nodeBounds.top > viewportHeight;
  24072. return aboveViewport || belowViewport || isCompletelyBehindHeader(nodeBounds);
  24073. };
  24074. var forceHide = function () {
  24075. InlineView.hide(contextbar);
  24076. };
  24077. var hideOrRepositionIfNecessary = function () {
  24078. lastAnchor.get().each(function (anchor) {
  24079. var contextBarEle = contextbar.element();
  24080. remove$6(contextBarEle, 'display');
  24081. if (shouldContextToolbarHide()) {
  24082. set$2(contextBarEle, 'display', 'none');
  24083. } else {
  24084. Positioning.positionWithinBounds(sink, anchor, contextbar, getBounds());
  24085. }
  24086. });
  24087. };
  24088. var lastAnchor = Cell(Option.none());
  24089. var lastElement = Cell(Option.none());
  24090. var timer = Cell(null);
  24091. var wrapInPopDialog = function (toolbarSpec) {
  24092. return {
  24093. dom: {
  24094. tag: 'div',
  24095. classes: ['tox-pop__dialog']
  24096. },
  24097. components: [toolbarSpec],
  24098. behaviours: derive$1([
  24099. Keying.config({ mode: 'acyclic' }),
  24100. config('pop-dialog-wrap-events', [
  24101. runOnAttached(function (comp) {
  24102. editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  24103. return Keying.focusIn(comp);
  24104. });
  24105. }),
  24106. runOnDetached(function (comp) {
  24107. editor.shortcuts.remove('ctrl+F9');
  24108. })
  24109. ])
  24110. ])
  24111. };
  24112. };
  24113. var getScopes = cached(function () {
  24114. return ToolbarScopes.categorise(registryContextToolbars, function (toolbarApi) {
  24115. var alloySpec = buildToolbar(toolbarApi);
  24116. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  24117. });
  24118. });
  24119. var buildToolbar = function (ctx) {
  24120. var buttons = editor.ui.registry.getAll().buttons;
  24121. var scopes = getScopes();
  24122. return ctx.type === 'contexttoolbar' ? function () {
  24123. var allButtons = merge(buttons, scopes.formNavigators);
  24124. var initGroups = identifyButtons(editor, {
  24125. buttons: allButtons,
  24126. toolbar: ctx.items
  24127. }, extras, Option.some(['form:']));
  24128. return renderToolbar({
  24129. uid: generate$1('context-toolbar'),
  24130. initGroups: initGroups,
  24131. onEscape: Option.none,
  24132. cyclicKeying: true,
  24133. backstage: extras.backstage,
  24134. getSink: function () {
  24135. return Result.error('');
  24136. }
  24137. });
  24138. }() : function () {
  24139. return ContextForm.renderContextForm(ctx, extras.backstage);
  24140. }();
  24141. };
  24142. editor.on(showContextToolbarEvent, function (e) {
  24143. var scopes = getScopes();
  24144. readOptFrom$1(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  24145. launchContext(ctx, e.target === editor ? Option.none() : Option.some(e));
  24146. InlineView.getContent(contextbar).each(Keying.focusIn);
  24147. });
  24148. });
  24149. var getAnchor = function (position, element) {
  24150. var anchorage = position === 'node' ? extras.backstage.shared.anchors.node(element) : extras.backstage.shared.anchors.cursor();
  24151. return deepMerge(anchorage, getAnchorLayout(position, isTouch()));
  24152. };
  24153. var launchContext = function (toolbarApi, elem) {
  24154. clearTimer();
  24155. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24156. return;
  24157. }
  24158. var toolbarSpec = buildToolbar(toolbarApi);
  24159. var sElem = elem.map(Element.fromDom);
  24160. var anchor = getAnchor(toolbarApi.position, sElem);
  24161. lastAnchor.set(Option.some(anchor));
  24162. lastElement.set(elem);
  24163. var contextBarEle = contextbar.element();
  24164. remove$6(contextBarEle, 'display');
  24165. InlineView.showWithinBounds(contextbar, anchor, wrapInPopDialog(toolbarSpec), getBounds);
  24166. if (shouldContextToolbarHide()) {
  24167. set$2(contextBarEle, 'display', 'none');
  24168. }
  24169. };
  24170. var launchContextToolbar = function () {
  24171. var scopes = getScopes();
  24172. ToolbarLookup.lookup(scopes, editor).fold(function () {
  24173. lastAnchor.set(Option.none());
  24174. InlineView.hide(contextbar);
  24175. }, function (info) {
  24176. launchContext(info.toolbarApi, Option.some(info.elem.dom()));
  24177. });
  24178. };
  24179. var clearTimer = function () {
  24180. var current = timer.get();
  24181. if (current !== null) {
  24182. global$2.clearTimeout(current);
  24183. timer.set(null);
  24184. }
  24185. };
  24186. var resetTimer = function (t) {
  24187. clearTimer();
  24188. timer.set(t);
  24189. };
  24190. editor.on('init', function () {
  24191. editor.on(hideContextToolbarEvent, forceHide);
  24192. editor.on('ScrollContent ScrollWindow longpress', hideOrRepositionIfNecessary);
  24193. editor.on('click keyup SetContent ObjectResized ResizeEditor', function (e) {
  24194. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24195. });
  24196. editor.on('focusout', function (e) {
  24197. global$2.setEditorTimeout(editor, function () {
  24198. if (search(sink.element()).isNone() && search(contextbar.element()).isNone()) {
  24199. lastAnchor.set(Option.none());
  24200. InlineView.hide(contextbar);
  24201. }
  24202. }, 0);
  24203. });
  24204. editor.on('SwitchMode', function () {
  24205. if (editor.readonly) {
  24206. lastAnchor.set(Option.none());
  24207. InlineView.hide(contextbar);
  24208. }
  24209. });
  24210. editor.on('NodeChange', function (e) {
  24211. search(contextbar.element()).fold(function () {
  24212. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24213. }, function (_) {
  24214. });
  24215. });
  24216. });
  24217. };
  24218. var ContextToolbar = { register: register$4 };
  24219. var setup$3 = function (editor, mothership, uiMothership) {
  24220. var onMousedown = bind$3(Element.fromDom(domGlobals.document), 'mousedown', function (evt) {
  24221. each([
  24222. mothership,
  24223. uiMothership
  24224. ], function (ship) {
  24225. ship.broadcastOn([dismissPopups()], { target: evt.target() });
  24226. });
  24227. });
  24228. var onTouchstart = bind$3(Element.fromDom(domGlobals.document), 'touchstart', function (evt) {
  24229. each([
  24230. mothership,
  24231. uiMothership
  24232. ], function (ship) {
  24233. ship.broadcastOn([dismissPopups()], { target: evt.target() });
  24234. });
  24235. });
  24236. var onTouchmove = bind$3(Element.fromDom(domGlobals.document), 'touchmove', function (evt) {
  24237. each([
  24238. mothership,
  24239. uiMothership
  24240. ], function (ship) {
  24241. ship.broadcastEvent(documentTouchmove(), evt);
  24242. });
  24243. });
  24244. var onTouchend = bind$3(Element.fromDom(domGlobals.document), 'touchend', function (evt) {
  24245. each([
  24246. mothership,
  24247. uiMothership
  24248. ], function (ship) {
  24249. ship.broadcastEvent(documentTouchend(), evt);
  24250. });
  24251. });
  24252. var onMouseup = bind$3(Element.fromDom(domGlobals.document), 'mouseup', function (evt) {
  24253. if (evt.raw().button === 0) {
  24254. each([
  24255. mothership,
  24256. uiMothership
  24257. ], function (ship) {
  24258. ship.broadcastOn([mouseReleased()], { target: evt.target() });
  24259. });
  24260. }
  24261. });
  24262. var onContentMousedown = function (raw) {
  24263. each([
  24264. mothership,
  24265. uiMothership
  24266. ], function (ship) {
  24267. ship.broadcastOn([dismissPopups()], { target: Element.fromDom(raw.target) });
  24268. });
  24269. };
  24270. var onContentMouseup = function (raw) {
  24271. if (raw.button === 0) {
  24272. each([
  24273. mothership,
  24274. uiMothership
  24275. ], function (ship) {
  24276. ship.broadcastOn([mouseReleased()], { target: Element.fromDom(raw.target) });
  24277. });
  24278. }
  24279. };
  24280. var onWindowScroll = function (evt) {
  24281. var sugarEvent = fromRawEvent$1(evt);
  24282. each([
  24283. mothership,
  24284. uiMothership
  24285. ], function (ship) {
  24286. ship.broadcastEvent(windowScroll(), sugarEvent);
  24287. });
  24288. };
  24289. var onWindowResize = function (evt) {
  24290. var sugarEvent = fromRawEvent$1(evt);
  24291. each([
  24292. mothership,
  24293. uiMothership
  24294. ], function (ship) {
  24295. ship.broadcastOn([repositionPopups()], {});
  24296. ship.broadcastEvent(windowResize(), sugarEvent);
  24297. });
  24298. };
  24299. var onEditorResize = function () {
  24300. each([
  24301. mothership,
  24302. uiMothership
  24303. ], function (ship) {
  24304. ship.broadcastOn([repositionPopups()], {});
  24305. });
  24306. };
  24307. editor.on('PostRender', function () {
  24308. editor.on('mousedown', onContentMousedown);
  24309. editor.on('touchstart', onContentMousedown);
  24310. editor.on('mouseup', onContentMouseup);
  24311. editor.on('ScrollWindow', onWindowScroll);
  24312. editor.on('ResizeWindow', onWindowResize);
  24313. editor.on('ResizeEditor', onEditorResize);
  24314. });
  24315. editor.on('remove', function () {
  24316. editor.off('mousedown', onContentMousedown);
  24317. editor.off('touchstart', onContentMousedown);
  24318. editor.off('mouseup', onContentMouseup);
  24319. editor.off('ScrollWindow', onWindowScroll);
  24320. editor.off('ResizeWindow', onWindowResize);
  24321. editor.off('ResizeEditor', onEditorResize);
  24322. onMousedown.unbind();
  24323. onTouchstart.unbind();
  24324. onTouchmove.unbind();
  24325. onTouchend.unbind();
  24326. onMouseup.unbind();
  24327. });
  24328. editor.on('detach', function () {
  24329. detachSystem(mothership);
  24330. detachSystem(uiMothership);
  24331. mothership.destroy();
  24332. uiMothership.destroy();
  24333. });
  24334. };
  24335. var Events$1 = { setup: setup$3 };
  24336. var schema$q = constant([
  24337. defaulted$1('shell', false),
  24338. strict$1('makeItem'),
  24339. defaulted$1('setupItem', noop),
  24340. SketchBehaviours.field('listBehaviours', [Replacing])
  24341. ]);
  24342. var customListDetail = function (detail) {
  24343. return { behaviours: derive$1([Replacing.config({})]) };
  24344. };
  24345. var itemsPart = optional({
  24346. name: 'items',
  24347. overrides: customListDetail
  24348. });
  24349. var parts$c = constant([itemsPart]);
  24350. var name$2 = constant('CustomList');
  24351. var factory$e = function (detail, components, spec, external) {
  24352. var setItems = function (list, items) {
  24353. getListContainer(list).fold(function () {
  24354. domGlobals.console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  24355. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  24356. }, function (container) {
  24357. var itemComps = Replacing.contents(container);
  24358. var numListsRequired = items.length;
  24359. var numListsToAdd = numListsRequired - itemComps.length;
  24360. var itemsToAdd = numListsToAdd > 0 ? range(numListsToAdd, function () {
  24361. return detail.makeItem();
  24362. }) : [];
  24363. var itemsToRemove = itemComps.slice(numListsRequired);
  24364. each(itemsToRemove, function (item) {
  24365. return Replacing.remove(container, item);
  24366. });
  24367. each(itemsToAdd, function (item) {
  24368. return Replacing.append(container, item);
  24369. });
  24370. var builtLists = Replacing.contents(container);
  24371. each(builtLists, function (item, i) {
  24372. detail.setupItem(list, item, items[i], i);
  24373. });
  24374. });
  24375. };
  24376. var extra = detail.shell ? {
  24377. behaviours: [Replacing.config({})],
  24378. components: []
  24379. } : {
  24380. behaviours: [],
  24381. components: components
  24382. };
  24383. var getListContainer = function (component) {
  24384. return detail.shell ? Option.some(component) : getPart(component, detail, 'items');
  24385. };
  24386. return {
  24387. uid: detail.uid,
  24388. dom: detail.dom,
  24389. components: extra.components,
  24390. behaviours: augment(detail.listBehaviours, extra.behaviours),
  24391. apis: { setItems: setItems }
  24392. };
  24393. };
  24394. var CustomList = composite$1({
  24395. name: name$2(),
  24396. configFields: schema$q(),
  24397. partFields: parts$c(),
  24398. factory: factory$e,
  24399. apis: {
  24400. setItems: function (apis, list, items) {
  24401. apis.setItems(list, items);
  24402. }
  24403. }
  24404. });
  24405. var parts$d = AlloyParts;
  24406. var partType$1 = PartType;
  24407. var getOrigin = function (element) {
  24408. var isFixed = getRaw(element, 'position').is('fixed');
  24409. var offsetParent$1 = isFixed ? Option.none() : offsetParent(element);
  24410. return offsetParent$1.orThunk(function () {
  24411. var marker = Element.fromTag('span');
  24412. before(element, marker);
  24413. var offsetParent$1 = offsetParent(marker);
  24414. remove(marker);
  24415. return offsetParent$1;
  24416. }).map(absolute).getOrThunk(function () {
  24417. return Position(0, 0);
  24418. });
  24419. };
  24420. var adt$c = Adt.generate([
  24421. {
  24422. offset: [
  24423. 'x',
  24424. 'y'
  24425. ]
  24426. },
  24427. {
  24428. absolute: [
  24429. 'x',
  24430. 'y'
  24431. ]
  24432. },
  24433. {
  24434. fixed: [
  24435. 'x',
  24436. 'y'
  24437. ]
  24438. }
  24439. ]);
  24440. var subtract = function (change) {
  24441. return function (point) {
  24442. return point.translate(-change.left(), -change.top());
  24443. };
  24444. };
  24445. var add$4 = function (change) {
  24446. return function (point) {
  24447. return point.translate(change.left(), change.top());
  24448. };
  24449. };
  24450. var transform$1 = function (changes) {
  24451. return function (x, y) {
  24452. return foldl(changes, function (rest, f) {
  24453. return f(rest);
  24454. }, Position(x, y));
  24455. };
  24456. };
  24457. var asFixed = function (coord, scroll, origin) {
  24458. return coord.fold(transform$1([
  24459. add$4(origin),
  24460. subtract(scroll)
  24461. ]), transform$1([subtract(scroll)]), transform$1([]));
  24462. };
  24463. var asAbsolute = function (coord, scroll, origin) {
  24464. return coord.fold(transform$1([add$4(origin)]), transform$1([]), transform$1([add$4(scroll)]));
  24465. };
  24466. var asOffset = function (coord, scroll, origin) {
  24467. return coord.fold(transform$1([]), transform$1([subtract(origin)]), transform$1([
  24468. add$4(scroll),
  24469. subtract(origin)
  24470. ]));
  24471. };
  24472. var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  24473. var a1 = asAbsolute(coord1, scroll, origin);
  24474. var a2 = asAbsolute(coord2, scroll, origin);
  24475. return Math.abs(a1.left() - a2.left()) <= xRange && Math.abs(a1.top() - a2.top()) <= yRange;
  24476. };
  24477. var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  24478. var a1 = asAbsolute(coord1, scroll, origin);
  24479. var a2 = asAbsolute(coord2, scroll, origin);
  24480. var left = Math.abs(a1.left() - a2.left());
  24481. var top = Math.abs(a1.top() - a2.top());
  24482. return Position(left, top);
  24483. };
  24484. var toStyles = function (coord, scroll, origin) {
  24485. return coord.fold(function (x, y) {
  24486. return {
  24487. position: 'absolute',
  24488. left: x + 'px',
  24489. top: y + 'px'
  24490. };
  24491. }, function (x, y) {
  24492. return {
  24493. position: 'absolute',
  24494. left: x - origin.left() + 'px',
  24495. top: y - origin.top() + 'px'
  24496. };
  24497. }, function (x, y) {
  24498. return {
  24499. position: 'fixed',
  24500. left: x + 'px',
  24501. top: y + 'px'
  24502. };
  24503. });
  24504. };
  24505. var translate$2 = function (coord, deltaX, deltaY) {
  24506. return coord.fold(function (x, y) {
  24507. return adt$c.offset(x + deltaX, y + deltaY);
  24508. }, function (x, y) {
  24509. return adt$c.absolute(x + deltaX, y + deltaY);
  24510. }, function (x, y) {
  24511. return adt$c.fixed(x + deltaX, y + deltaY);
  24512. });
  24513. };
  24514. var absorb = function (partialCoord, originalCoord, scroll, origin) {
  24515. var absorbOne = function (stencil, nu) {
  24516. return function (optX, optY) {
  24517. var original = stencil(originalCoord, scroll, origin);
  24518. return nu(optX.getOr(original.left()), optY.getOr(original.top()));
  24519. };
  24520. };
  24521. return partialCoord.fold(absorbOne(asOffset, adt$c.offset), absorbOne(asAbsolute, adt$c.absolute), absorbOne(asFixed, adt$c.fixed));
  24522. };
  24523. var offset = adt$c.offset;
  24524. var absolute$3 = adt$c.absolute;
  24525. var fixed$1 = adt$c.fixed;
  24526. var morphAdt = Adt.generate([
  24527. { static: [] },
  24528. {
  24529. absolute: [
  24530. 'x',
  24531. 'y'
  24532. ]
  24533. },
  24534. {
  24535. fixed: [
  24536. 'x',
  24537. 'y'
  24538. ]
  24539. }
  24540. ]);
  24541. var appear = function (component, contextualInfo) {
  24542. var elem = component.element();
  24543. add$2(elem, contextualInfo.transitionClass);
  24544. remove$4(elem, contextualInfo.fadeOutClass);
  24545. add$2(elem, contextualInfo.fadeInClass);
  24546. contextualInfo.onShow(component);
  24547. };
  24548. var disappear = function (component, contextualInfo) {
  24549. var elem = component.element();
  24550. add$2(elem, contextualInfo.transitionClass);
  24551. remove$4(elem, contextualInfo.fadeInClass);
  24552. add$2(elem, contextualInfo.fadeOutClass);
  24553. contextualInfo.onHide(component);
  24554. };
  24555. var isPartiallyVisible = function (box, viewport) {
  24556. return box.y() < viewport.bottom() && box.bottom() > viewport.y();
  24557. };
  24558. var isTopCompletelyVisible = function (box, viewport) {
  24559. return box.y() >= viewport.y();
  24560. };
  24561. var isBottomCompletelyVisible = function (box, viewport) {
  24562. return box.bottom() <= viewport.bottom();
  24563. };
  24564. var isVisibleForModes = function (modes, box, viewport) {
  24565. return forall(modes, function (mode) {
  24566. switch (mode) {
  24567. case 'bottom':
  24568. return isBottomCompletelyVisible(box, viewport);
  24569. case 'top':
  24570. return isTopCompletelyVisible(box, viewport);
  24571. }
  24572. });
  24573. };
  24574. var getAttr = function (elem, attr) {
  24575. return has$1(elem, attr) ? Option.some(parseInt(get$2(elem, attr), 10)) : Option.none();
  24576. };
  24577. var getPrior = function (elem, dockInfo) {
  24578. return getAttr(elem, dockInfo.leftAttr).bind(function (left) {
  24579. return getAttr(elem, dockInfo.topAttr).map(function (top) {
  24580. var w = get$7(elem);
  24581. var h = get$6(elem);
  24582. return bounds$1(left, top, w, h);
  24583. });
  24584. });
  24585. };
  24586. var setPrior = function (elem, dockInfo, absLeft, absTop, position) {
  24587. set$1(elem, dockInfo.leftAttr, absLeft);
  24588. set$1(elem, dockInfo.topAttr, absTop);
  24589. set$1(elem, dockInfo.positionAttr, position);
  24590. };
  24591. var clearPrior = function (elem, dockInfo) {
  24592. remove$1(elem, dockInfo.leftAttr);
  24593. remove$1(elem, dockInfo.topAttr);
  24594. remove$1(elem, dockInfo.positionAttr);
  24595. };
  24596. var revertToOriginal = function (elem, dockInfo, box) {
  24597. var position = get$2(elem, dockInfo.positionAttr);
  24598. clearPrior(elem, dockInfo);
  24599. switch (position) {
  24600. case 'static':
  24601. return Option.some(morphAdt.static());
  24602. case 'absolute':
  24603. return Option.some(morphAdt.absolute(box.x(), box.y()));
  24604. default:
  24605. return Option.none();
  24606. }
  24607. };
  24608. var morphToOriginal = function (elem, dockInfo, viewport) {
  24609. return getPrior(elem, dockInfo).filter(function (box) {
  24610. return isVisibleForModes(dockInfo.modes, box, viewport);
  24611. }).bind(function (box) {
  24612. return revertToOriginal(elem, dockInfo, box);
  24613. });
  24614. };
  24615. var morphToFixed = function (elem, dockInfo, viewport, scroll, origin) {
  24616. var box$1 = box(elem);
  24617. if (!isVisibleForModes(dockInfo.modes, box$1, viewport)) {
  24618. var position = get$4(elem, 'position');
  24619. setPrior(elem, dockInfo, box$1.x(), box$1.y(), position);
  24620. var coord = absolute$3(box$1.x(), box$1.y());
  24621. var asFixed$1 = asFixed(coord, scroll, origin);
  24622. var viewportPt = absolute$3(viewport.x(), viewport.y());
  24623. var fixedViewport = asFixed(viewportPt, scroll, origin);
  24624. var fixedY = box$1.y() <= viewport.y() ? fixedViewport.top() : fixedViewport.top() + viewport.height() - box$1.height();
  24625. return Option.some(morphAdt.fixed(asFixed$1.left(), fixedY));
  24626. } else {
  24627. return Option.none();
  24628. }
  24629. };
  24630. var getMorph = function (component, dockInfo, viewport, scroll, origin) {
  24631. var elem = component.element();
  24632. var isDocked = getRaw(elem, 'position').is('fixed');
  24633. return isDocked ? morphToOriginal(elem, dockInfo, viewport) : morphToFixed(elem, dockInfo, viewport, scroll, origin);
  24634. };
  24635. var getMorphToOriginal = function (component, dockInfo) {
  24636. var elem = component.element();
  24637. return getPrior(elem, dockInfo).bind(function (box) {
  24638. return revertToOriginal(elem, dockInfo, box);
  24639. });
  24640. };
  24641. var morphToStatic = function (component, config) {
  24642. each([
  24643. 'left',
  24644. 'top',
  24645. 'position'
  24646. ], function (prop) {
  24647. return remove$6(component.element(), prop);
  24648. });
  24649. config.onUndocked(component);
  24650. };
  24651. var morphToCoord = function (component, config, scroll, origin, morph) {
  24652. var styles = toStyles(morph, scroll, origin);
  24653. setAll$1(component.element(), styles);
  24654. var method = styles.position === 'fixed' ? config.onDocked : config.onUndocked;
  24655. method(component);
  24656. };
  24657. var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  24658. if (morphToDocked === void 0) {
  24659. morphToDocked = false;
  24660. }
  24661. config.contextual.each(function (contextInfo) {
  24662. contextInfo.lazyContext(component).each(function (box) {
  24663. var isVisible = isPartiallyVisible(box, viewport);
  24664. if (isVisible !== state.isVisible()) {
  24665. state.setVisible(isVisible);
  24666. if (morphToDocked && !isVisible) {
  24667. add$3(component.element(), [contextInfo.fadeOutClass]);
  24668. contextInfo.onHide(component);
  24669. } else {
  24670. var method = isVisible ? appear : disappear;
  24671. method(component, contextInfo);
  24672. }
  24673. }
  24674. });
  24675. });
  24676. };
  24677. var refreshInternal = function (component, config, state) {
  24678. var viewport = config.lazyViewport(component);
  24679. var elem = component.element();
  24680. var doc = owner(elem);
  24681. var scroll = get$8(doc);
  24682. var origin = getOrigin(elem);
  24683. var isDocked = state.isDocked();
  24684. if (isDocked) {
  24685. updateVisibility(component, config, state, viewport);
  24686. }
  24687. getMorph(component, config, viewport, scroll, origin).each(function (morph) {
  24688. state.setDocked(!isDocked);
  24689. morph.fold(function () {
  24690. return morphToStatic(component, config);
  24691. }, function (x, y) {
  24692. return morphToCoord(component, config, scroll, origin, absolute$3(x, y));
  24693. }, function (x, y) {
  24694. updateVisibility(component, config, state, viewport, true);
  24695. morphToCoord(component, config, scroll, origin, fixed$1(x, y));
  24696. });
  24697. });
  24698. };
  24699. var resetInternal = function (component, config, state) {
  24700. var elem = component.element();
  24701. state.setDocked(false);
  24702. getMorphToOriginal(component, config).each(function (morph) {
  24703. morph.fold(function () {
  24704. return morphToStatic(component, config);
  24705. }, function (x, y) {
  24706. var doc = owner(elem);
  24707. var scroll = get$8(doc);
  24708. var origin = getOrigin(elem);
  24709. morphToCoord(component, config, scroll, origin, absolute$3(x, y));
  24710. }, noop);
  24711. });
  24712. state.setVisible(true);
  24713. config.contextual.each(function (contextInfo) {
  24714. remove$5(elem, [
  24715. contextInfo.fadeInClass,
  24716. contextInfo.fadeOutClass,
  24717. contextInfo.transitionClass
  24718. ]);
  24719. contextInfo.onShow(component);
  24720. });
  24721. refresh$4(component, config, state);
  24722. };
  24723. var refresh$4 = function (component, config, state) {
  24724. if (component.getSystem().isConnected()) {
  24725. refreshInternal(component, config, state);
  24726. }
  24727. };
  24728. var reset = function (component, config, state) {
  24729. if (state.isDocked()) {
  24730. resetInternal(component, config, state);
  24731. }
  24732. };
  24733. var isDocked = function (component, config, state) {
  24734. return state.isDocked();
  24735. };
  24736. var DockingApis = /*#__PURE__*/Object.freeze({
  24737. refresh: refresh$4,
  24738. reset: reset,
  24739. isDocked: isDocked
  24740. });
  24741. var events$f = function (dockInfo, dockState) {
  24742. return derive([
  24743. runOnSource(transitionend(), function (component, simulatedEvent) {
  24744. dockInfo.contextual.each(function (contextInfo) {
  24745. if (has$2(component.element(), contextInfo.transitionClass)) {
  24746. remove$5(component.element(), [
  24747. contextInfo.transitionClass,
  24748. contextInfo.fadeInClass
  24749. ]);
  24750. var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  24751. notify(component);
  24752. }
  24753. simulatedEvent.stop();
  24754. });
  24755. }),
  24756. run(windowScroll(), function (component, _) {
  24757. refresh$4(component, dockInfo, dockState);
  24758. }),
  24759. run(windowResize(), function (component, _) {
  24760. reset(component, dockInfo, dockState);
  24761. })
  24762. ]);
  24763. };
  24764. var ActiveDocking = /*#__PURE__*/Object.freeze({
  24765. events: events$f
  24766. });
  24767. var DockingSchema = [
  24768. optionObjOf('contextual', [
  24769. strictString('fadeInClass'),
  24770. strictString('fadeOutClass'),
  24771. strictString('transitionClass'),
  24772. strictFunction('lazyContext'),
  24773. onHandler('onShow'),
  24774. onHandler('onShown'),
  24775. onHandler('onHide'),
  24776. onHandler('onHidden')
  24777. ]),
  24778. defaultedFunction('lazyViewport', win),
  24779. strictString('leftAttr'),
  24780. strictString('topAttr'),
  24781. strictString('positionAttr'),
  24782. defaultedArrayOf('modes', [
  24783. 'top',
  24784. 'bottom'
  24785. ], string),
  24786. onHandler('onDocked'),
  24787. onHandler('onUndocked')
  24788. ];
  24789. var init$b = function () {
  24790. var docked = Cell(false);
  24791. var visible = Cell(true);
  24792. var readState = function () {
  24793. return 'docked: ' + docked.get() + ', visible: ' + visible.get();
  24794. };
  24795. return nu$5({
  24796. isDocked: function () {
  24797. return docked.get();
  24798. },
  24799. setDocked: function (state) {
  24800. return docked.set(state);
  24801. },
  24802. isVisible: function () {
  24803. return visible.get();
  24804. },
  24805. setVisible: function (state) {
  24806. return visible.set(state);
  24807. },
  24808. readState: readState
  24809. });
  24810. };
  24811. var DockingState = /*#__PURE__*/Object.freeze({
  24812. init: init$b
  24813. });
  24814. var Docking = create$1({
  24815. fields: DockingSchema,
  24816. name: 'docking',
  24817. active: ActiveDocking,
  24818. apis: DockingApis,
  24819. state: DockingState
  24820. });
  24821. var visibility = {
  24822. fadeInClass: 'tox-editor-dock-fadein',
  24823. fadeOutClass: 'tox-editor-dock-fadeout',
  24824. transitionClass: 'tox-editor-dock-transition'
  24825. };
  24826. var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  24827. var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  24828. var updateContentFlow = function (header) {
  24829. var elm = header.element();
  24830. parent(elm).each(function (parentElem) {
  24831. if (Docking.isDocked(header)) {
  24832. var parentWidth = get$7(parentElem);
  24833. set$2(elm, 'width', parentWidth + 'px');
  24834. var headerHeight = getOuter$1(elm);
  24835. set$2(parentElem, 'padding-top', headerHeight + 'px');
  24836. } else {
  24837. remove$6(elm, 'width');
  24838. remove$6(parentElem, 'padding-top');
  24839. }
  24840. });
  24841. };
  24842. var updateSinkVisibility = function (sinkElem, visible) {
  24843. if (visible) {
  24844. remove$4(sinkElem, visibility.fadeOutClass);
  24845. add$3(sinkElem, [
  24846. visibility.transitionClass,
  24847. visibility.fadeInClass
  24848. ]);
  24849. } else {
  24850. remove$4(sinkElem, visibility.fadeInClass);
  24851. add$3(sinkElem, [
  24852. visibility.fadeOutClass,
  24853. visibility.transitionClass
  24854. ]);
  24855. }
  24856. };
  24857. var updateEditorClasses = function (editor, docked) {
  24858. var editorContainer = Element.fromDom(editor.getContainer());
  24859. if (docked) {
  24860. add$2(editorContainer, editorStickyOnClass);
  24861. remove$4(editorContainer, editorStickyOffClass);
  24862. } else {
  24863. add$2(editorContainer, editorStickyOffClass);
  24864. remove$4(editorContainer, editorStickyOnClass);
  24865. }
  24866. };
  24867. var restoreFocus = function (headerElem, focusedElem) {
  24868. var ownerDoc = owner(focusedElem);
  24869. active(ownerDoc).filter(function (activeElm) {
  24870. return !eq(focusedElem, activeElm);
  24871. }).filter(function (activeElm) {
  24872. return eq(activeElm, Element.fromDom(ownerDoc.dom().body)) || contains$2(headerElem, activeElm);
  24873. }).each(function () {
  24874. return focus$1(focusedElem);
  24875. });
  24876. };
  24877. var findFocusedElem = function (rootElm, lazySink) {
  24878. return search(rootElm).orThunk(function () {
  24879. return lazySink().toOption().bind(function (sink) {
  24880. return search(sink.element());
  24881. });
  24882. });
  24883. };
  24884. var setup$4 = function (editor, lazyHeader) {
  24885. if (!editor.inline) {
  24886. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  24887. lazyHeader().each(updateContentFlow);
  24888. });
  24889. editor.on('SkinLoaded', function () {
  24890. lazyHeader().each(Docking.reset);
  24891. });
  24892. }
  24893. editor.on('PostRender', function () {
  24894. updateEditorClasses(editor, false);
  24895. });
  24896. };
  24897. var isDocked$1 = function (lazyHeader) {
  24898. return lazyHeader().map(Docking.isDocked).getOr(false);
  24899. };
  24900. var getBehaviours$2 = function (editor, lazySink) {
  24901. var _a;
  24902. var focusedElm = Cell(Option.none());
  24903. var runOnSinkElement = function (f) {
  24904. lazySink().each(function (sink) {
  24905. return f(sink.element());
  24906. });
  24907. };
  24908. var onDockingSwitch = function (comp) {
  24909. if (!editor.inline) {
  24910. updateContentFlow(comp);
  24911. }
  24912. updateEditorClasses(editor, Docking.isDocked(comp));
  24913. comp.getSystem().broadcastOn([repositionPopups()], {});
  24914. lazySink().each(function (sink) {
  24915. return sink.getSystem().broadcastOn([repositionPopups()], {});
  24916. });
  24917. };
  24918. return [
  24919. Docking.config({
  24920. leftAttr: 'data-dock-left',
  24921. topAttr: 'data-dock-top',
  24922. positionAttr: 'data-dock-pos',
  24923. contextual: __assign({
  24924. lazyContext: function (comp) {
  24925. var headerHeight = getOuter$1(comp.element());
  24926. var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  24927. var box$1 = box(Element.fromDom(container));
  24928. var boxHeight = box$1.height() - headerHeight;
  24929. return Option.some(bounds$1(box$1.x(), box$1.y(), box$1.width(), boxHeight));
  24930. },
  24931. onShow: function () {
  24932. runOnSinkElement(function (elem) {
  24933. return updateSinkVisibility(elem, true);
  24934. });
  24935. },
  24936. onShown: function (comp) {
  24937. runOnSinkElement(function (elem) {
  24938. return remove$5(elem, [
  24939. visibility.transitionClass,
  24940. visibility.fadeInClass
  24941. ]);
  24942. });
  24943. focusedElm.get().each(function (elem) {
  24944. restoreFocus(comp.element(), elem);
  24945. focusedElm.set(Option.none());
  24946. });
  24947. },
  24948. onHide: function (comp) {
  24949. focusedElm.set(findFocusedElem(comp.element(), lazySink));
  24950. runOnSinkElement(function (elem) {
  24951. return updateSinkVisibility(elem, false);
  24952. });
  24953. },
  24954. onHidden: function () {
  24955. runOnSinkElement(function (elem) {
  24956. return remove$5(elem, [visibility.transitionClass]);
  24957. });
  24958. }
  24959. }, visibility),
  24960. modes: ['top'],
  24961. onDocked: onDockingSwitch,
  24962. onUndocked: onDockingSwitch
  24963. }),
  24964. Focusing.config({}),
  24965. Receiving.config({
  24966. channels: (_a = {}, _a[toolbarHeightChange()] = {
  24967. onReceive: function (comp) {
  24968. updateContentFlow(comp);
  24969. }
  24970. }, _a)
  24971. })
  24972. ];
  24973. };
  24974. var StickyHeader = /*#__PURE__*/Object.freeze({
  24975. setup: setup$4,
  24976. isDocked: isDocked$1,
  24977. getBehaviours: getBehaviours$2
  24978. });
  24979. var setup$5 = noop;
  24980. var isDocked$2 = never;
  24981. var getBehaviours$3 = constant([]);
  24982. var StaticHeader = /*#__PURE__*/Object.freeze({
  24983. setup: setup$5,
  24984. isDocked: isDocked$2,
  24985. getBehaviours: getBehaviours$3
  24986. });
  24987. var renderHeader = function (spec) {
  24988. var editor = spec.editor;
  24989. var getBehaviours = spec.sticky ? getBehaviours$2 : getBehaviours$3;
  24990. return {
  24991. uid: spec.uid,
  24992. dom: spec.dom,
  24993. components: spec.components,
  24994. behaviours: derive$1(getBehaviours(editor, spec.getSink))
  24995. };
  24996. };
  24997. var factory$f = function (detail, spec) {
  24998. var setMenus = function (comp, menus) {
  24999. var newMenus = map(menus, function (m) {
  25000. var buttonSpec = {
  25001. type: 'menubutton',
  25002. text: m.text,
  25003. fetch: function (callback) {
  25004. callback(m.getItems());
  25005. }
  25006. };
  25007. var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  25008. return formatError(errInfo);
  25009. }).getOrDie();
  25010. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Option.some('menuitem'));
  25011. });
  25012. Replacing.set(comp, newMenus);
  25013. };
  25014. var apis = {
  25015. focus: Keying.focusIn,
  25016. setMenus: setMenus
  25017. };
  25018. return {
  25019. uid: detail.uid,
  25020. dom: detail.dom,
  25021. components: [],
  25022. behaviours: derive$1([
  25023. Replacing.config({}),
  25024. config('menubar-events', [
  25025. runOnAttached(function (component) {
  25026. detail.onSetup(component);
  25027. }),
  25028. run(mouseover(), function (comp, se) {
  25029. descendant$1(comp.element(), '.' + 'tox-mbtn--active').each(function (activeButton) {
  25030. closest$3(se.event().target(), '.' + 'tox-mbtn').each(function (hoveredButton) {
  25031. if (!eq(activeButton, hoveredButton)) {
  25032. comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  25033. comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  25034. Dropdown.expand(hoveredComp);
  25035. Dropdown.close(activeComp);
  25036. Focusing.focus(hoveredComp);
  25037. });
  25038. });
  25039. }
  25040. });
  25041. });
  25042. }),
  25043. run(focusShifted(), function (comp, se) {
  25044. se.event().prevFocus().bind(function (prev) {
  25045. return comp.getSystem().getByDom(prev).toOption();
  25046. }).each(function (prev) {
  25047. se.event().newFocus().bind(function (nu) {
  25048. return comp.getSystem().getByDom(nu).toOption();
  25049. }).each(function (nu) {
  25050. if (Dropdown.isOpen(prev)) {
  25051. Dropdown.expand(nu);
  25052. Dropdown.close(prev);
  25053. }
  25054. });
  25055. });
  25056. })
  25057. ]),
  25058. Keying.config({
  25059. mode: 'flow',
  25060. selector: '.' + 'tox-mbtn',
  25061. onEscape: function (comp) {
  25062. detail.onEscape(comp);
  25063. return Option.some(true);
  25064. }
  25065. }),
  25066. Tabstopping.config({})
  25067. ]),
  25068. apis: apis,
  25069. domModification: { attributes: { role: 'menubar' } }
  25070. };
  25071. };
  25072. var SilverMenubar = single$2({
  25073. factory: factory$f,
  25074. name: 'silver.Menubar',
  25075. configFields: [
  25076. strict$1('dom'),
  25077. strict$1('uid'),
  25078. strict$1('onEscape'),
  25079. strict$1('backstage'),
  25080. defaulted$1('onSetup', noop)
  25081. ],
  25082. apis: {
  25083. focus: function (apis, comp) {
  25084. apis.focus(comp);
  25085. },
  25086. setMenus: function (apis, comp, menus) {
  25087. apis.setMenus(comp, menus);
  25088. }
  25089. }
  25090. });
  25091. var owner$4 = 'container';
  25092. var schema$r = [field$1('slotBehaviours', [])];
  25093. var getPartName$1 = function (name) {
  25094. return '<alloy.field.' + name + '>';
  25095. };
  25096. var sketch$2 = function (sSpec) {
  25097. var parts = function () {
  25098. var record = [];
  25099. var slot = function (name, config) {
  25100. record.push(name);
  25101. return generateOne(owner$4, getPartName$1(name), config);
  25102. };
  25103. return {
  25104. slot: slot,
  25105. record: function () {
  25106. return record;
  25107. }
  25108. };
  25109. }();
  25110. var spec = sSpec(parts);
  25111. var partNames = parts.record();
  25112. var fieldParts = map(partNames, function (n) {
  25113. return required({
  25114. name: n,
  25115. pname: getPartName$1(n)
  25116. });
  25117. });
  25118. return composite(owner$4, schema$r, fieldParts, make$7, spec);
  25119. };
  25120. var make$7 = function (detail, components, spec) {
  25121. var getSlotNames = function (_) {
  25122. return getAllPartNames(detail);
  25123. };
  25124. var getSlot = function (container, key) {
  25125. return getPart(container, detail, key);
  25126. };
  25127. var onSlot = function (f, def) {
  25128. if (def === void 0) {
  25129. def = undefined;
  25130. }
  25131. return function (container, key) {
  25132. return getPart(container, detail, key).map(function (slot) {
  25133. return f(slot, key);
  25134. }).getOr(def);
  25135. };
  25136. };
  25137. var onSlots = function (f) {
  25138. return function (container, keys) {
  25139. each(keys, function (key) {
  25140. return f(container, key);
  25141. });
  25142. };
  25143. };
  25144. var doShowing = function (comp, key) {
  25145. return get$2(comp.element(), 'aria-hidden') !== 'true';
  25146. };
  25147. var doShow = function (comp, key) {
  25148. if (!doShowing(comp)) {
  25149. var element = comp.element();
  25150. remove$6(element, 'display');
  25151. remove$1(element, 'aria-hidden');
  25152. emitWith(comp, slotVisibility(), {
  25153. name: key,
  25154. visible: true
  25155. });
  25156. }
  25157. };
  25158. var doHide = function (comp, key) {
  25159. if (doShowing(comp)) {
  25160. var element = comp.element();
  25161. set$2(element, 'display', 'none');
  25162. set$1(element, 'aria-hidden', 'true');
  25163. emitWith(comp, slotVisibility(), {
  25164. name: key,
  25165. visible: false
  25166. });
  25167. }
  25168. };
  25169. var isShowing = onSlot(doShowing, false);
  25170. var hideSlot = onSlot(doHide);
  25171. var hideSlots = onSlots(hideSlot);
  25172. var hideAllSlots = function (container) {
  25173. return hideSlots(container, getSlotNames());
  25174. };
  25175. var showSlot = onSlot(doShow);
  25176. var apis = {
  25177. getSlotNames: getSlotNames,
  25178. getSlot: getSlot,
  25179. isShowing: isShowing,
  25180. hideSlot: hideSlot,
  25181. hideAllSlots: hideAllSlots,
  25182. showSlot: showSlot
  25183. };
  25184. return {
  25185. uid: detail.uid,
  25186. dom: detail.dom,
  25187. components: components,
  25188. behaviours: get$b(detail.slotBehaviours),
  25189. apis: apis
  25190. };
  25191. };
  25192. var slotApis = map$1({
  25193. getSlotNames: function (apis, c) {
  25194. return apis.getSlotNames(c);
  25195. },
  25196. getSlot: function (apis, c, key) {
  25197. return apis.getSlot(c, key);
  25198. },
  25199. isShowing: function (apis, c, key) {
  25200. return apis.isShowing(c, key);
  25201. },
  25202. hideSlot: function (apis, c, key) {
  25203. return apis.hideSlot(c, key);
  25204. },
  25205. hideAllSlots: function (apis, c) {
  25206. return apis.hideAllSlots(c);
  25207. },
  25208. showSlot: function (apis, c, key) {
  25209. return apis.showSlot(c, key);
  25210. }
  25211. }, makeApi);
  25212. var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch$2 });
  25213. var sidebarSchema = objOf([
  25214. optionString('icon'),
  25215. optionString('tooltip'),
  25216. defaultedFunction('onShow', noop),
  25217. defaultedFunction('onHide', noop),
  25218. defaultedFunction('onSetup', function () {
  25219. return noop;
  25220. })
  25221. ]);
  25222. var createSidebar = function (spec) {
  25223. return asRaw('sidebar', sidebarSchema, spec);
  25224. };
  25225. var setup$6 = function (editor) {
  25226. var sidebars = editor.ui.registry.getAll().sidebars;
  25227. each(keys(sidebars), function (name) {
  25228. var spec = sidebars[name];
  25229. var isActive = function () {
  25230. return Option.from(editor.queryCommandValue('ToggleSidebar')).is(name);
  25231. };
  25232. editor.ui.registry.addToggleButton(name, {
  25233. icon: spec.icon,
  25234. tooltip: spec.tooltip,
  25235. onAction: function (buttonApi) {
  25236. editor.execCommand('ToggleSidebar', false, name);
  25237. buttonApi.setActive(isActive());
  25238. },
  25239. onSetup: function (buttonApi) {
  25240. var handleToggle = function () {
  25241. return buttonApi.setActive(isActive());
  25242. };
  25243. editor.on('ToggleSidebar', handleToggle);
  25244. return function () {
  25245. editor.off('ToggleSidebar', handleToggle);
  25246. };
  25247. }
  25248. });
  25249. });
  25250. };
  25251. var getApi = function (comp) {
  25252. return {
  25253. element: function () {
  25254. return comp.element().dom();
  25255. }
  25256. };
  25257. };
  25258. var makePanels = function (parts, panelConfigs) {
  25259. var specs = map(keys(panelConfigs), function (name) {
  25260. var spec = panelConfigs[name];
  25261. var bridged = getOrDie(createSidebar(spec));
  25262. return {
  25263. name: name,
  25264. getApi: getApi,
  25265. onSetup: bridged.onSetup,
  25266. onShow: bridged.onShow,
  25267. onHide: bridged.onHide
  25268. };
  25269. });
  25270. return map(specs, function (spec) {
  25271. var editorOffCell = Cell(noop);
  25272. return parts.slot(spec.name, {
  25273. dom: {
  25274. tag: 'div',
  25275. classes: ['tox-sidebar__pane']
  25276. },
  25277. behaviours: SimpleBehaviours.unnamedEvents([
  25278. onControlAttached(spec, editorOffCell),
  25279. onControlDetached(spec, editorOffCell),
  25280. run(slotVisibility(), function (sidepanel, se) {
  25281. var data = se.event();
  25282. var optSidePanelSpec = find(specs, function (config) {
  25283. return config.name === data.name();
  25284. });
  25285. optSidePanelSpec.each(function (sidePanelSpec) {
  25286. var handler = data.visible() ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  25287. handler(sidePanelSpec.getApi(sidepanel));
  25288. });
  25289. })
  25290. ])
  25291. });
  25292. });
  25293. };
  25294. var makeSidebar = function (panelConfigs) {
  25295. return SlotContainer.sketch(function (parts) {
  25296. return {
  25297. dom: {
  25298. tag: 'div',
  25299. classes: ['tox-sidebar__pane-container']
  25300. },
  25301. components: makePanels(parts, panelConfigs),
  25302. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  25303. return SlotContainer.hideAllSlots(slotContainer);
  25304. })])
  25305. };
  25306. });
  25307. };
  25308. var setSidebar = function (sidebar, panelConfigs) {
  25309. var optSlider = Composing.getCurrent(sidebar);
  25310. optSlider.each(function (slider) {
  25311. return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  25312. });
  25313. };
  25314. var toggleSidebar = function (sidebar, name) {
  25315. var optSlider = Composing.getCurrent(sidebar);
  25316. optSlider.each(function (slider) {
  25317. var optSlotContainer = Composing.getCurrent(slider);
  25318. optSlotContainer.each(function (slotContainer) {
  25319. if (Sliding.hasGrown(slider)) {
  25320. if (SlotContainer.isShowing(slotContainer, name)) {
  25321. Sliding.shrink(slider);
  25322. } else {
  25323. SlotContainer.hideAllSlots(slotContainer);
  25324. SlotContainer.showSlot(slotContainer, name);
  25325. }
  25326. } else {
  25327. SlotContainer.hideAllSlots(slotContainer);
  25328. SlotContainer.showSlot(slotContainer, name);
  25329. Sliding.grow(slider);
  25330. }
  25331. });
  25332. });
  25333. };
  25334. var whichSidebar = function (sidebar) {
  25335. var optSlider = Composing.getCurrent(sidebar);
  25336. return optSlider.bind(function (slider) {
  25337. var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  25338. if (sidebarOpen) {
  25339. var optSlotContainer = Composing.getCurrent(slider);
  25340. return optSlotContainer.bind(function (slotContainer) {
  25341. return find(SlotContainer.getSlotNames(slotContainer), function (name) {
  25342. return SlotContainer.isShowing(slotContainer, name);
  25343. });
  25344. });
  25345. } else {
  25346. return Option.none();
  25347. }
  25348. });
  25349. };
  25350. var fixSize = generate$1('FixSizeEvent');
  25351. var autoSize = generate$1('AutoSizeEvent');
  25352. var renderSidebar = function (spec) {
  25353. return {
  25354. uid: spec.uid,
  25355. dom: {
  25356. tag: 'div',
  25357. classes: ['tox-sidebar'],
  25358. attributes: { role: 'complementary' }
  25359. },
  25360. components: [{
  25361. dom: {
  25362. tag: 'div',
  25363. classes: ['tox-sidebar__slider']
  25364. },
  25365. components: [],
  25366. behaviours: derive$1([
  25367. Tabstopping.config({}),
  25368. Focusing.config({}),
  25369. Sliding.config({
  25370. dimension: { property: 'width' },
  25371. closedClass: 'tox-sidebar--sliding-closed',
  25372. openClass: 'tox-sidebar--sliding-open',
  25373. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  25374. growingClass: 'tox-sidebar--sliding-growing',
  25375. onShrunk: function (slider) {
  25376. var optSlotContainer = Composing.getCurrent(slider);
  25377. optSlotContainer.each(SlotContainer.hideAllSlots);
  25378. emit(slider, autoSize);
  25379. },
  25380. onGrown: function (slider) {
  25381. emit(slider, autoSize);
  25382. },
  25383. onStartGrow: function (slider) {
  25384. emitWith(slider, fixSize, { width: getRaw(slider.element(), 'width').getOr('') });
  25385. },
  25386. onStartShrink: function (slider) {
  25387. emitWith(slider, fixSize, { width: get$7(slider.element()) + 'px' });
  25388. }
  25389. }),
  25390. Replacing.config({}),
  25391. Composing.config({
  25392. find: function (comp) {
  25393. var children = Replacing.contents(comp);
  25394. return head(children);
  25395. }
  25396. })
  25397. ])
  25398. }],
  25399. behaviours: derive$1([
  25400. ComposingConfigs.childAt(0),
  25401. config('sidebar-sliding-events', [
  25402. run(fixSize, function (comp, se) {
  25403. set$2(comp.element(), 'width', se.event().width());
  25404. }),
  25405. run(autoSize, function (comp, se) {
  25406. remove$6(comp.element(), 'width');
  25407. })
  25408. ])
  25409. ])
  25410. };
  25411. };
  25412. var renderSpinner = function (providerBackstage) {
  25413. return {
  25414. dom: {
  25415. tag: 'div',
  25416. attributes: { 'aria-label': providerBackstage.translate('Loading...') },
  25417. classes: ['tox-throbber__busy-spinner']
  25418. },
  25419. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }],
  25420. behaviours: derive$1([
  25421. Keying.config({
  25422. mode: 'special',
  25423. onTab: function () {
  25424. return Option.some(true);
  25425. },
  25426. onShiftTab: function () {
  25427. return Option.some(true);
  25428. }
  25429. }),
  25430. Focusing.config({})
  25431. ])
  25432. };
  25433. };
  25434. var toggleThrobber = function (comp, state, providerBackstage) {
  25435. var element = comp.element();
  25436. if (state === true) {
  25437. Replacing.set(comp, [renderSpinner(providerBackstage)]);
  25438. remove$6(element, 'display');
  25439. remove$1(element, 'aria-hidden');
  25440. } else {
  25441. Replacing.set(comp, []);
  25442. set$2(element, 'display', 'none');
  25443. set$1(element, 'aria-hidden', 'true');
  25444. }
  25445. };
  25446. var renderThrobber = function (spec) {
  25447. return {
  25448. uid: spec.uid,
  25449. dom: {
  25450. tag: 'div',
  25451. attributes: { 'aria-hidden': 'true' },
  25452. classes: ['tox-throbber'],
  25453. styles: { display: 'none' }
  25454. },
  25455. behaviours: derive$1([Replacing.config({})]),
  25456. components: []
  25457. };
  25458. };
  25459. var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  25460. var throbberState = Cell(false);
  25461. var timer = Cell(Option.none());
  25462. var toggle = function (state) {
  25463. if (state !== throbberState.get()) {
  25464. toggleThrobber(lazyThrobber(), state, sharedBackstage.providers);
  25465. throbberState.set(state);
  25466. }
  25467. };
  25468. editor.on('ProgressState', function (e) {
  25469. timer.get().each(global$2.clearTimeout);
  25470. if (isNumber(e.time)) {
  25471. var timerId = global$2.setEditorTimeout(editor, function () {
  25472. return toggle(e.state);
  25473. }, e.time);
  25474. timer.set(Option.some(timerId));
  25475. } else {
  25476. toggle(e.state);
  25477. timer.set(Option.none());
  25478. }
  25479. });
  25480. };
  25481. var factory$g = function (detail, components, spec) {
  25482. var apis = {
  25483. getSocket: function (comp) {
  25484. return parts$d.getPart(comp, detail, 'socket');
  25485. },
  25486. setSidebar: function (comp, panelConfigs) {
  25487. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25488. return setSidebar(sidebar, panelConfigs);
  25489. });
  25490. },
  25491. toggleSidebar: function (comp, name) {
  25492. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25493. return toggleSidebar(sidebar, name);
  25494. });
  25495. },
  25496. whichSidebar: function (comp) {
  25497. return parts$d.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  25498. },
  25499. getHeader: function (comp) {
  25500. return parts$d.getPart(comp, detail, 'header');
  25501. },
  25502. getToolbar: function (comp) {
  25503. return parts$d.getPart(comp, detail, 'toolbar');
  25504. },
  25505. setToolbar: function (comp, groups) {
  25506. parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  25507. toolbar.getApis().setGroups(toolbar, groups);
  25508. });
  25509. },
  25510. setToolbars: function (comp, toolbars) {
  25511. parts$d.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  25512. CustomList.setItems(mToolbar, toolbars);
  25513. });
  25514. },
  25515. refreshToolbar: function (comp) {
  25516. var toolbar = parts$d.getPart(comp, detail, 'toolbar');
  25517. toolbar.each(function (toolbar) {
  25518. return toolbar.getApis().refresh(toolbar);
  25519. });
  25520. },
  25521. getMoreButton: function (comp) {
  25522. var toolbar = parts$d.getPart(comp, detail, 'toolbar');
  25523. return toolbar.bind(function (toolbar) {
  25524. return toolbar.getApis().getMoreButton(toolbar);
  25525. });
  25526. },
  25527. getThrobber: function (comp) {
  25528. return parts$d.getPart(comp, detail, 'throbber');
  25529. },
  25530. focusToolbar: function (comp) {
  25531. var optToolbar = parts$d.getPart(comp, detail, 'toolbar').orThunk(function () {
  25532. return parts$d.getPart(comp, detail, 'multiple-toolbar');
  25533. });
  25534. optToolbar.each(function (toolbar) {
  25535. Keying.focusIn(toolbar);
  25536. });
  25537. },
  25538. setMenubar: function (comp, menus) {
  25539. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  25540. SilverMenubar.setMenus(menubar, menus);
  25541. });
  25542. },
  25543. focusMenubar: function (comp) {
  25544. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  25545. SilverMenubar.focus(menubar);
  25546. });
  25547. }
  25548. };
  25549. return {
  25550. uid: detail.uid,
  25551. dom: detail.dom,
  25552. components: components,
  25553. apis: apis,
  25554. behaviours: detail.behaviours
  25555. };
  25556. };
  25557. var partMenubar = partType$1.optional({
  25558. factory: SilverMenubar,
  25559. name: 'menubar',
  25560. schema: [strict$1('backstage')]
  25561. });
  25562. var toolbarFactory = function (spec) {
  25563. if (spec.split === ToolbarDrawer.sliding) {
  25564. return renderSlidingMoreToolbar;
  25565. } else if (spec.split === ToolbarDrawer.floating) {
  25566. return renderFloatingMoreToolbar;
  25567. } else {
  25568. return renderToolbar;
  25569. }
  25570. };
  25571. var partMultipleToolbar = partType$1.optional({
  25572. factory: {
  25573. sketch: function (spec) {
  25574. return CustomList.sketch({
  25575. uid: spec.uid,
  25576. dom: spec.dom,
  25577. listBehaviours: derive$1([Keying.config({
  25578. mode: 'acyclic',
  25579. selector: '.tox-toolbar'
  25580. })]),
  25581. makeItem: function () {
  25582. return renderToolbar({
  25583. uid: generate$1('multiple-toolbar-item'),
  25584. backstage: spec.backstage,
  25585. cyclicKeying: false,
  25586. getSink: spec.getSink,
  25587. initGroups: [],
  25588. onEscape: function () {
  25589. return Option.none();
  25590. }
  25591. });
  25592. },
  25593. setupItem: function (mToolbar, tc, data, index) {
  25594. Toolbar.setGroups(tc, data);
  25595. },
  25596. shell: true
  25597. });
  25598. }
  25599. },
  25600. name: 'multiple-toolbar',
  25601. schema: [
  25602. strict$1('dom'),
  25603. strict$1('onEscape')
  25604. ]
  25605. });
  25606. var partToolbar = partType$1.optional({
  25607. factory: {
  25608. sketch: function (spec) {
  25609. var renderer = toolbarFactory(spec);
  25610. var toolbarSpec = {
  25611. uid: spec.uid,
  25612. onEscape: function () {
  25613. spec.onEscape();
  25614. return Option.some(true);
  25615. },
  25616. cyclicKeying: false,
  25617. initGroups: [],
  25618. getSink: spec.getSink,
  25619. backstage: spec.backstage,
  25620. moreDrawerData: {
  25621. lazyToolbar: spec.lazyToolbar,
  25622. lazyMoreButton: spec.lazyMoreButton,
  25623. lazyHeader: spec.lazyHeader
  25624. }
  25625. };
  25626. return renderer(toolbarSpec);
  25627. }
  25628. },
  25629. name: 'toolbar',
  25630. schema: [
  25631. strict$1('dom'),
  25632. strict$1('onEscape'),
  25633. strict$1('getSink')
  25634. ]
  25635. });
  25636. var partHeader = partType$1.optional({
  25637. factory: { sketch: renderHeader },
  25638. name: 'header',
  25639. schema: [strict$1('dom')]
  25640. });
  25641. var partSocket = partType$1.optional({
  25642. name: 'socket',
  25643. schema: [strict$1('dom')]
  25644. });
  25645. var partSidebar = partType$1.optional({
  25646. factory: { sketch: renderSidebar },
  25647. name: 'sidebar',
  25648. schema: [strict$1('dom')]
  25649. });
  25650. var partThrobber = partType$1.optional({
  25651. factory: { sketch: renderThrobber },
  25652. name: 'throbber',
  25653. schema: [strict$1('dom')]
  25654. });
  25655. var OuterContainer = composite$1({
  25656. name: 'OuterContainer',
  25657. factory: factory$g,
  25658. configFields: [
  25659. strict$1('dom'),
  25660. strict$1('behaviours')
  25661. ],
  25662. partFields: [
  25663. partHeader,
  25664. partMenubar,
  25665. partToolbar,
  25666. partMultipleToolbar,
  25667. partSocket,
  25668. partSidebar,
  25669. partThrobber
  25670. ],
  25671. apis: {
  25672. getSocket: function (apis, comp) {
  25673. return apis.getSocket(comp);
  25674. },
  25675. setSidebar: function (apis, comp, panelConfigs) {
  25676. apis.setSidebar(comp, panelConfigs);
  25677. },
  25678. toggleSidebar: function (apis, comp, name) {
  25679. apis.toggleSidebar(comp, name);
  25680. },
  25681. whichSidebar: function (apis, comp) {
  25682. return apis.whichSidebar(comp);
  25683. },
  25684. getHeader: function (apis, comp) {
  25685. return apis.getHeader(comp);
  25686. },
  25687. getToolbar: function (apis, comp) {
  25688. return apis.getToolbar(comp);
  25689. },
  25690. setToolbar: function (apis, comp, grps) {
  25691. var groups = map(grps, function (grp) {
  25692. return renderToolbarGroup(grp);
  25693. });
  25694. apis.setToolbar(comp, groups);
  25695. },
  25696. setToolbars: function (apis, comp, ts) {
  25697. var renderedToolbars = map(ts, function (g) {
  25698. return map(g, renderToolbarGroup);
  25699. });
  25700. apis.setToolbars(comp, renderedToolbars);
  25701. },
  25702. getMoreButton: function (apis, comp) {
  25703. return apis.getMoreButton(comp);
  25704. },
  25705. refreshToolbar: function (apis, comp) {
  25706. return apis.refreshToolbar(comp);
  25707. },
  25708. getThrobber: function (apis, comp) {
  25709. return apis.getThrobber(comp);
  25710. },
  25711. setMenubar: function (apis, comp, menus) {
  25712. apis.setMenubar(comp, menus);
  25713. },
  25714. focusMenubar: function (apis, comp) {
  25715. apis.focusMenubar(comp);
  25716. },
  25717. focusToolbar: function (apis, comp) {
  25718. apis.focusToolbar(comp);
  25719. }
  25720. }
  25721. });
  25722. var defaultMenubar = 'file edit view insert format tools table help';
  25723. var defaultMenus = {
  25724. file: {
  25725. title: 'File',
  25726. items: 'newdocument restoredraft | preview | print | deleteallconversations'
  25727. },
  25728. edit: {
  25729. title: 'Edit',
  25730. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  25731. },
  25732. view: {
  25733. title: 'View',
  25734. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  25735. },
  25736. insert: {
  25737. title: 'Insert',
  25738. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  25739. },
  25740. format: {
  25741. title: 'Format',
  25742. items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align | forecolor backcolor | removeformat'
  25743. },
  25744. tools: {
  25745. title: 'Tools',
  25746. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  25747. },
  25748. table: {
  25749. title: 'Table',
  25750. items: 'inserttable tableprops deletetable row column cell'
  25751. },
  25752. help: {
  25753. title: 'Help',
  25754. items: 'help'
  25755. }
  25756. };
  25757. var make$8 = function (menu, registry, editor) {
  25758. var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  25759. return {
  25760. text: menu.title,
  25761. getItems: function () {
  25762. return bind(menu.items, function (i) {
  25763. var itemName = i.toLowerCase();
  25764. if (itemName.trim().length === 0) {
  25765. return [];
  25766. } else if (exists(removedMenuItems, function (removedMenuItem) {
  25767. return removedMenuItem === itemName;
  25768. })) {
  25769. return [];
  25770. } else if (itemName === 'separator' || itemName === '|') {
  25771. return [{ type: 'separator' }];
  25772. } else if (registry.menuItems[itemName]) {
  25773. return [registry.menuItems[itemName]];
  25774. } else {
  25775. return [];
  25776. }
  25777. });
  25778. }
  25779. };
  25780. };
  25781. var parseItemsString = function (items) {
  25782. if (typeof items === 'string') {
  25783. return items.split(' ');
  25784. }
  25785. return items;
  25786. };
  25787. var identifyMenus = function (editor, registry) {
  25788. var rawMenuData = merge(defaultMenus, registry.menus);
  25789. var userDefinedMenus = keys(registry.menus).length > 0;
  25790. var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  25791. var validMenus = filter(menubar, function (menuName) {
  25792. return userDefinedMenus ? registry.menus.hasOwnProperty(menuName) && registry.menus[menuName].hasOwnProperty('items') || defaultMenus.hasOwnProperty(menuName) : defaultMenus.hasOwnProperty(menuName);
  25793. });
  25794. var menus = map(validMenus, function (menuName) {
  25795. var menuData = rawMenuData[menuName];
  25796. return make$8({
  25797. title: menuData.title,
  25798. items: parseItemsString(menuData.items)
  25799. }, registry, editor);
  25800. });
  25801. return filter(menus, function (menu) {
  25802. var isNotSeparator = function (item) {
  25803. return item.type !== 'separator';
  25804. };
  25805. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  25806. });
  25807. };
  25808. var fireSkinLoaded$1 = function (editor) {
  25809. var done = function () {
  25810. editor._skinLoaded = true;
  25811. Events.fireSkinLoaded(editor);
  25812. };
  25813. return function () {
  25814. if (editor.initialized) {
  25815. done();
  25816. } else {
  25817. editor.on('init', done);
  25818. }
  25819. };
  25820. };
  25821. var SkinLoaded = { fireSkinLoaded: fireSkinLoaded$1 };
  25822. var loadSkin = function (isInline, editor) {
  25823. var skinUrl = getSkinUrl(editor);
  25824. var skinUiCss;
  25825. if (skinUrl) {
  25826. skinUiCss = skinUrl + '/skin.min.css';
  25827. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  25828. }
  25829. if (isSkinDisabled(editor) === false && skinUiCss) {
  25830. global$7.DOM.styleSheetLoader.load(skinUiCss, SkinLoaded.fireSkinLoaded(editor));
  25831. } else {
  25832. SkinLoaded.fireSkinLoaded(editor)();
  25833. }
  25834. };
  25835. var iframe = curry(loadSkin, false);
  25836. var inline = curry(loadSkin, true);
  25837. var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  25838. var comp = uiComponents.outerContainer;
  25839. var toolbarConfig = rawUiConfig.toolbar;
  25840. var toolbarButtonsConfig = rawUiConfig.buttons;
  25841. if (isArrayOf(toolbarConfig, isString)) {
  25842. var toolbars = toolbarConfig.map(function (t) {
  25843. var config = {
  25844. toolbar: t,
  25845. buttons: toolbarButtonsConfig
  25846. };
  25847. return identifyButtons(editor, config, { backstage: backstage }, Option.none());
  25848. });
  25849. OuterContainer.setToolbars(comp, toolbars);
  25850. } else {
  25851. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Option.none()));
  25852. }
  25853. };
  25854. var DOM = global$7.DOM;
  25855. var detection = detect$3();
  25856. var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  25857. var setupEvents = function (editor) {
  25858. var contentWindow = editor.getWin();
  25859. var initialDocEle = editor.getDoc().documentElement;
  25860. var lastWindowDimensions = Cell(Position(contentWindow.innerWidth, contentWindow.innerHeight));
  25861. var lastDocumentDimensions = Cell(Position(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  25862. var resize = function (e) {
  25863. var docEle = editor.getDoc().documentElement;
  25864. var outer = lastWindowDimensions.get();
  25865. var inner = lastDocumentDimensions.get();
  25866. if (outer.left() !== contentWindow.innerWidth || outer.top() !== contentWindow.innerHeight) {
  25867. lastWindowDimensions.set(Position(contentWindow.innerWidth, contentWindow.innerHeight));
  25868. Events.fireResizeContent(editor, e);
  25869. } else if (inner.left() !== docEle.offsetWidth || inner.top() !== docEle.offsetHeight) {
  25870. lastDocumentDimensions.set(Position(docEle.offsetWidth, docEle.offsetHeight));
  25871. Events.fireResizeContent(editor, e);
  25872. }
  25873. };
  25874. var scroll = function (e) {
  25875. return Events.fireScrollContent(editor, e);
  25876. };
  25877. DOM.bind(contentWindow, 'resize', resize);
  25878. DOM.bind(contentWindow, 'scroll', scroll);
  25879. var elementLoad = capture$1(Element.fromDom(editor.getBody()), 'load', resize);
  25880. editor.on('remove', function () {
  25881. elementLoad.unbind();
  25882. DOM.unbind(contentWindow, 'resize', resize);
  25883. DOM.unbind(contentWindow, 'scroll', scroll);
  25884. });
  25885. };
  25886. var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  25887. var lastToolbarWidth = Cell(0);
  25888. iframe(editor);
  25889. attachSystemAfter(Element.fromDom(args.targetNode), uiComponents.mothership);
  25890. attachSystem(body(), uiComponents.uiMothership);
  25891. editor.on('PostRender', function () {
  25892. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  25893. lastToolbarWidth.set(editor.getWin().innerWidth);
  25894. OuterContainer.setMenubar(uiComponents.outerContainer, identifyMenus(editor, rawUiConfig));
  25895. OuterContainer.setSidebar(uiComponents.outerContainer, rawUiConfig.sidebar);
  25896. setupEvents(editor);
  25897. });
  25898. var socket = OuterContainer.getSocket(uiComponents.outerContainer).getOrDie('Could not find expected socket element');
  25899. if (isiOS12 === true) {
  25900. setAll$1(socket.element(), {
  25901. 'overflow': 'scroll',
  25902. '-webkit-overflow-scrolling': 'touch'
  25903. });
  25904. var limit = first$1(function () {
  25905. editor.fire('ScrollContent');
  25906. }, 20);
  25907. bind$3(socket.element(), 'scroll', limit.throttle);
  25908. }
  25909. setupReadonlyModeSwitch(editor, uiComponents);
  25910. editor.addCommand('ToggleSidebar', function (ui, value) {
  25911. OuterContainer.toggleSidebar(uiComponents.outerContainer, value);
  25912. editor.fire('ToggleSidebar');
  25913. });
  25914. editor.addQueryValueHandler('ToggleSidebar', function () {
  25915. return OuterContainer.whichSidebar(uiComponents.outerContainer);
  25916. });
  25917. var drawer = getToolbarDrawer(editor);
  25918. var refreshDrawer = function () {
  25919. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  25920. };
  25921. if (drawer === ToolbarDrawer.sliding || drawer === ToolbarDrawer.floating) {
  25922. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  25923. var width = editor.getWin().innerWidth;
  25924. if (width !== lastToolbarWidth.get()) {
  25925. refreshDrawer();
  25926. lastToolbarWidth.set(width);
  25927. }
  25928. });
  25929. }
  25930. return {
  25931. iframeContainer: socket.element().dom(),
  25932. editorContainer: uiComponents.outerContainer.element().dom()
  25933. };
  25934. };
  25935. var Iframe = { render: render };
  25936. var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  25937. var floatContainer;
  25938. var DOM = global$7.DOM;
  25939. var useFixedToolbarContainer = useFixedContainer(editor);
  25940. var isSticky = isStickyToolbar(editor);
  25941. var targetElm = Element.fromDom(args.targetNode);
  25942. var splitSetting = getToolbarDrawer(editor);
  25943. var split = splitSetting === ToolbarDrawer.sliding || splitSetting === ToolbarDrawer.floating;
  25944. inline(editor);
  25945. var updateChromePosition = function (toolbar) {
  25946. var offset = split ? toolbar.fold(function () {
  25947. return 0;
  25948. }, function (tbar) {
  25949. return tbar.components().length > 1 ? get$6(tbar.components()[1].element()) : 0;
  25950. }) : 0;
  25951. var location = absolute(targetElm);
  25952. var top = location.top() - get$6(floatContainer.element()) + offset;
  25953. setAll$1(uiComponents.outerContainer.element(), {
  25954. position: 'absolute',
  25955. top: Math.round(top) + 'px',
  25956. left: Math.round(location.left()) + 'px'
  25957. });
  25958. };
  25959. var updateChromeUi = function (resetDocking) {
  25960. if (resetDocking === void 0) {
  25961. resetDocking = false;
  25962. }
  25963. if (split) {
  25964. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  25965. }
  25966. if (!useFixedToolbarContainer) {
  25967. var toolbar = OuterContainer.getToolbar(uiComponents.outerContainer);
  25968. updateChromePosition(toolbar);
  25969. }
  25970. if (isSticky) {
  25971. resetDocking ? Docking.reset(floatContainer) : Docking.refresh(floatContainer);
  25972. }
  25973. };
  25974. var show = function () {
  25975. set$2(uiComponents.outerContainer.element(), 'display', 'flex');
  25976. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  25977. remove$6(uiComponents.uiMothership.element(), 'display');
  25978. updateChromeUi();
  25979. };
  25980. var hide = function () {
  25981. if (uiComponents.outerContainer) {
  25982. set$2(uiComponents.outerContainer.element(), 'display', 'none');
  25983. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  25984. }
  25985. set$2(uiComponents.uiMothership.element(), 'display', 'none');
  25986. };
  25987. var render = function () {
  25988. if (floatContainer) {
  25989. show();
  25990. return;
  25991. }
  25992. floatContainer = OuterContainer.getHeader(uiComponents.outerContainer).getOrDie();
  25993. var uiContainer = getUiContainer(editor);
  25994. attachSystem(uiContainer, uiComponents.mothership);
  25995. attachSystem(uiContainer, uiComponents.uiMothership);
  25996. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  25997. OuterContainer.setMenubar(uiComponents.outerContainer, identifyMenus(editor, rawUiConfig));
  25998. show();
  25999. editor.on('activate', show);
  26000. editor.on('deactivate', hide);
  26001. editor.on('NodeChange SkinLoaded ResizeWindow', function () {
  26002. if (!editor.hidden) {
  26003. updateChromeUi(true);
  26004. }
  26005. });
  26006. editor.nodeChanged();
  26007. };
  26008. editor.on('focus', render);
  26009. editor.on('blur hide', hide);
  26010. editor.on('init', function () {
  26011. if (editor.hasFocus()) {
  26012. render();
  26013. }
  26014. });
  26015. setupReadonlyModeSwitch(editor, uiComponents);
  26016. return { editorContainer: uiComponents.outerContainer.element().dom() };
  26017. };
  26018. var Inline = { render: render$1 };
  26019. var register$5 = function (editor) {
  26020. var alignToolbarButtons = [
  26021. {
  26022. name: 'alignleft',
  26023. text: 'Align left',
  26024. cmd: 'JustifyLeft',
  26025. icon: 'align-left'
  26026. },
  26027. {
  26028. name: 'aligncenter',
  26029. text: 'Align center',
  26030. cmd: 'JustifyCenter',
  26031. icon: 'align-center'
  26032. },
  26033. {
  26034. name: 'alignright',
  26035. text: 'Align right',
  26036. cmd: 'JustifyRight',
  26037. icon: 'align-right'
  26038. },
  26039. {
  26040. name: 'alignjustify',
  26041. text: 'Justify',
  26042. cmd: 'JustifyFull',
  26043. icon: 'align-justify'
  26044. }
  26045. ];
  26046. global$e.each(alignToolbarButtons, function (item) {
  26047. editor.ui.registry.addToggleButton(item.name, {
  26048. tooltip: item.text,
  26049. onAction: function () {
  26050. return editor.execCommand(item.cmd);
  26051. },
  26052. icon: item.icon,
  26053. onSetup: onSetupFormatToggle(editor, item.name)
  26054. });
  26055. });
  26056. var alignNoneToolbarButton = {
  26057. name: 'alignnone',
  26058. text: 'No alignment',
  26059. cmd: 'JustifyNone',
  26060. icon: 'align-none'
  26061. };
  26062. editor.ui.registry.addButton(alignNoneToolbarButton.name, {
  26063. tooltip: alignNoneToolbarButton.text,
  26064. onAction: function () {
  26065. return editor.execCommand(alignNoneToolbarButton.cmd);
  26066. },
  26067. icon: alignNoneToolbarButton.icon
  26068. });
  26069. };
  26070. var AlignmentButtons = { register: register$5 };
  26071. var toggleFormat = function (editor, fmt) {
  26072. return function () {
  26073. editor.execCommand('mceToggleFormat', false, fmt);
  26074. };
  26075. };
  26076. var registerFormatButtons = function (editor) {
  26077. global$e.each([
  26078. {
  26079. name: 'bold',
  26080. text: 'Bold',
  26081. icon: 'bold'
  26082. },
  26083. {
  26084. name: 'italic',
  26085. text: 'Italic',
  26086. icon: 'italic'
  26087. },
  26088. {
  26089. name: 'underline',
  26090. text: 'Underline',
  26091. icon: 'underline'
  26092. },
  26093. {
  26094. name: 'strikethrough',
  26095. text: 'Strikethrough',
  26096. icon: 'strike-through'
  26097. },
  26098. {
  26099. name: 'subscript',
  26100. text: 'Subscript',
  26101. icon: 'subscript'
  26102. },
  26103. {
  26104. name: 'superscript',
  26105. text: 'Superscript',
  26106. icon: 'superscript'
  26107. }
  26108. ], function (btn, idx) {
  26109. editor.ui.registry.addToggleButton(btn.name, {
  26110. tooltip: btn.text,
  26111. icon: btn.icon,
  26112. onSetup: onSetupFormatToggle(editor, btn.name),
  26113. onAction: toggleFormat(editor, btn.name)
  26114. });
  26115. });
  26116. for (var i = 1; i <= 6; i++) {
  26117. var name = 'h' + i;
  26118. editor.ui.registry.addToggleButton(name, {
  26119. text: name.toUpperCase(),
  26120. tooltip: 'Heading ' + i,
  26121. onSetup: onSetupFormatToggle(editor, name),
  26122. onAction: toggleFormat(editor, name)
  26123. });
  26124. }
  26125. };
  26126. var registerCommandButtons = function (editor) {
  26127. global$e.each([
  26128. {
  26129. name: 'cut',
  26130. text: 'Cut',
  26131. action: 'Cut',
  26132. icon: 'cut'
  26133. },
  26134. {
  26135. name: 'copy',
  26136. text: 'Copy',
  26137. action: 'Copy',
  26138. icon: 'copy'
  26139. },
  26140. {
  26141. name: 'paste',
  26142. text: 'Paste',
  26143. action: 'Paste',
  26144. icon: 'paste'
  26145. },
  26146. {
  26147. name: 'help',
  26148. text: 'Help',
  26149. action: 'mceHelp',
  26150. icon: 'help'
  26151. },
  26152. {
  26153. name: 'selectall',
  26154. text: 'Select all',
  26155. action: 'SelectAll',
  26156. icon: 'select-all'
  26157. },
  26158. {
  26159. name: 'newdocument',
  26160. text: 'New document',
  26161. action: 'mceNewDocument',
  26162. icon: 'new-document'
  26163. },
  26164. {
  26165. name: 'removeformat',
  26166. text: 'Clear formatting',
  26167. action: 'RemoveFormat',
  26168. icon: 'remove-formatting'
  26169. },
  26170. {
  26171. name: 'remove',
  26172. text: 'Remove',
  26173. action: 'Delete',
  26174. icon: 'remove'
  26175. }
  26176. ], function (btn) {
  26177. editor.ui.registry.addButton(btn.name, {
  26178. tooltip: btn.text,
  26179. icon: btn.icon,
  26180. onAction: function () {
  26181. return editor.execCommand(btn.action);
  26182. }
  26183. });
  26184. });
  26185. };
  26186. var registerCommandToggleButtons = function (editor) {
  26187. global$e.each([{
  26188. name: 'blockquote',
  26189. text: 'Blockquote',
  26190. action: 'mceBlockQuote',
  26191. icon: 'quote'
  26192. }], function (btn) {
  26193. editor.ui.registry.addToggleButton(btn.name, {
  26194. tooltip: btn.text,
  26195. icon: btn.icon,
  26196. onAction: function () {
  26197. return editor.execCommand(btn.action);
  26198. },
  26199. onSetup: onSetupFormatToggle(editor, btn.name)
  26200. });
  26201. });
  26202. };
  26203. var registerButtons = function (editor) {
  26204. registerFormatButtons(editor);
  26205. registerCommandButtons(editor);
  26206. registerCommandToggleButtons(editor);
  26207. };
  26208. var registerMenuItems = function (editor) {
  26209. global$e.each([
  26210. {
  26211. name: 'bold',
  26212. text: 'Bold',
  26213. action: 'Bold',
  26214. icon: 'bold',
  26215. shortcut: 'Meta+B'
  26216. },
  26217. {
  26218. name: 'italic',
  26219. text: 'Italic',
  26220. action: 'Italic',
  26221. icon: 'italic',
  26222. shortcut: 'Meta+I'
  26223. },
  26224. {
  26225. name: 'underline',
  26226. text: 'Underline',
  26227. action: 'Underline',
  26228. icon: 'underline',
  26229. shortcut: 'Meta+U'
  26230. },
  26231. {
  26232. name: 'strikethrough',
  26233. text: 'Strikethrough',
  26234. action: 'Strikethrough',
  26235. icon: 'strike-through',
  26236. shortcut: ''
  26237. },
  26238. {
  26239. name: 'subscript',
  26240. text: 'Subscript',
  26241. action: 'Subscript',
  26242. icon: 'subscript',
  26243. shortcut: ''
  26244. },
  26245. {
  26246. name: 'superscript',
  26247. text: 'Superscript',
  26248. action: 'Superscript',
  26249. icon: 'superscript',
  26250. shortcut: ''
  26251. },
  26252. {
  26253. name: 'removeformat',
  26254. text: 'Clear formatting',
  26255. action: 'RemoveFormat',
  26256. icon: 'remove-formatting',
  26257. shortcut: ''
  26258. },
  26259. {
  26260. name: 'newdocument',
  26261. text: 'New document',
  26262. action: 'mceNewDocument',
  26263. icon: 'new-document',
  26264. shortcut: ''
  26265. },
  26266. {
  26267. name: 'cut',
  26268. text: 'Cut',
  26269. action: 'Cut',
  26270. icon: 'cut',
  26271. shortcut: 'Meta+X'
  26272. },
  26273. {
  26274. name: 'copy',
  26275. text: 'Copy',
  26276. action: 'Copy',
  26277. icon: 'copy',
  26278. shortcut: 'Meta+C'
  26279. },
  26280. {
  26281. name: 'paste',
  26282. text: 'Paste',
  26283. action: 'Paste',
  26284. icon: 'paste',
  26285. shortcut: 'Meta+V'
  26286. },
  26287. {
  26288. name: 'selectall',
  26289. text: 'Select all',
  26290. action: 'SelectAll',
  26291. icon: 'select-all',
  26292. shortcut: 'Meta+A'
  26293. }
  26294. ], function (btn) {
  26295. editor.ui.registry.addMenuItem(btn.name, {
  26296. text: btn.text,
  26297. icon: btn.icon,
  26298. shortcut: btn.shortcut,
  26299. onAction: function () {
  26300. return editor.execCommand(btn.action);
  26301. }
  26302. });
  26303. });
  26304. editor.ui.registry.addMenuItem('codeformat', {
  26305. text: 'Code',
  26306. icon: 'sourcecode',
  26307. onAction: toggleFormat(editor, 'code')
  26308. });
  26309. };
  26310. var register$6 = function (editor) {
  26311. registerButtons(editor);
  26312. registerMenuItems(editor);
  26313. };
  26314. var SimpleControls = { register: register$6 };
  26315. var toggleUndoRedoState = function (api, editor, type) {
  26316. var checkState = function () {
  26317. return editor.undoManager ? editor.undoManager[type]() : false;
  26318. };
  26319. var onUndoStateChange = function () {
  26320. api.setDisabled(editor.readonly || !checkState());
  26321. };
  26322. api.setDisabled(!checkState());
  26323. editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  26324. return function () {
  26325. return editor.off('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  26326. };
  26327. };
  26328. var registerMenuItems$1 = function (editor) {
  26329. editor.ui.registry.addMenuItem('undo', {
  26330. text: 'Undo',
  26331. icon: 'undo',
  26332. shortcut: 'Meta+Z',
  26333. onSetup: function (api) {
  26334. return toggleUndoRedoState(api, editor, 'hasUndo');
  26335. },
  26336. onAction: function () {
  26337. return editor.execCommand('undo');
  26338. }
  26339. });
  26340. editor.ui.registry.addMenuItem('redo', {
  26341. text: 'Redo',
  26342. icon: 'redo',
  26343. shortcut: 'Meta+Y',
  26344. onSetup: function (api) {
  26345. return toggleUndoRedoState(api, editor, 'hasRedo');
  26346. },
  26347. onAction: function () {
  26348. return editor.execCommand('redo');
  26349. }
  26350. });
  26351. };
  26352. var registerButtons$1 = function (editor) {
  26353. editor.ui.registry.addButton('undo', {
  26354. tooltip: 'Undo',
  26355. icon: 'undo',
  26356. onSetup: function (api) {
  26357. return toggleUndoRedoState(api, editor, 'hasUndo');
  26358. },
  26359. onAction: function () {
  26360. return editor.execCommand('undo');
  26361. }
  26362. });
  26363. editor.ui.registry.addButton('redo', {
  26364. tooltip: 'Redo',
  26365. icon: 'redo',
  26366. onSetup: function (api) {
  26367. return toggleUndoRedoState(api, editor, 'hasRedo');
  26368. },
  26369. onAction: function () {
  26370. return editor.execCommand('redo');
  26371. }
  26372. });
  26373. };
  26374. var register$7 = function (editor) {
  26375. registerMenuItems$1(editor);
  26376. registerButtons$1(editor);
  26377. };
  26378. var UndoRedo = { register: register$7 };
  26379. var toggleVisualAidState = function (api, editor) {
  26380. api.setActive(editor.hasVisual);
  26381. var onVisualAid = function (e) {
  26382. api.setActive(e.hasVisual);
  26383. };
  26384. editor.on('VisualAid', onVisualAid);
  26385. return function () {
  26386. return editor.off('VisualAid', onVisualAid);
  26387. };
  26388. };
  26389. var registerMenuItems$2 = function (editor) {
  26390. editor.ui.registry.addToggleMenuItem('visualaid', {
  26391. text: 'Visual aids',
  26392. onSetup: function (api) {
  26393. return toggleVisualAidState(api, editor);
  26394. },
  26395. onAction: function () {
  26396. editor.execCommand('mceToggleVisualAid');
  26397. }
  26398. });
  26399. };
  26400. var registerToolbarButton = function (editor) {
  26401. editor.ui.registry.addButton('visualaid', {
  26402. tooltip: 'Visual aids',
  26403. text: 'Visual aids',
  26404. onAction: function () {
  26405. return editor.execCommand('mceToggleVisualAid');
  26406. }
  26407. });
  26408. };
  26409. var register$8 = function (editor) {
  26410. registerToolbarButton(editor);
  26411. registerMenuItems$2(editor);
  26412. };
  26413. var VisualAid = { register: register$8 };
  26414. var toggleOutdentState = function (api, editor) {
  26415. api.setDisabled(!editor.queryCommandState('outdent'));
  26416. var onNodeChange = function () {
  26417. api.setDisabled(!editor.queryCommandState('outdent'));
  26418. };
  26419. editor.on('NodeChange', onNodeChange);
  26420. return function () {
  26421. return editor.off('NodeChange', onNodeChange);
  26422. };
  26423. };
  26424. var registerButtons$2 = function (editor) {
  26425. editor.ui.registry.addButton('outdent', {
  26426. tooltip: 'Decrease indent',
  26427. icon: 'outdent',
  26428. onSetup: function (api) {
  26429. return toggleOutdentState(api, editor);
  26430. },
  26431. onAction: function () {
  26432. return editor.execCommand('outdent');
  26433. }
  26434. });
  26435. editor.ui.registry.addButton('indent', {
  26436. tooltip: 'Increase indent',
  26437. icon: 'indent',
  26438. onAction: function () {
  26439. return editor.execCommand('indent');
  26440. }
  26441. });
  26442. };
  26443. var register$9 = function (editor) {
  26444. registerButtons$2(editor);
  26445. };
  26446. var IndentOutdent = { register: register$9 };
  26447. var register$a = function (editor, backstage) {
  26448. alignSelectMenu(editor, backstage);
  26449. fontSelectMenu(editor, backstage);
  26450. styleSelectMenu(editor, backstage);
  26451. formatSelectMenu(editor, backstage);
  26452. fontsizeSelectMenu(editor, backstage);
  26453. };
  26454. var ComplexControls = { register: register$a };
  26455. var setup$8 = function (editor, backstage) {
  26456. AlignmentButtons.register(editor);
  26457. SimpleControls.register(editor);
  26458. ComplexControls.register(editor, backstage);
  26459. UndoRedo.register(editor);
  26460. ColorSwatch.register(editor);
  26461. VisualAid.register(editor);
  26462. IndentOutdent.register(editor);
  26463. };
  26464. var FormatControls = { setup: setup$8 };
  26465. var nu$d = function (x, y) {
  26466. return {
  26467. anchor: 'makeshift',
  26468. x: x,
  26469. y: y
  26470. };
  26471. };
  26472. var transpose$1 = function (pos, dx, dy) {
  26473. return nu$d(pos.x + dx, pos.y + dy);
  26474. };
  26475. var isTouchEvent = function (e) {
  26476. return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  26477. };
  26478. var fromPageXY = function (e) {
  26479. if (isTouchEvent(e)) {
  26480. var touch = e.touches[0];
  26481. return nu$d(touch.pageX, touch.pageY);
  26482. } else {
  26483. return nu$d(e.pageX, e.pageY);
  26484. }
  26485. };
  26486. var fromClientXY = function (e) {
  26487. if (isTouchEvent(e)) {
  26488. var touch = e.touches[0];
  26489. return nu$d(touch.clientX, touch.clientY);
  26490. } else {
  26491. return nu$d(e.clientX, e.clientY);
  26492. }
  26493. };
  26494. var transposeContentAreaContainer = function (element, pos) {
  26495. var containerPos = global$7.DOM.getPos(element);
  26496. return transpose$1(pos, containerPos.x, containerPos.y);
  26497. };
  26498. var getPointAnchor = function (editor, e) {
  26499. if (e.type === 'contextmenu') {
  26500. if (editor.inline) {
  26501. return fromPageXY(e);
  26502. } else {
  26503. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  26504. }
  26505. } else {
  26506. return getSelectionAnchor(editor);
  26507. }
  26508. };
  26509. var getSelectionAnchor = function (editor) {
  26510. return {
  26511. anchor: 'selection',
  26512. root: Element.fromDom(editor.selection.getNode())
  26513. };
  26514. };
  26515. var getNodeAnchor$1 = function (editor) {
  26516. return {
  26517. anchor: 'node',
  26518. node: Option.some(Element.fromDom(editor.selection.getNode())),
  26519. root: Element.fromDom(editor.getBody())
  26520. };
  26521. };
  26522. var getAnchorSpec = function (editor, e, isTriggeredByKeyboardEvent) {
  26523. return isTriggeredByKeyboardEvent ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
  26524. };
  26525. var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  26526. var items = buildMenu();
  26527. var anchorSpec = getAnchorSpec(editor, e, isTriggeredByKeyboardEvent);
  26528. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  26529. e.preventDefault();
  26530. InlineView.showMenuAt(contextmenu, anchorSpec, {
  26531. menu: { markers: markers$1('normal') },
  26532. data: menuData
  26533. });
  26534. });
  26535. };
  26536. var layouts = {
  26537. onLtr: function () {
  26538. return [
  26539. south$1,
  26540. southeast$1,
  26541. southwest$1,
  26542. northeast$1,
  26543. northwest$1,
  26544. north$1,
  26545. north$3,
  26546. south$3,
  26547. northeast$3,
  26548. southeast$3,
  26549. northwest$3,
  26550. southwest$3
  26551. ];
  26552. },
  26553. onRtl: function () {
  26554. return [
  26555. south$1,
  26556. southwest$1,
  26557. southeast$1,
  26558. northwest$1,
  26559. northeast$1,
  26560. north$1,
  26561. north$3,
  26562. south$3,
  26563. northwest$3,
  26564. southwest$3,
  26565. northeast$3,
  26566. southeast$3
  26567. ];
  26568. }
  26569. };
  26570. var bubbleSize$1 = 12;
  26571. var bubbleAlignments$2 = {
  26572. valignCentre: [],
  26573. alignCentre: [],
  26574. alignLeft: ['tox-pop--align-left'],
  26575. alignRight: ['tox-pop--align-right'],
  26576. right: ['tox-pop--right'],
  26577. left: ['tox-pop--left'],
  26578. bottom: ['tox-pop--bottom'],
  26579. top: ['tox-pop--top']
  26580. };
  26581. var isTouchWithinSelection = function (editor, e) {
  26582. var selection = editor.selection;
  26583. if (selection.isCollapsed() || e.touches.length < 1) {
  26584. return false;
  26585. } else {
  26586. var touch_1 = e.touches[0];
  26587. var rng = selection.getRng();
  26588. var rngRectOpt = getFirstRect$1(editor.getWin(), Selection.domRange(rng));
  26589. return rngRectOpt.exists(function (rngRect) {
  26590. return rngRect.left() <= touch_1.clientX && rngRect.right() >= touch_1.clientX && rngRect.top() <= touch_1.clientY && rngRect.bottom() >= touch_1.clientY;
  26591. });
  26592. }
  26593. };
  26594. var getAnchorSpec$1 = function (editor, isTriggeredByKeyboardEvent) {
  26595. var anchorSpec = isTriggeredByKeyboardEvent ? getNodeAnchor$1(editor) : getSelectionAnchor(editor);
  26596. return __assign({
  26597. bubble: nu$8(0, bubbleSize$1, bubbleAlignments$2),
  26598. layouts: layouts,
  26599. overrides: {
  26600. maxWidthFunction: expandable$1(),
  26601. maxHeightFunction: expandable()
  26602. }
  26603. }, anchorSpec);
  26604. };
  26605. var setupiOSOverrides = function (editor) {
  26606. var originalSelection = editor.selection.getRng();
  26607. var selectionReset = function () {
  26608. global$2.setEditorTimeout(editor, function () {
  26609. editor.selection.setRng(originalSelection);
  26610. }, 10);
  26611. unbindEventListeners();
  26612. };
  26613. editor.once('touchend', selectionReset);
  26614. var preventMousedown = function (e) {
  26615. e.preventDefault();
  26616. e.stopImmediatePropagation();
  26617. };
  26618. editor.on('mousedown', preventMousedown, true);
  26619. var clearSelectionReset = function () {
  26620. return unbindEventListeners();
  26621. };
  26622. editor.once('longpresscancel', clearSelectionReset);
  26623. var unbindEventListeners = function () {
  26624. editor.off('touchend', selectionReset);
  26625. editor.off('longpresscancel', clearSelectionReset);
  26626. editor.off('mousedown', preventMousedown);
  26627. };
  26628. };
  26629. var show = function (editor, e, items, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  26630. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  26631. var anchorSpec = getAnchorSpec$1(editor, isTriggeredByKeyboardEvent);
  26632. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  26633. e.preventDefault();
  26634. InlineView.showMenuWithinBounds(contextmenu, anchorSpec, {
  26635. menu: { markers: markers$1('normal') },
  26636. data: menuData,
  26637. type: 'horizontal'
  26638. }, function () {
  26639. return getBounds$2(editor, toolbarOrMenubarEnabled);
  26640. });
  26641. editor.fire(hideContextToolbarEvent);
  26642. });
  26643. };
  26644. var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  26645. var detection = detect$3();
  26646. var isiOS = detection.os.isiOS();
  26647. var isOSX = detection.os.isOSX();
  26648. var isAndroid = detection.os.isAndroid();
  26649. var open = function () {
  26650. var items = buildMenu();
  26651. show(editor, e, items, backstage, contextmenu, isTriggeredByKeyboardEvent);
  26652. };
  26653. if ((isOSX || isiOS) && !isTriggeredByKeyboardEvent) {
  26654. var openiOS_1 = function () {
  26655. setupiOSOverrides(editor);
  26656. open();
  26657. };
  26658. if (isTouchWithinSelection(editor, e)) {
  26659. openiOS_1();
  26660. } else {
  26661. editor.once('selectionchange', openiOS_1);
  26662. editor.once('touchend', function () {
  26663. return editor.off('selectionchange', openiOS_1);
  26664. });
  26665. }
  26666. } else {
  26667. if (isAndroid && !isTriggeredByKeyboardEvent) {
  26668. editor.selection.setCursorLocation(e.target, 0);
  26669. }
  26670. open();
  26671. }
  26672. };
  26673. var patchPipeConfig = function (config) {
  26674. return typeof config === 'string' ? config.split(/[ ,]/) : config;
  26675. };
  26676. var shouldNeverUseNative = function (editor) {
  26677. return editor.settings.contextmenu_never_use_native || false;
  26678. };
  26679. var getMenuItems = function (editor, name, defaultItems) {
  26680. var contextMenus = editor.ui.registry.getAll().contextMenus;
  26681. return get(editor.settings, name).map(patchPipeConfig).getOrThunk(function () {
  26682. return filter(patchPipeConfig(defaultItems), function (item) {
  26683. return has(contextMenus, item);
  26684. });
  26685. });
  26686. };
  26687. var isContextMenuDisabled = function (editor) {
  26688. return editor.getParam('contextmenu') === false;
  26689. };
  26690. var getContextMenu = function (editor) {
  26691. return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  26692. };
  26693. var Settings$1 = {
  26694. shouldNeverUseNative: shouldNeverUseNative,
  26695. getContextMenu: getContextMenu,
  26696. isContextMenuDisabled: isContextMenuDisabled
  26697. };
  26698. var isSeparator$1 = function (item) {
  26699. return isString(item) ? item === '|' : item.type === 'separator';
  26700. };
  26701. var separator$3 = { type: 'separator' };
  26702. var makeContextItem = function (item) {
  26703. if (isString(item)) {
  26704. return item;
  26705. } else {
  26706. switch (item.type) {
  26707. case 'separator':
  26708. return separator$3;
  26709. case 'submenu':
  26710. return {
  26711. type: 'nestedmenuitem',
  26712. text: item.text,
  26713. icon: item.icon,
  26714. getSubmenuItems: function () {
  26715. var items = item.getSubmenuItems();
  26716. if (isString(items)) {
  26717. return items;
  26718. } else {
  26719. return map(items, makeContextItem);
  26720. }
  26721. }
  26722. };
  26723. default:
  26724. return {
  26725. type: 'menuitem',
  26726. text: item.text,
  26727. icon: item.icon,
  26728. onAction: noarg(item.onAction)
  26729. };
  26730. }
  26731. }
  26732. };
  26733. var addContextMenuGroup = function (xs, groupItems) {
  26734. if (groupItems.length === 0) {
  26735. return xs;
  26736. }
  26737. var lastMenuItem = last(xs).filter(function (item) {
  26738. return !isSeparator$1(item);
  26739. });
  26740. var before = lastMenuItem.fold(function () {
  26741. return [];
  26742. }, function (_) {
  26743. return [separator$3];
  26744. });
  26745. return xs.concat(before).concat(groupItems).concat([separator$3]);
  26746. };
  26747. var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  26748. var sections = foldl(menuConfig, function (acc, name) {
  26749. if (has(contextMenus, name)) {
  26750. var items = contextMenus[name].update(selectedElement);
  26751. if (isString(items)) {
  26752. return addContextMenuGroup(acc, items.split(' '));
  26753. } else if (items.length > 0) {
  26754. var allItems = map(items, makeContextItem);
  26755. return addContextMenuGroup(acc, allItems);
  26756. } else {
  26757. return acc;
  26758. }
  26759. } else {
  26760. return acc.concat([name]);
  26761. }
  26762. }, []);
  26763. if (sections.length > 0 && isSeparator$1(sections[sections.length - 1])) {
  26764. sections.pop();
  26765. }
  26766. return sections;
  26767. };
  26768. var isNativeOverrideKeyEvent = function (editor, e) {
  26769. return e.ctrlKey && !Settings$1.shouldNeverUseNative(editor);
  26770. };
  26771. var setup$9 = function (editor, lazySink, backstage) {
  26772. var detection = detect$3();
  26773. var isTouch = detection.deviceType.isTouch;
  26774. var contextmenu = build$1(InlineView.sketch({
  26775. dom: { tag: 'div' },
  26776. lazySink: lazySink,
  26777. onEscape: function () {
  26778. return editor.focus();
  26779. },
  26780. onShow: function () {
  26781. return backstage.setContextMenuState(true);
  26782. },
  26783. onHide: function () {
  26784. return backstage.setContextMenuState(false);
  26785. },
  26786. fireDismissalEventInstead: {},
  26787. inlineBehaviours: derive$1([config('dismissContextMenu', [run(dismissRequested(), function (comp, se) {
  26788. Sandboxing.close(comp);
  26789. editor.focus();
  26790. })])])
  26791. }));
  26792. var hideContextMenu = function (_e) {
  26793. return InlineView.hide(contextmenu);
  26794. };
  26795. var showContextMenu = function (e) {
  26796. var isLongpress = e.type === 'longpress';
  26797. if (Settings$1.shouldNeverUseNative(editor)) {
  26798. e.preventDefault();
  26799. }
  26800. if (isNativeOverrideKeyEvent(editor, e) || Settings$1.isContextMenuDisabled(editor)) {
  26801. return;
  26802. }
  26803. var isTriggeredByKeyboardEvent = !isLongpress && (e.button !== 2 || e.target === editor.getBody());
  26804. var buildMenu = function () {
  26805. var selectedElement = isTriggeredByKeyboardEvent ? editor.selection.getStart(true) : e.target;
  26806. var registry = editor.ui.registry.getAll();
  26807. var menuConfig = Settings$1.getContextMenu(editor);
  26808. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  26809. };
  26810. var initAndShow$2 = isTouch() ? initAndShow$1 : initAndShow;
  26811. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent);
  26812. };
  26813. editor.on('init', function () {
  26814. var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : 'ResizeWindow');
  26815. editor.on(hideEvents, hideContextMenu);
  26816. editor.on(isTouch() ? 'longpress' : 'longpress contextmenu', showContextMenu);
  26817. });
  26818. };
  26819. var parseToInt = function (val) {
  26820. var re = /^[0-9\.]+(|px)$/i;
  26821. if (re.test('' + val)) {
  26822. return Option.some(parseInt(val, 10));
  26823. }
  26824. return Option.none();
  26825. };
  26826. var numToPx = function (val) {
  26827. return isNumber(val) ? val + 'px' : val;
  26828. };
  26829. var Utils = {
  26830. parseToInt: parseToInt,
  26831. numToPx: numToPx
  26832. };
  26833. var initialAttribute = 'data-initial-z-index';
  26834. var resetZIndex = function (blocker) {
  26835. parent(blocker.element()).filter(isElement).each(function (root) {
  26836. var initZIndex = get$2(root, initialAttribute);
  26837. if (has$1(root, initialAttribute)) {
  26838. set$2(root, 'z-index', initZIndex);
  26839. } else {
  26840. remove$6(root, 'z-index');
  26841. }
  26842. remove$1(root, initialAttribute);
  26843. });
  26844. };
  26845. var changeZIndex = function (blocker) {
  26846. parent(blocker.element()).filter(isElement).each(function (root) {
  26847. getRaw(root, 'z-index').each(function (zindex) {
  26848. set$1(root, initialAttribute, zindex);
  26849. });
  26850. set$2(root, 'z-index', get$4(blocker.element(), 'z-index'));
  26851. });
  26852. };
  26853. var instigate = function (anyComponent, blocker) {
  26854. anyComponent.getSystem().addToGui(blocker);
  26855. changeZIndex(blocker);
  26856. };
  26857. var discard = function (blocker) {
  26858. resetZIndex(blocker);
  26859. blocker.getSystem().removeFromGui(blocker);
  26860. };
  26861. var get$d = function (component, snapsInfo) {
  26862. var element = component.element();
  26863. var x = parseInt(get$2(element, snapsInfo.leftAttr), 10);
  26864. var y = parseInt(get$2(element, snapsInfo.topAttr), 10);
  26865. return isNaN(x) || isNaN(y) ? Option.none() : Option.some(Position(x, y));
  26866. };
  26867. var set$8 = function (component, snapsInfo, pt) {
  26868. var element = component.element();
  26869. set$1(element, snapsInfo.leftAttr, pt.left() + 'px');
  26870. set$1(element, snapsInfo.topAttr, pt.top() + 'px');
  26871. };
  26872. var clear = function (component, snapsInfo) {
  26873. var element = component.element();
  26874. remove$1(element, snapsInfo.leftAttr);
  26875. remove$1(element, snapsInfo.topAttr);
  26876. };
  26877. var getCoords = function (component, snapInfo, coord, delta) {
  26878. return get$d(component, snapInfo).fold(function () {
  26879. return coord;
  26880. }, function (fixed) {
  26881. return fixed$1(fixed.left() + delta.left(), fixed.top() + delta.top());
  26882. });
  26883. };
  26884. var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  26885. var newCoord = getCoords(component, snapInfo, coord, delta);
  26886. var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  26887. var fixedCoord = asFixed(newCoord, scroll, origin);
  26888. set$8(component, snapInfo, fixedCoord);
  26889. return snap.fold(function () {
  26890. return {
  26891. coord: fixed$1(fixedCoord.left(), fixedCoord.top()),
  26892. extra: Option.none()
  26893. };
  26894. }, function (spanned) {
  26895. return {
  26896. coord: spanned.output(),
  26897. extra: spanned.extra()
  26898. };
  26899. });
  26900. };
  26901. var stopDrag = function (component, snapInfo) {
  26902. clear(component, snapInfo);
  26903. };
  26904. var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  26905. return findMap(snaps, function (snap) {
  26906. var sensor = snap.sensor();
  26907. var inRange = withinRange(newCoord, sensor, snap.range().left(), snap.range().top(), scroll, origin);
  26908. return inRange ? Option.some({
  26909. output: constant(absorb(snap.output(), newCoord, scroll, origin)),
  26910. extra: snap.extra
  26911. }) : Option.none();
  26912. });
  26913. };
  26914. var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  26915. var snaps = snapInfo.getSnapPoints(component);
  26916. var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  26917. return matchSnap.orThunk(function () {
  26918. var bestSnap = foldl(snaps, function (acc, snap) {
  26919. var sensor = snap.sensor();
  26920. var deltas = getDeltas(newCoord, sensor, snap.range().left(), snap.range().top(), scroll, origin);
  26921. return acc.deltas.fold(function () {
  26922. return {
  26923. deltas: Option.some(deltas),
  26924. snap: Option.some(snap)
  26925. };
  26926. }, function (bestDeltas) {
  26927. var currAvg = (deltas.left() + deltas.top()) / 2;
  26928. var bestAvg = (bestDeltas.left() + bestDeltas.top()) / 2;
  26929. if (currAvg <= bestAvg) {
  26930. return {
  26931. deltas: Option.some(deltas),
  26932. snap: Option.some(snap)
  26933. };
  26934. } else {
  26935. return acc;
  26936. }
  26937. });
  26938. }, {
  26939. deltas: Option.none(),
  26940. snap: Option.none()
  26941. });
  26942. return bestSnap.snap.map(function (snap) {
  26943. return {
  26944. output: constant(absorb(snap.output(), newCoord, scroll, origin)),
  26945. extra: snap.extra
  26946. };
  26947. });
  26948. });
  26949. };
  26950. var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  26951. var snaps = snapInfo.getSnapPoints(component);
  26952. return findMatchingSnap(snaps, newCoord, scroll, origin);
  26953. };
  26954. var snapTo = function (snap, scroll, origin) {
  26955. return {
  26956. coord: absorb(snap.output(), snap.output(), scroll, origin),
  26957. extra: snap.extra()
  26958. };
  26959. };
  26960. var getCurrentCoord = function (target) {
  26961. return getRaw(target, 'left').bind(function (left) {
  26962. return getRaw(target, 'top').bind(function (top) {
  26963. return getRaw(target, 'position').map(function (position) {
  26964. var nu = position === 'fixed' ? fixed$1 : offset;
  26965. return nu(parseInt(left, 10), parseInt(top, 10));
  26966. });
  26967. });
  26968. }).getOrThunk(function () {
  26969. var location = absolute(target);
  26970. return absolute$3(location.left(), location.top());
  26971. });
  26972. };
  26973. var calcStartData = function (dragConfig, comp) {
  26974. return {
  26975. bounds: dragConfig.getBounds(),
  26976. height: getOuter$1(comp.element()),
  26977. width: getOuter$2(comp.element()),
  26978. comp: comp
  26979. };
  26980. };
  26981. var clampCoords = function (component, coords, scroll, origin, startData) {
  26982. var bounds = startData.bounds;
  26983. var absoluteCoord = asAbsolute(coords, scroll, origin);
  26984. var newX = cap(absoluteCoord.left(), bounds.x(), bounds.x() + bounds.width() - startData.width);
  26985. var newY = cap(absoluteCoord.top(), bounds.y(), bounds.y() + bounds.height() - startData.height);
  26986. var newCoords = absolute$3(newX, newY);
  26987. return coords.fold(function () {
  26988. var offset$1 = asOffset(newCoords, scroll, origin);
  26989. return offset(offset$1.left(), offset$1.top());
  26990. }, function () {
  26991. return newCoords;
  26992. }, function () {
  26993. var fixed = asFixed(newCoords, scroll, origin);
  26994. return fixed$1(fixed.left(), fixed.top());
  26995. });
  26996. };
  26997. var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  26998. var newCoord = optSnaps.fold(function () {
  26999. var translated = translate$2(currentCoord, delta.left(), delta.top());
  27000. var fixedCoord = asFixed(translated, scroll, origin);
  27001. return fixed$1(fixedCoord.left(), fixedCoord.top());
  27002. }, function (snapInfo) {
  27003. var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  27004. snapping.extra.each(function (extra) {
  27005. snapInfo.onSensor(component, extra);
  27006. });
  27007. return snapping.coord;
  27008. });
  27009. return clampCoords(component, newCoord, scroll, origin, startData);
  27010. };
  27011. var dragBy = function (component, dragConfig, startData, delta) {
  27012. var target = dragConfig.getTarget(component.element());
  27013. if (dragConfig.repositionTarget) {
  27014. var doc = owner(component.element());
  27015. var scroll = get$8(doc);
  27016. var origin = getOrigin(target);
  27017. var currentCoord = getCurrentCoord(target);
  27018. var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll, origin, delta, startData);
  27019. var styles = toStyles(newCoord, scroll, origin);
  27020. setAll$1(target, styles);
  27021. }
  27022. dragConfig.onDrag(component, target, delta);
  27023. };
  27024. var SnapSchema = optionObjOf('snaps', [
  27025. strict$1('getSnapPoints'),
  27026. onHandler('onSensor'),
  27027. strict$1('leftAttr'),
  27028. strict$1('topAttr'),
  27029. defaulted$1('lazyViewport', win),
  27030. defaulted$1('mustSnap', false)
  27031. ]);
  27032. var init$c = function (dragApi) {
  27033. return derive([
  27034. run(mousedown(), dragApi.forceDrop),
  27035. run(mouseup(), dragApi.drop),
  27036. run(mousemove(), function (comp, simulatedEvent) {
  27037. dragApi.move(simulatedEvent.event());
  27038. }),
  27039. run(mouseout(), dragApi.delayDrop)
  27040. ]);
  27041. };
  27042. var getData$1 = function (event) {
  27043. return Option.from(Position(event.x(), event.y()));
  27044. };
  27045. var getDelta$1 = function (old, nu) {
  27046. return Position(nu.left() - old.left(), nu.top() - old.top());
  27047. };
  27048. var MouseData = /*#__PURE__*/Object.freeze({
  27049. getData: getData$1,
  27050. getDelta: getDelta$1
  27051. });
  27052. var handlers = function (dragConfig, dragState) {
  27053. var updateStartState = function (comp) {
  27054. dragState.setStartData(calcStartData(dragConfig, comp));
  27055. };
  27056. return derive([
  27057. run(windowScroll(), updateStartState),
  27058. run(mousedown(), function (component, simulatedEvent) {
  27059. var raw = simulatedEvent.event().raw();
  27060. if (raw.button !== 0) {
  27061. return;
  27062. }
  27063. simulatedEvent.stop();
  27064. var dragApi = {
  27065. drop: function () {
  27066. stop();
  27067. },
  27068. delayDrop: function () {
  27069. delayDrop.schedule();
  27070. },
  27071. forceDrop: function () {
  27072. stop();
  27073. },
  27074. move: function (event) {
  27075. delayDrop.cancel();
  27076. var delta = dragState.update(MouseData, event);
  27077. var dragStartData = dragState.getStartData().getOrThunk(function () {
  27078. return calcStartData(dragConfig, component);
  27079. });
  27080. delta.each(function (dlt) {
  27081. dragBy(component, dragConfig, dragStartData, dlt);
  27082. });
  27083. }
  27084. };
  27085. var blocker = component.getSystem().build(Container.sketch({
  27086. dom: {
  27087. styles: {
  27088. 'left': '0px',
  27089. 'top': '0px',
  27090. 'width': '100%',
  27091. 'height': '100%',
  27092. 'position': 'fixed',
  27093. 'z-index': '1000000000000000'
  27094. },
  27095. classes: [dragConfig.blockerClass]
  27096. },
  27097. events: init$c(dragApi)
  27098. }));
  27099. var stop = function () {
  27100. discard(blocker);
  27101. dragConfig.snaps.each(function (snapInfo) {
  27102. stopDrag(component, snapInfo);
  27103. });
  27104. var target = dragConfig.getTarget(component.element());
  27105. dragState.reset();
  27106. dragConfig.onDrop(component, target);
  27107. };
  27108. var delayDrop = DelayedFunction(stop, 200);
  27109. var start = function () {
  27110. updateStartState(component);
  27111. instigate(component, blocker);
  27112. };
  27113. start();
  27114. })
  27115. ]);
  27116. };
  27117. var schema$s = [
  27118. defaulted$1('useFixed', never),
  27119. strict$1('blockerClass'),
  27120. defaulted$1('getTarget', identity),
  27121. defaulted$1('onDrag', noop),
  27122. defaulted$1('repositionTarget', true),
  27123. onHandler('onDrop'),
  27124. defaultedFunction('getBounds', win),
  27125. SnapSchema,
  27126. output('dragger', { handlers: handlers })
  27127. ];
  27128. var getDataFrom = function (touches) {
  27129. var touch = touches[0];
  27130. return Option.some(Position(touch.clientX, touch.clientY));
  27131. };
  27132. var getData$2 = function (event) {
  27133. var raw = event.raw();
  27134. var touches = raw.touches;
  27135. return touches.length === 1 ? getDataFrom(touches) : Option.none();
  27136. };
  27137. var getDelta$2 = function (old, nu) {
  27138. return Position(nu.left() - old.left(), nu.top() - old.top());
  27139. };
  27140. var TouchData = /*#__PURE__*/Object.freeze({
  27141. getData: getData$2,
  27142. getDelta: getDelta$2
  27143. });
  27144. var handlers$1 = function (dragConfig, dragState) {
  27145. var updateStartState = function (comp) {
  27146. dragState.setStartData(calcStartData(dragConfig, comp));
  27147. };
  27148. return derive([
  27149. run(windowScroll(), updateStartState),
  27150. run(touchstart(), function (component, simulatedEvent) {
  27151. updateStartState(component);
  27152. simulatedEvent.stop();
  27153. }),
  27154. run(documentTouchmove(), function (component, simulatedEvent) {
  27155. dragState.getStartData().each(function (startData) {
  27156. if (eq(startData.comp.element(), component.element())) {
  27157. simulatedEvent.stop();
  27158. var delta = dragState.update(TouchData, simulatedEvent.event());
  27159. var dragStartData_1 = dragState.getStartData().getOrThunk(function () {
  27160. return calcStartData(dragConfig, component);
  27161. });
  27162. delta.each(function (dlt) {
  27163. dragBy(component, dragConfig, dragStartData_1, dlt);
  27164. });
  27165. }
  27166. });
  27167. }),
  27168. run(documentTouchend(), function (component, simulatedEvent) {
  27169. dragState.getStartData().each(function (startData) {
  27170. if (eq(startData.comp.element(), component.element())) {
  27171. dragConfig.snaps.each(function (snapInfo) {
  27172. stopDrag(component, snapInfo);
  27173. });
  27174. var target = dragConfig.getTarget(component.element());
  27175. dragState.reset();
  27176. dragConfig.onDrop(component, target);
  27177. }
  27178. });
  27179. })
  27180. ]);
  27181. };
  27182. var schema$t = [
  27183. defaulted$1('useFixed', never),
  27184. defaulted$1('getTarget', identity),
  27185. defaulted$1('onDrag', noop),
  27186. defaulted$1('repositionTarget', true),
  27187. defaulted$1('onDrop', noop),
  27188. defaultedFunction('getBounds', win),
  27189. SnapSchema,
  27190. output('dragger', { handlers: handlers$1 })
  27191. ];
  27192. var mouse = schema$s;
  27193. var touch = schema$t;
  27194. var DraggingBranches = /*#__PURE__*/Object.freeze({
  27195. mouse: mouse,
  27196. touch: touch
  27197. });
  27198. var init$d = function () {
  27199. var previous = Option.none();
  27200. var startData = Option.none();
  27201. var reset = function () {
  27202. previous = Option.none();
  27203. startData = Option.none();
  27204. };
  27205. var calculateDelta = function (mode, nu) {
  27206. var result = previous.map(function (old) {
  27207. return mode.getDelta(old, nu);
  27208. });
  27209. previous = Option.some(nu);
  27210. return result;
  27211. };
  27212. var update = function (mode, dragEvent) {
  27213. return mode.getData(dragEvent).bind(function (nuData) {
  27214. return calculateDelta(mode, nuData);
  27215. });
  27216. };
  27217. var setStartData = function (data) {
  27218. startData = Option.some(data);
  27219. };
  27220. var getStartData = function () {
  27221. return startData;
  27222. };
  27223. var readState = constant({});
  27224. return nu$5({
  27225. readState: readState,
  27226. reset: reset,
  27227. update: update,
  27228. getStartData: getStartData,
  27229. setStartData: setStartData
  27230. });
  27231. };
  27232. var DragState = /*#__PURE__*/Object.freeze({
  27233. init: init$d
  27234. });
  27235. var snapTo$1 = function (component, dragConfig, _state, snap) {
  27236. var target = dragConfig.getTarget(component.element());
  27237. if (dragConfig.repositionTarget) {
  27238. var doc = owner(component.element());
  27239. var scroll = get$8(doc);
  27240. var origin = getOrigin(target);
  27241. var snapPin = snapTo(snap, scroll, origin);
  27242. var styles = toStyles(snapPin.coord, scroll, origin);
  27243. setAll$1(target, styles);
  27244. }
  27245. };
  27246. var DraggingApis = /*#__PURE__*/Object.freeze({
  27247. snapTo: snapTo$1
  27248. });
  27249. var Dragging = createModes$1({
  27250. branchKey: 'mode',
  27251. branches: DraggingBranches,
  27252. name: 'dragging',
  27253. active: {
  27254. events: function (dragConfig, dragState) {
  27255. var dragger = dragConfig.dragger;
  27256. return dragger.handlers(dragConfig, dragState);
  27257. }
  27258. },
  27259. extra: {
  27260. snap: MixedBag([
  27261. 'sensor',
  27262. 'range',
  27263. 'output'
  27264. ], ['extra'])
  27265. },
  27266. state: DragState,
  27267. apis: DraggingApis
  27268. });
  27269. var ResizeTypes;
  27270. (function (ResizeTypes) {
  27271. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  27272. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  27273. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  27274. }(ResizeTypes || (ResizeTypes = {})));
  27275. var calcCappedSize = function (originalSize, delta, minSize, maxSize) {
  27276. var newSize = originalSize + delta;
  27277. var minOverride = minSize.filter(function (min) {
  27278. return newSize < min;
  27279. });
  27280. var maxOverride = maxSize.filter(function (max) {
  27281. return newSize > max;
  27282. });
  27283. return minOverride.or(maxOverride).getOr(newSize);
  27284. };
  27285. var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  27286. var dimensions = {};
  27287. dimensions.height = calcCappedSize(originalHeight, deltas.top(), getMinHeightSetting(editor), getMaxHeightSetting(editor));
  27288. if (resizeType === ResizeTypes.Both) {
  27289. dimensions.width = calcCappedSize(originalWidth, deltas.left(), getMinWidthSetting(editor), getMaxWidthSetting(editor));
  27290. }
  27291. return dimensions;
  27292. };
  27293. var resize$3 = function (editor, deltas, resizeType) {
  27294. var container = Element.fromDom(editor.getContainer());
  27295. var dimensions = getDimensions(editor, deltas, resizeType, get$6(container), get$7(container));
  27296. each$1(dimensions, function (val, dim) {
  27297. return set$2(container, dim, Utils.numToPx(val));
  27298. });
  27299. Events.fireResizeEditor(editor);
  27300. };
  27301. var isHidden$1 = function (elm) {
  27302. if (elm.nodeType === 1) {
  27303. if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  27304. return true;
  27305. }
  27306. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  27307. return true;
  27308. }
  27309. }
  27310. return false;
  27311. };
  27312. var renderElementPath = function (editor, settings) {
  27313. if (!settings.delimiter) {
  27314. settings.delimiter = '\xBB';
  27315. }
  27316. var getDataPath = function (data) {
  27317. var parts = data || [];
  27318. var newPathElements = map(parts, function (part, index) {
  27319. return Button.sketch({
  27320. dom: {
  27321. tag: 'div',
  27322. classes: ['tox-statusbar__path-item'],
  27323. attributes: {
  27324. 'role': 'button',
  27325. 'data-index': index,
  27326. 'tab-index': -1,
  27327. 'aria-level': index + 1
  27328. },
  27329. innerHtml: part.name
  27330. },
  27331. action: function (btn) {
  27332. editor.focus();
  27333. editor.selection.select(part.element);
  27334. editor.nodeChanged();
  27335. }
  27336. });
  27337. });
  27338. var divider = {
  27339. dom: {
  27340. tag: 'div',
  27341. classes: ['tox-statusbar__path-divider'],
  27342. attributes: { 'aria-hidden': true },
  27343. innerHtml: ' ' + settings.delimiter + ' '
  27344. }
  27345. };
  27346. return foldl(newPathElements.slice(1), function (acc, element) {
  27347. var newAcc = acc;
  27348. newAcc.push(divider);
  27349. newAcc.push(element);
  27350. return newAcc;
  27351. }, [newPathElements[0]]);
  27352. };
  27353. var updatePath = function (parents) {
  27354. var newPath = [];
  27355. var i = parents.length;
  27356. while (i-- > 0) {
  27357. var parent = parents[i];
  27358. if (parent.nodeType === 1 && !isHidden$1(parent)) {
  27359. var args = editor.fire('ResolveName', {
  27360. name: parent.nodeName.toLowerCase(),
  27361. target: parent
  27362. });
  27363. if (!args.isDefaultPrevented()) {
  27364. newPath.push({
  27365. name: args.name,
  27366. element: parent
  27367. });
  27368. }
  27369. if (args.isPropagationStopped()) {
  27370. break;
  27371. }
  27372. }
  27373. }
  27374. return newPath;
  27375. };
  27376. return {
  27377. dom: {
  27378. tag: 'div',
  27379. classes: ['tox-statusbar__path'],
  27380. attributes: { role: 'navigation' }
  27381. },
  27382. behaviours: derive$1([
  27383. Keying.config({
  27384. mode: 'flow',
  27385. selector: 'div[role=button]'
  27386. }),
  27387. Tabstopping.config({}),
  27388. Replacing.config({}),
  27389. config('elementPathEvents', [runOnAttached(function (comp, e) {
  27390. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  27391. return Keying.focusIn(comp);
  27392. });
  27393. editor.on('NodeChange', function (e) {
  27394. var newPath = updatePath(e.parents);
  27395. if (newPath.length > 0) {
  27396. Replacing.set(comp, getDataPath(newPath));
  27397. }
  27398. });
  27399. })])
  27400. ]),
  27401. components: []
  27402. };
  27403. };
  27404. var ElementPath = { renderElementPath: renderElementPath };
  27405. var renderWordCount = function (editor, providersBackstage) {
  27406. var _a;
  27407. var replaceCountText = function (comp, count, mode) {
  27408. return Replacing.set(comp, [text(providersBackstage.translate([
  27409. '{0} ' + mode,
  27410. count[mode]
  27411. ]))]);
  27412. };
  27413. return Button.sketch({
  27414. dom: {
  27415. tag: 'button',
  27416. classes: ['tox-statusbar__wordcount']
  27417. },
  27418. components: [],
  27419. buttonBehaviours: derive$1([
  27420. Tabstopping.config({}),
  27421. Replacing.config({}),
  27422. Representing.config({
  27423. store: {
  27424. mode: 'memory',
  27425. initialValue: {
  27426. mode: 'words',
  27427. count: {
  27428. words: 0,
  27429. characters: 0
  27430. }
  27431. }
  27432. }
  27433. }),
  27434. config('wordcount-events', [
  27435. run(tapOrClick(), function (comp) {
  27436. var currentVal = Representing.getValue(comp);
  27437. var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  27438. Representing.setValue(comp, {
  27439. mode: newMode,
  27440. count: currentVal.count
  27441. });
  27442. replaceCountText(comp, currentVal.count, newMode);
  27443. }),
  27444. runOnAttached(function (comp) {
  27445. editor.on('wordCountUpdate', function (e) {
  27446. var mode = Representing.getValue(comp).mode;
  27447. Representing.setValue(comp, {
  27448. mode: mode,
  27449. count: e.wordCount
  27450. });
  27451. replaceCountText(comp, e.wordCount, mode);
  27452. });
  27453. })
  27454. ])
  27455. ]),
  27456. eventOrder: (_a = {}, _a[tapOrClick()] = [
  27457. 'wordcount-events',
  27458. 'alloy.base.behaviour'
  27459. ], _a)
  27460. });
  27461. };
  27462. var renderStatusbar = function (editor, providersBackstage) {
  27463. var renderResizeHandlerIcon = function (resizeType) {
  27464. return {
  27465. dom: {
  27466. tag: 'div',
  27467. classes: ['tox-statusbar__resize-handle'],
  27468. attributes: { title: providersBackstage.translate('Resize') },
  27469. innerHtml: get$c('resize-handle', providersBackstage.icons)
  27470. },
  27471. behaviours: derive$1([Dragging.config({
  27472. mode: 'mouse',
  27473. repositionTarget: false,
  27474. onDrag: function (comp, target, delta) {
  27475. resize$3(editor, delta, resizeType);
  27476. },
  27477. blockerClass: 'tox-blocker'
  27478. })])
  27479. };
  27480. };
  27481. var renderBranding = function () {
  27482. var label = global$5.translate([
  27483. 'Powered by {0}',
  27484. 'Tiny'
  27485. ]);
  27486. 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>';
  27487. return {
  27488. dom: {
  27489. tag: 'span',
  27490. classes: ['tox-statusbar__branding'],
  27491. innerHtml: linkHtml
  27492. }
  27493. };
  27494. };
  27495. var getResizeType = function (editor) {
  27496. var fallback = !contains$1(editor.settings.plugins, 'autoresize');
  27497. var resize = editor.getParam('resize', fallback);
  27498. if (resize === false) {
  27499. return ResizeTypes.None;
  27500. } else if (resize === 'both') {
  27501. return ResizeTypes.Both;
  27502. } else {
  27503. return ResizeTypes.Vertical;
  27504. }
  27505. };
  27506. var getTextComponents = function () {
  27507. var components = [];
  27508. if (editor.getParam('elementpath', true, 'boolean')) {
  27509. components.push(ElementPath.renderElementPath(editor, {}));
  27510. }
  27511. if (contains$1(editor.settings.plugins, 'wordcount')) {
  27512. components.push(renderWordCount(editor, providersBackstage));
  27513. }
  27514. if (editor.getParam('branding', true, 'boolean')) {
  27515. components.push(renderBranding());
  27516. }
  27517. if (components.length > 0) {
  27518. return [{
  27519. dom: {
  27520. tag: 'div',
  27521. classes: ['tox-statusbar__text-container']
  27522. },
  27523. components: components
  27524. }];
  27525. }
  27526. return [];
  27527. };
  27528. var getComponents = function () {
  27529. var components = getTextComponents();
  27530. var resizeType = getResizeType(editor);
  27531. if (resizeType !== ResizeTypes.None) {
  27532. components.push(renderResizeHandlerIcon(resizeType));
  27533. }
  27534. return components;
  27535. };
  27536. return {
  27537. dom: {
  27538. tag: 'div',
  27539. classes: ['tox-statusbar']
  27540. },
  27541. components: getComponents()
  27542. };
  27543. };
  27544. var platform$2 = detect$3();
  27545. var snapWidth = 40;
  27546. var snapOffset = snapWidth / 2;
  27547. var setup$a = function (editor, sink) {
  27548. var tlTds = Cell([]);
  27549. var brTds = Cell([]);
  27550. var getTopLeftSnap = function (td) {
  27551. var box = absolute$1(td);
  27552. return memTopLeft.getOpt(sink).fold(function () {
  27553. return Dragging.snap({
  27554. sensor: absolute$3(box.x() - snapOffset, box.y() - snapOffset),
  27555. range: Position(box.width(), box.height()),
  27556. output: absolute$3(Option.some(box.x()), Option.some(box.y())),
  27557. extra: { td: td }
  27558. });
  27559. }, function (selectorHandle) {
  27560. var sensorLeft = box.x() - snapOffset;
  27561. var sensorTop = box.y() - snapOffset;
  27562. var sensorWidth = snapWidth;
  27563. var sensorHeight = snapWidth;
  27564. var rect = selectorHandle.element().dom().getBoundingClientRect();
  27565. return Dragging.snap({
  27566. sensor: absolute$3(sensorLeft, sensorTop),
  27567. range: Position(sensorWidth, sensorHeight),
  27568. output: absolute$3(Option.some(box.x() - rect.width / 2), Option.some(box.y() - rect.height / 2)),
  27569. extra: { td: td }
  27570. });
  27571. });
  27572. };
  27573. var getTopLeftSnaps = function () {
  27574. return map(tlTds.get(), function (td) {
  27575. return getTopLeftSnap(td);
  27576. });
  27577. };
  27578. var getBottomRightSnap = function (td) {
  27579. var box = absolute$1(td);
  27580. return memBottomRight.getOpt(sink).fold(function () {
  27581. return Dragging.snap({
  27582. sensor: absolute$3(box.x() - snapOffset, box.y() - snapOffset),
  27583. range: Position(box.width(), box.height()),
  27584. output: absolute$3(Option.some(box.right()), Option.some(box.bottom())),
  27585. extra: { td: td }
  27586. });
  27587. }, function (selectorHandle) {
  27588. var sensorLeft = box.right() - snapOffset;
  27589. var sensorTop = box.bottom() - snapOffset;
  27590. var sensorWidth = snapWidth;
  27591. var sensorHeight = snapWidth;
  27592. var rect = selectorHandle.element().dom().getBoundingClientRect();
  27593. return Dragging.snap({
  27594. sensor: absolute$3(sensorLeft, sensorTop),
  27595. range: Position(sensorWidth, sensorHeight),
  27596. output: absolute$3(Option.some(box.right() - rect.width / 2), Option.some(box.bottom() - rect.height / 2)),
  27597. extra: { td: td }
  27598. });
  27599. });
  27600. };
  27601. var getBottomRightSnaps = function () {
  27602. return map(brTds.get(), function (td) {
  27603. return getBottomRightSnap(td);
  27604. });
  27605. };
  27606. var topLeftSnaps = {
  27607. getSnapPoints: getTopLeftSnaps,
  27608. leftAttr: 'data-drag-left',
  27609. topAttr: 'data-drag-top',
  27610. onSensor: function (component, extra) {
  27611. startCell.set(extra.td);
  27612. editor.fire('tableselectorchange', {
  27613. start: startCell.get(),
  27614. finish: finishCell.get()
  27615. });
  27616. },
  27617. mustSnap: true
  27618. };
  27619. var bottomRightSnaps = {
  27620. getSnapPoints: getBottomRightSnaps,
  27621. leftAttr: 'data-drag-left',
  27622. topAttr: 'data-drag-top',
  27623. onSensor: function (component, extra) {
  27624. finishCell.set(extra.td);
  27625. editor.fire('tableselectorchange', {
  27626. start: startCell.get(),
  27627. finish: finishCell.get()
  27628. });
  27629. },
  27630. mustSnap: true
  27631. };
  27632. var memTopLeft = record(Button.sketch({
  27633. dom: {
  27634. tag: 'div',
  27635. classes: ['tox-selector']
  27636. },
  27637. buttonBehaviours: derive$1([
  27638. Dragging.config(platform$2.deviceType.isTouch() ? {
  27639. mode: 'touch',
  27640. snaps: topLeftSnaps
  27641. } : {
  27642. mode: 'mouse',
  27643. blockerClass: 'blocker',
  27644. snaps: topLeftSnaps
  27645. }),
  27646. Unselecting.config({})
  27647. ]),
  27648. eventOrder: {
  27649. mousedown: [
  27650. 'dragging',
  27651. 'alloy.base.behaviour'
  27652. ]
  27653. }
  27654. }));
  27655. var memBottomRight = record(Button.sketch({
  27656. dom: {
  27657. tag: 'div',
  27658. classes: ['tox-selector']
  27659. },
  27660. buttonBehaviours: derive$1([
  27661. Dragging.config(platform$2.deviceType.isTouch() ? {
  27662. mode: 'touch',
  27663. snaps: bottomRightSnaps
  27664. } : {
  27665. mode: 'mouse',
  27666. blockerClass: 'blocker',
  27667. snaps: bottomRightSnaps
  27668. }),
  27669. Unselecting.config({})
  27670. ]),
  27671. eventOrder: {
  27672. mousedown: [
  27673. 'dragging',
  27674. 'alloy.base.behaviour'
  27675. ]
  27676. }
  27677. }));
  27678. var topLeft = build$1(memTopLeft.asSpec());
  27679. var bottomRight = build$1(memBottomRight.asSpec());
  27680. var isVisible = Cell(false);
  27681. var startCell = Cell(null);
  27682. var finishCell = Cell(null);
  27683. var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  27684. var cellRect = cell.dom().getBoundingClientRect();
  27685. remove$6(selector.element(), 'display');
  27686. var viewportHeight = defaultView(Element.fromDom(editor.getBody())).dom().innerHeight;
  27687. var aboveViewport = isAbove(cellRect);
  27688. var belowViewport = isBelow(cellRect, viewportHeight);
  27689. if (aboveViewport || belowViewport) {
  27690. set$2(selector.element(), 'display', 'none');
  27691. }
  27692. };
  27693. var snapLastTopLeft = function () {
  27694. var cell = startCell.get();
  27695. snapTopLeft(cell);
  27696. };
  27697. var snapTopLeft = function (cell) {
  27698. var snap = getTopLeftSnap(cell);
  27699. Dragging.snapTo(topLeft, snap);
  27700. var isAbove = function (rect) {
  27701. return rect.top < 0;
  27702. };
  27703. var isBelow = function (rect, viewportHeight) {
  27704. return rect.top > viewportHeight;
  27705. };
  27706. showOrHideHandle(topLeft, cell, isAbove, isBelow);
  27707. };
  27708. var snapLastBottomRight = function () {
  27709. var cell = finishCell.get();
  27710. snapBottomRight(cell);
  27711. };
  27712. var snapBottomRight = function (cell) {
  27713. var firstSnap = getBottomRightSnap(cell);
  27714. Dragging.snapTo(bottomRight, firstSnap);
  27715. var isAbove = function (rect) {
  27716. return rect.bottom < 0;
  27717. };
  27718. var isBelow = function (rect, viewportHeight) {
  27719. return rect.bottom > viewportHeight;
  27720. };
  27721. showOrHideHandle(bottomRight, cell, isAbove, isBelow);
  27722. };
  27723. if (platform$2.deviceType.isTouch()) {
  27724. editor.on('tableselectionchange', function (e) {
  27725. if (!isVisible.get()) {
  27726. attach$1(sink, topLeft);
  27727. attach$1(sink, bottomRight);
  27728. isVisible.set(true);
  27729. }
  27730. startCell.set(e.start);
  27731. finishCell.set(e.finish);
  27732. e.otherCells.each(function (otherCells) {
  27733. tlTds.set(otherCells.upOrLeftCells);
  27734. brTds.set(otherCells.downOrRightCells);
  27735. snapTopLeft(e.start);
  27736. snapBottomRight(e.finish);
  27737. });
  27738. });
  27739. editor.on('resize ScrollContent', function () {
  27740. snapLastTopLeft();
  27741. snapLastBottomRight();
  27742. });
  27743. editor.on('tableselectionclear', function () {
  27744. if (isVisible.get()) {
  27745. detach(topLeft);
  27746. detach(bottomRight);
  27747. isVisible.set(false);
  27748. }
  27749. });
  27750. }
  27751. };
  27752. var TableSelectorHandles = { setup: setup$a };
  27753. var SIGNIFICANT_MOVE$1 = 5;
  27754. var LONGPRESS_DELAY$1 = 400;
  27755. var getTouch$1 = function (event) {
  27756. if (event.touches === undefined || event.touches.length !== 1) {
  27757. return Option.none();
  27758. }
  27759. return Option.some(event.touches[0]);
  27760. };
  27761. var isFarEnough$1 = function (touch, data) {
  27762. var distX = Math.abs(touch.clientX - data.x());
  27763. var distY = Math.abs(touch.clientY - data.y());
  27764. return distX > SIGNIFICANT_MOVE$1 || distY > SIGNIFICANT_MOVE$1;
  27765. };
  27766. var setupLongpress = function (editor) {
  27767. var startData = Cell(Option.none());
  27768. var longpressFired = Cell(false);
  27769. var debounceLongpress = last$2(function (e) {
  27770. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  27771. longpressFired.set(true);
  27772. }, LONGPRESS_DELAY$1);
  27773. editor.on('touchstart', function (e) {
  27774. getTouch$1(e).each(function (touch) {
  27775. debounceLongpress.cancel();
  27776. var data = {
  27777. x: constant(touch.clientX),
  27778. y: constant(touch.clientY),
  27779. target: constant(e.target)
  27780. };
  27781. debounceLongpress.throttle(e);
  27782. longpressFired.set(false);
  27783. startData.set(Option.some(data));
  27784. });
  27785. }, true);
  27786. editor.on('touchmove', function (e) {
  27787. debounceLongpress.cancel();
  27788. getTouch$1(e).each(function (touch) {
  27789. startData.get().each(function (data) {
  27790. if (isFarEnough$1(touch, data)) {
  27791. startData.set(Option.none());
  27792. longpressFired.set(false);
  27793. editor.fire('longpresscancel');
  27794. }
  27795. });
  27796. });
  27797. }, true);
  27798. editor.on('touchend touchcancel', function (e) {
  27799. debounceLongpress.cancel();
  27800. if (e.type === 'touchend' && longpressFired.get()) {
  27801. startData.get().filter(function (data) {
  27802. return data.target().isEqualNode(e.target);
  27803. }).map(function () {
  27804. e.preventDefault();
  27805. });
  27806. }
  27807. }, true);
  27808. };
  27809. var TouchEvents = { setupLongpress: setupLongpress };
  27810. var setup$b = function (editor) {
  27811. var isInline = editor.inline;
  27812. var mode = isInline ? Inline : Iframe;
  27813. var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  27814. var lazyOuterContainer = Option.none();
  27815. var platform = detect$3();
  27816. var isIE = platform.browser.isIE();
  27817. var platformClasses = isIE ? ['tox-platform-ie'] : [];
  27818. var isTouch = platform.deviceType.isTouch();
  27819. var touchPlatformClass = 'tox-platform-touch';
  27820. var deviceClasses = isTouch ? [touchPlatformClass] : [];
  27821. var dirAttributes = global$5.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  27822. var lazyHeader = function () {
  27823. return lazyOuterContainer.bind(OuterContainer.getHeader);
  27824. };
  27825. var sink = build$1({
  27826. dom: __assign({
  27827. tag: 'div',
  27828. classes: [
  27829. 'tox',
  27830. 'tox-silver-sink',
  27831. 'tox-tinymce-aux'
  27832. ].concat(platformClasses).concat(deviceClasses)
  27833. }, dirAttributes),
  27834. behaviours: derive$1([Positioning.config({
  27835. useFixed: function () {
  27836. return header.isDocked(lazyHeader);
  27837. }
  27838. })])
  27839. });
  27840. var lazySink = function () {
  27841. return Result.value(sink);
  27842. };
  27843. var memAnchorBar = record({
  27844. dom: {
  27845. tag: 'div',
  27846. classes: ['tox-anchorbar']
  27847. }
  27848. });
  27849. var lazyAnchorBar = function () {
  27850. return lazyOuterContainer.bind(function (container) {
  27851. return memAnchorBar.getOpt(container);
  27852. }).getOrDie('Could not find a anchor bar element');
  27853. };
  27854. var lazyMoreButton = function () {
  27855. return lazyOuterContainer.bind(function (container) {
  27856. return OuterContainer.getMoreButton(container);
  27857. }).getOrDie('Could not find more button element');
  27858. };
  27859. var lazyToolbar = function () {
  27860. return lazyOuterContainer.bind(function (container) {
  27861. return OuterContainer.getToolbar(container);
  27862. }).getOrDie('Could not find more toolbar element');
  27863. };
  27864. var lazyThrobber = function () {
  27865. return lazyOuterContainer.bind(function (container) {
  27866. return OuterContainer.getThrobber(container);
  27867. }).getOrDie('Could not find throbber element');
  27868. };
  27869. var backstage = init$8(sink, editor, lazyAnchorBar, lazyMoreButton);
  27870. var partMenubar = OuterContainer.parts().menubar({
  27871. dom: {
  27872. tag: 'div',
  27873. classes: ['tox-menubar']
  27874. },
  27875. backstage: backstage,
  27876. onEscape: function () {
  27877. editor.focus();
  27878. }
  27879. });
  27880. var toolbarDrawer = function (editor) {
  27881. return getToolbarDrawer(editor);
  27882. };
  27883. var partToolbar = OuterContainer.parts().toolbar({
  27884. dom: {
  27885. tag: 'div',
  27886. classes: ['tox-toolbar']
  27887. },
  27888. getSink: lazySink,
  27889. backstage: backstage,
  27890. onEscape: function () {
  27891. editor.focus();
  27892. },
  27893. split: toolbarDrawer(editor),
  27894. lazyToolbar: lazyToolbar,
  27895. lazyMoreButton: lazyMoreButton,
  27896. lazyHeader: function () {
  27897. return lazyHeader().getOrDie('Could not find header element');
  27898. }
  27899. });
  27900. var partMultipleToolbar = OuterContainer.parts()['multiple-toolbar']({
  27901. dom: {
  27902. tag: 'div',
  27903. classes: ['tox-toolbar-overlord']
  27904. },
  27905. onEscape: function () {
  27906. }
  27907. });
  27908. var partSocket = OuterContainer.parts().socket({
  27909. dom: {
  27910. tag: 'div',
  27911. classes: ['tox-edit-area']
  27912. }
  27913. });
  27914. var partSidebar = OuterContainer.parts().sidebar({
  27915. dom: {
  27916. tag: 'div',
  27917. classes: ['tox-sidebar']
  27918. }
  27919. });
  27920. var partThrobber = OuterContainer.parts().throbber({
  27921. dom: {
  27922. tag: 'div',
  27923. classes: ['tox-throbber']
  27924. },
  27925. backstage: backstage
  27926. });
  27927. var sb = editor.getParam('statusbar', true, 'boolean');
  27928. var statusbar = sb && !isInline ? Option.some(renderStatusbar(editor, backstage.shared.providers)) : Option.none();
  27929. var socketSidebarContainer = {
  27930. dom: {
  27931. tag: 'div',
  27932. classes: ['tox-sidebar-wrap']
  27933. },
  27934. components: [
  27935. partSocket,
  27936. partSidebar
  27937. ]
  27938. };
  27939. var hasMultipleToolbar = isMultipleToolbars(editor);
  27940. var hasToolbar = isToolbarEnabled(editor);
  27941. var hasMenubar = isMenubarEnabled(editor);
  27942. var hasToolbarDrawer = toolbarDrawer(editor) !== ToolbarDrawer.default;
  27943. var getPartToolbar = function () {
  27944. if (hasMultipleToolbar) {
  27945. if (hasToolbarDrawer) {
  27946. domGlobals.console.warn('Toolbar drawer cannot be applied when multiple toolbars are active');
  27947. }
  27948. return [partMultipleToolbar];
  27949. } else if (hasToolbar) {
  27950. return [partToolbar];
  27951. } else {
  27952. return [];
  27953. }
  27954. };
  27955. var partHeader = OuterContainer.parts().header({
  27956. dom: {
  27957. tag: 'div',
  27958. classes: ['tox-editor-header']
  27959. },
  27960. components: flatten([
  27961. hasMenubar ? [partMenubar] : [],
  27962. getPartToolbar(),
  27963. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  27964. ]),
  27965. sticky: isStickyToolbar(editor),
  27966. editor: editor,
  27967. getSink: lazySink
  27968. });
  27969. var editorComponents = flatten([
  27970. [partHeader],
  27971. isInline ? [] : [socketSidebarContainer]
  27972. ]);
  27973. var editorContainer = {
  27974. dom: {
  27975. tag: 'div',
  27976. classes: ['tox-editor-container']
  27977. },
  27978. components: editorComponents
  27979. };
  27980. var containerComponents = flatten([
  27981. [editorContainer],
  27982. isInline ? [] : statusbar.toArray(),
  27983. [partThrobber]
  27984. ]);
  27985. var isHidden = isDistractionFree(editor);
  27986. var attributes = __assign(__assign({ role: 'application' }, global$5.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  27987. var outerContainer = build$1(OuterContainer.sketch({
  27988. dom: {
  27989. tag: 'div',
  27990. classes: [
  27991. 'tox',
  27992. 'tox-tinymce'
  27993. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(deviceClasses).concat(platformClasses),
  27994. styles: __assign({ visibility: 'hidden' }, isHidden ? {
  27995. opacity: '0',
  27996. border: '0'
  27997. } : {}),
  27998. attributes: attributes
  27999. },
  28000. components: containerComponents,
  28001. behaviours: derive$1([Keying.config({
  28002. mode: 'cyclic',
  28003. 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'
  28004. })])
  28005. }));
  28006. lazyOuterContainer = Option.some(outerContainer);
  28007. editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  28008. OuterContainer.focusMenubar(outerContainer);
  28009. });
  28010. editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  28011. OuterContainer.focusToolbar(outerContainer);
  28012. });
  28013. var mothership = takeover(outerContainer);
  28014. var uiMothership = takeover(sink);
  28015. Events$1.setup(editor, mothership, uiMothership);
  28016. TouchEvents.setupLongpress(editor);
  28017. var getUi = function () {
  28018. var channels = {
  28019. broadcastAll: uiMothership.broadcast,
  28020. broadcastOn: uiMothership.broadcastOn,
  28021. register: function () {
  28022. }
  28023. };
  28024. return { channels: channels };
  28025. };
  28026. var setEditorSize = function (elm) {
  28027. var DOM = global$7.DOM;
  28028. var baseWidth = editor.getParam('width', DOM.getStyle(elm, 'width'));
  28029. var baseHeight = getHeightSetting(editor);
  28030. var minWidth = getMinWidthSetting(editor);
  28031. var minHeight = getMinHeightSetting(editor);
  28032. var parsedWidth = Utils.parseToInt(baseWidth).bind(function (w) {
  28033. return Utils.numToPx(minWidth.map(function (mw) {
  28034. return Math.max(w, mw);
  28035. }));
  28036. }).getOr(Utils.numToPx(baseWidth));
  28037. var parsedHeight = Utils.parseToInt(baseHeight).bind(function (h) {
  28038. return minHeight.map(function (mh) {
  28039. return Math.max(h, mh);
  28040. });
  28041. }).getOr(baseHeight);
  28042. var stringWidth = Utils.numToPx(parsedWidth);
  28043. var widthProperty = editor.inline ? 'max-width' : 'width';
  28044. if (isValidValue('div', widthProperty, stringWidth)) {
  28045. set$2(outerContainer.element(), widthProperty, stringWidth);
  28046. }
  28047. if (!editor.inline) {
  28048. var stringHeight = Utils.numToPx(parsedHeight);
  28049. if (isValidValue('div', 'height', stringHeight)) {
  28050. set$2(outerContainer.element(), 'height', stringHeight);
  28051. } else {
  28052. set$2(outerContainer.element(), 'height', '200px');
  28053. }
  28054. }
  28055. return parsedHeight;
  28056. };
  28057. var renderUI = function () {
  28058. header.setup(editor, lazyHeader);
  28059. FormatControls.setup(editor, backstage);
  28060. setup$9(editor, lazySink, backstage);
  28061. setup$6(editor);
  28062. setup$7(editor, lazyThrobber, backstage.shared);
  28063. var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  28064. var toolbarOpt = getMultipleToolbarsSetting(editor);
  28065. var rawUiConfig = {
  28066. menuItems: menuItems,
  28067. menus: !editor.settings.menu ? {} : map$1(editor.settings.menu, function (menu) {
  28068. return merge(menu, { items: menu.items });
  28069. }),
  28070. menubar: editor.settings.menubar,
  28071. toolbar: toolbarOpt.getOrThunk(function () {
  28072. return editor.getParam('toolbar', true);
  28073. }),
  28074. buttons: buttons,
  28075. sidebar: sidebars
  28076. };
  28077. ContextToolbar.register(editor, contextToolbars, sink, { backstage: backstage });
  28078. TableSelectorHandles.setup(editor, sink);
  28079. var elm = editor.getElement();
  28080. var height = setEditorSize(elm);
  28081. var uiComponents = {
  28082. mothership: mothership,
  28083. uiMothership: uiMothership,
  28084. outerContainer: outerContainer
  28085. };
  28086. var args = {
  28087. targetNode: elm,
  28088. height: height
  28089. };
  28090. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  28091. };
  28092. return {
  28093. mothership: mothership,
  28094. uiMothership: uiMothership,
  28095. backstage: backstage,
  28096. renderUI: renderUI,
  28097. getUi: getUi
  28098. };
  28099. };
  28100. var Render = { setup: setup$b };
  28101. var describedBy = function (describedElement, describeElement) {
  28102. var describeId = Option.from(get$2(describedElement, 'id')).fold(function () {
  28103. var id = generate$1('dialog-describe');
  28104. set$1(describeElement, 'id', id);
  28105. return id;
  28106. }, identity);
  28107. set$1(describedElement, 'aria-describedby', describeId);
  28108. };
  28109. var AriaLabel = {
  28110. labelledBy: function (labelledElement, labelElement) {
  28111. var labelId = Option.from(get$2(labelledElement, 'id')).fold(function () {
  28112. var id = generate$1('dialog-label');
  28113. set$1(labelElement, 'id', id);
  28114. return id;
  28115. }, identity);
  28116. set$1(labelledElement, 'aria-labelledby', labelId);
  28117. }
  28118. };
  28119. var schema$u = constant([
  28120. strict$1('lazySink'),
  28121. option('dragBlockClass'),
  28122. defaultedFunction('getBounds', win),
  28123. defaulted$1('useTabstopAt', constant(true)),
  28124. defaulted$1('eventOrder', {}),
  28125. field$1('modalBehaviours', [Keying]),
  28126. onKeyboardHandler('onExecute'),
  28127. onStrictKeyboardHandler('onEscape')
  28128. ]);
  28129. var basic = { sketch: identity };
  28130. var parts$e = constant([
  28131. optional({
  28132. name: 'draghandle',
  28133. overrides: function (detail, spec) {
  28134. return {
  28135. behaviours: derive$1([Dragging.config({
  28136. mode: 'mouse',
  28137. getTarget: function (handle) {
  28138. return ancestor$1(handle, '[role="dialog"]').getOr(handle);
  28139. },
  28140. 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),
  28141. getBounds: detail.getDragBounds
  28142. })])
  28143. };
  28144. }
  28145. }),
  28146. required({
  28147. schema: [strict$1('dom')],
  28148. name: 'title'
  28149. }),
  28150. required({
  28151. factory: basic,
  28152. schema: [strict$1('dom')],
  28153. name: 'close'
  28154. }),
  28155. required({
  28156. factory: basic,
  28157. schema: [strict$1('dom')],
  28158. name: 'body'
  28159. }),
  28160. optional({
  28161. factory: basic,
  28162. schema: [strict$1('dom')],
  28163. name: 'footer'
  28164. }),
  28165. external$1({
  28166. factory: {
  28167. sketch: function (spec, detail) {
  28168. return __assign(__assign({}, spec), {
  28169. dom: detail.dom,
  28170. components: detail.components
  28171. });
  28172. }
  28173. },
  28174. schema: [
  28175. defaulted$1('dom', {
  28176. tag: 'div',
  28177. styles: {
  28178. position: 'fixed',
  28179. left: '0px',
  28180. top: '0px',
  28181. right: '0px',
  28182. bottom: '0px'
  28183. }
  28184. }),
  28185. defaulted$1('components', [])
  28186. ],
  28187. name: 'blocker'
  28188. })
  28189. ]);
  28190. var factory$h = function (detail, components, spec, externals) {
  28191. var dialogBusyEvent = generate$1('alloy.dialog.busy');
  28192. var dialogIdleEvent = generate$1('alloy.dialog.idle');
  28193. var busyBehaviours = derive$1([
  28194. Keying.config({
  28195. mode: 'special',
  28196. onTab: function () {
  28197. return Option.some(true);
  28198. },
  28199. onShiftTab: function () {
  28200. return Option.some(true);
  28201. }
  28202. }),
  28203. Focusing.config({})
  28204. ]);
  28205. var showDialog = function (dialog) {
  28206. var sink = detail.lazySink(dialog).getOrDie();
  28207. var busyComp = Cell(Option.none());
  28208. var externalBlocker = externals.blocker();
  28209. var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  28210. components: externalBlocker.components.concat([premade$1(dialog)]),
  28211. behaviours: derive$1([config('dialog-blocker-events', [
  28212. run(dialogIdleEvent, function (blocker, se) {
  28213. if (has$1(dialog.element(), 'aria-busy')) {
  28214. remove$1(dialog.element(), 'aria-busy');
  28215. busyComp.get().each(function (bc) {
  28216. return Replacing.remove(dialog, bc);
  28217. });
  28218. }
  28219. }),
  28220. run(dialogBusyEvent, function (blocker, se) {
  28221. set$1(dialog.element(), 'aria-busy', 'true');
  28222. var getBusySpec = se.event().getBusySpec();
  28223. busyComp.get().each(function (bc) {
  28224. Replacing.remove(dialog, bc);
  28225. });
  28226. var busySpec = getBusySpec(dialog, busyBehaviours);
  28227. var busy = blocker.getSystem().build(busySpec);
  28228. busyComp.set(Option.some(busy));
  28229. Replacing.append(dialog, premade$1(busy));
  28230. if (busy.hasConfigured(Keying)) {
  28231. Keying.focusIn(busy);
  28232. }
  28233. })
  28234. ])])
  28235. }));
  28236. attach$1(sink, blocker);
  28237. Keying.focusIn(dialog);
  28238. };
  28239. var hideDialog = function (dialog) {
  28240. parent(dialog.element()).each(function (blockerDom) {
  28241. dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  28242. detach(blocker);
  28243. });
  28244. });
  28245. };
  28246. var getDialogBody = function (dialog) {
  28247. return getPartOrDie(dialog, detail, 'body');
  28248. };
  28249. var getDialogFooter = function (dialog) {
  28250. return getPartOrDie(dialog, detail, 'footer');
  28251. };
  28252. var setBusy = function (dialog, getBusySpec) {
  28253. emitWith(dialog, dialogBusyEvent, { getBusySpec: getBusySpec });
  28254. };
  28255. var setIdle = function (dialog) {
  28256. emit(dialog, dialogIdleEvent);
  28257. };
  28258. var modalEventsId = generate$1('modal-events');
  28259. var eventOrder = __assign(__assign({}, detail.eventOrder), { 'alloy.system.attached': [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []) });
  28260. return {
  28261. uid: detail.uid,
  28262. dom: detail.dom,
  28263. components: components,
  28264. apis: {
  28265. show: showDialog,
  28266. hide: hideDialog,
  28267. getBody: getDialogBody,
  28268. getFooter: getDialogFooter,
  28269. setIdle: setIdle,
  28270. setBusy: setBusy
  28271. },
  28272. eventOrder: eventOrder,
  28273. domModification: {
  28274. attributes: {
  28275. 'role': 'dialog',
  28276. 'aria-modal': 'true'
  28277. }
  28278. },
  28279. behaviours: augment(detail.modalBehaviours, [
  28280. Replacing.config({}),
  28281. Keying.config({
  28282. mode: 'cyclic',
  28283. onEnter: detail.onExecute,
  28284. onEscape: detail.onEscape,
  28285. useTabstopAt: detail.useTabstopAt
  28286. }),
  28287. config(modalEventsId, [runOnAttached(function (c) {
  28288. AriaLabel.labelledBy(c.element(), getPartOrDie(c, detail, 'title').element());
  28289. describedBy(c.element(), getPartOrDie(c, detail, 'body').element());
  28290. })])
  28291. ])
  28292. };
  28293. };
  28294. var ModalDialog = composite$1({
  28295. name: 'ModalDialog',
  28296. configFields: schema$u(),
  28297. partFields: parts$e(),
  28298. factory: factory$h,
  28299. apis: {
  28300. show: function (apis, dialog) {
  28301. apis.show(dialog);
  28302. },
  28303. hide: function (apis, dialog) {
  28304. apis.hide(dialog);
  28305. },
  28306. getBody: function (apis, dialog) {
  28307. return apis.getBody(dialog);
  28308. },
  28309. getFooter: function (apis, dialog) {
  28310. return apis.getFooter(dialog);
  28311. },
  28312. setBusy: function (apis, dialog, getBusySpec) {
  28313. apis.setBusy(dialog, getBusySpec);
  28314. },
  28315. setIdle: function (apis, dialog) {
  28316. apis.setIdle(dialog);
  28317. }
  28318. }
  28319. });
  28320. var alertBannerFields = [
  28321. strictString('type'),
  28322. strictString('text'),
  28323. strictStringEnum('level', [
  28324. 'info',
  28325. 'warn',
  28326. 'error',
  28327. 'success'
  28328. ]),
  28329. strictString('icon'),
  28330. defaulted$1('url', '')
  28331. ];
  28332. var alertBannerSchema = objOf(alertBannerFields);
  28333. var createBarFields = function (itemsField) {
  28334. return [
  28335. strictString('type'),
  28336. itemsField
  28337. ];
  28338. };
  28339. var buttonFields = [
  28340. strictString('type'),
  28341. strictString('text'),
  28342. defaultedBoolean('disabled', false),
  28343. defaultedBoolean('primary', false),
  28344. field('name', 'name', defaultedThunk(function () {
  28345. return generate$1('button-name');
  28346. }), string),
  28347. optionString('icon'),
  28348. defaultedBoolean('borderless', false)
  28349. ];
  28350. var buttonSchema = objOf(buttonFields);
  28351. var checkboxFields = [
  28352. strictString('type'),
  28353. strictString('name'),
  28354. strictString('label'),
  28355. defaultedBoolean('disabled', false)
  28356. ];
  28357. var checkboxSchema = objOf(checkboxFields);
  28358. var checkboxDataProcessor = boolean;
  28359. var formComponentFields = [
  28360. strictString('type'),
  28361. strictString('name')
  28362. ];
  28363. var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  28364. var colorInputFields = formComponentWithLabelFields;
  28365. var colorInputSchema = objOf(colorInputFields);
  28366. var colorInputDataProcessor = string;
  28367. var colorPickerFields = formComponentWithLabelFields;
  28368. var colorPickerSchema = objOf(colorPickerFields);
  28369. var colorPickerDataProcessor = string;
  28370. var dropZoneFields = formComponentWithLabelFields;
  28371. var dropZoneSchema = objOf(dropZoneFields);
  28372. var dropZoneDataProcessor = arrOfVal();
  28373. var createGridFields = function (itemsField) {
  28374. return [
  28375. strictString('type'),
  28376. strictNumber('columns'),
  28377. itemsField
  28378. ];
  28379. };
  28380. var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  28381. var iframeSchema = objOf(iframeFields);
  28382. var iframeDataProcessor = string;
  28383. var inputFields = formComponentWithLabelFields.concat([
  28384. optionString('inputMode'),
  28385. optionString('placeholder'),
  28386. defaultedBoolean('maximized', false),
  28387. defaultedBoolean('disabled', false)
  28388. ]);
  28389. var inputSchema = objOf(inputFields);
  28390. var inputDataProcessor = string;
  28391. var selectBoxFields = formComponentWithLabelFields.concat([
  28392. strictArrayOfObj('items', [
  28393. strictString('text'),
  28394. strictString('value')
  28395. ]),
  28396. defaultedNumber('size', 1),
  28397. defaultedBoolean('disabled', false)
  28398. ]);
  28399. var selectBoxSchema = objOf(selectBoxFields);
  28400. var selectBoxDataProcessor = string;
  28401. var sizeInputFields = formComponentWithLabelFields.concat([
  28402. defaultedBoolean('constrain', true),
  28403. defaultedBoolean('disabled', false)
  28404. ]);
  28405. var sizeInputSchema = objOf(sizeInputFields);
  28406. var sizeInputDataProcessor = objOf([
  28407. strictString('width'),
  28408. strictString('height')
  28409. ]);
  28410. var textAreaFields = formComponentWithLabelFields.concat([
  28411. optionString('placeholder'),
  28412. defaultedBoolean('maximized', false),
  28413. defaultedBoolean('disabled', false)
  28414. ]);
  28415. var textAreaSchema = objOf(textAreaFields);
  28416. var textAreaDataProcessor = string;
  28417. var urlInputFields = formComponentWithLabelFields.concat([
  28418. defaultedStringEnum('filetype', 'file', [
  28419. 'image',
  28420. 'media',
  28421. 'file'
  28422. ]),
  28423. defaulted$1('disabled', false)
  28424. ]);
  28425. var urlInputSchema = objOf(urlInputFields);
  28426. var urlInputDataProcessor = objOf([
  28427. strictString('value'),
  28428. defaulted$1('meta', {})
  28429. ]);
  28430. var customEditorFields = formComponentFields.concat([
  28431. defaultedString('tag', 'textarea'),
  28432. strictString('scriptId'),
  28433. strictString('scriptUrl'),
  28434. defaultedPostMsg('settings', undefined)
  28435. ]);
  28436. var customEditorFieldsOld = formComponentFields.concat([
  28437. defaultedString('tag', 'textarea'),
  28438. strictFunction('init')
  28439. ]);
  28440. var customEditorSchema = valueOf(function (v) {
  28441. return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  28442. return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  28443. });
  28444. });
  28445. var customEditorDataProcessor = string;
  28446. var htmlPanelFields = [
  28447. strictString('type'),
  28448. strictString('html'),
  28449. defaultedStringEnum('presets', 'presentation', [
  28450. 'presentation',
  28451. 'document'
  28452. ])
  28453. ];
  28454. var htmlPanelSchema = objOf(htmlPanelFields);
  28455. var imageToolsFields = formComponentWithLabelFields.concat([strictOf('currentState', objOf([
  28456. strict$1('blob'),
  28457. strictString('url')
  28458. ]))]);
  28459. var imageToolsSchema = objOf(imageToolsFields);
  28460. var collectionFields = formComponentWithLabelFields.concat([defaulted$1('columns', 'auto')]);
  28461. var collectionSchema = objOf(collectionFields);
  28462. var collectionDataProcessor = arrOfObj$1([
  28463. strictString('value'),
  28464. strictString('text'),
  28465. strictString('icon')
  28466. ]);
  28467. var createLabelFields = function (itemsField) {
  28468. return [
  28469. strictString('type'),
  28470. strictString('label'),
  28471. itemsField
  28472. ];
  28473. };
  28474. var tableFields = [
  28475. strictString('type'),
  28476. strictArrayOf('header', string),
  28477. strictArrayOf('cells', arrOf(string))
  28478. ];
  28479. var tableSchema = objOf(tableFields);
  28480. var createItemsField = function (name) {
  28481. return field('items', 'items', strict(), arrOf(valueOf(function (v) {
  28482. return asRaw('Checking item of ' + name, itemSchema$2, v).fold(function (sErr) {
  28483. return Result.error(formatError(sErr));
  28484. }, function (passValue) {
  28485. return Result.value(passValue);
  28486. });
  28487. })));
  28488. };
  28489. var itemSchema$2 = valueThunkOf(function () {
  28490. return chooseProcessor('type', {
  28491. alertbanner: alertBannerSchema,
  28492. bar: objOf(createBarFields(createItemsField('bar'))),
  28493. button: buttonSchema,
  28494. checkbox: checkboxSchema,
  28495. colorinput: colorInputSchema,
  28496. colorpicker: colorPickerSchema,
  28497. dropzone: dropZoneSchema,
  28498. grid: objOf(createGridFields(createItemsField('grid'))),
  28499. iframe: iframeSchema,
  28500. input: inputSchema,
  28501. selectbox: selectBoxSchema,
  28502. sizeinput: sizeInputSchema,
  28503. textarea: textAreaSchema,
  28504. urlinput: urlInputSchema,
  28505. customeditor: customEditorSchema,
  28506. htmlpanel: htmlPanelSchema,
  28507. imagetools: imageToolsSchema,
  28508. collection: collectionSchema,
  28509. label: objOf(createLabelFields(createItemsField('label'))),
  28510. table: tableSchema,
  28511. panel: panelSchema
  28512. });
  28513. });
  28514. var panelFields = [
  28515. strictString('type'),
  28516. defaulted$1('classes', []),
  28517. strictArrayOf('items', itemSchema$2)
  28518. ];
  28519. var panelSchema = objOf(panelFields);
  28520. var tabFields = [
  28521. field('name', 'name', defaultedThunk(function () {
  28522. return generate$1('tab-name');
  28523. }), string),
  28524. strictString('title'),
  28525. strictArrayOf('items', itemSchema$2)
  28526. ];
  28527. var tabPanelFields = [
  28528. strictString('type'),
  28529. strictArrayOfObj('tabs', tabFields)
  28530. ];
  28531. var tabPanelSchema = objOf(tabPanelFields);
  28532. var dialogToggleMenuItemSchema = objOf([
  28533. strictString('type'),
  28534. strictString('name'),
  28535. defaultedBoolean('active', false)
  28536. ].concat(commonMenuItemFields));
  28537. var dialogToggleMenuItemDataProcessor = boolean;
  28538. var baseButtonFields = [
  28539. field('name', 'name', defaultedThunk(function () {
  28540. return generate$1('button-name');
  28541. }), string),
  28542. optionString('icon'),
  28543. defaultedStringEnum('align', 'end', [
  28544. 'start',
  28545. 'end'
  28546. ]),
  28547. defaultedBoolean('primary', false),
  28548. defaultedBoolean('disabled', false)
  28549. ];
  28550. var dialogButtonFields = __spreadArrays(baseButtonFields, [strictString('text')]);
  28551. var normalButtonFields = __spreadArrays([strictStringEnum('type', [
  28552. 'submit',
  28553. 'cancel',
  28554. 'custom'
  28555. ])], dialogButtonFields);
  28556. var menuButtonFields = __spreadArrays([
  28557. strictStringEnum('type', ['menu']),
  28558. optionString('text'),
  28559. optionString('tooltip'),
  28560. optionString('icon'),
  28561. strictArrayOf('items', dialogToggleMenuItemSchema),
  28562. defaultedFunction('onSetup', function () {
  28563. return noop;
  28564. })
  28565. ], baseButtonFields);
  28566. var dialogButtonSchema = choose$1('type', {
  28567. submit: normalButtonFields,
  28568. cancel: normalButtonFields,
  28569. custom: normalButtonFields,
  28570. menu: menuButtonFields
  28571. });
  28572. var dialogButtonFields$1 = dialogButtonFields;
  28573. var dialogButtonSchema$1 = dialogButtonSchema;
  28574. var dialogSchema = objOf([
  28575. strictString('title'),
  28576. strictOf('body', chooseProcessor('type', {
  28577. panel: panelSchema,
  28578. tabpanel: tabPanelSchema
  28579. })),
  28580. defaultedString('size', 'normal'),
  28581. strictArrayOf('buttons', dialogButtonSchema$1),
  28582. defaulted$1('initialData', {}),
  28583. defaultedFunction('onAction', noop),
  28584. defaultedFunction('onChange', noop),
  28585. defaultedFunction('onSubmit', noop),
  28586. defaultedFunction('onClose', noop),
  28587. defaultedFunction('onCancel', noop),
  28588. defaulted$1('onTabChange', noop)
  28589. ]);
  28590. var createDialog = function (spec) {
  28591. return asRaw('dialog', dialogSchema, spec);
  28592. };
  28593. var getAllObjects = function (obj) {
  28594. if (isObject(obj)) {
  28595. return [obj].concat(bind(values(obj), getAllObjects));
  28596. } else if (isArray(obj)) {
  28597. return bind(obj, getAllObjects);
  28598. } else {
  28599. return [];
  28600. }
  28601. };
  28602. var isNamedItem = function (obj) {
  28603. return isString(obj.type) && isString(obj.name);
  28604. };
  28605. var dataProcessors = {
  28606. checkbox: checkboxDataProcessor,
  28607. colorinput: colorInputDataProcessor,
  28608. colorpicker: colorPickerDataProcessor,
  28609. dropzone: dropZoneDataProcessor,
  28610. input: inputDataProcessor,
  28611. iframe: iframeDataProcessor,
  28612. sizeinput: sizeInputDataProcessor,
  28613. selectbox: selectBoxDataProcessor,
  28614. size: sizeInputDataProcessor,
  28615. textarea: textAreaDataProcessor,
  28616. urlinput: urlInputDataProcessor,
  28617. customeditor: customEditorDataProcessor,
  28618. collection: collectionDataProcessor,
  28619. togglemenuitem: dialogToggleMenuItemDataProcessor
  28620. };
  28621. var getDataProcessor = function (item) {
  28622. return Option.from(dataProcessors[item.type]);
  28623. };
  28624. var getNamedItems = function (structure) {
  28625. return filter(getAllObjects(structure), isNamedItem);
  28626. };
  28627. var createDataValidator = function (structure) {
  28628. var namedItems = getNamedItems(structure);
  28629. var fields = bind(namedItems, function (item) {
  28630. return getDataProcessor(item).fold(function () {
  28631. return [];
  28632. }, function (schema) {
  28633. return [strictOf(item.name, schema)];
  28634. });
  28635. });
  28636. return objOf(fields);
  28637. };
  28638. var urlDialogButtonSchema = objOf(__spreadArrays([strictStringEnum('type', [
  28639. 'cancel',
  28640. 'custom'
  28641. ])], dialogButtonFields$1));
  28642. var urlDialogSchema = objOf([
  28643. strictString('title'),
  28644. strictString('url'),
  28645. optionNumber('height'),
  28646. optionNumber('width'),
  28647. optionArrayOf('buttons', urlDialogButtonSchema),
  28648. defaultedFunction('onAction', noop),
  28649. defaultedFunction('onCancel', noop),
  28650. defaultedFunction('onClose', noop),
  28651. defaultedFunction('onMessage', noop)
  28652. ]);
  28653. var createUrlDialog = function (spec) {
  28654. return asRaw('dialog', urlDialogSchema, spec);
  28655. };
  28656. var extract$1 = function (structure) {
  28657. var internalDialog = getOrDie(createDialog(structure));
  28658. var dataValidator = createDataValidator(structure);
  28659. var initialData = structure.initialData;
  28660. return {
  28661. internalDialog: internalDialog,
  28662. dataValidator: dataValidator,
  28663. initialData: initialData
  28664. };
  28665. };
  28666. var DialogManager = {
  28667. open: function (factory, structure) {
  28668. var extraction = extract$1(structure);
  28669. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  28670. },
  28671. openUrl: function (factory, structure) {
  28672. var internalDialog = getOrDie(createUrlDialog(structure));
  28673. return factory(internalDialog);
  28674. },
  28675. redial: function (structure) {
  28676. return extract$1(structure);
  28677. }
  28678. };
  28679. var value$3 = function () {
  28680. var subject = Cell(Option.none());
  28681. var clear = function () {
  28682. subject.set(Option.none());
  28683. };
  28684. var set = function (s) {
  28685. subject.set(Option.some(s));
  28686. };
  28687. var on = function (f) {
  28688. subject.get().each(f);
  28689. };
  28690. var isSet = function () {
  28691. return subject.get().isSome();
  28692. };
  28693. return {
  28694. clear: clear,
  28695. set: set,
  28696. isSet: isSet,
  28697. on: on
  28698. };
  28699. };
  28700. var toValidValues = function (values) {
  28701. var errors = [];
  28702. var result = {};
  28703. each$1(values, function (value, name) {
  28704. value.fold(function () {
  28705. errors.push(name);
  28706. }, function (v) {
  28707. result[name] = v;
  28708. });
  28709. });
  28710. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  28711. };
  28712. var renderBodyPanel = function (spec, backstage) {
  28713. var memForm = record(Form.sketch(function (parts) {
  28714. return {
  28715. dom: {
  28716. tag: 'div',
  28717. classes: ['tox-form'].concat(spec.classes)
  28718. },
  28719. components: map(spec.items, function (item) {
  28720. return interpretInForm(parts, item, backstage);
  28721. })
  28722. };
  28723. }));
  28724. return {
  28725. dom: {
  28726. tag: 'div',
  28727. classes: ['tox-dialog__body']
  28728. },
  28729. components: [{
  28730. dom: {
  28731. tag: 'div',
  28732. classes: ['tox-dialog__body-content']
  28733. },
  28734. components: [memForm.asSpec()]
  28735. }],
  28736. behaviours: derive$1([
  28737. Keying.config({
  28738. mode: 'acyclic',
  28739. useTabstopAt: not(NavigableObject.isPseudoStop)
  28740. }),
  28741. ComposingConfigs.memento(memForm),
  28742. RepresentingConfigs.memento(memForm, {
  28743. postprocess: function (formValue) {
  28744. return toValidValues(formValue).fold(function (err) {
  28745. domGlobals.console.error(err);
  28746. return {};
  28747. }, function (vals) {
  28748. return vals;
  28749. });
  28750. }
  28751. })
  28752. ])
  28753. };
  28754. };
  28755. var factory$i = function (detail, spec) {
  28756. return {
  28757. uid: detail.uid,
  28758. dom: detail.dom,
  28759. components: detail.components,
  28760. events: events$7(detail.action),
  28761. behaviours: augment(detail.tabButtonBehaviours, [
  28762. Focusing.config({}),
  28763. Keying.config({
  28764. mode: 'execution',
  28765. useSpace: true,
  28766. useEnter: true
  28767. }),
  28768. Representing.config({
  28769. store: {
  28770. mode: 'memory',
  28771. initialValue: detail.value
  28772. }
  28773. })
  28774. ]),
  28775. domModification: detail.domModification
  28776. };
  28777. };
  28778. var TabButton = single$2({
  28779. name: 'TabButton',
  28780. configFields: [
  28781. defaulted$1('uid', undefined),
  28782. strict$1('value'),
  28783. field('dom', 'dom', mergeWithThunk(function (spec) {
  28784. return {
  28785. attributes: {
  28786. 'role': 'tab',
  28787. 'id': generate$1('aria'),
  28788. 'aria-selected': 'false'
  28789. }
  28790. };
  28791. }), anyValue$1()),
  28792. option('action'),
  28793. defaulted$1('domModification', {}),
  28794. field$1('tabButtonBehaviours', [
  28795. Focusing,
  28796. Keying,
  28797. Representing
  28798. ]),
  28799. strict$1('view')
  28800. ],
  28801. factory: factory$i
  28802. });
  28803. var schema$v = constant([
  28804. strict$1('tabs'),
  28805. strict$1('dom'),
  28806. defaulted$1('clickToDismiss', false),
  28807. field$1('tabbarBehaviours', [
  28808. Highlighting,
  28809. Keying
  28810. ]),
  28811. markers([
  28812. 'tabClass',
  28813. 'selectedClass'
  28814. ])
  28815. ]);
  28816. var tabsPart = group({
  28817. factory: TabButton,
  28818. name: 'tabs',
  28819. unit: 'tab',
  28820. overrides: function (barDetail, tabSpec) {
  28821. var dismissTab$1 = function (tabbar, button) {
  28822. Highlighting.dehighlight(tabbar, button);
  28823. emitWith(tabbar, dismissTab(), {
  28824. tabbar: tabbar,
  28825. button: button
  28826. });
  28827. };
  28828. var changeTab$1 = function (tabbar, button) {
  28829. Highlighting.highlight(tabbar, button);
  28830. emitWith(tabbar, changeTab(), {
  28831. tabbar: tabbar,
  28832. button: button
  28833. });
  28834. };
  28835. return {
  28836. action: function (button) {
  28837. var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  28838. var activeButton = Highlighting.isHighlighted(tabbar, button);
  28839. var response = function () {
  28840. if (activeButton && barDetail.clickToDismiss) {
  28841. return dismissTab$1;
  28842. } else if (!activeButton) {
  28843. return changeTab$1;
  28844. } else {
  28845. return noop;
  28846. }
  28847. }();
  28848. response(tabbar, button);
  28849. },
  28850. domModification: { classes: [barDetail.markers.tabClass] }
  28851. };
  28852. }
  28853. });
  28854. var parts$f = constant([tabsPart]);
  28855. var factory$j = function (detail, components, spec, externals) {
  28856. return {
  28857. 'uid': detail.uid,
  28858. 'dom': detail.dom,
  28859. 'components': components,
  28860. 'debug.sketcher': 'Tabbar',
  28861. 'domModification': { attributes: { role: 'tablist' } },
  28862. 'behaviours': augment(detail.tabbarBehaviours, [
  28863. Highlighting.config({
  28864. highlightClass: detail.markers.selectedClass,
  28865. itemClass: detail.markers.tabClass,
  28866. onHighlight: function (tabbar, tab) {
  28867. set$1(tab.element(), 'aria-selected', 'true');
  28868. },
  28869. onDehighlight: function (tabbar, tab) {
  28870. set$1(tab.element(), 'aria-selected', 'false');
  28871. }
  28872. }),
  28873. Keying.config({
  28874. mode: 'flow',
  28875. getInitial: function (tabbar) {
  28876. return Highlighting.getHighlighted(tabbar).map(function (tab) {
  28877. return tab.element();
  28878. });
  28879. },
  28880. selector: '.' + detail.markers.tabClass,
  28881. executeOnMove: true
  28882. })
  28883. ])
  28884. };
  28885. };
  28886. var Tabbar = composite$1({
  28887. name: 'Tabbar',
  28888. configFields: schema$v(),
  28889. partFields: parts$f(),
  28890. factory: factory$j
  28891. });
  28892. var factory$k = function (detail, spec) {
  28893. return {
  28894. uid: detail.uid,
  28895. dom: detail.dom,
  28896. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  28897. domModification: { attributes: { role: 'tabpanel' } }
  28898. };
  28899. };
  28900. var Tabview = single$2({
  28901. name: 'Tabview',
  28902. configFields: [field$1('tabviewBehaviours', [Replacing])],
  28903. factory: factory$k
  28904. });
  28905. var schema$w = constant([
  28906. defaulted$1('selectFirst', true),
  28907. onHandler('onChangeTab'),
  28908. onHandler('onDismissTab'),
  28909. defaulted$1('tabs', []),
  28910. field$1('tabSectionBehaviours', [])
  28911. ]);
  28912. var barPart = required({
  28913. factory: Tabbar,
  28914. schema: [
  28915. strict$1('dom'),
  28916. strictObjOf('markers', [
  28917. strict$1('tabClass'),
  28918. strict$1('selectedClass')
  28919. ])
  28920. ],
  28921. name: 'tabbar',
  28922. defaults: function (detail) {
  28923. return { tabs: detail.tabs };
  28924. }
  28925. });
  28926. var viewPart = required({
  28927. factory: Tabview,
  28928. name: 'tabview'
  28929. });
  28930. var parts$g = constant([
  28931. barPart,
  28932. viewPart
  28933. ]);
  28934. var factory$l = function (detail, components, spec, externals) {
  28935. var changeTab$1 = function (button) {
  28936. var tabValue = Representing.getValue(button);
  28937. getPart(button, detail, 'tabview').each(function (tabview) {
  28938. var tabWithValue = find(detail.tabs, function (t) {
  28939. return t.value === tabValue;
  28940. });
  28941. tabWithValue.each(function (tabData) {
  28942. var panel = tabData.view();
  28943. set$1(tabview.element(), 'aria-labelledby', get$2(button.element(), 'id'));
  28944. Replacing.set(tabview, panel);
  28945. detail.onChangeTab(tabview, button, panel);
  28946. });
  28947. });
  28948. };
  28949. var changeTabBy = function (section, byPred) {
  28950. getPart(section, detail, 'tabbar').each(function (tabbar) {
  28951. byPred(tabbar).each(emitExecute);
  28952. });
  28953. };
  28954. return {
  28955. uid: detail.uid,
  28956. dom: detail.dom,
  28957. components: components,
  28958. behaviours: get$b(detail.tabSectionBehaviours),
  28959. events: derive(flatten([
  28960. detail.selectFirst ? [runOnAttached(function (section, simulatedEvent) {
  28961. changeTabBy(section, Highlighting.getFirst);
  28962. })] : [],
  28963. [
  28964. run(changeTab(), function (section, simulatedEvent) {
  28965. var button = simulatedEvent.event().button();
  28966. changeTab$1(button);
  28967. }),
  28968. run(dismissTab(), function (section, simulatedEvent) {
  28969. var button = simulatedEvent.event().button();
  28970. detail.onDismissTab(section, button);
  28971. })
  28972. ]
  28973. ])),
  28974. apis: {
  28975. getViewItems: function (section) {
  28976. return getPart(section, detail, 'tabview').map(function (tabview) {
  28977. return Replacing.contents(tabview);
  28978. }).getOr([]);
  28979. },
  28980. showTab: function (section, tabKey) {
  28981. var getTabIfNotActive = function (tabbar) {
  28982. var candidates = Highlighting.getCandidates(tabbar);
  28983. var optTab = find(candidates, function (c) {
  28984. return Representing.getValue(c) === tabKey;
  28985. });
  28986. return optTab.filter(function (tab) {
  28987. return !Highlighting.isHighlighted(tabbar, tab);
  28988. });
  28989. };
  28990. changeTabBy(section, getTabIfNotActive);
  28991. }
  28992. }
  28993. };
  28994. };
  28995. var TabSection = composite$1({
  28996. name: 'TabSection',
  28997. configFields: schema$w(),
  28998. partFields: parts$g(),
  28999. factory: factory$l,
  29000. apis: {
  29001. getViewItems: function (apis, component) {
  29002. return apis.getViewItems(component);
  29003. },
  29004. showTab: function (apis, component, tabKey) {
  29005. apis.showTab(component, tabKey);
  29006. }
  29007. }
  29008. });
  29009. var measureHeights = function (allTabs, tabview, tabviewComp) {
  29010. return map(allTabs, function (tab, i) {
  29011. Replacing.set(tabviewComp, allTabs[i].view());
  29012. var rect = tabview.dom().getBoundingClientRect();
  29013. Replacing.set(tabviewComp, []);
  29014. return rect.height;
  29015. });
  29016. };
  29017. var getMaxHeight = function (heights) {
  29018. return head(sort(heights, function (a, b) {
  29019. if (a > b) {
  29020. return -1;
  29021. } else if (a < b) {
  29022. return +1;
  29023. } else {
  29024. return 0;
  29025. }
  29026. }));
  29027. };
  29028. var getMaxTabviewHeight = function (dialog, dialogBody) {
  29029. var rootElm = ancestor$1(dialog, '.tox-dialog-wrap').getOr(dialog);
  29030. var isFixed = get$4(rootElm, 'position') === 'fixed';
  29031. var maxHeight;
  29032. if (isFixed) {
  29033. maxHeight = Math.max(domGlobals.document.documentElement.clientHeight, domGlobals.window.innerHeight);
  29034. } else {
  29035. maxHeight = Math.max(domGlobals.document.documentElement.offsetHeight, domGlobals.document.documentElement.scrollHeight);
  29036. }
  29037. var dialogChrome = dialog.dom().getBoundingClientRect().height - dialogBody.dom().getBoundingClientRect().height;
  29038. return maxHeight - dialogChrome;
  29039. };
  29040. var showTab = function (allTabs, comp) {
  29041. head(allTabs).each(function (tab) {
  29042. return TabSection.showTab(comp, tab.value);
  29043. });
  29044. };
  29045. var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  29046. ancestor$1(dialogBody, '[role="dialog"]').each(function (dialog) {
  29047. maxTabHeight.get().map(function (height) {
  29048. set$2(tabview, 'height', '0');
  29049. return Math.min(height, getMaxTabviewHeight(dialog, dialogBody));
  29050. }).each(function (height) {
  29051. set$2(tabview, 'height', height + 'px');
  29052. });
  29053. });
  29054. };
  29055. var setMode = function (allTabs) {
  29056. var smartTabHeight = function () {
  29057. var maxTabHeight = Cell(Option.none());
  29058. var extraEvents = [
  29059. runOnAttached(function (comp) {
  29060. descendant$1(comp.element(), '[role="tabpanel"]').each(function (tabview) {
  29061. set$2(tabview, 'visibility', 'hidden');
  29062. comp.getSystem().getByDom(tabview).toOption().each(function (tabviewComp) {
  29063. var heights = measureHeights(allTabs, tabview, tabviewComp);
  29064. var maxTabHeightOpt = getMaxHeight(heights);
  29065. maxTabHeight.set(maxTabHeightOpt);
  29066. });
  29067. updateTabviewHeight(comp.element(), tabview, maxTabHeight);
  29068. remove$6(tabview, 'visibility');
  29069. showTab(allTabs, comp);
  29070. global$2.requestAnimationFrame(function () {
  29071. updateTabviewHeight(comp.element(), tabview, maxTabHeight);
  29072. });
  29073. });
  29074. }),
  29075. run(windowResize(), function (comp) {
  29076. descendant$1(comp.element(), '[role="tabpanel"]').each(function (tabview) {
  29077. updateTabviewHeight(comp.element(), tabview, maxTabHeight);
  29078. });
  29079. }),
  29080. run(formResizeEvent, function (comp, se) {
  29081. descendant$1(comp.element(), '[role="tabpanel"]').each(function (tabview) {
  29082. var oldFocus = active();
  29083. set$2(tabview, 'visibility', 'hidden');
  29084. var oldHeight = getRaw(tabview, 'height').map(function (h) {
  29085. return parseInt(h, 10);
  29086. });
  29087. remove$6(tabview, 'height');
  29088. var newHeight = tabview.dom().getBoundingClientRect().height;
  29089. var hasGrown = oldHeight.forall(function (h) {
  29090. return newHeight > h;
  29091. });
  29092. if (hasGrown) {
  29093. maxTabHeight.set(Option.from(newHeight));
  29094. updateTabviewHeight(comp.element(), tabview, maxTabHeight);
  29095. } else {
  29096. oldHeight.each(function (h) {
  29097. set$2(tabview, 'height', h + 'px');
  29098. });
  29099. }
  29100. remove$6(tabview, 'visibility');
  29101. oldFocus.each(focus$1);
  29102. });
  29103. })
  29104. ];
  29105. var selectFirst = false;
  29106. return {
  29107. extraEvents: extraEvents,
  29108. selectFirst: selectFirst
  29109. };
  29110. }();
  29111. var naiveTabHeight = function () {
  29112. var extraEvents = [];
  29113. var selectFirst = true;
  29114. return {
  29115. extraEvents: extraEvents,
  29116. selectFirst: selectFirst
  29117. };
  29118. }();
  29119. return {
  29120. smartTabHeight: smartTabHeight,
  29121. naiveTabHeight: naiveTabHeight
  29122. };
  29123. };
  29124. var SendDataToSectionChannel = 'send-data-to-section';
  29125. var SendDataToViewChannel = 'send-data-to-view';
  29126. var renderTabPanel = function (spec, backstage) {
  29127. var storedValue = Cell({});
  29128. var updateDataWithForm = function (form) {
  29129. var formData = Representing.getValue(form);
  29130. var validData = toValidValues(formData).getOr({});
  29131. var currentData = storedValue.get();
  29132. var newData = deepMerge(currentData, validData);
  29133. storedValue.set(newData);
  29134. };
  29135. var setDataOnForm = function (form) {
  29136. var tabData = storedValue.get();
  29137. Representing.setValue(form, tabData);
  29138. };
  29139. var oldTab = Cell(null);
  29140. var allTabs = map(spec.tabs, function (tab) {
  29141. return {
  29142. value: tab.name,
  29143. dom: {
  29144. tag: 'div',
  29145. classes: ['tox-dialog__body-nav-item'],
  29146. innerHtml: backstage.shared.providers.translate(tab.title)
  29147. },
  29148. view: function () {
  29149. return [Form.sketch(function (parts) {
  29150. return {
  29151. dom: {
  29152. tag: 'div',
  29153. classes: ['tox-form']
  29154. },
  29155. components: map(tab.items, function (item) {
  29156. return interpretInForm(parts, item, backstage);
  29157. }),
  29158. formBehaviours: derive$1([
  29159. Keying.config({
  29160. mode: 'acyclic',
  29161. useTabstopAt: not(NavigableObject.isPseudoStop)
  29162. }),
  29163. config('TabView.form.events', [
  29164. runOnAttached(setDataOnForm),
  29165. runOnDetached(updateDataWithForm)
  29166. ]),
  29167. Receiving.config({
  29168. channels: wrapAll$1([
  29169. {
  29170. key: SendDataToSectionChannel,
  29171. value: { onReceive: updateDataWithForm }
  29172. },
  29173. {
  29174. key: SendDataToViewChannel,
  29175. value: { onReceive: setDataOnForm }
  29176. }
  29177. ])
  29178. })
  29179. ])
  29180. };
  29181. })];
  29182. }
  29183. };
  29184. });
  29185. var tabMode = setMode(allTabs).smartTabHeight;
  29186. return TabSection.sketch({
  29187. dom: {
  29188. tag: 'div',
  29189. classes: ['tox-dialog__body']
  29190. },
  29191. onChangeTab: function (section, button, _viewItems) {
  29192. var name = Representing.getValue(button);
  29193. emitWith(section, formTabChangeEvent, {
  29194. name: name,
  29195. oldName: oldTab.get()
  29196. });
  29197. oldTab.set(name);
  29198. },
  29199. tabs: allTabs,
  29200. components: [
  29201. TabSection.parts().tabbar({
  29202. dom: {
  29203. tag: 'div',
  29204. classes: ['tox-dialog__body-nav']
  29205. },
  29206. components: [Tabbar.parts().tabs({})],
  29207. markers: {
  29208. tabClass: 'tox-tab',
  29209. selectedClass: 'tox-dialog__body-nav-item--active'
  29210. },
  29211. tabbarBehaviours: derive$1([Tabstopping.config({})])
  29212. }),
  29213. TabSection.parts().tabview({
  29214. dom: {
  29215. tag: 'div',
  29216. classes: ['tox-dialog__body-content']
  29217. }
  29218. })
  29219. ],
  29220. selectFirst: tabMode.selectFirst,
  29221. tabSectionBehaviours: derive$1([
  29222. config('tabpanel', tabMode.extraEvents),
  29223. Keying.config({ mode: 'acyclic' }),
  29224. Composing.config({
  29225. find: function (comp) {
  29226. return head(TabSection.getViewItems(comp));
  29227. }
  29228. }),
  29229. Representing.config({
  29230. store: {
  29231. mode: 'manual',
  29232. getValue: function (tsection) {
  29233. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  29234. return storedValue.get();
  29235. },
  29236. setValue: function (tsection, value) {
  29237. storedValue.set(value);
  29238. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  29239. }
  29240. }
  29241. })
  29242. ])
  29243. });
  29244. };
  29245. var dialogChannel = generate$1('update-dialog');
  29246. var titleChannel = generate$1('update-title');
  29247. var bodyChannel = generate$1('update-body');
  29248. var footerChannel = generate$1('update-footer');
  29249. var bodySendMessageChannel = generate$1('body-send-message');
  29250. var renderBody = function (spec, id, backstage, ariaAttrs) {
  29251. var renderComponents = function (incoming) {
  29252. switch (incoming.body.type) {
  29253. case 'tabpanel': {
  29254. return [renderTabPanel(incoming.body, backstage)];
  29255. }
  29256. default: {
  29257. return [renderBodyPanel(incoming.body, backstage)];
  29258. }
  29259. }
  29260. };
  29261. var updateState = function (_comp, incoming) {
  29262. return Option.some({
  29263. isTabPanel: function () {
  29264. return incoming.body.type === 'tabpanel';
  29265. }
  29266. });
  29267. };
  29268. var ariaAttributes = { 'aria-live': 'polite' };
  29269. return {
  29270. dom: {
  29271. tag: 'div',
  29272. classes: ['tox-dialog__content-js'],
  29273. attributes: __assign(__assign({}, id.map(function (x) {
  29274. return { id: x };
  29275. }).getOr({})), ariaAttrs ? ariaAttributes : {})
  29276. },
  29277. components: [],
  29278. behaviours: derive$1([
  29279. ComposingConfigs.childAt(0),
  29280. Reflecting.config({
  29281. channel: bodyChannel,
  29282. updateState: updateState,
  29283. renderComponents: renderComponents,
  29284. initialData: spec
  29285. })
  29286. ])
  29287. };
  29288. };
  29289. var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  29290. return renderBody(spec, Option.some(contentId), backstage, ariaAttrs);
  29291. };
  29292. var renderModalBody = function (spec, backstage) {
  29293. var bodySpec = renderBody(spec, Option.none(), backstage, false);
  29294. return ModalDialog.parts().body(bodySpec);
  29295. };
  29296. var renderIframeBody = function (spec) {
  29297. var bodySpec = {
  29298. dom: {
  29299. tag: 'div',
  29300. classes: ['tox-dialog__content-js']
  29301. },
  29302. components: [{
  29303. dom: {
  29304. tag: 'div',
  29305. classes: ['tox-dialog__body-iframe']
  29306. },
  29307. components: [NavigableObject.craft({
  29308. dom: {
  29309. tag: 'iframe',
  29310. attributes: { src: spec.url }
  29311. },
  29312. behaviours: derive$1([
  29313. Tabstopping.config({}),
  29314. Focusing.config({})
  29315. ])
  29316. })]
  29317. }],
  29318. behaviours: derive$1([Keying.config({
  29319. mode: 'acyclic',
  29320. useTabstopAt: not(NavigableObject.isPseudoStop)
  29321. })])
  29322. };
  29323. return ModalDialog.parts().body(bodySpec);
  29324. };
  29325. var initCommonEvents = function (fireApiEvent, extras) {
  29326. return [
  29327. runWithTarget(focusin(), NavigableObject.onFocus),
  29328. fireApiEvent(formCloseEvent, function (api, spec) {
  29329. extras.onClose();
  29330. spec.onClose();
  29331. }),
  29332. fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  29333. spec.onCancel(api);
  29334. emit(self, formCloseEvent);
  29335. }),
  29336. run(formUnblockEvent, function (c, se) {
  29337. return extras.onUnblock();
  29338. }),
  29339. run(formBlockEvent, function (c, se) {
  29340. return extras.onBlock(se.event());
  29341. })
  29342. ];
  29343. };
  29344. var initUrlDialog = function (getInstanceApi, extras) {
  29345. var fireApiEvent = function (eventName, f) {
  29346. return run(eventName, function (c, se) {
  29347. withSpec(c, function (spec, _c) {
  29348. f(getInstanceApi(), spec, se.event(), c);
  29349. });
  29350. });
  29351. };
  29352. var withSpec = function (c, f) {
  29353. Reflecting.getState(c).get().each(function (currentDialog) {
  29354. f(currentDialog, c);
  29355. });
  29356. };
  29357. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [fireApiEvent(formActionEvent, function (api, spec, event) {
  29358. spec.onAction(api, { name: event.name() });
  29359. })]);
  29360. };
  29361. var initDialog = function (getInstanceApi, extras) {
  29362. var fireApiEvent = function (eventName, f) {
  29363. return run(eventName, function (c, se) {
  29364. withSpec(c, function (spec, _c) {
  29365. f(getInstanceApi(), spec, se.event(), c);
  29366. });
  29367. });
  29368. };
  29369. var withSpec = function (c, f) {
  29370. Reflecting.getState(c).get().each(function (currentDialogInit) {
  29371. f(currentDialogInit.internalDialog, c);
  29372. });
  29373. };
  29374. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [
  29375. fireApiEvent(formSubmitEvent, function (api, spec) {
  29376. return spec.onSubmit(api);
  29377. }),
  29378. fireApiEvent(formChangeEvent, function (api, spec, event) {
  29379. spec.onChange(api, { name: event.name() });
  29380. }),
  29381. fireApiEvent(formActionEvent, function (api, spec, event, component) {
  29382. var focusIn = function () {
  29383. return Keying.focusIn(component);
  29384. };
  29385. var current = active();
  29386. spec.onAction(api, {
  29387. name: event.name(),
  29388. value: event.value()
  29389. });
  29390. active().fold(function () {
  29391. focusIn();
  29392. }, function (focused) {
  29393. if (!contains$2(component.element(), focused) || has$1(focused, 'disabled')) {
  29394. focusIn();
  29395. } else if (contains$2(focused, current.getOrNull()) && has$1(current.getOrDie(), 'disabled')) {
  29396. focusIn();
  29397. }
  29398. });
  29399. }),
  29400. fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  29401. spec.onTabChange(api, {
  29402. newTabName: event.name(),
  29403. oldTabName: event.oldName()
  29404. });
  29405. }),
  29406. runOnDetached(function (component) {
  29407. var api = getInstanceApi();
  29408. Representing.setValue(component, api.getData());
  29409. })
  29410. ]);
  29411. };
  29412. var SilverDialogEvents = {
  29413. initUrlDialog: initUrlDialog,
  29414. initDialog: initDialog
  29415. };
  29416. var makeButton = function (button, backstage) {
  29417. return renderFooterButton(button, button.type, backstage);
  29418. };
  29419. var lookup$2 = function (compInSystem, footerButtons, buttonName) {
  29420. return find(footerButtons, function (button) {
  29421. return button.name === buttonName;
  29422. }).bind(function (memButton) {
  29423. return memButton.memento.getOpt(compInSystem);
  29424. });
  29425. };
  29426. var renderComponents = function (_data, state) {
  29427. var footerButtons = state.map(function (s) {
  29428. return s.footerButtons;
  29429. }).getOr([]);
  29430. var buttonGroups = partition(footerButtons, function (button) {
  29431. return button.align === 'start';
  29432. });
  29433. var makeGroup = function (edge, buttons) {
  29434. return Container.sketch({
  29435. dom: {
  29436. tag: 'div',
  29437. classes: ['tox-dialog__footer-' + edge]
  29438. },
  29439. components: map(buttons, function (button) {
  29440. return button.memento.asSpec();
  29441. })
  29442. });
  29443. };
  29444. var startButtons = makeGroup('start', buttonGroups.pass);
  29445. var endButtons = makeGroup('end', buttonGroups.fail);
  29446. return [
  29447. startButtons,
  29448. endButtons
  29449. ];
  29450. };
  29451. var renderFooter = function (initSpec, backstage) {
  29452. var updateState = function (_comp, data) {
  29453. var footerButtons = map(data.buttons, function (button) {
  29454. var memButton = record(makeButton(button, backstage));
  29455. return {
  29456. name: button.name,
  29457. align: button.align,
  29458. memento: memButton
  29459. };
  29460. });
  29461. var lookupByName = function (compInSystem, buttonName) {
  29462. return lookup$2(compInSystem, footerButtons, buttonName);
  29463. };
  29464. return Option.some({
  29465. lookupByName: lookupByName,
  29466. footerButtons: footerButtons
  29467. });
  29468. };
  29469. return {
  29470. dom: fromHtml$2('<div class="tox-dialog__footer"></div>'),
  29471. components: [],
  29472. behaviours: derive$1([Reflecting.config({
  29473. channel: footerChannel,
  29474. initialData: initSpec,
  29475. updateState: updateState,
  29476. renderComponents: renderComponents
  29477. })])
  29478. };
  29479. };
  29480. var renderInlineFooter = function (initSpec, backstage) {
  29481. return renderFooter(initSpec, backstage);
  29482. };
  29483. var renderModalFooter = function (initSpec, backstage) {
  29484. return ModalDialog.parts().footer(renderFooter(initSpec, backstage));
  29485. };
  29486. var getCompByName = function (access, name) {
  29487. var root = access.getRoot();
  29488. if (root.getSystem().isConnected()) {
  29489. var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  29490. return Form.getField(form_1, name).fold(function () {
  29491. var footer = access.getFooter();
  29492. var footerState = Reflecting.getState(footer);
  29493. return footerState.get().bind(function (f) {
  29494. return f.lookupByName(form_1, name);
  29495. });
  29496. }, function (comp) {
  29497. return Option.some(comp);
  29498. });
  29499. } else {
  29500. return Option.none();
  29501. }
  29502. };
  29503. var validateData = function (access, data) {
  29504. var root = access.getRoot();
  29505. return Reflecting.getState(root).get().map(function (dialogState) {
  29506. return getOrDie(asRaw('data', dialogState.dataValidator, data));
  29507. }).getOr(data);
  29508. };
  29509. var getDialogApi = function (access, doRedial, menuItemStates) {
  29510. var withRoot = function (f) {
  29511. var root = access.getRoot();
  29512. if (root.getSystem().isConnected()) {
  29513. f(root);
  29514. }
  29515. };
  29516. var getData = function () {
  29517. var root = access.getRoot();
  29518. var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  29519. var representedValues = Representing.getValue(valueComp);
  29520. var menuItemCurrentState = map$1(menuItemStates, function (cell) {
  29521. return cell.get();
  29522. });
  29523. return __assign(__assign({}, representedValues), menuItemCurrentState);
  29524. };
  29525. var setData = function (newData) {
  29526. withRoot(function (_) {
  29527. var prevData = instanceApi.getData();
  29528. var mergedData = merge(prevData, newData);
  29529. var newInternalData = validateData(access, mergedData);
  29530. var form = access.getFormWrapper();
  29531. Representing.setValue(form, newInternalData);
  29532. each$1(menuItemStates, function (v, k) {
  29533. if (has(mergedData, k)) {
  29534. v.set(mergedData[k]);
  29535. }
  29536. });
  29537. });
  29538. };
  29539. var disable = function (name) {
  29540. getCompByName(access, name).each(Disabling.disable);
  29541. };
  29542. var enable = function (name) {
  29543. getCompByName(access, name).each(Disabling.enable);
  29544. };
  29545. var focus = function (name) {
  29546. getCompByName(access, name).each(Focusing.focus);
  29547. };
  29548. var block = function (message) {
  29549. if (!isString(message)) {
  29550. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  29551. }
  29552. withRoot(function (root) {
  29553. emitWith(root, formBlockEvent, { message: message });
  29554. });
  29555. };
  29556. var unblock = function () {
  29557. withRoot(function (root) {
  29558. emit(root, formUnblockEvent);
  29559. });
  29560. };
  29561. var showTab = function (name) {
  29562. withRoot(function (_) {
  29563. var body = access.getBody();
  29564. var bodyState = Reflecting.getState(body);
  29565. if (bodyState.get().exists(function (b) {
  29566. return b.isTabPanel();
  29567. })) {
  29568. Composing.getCurrent(body).each(function (tabSection) {
  29569. TabSection.showTab(tabSection, name);
  29570. });
  29571. }
  29572. });
  29573. };
  29574. var redial = function (d) {
  29575. withRoot(function (root) {
  29576. var dialogInit = doRedial(d);
  29577. root.getSystem().broadcastOn([dialogChannel], dialogInit);
  29578. root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  29579. root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  29580. root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  29581. instanceApi.setData(dialogInit.initialData);
  29582. });
  29583. };
  29584. var close = function () {
  29585. withRoot(function (root) {
  29586. emit(root, formCloseEvent);
  29587. });
  29588. };
  29589. var instanceApi = {
  29590. getData: getData,
  29591. setData: setData,
  29592. disable: disable,
  29593. enable: enable,
  29594. focus: focus,
  29595. block: block,
  29596. unblock: unblock,
  29597. showTab: showTab,
  29598. redial: redial,
  29599. close: close
  29600. };
  29601. return instanceApi;
  29602. };
  29603. var renderClose = function (providersBackstage) {
  29604. return Button.sketch({
  29605. dom: {
  29606. tag: 'button',
  29607. classes: [
  29608. 'tox-button',
  29609. 'tox-button--icon',
  29610. 'tox-button--naked'
  29611. ],
  29612. attributes: {
  29613. 'type': 'button',
  29614. 'aria-label': providersBackstage.translate('Close'),
  29615. 'title': providersBackstage.translate('Close')
  29616. }
  29617. },
  29618. components: [{
  29619. dom: {
  29620. tag: 'div',
  29621. classes: ['tox-icon'],
  29622. 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>'
  29623. }
  29624. }],
  29625. action: function (comp) {
  29626. emit(comp, formCancelEvent);
  29627. }
  29628. });
  29629. };
  29630. var renderTitle = function (spec, id, providersBackstage) {
  29631. var renderComponents = function (data) {
  29632. return [text(providersBackstage.translate(data.title))];
  29633. };
  29634. return {
  29635. dom: {
  29636. tag: 'div',
  29637. classes: ['tox-dialog__title'],
  29638. attributes: __assign({}, id.map(function (x) {
  29639. return { id: x };
  29640. }).getOr({}))
  29641. },
  29642. components: renderComponents(spec),
  29643. behaviours: derive$1([Reflecting.config({
  29644. channel: titleChannel,
  29645. renderComponents: renderComponents
  29646. })])
  29647. };
  29648. };
  29649. var renderDragHandle = function () {
  29650. return { dom: fromHtml$2('<div class="tox-dialog__draghandle"></div>') };
  29651. };
  29652. var renderInlineHeader = function (spec, titleId, providersBackstage) {
  29653. return Container.sketch({
  29654. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  29655. components: [
  29656. renderTitle(spec, Option.some(titleId), providersBackstage),
  29657. renderDragHandle(),
  29658. renderClose(providersBackstage)
  29659. ],
  29660. containerBehaviours: derive$1([Dragging.config({
  29661. mode: 'mouse',
  29662. blockerClass: 'blocker',
  29663. getTarget: function (handle) {
  29664. return closest$3(handle, '[role="dialog"]').getOrDie();
  29665. },
  29666. snaps: {
  29667. getSnapPoints: function () {
  29668. return [];
  29669. },
  29670. leftAttr: 'data-drag-left',
  29671. topAttr: 'data-drag-top'
  29672. }
  29673. })])
  29674. });
  29675. };
  29676. var renderModalHeader = function (spec, providersBackstage) {
  29677. var pTitle = ModalDialog.parts().title(renderTitle(spec, Option.none(), providersBackstage));
  29678. var pHandle = ModalDialog.parts().draghandle(renderDragHandle());
  29679. var pClose = ModalDialog.parts().close(renderClose(providersBackstage));
  29680. var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  29681. return Container.sketch({
  29682. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  29683. components: components
  29684. });
  29685. };
  29686. var isTouch$4 = global$6.deviceType.isTouch();
  29687. var getHeader = function (title, backstage) {
  29688. return renderModalHeader({
  29689. title: backstage.shared.providers.translate(title),
  29690. draggable: backstage.dialog.isDraggableModal()
  29691. }, backstage.shared.providers);
  29692. };
  29693. var getEventExtras = function (lazyDialog, extra) {
  29694. return {
  29695. onClose: function () {
  29696. return extra.closeWindow();
  29697. },
  29698. onBlock: function (blockEvent) {
  29699. ModalDialog.setBusy(lazyDialog(), function (d, bs) {
  29700. return {
  29701. dom: {
  29702. tag: 'div',
  29703. classes: ['tox-dialog__busy-spinner'],
  29704. attributes: { 'aria-label': blockEvent.message() },
  29705. styles: {
  29706. left: '0px',
  29707. right: '0px',
  29708. bottom: '0px',
  29709. top: '0px',
  29710. position: 'absolute'
  29711. }
  29712. },
  29713. behaviours: bs,
  29714. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  29715. };
  29716. });
  29717. },
  29718. onUnblock: function () {
  29719. ModalDialog.setIdle(lazyDialog());
  29720. }
  29721. };
  29722. };
  29723. var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  29724. var _a;
  29725. var updateState = function (_comp, incoming) {
  29726. return Option.some(incoming);
  29727. };
  29728. return build$1(ModalDialog.sketch({
  29729. lazySink: backstage.shared.getSink,
  29730. onEscape: function (c) {
  29731. emit(c, formCancelEvent);
  29732. return Option.some(true);
  29733. },
  29734. useTabstopAt: function (elem) {
  29735. return !NavigableObject.isPseudoStop(elem);
  29736. },
  29737. modalBehaviours: derive$1(__spreadArrays([
  29738. Reflecting.config({
  29739. channel: dialogChannel,
  29740. updateState: updateState,
  29741. initialData: initialData
  29742. }),
  29743. RepresentingConfigs.memory({}),
  29744. Focusing.config({}),
  29745. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, se) {
  29746. Keying.focusIn(comp);
  29747. })])),
  29748. config('scroll-lock', [
  29749. runOnAttached(function () {
  29750. add$2(body(), 'tox-dialog__disable-scroll');
  29751. }),
  29752. runOnDetached(function () {
  29753. remove$4(body(), 'tox-dialog__disable-scroll');
  29754. })
  29755. ])
  29756. ], spec.extraBehaviours)),
  29757. eventOrder: (_a = {}, _a[execute()] = ['execute-on-form'], _a[receive()] = [
  29758. 'reflecting',
  29759. 'receiving'
  29760. ], _a[attachedToDom()] = [
  29761. 'scroll-lock',
  29762. 'reflecting',
  29763. 'messages',
  29764. 'execute-on-form',
  29765. 'alloy.base.behaviour'
  29766. ], _a[detachedFromDom()] = [
  29767. 'alloy.base.behaviour',
  29768. 'execute-on-form',
  29769. 'messages',
  29770. 'reflecting',
  29771. 'scroll-lock'
  29772. ], _a),
  29773. dom: {
  29774. tag: 'div',
  29775. classes: ['tox-dialog'].concat(spec.extraClasses),
  29776. styles: __assign({ position: 'relative' }, spec.extraStyles)
  29777. },
  29778. components: __spreadArrays([
  29779. spec.header,
  29780. spec.body
  29781. ], spec.footer.toArray()),
  29782. dragBlockClass: 'tox-dialog-wrap',
  29783. parts: {
  29784. blocker: {
  29785. dom: fromHtml$2('<div class="tox-dialog-wrap"></div>'),
  29786. components: [{
  29787. dom: {
  29788. tag: 'div',
  29789. classes: isTouch$4 ? [
  29790. 'tox-dialog-wrap__backdrop',
  29791. 'tox-dialog-wrap__backdrop--opaque'
  29792. ] : ['tox-dialog-wrap__backdrop']
  29793. }
  29794. }]
  29795. }
  29796. }
  29797. }));
  29798. };
  29799. var mapMenuButtons = function (buttons) {
  29800. var mapItems = function (button) {
  29801. var items = map(button.items, function (item) {
  29802. var cell = Cell(false);
  29803. return __assign(__assign({}, item), { storage: cell });
  29804. });
  29805. return __assign(__assign({}, button), { items: items });
  29806. };
  29807. return map(buttons, function (button) {
  29808. if (button.type === 'menu') {
  29809. return mapItems(button);
  29810. }
  29811. return button;
  29812. });
  29813. };
  29814. var extractCellsToObject = function (buttons) {
  29815. return foldl(buttons, function (acc, button) {
  29816. if (button.type === 'menu') {
  29817. var menuButton = button;
  29818. return foldl(menuButton.items, function (innerAcc, item) {
  29819. innerAcc[item.name] = item.storage;
  29820. return innerAcc;
  29821. }, acc);
  29822. }
  29823. return acc;
  29824. }, {});
  29825. };
  29826. var renderDialog = function (dialogInit, extra, backstage) {
  29827. var header = getHeader(dialogInit.internalDialog.title, backstage);
  29828. var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  29829. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  29830. var objOfCells = extractCellsToObject(storagedMenuButtons);
  29831. var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  29832. var dialogEvents = SilverDialogEvents.initDialog(function () {
  29833. return instanceApi;
  29834. }, getEventExtras(function () {
  29835. return dialog;
  29836. }, extra));
  29837. var dialogSize = dialogInit.internalDialog.size !== 'normal' ? dialogInit.internalDialog.size === 'large' ? ['tox-dialog--width-lg'] : ['tox-dialog--width-md'] : [];
  29838. var spec = {
  29839. header: header,
  29840. body: body,
  29841. footer: Option.some(footer),
  29842. extraClasses: dialogSize,
  29843. extraBehaviours: [],
  29844. extraStyles: {}
  29845. };
  29846. var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  29847. var modalAccess = function () {
  29848. var getForm = function () {
  29849. var outerForm = ModalDialog.getBody(dialog);
  29850. return Composing.getCurrent(outerForm).getOr(outerForm);
  29851. };
  29852. return {
  29853. getRoot: function () {
  29854. return dialog;
  29855. },
  29856. getBody: function () {
  29857. return ModalDialog.getBody(dialog);
  29858. },
  29859. getFooter: function () {
  29860. return ModalDialog.getFooter(dialog);
  29861. },
  29862. getFormWrapper: getForm
  29863. };
  29864. }();
  29865. var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  29866. return {
  29867. dialog: dialog,
  29868. instanceApi: instanceApi
  29869. };
  29870. };
  29871. var global$g = tinymce.util.Tools.resolve('tinymce.util.URI');
  29872. var getUrlDialogApi = function (root) {
  29873. var withRoot = function (f) {
  29874. if (root.getSystem().isConnected()) {
  29875. f(root);
  29876. }
  29877. };
  29878. var block = function (message) {
  29879. if (!isString(message)) {
  29880. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  29881. }
  29882. withRoot(function (root) {
  29883. emitWith(root, formBlockEvent, { message: message });
  29884. });
  29885. };
  29886. var unblock = function () {
  29887. withRoot(function (root) {
  29888. emit(root, formUnblockEvent);
  29889. });
  29890. };
  29891. var close = function () {
  29892. withRoot(function (root) {
  29893. emit(root, formCloseEvent);
  29894. });
  29895. };
  29896. var sendMessage = function (data) {
  29897. withRoot(function (root) {
  29898. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  29899. });
  29900. };
  29901. return {
  29902. block: block,
  29903. unblock: unblock,
  29904. close: close,
  29905. sendMessage: sendMessage
  29906. };
  29907. };
  29908. var SUPPORTED_MESSAGE_ACTIONS = [
  29909. 'insertContent',
  29910. 'setContent',
  29911. 'execCommand',
  29912. 'close',
  29913. 'block',
  29914. 'unblock'
  29915. ];
  29916. var isSupportedMessage = function (data) {
  29917. return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  29918. };
  29919. var isCustomMessage = function (data) {
  29920. return !isSupportedMessage(data) && isObject(data) && has(data, 'mceAction');
  29921. };
  29922. var handleMessage = function (editor, api, data) {
  29923. switch (data.mceAction) {
  29924. case 'insertContent':
  29925. editor.insertContent(data.content);
  29926. break;
  29927. case 'setContent':
  29928. editor.setContent(data.content);
  29929. break;
  29930. case 'execCommand':
  29931. var ui = isBoolean(data.ui) ? data.ui : false;
  29932. editor.execCommand(data.cmd, ui, data.value);
  29933. break;
  29934. case 'close':
  29935. api.close();
  29936. break;
  29937. case 'block':
  29938. api.block(data.message);
  29939. break;
  29940. case 'unblock':
  29941. api.unblock();
  29942. break;
  29943. }
  29944. };
  29945. var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  29946. var _a;
  29947. var header = getHeader(internalDialog.title, backstage);
  29948. var body = renderIframeBody(internalDialog);
  29949. var footer = internalDialog.buttons.bind(function (buttons) {
  29950. if (buttons.length === 0) {
  29951. return Option.none();
  29952. } else {
  29953. return Option.some(renderModalFooter({ buttons: buttons }, backstage));
  29954. }
  29955. });
  29956. var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  29957. return instanceApi;
  29958. }, getEventExtras(function () {
  29959. return dialog;
  29960. }, extra));
  29961. var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  29962. return {};
  29963. }, function (height) {
  29964. return {
  29965. 'height': height + 'px',
  29966. 'max-height': height + 'px'
  29967. };
  29968. })), internalDialog.width.fold(function () {
  29969. return {};
  29970. }, function (width) {
  29971. return {
  29972. 'width': width + 'px',
  29973. 'max-width': width + 'px'
  29974. };
  29975. }));
  29976. var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  29977. var iframeUri = new global$g(internalDialog.url, { base_uri: new global$g(domGlobals.window.location.href) });
  29978. var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  29979. var messageHandlerUnbinder = Cell(Option.none());
  29980. var extraBehaviours = [
  29981. config('messages', [
  29982. runOnAttached(function () {
  29983. var unbind = bind$3(Element.fromDom(domGlobals.window), 'message', function (e) {
  29984. if (iframeUri.isSameOrigin(new global$g(e.raw().origin))) {
  29985. var data = e.raw().data;
  29986. if (isSupportedMessage(data)) {
  29987. handleMessage(editor, instanceApi, data);
  29988. } else if (isCustomMessage(data)) {
  29989. internalDialog.onMessage(instanceApi, data);
  29990. }
  29991. }
  29992. });
  29993. messageHandlerUnbinder.set(Option.some(unbind));
  29994. }),
  29995. runOnDetached(function () {
  29996. messageHandlerUnbinder.get().each(function (unbinder) {
  29997. return unbinder.unbind();
  29998. });
  29999. })
  30000. ]),
  30001. Receiving.config({
  30002. channels: (_a = {}, _a[bodySendMessageChannel] = {
  30003. onReceive: function (comp, data) {
  30004. descendant$1(comp.element(), 'iframe').each(function (iframeEle) {
  30005. var iframeWin = iframeEle.dom().contentWindow;
  30006. iframeWin.postMessage(data, iframeDomain);
  30007. });
  30008. }
  30009. }, _a)
  30010. })
  30011. ];
  30012. var spec = {
  30013. header: header,
  30014. body: body,
  30015. footer: footer,
  30016. extraClasses: classes,
  30017. extraBehaviours: extraBehaviours,
  30018. extraStyles: styles
  30019. };
  30020. var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  30021. var instanceApi = getUrlDialogApi(dialog);
  30022. return {
  30023. dialog: dialog,
  30024. instanceApi: instanceApi
  30025. };
  30026. };
  30027. var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  30028. var _a, _b;
  30029. var dialogLabelId = generate$1('dialog-label');
  30030. var dialogContentId = generate$1('dialog-content');
  30031. var updateState = function (_comp, incoming) {
  30032. return Option.some(incoming);
  30033. };
  30034. var memHeader = record(renderInlineHeader({
  30035. title: dialogInit.internalDialog.title,
  30036. draggable: true
  30037. }, dialogLabelId, backstage.shared.providers));
  30038. var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  30039. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  30040. var objOfCells = extractCellsToObject(storagedMenuButtons);
  30041. var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  30042. var dialogEvents = SilverDialogEvents.initDialog(function () {
  30043. return instanceApi;
  30044. }, {
  30045. onBlock: function () {
  30046. },
  30047. onUnblock: function () {
  30048. },
  30049. onClose: function () {
  30050. return extra.closeWindow();
  30051. }
  30052. });
  30053. var dialog = build$1({
  30054. dom: {
  30055. tag: 'div',
  30056. classes: [
  30057. 'tox-dialog',
  30058. 'tox-dialog-inline'
  30059. ],
  30060. attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = '' + dialogContentId, _a)
  30061. },
  30062. eventOrder: (_b = {}, _b[receive()] = [
  30063. Reflecting.name(),
  30064. Receiving.name()
  30065. ], _b[execute()] = ['execute-on-form'], _b[attachedToDom()] = [
  30066. 'reflecting',
  30067. 'execute-on-form'
  30068. ], _b),
  30069. behaviours: derive$1([
  30070. Keying.config({
  30071. mode: 'cyclic',
  30072. onEscape: function (c) {
  30073. emit(c, formCloseEvent);
  30074. return Option.some(true);
  30075. },
  30076. useTabstopAt: function (elem) {
  30077. return !NavigableObject.isPseudoStop(elem) && (name(elem) !== 'button' || get$2(elem, 'disabled') !== 'disabled');
  30078. }
  30079. }),
  30080. Reflecting.config({
  30081. channel: dialogChannel,
  30082. updateState: updateState,
  30083. initialData: dialogInit
  30084. }),
  30085. Focusing.config({}),
  30086. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, se) {
  30087. Keying.focusIn(comp);
  30088. })])),
  30089. RepresentingConfigs.memory({})
  30090. ]),
  30091. components: [
  30092. memHeader.asSpec(),
  30093. memBody.asSpec(),
  30094. memFooter.asSpec()
  30095. ]
  30096. });
  30097. var instanceApi = getDialogApi({
  30098. getRoot: function () {
  30099. return dialog;
  30100. },
  30101. getFooter: function () {
  30102. return memFooter.get(dialog);
  30103. },
  30104. getBody: function () {
  30105. return memBody.get(dialog);
  30106. },
  30107. getFormWrapper: function () {
  30108. var body = memBody.get(dialog);
  30109. return Composing.getCurrent(body).getOr(body);
  30110. }
  30111. }, extra.redial, objOfCells);
  30112. return {
  30113. dialog: dialog,
  30114. instanceApi: instanceApi
  30115. };
  30116. };
  30117. var isTouch$5 = global$6.deviceType.isTouch();
  30118. var hiddenHeader = {
  30119. dom: {
  30120. tag: 'div',
  30121. styles: { display: 'none' },
  30122. classes: ['tox-dialog__header']
  30123. }
  30124. };
  30125. var defaultHeader = {
  30126. dom: {
  30127. tag: 'div',
  30128. classes: ['tox-dialog__header']
  30129. }
  30130. };
  30131. var pClose = function (onClose, providersBackstage) {
  30132. return ModalDialog.parts().close(Button.sketch({
  30133. dom: {
  30134. tag: 'button',
  30135. classes: [
  30136. 'tox-button',
  30137. 'tox-button--icon',
  30138. 'tox-button--naked'
  30139. ],
  30140. attributes: {
  30141. 'type': 'button',
  30142. 'aria-label': providersBackstage.translate('Close')
  30143. }
  30144. },
  30145. action: onClose,
  30146. buttonBehaviours: derive$1([Tabstopping.config({})])
  30147. }));
  30148. };
  30149. var pUntitled = function () {
  30150. return ModalDialog.parts().title({
  30151. dom: {
  30152. tag: 'div',
  30153. classes: ['tox-dialog__title'],
  30154. innerHtml: '',
  30155. styles: { display: 'none' }
  30156. }
  30157. });
  30158. };
  30159. var pBodyMessage = function (message, providersBackstage) {
  30160. return ModalDialog.parts().body({
  30161. dom: {
  30162. tag: 'div',
  30163. classes: ['tox-dialog__body']
  30164. },
  30165. components: [{
  30166. dom: {
  30167. tag: 'div',
  30168. classes: ['tox-dialog__body-content']
  30169. },
  30170. components: [{ dom: fromHtml$2('<p>' + providersBackstage.translate(message) + '</p>') }]
  30171. }]
  30172. });
  30173. };
  30174. var pFooter = function (buttons) {
  30175. return ModalDialog.parts().footer({
  30176. dom: {
  30177. tag: 'div',
  30178. classes: ['tox-dialog__footer']
  30179. },
  30180. components: buttons
  30181. });
  30182. };
  30183. var pFooterGroup = function (startButtons, endButtons) {
  30184. return [
  30185. Container.sketch({
  30186. dom: {
  30187. tag: 'div',
  30188. classes: ['tox-dialog__footer-start']
  30189. },
  30190. components: startButtons
  30191. }),
  30192. Container.sketch({
  30193. dom: {
  30194. tag: 'div',
  30195. classes: ['tox-dialog__footer-end']
  30196. },
  30197. components: endButtons
  30198. })
  30199. ];
  30200. };
  30201. var renderDialog$1 = function (spec) {
  30202. return ModalDialog.sketch({
  30203. lazySink: spec.lazySink,
  30204. onEscape: function () {
  30205. spec.onCancel();
  30206. return Option.some(true);
  30207. },
  30208. dom: {
  30209. tag: 'div',
  30210. classes: ['tox-dialog'].concat(spec.extraClasses)
  30211. },
  30212. components: [
  30213. deepMerge(spec.headerOverride.getOr(defaultHeader), {
  30214. components: [
  30215. spec.partSpecs.title,
  30216. spec.partSpecs.close
  30217. ]
  30218. }),
  30219. spec.partSpecs.body,
  30220. spec.partSpecs.footer
  30221. ],
  30222. parts: {
  30223. blocker: {
  30224. dom: fromHtml$2('<div class="tox-dialog-wrap"></div>'),
  30225. components: [{
  30226. dom: {
  30227. tag: 'div',
  30228. classes: isTouch$5 ? [
  30229. 'tox-dialog-wrap__backdrop',
  30230. 'tox-dialog-wrap__backdrop--opaque'
  30231. ] : ['tox-dialog-wrap__backdrop']
  30232. }
  30233. }]
  30234. }
  30235. },
  30236. modalBehaviours: derive$1([config('basic-dialog-events', [
  30237. run(formCancelEvent, function (comp, se) {
  30238. spec.onCancel();
  30239. }),
  30240. run(formSubmitEvent, function (comp, se) {
  30241. spec.onSubmit();
  30242. })
  30243. ])])
  30244. });
  30245. };
  30246. var setup$c = function (extras) {
  30247. var sharedBackstage = extras.backstage.shared;
  30248. var open = function (message, callback) {
  30249. var closeDialog = function () {
  30250. ModalDialog.hide(alertDialog);
  30251. callback();
  30252. };
  30253. var memFooterClose = record(renderFooterButton({
  30254. name: 'close-alert',
  30255. text: 'OK',
  30256. primary: true,
  30257. align: 'end',
  30258. disabled: false,
  30259. icon: Option.none()
  30260. }, 'cancel', extras.backstage));
  30261. var alertDialog = build$1(renderDialog$1({
  30262. lazySink: function () {
  30263. return sharedBackstage.getSink();
  30264. },
  30265. headerOverride: Option.some(hiddenHeader),
  30266. partSpecs: {
  30267. title: pUntitled(),
  30268. close: pClose(function () {
  30269. closeDialog();
  30270. }, sharedBackstage.providers),
  30271. body: pBodyMessage(message, sharedBackstage.providers),
  30272. footer: pFooter(pFooterGroup([], [memFooterClose.asSpec()]))
  30273. },
  30274. onCancel: function () {
  30275. return closeDialog();
  30276. },
  30277. onSubmit: noop,
  30278. extraClasses: ['tox-alert-dialog']
  30279. }));
  30280. ModalDialog.show(alertDialog);
  30281. var footerCloseButton = memFooterClose.get(alertDialog);
  30282. Focusing.focus(footerCloseButton);
  30283. };
  30284. return { open: open };
  30285. };
  30286. var setup$d = function (extras) {
  30287. var sharedBackstage = extras.backstage.shared;
  30288. var open = function (message, callback) {
  30289. var closeDialog = function (state) {
  30290. ModalDialog.hide(confirmDialog);
  30291. callback(state);
  30292. };
  30293. var memFooterYes = record(renderFooterButton({
  30294. name: 'yes',
  30295. text: 'Yes',
  30296. primary: true,
  30297. align: 'end',
  30298. disabled: false,
  30299. icon: Option.none()
  30300. }, 'submit', extras.backstage));
  30301. var footerNo = renderFooterButton({
  30302. name: 'no',
  30303. text: 'No',
  30304. primary: true,
  30305. align: 'end',
  30306. disabled: false,
  30307. icon: Option.none()
  30308. }, 'cancel', extras.backstage);
  30309. var confirmDialog = build$1(renderDialog$1({
  30310. lazySink: function () {
  30311. return sharedBackstage.getSink();
  30312. },
  30313. headerOverride: Option.some(hiddenHeader),
  30314. partSpecs: {
  30315. title: pUntitled(),
  30316. close: pClose(function () {
  30317. closeDialog(false);
  30318. }, sharedBackstage.providers),
  30319. body: pBodyMessage(message, sharedBackstage.providers),
  30320. footer: pFooter(pFooterGroup([], [
  30321. footerNo,
  30322. memFooterYes.asSpec()
  30323. ]))
  30324. },
  30325. onCancel: function () {
  30326. return closeDialog(false);
  30327. },
  30328. onSubmit: function () {
  30329. return closeDialog(true);
  30330. },
  30331. extraClasses: ['tox-confirm-dialog']
  30332. }));
  30333. ModalDialog.show(confirmDialog);
  30334. var footerYesButton = memFooterYes.get(confirmDialog);
  30335. Focusing.focus(footerYesButton);
  30336. };
  30337. return { open: open };
  30338. };
  30339. var validateData$1 = function (data, validator) {
  30340. return getOrDie(asRaw('data', validator, data));
  30341. };
  30342. var inlineAdditionalBehaviours = function (editor, isStickyToolbar) {
  30343. if (isStickyToolbar) {
  30344. return [];
  30345. } else {
  30346. return [Docking.config({
  30347. contextual: {
  30348. lazyContext: function () {
  30349. return Option.some(box(Element.fromDom(editor.getContentAreaContainer())));
  30350. },
  30351. fadeInClass: 'tox-dialog-dock-fadein',
  30352. fadeOutClass: 'tox-dialog-dock-fadeout',
  30353. transitionClass: 'tox-dialog-dock-transition'
  30354. },
  30355. leftAttr: 'data-dock-left',
  30356. topAttr: 'data-dock-top',
  30357. positionAttr: 'data-dock-pos',
  30358. modes: ['top'],
  30359. lazyViewport: function () {
  30360. var win$1 = win();
  30361. var headerEle = descendant$1(Element.fromDom(editor.getContainer()), '.tox-editor-header').getOrDie();
  30362. var headerBounds = absolute$1(headerEle);
  30363. var topBounds = Math.max(win$1.y(), headerBounds.bottom());
  30364. return bounds$1(win$1.x(), topBounds, win$1.width(), win$1.bottom() - topBounds);
  30365. }
  30366. })];
  30367. }
  30368. };
  30369. var setup$e = function (extras) {
  30370. var backstage = extras.backstage;
  30371. var editor = extras.editor;
  30372. var isStickyToolbar$1 = isStickyToolbar(editor);
  30373. var alertDialog = setup$c(extras);
  30374. var confirmDialog = setup$d(extras);
  30375. var open = function (config, params, closeWindow) {
  30376. if (params !== undefined && params.inline === 'toolbar') {
  30377. return openInlineDialog(config, backstage.shared.anchors.toolbar(), closeWindow, params.ariaAttrs);
  30378. } else if (params !== undefined && params.inline === 'cursor') {
  30379. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  30380. } else {
  30381. return openModalDialog(config, closeWindow);
  30382. }
  30383. };
  30384. var openUrl = function (config, closeWindow) {
  30385. return openModalUrlDialog(config, closeWindow);
  30386. };
  30387. var openModalUrlDialog = function (config, closeWindow) {
  30388. var factory = function (contents) {
  30389. var dialog = renderUrlDialog(contents, {
  30390. closeWindow: function () {
  30391. ModalDialog.hide(dialog.dialog);
  30392. closeWindow(dialog.instanceApi);
  30393. }
  30394. }, editor, backstage);
  30395. ModalDialog.show(dialog.dialog);
  30396. return dialog.instanceApi;
  30397. };
  30398. return DialogManager.openUrl(factory, config);
  30399. };
  30400. var openModalDialog = function (config, closeWindow) {
  30401. var factory = function (contents, internalInitialData, dataValidator) {
  30402. var initialData = internalInitialData;
  30403. var dialogInit = {
  30404. dataValidator: dataValidator,
  30405. initialData: initialData,
  30406. internalDialog: contents
  30407. };
  30408. var dialog = renderDialog(dialogInit, {
  30409. redial: DialogManager.redial,
  30410. closeWindow: function () {
  30411. ModalDialog.hide(dialog.dialog);
  30412. closeWindow(dialog.instanceApi);
  30413. }
  30414. }, backstage);
  30415. ModalDialog.show(dialog.dialog);
  30416. dialog.instanceApi.setData(initialData);
  30417. return dialog.instanceApi;
  30418. };
  30419. return DialogManager.open(factory, config);
  30420. };
  30421. var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  30422. var factory = function (contents, internalInitialData, dataValidator) {
  30423. var initialData = validateData$1(internalInitialData, dataValidator);
  30424. var inlineDialog = value$3();
  30425. var dialogInit = {
  30426. dataValidator: dataValidator,
  30427. initialData: initialData,
  30428. internalDialog: contents
  30429. };
  30430. var refreshDocking = function () {
  30431. return inlineDialog.on(function (dialog) {
  30432. Docking.refresh(dialog);
  30433. });
  30434. };
  30435. var dialogUi = renderInlineDialog(dialogInit, {
  30436. redial: DialogManager.redial,
  30437. closeWindow: function () {
  30438. inlineDialog.on(InlineView.hide);
  30439. editor.off('ResizeEditor', refreshDocking);
  30440. inlineDialog.clear();
  30441. closeWindow(dialogUi.instanceApi);
  30442. }
  30443. }, backstage, ariaAttrs);
  30444. var inlineDialogComp = build$1(InlineView.sketch({
  30445. lazySink: backstage.shared.getSink,
  30446. dom: {
  30447. tag: 'div',
  30448. classes: []
  30449. },
  30450. fireDismissalEventInstead: {},
  30451. inlineBehaviours: derive$1(__spreadArrays([config('window-manager-inline-events', [run(dismissRequested(), function (comp, se) {
  30452. emit(dialogUi.dialog, formCancelEvent);
  30453. })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1)))
  30454. }));
  30455. inlineDialog.set(inlineDialogComp);
  30456. InlineView.showWithin(inlineDialogComp, anchor, premade$1(dialogUi.dialog), Option.some(body()));
  30457. if (!isStickyToolbar$1) {
  30458. Docking.refresh(inlineDialogComp);
  30459. editor.on('ResizeEditor', refreshDocking);
  30460. }
  30461. dialogUi.instanceApi.setData(initialData);
  30462. Keying.focusIn(dialogUi.dialog);
  30463. return dialogUi.instanceApi;
  30464. };
  30465. return DialogManager.open(factory, config$1);
  30466. };
  30467. var confirm = function (message, callback) {
  30468. confirmDialog.open(message, function (state) {
  30469. callback(state);
  30470. });
  30471. };
  30472. var alert = function (message, callback) {
  30473. alertDialog.open(message, function () {
  30474. callback();
  30475. });
  30476. };
  30477. var close = function (instanceApi) {
  30478. instanceApi.close();
  30479. };
  30480. return {
  30481. open: open,
  30482. openUrl: openUrl,
  30483. alert: alert,
  30484. close: close,
  30485. confirm: confirm
  30486. };
  30487. };
  30488. var WindowManager = { setup: setup$e };
  30489. function Theme () {
  30490. global$1.add('silver', function (editor) {
  30491. var _a = Render.setup(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  30492. Autocompleter.register(editor, backstage.shared);
  30493. var windowMgr = WindowManager.setup({
  30494. editor: editor,
  30495. backstage: backstage
  30496. });
  30497. return {
  30498. renderUI: renderUI,
  30499. getWindowManagerImpl: constant(windowMgr),
  30500. getNotificationManagerImpl: function () {
  30501. return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  30502. },
  30503. ui: getUi()
  30504. };
  30505. });
  30506. }
  30507. Theme();
  30508. }(window));