plugin.js 314 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479
  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 Cell = function (initial) {
  12. var value = initial;
  13. var get = function () {
  14. return value;
  15. };
  16. var set = function (v) {
  17. value = v;
  18. };
  19. var clone = function () {
  20. return Cell(get());
  21. };
  22. return {
  23. get: get,
  24. set: set,
  25. clone: clone
  26. };
  27. };
  28. var noop = function () {
  29. };
  30. var compose = function (fa, fb) {
  31. return function () {
  32. var args = [];
  33. for (var _i = 0; _i < arguments.length; _i++) {
  34. args[_i] = arguments[_i];
  35. }
  36. return fa(fb.apply(null, args));
  37. };
  38. };
  39. var constant = function (value) {
  40. return function () {
  41. return value;
  42. };
  43. };
  44. var identity = function (x) {
  45. return x;
  46. };
  47. function curry(fn) {
  48. var initialArgs = [];
  49. for (var _i = 1; _i < arguments.length; _i++) {
  50. initialArgs[_i - 1] = arguments[_i];
  51. }
  52. return function () {
  53. var restArgs = [];
  54. for (var _i = 0; _i < arguments.length; _i++) {
  55. restArgs[_i] = arguments[_i];
  56. }
  57. var all = initialArgs.concat(restArgs);
  58. return fn.apply(null, all);
  59. };
  60. }
  61. var not = function (f) {
  62. return function () {
  63. var args = [];
  64. for (var _i = 0; _i < arguments.length; _i++) {
  65. args[_i] = arguments[_i];
  66. }
  67. return !f.apply(null, args);
  68. };
  69. };
  70. var die = function (msg) {
  71. return function () {
  72. throw new Error(msg);
  73. };
  74. };
  75. var never = constant(false);
  76. var always = constant(true);
  77. var none = function () {
  78. return NONE;
  79. };
  80. var NONE = function () {
  81. var eq = function (o) {
  82. return o.isNone();
  83. };
  84. var call = function (thunk) {
  85. return thunk();
  86. };
  87. var id = function (n) {
  88. return n;
  89. };
  90. var me = {
  91. fold: function (n, s) {
  92. return n();
  93. },
  94. is: never,
  95. isSome: never,
  96. isNone: always,
  97. getOr: id,
  98. getOrThunk: call,
  99. getOrDie: function (msg) {
  100. throw new Error(msg || 'error: getOrDie called on none.');
  101. },
  102. getOrNull: constant(null),
  103. getOrUndefined: constant(undefined),
  104. or: id,
  105. orThunk: call,
  106. map: none,
  107. each: noop,
  108. bind: none,
  109. exists: never,
  110. forall: always,
  111. filter: none,
  112. equals: eq,
  113. equals_: eq,
  114. toArray: function () {
  115. return [];
  116. },
  117. toString: constant('none()')
  118. };
  119. if (Object.freeze) {
  120. Object.freeze(me);
  121. }
  122. return me;
  123. }();
  124. var some = function (a) {
  125. var constant_a = constant(a);
  126. var self = function () {
  127. return me;
  128. };
  129. var bind = function (f) {
  130. return f(a);
  131. };
  132. var me = {
  133. fold: function (n, s) {
  134. return s(a);
  135. },
  136. is: function (v) {
  137. return a === v;
  138. },
  139. isSome: always,
  140. isNone: never,
  141. getOr: constant_a,
  142. getOrThunk: constant_a,
  143. getOrDie: constant_a,
  144. getOrNull: constant_a,
  145. getOrUndefined: constant_a,
  146. or: self,
  147. orThunk: self,
  148. map: function (f) {
  149. return some(f(a));
  150. },
  151. each: function (f) {
  152. f(a);
  153. },
  154. bind: bind,
  155. exists: bind,
  156. forall: bind,
  157. filter: function (f) {
  158. return f(a) ? me : NONE;
  159. },
  160. toArray: function () {
  161. return [a];
  162. },
  163. toString: function () {
  164. return 'some(' + a + ')';
  165. },
  166. equals: function (o) {
  167. return o.is(a);
  168. },
  169. equals_: function (o, elementEq) {
  170. return o.fold(never, function (b) {
  171. return elementEq(a, b);
  172. });
  173. }
  174. };
  175. return me;
  176. };
  177. var from = function (value) {
  178. return value === null || value === undefined ? NONE : some(value);
  179. };
  180. var Option = {
  181. some: some,
  182. none: none,
  183. from: from
  184. };
  185. var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
  186. var typeOf = function (x) {
  187. if (x === null) {
  188. return 'null';
  189. }
  190. var t = typeof x;
  191. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  192. return 'array';
  193. }
  194. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  195. return 'string';
  196. }
  197. return t;
  198. };
  199. var isType = function (type) {
  200. return function (value) {
  201. return typeOf(value) === type;
  202. };
  203. };
  204. var isString = isType('string');
  205. var isArray = isType('array');
  206. var isBoolean = isType('boolean');
  207. var isFunction = isType('function');
  208. var isNumber = isType('number');
  209. var nativeSlice = Array.prototype.slice;
  210. var nativeIndexOf = Array.prototype.indexOf;
  211. var nativePush = Array.prototype.push;
  212. var rawIndexOf = function (ts, t) {
  213. return nativeIndexOf.call(ts, t);
  214. };
  215. var contains = function (xs, x) {
  216. return rawIndexOf(xs, x) > -1;
  217. };
  218. var exists = function (xs, pred) {
  219. for (var i = 0, len = xs.length; i < len; i++) {
  220. var x = xs[i];
  221. if (pred(x, i)) {
  222. return true;
  223. }
  224. }
  225. return false;
  226. };
  227. var map = function (xs, f) {
  228. var len = xs.length;
  229. var r = new Array(len);
  230. for (var i = 0; i < len; i++) {
  231. var x = xs[i];
  232. r[i] = f(x, i);
  233. }
  234. return r;
  235. };
  236. var each = function (xs, f) {
  237. for (var i = 0, len = xs.length; i < len; i++) {
  238. var x = xs[i];
  239. f(x, i);
  240. }
  241. };
  242. var eachr = function (xs, f) {
  243. for (var i = xs.length - 1; i >= 0; i--) {
  244. var x = xs[i];
  245. f(x, i);
  246. }
  247. };
  248. var filter = function (xs, pred) {
  249. var r = [];
  250. for (var i = 0, len = xs.length; i < len; i++) {
  251. var x = xs[i];
  252. if (pred(x, i)) {
  253. r.push(x);
  254. }
  255. }
  256. return r;
  257. };
  258. var foldr = function (xs, f, acc) {
  259. eachr(xs, function (x) {
  260. acc = f(acc, x);
  261. });
  262. return acc;
  263. };
  264. var foldl = function (xs, f, acc) {
  265. each(xs, function (x) {
  266. acc = f(acc, x);
  267. });
  268. return acc;
  269. };
  270. var find = function (xs, pred) {
  271. for (var i = 0, len = xs.length; i < len; i++) {
  272. var x = xs[i];
  273. if (pred(x, i)) {
  274. return Option.some(x);
  275. }
  276. }
  277. return Option.none();
  278. };
  279. var findIndex = function (xs, pred) {
  280. for (var i = 0, len = xs.length; i < len; i++) {
  281. var x = xs[i];
  282. if (pred(x, i)) {
  283. return Option.some(i);
  284. }
  285. }
  286. return Option.none();
  287. };
  288. var flatten = function (xs) {
  289. var r = [];
  290. for (var i = 0, len = xs.length; i < len; ++i) {
  291. if (!isArray(xs[i])) {
  292. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  293. }
  294. nativePush.apply(r, xs[i]);
  295. }
  296. return r;
  297. };
  298. var bind = function (xs, f) {
  299. var output = map(xs, f);
  300. return flatten(output);
  301. };
  302. var forall = function (xs, pred) {
  303. for (var i = 0, len = xs.length; i < len; ++i) {
  304. var x = xs[i];
  305. if (pred(x, i) !== true) {
  306. return false;
  307. }
  308. }
  309. return true;
  310. };
  311. var reverse = function (xs) {
  312. var r = nativeSlice.call(xs, 0);
  313. r.reverse();
  314. return r;
  315. };
  316. var last = function (xs) {
  317. return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  318. };
  319. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  320. return nativeSlice.call(x);
  321. };
  322. var keys = Object.keys;
  323. var hasOwnProperty = Object.hasOwnProperty;
  324. var each$1 = function (obj, f) {
  325. var props = keys(obj);
  326. for (var k = 0, len = props.length; k < len; k++) {
  327. var i = props[k];
  328. var x = obj[i];
  329. f(x, i);
  330. }
  331. };
  332. var map$1 = function (obj, f) {
  333. return tupleMap(obj, function (x, i) {
  334. return {
  335. k: i,
  336. v: f(x, i)
  337. };
  338. });
  339. };
  340. var tupleMap = function (obj, f) {
  341. var r = {};
  342. each$1(obj, function (x, i) {
  343. var tuple = f(x, i);
  344. r[tuple.k] = tuple.v;
  345. });
  346. return r;
  347. };
  348. var get = function (obj, key) {
  349. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  350. };
  351. var has = function (obj, key) {
  352. return hasOwnProperty.call(obj, key);
  353. };
  354. var Immutable = function () {
  355. var fields = [];
  356. for (var _i = 0; _i < arguments.length; _i++) {
  357. fields[_i] = arguments[_i];
  358. }
  359. return function () {
  360. var values = [];
  361. for (var _i = 0; _i < arguments.length; _i++) {
  362. values[_i] = arguments[_i];
  363. }
  364. if (fields.length !== values.length) {
  365. throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
  366. }
  367. var struct = {};
  368. each(fields, function (name, i) {
  369. struct[name] = constant(values[i]);
  370. });
  371. return struct;
  372. };
  373. };
  374. var sort = function (arr) {
  375. return arr.slice(0).sort();
  376. };
  377. var reqMessage = function (required, keys) {
  378. throw new Error('All required keys (' + sort(required).join(', ') + ') were not specified. Specified keys were: ' + sort(keys).join(', ') + '.');
  379. };
  380. var unsuppMessage = function (unsupported) {
  381. throw new Error('Unsupported keys for object: ' + sort(unsupported).join(', '));
  382. };
  383. var validateStrArr = function (label, array) {
  384. if (!isArray(array)) {
  385. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  386. }
  387. each(array, function (a) {
  388. if (!isString(a)) {
  389. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  390. }
  391. });
  392. };
  393. var invalidTypeMessage = function (incorrect, type) {
  394. throw new Error('All values need to be of type: ' + type + '. Keys (' + sort(incorrect).join(', ') + ') were not.');
  395. };
  396. var checkDupes = function (everything) {
  397. var sorted = sort(everything);
  398. var dupe = find(sorted, function (s, i) {
  399. return i < sorted.length - 1 && s === sorted[i + 1];
  400. });
  401. dupe.each(function (d) {
  402. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  403. });
  404. };
  405. var MixedBag = function (required, optional) {
  406. var everything = required.concat(optional);
  407. if (everything.length === 0) {
  408. throw new Error('You must specify at least one required or optional field.');
  409. }
  410. validateStrArr('required', required);
  411. validateStrArr('optional', optional);
  412. checkDupes(everything);
  413. return function (obj) {
  414. var keys$1 = keys(obj);
  415. var allReqd = forall(required, function (req) {
  416. return contains(keys$1, req);
  417. });
  418. if (!allReqd) {
  419. reqMessage(required, keys$1);
  420. }
  421. var unsupported = filter(keys$1, function (key) {
  422. return !contains(everything, key);
  423. });
  424. if (unsupported.length > 0) {
  425. unsuppMessage(unsupported);
  426. }
  427. var r = {};
  428. each(required, function (req) {
  429. r[req] = constant(obj[req]);
  430. });
  431. each(optional, function (opt) {
  432. r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
  433. });
  434. return r;
  435. };
  436. };
  437. var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE;
  438. var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE;
  439. var COMMENT = domGlobals.Node.COMMENT_NODE;
  440. var DOCUMENT = domGlobals.Node.DOCUMENT_NODE;
  441. var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE;
  442. var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE;
  443. var ELEMENT = domGlobals.Node.ELEMENT_NODE;
  444. var TEXT = domGlobals.Node.TEXT_NODE;
  445. var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE;
  446. var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE;
  447. var ENTITY = domGlobals.Node.ENTITY_NODE;
  448. var NOTATION = domGlobals.Node.NOTATION_NODE;
  449. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  450. var name = function (element) {
  451. var r = element.dom().nodeName;
  452. return r.toLowerCase();
  453. };
  454. var type = function (element) {
  455. return element.dom().nodeType;
  456. };
  457. var isType$1 = function (t) {
  458. return function (element) {
  459. return type(element) === t;
  460. };
  461. };
  462. var isComment = function (element) {
  463. return type(element) === COMMENT || name(element) === '#comment';
  464. };
  465. var isElement = isType$1(ELEMENT);
  466. var isText = isType$1(TEXT);
  467. var rawSet = function (dom, key, value) {
  468. if (isString(value) || isBoolean(value) || isNumber(value)) {
  469. dom.setAttribute(key, value + '');
  470. } else {
  471. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  472. throw new Error('Attribute value was not simple');
  473. }
  474. };
  475. var set = function (element, key, value) {
  476. rawSet(element.dom(), key, value);
  477. };
  478. var setAll = function (element, attrs) {
  479. var dom = element.dom();
  480. each$1(attrs, function (v, k) {
  481. rawSet(dom, k, v);
  482. });
  483. };
  484. var get$1 = function (element, key) {
  485. var v = element.dom().getAttribute(key);
  486. return v === null ? undefined : v;
  487. };
  488. var has$1 = function (element, key) {
  489. var dom = element.dom();
  490. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  491. };
  492. var remove = function (element, key) {
  493. element.dom().removeAttribute(key);
  494. };
  495. var clone = function (element) {
  496. return foldl(element.dom().attributes, function (acc, attr) {
  497. acc[attr.name] = attr.value;
  498. return acc;
  499. }, {});
  500. };
  501. var checkRange = function (str, substr, start) {
  502. if (substr === '') {
  503. return true;
  504. }
  505. if (str.length < substr.length) {
  506. return false;
  507. }
  508. var x = str.substr(start, start + substr.length);
  509. return x === substr;
  510. };
  511. var contains$1 = function (str, substr) {
  512. return str.indexOf(substr) !== -1;
  513. };
  514. var startsWith = function (str, prefix) {
  515. return checkRange(str, prefix, 0);
  516. };
  517. var endsWith = function (str, suffix) {
  518. return checkRange(str, suffix, str.length - suffix.length);
  519. };
  520. var trim = function (str) {
  521. return str.replace(/^\s+|\s+$/g, '');
  522. };
  523. var isSupported = function (dom) {
  524. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  525. };
  526. var cached = function (f) {
  527. var called = false;
  528. var r;
  529. return function () {
  530. var args = [];
  531. for (var _i = 0; _i < arguments.length; _i++) {
  532. args[_i] = arguments[_i];
  533. }
  534. if (!called) {
  535. called = true;
  536. r = f.apply(null, args);
  537. }
  538. return r;
  539. };
  540. };
  541. var fromHtml = function (html, scope) {
  542. var doc = scope || domGlobals.document;
  543. var div = doc.createElement('div');
  544. div.innerHTML = html;
  545. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  546. domGlobals.console.error('HTML does not have a single root node', html);
  547. throw new Error('HTML must have a single root node');
  548. }
  549. return fromDom(div.childNodes[0]);
  550. };
  551. var fromTag = function (tag, scope) {
  552. var doc = scope || domGlobals.document;
  553. var node = doc.createElement(tag);
  554. return fromDom(node);
  555. };
  556. var fromText = function (text, scope) {
  557. var doc = scope || domGlobals.document;
  558. var node = doc.createTextNode(text);
  559. return fromDom(node);
  560. };
  561. var fromDom = function (node) {
  562. if (node === null || node === undefined) {
  563. throw new Error('Node cannot be null or undefined');
  564. }
  565. return { dom: constant(node) };
  566. };
  567. var fromPoint = function (docElm, x, y) {
  568. var doc = docElm.dom();
  569. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  570. };
  571. var Element = {
  572. fromHtml: fromHtml,
  573. fromTag: fromTag,
  574. fromText: fromText,
  575. fromDom: fromDom,
  576. fromPoint: fromPoint
  577. };
  578. var inBody = function (element) {
  579. var dom = isText(element) ? element.dom().parentNode : element.dom();
  580. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  581. };
  582. var body = cached(function () {
  583. return getBody(Element.fromDom(domGlobals.document));
  584. });
  585. var getBody = function (doc) {
  586. var b = doc.dom().body;
  587. if (b === null || b === undefined) {
  588. throw new Error('Body is not available yet');
  589. }
  590. return Element.fromDom(b);
  591. };
  592. var internalSet = function (dom, property, value) {
  593. if (!isString(value)) {
  594. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  595. throw new Error('CSS value must be a string: ' + value);
  596. }
  597. if (isSupported(dom)) {
  598. dom.style.setProperty(property, value);
  599. }
  600. };
  601. var internalRemove = function (dom, property) {
  602. if (isSupported(dom)) {
  603. dom.style.removeProperty(property);
  604. }
  605. };
  606. var set$1 = function (element, property, value) {
  607. var dom = element.dom();
  608. internalSet(dom, property, value);
  609. };
  610. var setAll$1 = function (element, css) {
  611. var dom = element.dom();
  612. each$1(css, function (v, k) {
  613. internalSet(dom, k, v);
  614. });
  615. };
  616. var get$2 = function (element, property) {
  617. var dom = element.dom();
  618. var styles = domGlobals.window.getComputedStyle(dom);
  619. var r = styles.getPropertyValue(property);
  620. var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  621. return v === null ? undefined : v;
  622. };
  623. var getUnsafeProperty = function (dom, property) {
  624. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  625. };
  626. var getRaw = function (element, property) {
  627. var dom = element.dom();
  628. var raw = getUnsafeProperty(dom, property);
  629. return Option.from(raw).filter(function (r) {
  630. return r.length > 0;
  631. });
  632. };
  633. var remove$1 = function (element, property) {
  634. var dom = element.dom();
  635. internalRemove(dom, property);
  636. if (has$1(element, 'style') && trim(get$1(element, 'style')) === '') {
  637. remove(element, 'style');
  638. }
  639. };
  640. var copy = function (source, target) {
  641. var sourceDom = source.dom();
  642. var targetDom = target.dom();
  643. if (isSupported(sourceDom) && isSupported(targetDom)) {
  644. targetDom.style.cssText = sourceDom.style.cssText;
  645. }
  646. };
  647. var compareDocumentPosition = function (a, b, match) {
  648. return (a.compareDocumentPosition(b) & match) !== 0;
  649. };
  650. var documentPositionPreceding = function (a, b) {
  651. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_PRECEDING);
  652. };
  653. var documentPositionContainedBy = function (a, b) {
  654. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY);
  655. };
  656. var Node = {
  657. documentPositionPreceding: documentPositionPreceding,
  658. documentPositionContainedBy: documentPositionContainedBy
  659. };
  660. var __assign = function () {
  661. __assign = Object.assign || function __assign(t) {
  662. for (var s, i = 1, n = arguments.length; i < n; i++) {
  663. s = arguments[i];
  664. for (var p in s)
  665. if (Object.prototype.hasOwnProperty.call(s, p))
  666. t[p] = s[p];
  667. }
  668. return t;
  669. };
  670. return __assign.apply(this, arguments);
  671. };
  672. var firstMatch = function (regexes, s) {
  673. for (var i = 0; i < regexes.length; i++) {
  674. var x = regexes[i];
  675. if (x.test(s)) {
  676. return x;
  677. }
  678. }
  679. return undefined;
  680. };
  681. var find$1 = function (regexes, agent) {
  682. var r = firstMatch(regexes, agent);
  683. if (!r) {
  684. return {
  685. major: 0,
  686. minor: 0
  687. };
  688. }
  689. var group = function (i) {
  690. return Number(agent.replace(r, '$' + i));
  691. };
  692. return nu(group(1), group(2));
  693. };
  694. var detect = function (versionRegexes, agent) {
  695. var cleanedAgent = String(agent).toLowerCase();
  696. if (versionRegexes.length === 0) {
  697. return unknown();
  698. }
  699. return find$1(versionRegexes, cleanedAgent);
  700. };
  701. var unknown = function () {
  702. return nu(0, 0);
  703. };
  704. var nu = function (major, minor) {
  705. return {
  706. major: major,
  707. minor: minor
  708. };
  709. };
  710. var Version = {
  711. nu: nu,
  712. detect: detect,
  713. unknown: unknown
  714. };
  715. var edge = 'Edge';
  716. var chrome = 'Chrome';
  717. var ie = 'IE';
  718. var opera = 'Opera';
  719. var firefox = 'Firefox';
  720. var safari = 'Safari';
  721. var isBrowser = function (name, current) {
  722. return function () {
  723. return current === name;
  724. };
  725. };
  726. var unknown$1 = function () {
  727. return nu$1({
  728. current: undefined,
  729. version: Version.unknown()
  730. });
  731. };
  732. var nu$1 = function (info) {
  733. var current = info.current;
  734. var version = info.version;
  735. return {
  736. current: current,
  737. version: version,
  738. isEdge: isBrowser(edge, current),
  739. isChrome: isBrowser(chrome, current),
  740. isIE: isBrowser(ie, current),
  741. isOpera: isBrowser(opera, current),
  742. isFirefox: isBrowser(firefox, current),
  743. isSafari: isBrowser(safari, current)
  744. };
  745. };
  746. var Browser = {
  747. unknown: unknown$1,
  748. nu: nu$1,
  749. edge: constant(edge),
  750. chrome: constant(chrome),
  751. ie: constant(ie),
  752. opera: constant(opera),
  753. firefox: constant(firefox),
  754. safari: constant(safari)
  755. };
  756. var windows = 'Windows';
  757. var ios = 'iOS';
  758. var android = 'Android';
  759. var linux = 'Linux';
  760. var osx = 'OSX';
  761. var solaris = 'Solaris';
  762. var freebsd = 'FreeBSD';
  763. var isOS = function (name, current) {
  764. return function () {
  765. return current === name;
  766. };
  767. };
  768. var unknown$2 = function () {
  769. return nu$2({
  770. current: undefined,
  771. version: Version.unknown()
  772. });
  773. };
  774. var nu$2 = function (info) {
  775. var current = info.current;
  776. var version = info.version;
  777. return {
  778. current: current,
  779. version: version,
  780. isWindows: isOS(windows, current),
  781. isiOS: isOS(ios, current),
  782. isAndroid: isOS(android, current),
  783. isOSX: isOS(osx, current),
  784. isLinux: isOS(linux, current),
  785. isSolaris: isOS(solaris, current),
  786. isFreeBSD: isOS(freebsd, current)
  787. };
  788. };
  789. var OperatingSystem = {
  790. unknown: unknown$2,
  791. nu: nu$2,
  792. windows: constant(windows),
  793. ios: constant(ios),
  794. android: constant(android),
  795. linux: constant(linux),
  796. osx: constant(osx),
  797. solaris: constant(solaris),
  798. freebsd: constant(freebsd)
  799. };
  800. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  801. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  802. var isiPhone = os.isiOS() && !isiPad;
  803. var isMobile = os.isiOS() || os.isAndroid();
  804. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  805. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  806. var isPhone = isiPhone || isMobile && !isTablet;
  807. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  808. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  809. return {
  810. isiPad: constant(isiPad),
  811. isiPhone: constant(isiPhone),
  812. isTablet: constant(isTablet),
  813. isPhone: constant(isPhone),
  814. isTouch: constant(isTouch),
  815. isAndroid: os.isAndroid,
  816. isiOS: os.isiOS,
  817. isWebView: constant(iOSwebview),
  818. isDesktop: constant(isDesktop)
  819. };
  820. };
  821. var detect$1 = function (candidates, userAgent) {
  822. var agent = String(userAgent).toLowerCase();
  823. return find(candidates, function (candidate) {
  824. return candidate.search(agent);
  825. });
  826. };
  827. var detectBrowser = function (browsers, userAgent) {
  828. return detect$1(browsers, userAgent).map(function (browser) {
  829. var version = Version.detect(browser.versionRegexes, userAgent);
  830. return {
  831. current: browser.name,
  832. version: version
  833. };
  834. });
  835. };
  836. var detectOs = function (oses, userAgent) {
  837. return detect$1(oses, userAgent).map(function (os) {
  838. var version = Version.detect(os.versionRegexes, userAgent);
  839. return {
  840. current: os.name,
  841. version: version
  842. };
  843. });
  844. };
  845. var UaString = {
  846. detectBrowser: detectBrowser,
  847. detectOs: detectOs
  848. };
  849. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  850. var checkContains = function (target) {
  851. return function (uastring) {
  852. return contains$1(uastring, target);
  853. };
  854. };
  855. var browsers = [
  856. {
  857. name: 'Edge',
  858. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  859. search: function (uastring) {
  860. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  861. }
  862. },
  863. {
  864. name: 'Chrome',
  865. versionRegexes: [
  866. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  867. normalVersionRegex
  868. ],
  869. search: function (uastring) {
  870. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  871. }
  872. },
  873. {
  874. name: 'IE',
  875. versionRegexes: [
  876. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  877. /.*?rv:([0-9]+)\.([0-9]+).*/
  878. ],
  879. search: function (uastring) {
  880. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  881. }
  882. },
  883. {
  884. name: 'Opera',
  885. versionRegexes: [
  886. normalVersionRegex,
  887. /.*?opera\/([0-9]+)\.([0-9]+).*/
  888. ],
  889. search: checkContains('opera')
  890. },
  891. {
  892. name: 'Firefox',
  893. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  894. search: checkContains('firefox')
  895. },
  896. {
  897. name: 'Safari',
  898. versionRegexes: [
  899. normalVersionRegex,
  900. /.*?cpu os ([0-9]+)_([0-9]+).*/
  901. ],
  902. search: function (uastring) {
  903. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  904. }
  905. }
  906. ];
  907. var oses = [
  908. {
  909. name: 'Windows',
  910. search: checkContains('win'),
  911. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  912. },
  913. {
  914. name: 'iOS',
  915. search: function (uastring) {
  916. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  917. },
  918. versionRegexes: [
  919. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  920. /.*cpu os ([0-9]+)_([0-9]+).*/,
  921. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  922. ]
  923. },
  924. {
  925. name: 'Android',
  926. search: checkContains('android'),
  927. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  928. },
  929. {
  930. name: 'OSX',
  931. search: checkContains('os x'),
  932. versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
  933. },
  934. {
  935. name: 'Linux',
  936. search: checkContains('linux'),
  937. versionRegexes: []
  938. },
  939. {
  940. name: 'Solaris',
  941. search: checkContains('sunos'),
  942. versionRegexes: []
  943. },
  944. {
  945. name: 'FreeBSD',
  946. search: checkContains('freebsd'),
  947. versionRegexes: []
  948. }
  949. ];
  950. var PlatformInfo = {
  951. browsers: constant(browsers),
  952. oses: constant(oses)
  953. };
  954. var detect$2 = function (userAgent, mediaMatch) {
  955. var browsers = PlatformInfo.browsers();
  956. var oses = PlatformInfo.oses();
  957. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  958. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  959. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  960. return {
  961. browser: browser,
  962. os: os,
  963. deviceType: deviceType
  964. };
  965. };
  966. var PlatformDetection = { detect: detect$2 };
  967. var mediaMatch = function (query) {
  968. return domGlobals.window.matchMedia(query).matches;
  969. };
  970. var platform = Cell(PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch));
  971. var detect$3 = function () {
  972. return platform.get();
  973. };
  974. var ELEMENT$1 = ELEMENT;
  975. var DOCUMENT$1 = DOCUMENT;
  976. var is = function (element, selector) {
  977. var dom = element.dom();
  978. if (dom.nodeType !== ELEMENT$1) {
  979. return false;
  980. } else {
  981. var elem = dom;
  982. if (elem.matches !== undefined) {
  983. return elem.matches(selector);
  984. } else if (elem.msMatchesSelector !== undefined) {
  985. return elem.msMatchesSelector(selector);
  986. } else if (elem.webkitMatchesSelector !== undefined) {
  987. return elem.webkitMatchesSelector(selector);
  988. } else if (elem.mozMatchesSelector !== undefined) {
  989. return elem.mozMatchesSelector(selector);
  990. } else {
  991. throw new Error('Browser lacks native selectors');
  992. }
  993. }
  994. };
  995. var bypassSelector = function (dom) {
  996. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  997. };
  998. var all = function (selector, scope) {
  999. var base = scope === undefined ? domGlobals.document : scope.dom();
  1000. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), Element.fromDom);
  1001. };
  1002. var one = function (selector, scope) {
  1003. var base = scope === undefined ? domGlobals.document : scope.dom();
  1004. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1005. };
  1006. var eq = function (e1, e2) {
  1007. return e1.dom() === e2.dom();
  1008. };
  1009. var regularContains = function (e1, e2) {
  1010. var d1 = e1.dom();
  1011. var d2 = e2.dom();
  1012. return d1 === d2 ? false : d1.contains(d2);
  1013. };
  1014. var ieContains = function (e1, e2) {
  1015. return Node.documentPositionContainedBy(e1.dom(), e2.dom());
  1016. };
  1017. var browser = detect$3().browser;
  1018. var contains$2 = browser.isIE() ? ieContains : regularContains;
  1019. var is$1 = is;
  1020. var owner = function (element) {
  1021. return Element.fromDom(element.dom().ownerDocument);
  1022. };
  1023. var defaultView = function (element) {
  1024. return Element.fromDom(element.dom().ownerDocument.defaultView);
  1025. };
  1026. var parent = function (element) {
  1027. return Option.from(element.dom().parentNode).map(Element.fromDom);
  1028. };
  1029. var parents = function (element, isRoot) {
  1030. var stop = isFunction(isRoot) ? isRoot : never;
  1031. var dom = element.dom();
  1032. var ret = [];
  1033. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1034. var rawParent = dom.parentNode;
  1035. var p = Element.fromDom(rawParent);
  1036. ret.push(p);
  1037. if (stop(p) === true) {
  1038. break;
  1039. } else {
  1040. dom = rawParent;
  1041. }
  1042. }
  1043. return ret;
  1044. };
  1045. var prevSibling = function (element) {
  1046. return Option.from(element.dom().previousSibling).map(Element.fromDom);
  1047. };
  1048. var nextSibling = function (element) {
  1049. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  1050. };
  1051. var children = function (element) {
  1052. return map(element.dom().childNodes, Element.fromDom);
  1053. };
  1054. var child = function (element, index) {
  1055. var cs = element.dom().childNodes;
  1056. return Option.from(cs[index]).map(Element.fromDom);
  1057. };
  1058. var firstChild = function (element) {
  1059. return child(element, 0);
  1060. };
  1061. var spot = Immutable('element', 'offset');
  1062. var before = function (marker, element) {
  1063. var parent$1 = parent(marker);
  1064. parent$1.each(function (v) {
  1065. v.dom().insertBefore(element.dom(), marker.dom());
  1066. });
  1067. };
  1068. var after = function (marker, element) {
  1069. var sibling = nextSibling(marker);
  1070. sibling.fold(function () {
  1071. var parent$1 = parent(marker);
  1072. parent$1.each(function (v) {
  1073. append(v, element);
  1074. });
  1075. }, function (v) {
  1076. before(v, element);
  1077. });
  1078. };
  1079. var prepend = function (parent, element) {
  1080. var firstChild$1 = firstChild(parent);
  1081. firstChild$1.fold(function () {
  1082. append(parent, element);
  1083. }, function (v) {
  1084. parent.dom().insertBefore(element.dom(), v.dom());
  1085. });
  1086. };
  1087. var append = function (parent, element) {
  1088. parent.dom().appendChild(element.dom());
  1089. };
  1090. var wrap = function (element, wrapper) {
  1091. before(element, wrapper);
  1092. append(wrapper, element);
  1093. };
  1094. var before$1 = function (marker, elements) {
  1095. each(elements, function (x) {
  1096. before(marker, x);
  1097. });
  1098. };
  1099. var after$1 = function (marker, elements) {
  1100. each(elements, function (x, i) {
  1101. var e = i === 0 ? marker : elements[i - 1];
  1102. after(e, x);
  1103. });
  1104. };
  1105. var append$1 = function (parent, elements) {
  1106. each(elements, function (x) {
  1107. append(parent, x);
  1108. });
  1109. };
  1110. var empty = function (element) {
  1111. element.dom().textContent = '';
  1112. each(children(element), function (rogue) {
  1113. remove$2(rogue);
  1114. });
  1115. };
  1116. var remove$2 = function (element) {
  1117. var dom = element.dom();
  1118. if (dom.parentNode !== null) {
  1119. dom.parentNode.removeChild(dom);
  1120. }
  1121. };
  1122. var unwrap = function (wrapper) {
  1123. var children$1 = children(wrapper);
  1124. if (children$1.length > 0) {
  1125. before$1(wrapper, children$1);
  1126. }
  1127. remove$2(wrapper);
  1128. };
  1129. var dimension = Immutable('width', 'height');
  1130. var dimensions = Immutable('width', 'height');
  1131. var grid = Immutable('rows', 'columns');
  1132. var address = Immutable('row', 'column');
  1133. var coords = Immutable('x', 'y');
  1134. var detail = Immutable('element', 'rowspan', 'colspan');
  1135. var detailnew = Immutable('element', 'rowspan', 'colspan', 'isNew');
  1136. var extended = Immutable('element', 'rowspan', 'colspan', 'row', 'column');
  1137. var rowdata = Immutable('element', 'cells', 'section');
  1138. var elementnew = Immutable('element', 'isNew');
  1139. var rowdatanew = Immutable('element', 'cells', 'section', 'isNew');
  1140. var rowcells = Immutable('cells', 'section');
  1141. var rowdetails = Immutable('details', 'section');
  1142. var bounds = Immutable('startRow', 'startCol', 'finishRow', 'finishCol');
  1143. var ancestors = function (scope, predicate, isRoot) {
  1144. return filter(parents(scope, isRoot), predicate);
  1145. };
  1146. var children$1 = function (scope, predicate) {
  1147. return filter(children(scope), predicate);
  1148. };
  1149. var descendants = function (scope, predicate) {
  1150. var result = [];
  1151. each(children(scope), function (x) {
  1152. if (predicate(x)) {
  1153. result = result.concat([x]);
  1154. }
  1155. result = result.concat(descendants(x, predicate));
  1156. });
  1157. return result;
  1158. };
  1159. var ancestors$1 = function (scope, selector, isRoot) {
  1160. return ancestors(scope, function (e) {
  1161. return is(e, selector);
  1162. }, isRoot);
  1163. };
  1164. var children$2 = function (scope, selector) {
  1165. return children$1(scope, function (e) {
  1166. return is(e, selector);
  1167. });
  1168. };
  1169. var descendants$1 = function (scope, selector) {
  1170. return all(selector, scope);
  1171. };
  1172. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  1173. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  1174. }
  1175. var ancestor = function (scope, predicate, isRoot) {
  1176. var element = scope.dom();
  1177. var stop = isFunction(isRoot) ? isRoot : constant(false);
  1178. while (element.parentNode) {
  1179. element = element.parentNode;
  1180. var el = Element.fromDom(element);
  1181. if (predicate(el)) {
  1182. return Option.some(el);
  1183. } else if (stop(el)) {
  1184. break;
  1185. }
  1186. }
  1187. return Option.none();
  1188. };
  1189. var closest = function (scope, predicate, isRoot) {
  1190. var is = function (s, test) {
  1191. return test(s);
  1192. };
  1193. return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  1194. };
  1195. var child$1 = function (scope, predicate) {
  1196. var pred = function (node) {
  1197. return predicate(Element.fromDom(node));
  1198. };
  1199. var result = find(scope.dom().childNodes, pred);
  1200. return result.map(Element.fromDom);
  1201. };
  1202. var descendant = function (scope, predicate) {
  1203. var descend = function (node) {
  1204. for (var i = 0; i < node.childNodes.length; i++) {
  1205. var child_1 = Element.fromDom(node.childNodes[i]);
  1206. if (predicate(child_1)) {
  1207. return Option.some(child_1);
  1208. }
  1209. var res = descend(node.childNodes[i]);
  1210. if (res.isSome()) {
  1211. return res;
  1212. }
  1213. }
  1214. return Option.none();
  1215. };
  1216. return descend(scope.dom());
  1217. };
  1218. var ancestor$1 = function (scope, selector, isRoot) {
  1219. return ancestor(scope, function (e) {
  1220. return is(e, selector);
  1221. }, isRoot);
  1222. };
  1223. var child$2 = function (scope, selector) {
  1224. return child$1(scope, function (e) {
  1225. return is(e, selector);
  1226. });
  1227. };
  1228. var descendant$1 = function (scope, selector) {
  1229. return one(selector, scope);
  1230. };
  1231. var closest$1 = function (scope, selector, isRoot) {
  1232. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  1233. };
  1234. var firstLayer = function (scope, selector) {
  1235. return filterFirstLayer(scope, selector, constant(true));
  1236. };
  1237. var filterFirstLayer = function (scope, selector, predicate) {
  1238. return bind(children(scope), function (x) {
  1239. return is(x, selector) ? predicate(x) ? [x] : [] : filterFirstLayer(x, selector, predicate);
  1240. });
  1241. };
  1242. var LayerSelector = {
  1243. firstLayer: firstLayer,
  1244. filterFirstLayer: filterFirstLayer
  1245. };
  1246. var lookup = function (tags, element, isRoot) {
  1247. if (isRoot === void 0) {
  1248. isRoot = never;
  1249. }
  1250. if (isRoot(element)) {
  1251. return Option.none();
  1252. }
  1253. if (contains(tags, name(element))) {
  1254. return Option.some(element);
  1255. }
  1256. var isRootOrUpperTable = function (elm) {
  1257. return is(elm, 'table') || isRoot(elm);
  1258. };
  1259. return ancestor$1(element, tags.join(','), isRootOrUpperTable);
  1260. };
  1261. var cell = function (element, isRoot) {
  1262. return lookup([
  1263. 'td',
  1264. 'th'
  1265. ], element, isRoot);
  1266. };
  1267. var cells = function (ancestor) {
  1268. return LayerSelector.firstLayer(ancestor, 'th,td');
  1269. };
  1270. var notCell = function (element, isRoot) {
  1271. return lookup([
  1272. 'caption',
  1273. 'tr',
  1274. 'tbody',
  1275. 'tfoot',
  1276. 'thead'
  1277. ], element, isRoot);
  1278. };
  1279. var neighbours = function (selector, element) {
  1280. return parent(element).map(function (parent) {
  1281. return children$2(parent, selector);
  1282. });
  1283. };
  1284. var neighbourCells = curry(neighbours, 'th,td');
  1285. var neighbourRows = curry(neighbours, 'tr');
  1286. var firstCell = function (ancestor) {
  1287. return descendant$1(ancestor, 'th,td');
  1288. };
  1289. var table = function (element, isRoot) {
  1290. return closest$1(element, 'table', isRoot);
  1291. };
  1292. var row = function (element, isRoot) {
  1293. return lookup(['tr'], element, isRoot);
  1294. };
  1295. var rows = function (ancestor) {
  1296. return LayerSelector.firstLayer(ancestor, 'tr');
  1297. };
  1298. var attr = function (element, property) {
  1299. return parseInt(get$1(element, property), 10);
  1300. };
  1301. var grid$1 = function (element, rowProp, colProp) {
  1302. var rowsCount = attr(element, rowProp);
  1303. var cols = attr(element, colProp);
  1304. return grid(rowsCount, cols);
  1305. };
  1306. var TableLookup = {
  1307. cell: cell,
  1308. firstCell: firstCell,
  1309. cells: cells,
  1310. neighbourCells: neighbourCells,
  1311. table: table,
  1312. row: row,
  1313. rows: rows,
  1314. notCell: notCell,
  1315. neighbourRows: neighbourRows,
  1316. attr: attr,
  1317. grid: grid$1
  1318. };
  1319. var fromTable = function (table) {
  1320. var rows = TableLookup.rows(table);
  1321. return map(rows, function (row) {
  1322. var element = row;
  1323. var parent$1 = parent(element);
  1324. var parentSection = parent$1.map(function (p) {
  1325. var parentName = name(p);
  1326. return parentName === 'tfoot' || parentName === 'thead' || parentName === 'tbody' ? parentName : 'tbody';
  1327. }).getOr('tbody');
  1328. var cells = map(TableLookup.cells(row), function (cell) {
  1329. var rowspan = has$1(cell, 'rowspan') ? parseInt(get$1(cell, 'rowspan'), 10) : 1;
  1330. var colspan = has$1(cell, 'colspan') ? parseInt(get$1(cell, 'colspan'), 10) : 1;
  1331. return detail(cell, rowspan, colspan);
  1332. });
  1333. return rowdata(element, cells, parentSection);
  1334. });
  1335. };
  1336. var fromPastedRows = function (rows, example) {
  1337. return map(rows, function (row) {
  1338. var cells = map(TableLookup.cells(row), function (cell) {
  1339. var rowspan = has$1(cell, 'rowspan') ? parseInt(get$1(cell, 'rowspan'), 10) : 1;
  1340. var colspan = has$1(cell, 'colspan') ? parseInt(get$1(cell, 'colspan'), 10) : 1;
  1341. return detail(cell, rowspan, colspan);
  1342. });
  1343. return rowdata(row, cells, example.section());
  1344. });
  1345. };
  1346. var DetailsList = {
  1347. fromTable: fromTable,
  1348. fromPastedRows: fromPastedRows
  1349. };
  1350. var key = function (row, column) {
  1351. return row + ',' + column;
  1352. };
  1353. var getAt = function (warehouse, row, column) {
  1354. var raw = warehouse.access()[key(row, column)];
  1355. return raw !== undefined ? Option.some(raw) : Option.none();
  1356. };
  1357. var findItem = function (warehouse, item, comparator) {
  1358. var filtered = filterItems(warehouse, function (detail) {
  1359. return comparator(item, detail.element());
  1360. });
  1361. return filtered.length > 0 ? Option.some(filtered[0]) : Option.none();
  1362. };
  1363. var filterItems = function (warehouse, predicate) {
  1364. var all = bind(warehouse.all(), function (r) {
  1365. return r.cells();
  1366. });
  1367. return filter(all, predicate);
  1368. };
  1369. var generate = function (list) {
  1370. var access = {};
  1371. var cells = [];
  1372. var maxRows = list.length;
  1373. var maxColumns = 0;
  1374. each(list, function (details, r) {
  1375. var currentRow = [];
  1376. each(details.cells(), function (detail) {
  1377. var start = 0;
  1378. while (access[key(r, start)] !== undefined) {
  1379. start++;
  1380. }
  1381. var current = extended(detail.element(), detail.rowspan(), detail.colspan(), r, start);
  1382. for (var i = 0; i < detail.colspan(); i++) {
  1383. for (var j = 0; j < detail.rowspan(); j++) {
  1384. var cr = r + j;
  1385. var cc = start + i;
  1386. var newpos = key(cr, cc);
  1387. access[newpos] = current;
  1388. maxColumns = Math.max(maxColumns, cc + 1);
  1389. }
  1390. }
  1391. currentRow.push(current);
  1392. });
  1393. cells.push(rowdata(details.element(), currentRow, details.section()));
  1394. });
  1395. var grid$1 = grid(maxRows, maxColumns);
  1396. return {
  1397. grid: constant(grid$1),
  1398. access: constant(access),
  1399. all: constant(cells)
  1400. };
  1401. };
  1402. var justCells = function (warehouse) {
  1403. var rows = map(warehouse.all(), function (w) {
  1404. return w.cells();
  1405. });
  1406. return flatten(rows);
  1407. };
  1408. var Warehouse = {
  1409. generate: generate,
  1410. getAt: getAt,
  1411. findItem: findItem,
  1412. filterItems: filterItems,
  1413. justCells: justCells
  1414. };
  1415. var statsStruct = Immutable('minRow', 'minCol', 'maxRow', 'maxCol');
  1416. var findSelectedStats = function (house, isSelected) {
  1417. var totalColumns = house.grid().columns();
  1418. var totalRows = house.grid().rows();
  1419. var minRow = totalRows;
  1420. var minCol = totalColumns;
  1421. var maxRow = 0;
  1422. var maxCol = 0;
  1423. each$1(house.access(), function (detail) {
  1424. if (isSelected(detail)) {
  1425. var startRow = detail.row();
  1426. var endRow = startRow + detail.rowspan() - 1;
  1427. var startCol = detail.column();
  1428. var endCol = startCol + detail.colspan() - 1;
  1429. if (startRow < minRow) {
  1430. minRow = startRow;
  1431. } else if (endRow > maxRow) {
  1432. maxRow = endRow;
  1433. }
  1434. if (startCol < minCol) {
  1435. minCol = startCol;
  1436. } else if (endCol > maxCol) {
  1437. maxCol = endCol;
  1438. }
  1439. }
  1440. });
  1441. return statsStruct(minRow, minCol, maxRow, maxCol);
  1442. };
  1443. var makeCell = function (list, seenSelected, rowIndex) {
  1444. var row = list[rowIndex].element();
  1445. var td = Element.fromTag('td');
  1446. append(td, Element.fromTag('br'));
  1447. var f = seenSelected ? append : prepend;
  1448. f(row, td);
  1449. };
  1450. var fillInGaps = function (list, house, stats, isSelected) {
  1451. var totalColumns = house.grid().columns();
  1452. var totalRows = house.grid().rows();
  1453. for (var i = 0; i < totalRows; i++) {
  1454. var seenSelected = false;
  1455. for (var j = 0; j < totalColumns; j++) {
  1456. if (!(i < stats.minRow() || i > stats.maxRow() || j < stats.minCol() || j > stats.maxCol())) {
  1457. var needCell = Warehouse.getAt(house, i, j).filter(isSelected).isNone();
  1458. if (needCell) {
  1459. makeCell(list, seenSelected, i);
  1460. } else {
  1461. seenSelected = true;
  1462. }
  1463. }
  1464. }
  1465. }
  1466. };
  1467. var clean = function (table, stats) {
  1468. var emptyRows = filter(LayerSelector.firstLayer(table, 'tr'), function (row) {
  1469. return row.dom().childElementCount === 0;
  1470. });
  1471. each(emptyRows, remove$2);
  1472. if (stats.minCol() === stats.maxCol() || stats.minRow() === stats.maxRow()) {
  1473. each(LayerSelector.firstLayer(table, 'th,td'), function (cell) {
  1474. remove(cell, 'rowspan');
  1475. remove(cell, 'colspan');
  1476. });
  1477. }
  1478. remove(table, 'width');
  1479. remove(table, 'height');
  1480. remove$1(table, 'width');
  1481. remove$1(table, 'height');
  1482. };
  1483. var extract = function (table, selectedSelector) {
  1484. var isSelected = function (detail) {
  1485. return is(detail.element(), selectedSelector);
  1486. };
  1487. var list = DetailsList.fromTable(table);
  1488. var house = Warehouse.generate(list);
  1489. var stats = findSelectedStats(house, isSelected);
  1490. var selector = 'th:not(' + selectedSelector + ')' + ',td:not(' + selectedSelector + ')';
  1491. var unselectedCells = LayerSelector.filterFirstLayer(table, 'th,td', function (cell) {
  1492. return is(cell, selector);
  1493. });
  1494. each(unselectedCells, remove$2);
  1495. fillInGaps(list, house, stats, isSelected);
  1496. clean(table, stats);
  1497. return table;
  1498. };
  1499. var CopySelected = { extract: extract };
  1500. function NodeValue (is, name) {
  1501. var get = function (element) {
  1502. if (!is(element)) {
  1503. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  1504. }
  1505. return getOption(element).getOr('');
  1506. };
  1507. var getOption = function (element) {
  1508. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  1509. };
  1510. var set = function (element, value) {
  1511. if (!is(element)) {
  1512. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  1513. }
  1514. element.dom().nodeValue = value;
  1515. };
  1516. return {
  1517. get: get,
  1518. getOption: getOption,
  1519. set: set
  1520. };
  1521. }
  1522. var api = NodeValue(isText, 'text');
  1523. var get$3 = function (element) {
  1524. return api.get(element);
  1525. };
  1526. var getOption = function (element) {
  1527. return api.getOption(element);
  1528. };
  1529. var set$2 = function (element, value) {
  1530. api.set(element, value);
  1531. };
  1532. var getEnd = function (element) {
  1533. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  1534. return children(element).length;
  1535. }, function (v) {
  1536. return v.length;
  1537. });
  1538. };
  1539. var NBSP = '\xA0';
  1540. var isTextNodeWithCursorPosition = function (el) {
  1541. return getOption(el).filter(function (text) {
  1542. return text.trim().length !== 0 || text.indexOf(NBSP) > -1;
  1543. }).isSome();
  1544. };
  1545. var elementsWithCursorPosition = [
  1546. 'img',
  1547. 'br'
  1548. ];
  1549. var isCursorPosition = function (elem) {
  1550. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  1551. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  1552. };
  1553. var first = function (element) {
  1554. return descendant(element, isCursorPosition);
  1555. };
  1556. var last$1 = function (element) {
  1557. return descendantRtl(element, isCursorPosition);
  1558. };
  1559. var descendantRtl = function (scope, predicate) {
  1560. var descend = function (element) {
  1561. var children$1 = children(element);
  1562. for (var i = children$1.length - 1; i >= 0; i--) {
  1563. var child = children$1[i];
  1564. if (predicate(child)) {
  1565. return Option.some(child);
  1566. }
  1567. var res = descend(child);
  1568. if (res.isSome()) {
  1569. return res;
  1570. }
  1571. }
  1572. return Option.none();
  1573. };
  1574. return descend(scope);
  1575. };
  1576. var clone$1 = function (original, isDeep) {
  1577. return Element.fromDom(original.dom().cloneNode(isDeep));
  1578. };
  1579. var shallow = function (original) {
  1580. return clone$1(original, false);
  1581. };
  1582. var deep = function (original) {
  1583. return clone$1(original, true);
  1584. };
  1585. var shallowAs = function (original, tag) {
  1586. var nu = Element.fromTag(tag);
  1587. var attributes = clone(original);
  1588. setAll(nu, attributes);
  1589. return nu;
  1590. };
  1591. var copy$1 = function (original, tag) {
  1592. var nu = shallowAs(original, tag);
  1593. var cloneChildren = children(deep(original));
  1594. append$1(nu, cloneChildren);
  1595. return nu;
  1596. };
  1597. var createCell = function () {
  1598. var td = Element.fromTag('td');
  1599. append(td, Element.fromTag('br'));
  1600. return td;
  1601. };
  1602. var replace = function (cell, tag, attrs) {
  1603. var replica = copy$1(cell, tag);
  1604. each$1(attrs, function (v, k) {
  1605. if (v === null) {
  1606. remove(replica, k);
  1607. } else {
  1608. set(replica, k, v);
  1609. }
  1610. });
  1611. return replica;
  1612. };
  1613. var pasteReplace = function (cell) {
  1614. return cell;
  1615. };
  1616. var newRow = function (doc) {
  1617. return function () {
  1618. return Element.fromTag('tr', doc.dom());
  1619. };
  1620. };
  1621. var cloneFormats = function (oldCell, newCell, formats) {
  1622. var first$1 = first(oldCell);
  1623. return first$1.map(function (firstText) {
  1624. var formatSelector = formats.join(',');
  1625. var parents = ancestors$1(firstText, formatSelector, function (element) {
  1626. return eq(element, oldCell);
  1627. });
  1628. return foldr(parents, function (last, parent) {
  1629. var clonedFormat = shallow(parent);
  1630. remove(clonedFormat, 'contenteditable');
  1631. append(last, clonedFormat);
  1632. return clonedFormat;
  1633. }, newCell);
  1634. }).getOr(newCell);
  1635. };
  1636. var cellOperations = function (mutate, doc, formatsToClone) {
  1637. var newCell = function (prev) {
  1638. var docu = owner(prev.element());
  1639. var td = Element.fromTag(name(prev.element()), docu.dom());
  1640. var formats = formatsToClone.getOr([
  1641. 'strong',
  1642. 'em',
  1643. 'b',
  1644. 'i',
  1645. 'span',
  1646. 'font',
  1647. 'h1',
  1648. 'h2',
  1649. 'h3',
  1650. 'h4',
  1651. 'h5',
  1652. 'h6',
  1653. 'p',
  1654. 'div'
  1655. ]);
  1656. var lastNode = formats.length > 0 ? cloneFormats(prev.element(), td, formats) : td;
  1657. append(lastNode, Element.fromTag('br'));
  1658. copy(prev.element(), td);
  1659. remove$1(td, 'height');
  1660. if (prev.colspan() !== 1) {
  1661. remove$1(prev.element(), 'width');
  1662. }
  1663. mutate(prev.element(), td);
  1664. return td;
  1665. };
  1666. return {
  1667. row: newRow(doc),
  1668. cell: newCell,
  1669. replace: replace,
  1670. gap: createCell
  1671. };
  1672. };
  1673. var paste = function (doc) {
  1674. return {
  1675. row: newRow(doc),
  1676. cell: createCell,
  1677. replace: pasteReplace,
  1678. gap: createCell
  1679. };
  1680. };
  1681. var TableFill = {
  1682. cellOperations: cellOperations,
  1683. paste: paste
  1684. };
  1685. var fromHtml$1 = function (html, scope) {
  1686. var doc = scope || domGlobals.document;
  1687. var div = doc.createElement('div');
  1688. div.innerHTML = html;
  1689. return children(Element.fromDom(div));
  1690. };
  1691. var inSelection = function (bounds, detail) {
  1692. var leftEdge = detail.column();
  1693. var rightEdge = detail.column() + detail.colspan() - 1;
  1694. var topEdge = detail.row();
  1695. var bottomEdge = detail.row() + detail.rowspan() - 1;
  1696. return leftEdge <= bounds.finishCol() && rightEdge >= bounds.startCol() && (topEdge <= bounds.finishRow() && bottomEdge >= bounds.startRow());
  1697. };
  1698. var isWithin = function (bounds, detail) {
  1699. return detail.column() >= bounds.startCol() && detail.column() + detail.colspan() - 1 <= bounds.finishCol() && detail.row() >= bounds.startRow() && detail.row() + detail.rowspan() - 1 <= bounds.finishRow();
  1700. };
  1701. var isRectangular = function (warehouse, bounds) {
  1702. var isRect = true;
  1703. var detailIsWithin = curry(isWithin, bounds);
  1704. for (var i = bounds.startRow(); i <= bounds.finishRow(); i++) {
  1705. for (var j = bounds.startCol(); j <= bounds.finishCol(); j++) {
  1706. isRect = isRect && Warehouse.getAt(warehouse, i, j).exists(detailIsWithin);
  1707. }
  1708. }
  1709. return isRect ? Option.some(bounds) : Option.none();
  1710. };
  1711. var CellBounds = {
  1712. inSelection: inSelection,
  1713. isWithin: isWithin,
  1714. isRectangular: isRectangular
  1715. };
  1716. var getBounds = function (detailA, detailB) {
  1717. return bounds(Math.min(detailA.row(), detailB.row()), Math.min(detailA.column(), detailB.column()), Math.max(detailA.row() + detailA.rowspan() - 1, detailB.row() + detailB.rowspan() - 1), Math.max(detailA.column() + detailA.colspan() - 1, detailB.column() + detailB.colspan() - 1));
  1718. };
  1719. var getAnyBox = function (warehouse, startCell, finishCell) {
  1720. var startCoords = Warehouse.findItem(warehouse, startCell, eq);
  1721. var finishCoords = Warehouse.findItem(warehouse, finishCell, eq);
  1722. return startCoords.bind(function (sc) {
  1723. return finishCoords.map(function (fc) {
  1724. return getBounds(sc, fc);
  1725. });
  1726. });
  1727. };
  1728. var getBox = function (warehouse, startCell, finishCell) {
  1729. return getAnyBox(warehouse, startCell, finishCell).bind(function (bounds) {
  1730. return CellBounds.isRectangular(warehouse, bounds);
  1731. });
  1732. };
  1733. var CellGroup = {
  1734. getAnyBox: getAnyBox,
  1735. getBox: getBox
  1736. };
  1737. var moveBy = function (warehouse, cell, row, column) {
  1738. return Warehouse.findItem(warehouse, cell, eq).bind(function (detail) {
  1739. var startRow = row > 0 ? detail.row() + detail.rowspan() - 1 : detail.row();
  1740. var startCol = column > 0 ? detail.column() + detail.colspan() - 1 : detail.column();
  1741. var dest = Warehouse.getAt(warehouse, startRow + row, startCol + column);
  1742. return dest.map(function (d) {
  1743. return d.element();
  1744. });
  1745. });
  1746. };
  1747. var intercepts = function (warehouse, start, finish) {
  1748. return CellGroup.getAnyBox(warehouse, start, finish).map(function (bounds) {
  1749. var inside = Warehouse.filterItems(warehouse, curry(CellBounds.inSelection, bounds));
  1750. return map(inside, function (detail) {
  1751. return detail.element();
  1752. });
  1753. });
  1754. };
  1755. var parentCell = function (warehouse, innerCell) {
  1756. var isContainedBy = function (c1, c2) {
  1757. return contains$2(c2, c1);
  1758. };
  1759. return Warehouse.findItem(warehouse, innerCell, isContainedBy).map(function (detail) {
  1760. return detail.element();
  1761. });
  1762. };
  1763. var CellFinder = {
  1764. moveBy: moveBy,
  1765. intercepts: intercepts,
  1766. parentCell: parentCell
  1767. };
  1768. var moveBy$1 = function (cell, deltaRow, deltaColumn) {
  1769. return TableLookup.table(cell).bind(function (table) {
  1770. var warehouse = getWarehouse(table);
  1771. return CellFinder.moveBy(warehouse, cell, deltaRow, deltaColumn);
  1772. });
  1773. };
  1774. var intercepts$1 = function (table, first, last) {
  1775. var warehouse = getWarehouse(table);
  1776. return CellFinder.intercepts(warehouse, first, last);
  1777. };
  1778. var nestedIntercepts = function (table, first, firstTable, last, lastTable) {
  1779. var warehouse = getWarehouse(table);
  1780. var optStartCell = eq(table, firstTable) ? Option.some(first) : CellFinder.parentCell(warehouse, first);
  1781. var optLastCell = eq(table, lastTable) ? Option.some(last) : CellFinder.parentCell(warehouse, last);
  1782. return optStartCell.bind(function (startCell) {
  1783. return optLastCell.bind(function (lastCell) {
  1784. return CellFinder.intercepts(warehouse, startCell, lastCell);
  1785. });
  1786. });
  1787. };
  1788. var getBox$1 = function (table, first, last) {
  1789. var warehouse = getWarehouse(table);
  1790. return CellGroup.getBox(warehouse, first, last);
  1791. };
  1792. var getWarehouse = function (table) {
  1793. var list = DetailsList.fromTable(table);
  1794. return Warehouse.generate(list);
  1795. };
  1796. var TablePositions = {
  1797. moveBy: moveBy$1,
  1798. intercepts: intercepts$1,
  1799. nestedIntercepts: nestedIntercepts,
  1800. getBox: getBox$1
  1801. };
  1802. var TagBoundaries = [
  1803. 'body',
  1804. 'p',
  1805. 'div',
  1806. 'article',
  1807. 'aside',
  1808. 'figcaption',
  1809. 'figure',
  1810. 'footer',
  1811. 'header',
  1812. 'nav',
  1813. 'section',
  1814. 'ol',
  1815. 'ul',
  1816. 'li',
  1817. 'table',
  1818. 'thead',
  1819. 'tbody',
  1820. 'tfoot',
  1821. 'caption',
  1822. 'tr',
  1823. 'td',
  1824. 'th',
  1825. 'h1',
  1826. 'h2',
  1827. 'h3',
  1828. 'h4',
  1829. 'h5',
  1830. 'h6',
  1831. 'blockquote',
  1832. 'pre',
  1833. 'address'
  1834. ];
  1835. function DomUniverse () {
  1836. var clone$1 = function (element) {
  1837. return Element.fromDom(element.dom().cloneNode(false));
  1838. };
  1839. var document = function (element) {
  1840. return element.dom().ownerDocument;
  1841. };
  1842. var isBoundary = function (element) {
  1843. if (!isElement(element)) {
  1844. return false;
  1845. }
  1846. if (name(element) === 'body') {
  1847. return true;
  1848. }
  1849. return contains(TagBoundaries, name(element));
  1850. };
  1851. var isEmptyTag = function (element) {
  1852. if (!isElement(element)) {
  1853. return false;
  1854. }
  1855. return contains([
  1856. 'br',
  1857. 'img',
  1858. 'hr',
  1859. 'input'
  1860. ], name(element));
  1861. };
  1862. var comparePosition = function (element, other) {
  1863. return element.dom().compareDocumentPosition(other.dom());
  1864. };
  1865. var copyAttributesTo = function (source, destination) {
  1866. var as = clone(source);
  1867. setAll(destination, as);
  1868. };
  1869. return {
  1870. up: constant({
  1871. selector: ancestor$1,
  1872. closest: closest$1,
  1873. predicate: ancestor,
  1874. all: parents
  1875. }),
  1876. down: constant({
  1877. selector: descendants$1,
  1878. predicate: descendants
  1879. }),
  1880. styles: constant({
  1881. get: get$2,
  1882. getRaw: getRaw,
  1883. set: set$1,
  1884. remove: remove$1
  1885. }),
  1886. attrs: constant({
  1887. get: get$1,
  1888. set: set,
  1889. remove: remove,
  1890. copyTo: copyAttributesTo
  1891. }),
  1892. insert: constant({
  1893. before: before,
  1894. after: after,
  1895. afterAll: after$1,
  1896. append: append,
  1897. appendAll: append$1,
  1898. prepend: prepend,
  1899. wrap: wrap
  1900. }),
  1901. remove: constant({
  1902. unwrap: unwrap,
  1903. remove: remove$2
  1904. }),
  1905. create: constant({
  1906. nu: Element.fromTag,
  1907. clone: clone$1,
  1908. text: Element.fromText
  1909. }),
  1910. query: constant({
  1911. comparePosition: comparePosition,
  1912. prevSibling: prevSibling,
  1913. nextSibling: nextSibling
  1914. }),
  1915. property: constant({
  1916. children: children,
  1917. name: name,
  1918. parent: parent,
  1919. document: document,
  1920. isText: isText,
  1921. isComment: isComment,
  1922. isElement: isElement,
  1923. getText: get$3,
  1924. setText: set$2,
  1925. isBoundary: isBoundary,
  1926. isEmptyTag: isEmptyTag
  1927. }),
  1928. eq: eq,
  1929. is: is$1
  1930. };
  1931. }
  1932. var leftRight = Immutable('left', 'right');
  1933. var brokenPath = Immutable('first', 'second', 'splits');
  1934. var bisect = function (universe, parent, child) {
  1935. var children = universe.property().children(parent);
  1936. var index = findIndex(children, curry(universe.eq, child));
  1937. return index.map(function (ind) {
  1938. return {
  1939. before: constant(children.slice(0, ind)),
  1940. after: constant(children.slice(ind + 1))
  1941. };
  1942. });
  1943. };
  1944. var breakToRight = function (universe, parent, child) {
  1945. return bisect(universe, parent, child).map(function (parts) {
  1946. var second = universe.create().clone(parent);
  1947. universe.insert().appendAll(second, parts.after());
  1948. universe.insert().after(parent, second);
  1949. return leftRight(parent, second);
  1950. });
  1951. };
  1952. var breakToLeft = function (universe, parent, child) {
  1953. return bisect(universe, parent, child).map(function (parts) {
  1954. var prior = universe.create().clone(parent);
  1955. universe.insert().appendAll(prior, parts.before().concat([child]));
  1956. universe.insert().appendAll(parent, parts.after());
  1957. universe.insert().before(parent, prior);
  1958. return leftRight(prior, parent);
  1959. });
  1960. };
  1961. var breakPath = function (universe, item, isTop, breaker) {
  1962. var next = function (child, group, splits) {
  1963. var fallback = brokenPath(child, Option.none(), splits);
  1964. if (isTop(child)) {
  1965. return brokenPath(child, group, splits);
  1966. } else {
  1967. return universe.property().parent(child).bind(function (parent) {
  1968. return breaker(universe, parent, child).map(function (breakage) {
  1969. var extra = [{
  1970. first: breakage.left,
  1971. second: breakage.right
  1972. }];
  1973. var nextChild = isTop(parent) ? parent : breakage.left();
  1974. return next(nextChild, Option.some(breakage.right()), splits.concat(extra));
  1975. });
  1976. }).getOr(fallback);
  1977. }
  1978. };
  1979. return next(item, Option.none(), []);
  1980. };
  1981. var all$1 = function (universe, look, elements, f) {
  1982. var head = elements[0];
  1983. var tail = elements.slice(1);
  1984. return f(universe, look, head, tail);
  1985. };
  1986. var oneAll = function (universe, look, elements) {
  1987. return elements.length > 0 ? all$1(universe, look, elements, unsafeOne) : Option.none();
  1988. };
  1989. var unsafeOne = function (universe, look, head, tail) {
  1990. var start = look(universe, head);
  1991. return foldr(tail, function (b, a) {
  1992. var current = look(universe, a);
  1993. return commonElement(universe, b, current);
  1994. }, start);
  1995. };
  1996. var commonElement = function (universe, start, end) {
  1997. return start.bind(function (s) {
  1998. return end.filter(curry(universe.eq, s));
  1999. });
  2000. };
  2001. var eq$1 = function (universe, item) {
  2002. return curry(universe.eq, item);
  2003. };
  2004. var unsafeSubset = function (universe, common, ps1, ps2) {
  2005. var children = universe.property().children(common);
  2006. if (universe.eq(common, ps1[0])) {
  2007. return Option.some([ps1[0]]);
  2008. }
  2009. if (universe.eq(common, ps2[0])) {
  2010. return Option.some([ps2[0]]);
  2011. }
  2012. var finder = function (ps) {
  2013. var topDown = reverse(ps);
  2014. var index = findIndex(topDown, eq$1(universe, common)).getOr(-1);
  2015. var item = index < topDown.length - 1 ? topDown[index + 1] : topDown[index];
  2016. return findIndex(children, eq$1(universe, item));
  2017. };
  2018. var startIndex = finder(ps1);
  2019. var endIndex = finder(ps2);
  2020. return startIndex.bind(function (sIndex) {
  2021. return endIndex.map(function (eIndex) {
  2022. var first = Math.min(sIndex, eIndex);
  2023. var last = Math.max(sIndex, eIndex);
  2024. return children.slice(first, last + 1);
  2025. });
  2026. });
  2027. };
  2028. var ancestors$2 = function (universe, start, end, isRoot) {
  2029. if (isRoot === void 0) {
  2030. isRoot = never;
  2031. }
  2032. var ps1 = [start].concat(universe.up().all(start));
  2033. var ps2 = [end].concat(universe.up().all(end));
  2034. var prune = function (path) {
  2035. var index = findIndex(path, isRoot);
  2036. return index.fold(function () {
  2037. return path;
  2038. }, function (ind) {
  2039. return path.slice(0, ind + 1);
  2040. });
  2041. };
  2042. var pruned1 = prune(ps1);
  2043. var pruned2 = prune(ps2);
  2044. var shared = find(pruned1, function (x) {
  2045. return exists(pruned2, eq$1(universe, x));
  2046. });
  2047. return {
  2048. firstpath: constant(pruned1),
  2049. secondpath: constant(pruned2),
  2050. shared: constant(shared)
  2051. };
  2052. };
  2053. var subset = function (universe, start, end) {
  2054. var ancs = ancestors$2(universe, start, end);
  2055. return ancs.shared().bind(function (shared) {
  2056. return unsafeSubset(universe, shared, ancs.firstpath(), ancs.secondpath());
  2057. });
  2058. };
  2059. var SubsetFn = {
  2060. subset: subset,
  2061. ancestors: ancestors$2
  2062. };
  2063. var sharedOne = oneAll;
  2064. var subset$1 = SubsetFn.subset;
  2065. var ancestors$3 = SubsetFn.ancestors;
  2066. var breakToLeft$1 = breakToLeft;
  2067. var breakToRight$1 = breakToRight;
  2068. var breakPath$1 = breakPath;
  2069. var Parent = {
  2070. sharedOne: sharedOne,
  2071. subset: subset$1,
  2072. ancestors: ancestors$3,
  2073. breakToLeft: breakToLeft$1,
  2074. breakToRight: breakToRight$1,
  2075. breakPath: breakPath$1
  2076. };
  2077. var universe = DomUniverse();
  2078. var sharedOne$1 = function (look, elements) {
  2079. return Parent.sharedOne(universe, function (_universe, element) {
  2080. return look(element);
  2081. }, elements);
  2082. };
  2083. var subset$2 = function (start, finish) {
  2084. return Parent.subset(universe, start, finish);
  2085. };
  2086. var ancestors$4 = function (start, finish, isRoot) {
  2087. return Parent.ancestors(universe, start, finish, isRoot);
  2088. };
  2089. var breakToLeft$2 = function (parent, child) {
  2090. return Parent.breakToLeft(universe, parent, child);
  2091. };
  2092. var breakToRight$2 = function (parent, child) {
  2093. return Parent.breakToRight(universe, parent, child);
  2094. };
  2095. var breakPath$2 = function (child, isTop, breaker) {
  2096. return Parent.breakPath(universe, child, isTop, function (u, p, c) {
  2097. return breaker(p, c);
  2098. });
  2099. };
  2100. var DomParent = {
  2101. sharedOne: sharedOne$1,
  2102. subset: subset$2,
  2103. ancestors: ancestors$4,
  2104. breakToLeft: breakToLeft$2,
  2105. breakToRight: breakToRight$2,
  2106. breakPath: breakPath$2
  2107. };
  2108. var create = MixedBag([
  2109. 'boxes',
  2110. 'start',
  2111. 'finish'
  2112. ], []);
  2113. var Identified = { create: create };
  2114. var lookupTable = function (container) {
  2115. return ancestor$1(container, 'table');
  2116. };
  2117. var identify = function (start, finish, isRoot) {
  2118. var getIsRoot = function (rootTable) {
  2119. return function (element) {
  2120. return isRoot !== undefined && isRoot(element) || eq(element, rootTable);
  2121. };
  2122. };
  2123. if (eq(start, finish)) {
  2124. return Option.some(Identified.create({
  2125. boxes: Option.some([start]),
  2126. start: start,
  2127. finish: finish
  2128. }));
  2129. } else {
  2130. return lookupTable(start).bind(function (startTable) {
  2131. return lookupTable(finish).bind(function (finishTable) {
  2132. if (eq(startTable, finishTable)) {
  2133. return Option.some(Identified.create({
  2134. boxes: TablePositions.intercepts(startTable, start, finish),
  2135. start: start,
  2136. finish: finish
  2137. }));
  2138. } else if (contains$2(startTable, finishTable)) {
  2139. var ancestorCells = ancestors$1(finish, 'td,th', getIsRoot(startTable));
  2140. var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
  2141. return Option.some(Identified.create({
  2142. boxes: TablePositions.nestedIntercepts(startTable, start, startTable, finish, finishTable),
  2143. start: start,
  2144. finish: finishCell
  2145. }));
  2146. } else if (contains$2(finishTable, startTable)) {
  2147. var ancestorCells = ancestors$1(start, 'td,th', getIsRoot(finishTable));
  2148. var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start;
  2149. return Option.some(Identified.create({
  2150. boxes: TablePositions.nestedIntercepts(finishTable, start, startTable, finish, finishTable),
  2151. start: start,
  2152. finish: startCell
  2153. }));
  2154. } else {
  2155. return DomParent.ancestors(start, finish).shared().bind(function (lca) {
  2156. return closest$1(lca, 'table', isRoot).bind(function (lcaTable) {
  2157. var finishAncestorCells = ancestors$1(finish, 'td,th', getIsRoot(lcaTable));
  2158. var finishCell = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
  2159. var startAncestorCells = ancestors$1(start, 'td,th', getIsRoot(lcaTable));
  2160. var startCell = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start;
  2161. return Option.some(Identified.create({
  2162. boxes: TablePositions.nestedIntercepts(lcaTable, start, startTable, finish, finishTable),
  2163. start: startCell,
  2164. finish: finishCell
  2165. }));
  2166. });
  2167. });
  2168. }
  2169. });
  2170. });
  2171. }
  2172. };
  2173. var retrieve = function (container, selector) {
  2174. var sels = descendants$1(container, selector);
  2175. return sels.length > 0 ? Option.some(sels) : Option.none();
  2176. };
  2177. var getLast = function (boxes, lastSelectedSelector) {
  2178. return find(boxes, function (box) {
  2179. return is(box, lastSelectedSelector);
  2180. });
  2181. };
  2182. var getEdges = function (container, firstSelectedSelector, lastSelectedSelector) {
  2183. return descendant$1(container, firstSelectedSelector).bind(function (first) {
  2184. return descendant$1(container, lastSelectedSelector).bind(function (last) {
  2185. return DomParent.sharedOne(lookupTable, [
  2186. first,
  2187. last
  2188. ]).map(function (tbl) {
  2189. return {
  2190. first: constant(first),
  2191. last: constant(last),
  2192. table: constant(tbl)
  2193. };
  2194. });
  2195. });
  2196. });
  2197. };
  2198. var expandTo = function (finish, firstSelectedSelector) {
  2199. return ancestor$1(finish, 'table').bind(function (table) {
  2200. return descendant$1(table, firstSelectedSelector).bind(function (start) {
  2201. return identify(start, finish).bind(function (identified) {
  2202. return identified.boxes().map(function (boxes) {
  2203. return {
  2204. boxes: constant(boxes),
  2205. start: constant(identified.start()),
  2206. finish: constant(identified.finish())
  2207. };
  2208. });
  2209. });
  2210. });
  2211. });
  2212. };
  2213. var shiftSelection = function (boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
  2214. return getLast(boxes, lastSelectedSelector).bind(function (last) {
  2215. return TablePositions.moveBy(last, deltaRow, deltaColumn).bind(function (finish) {
  2216. return expandTo(finish, firstSelectedSelector);
  2217. });
  2218. });
  2219. };
  2220. var CellSelection = {
  2221. identify: identify,
  2222. retrieve: retrieve,
  2223. shiftSelection: shiftSelection,
  2224. getEdges: getEdges
  2225. };
  2226. var retrieve$1 = function (container, selector) {
  2227. return CellSelection.retrieve(container, selector);
  2228. };
  2229. var retrieveBox = function (container, firstSelectedSelector, lastSelectedSelector) {
  2230. return CellSelection.getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function (edges) {
  2231. var isRoot = function (ancestor) {
  2232. return eq(container, ancestor);
  2233. };
  2234. var firstAncestor = ancestor$1(edges.first(), 'thead,tfoot,tbody,table', isRoot);
  2235. var lastAncestor = ancestor$1(edges.last(), 'thead,tfoot,tbody,table', isRoot);
  2236. return firstAncestor.bind(function (fA) {
  2237. return lastAncestor.bind(function (lA) {
  2238. return eq(fA, lA) ? TablePositions.getBox(edges.table(), edges.first(), edges.last()) : Option.none();
  2239. });
  2240. });
  2241. });
  2242. };
  2243. var TableSelection = {
  2244. retrieve: retrieve$1,
  2245. retrieveBox: retrieveBox
  2246. };
  2247. var selected = 'data-mce-selected';
  2248. var selectedSelector = 'td[' + selected + '],th[' + selected + ']';
  2249. var attributeSelector = '[' + selected + ']';
  2250. var firstSelected = 'data-mce-first-selected';
  2251. var firstSelectedSelector = 'td[' + firstSelected + '],th[' + firstSelected + ']';
  2252. var lastSelected = 'data-mce-last-selected';
  2253. var lastSelectedSelector = 'td[' + lastSelected + '],th[' + lastSelected + ']';
  2254. var Ephemera = {
  2255. selected: constant(selected),
  2256. selectedSelector: constant(selectedSelector),
  2257. attributeSelector: constant(attributeSelector),
  2258. firstSelected: constant(firstSelected),
  2259. firstSelectedSelector: constant(firstSelectedSelector),
  2260. lastSelected: constant(lastSelected),
  2261. lastSelectedSelector: constant(lastSelectedSelector)
  2262. };
  2263. var generate$1 = function (cases) {
  2264. if (!isArray(cases)) {
  2265. throw new Error('cases must be an array');
  2266. }
  2267. if (cases.length === 0) {
  2268. throw new Error('there must be at least one case');
  2269. }
  2270. var constructors = [];
  2271. var adt = {};
  2272. each(cases, function (acase, count) {
  2273. var keys$1 = keys(acase);
  2274. if (keys$1.length !== 1) {
  2275. throw new Error('one and only one name per case');
  2276. }
  2277. var key = keys$1[0];
  2278. var value = acase[key];
  2279. if (adt[key] !== undefined) {
  2280. throw new Error('duplicate key detected:' + key);
  2281. } else if (key === 'cata') {
  2282. throw new Error('cannot have a case named cata (sorry)');
  2283. } else if (!isArray(value)) {
  2284. throw new Error('case arguments must be an array');
  2285. }
  2286. constructors.push(key);
  2287. adt[key] = function () {
  2288. var argLength = arguments.length;
  2289. if (argLength !== value.length) {
  2290. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2291. }
  2292. var args = new Array(argLength);
  2293. for (var i = 0; i < args.length; i++) {
  2294. args[i] = arguments[i];
  2295. }
  2296. var match = function (branches) {
  2297. var branchKeys = keys(branches);
  2298. if (constructors.length !== branchKeys.length) {
  2299. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2300. }
  2301. var allReqd = forall(constructors, function (reqKey) {
  2302. return contains(branchKeys, reqKey);
  2303. });
  2304. if (!allReqd) {
  2305. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2306. }
  2307. return branches[key].apply(null, args);
  2308. };
  2309. return {
  2310. fold: function () {
  2311. if (arguments.length !== cases.length) {
  2312. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  2313. }
  2314. var target = arguments[count];
  2315. return target.apply(null, args);
  2316. },
  2317. match: match,
  2318. log: function (label) {
  2319. domGlobals.console.log(label, {
  2320. constructors: constructors,
  2321. constructor: key,
  2322. params: args
  2323. });
  2324. }
  2325. };
  2326. };
  2327. });
  2328. return adt;
  2329. };
  2330. var Adt = { generate: generate$1 };
  2331. var type$1 = Adt.generate([
  2332. { none: [] },
  2333. { multiple: ['elements'] },
  2334. { single: ['selection'] }
  2335. ]);
  2336. var cata = function (subject, onNone, onMultiple, onSingle) {
  2337. return subject.fold(onNone, onMultiple, onSingle);
  2338. };
  2339. var SelectionTypes = {
  2340. cata: cata,
  2341. none: type$1.none,
  2342. multiple: type$1.multiple,
  2343. single: type$1.single
  2344. };
  2345. var selection = function (cell, selections) {
  2346. return SelectionTypes.cata(selections.get(), constant([]), identity, constant([cell]));
  2347. };
  2348. var unmergable = function (cell, selections) {
  2349. var hasSpan = function (elem) {
  2350. return has$1(elem, 'rowspan') && parseInt(get$1(elem, 'rowspan'), 10) > 1 || has$1(elem, 'colspan') && parseInt(get$1(elem, 'colspan'), 10) > 1;
  2351. };
  2352. var candidates = selection(cell, selections);
  2353. return candidates.length > 0 && forall(candidates, hasSpan) ? Option.some(candidates) : Option.none();
  2354. };
  2355. var mergable = function (table, selections) {
  2356. return SelectionTypes.cata(selections.get(), Option.none, function (cells, _env) {
  2357. if (cells.length === 0) {
  2358. return Option.none();
  2359. }
  2360. return TableSelection.retrieveBox(table, Ephemera.firstSelectedSelector(), Ephemera.lastSelectedSelector()).bind(function (bounds) {
  2361. return cells.length > 1 ? Option.some({
  2362. bounds: constant(bounds),
  2363. cells: constant(cells)
  2364. }) : Option.none();
  2365. });
  2366. }, Option.none);
  2367. };
  2368. var CellOperations = {
  2369. mergable: mergable,
  2370. unmergable: unmergable,
  2371. selection: selection
  2372. };
  2373. var noMenu = function (cell) {
  2374. return {
  2375. element: constant(cell),
  2376. mergable: Option.none,
  2377. unmergable: Option.none,
  2378. selection: constant([cell])
  2379. };
  2380. };
  2381. var forMenu = function (selections, table, cell) {
  2382. return {
  2383. element: constant(cell),
  2384. mergable: constant(CellOperations.mergable(table, selections)),
  2385. unmergable: constant(CellOperations.unmergable(cell, selections)),
  2386. selection: constant(CellOperations.selection(cell, selections))
  2387. };
  2388. };
  2389. var notCell$1 = function (element) {
  2390. return noMenu(element);
  2391. };
  2392. var paste$1 = Immutable('element', 'clipboard', 'generators');
  2393. var pasteRows = function (selections, table, cell, clipboard, generators) {
  2394. return {
  2395. element: constant(cell),
  2396. mergable: Option.none,
  2397. unmergable: Option.none,
  2398. selection: constant(CellOperations.selection(cell, selections)),
  2399. clipboard: constant(clipboard),
  2400. generators: constant(generators)
  2401. };
  2402. };
  2403. var TableTargets = {
  2404. noMenu: noMenu,
  2405. forMenu: forMenu,
  2406. notCell: notCell$1,
  2407. paste: paste$1,
  2408. pasteRows: pasteRows
  2409. };
  2410. var extractSelected = function (cells) {
  2411. return TableLookup.table(cells[0]).map(deep).map(function (replica) {
  2412. return [CopySelected.extract(replica, Ephemera.attributeSelector())];
  2413. });
  2414. };
  2415. var serializeElements = function (editor, elements) {
  2416. return map(elements, function (elm) {
  2417. return editor.selection.serializer.serialize(elm.dom(), {});
  2418. }).join('');
  2419. };
  2420. var getTextContent = function (elements) {
  2421. return map(elements, function (element) {
  2422. return element.dom().innerText;
  2423. }).join('');
  2424. };
  2425. var registerEvents = function (editor, selections, actions, cellSelection) {
  2426. editor.on('BeforeGetContent', function (e) {
  2427. var multiCellContext = function (cells) {
  2428. e.preventDefault();
  2429. extractSelected(cells).each(function (elements) {
  2430. e.content = e.format === 'text' ? getTextContent(elements) : serializeElements(editor, elements);
  2431. });
  2432. };
  2433. if (e.selection === true) {
  2434. SelectionTypes.cata(selections.get(), noop, multiCellContext, noop);
  2435. }
  2436. });
  2437. editor.on('BeforeSetContent', function (e) {
  2438. if (e.selection === true && e.paste === true) {
  2439. var cellOpt = Option.from(editor.dom.getParent(editor.selection.getStart(), 'th,td'));
  2440. cellOpt.each(function (domCell) {
  2441. var cell = Element.fromDom(domCell);
  2442. TableLookup.table(cell).each(function (table) {
  2443. var elements = filter(fromHtml$1(e.content), function (content) {
  2444. return name(content) !== 'meta';
  2445. });
  2446. if (elements.length === 1 && name(elements[0]) === 'table') {
  2447. e.preventDefault();
  2448. var doc = Element.fromDom(editor.getDoc());
  2449. var generators = TableFill.paste(doc);
  2450. var targets = TableTargets.paste(cell, elements[0], generators);
  2451. actions.pasteCells(table, targets).each(function (rng) {
  2452. editor.selection.setRng(rng);
  2453. editor.focus();
  2454. cellSelection.clear(table);
  2455. });
  2456. }
  2457. });
  2458. });
  2459. }
  2460. });
  2461. };
  2462. var Clipboard = { registerEvents: registerEvents };
  2463. function Dimension (name, getOffset) {
  2464. var set = function (element, h) {
  2465. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  2466. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  2467. }
  2468. var dom = element.dom();
  2469. if (isSupported(dom)) {
  2470. dom.style[name] = h + 'px';
  2471. }
  2472. };
  2473. var get = function (element) {
  2474. var r = getOffset(element);
  2475. if (r <= 0 || r === null) {
  2476. var css = get$2(element, name);
  2477. return parseFloat(css) || 0;
  2478. }
  2479. return r;
  2480. };
  2481. var getOuter = get;
  2482. var aggregate = function (element, properties) {
  2483. return foldl(properties, function (acc, property) {
  2484. var val = get$2(element, property);
  2485. var value = val === undefined ? 0 : parseInt(val, 10);
  2486. return isNaN(value) ? acc : acc + value;
  2487. }, 0);
  2488. };
  2489. var max = function (element, value, properties) {
  2490. var cumulativeInclusions = aggregate(element, properties);
  2491. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  2492. return absoluteMax;
  2493. };
  2494. return {
  2495. set: set,
  2496. get: get,
  2497. getOuter: getOuter,
  2498. aggregate: aggregate,
  2499. max: max
  2500. };
  2501. }
  2502. var api$1 = Dimension('height', function (element) {
  2503. var dom = element.dom();
  2504. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  2505. });
  2506. var get$4 = function (element) {
  2507. return api$1.get(element);
  2508. };
  2509. var getOuter = function (element) {
  2510. return api$1.getOuter(element);
  2511. };
  2512. var api$2 = Dimension('width', function (element) {
  2513. return element.dom().offsetWidth;
  2514. });
  2515. var get$5 = function (element) {
  2516. return api$2.get(element);
  2517. };
  2518. var getOuter$1 = function (element) {
  2519. return api$2.getOuter(element);
  2520. };
  2521. var platform$1 = detect$3();
  2522. var needManualCalc = function () {
  2523. return platform$1.browser.isIE() || platform$1.browser.isEdge();
  2524. };
  2525. var toNumber = function (px, fallback) {
  2526. var num = parseFloat(px);
  2527. return isNaN(num) ? fallback : num;
  2528. };
  2529. var getProp = function (elm, name, fallback) {
  2530. return toNumber(get$2(elm, name), fallback);
  2531. };
  2532. var getCalculatedHeight = function (cell) {
  2533. var paddingTop = getProp(cell, 'padding-top', 0);
  2534. var paddingBottom = getProp(cell, 'padding-bottom', 0);
  2535. var borderTop = getProp(cell, 'border-top-width', 0);
  2536. var borderBottom = getProp(cell, 'border-bottom-width', 0);
  2537. var height = cell.dom().getBoundingClientRect().height;
  2538. var boxSizing = get$2(cell, 'box-sizing');
  2539. var borders = borderTop + borderBottom;
  2540. return boxSizing === 'border-box' ? height : height - paddingTop - paddingBottom - borders;
  2541. };
  2542. var getWidth = function (cell) {
  2543. return getProp(cell, 'width', get$5(cell));
  2544. };
  2545. var getHeight = function (cell) {
  2546. return needManualCalc() ? getCalculatedHeight(cell) : getProp(cell, 'height', get$4(cell));
  2547. };
  2548. var RuntimeSize = {
  2549. getWidth: getWidth,
  2550. getHeight: getHeight
  2551. };
  2552. var genericSizeRegex = /(\d+(\.\d+)?)(\w|%)*/;
  2553. var percentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
  2554. var pixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
  2555. var setPixelWidth = function (cell, amount) {
  2556. set$1(cell, 'width', amount + 'px');
  2557. };
  2558. var setPercentageWidth = function (cell, amount) {
  2559. set$1(cell, 'width', amount + '%');
  2560. };
  2561. var setHeight = function (cell, amount) {
  2562. set$1(cell, 'height', amount + 'px');
  2563. };
  2564. var getHeightValue = function (cell) {
  2565. return getRaw(cell, 'height').getOrThunk(function () {
  2566. return RuntimeSize.getHeight(cell) + 'px';
  2567. });
  2568. };
  2569. var convert = function (cell, number, getter, setter) {
  2570. var newSize = TableLookup.table(cell).map(function (table) {
  2571. var total = getter(table);
  2572. return Math.floor(number / 100 * total);
  2573. }).getOr(number);
  2574. setter(cell, newSize);
  2575. return newSize;
  2576. };
  2577. var normalizePixelSize = function (value, cell, getter, setter) {
  2578. var number = parseInt(value, 10);
  2579. return endsWith(value, '%') && name(cell) !== 'table' ? convert(cell, number, getter, setter) : number;
  2580. };
  2581. var getTotalHeight = function (cell) {
  2582. var value = getHeightValue(cell);
  2583. if (!value) {
  2584. return get$4(cell);
  2585. }
  2586. return normalizePixelSize(value, cell, get$4, setHeight);
  2587. };
  2588. var get$6 = function (cell, type, f) {
  2589. var v = f(cell);
  2590. var span = getSpan(cell, type);
  2591. return v / span;
  2592. };
  2593. var getSpan = function (cell, type) {
  2594. return has$1(cell, type) ? parseInt(get$1(cell, type), 10) : 1;
  2595. };
  2596. var getRawWidth = function (element) {
  2597. var cssWidth = getRaw(element, 'width');
  2598. return cssWidth.fold(function () {
  2599. return Option.from(get$1(element, 'width'));
  2600. }, function (width) {
  2601. return Option.some(width);
  2602. });
  2603. };
  2604. var normalizePercentageWidth = function (cellWidth, tableSize) {
  2605. return cellWidth / tableSize.pixelWidth() * 100;
  2606. };
  2607. var choosePercentageSize = function (element, width, tableSize) {
  2608. var percentMatch = percentageBasedSizeRegex.exec(width);
  2609. if (percentMatch !== null) {
  2610. return parseFloat(percentMatch[1]);
  2611. } else {
  2612. var intWidth = get$5(element);
  2613. return normalizePercentageWidth(intWidth, tableSize);
  2614. }
  2615. };
  2616. var getPercentageWidth = function (cell, tableSize) {
  2617. var width = getRawWidth(cell);
  2618. return width.fold(function () {
  2619. var intWidth = get$5(cell);
  2620. return normalizePercentageWidth(intWidth, tableSize);
  2621. }, function (w) {
  2622. return choosePercentageSize(cell, w, tableSize);
  2623. });
  2624. };
  2625. var normalizePixelWidth = function (cellWidth, tableSize) {
  2626. return cellWidth / 100 * tableSize.pixelWidth();
  2627. };
  2628. var choosePixelSize = function (element, width, tableSize) {
  2629. var pixelMatch = pixelBasedSizeRegex.exec(width);
  2630. if (pixelMatch !== null) {
  2631. return parseInt(pixelMatch[1], 10);
  2632. }
  2633. var percentMatch = percentageBasedSizeRegex.exec(width);
  2634. if (percentMatch !== null) {
  2635. var floatWidth = parseFloat(percentMatch[1]);
  2636. return normalizePixelWidth(floatWidth, tableSize);
  2637. }
  2638. return get$5(element);
  2639. };
  2640. var getPixelWidth = function (cell, tableSize) {
  2641. var width = getRawWidth(cell);
  2642. return width.fold(function () {
  2643. return get$5(cell);
  2644. }, function (w) {
  2645. return choosePixelSize(cell, w, tableSize);
  2646. });
  2647. };
  2648. var getHeight$1 = function (cell) {
  2649. return get$6(cell, 'rowspan', getTotalHeight);
  2650. };
  2651. var getGenericWidth = function (cell) {
  2652. var width = getRawWidth(cell);
  2653. return width.bind(function (w) {
  2654. var match = genericSizeRegex.exec(w);
  2655. if (match !== null) {
  2656. return Option.some({
  2657. width: constant(parseFloat(match[1])),
  2658. unit: constant(match[3])
  2659. });
  2660. } else {
  2661. return Option.none();
  2662. }
  2663. });
  2664. };
  2665. var setGenericWidth = function (cell, amount, unit) {
  2666. set$1(cell, 'width', amount + unit);
  2667. };
  2668. var Sizes = {
  2669. percentageBasedSizeRegex: constant(percentageBasedSizeRegex),
  2670. pixelBasedSizeRegex: constant(pixelBasedSizeRegex),
  2671. setPixelWidth: setPixelWidth,
  2672. setPercentageWidth: setPercentageWidth,
  2673. setHeight: setHeight,
  2674. getPixelWidth: getPixelWidth,
  2675. getPercentageWidth: getPercentageWidth,
  2676. getGenericWidth: getGenericWidth,
  2677. setGenericWidth: setGenericWidth,
  2678. getHeight: getHeight$1,
  2679. getRawWidth: getRawWidth
  2680. };
  2681. var halve = function (main, other) {
  2682. var width = Sizes.getGenericWidth(main);
  2683. width.each(function (w) {
  2684. var newWidth = w.width() / 2;
  2685. Sizes.setGenericWidth(main, newWidth, w.unit());
  2686. Sizes.setGenericWidth(other, newWidth, w.unit());
  2687. });
  2688. };
  2689. var CellMutations = { halve: halve };
  2690. var r = function (left, top) {
  2691. var translate = function (x, y) {
  2692. return r(left + x, top + y);
  2693. };
  2694. return {
  2695. left: constant(left),
  2696. top: constant(top),
  2697. translate: translate
  2698. };
  2699. };
  2700. var Position = r;
  2701. var boxPosition = function (dom) {
  2702. var box = dom.getBoundingClientRect();
  2703. return Position(box.left, box.top);
  2704. };
  2705. var firstDefinedOrZero = function (a, b) {
  2706. return a !== undefined ? a : b !== undefined ? b : 0;
  2707. };
  2708. var absolute = function (element) {
  2709. var doc = element.dom().ownerDocument;
  2710. var body = doc.body;
  2711. var win = doc.defaultView;
  2712. var html = doc.documentElement;
  2713. if (body === element.dom()) {
  2714. return Position(body.offsetLeft, body.offsetTop);
  2715. }
  2716. var scrollTop = firstDefinedOrZero(win.pageYOffset, html.scrollTop);
  2717. var scrollLeft = firstDefinedOrZero(win.pageXOffset, html.scrollLeft);
  2718. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  2719. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  2720. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  2721. };
  2722. var viewport = function (element) {
  2723. var dom = element.dom();
  2724. var doc = dom.ownerDocument;
  2725. var body = doc.body;
  2726. if (body === dom) {
  2727. return Position(body.offsetLeft, body.offsetTop);
  2728. }
  2729. if (!inBody(element)) {
  2730. return Position(0, 0);
  2731. }
  2732. return boxPosition(dom);
  2733. };
  2734. var rowInfo = Immutable('row', 'y');
  2735. var colInfo = Immutable('col', 'x');
  2736. var rtlEdge = function (cell) {
  2737. var pos = absolute(cell);
  2738. return pos.left() + getOuter$1(cell);
  2739. };
  2740. var ltrEdge = function (cell) {
  2741. return absolute(cell).left();
  2742. };
  2743. var getLeftEdge = function (index, cell) {
  2744. return colInfo(index, ltrEdge(cell));
  2745. };
  2746. var getRightEdge = function (index, cell) {
  2747. return colInfo(index, rtlEdge(cell));
  2748. };
  2749. var getTop = function (cell) {
  2750. return absolute(cell).top();
  2751. };
  2752. var getTopEdge = function (index, cell) {
  2753. return rowInfo(index, getTop(cell));
  2754. };
  2755. var getBottomEdge = function (index, cell) {
  2756. return rowInfo(index, getTop(cell) + getOuter(cell));
  2757. };
  2758. var findPositions = function (getInnerEdge, getOuterEdge, array) {
  2759. if (array.length === 0) {
  2760. return [];
  2761. }
  2762. var lines = map(array.slice(1), function (cellOption, index) {
  2763. return cellOption.map(function (cell) {
  2764. return getInnerEdge(index, cell);
  2765. });
  2766. });
  2767. var lastLine = array[array.length - 1].map(function (cell) {
  2768. return getOuterEdge(array.length - 1, cell);
  2769. });
  2770. return lines.concat([lastLine]);
  2771. };
  2772. var negate = function (step) {
  2773. return -step;
  2774. };
  2775. var height = {
  2776. delta: identity,
  2777. positions: function (optElements) {
  2778. return findPositions(getTopEdge, getBottomEdge, optElements);
  2779. },
  2780. edge: getTop
  2781. };
  2782. var ltr = {
  2783. delta: identity,
  2784. edge: ltrEdge,
  2785. positions: function (optElements) {
  2786. return findPositions(getLeftEdge, getRightEdge, optElements);
  2787. }
  2788. };
  2789. var rtl = {
  2790. delta: negate,
  2791. edge: rtlEdge,
  2792. positions: function (optElements) {
  2793. return findPositions(getRightEdge, getLeftEdge, optElements);
  2794. }
  2795. };
  2796. var BarPositions = {
  2797. height: height,
  2798. rtl: rtl,
  2799. ltr: ltr
  2800. };
  2801. var ResizeDirection = {
  2802. ltr: BarPositions.ltr,
  2803. rtl: BarPositions.rtl
  2804. };
  2805. function TableDirection (directionAt) {
  2806. var auto = function (table) {
  2807. return directionAt(table).isRtl() ? ResizeDirection.rtl : ResizeDirection.ltr;
  2808. };
  2809. var delta = function (amount, table) {
  2810. return auto(table).delta(amount, table);
  2811. };
  2812. var positions = function (cols, table) {
  2813. return auto(table).positions(cols, table);
  2814. };
  2815. var edge = function (cell) {
  2816. return auto(cell).edge(cell);
  2817. };
  2818. return {
  2819. delta: delta,
  2820. edge: edge,
  2821. positions: positions
  2822. };
  2823. }
  2824. var getGridSize = function (table) {
  2825. var input = DetailsList.fromTable(table);
  2826. var warehouse = Warehouse.generate(input);
  2827. return warehouse.grid();
  2828. };
  2829. var TableGridSize = { getGridSize: getGridSize };
  2830. var cat = function (arr) {
  2831. var r = [];
  2832. var push = function (x) {
  2833. r.push(x);
  2834. };
  2835. for (var i = 0; i < arr.length; i++) {
  2836. arr[i].each(push);
  2837. }
  2838. return r;
  2839. };
  2840. var findMap = function (arr, f) {
  2841. for (var i = 0; i < arr.length; i++) {
  2842. var r = f(arr[i], i);
  2843. if (r.isSome()) {
  2844. return r;
  2845. }
  2846. }
  2847. return Option.none();
  2848. };
  2849. var setIfNot = function (element, property, value, ignore) {
  2850. if (value === ignore) {
  2851. remove(element, property);
  2852. } else {
  2853. set(element, property, value);
  2854. }
  2855. };
  2856. var render = function (table, grid) {
  2857. var newRows = [];
  2858. var newCells = [];
  2859. var renderSection = function (gridSection, sectionName) {
  2860. var section = child$2(table, sectionName).getOrThunk(function () {
  2861. var tb = Element.fromTag(sectionName, owner(table).dom());
  2862. append(table, tb);
  2863. return tb;
  2864. });
  2865. empty(section);
  2866. var rows = map(gridSection, function (row) {
  2867. if (row.isNew()) {
  2868. newRows.push(row.element());
  2869. }
  2870. var tr = row.element();
  2871. empty(tr);
  2872. each(row.cells(), function (cell) {
  2873. if (cell.isNew()) {
  2874. newCells.push(cell.element());
  2875. }
  2876. setIfNot(cell.element(), 'colspan', cell.colspan(), 1);
  2877. setIfNot(cell.element(), 'rowspan', cell.rowspan(), 1);
  2878. append(tr, cell.element());
  2879. });
  2880. return tr;
  2881. });
  2882. append$1(section, rows);
  2883. };
  2884. var removeSection = function (sectionName) {
  2885. child$2(table, sectionName).each(remove$2);
  2886. };
  2887. var renderOrRemoveSection = function (gridSection, sectionName) {
  2888. if (gridSection.length > 0) {
  2889. renderSection(gridSection, sectionName);
  2890. } else {
  2891. removeSection(sectionName);
  2892. }
  2893. };
  2894. var headSection = [];
  2895. var bodySection = [];
  2896. var footSection = [];
  2897. each(grid, function (row) {
  2898. switch (row.section()) {
  2899. case 'thead':
  2900. headSection.push(row);
  2901. break;
  2902. case 'tbody':
  2903. bodySection.push(row);
  2904. break;
  2905. case 'tfoot':
  2906. footSection.push(row);
  2907. break;
  2908. }
  2909. });
  2910. renderOrRemoveSection(headSection, 'thead');
  2911. renderOrRemoveSection(bodySection, 'tbody');
  2912. renderOrRemoveSection(footSection, 'tfoot');
  2913. return {
  2914. newRows: constant(newRows),
  2915. newCells: constant(newCells)
  2916. };
  2917. };
  2918. var copy$2 = function (grid) {
  2919. var rows = map(grid, function (row) {
  2920. var tr = shallow(row.element());
  2921. each(row.cells(), function (cell) {
  2922. var clonedCell = deep(cell.element());
  2923. setIfNot(clonedCell, 'colspan', cell.colspan(), 1);
  2924. setIfNot(clonedCell, 'rowspan', cell.rowspan(), 1);
  2925. append(tr, clonedCell);
  2926. });
  2927. return tr;
  2928. });
  2929. return rows;
  2930. };
  2931. var Redraw = {
  2932. render: render,
  2933. copy: copy$2
  2934. };
  2935. var read = function (element, attr) {
  2936. var value = get$1(element, attr);
  2937. return value === undefined || value === '' ? [] : value.split(' ');
  2938. };
  2939. var add = function (element, attr, id) {
  2940. var old = read(element, attr);
  2941. var nu = old.concat([id]);
  2942. set(element, attr, nu.join(' '));
  2943. return true;
  2944. };
  2945. var remove$3 = function (element, attr, id) {
  2946. var nu = filter(read(element, attr), function (v) {
  2947. return v !== id;
  2948. });
  2949. if (nu.length > 0) {
  2950. set(element, attr, nu.join(' '));
  2951. } else {
  2952. remove(element, attr);
  2953. }
  2954. return false;
  2955. };
  2956. var supports = function (element) {
  2957. return element.dom().classList !== undefined;
  2958. };
  2959. var get$7 = function (element) {
  2960. return read(element, 'class');
  2961. };
  2962. var add$1 = function (element, clazz) {
  2963. return add(element, 'class', clazz);
  2964. };
  2965. var remove$4 = function (element, clazz) {
  2966. return remove$3(element, 'class', clazz);
  2967. };
  2968. var add$2 = function (element, clazz) {
  2969. if (supports(element)) {
  2970. element.dom().classList.add(clazz);
  2971. } else {
  2972. add$1(element, clazz);
  2973. }
  2974. };
  2975. var cleanClass = function (element) {
  2976. var classList = supports(element) ? element.dom().classList : get$7(element);
  2977. if (classList.length === 0) {
  2978. remove(element, 'class');
  2979. }
  2980. };
  2981. var remove$5 = function (element, clazz) {
  2982. if (supports(element)) {
  2983. var classList = element.dom().classList;
  2984. classList.remove(clazz);
  2985. } else {
  2986. remove$4(element, clazz);
  2987. }
  2988. cleanClass(element);
  2989. };
  2990. var has$2 = function (element, clazz) {
  2991. return supports(element) && element.dom().classList.contains(clazz);
  2992. };
  2993. var repeat = function (repititions, f) {
  2994. var r = [];
  2995. for (var i = 0; i < repititions; i++) {
  2996. r.push(f(i));
  2997. }
  2998. return r;
  2999. };
  3000. var range = function (start, end) {
  3001. var r = [];
  3002. for (var i = start; i < end; i++) {
  3003. r.push(i);
  3004. }
  3005. return r;
  3006. };
  3007. var deduce = function (xs, index) {
  3008. if (index < 0 || index >= xs.length - 1) {
  3009. return Option.none();
  3010. }
  3011. var current = xs[index].fold(function () {
  3012. var rest = reverse(xs.slice(0, index));
  3013. return findMap(rest, function (a, i) {
  3014. return a.map(function (aa) {
  3015. return {
  3016. value: aa,
  3017. delta: i + 1
  3018. };
  3019. });
  3020. });
  3021. }, function (c) {
  3022. return Option.some({
  3023. value: c,
  3024. delta: 0
  3025. });
  3026. });
  3027. var next = xs[index + 1].fold(function () {
  3028. var rest = xs.slice(index + 1);
  3029. return findMap(rest, function (a, i) {
  3030. return a.map(function (aa) {
  3031. return {
  3032. value: aa,
  3033. delta: i + 1
  3034. };
  3035. });
  3036. });
  3037. }, function (n) {
  3038. return Option.some({
  3039. value: n,
  3040. delta: 1
  3041. });
  3042. });
  3043. return current.bind(function (c) {
  3044. return next.map(function (n) {
  3045. var extras = n.delta + c.delta;
  3046. return Math.abs(n.value - c.value) / extras;
  3047. });
  3048. });
  3049. };
  3050. var columns = function (warehouse) {
  3051. var grid = warehouse.grid();
  3052. var cols = range(0, grid.columns());
  3053. var rowsArr = range(0, grid.rows());
  3054. return map(cols, function (col) {
  3055. var getBlock = function () {
  3056. return bind(rowsArr, function (r) {
  3057. return Warehouse.getAt(warehouse, r, col).filter(function (detail) {
  3058. return detail.column() === col;
  3059. }).fold(constant([]), function (detail) {
  3060. return [detail];
  3061. });
  3062. });
  3063. };
  3064. var isSingle = function (detail) {
  3065. return detail.colspan() === 1;
  3066. };
  3067. var getFallback = function () {
  3068. return Warehouse.getAt(warehouse, 0, col);
  3069. };
  3070. return decide(getBlock, isSingle, getFallback);
  3071. });
  3072. };
  3073. var decide = function (getBlock, isSingle, getFallback) {
  3074. var inBlock = getBlock();
  3075. var singleInBlock = find(inBlock, isSingle);
  3076. var detailOption = singleInBlock.orThunk(function () {
  3077. return Option.from(inBlock[0]).orThunk(getFallback);
  3078. });
  3079. return detailOption.map(function (detail) {
  3080. return detail.element();
  3081. });
  3082. };
  3083. var rows$1 = function (warehouse) {
  3084. var grid = warehouse.grid();
  3085. var rowsArr = range(0, grid.rows());
  3086. var cols = range(0, grid.columns());
  3087. return map(rowsArr, function (row) {
  3088. var getBlock = function () {
  3089. return bind(cols, function (c) {
  3090. return Warehouse.getAt(warehouse, row, c).filter(function (detail) {
  3091. return detail.row() === row;
  3092. }).fold(constant([]), function (detail) {
  3093. return [detail];
  3094. });
  3095. });
  3096. };
  3097. var isSingle = function (detail) {
  3098. return detail.rowspan() === 1;
  3099. };
  3100. var getFallback = function () {
  3101. return Warehouse.getAt(warehouse, row, 0);
  3102. };
  3103. return decide(getBlock, isSingle, getFallback);
  3104. });
  3105. };
  3106. var Blocks = {
  3107. columns: columns,
  3108. rows: rows$1
  3109. };
  3110. var css = function (namespace) {
  3111. var dashNamespace = namespace.replace(/\./g, '-');
  3112. var resolve = function (str) {
  3113. return dashNamespace + '-' + str;
  3114. };
  3115. return { resolve: resolve };
  3116. };
  3117. var styles = css('ephox-snooker');
  3118. var Styles = { resolve: styles.resolve };
  3119. var col = function (column, x, y, w, h) {
  3120. var blocker = Element.fromTag('div');
  3121. setAll$1(blocker, {
  3122. position: 'absolute',
  3123. left: x - w / 2 + 'px',
  3124. top: y + 'px',
  3125. height: h + 'px',
  3126. width: w + 'px'
  3127. });
  3128. setAll(blocker, {
  3129. 'data-column': column,
  3130. 'role': 'presentation'
  3131. });
  3132. return blocker;
  3133. };
  3134. var row$1 = function (r, x, y, w, h) {
  3135. var blocker = Element.fromTag('div');
  3136. setAll$1(blocker, {
  3137. position: 'absolute',
  3138. left: x + 'px',
  3139. top: y - h / 2 + 'px',
  3140. height: h + 'px',
  3141. width: w + 'px'
  3142. });
  3143. setAll(blocker, {
  3144. 'data-row': r,
  3145. 'role': 'presentation'
  3146. });
  3147. return blocker;
  3148. };
  3149. var Bar = {
  3150. col: col,
  3151. row: row$1
  3152. };
  3153. var resizeBar = Styles.resolve('resizer-bar');
  3154. var resizeRowBar = Styles.resolve('resizer-rows');
  3155. var resizeColBar = Styles.resolve('resizer-cols');
  3156. var BAR_THICKNESS = 7;
  3157. var destroy = function (wire) {
  3158. var previous = descendants$1(wire.parent(), '.' + resizeBar);
  3159. each(previous, remove$2);
  3160. };
  3161. var drawBar = function (wire, positions, create) {
  3162. var origin = wire.origin();
  3163. each(positions, function (cpOption, i) {
  3164. cpOption.each(function (cp) {
  3165. var bar = create(origin, cp);
  3166. add$2(bar, resizeBar);
  3167. append(wire.parent(), bar);
  3168. });
  3169. });
  3170. };
  3171. var refreshCol = function (wire, colPositions, position, tableHeight) {
  3172. drawBar(wire, colPositions, function (origin, cp) {
  3173. var colBar = Bar.col(cp.col(), cp.x() - origin.left(), position.top() - origin.top(), BAR_THICKNESS, tableHeight);
  3174. add$2(colBar, resizeColBar);
  3175. return colBar;
  3176. });
  3177. };
  3178. var refreshRow = function (wire, rowPositions, position, tableWidth) {
  3179. drawBar(wire, rowPositions, function (origin, cp) {
  3180. var rowBar = Bar.row(cp.row(), position.left() - origin.left(), cp.y() - origin.top(), tableWidth, BAR_THICKNESS);
  3181. add$2(rowBar, resizeRowBar);
  3182. return rowBar;
  3183. });
  3184. };
  3185. var refreshGrid = function (wire, table, rows, cols, hdirection, vdirection) {
  3186. var position = absolute(table);
  3187. var rowPositions = rows.length > 0 ? hdirection.positions(rows, table) : [];
  3188. refreshRow(wire, rowPositions, position, getOuter$1(table));
  3189. var colPositions = cols.length > 0 ? vdirection.positions(cols, table) : [];
  3190. refreshCol(wire, colPositions, position, getOuter(table));
  3191. };
  3192. var refresh = function (wire, table, hdirection, vdirection) {
  3193. destroy(wire);
  3194. var list = DetailsList.fromTable(table);
  3195. var warehouse = Warehouse.generate(list);
  3196. var rows = Blocks.rows(warehouse);
  3197. var cols = Blocks.columns(warehouse);
  3198. refreshGrid(wire, table, rows, cols, hdirection, vdirection);
  3199. };
  3200. var each$2 = function (wire, f) {
  3201. var bars = descendants$1(wire.parent(), '.' + resizeBar);
  3202. each(bars, f);
  3203. };
  3204. var hide = function (wire) {
  3205. each$2(wire, function (bar) {
  3206. set$1(bar, 'display', 'none');
  3207. });
  3208. };
  3209. var show = function (wire) {
  3210. each$2(wire, function (bar) {
  3211. set$1(bar, 'display', 'block');
  3212. });
  3213. };
  3214. var isRowBar = function (element) {
  3215. return has$2(element, resizeRowBar);
  3216. };
  3217. var isColBar = function (element) {
  3218. return has$2(element, resizeColBar);
  3219. };
  3220. var Bars = {
  3221. refresh: refresh,
  3222. hide: hide,
  3223. show: show,
  3224. destroy: destroy,
  3225. isRowBar: isRowBar,
  3226. isColBar: isColBar
  3227. };
  3228. var addCell = function (gridRow, index, cell) {
  3229. var cells = gridRow.cells();
  3230. var before = cells.slice(0, index);
  3231. var after = cells.slice(index);
  3232. var newCells = before.concat([cell]).concat(after);
  3233. return setCells(gridRow, newCells);
  3234. };
  3235. var mutateCell = function (gridRow, index, cell) {
  3236. var cells = gridRow.cells();
  3237. cells[index] = cell;
  3238. };
  3239. var setCells = function (gridRow, cells) {
  3240. return rowcells(cells, gridRow.section());
  3241. };
  3242. var mapCells = function (gridRow, f) {
  3243. var cells = gridRow.cells();
  3244. var r = map(cells, f);
  3245. return rowcells(r, gridRow.section());
  3246. };
  3247. var getCell = function (gridRow, index) {
  3248. return gridRow.cells()[index];
  3249. };
  3250. var getCellElement = function (gridRow, index) {
  3251. return getCell(gridRow, index).element();
  3252. };
  3253. var cellLength = function (gridRow) {
  3254. return gridRow.cells().length;
  3255. };
  3256. var GridRow = {
  3257. addCell: addCell,
  3258. setCells: setCells,
  3259. mutateCell: mutateCell,
  3260. getCell: getCell,
  3261. getCellElement: getCellElement,
  3262. mapCells: mapCells,
  3263. cellLength: cellLength
  3264. };
  3265. var getColumn = function (grid, index) {
  3266. return map(grid, function (row) {
  3267. return GridRow.getCell(row, index);
  3268. });
  3269. };
  3270. var getRow = function (grid, index) {
  3271. return grid[index];
  3272. };
  3273. var findDiff = function (xs, comp) {
  3274. if (xs.length === 0) {
  3275. return 0;
  3276. }
  3277. var first = xs[0];
  3278. var index = findIndex(xs, function (x) {
  3279. return !comp(first.element(), x.element());
  3280. });
  3281. return index.fold(function () {
  3282. return xs.length;
  3283. }, function (ind) {
  3284. return ind;
  3285. });
  3286. };
  3287. var subgrid = function (grid, row, column, comparator) {
  3288. var restOfRow = getRow(grid, row).cells().slice(column);
  3289. var endColIndex = findDiff(restOfRow, comparator);
  3290. var restOfColumn = getColumn(grid, column).slice(row);
  3291. var endRowIndex = findDiff(restOfColumn, comparator);
  3292. return {
  3293. colspan: constant(endColIndex),
  3294. rowspan: constant(endRowIndex)
  3295. };
  3296. };
  3297. var TableGrid = { subgrid: subgrid };
  3298. var toDetails = function (grid, comparator) {
  3299. var seen = map(grid, function (row, ri) {
  3300. return map(row.cells(), function (col, ci) {
  3301. return false;
  3302. });
  3303. });
  3304. var updateSeen = function (ri, ci, rowspan, colspan) {
  3305. for (var r = ri; r < ri + rowspan; r++) {
  3306. for (var c = ci; c < ci + colspan; c++) {
  3307. seen[r][c] = true;
  3308. }
  3309. }
  3310. };
  3311. return map(grid, function (row, ri) {
  3312. var details = bind(row.cells(), function (cell, ci) {
  3313. if (seen[ri][ci] === false) {
  3314. var result = TableGrid.subgrid(grid, ri, ci, comparator);
  3315. updateSeen(ri, ci, result.rowspan(), result.colspan());
  3316. return [detailnew(cell.element(), result.rowspan(), result.colspan(), cell.isNew())];
  3317. } else {
  3318. return [];
  3319. }
  3320. });
  3321. return rowdetails(details, row.section());
  3322. });
  3323. };
  3324. var toGrid = function (warehouse, generators, isNew) {
  3325. var grid = [];
  3326. for (var i = 0; i < warehouse.grid().rows(); i++) {
  3327. var rowCells = [];
  3328. for (var j = 0; j < warehouse.grid().columns(); j++) {
  3329. var element = Warehouse.getAt(warehouse, i, j).map(function (item) {
  3330. return elementnew(item.element(), isNew);
  3331. }).getOrThunk(function () {
  3332. return elementnew(generators.gap(), true);
  3333. });
  3334. rowCells.push(element);
  3335. }
  3336. var row = rowcells(rowCells, warehouse.all()[i].section());
  3337. grid.push(row);
  3338. }
  3339. return grid;
  3340. };
  3341. var Transitions = {
  3342. toDetails: toDetails,
  3343. toGrid: toGrid
  3344. };
  3345. var fromWarehouse = function (warehouse, generators) {
  3346. return Transitions.toGrid(warehouse, generators, false);
  3347. };
  3348. var deriveRows = function (rendered, generators) {
  3349. var findRow = function (details) {
  3350. var rowOfCells = findMap(details, function (detail) {
  3351. return parent(detail.element()).map(function (row) {
  3352. var isNew = parent(row).isNone();
  3353. return elementnew(row, isNew);
  3354. });
  3355. });
  3356. return rowOfCells.getOrThunk(function () {
  3357. return elementnew(generators.row(), true);
  3358. });
  3359. };
  3360. return map(rendered, function (details) {
  3361. var row = findRow(details.details());
  3362. return rowdatanew(row.element(), details.details(), details.section(), row.isNew());
  3363. });
  3364. };
  3365. var toDetailList = function (grid, generators) {
  3366. var rendered = Transitions.toDetails(grid, eq);
  3367. return deriveRows(rendered, generators);
  3368. };
  3369. var findInWarehouse = function (warehouse, element) {
  3370. var all = flatten(map(warehouse.all(), function (r) {
  3371. return r.cells();
  3372. }));
  3373. return find(all, function (e) {
  3374. return eq(element, e.element());
  3375. });
  3376. };
  3377. var run = function (operation, extract, adjustment, postAction, genWrappers) {
  3378. return function (wire, table, target, generators, direction) {
  3379. var input = DetailsList.fromTable(table);
  3380. var warehouse = Warehouse.generate(input);
  3381. var output = extract(warehouse, target).map(function (info) {
  3382. var model = fromWarehouse(warehouse, generators);
  3383. var result = operation(model, info, eq, genWrappers(generators));
  3384. var grid = toDetailList(result.grid(), generators);
  3385. return {
  3386. grid: constant(grid),
  3387. cursor: result.cursor
  3388. };
  3389. });
  3390. return output.fold(function () {
  3391. return Option.none();
  3392. }, function (out) {
  3393. var newElements = Redraw.render(table, out.grid());
  3394. adjustment(table, out.grid(), direction);
  3395. postAction(table);
  3396. Bars.refresh(wire, table, BarPositions.height, direction);
  3397. return Option.some({
  3398. cursor: out.cursor,
  3399. newRows: newElements.newRows,
  3400. newCells: newElements.newCells
  3401. });
  3402. });
  3403. };
  3404. };
  3405. var onCell = function (warehouse, target) {
  3406. return TableLookup.cell(target.element()).bind(function (cell) {
  3407. return findInWarehouse(warehouse, cell);
  3408. });
  3409. };
  3410. var onPaste = function (warehouse, target) {
  3411. return TableLookup.cell(target.element()).bind(function (cell) {
  3412. return findInWarehouse(warehouse, cell).map(function (details) {
  3413. var value = __assign(__assign({}, details), {
  3414. generators: target.generators,
  3415. clipboard: target.clipboard
  3416. });
  3417. return value;
  3418. });
  3419. });
  3420. };
  3421. var onPasteRows = function (warehouse, target) {
  3422. var details = map(target.selection(), function (cell) {
  3423. return TableLookup.cell(cell).bind(function (lc) {
  3424. return findInWarehouse(warehouse, lc);
  3425. });
  3426. });
  3427. var cells = cat(details);
  3428. return cells.length > 0 ? Option.some({
  3429. cells: cells,
  3430. generators: target.generators,
  3431. clipboard: target.clipboard
  3432. }) : Option.none();
  3433. };
  3434. var onMergable = function (_warehouse, target) {
  3435. return target.mergable();
  3436. };
  3437. var onUnmergable = function (_warehouse, target) {
  3438. return target.unmergable();
  3439. };
  3440. var onCells = function (warehouse, target) {
  3441. var details = map(target.selection(), function (cell) {
  3442. return TableLookup.cell(cell).bind(function (lc) {
  3443. return findInWarehouse(warehouse, lc);
  3444. });
  3445. });
  3446. var cells = cat(details);
  3447. return cells.length > 0 ? Option.some(cells) : Option.none();
  3448. };
  3449. var value = function (o) {
  3450. var is = function (v) {
  3451. return o === v;
  3452. };
  3453. var or = function (opt) {
  3454. return value(o);
  3455. };
  3456. var orThunk = function (f) {
  3457. return value(o);
  3458. };
  3459. var map = function (f) {
  3460. return value(f(o));
  3461. };
  3462. var mapError = function (f) {
  3463. return value(o);
  3464. };
  3465. var each = function (f) {
  3466. f(o);
  3467. };
  3468. var bind = function (f) {
  3469. return f(o);
  3470. };
  3471. var fold = function (_, onValue) {
  3472. return onValue(o);
  3473. };
  3474. var exists = function (f) {
  3475. return f(o);
  3476. };
  3477. var forall = function (f) {
  3478. return f(o);
  3479. };
  3480. var toOption = function () {
  3481. return Option.some(o);
  3482. };
  3483. return {
  3484. is: is,
  3485. isValue: always,
  3486. isError: never,
  3487. getOr: constant(o),
  3488. getOrThunk: constant(o),
  3489. getOrDie: constant(o),
  3490. or: or,
  3491. orThunk: orThunk,
  3492. fold: fold,
  3493. map: map,
  3494. mapError: mapError,
  3495. each: each,
  3496. bind: bind,
  3497. exists: exists,
  3498. forall: forall,
  3499. toOption: toOption
  3500. };
  3501. };
  3502. var error = function (message) {
  3503. var getOrThunk = function (f) {
  3504. return f();
  3505. };
  3506. var getOrDie = function () {
  3507. return die(String(message))();
  3508. };
  3509. var or = function (opt) {
  3510. return opt;
  3511. };
  3512. var orThunk = function (f) {
  3513. return f();
  3514. };
  3515. var map = function (f) {
  3516. return error(message);
  3517. };
  3518. var mapError = function (f) {
  3519. return error(f(message));
  3520. };
  3521. var bind = function (f) {
  3522. return error(message);
  3523. };
  3524. var fold = function (onError, _) {
  3525. return onError(message);
  3526. };
  3527. return {
  3528. is: never,
  3529. isValue: never,
  3530. isError: always,
  3531. getOr: identity,
  3532. getOrThunk: getOrThunk,
  3533. getOrDie: getOrDie,
  3534. or: or,
  3535. orThunk: orThunk,
  3536. fold: fold,
  3537. map: map,
  3538. mapError: mapError,
  3539. each: noop,
  3540. bind: bind,
  3541. exists: never,
  3542. forall: always,
  3543. toOption: Option.none
  3544. };
  3545. };
  3546. var fromOption = function (opt, err) {
  3547. return opt.fold(function () {
  3548. return error(err);
  3549. }, value);
  3550. };
  3551. var Result = {
  3552. value: value,
  3553. error: error,
  3554. fromOption: fromOption
  3555. };
  3556. var measure = function (startAddress, gridA, gridB) {
  3557. if (startAddress.row() >= gridA.length || startAddress.column() > GridRow.cellLength(gridA[0])) {
  3558. return Result.error('invalid start address out of table bounds, row: ' + startAddress.row() + ', column: ' + startAddress.column());
  3559. }
  3560. var rowRemainder = gridA.slice(startAddress.row());
  3561. var colRemainder = rowRemainder[0].cells().slice(startAddress.column());
  3562. var colRequired = GridRow.cellLength(gridB[0]);
  3563. var rowRequired = gridB.length;
  3564. return Result.value({
  3565. rowDelta: constant(rowRemainder.length - rowRequired),
  3566. colDelta: constant(colRemainder.length - colRequired)
  3567. });
  3568. };
  3569. var measureWidth = function (gridA, gridB) {
  3570. var colLengthA = GridRow.cellLength(gridA[0]);
  3571. var colLengthB = GridRow.cellLength(gridB[0]);
  3572. return {
  3573. rowDelta: constant(0),
  3574. colDelta: constant(colLengthA - colLengthB)
  3575. };
  3576. };
  3577. var fill = function (cells, generator) {
  3578. return map(cells, function () {
  3579. return elementnew(generator.cell(), true);
  3580. });
  3581. };
  3582. var rowFill = function (grid, amount, generator) {
  3583. return grid.concat(repeat(amount, function (_row) {
  3584. return GridRow.setCells(grid[grid.length - 1], fill(grid[grid.length - 1].cells(), generator));
  3585. }));
  3586. };
  3587. var colFill = function (grid, amount, generator) {
  3588. return map(grid, function (row) {
  3589. return GridRow.setCells(row, row.cells().concat(fill(range(0, amount), generator)));
  3590. });
  3591. };
  3592. var tailor = function (gridA, delta, generator) {
  3593. var fillCols = delta.colDelta() < 0 ? colFill : identity;
  3594. var fillRows = delta.rowDelta() < 0 ? rowFill : identity;
  3595. var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta()), generator);
  3596. var tailoredGrid = fillRows(modifiedCols, Math.abs(delta.rowDelta()), generator);
  3597. return tailoredGrid;
  3598. };
  3599. var Fitment = {
  3600. measure: measure,
  3601. measureWidth: measureWidth,
  3602. tailor: tailor
  3603. };
  3604. var merge = function (grid, bounds, comparator, substitution) {
  3605. if (grid.length === 0) {
  3606. return grid;
  3607. }
  3608. for (var i = bounds.startRow(); i <= bounds.finishRow(); i++) {
  3609. for (var j = bounds.startCol(); j <= bounds.finishCol(); j++) {
  3610. GridRow.mutateCell(grid[i], j, elementnew(substitution(), false));
  3611. }
  3612. }
  3613. return grid;
  3614. };
  3615. var unmerge = function (grid, target, comparator, substitution) {
  3616. var first = true;
  3617. for (var i = 0; i < grid.length; i++) {
  3618. for (var j = 0; j < GridRow.cellLength(grid[0]); j++) {
  3619. var current = GridRow.getCellElement(grid[i], j);
  3620. var isToReplace = comparator(current, target);
  3621. if (isToReplace === true && first === false) {
  3622. GridRow.mutateCell(grid[i], j, elementnew(substitution(), true));
  3623. } else if (isToReplace === true) {
  3624. first = false;
  3625. }
  3626. }
  3627. }
  3628. return grid;
  3629. };
  3630. var uniqueCells = function (row, comparator) {
  3631. return foldl(row, function (rest, cell) {
  3632. return exists(rest, function (currentCell) {
  3633. return comparator(currentCell.element(), cell.element());
  3634. }) ? rest : rest.concat([cell]);
  3635. }, []);
  3636. };
  3637. var splitRows = function (grid, index, comparator, substitution) {
  3638. if (index > 0 && index < grid.length) {
  3639. var rowPrevCells = grid[index - 1].cells();
  3640. var cells = uniqueCells(rowPrevCells, comparator);
  3641. each(cells, function (cell) {
  3642. var replacement = Option.none();
  3643. var _loop_1 = function (i) {
  3644. var _loop_2 = function (j) {
  3645. var current = grid[i].cells()[j];
  3646. var isToReplace = comparator(current.element(), cell.element());
  3647. if (isToReplace) {
  3648. if (replacement.isNone()) {
  3649. replacement = Option.some(substitution());
  3650. }
  3651. replacement.each(function (sub) {
  3652. GridRow.mutateCell(grid[i], j, elementnew(sub, true));
  3653. });
  3654. }
  3655. };
  3656. for (var j = 0; j < GridRow.cellLength(grid[0]); j++) {
  3657. _loop_2(j);
  3658. }
  3659. };
  3660. for (var i = index; i < grid.length; i++) {
  3661. _loop_1(i);
  3662. }
  3663. });
  3664. }
  3665. return grid;
  3666. };
  3667. var MergingOperations = {
  3668. merge: merge,
  3669. unmerge: unmerge,
  3670. splitRows: splitRows
  3671. };
  3672. var isSpanning = function (grid, row, col, comparator) {
  3673. var candidate = GridRow.getCell(grid[row], col);
  3674. var matching = curry(comparator, candidate.element());
  3675. var currentRow = grid[row];
  3676. return grid.length > 1 && GridRow.cellLength(currentRow) > 1 && (col > 0 && matching(GridRow.getCellElement(currentRow, col - 1)) || col < currentRow.cells().length - 1 && matching(GridRow.getCellElement(currentRow, col + 1)) || row > 0 && matching(GridRow.getCellElement(grid[row - 1], col)) || row < grid.length - 1 && matching(GridRow.getCellElement(grid[row + 1], col)));
  3677. };
  3678. var mergeTables = function (startAddress, gridA, gridB, generator, comparator) {
  3679. var startRow = startAddress.row();
  3680. var startCol = startAddress.column();
  3681. var mergeHeight = gridB.length;
  3682. var mergeWidth = GridRow.cellLength(gridB[0]);
  3683. var endRow = startRow + mergeHeight;
  3684. var endCol = startCol + mergeWidth;
  3685. for (var r = startRow; r < endRow; r++) {
  3686. for (var c = startCol; c < endCol; c++) {
  3687. if (isSpanning(gridA, r, c, comparator)) {
  3688. MergingOperations.unmerge(gridA, GridRow.getCellElement(gridA[r], c), comparator, generator.cell);
  3689. }
  3690. var newCell = GridRow.getCellElement(gridB[r - startRow], c - startCol);
  3691. var replacement = generator.replace(newCell);
  3692. GridRow.mutateCell(gridA[r], c, elementnew(replacement, true));
  3693. }
  3694. }
  3695. return gridA;
  3696. };
  3697. var merge$1 = function (startAddress, gridA, gridB, generator, comparator) {
  3698. var result = Fitment.measure(startAddress, gridA, gridB);
  3699. return result.map(function (delta) {
  3700. var fittedGrid = Fitment.tailor(gridA, delta, generator);
  3701. return mergeTables(startAddress, fittedGrid, gridB, generator, comparator);
  3702. });
  3703. };
  3704. var insert = function (index, gridA, gridB, generator, comparator) {
  3705. MergingOperations.splitRows(gridA, index, comparator, generator.cell);
  3706. var delta = Fitment.measureWidth(gridB, gridA);
  3707. var fittedNewGrid = Fitment.tailor(gridB, delta, generator);
  3708. var secondDelta = Fitment.measureWidth(gridA, fittedNewGrid);
  3709. var fittedOldGrid = Fitment.tailor(gridA, secondDelta, generator);
  3710. return fittedOldGrid.slice(0, index).concat(fittedNewGrid).concat(fittedOldGrid.slice(index, fittedOldGrid.length));
  3711. };
  3712. var TableMerge = {
  3713. merge: merge$1,
  3714. insert: insert
  3715. };
  3716. var insertRowAt = function (grid, index, example, comparator, substitution) {
  3717. var before = grid.slice(0, index);
  3718. var after = grid.slice(index);
  3719. var between = GridRow.mapCells(grid[example], function (ex, c) {
  3720. var withinSpan = index > 0 && index < grid.length && comparator(GridRow.getCellElement(grid[index - 1], c), GridRow.getCellElement(grid[index], c));
  3721. var ret = withinSpan ? GridRow.getCell(grid[index], c) : elementnew(substitution(ex.element(), comparator), true);
  3722. return ret;
  3723. });
  3724. return before.concat([between]).concat(after);
  3725. };
  3726. var insertColumnAt = function (grid, index, example, comparator, substitution) {
  3727. return map(grid, function (row) {
  3728. var withinSpan = index > 0 && index < GridRow.cellLength(row) && comparator(GridRow.getCellElement(row, index - 1), GridRow.getCellElement(row, index));
  3729. var sub = withinSpan ? GridRow.getCell(row, index) : elementnew(substitution(GridRow.getCellElement(row, example), comparator), true);
  3730. return GridRow.addCell(row, index, sub);
  3731. });
  3732. };
  3733. var splitCellIntoColumns = function (grid, exampleRow, exampleCol, comparator, substitution) {
  3734. var index = exampleCol + 1;
  3735. return map(grid, function (row, i) {
  3736. var isTargetCell = i === exampleRow;
  3737. var sub = isTargetCell ? elementnew(substitution(GridRow.getCellElement(row, exampleCol), comparator), true) : GridRow.getCell(row, exampleCol);
  3738. return GridRow.addCell(row, index, sub);
  3739. });
  3740. };
  3741. var splitCellIntoRows = function (grid, exampleRow, exampleCol, comparator, substitution) {
  3742. var index = exampleRow + 1;
  3743. var before = grid.slice(0, index);
  3744. var after = grid.slice(index);
  3745. var between = GridRow.mapCells(grid[exampleRow], function (ex, i) {
  3746. var isTargetCell = i === exampleCol;
  3747. return isTargetCell ? elementnew(substitution(ex.element(), comparator), true) : ex;
  3748. });
  3749. return before.concat([between]).concat(after);
  3750. };
  3751. var deleteColumnsAt = function (grid, start, finish) {
  3752. var rows = map(grid, function (row) {
  3753. var cells = row.cells().slice(0, start).concat(row.cells().slice(finish + 1));
  3754. return rowcells(cells, row.section());
  3755. });
  3756. return filter(rows, function (row) {
  3757. return row.cells().length > 0;
  3758. });
  3759. };
  3760. var deleteRowsAt = function (grid, start, finish) {
  3761. return grid.slice(0, start).concat(grid.slice(finish + 1));
  3762. };
  3763. var ModificationOperations = {
  3764. insertRowAt: insertRowAt,
  3765. insertColumnAt: insertColumnAt,
  3766. splitCellIntoColumns: splitCellIntoColumns,
  3767. splitCellIntoRows: splitCellIntoRows,
  3768. deleteRowsAt: deleteRowsAt,
  3769. deleteColumnsAt: deleteColumnsAt
  3770. };
  3771. var replaceIn = function (grid, targets, comparator, substitution) {
  3772. var isTarget = function (cell) {
  3773. return exists(targets, function (target) {
  3774. return comparator(cell.element(), target.element());
  3775. });
  3776. };
  3777. return map(grid, function (row) {
  3778. return GridRow.mapCells(row, function (cell) {
  3779. return isTarget(cell) ? elementnew(substitution(cell.element(), comparator), true) : cell;
  3780. });
  3781. });
  3782. };
  3783. var notStartRow = function (grid, rowIndex, colIndex, comparator) {
  3784. return GridRow.getCellElement(grid[rowIndex], colIndex) !== undefined && (rowIndex > 0 && comparator(GridRow.getCellElement(grid[rowIndex - 1], colIndex), GridRow.getCellElement(grid[rowIndex], colIndex)));
  3785. };
  3786. var notStartColumn = function (row, index, comparator) {
  3787. return index > 0 && comparator(GridRow.getCellElement(row, index - 1), GridRow.getCellElement(row, index));
  3788. };
  3789. var replaceColumn = function (grid, index, comparator, substitution) {
  3790. var targets = bind(grid, function (row, i) {
  3791. var alreadyAdded = notStartRow(grid, i, index, comparator) || notStartColumn(row, index, comparator);
  3792. return alreadyAdded ? [] : [GridRow.getCell(row, index)];
  3793. });
  3794. return replaceIn(grid, targets, comparator, substitution);
  3795. };
  3796. var replaceRow = function (grid, index, comparator, substitution) {
  3797. var targetRow = grid[index];
  3798. var targets = bind(targetRow.cells(), function (item, i) {
  3799. var alreadyAdded = notStartRow(grid, index, i, comparator) || notStartColumn(targetRow, i, comparator);
  3800. return alreadyAdded ? [] : [item];
  3801. });
  3802. return replaceIn(grid, targets, comparator, substitution);
  3803. };
  3804. var TransformOperations = {
  3805. replaceColumn: replaceColumn,
  3806. replaceRow: replaceRow
  3807. };
  3808. var adt = Adt.generate([
  3809. { none: [] },
  3810. { only: ['index'] },
  3811. {
  3812. left: [
  3813. 'index',
  3814. 'next'
  3815. ]
  3816. },
  3817. {
  3818. middle: [
  3819. 'prev',
  3820. 'index',
  3821. 'next'
  3822. ]
  3823. },
  3824. {
  3825. right: [
  3826. 'prev',
  3827. 'index'
  3828. ]
  3829. }
  3830. ]);
  3831. var ColumnContext = __assign({}, adt);
  3832. var neighbours$1 = function (input, index) {
  3833. if (input.length === 0) {
  3834. return ColumnContext.none();
  3835. }
  3836. if (input.length === 1) {
  3837. return ColumnContext.only(0);
  3838. }
  3839. if (index === 0) {
  3840. return ColumnContext.left(0, 1);
  3841. }
  3842. if (index === input.length - 1) {
  3843. return ColumnContext.right(index - 1, index);
  3844. }
  3845. if (index > 0 && index < input.length - 1) {
  3846. return ColumnContext.middle(index - 1, index, index + 1);
  3847. }
  3848. return ColumnContext.none();
  3849. };
  3850. var determine = function (input, column, step, tableSize) {
  3851. var result = input.slice(0);
  3852. var context = neighbours$1(input, column);
  3853. var zero = function (array) {
  3854. return map(array, constant(0));
  3855. };
  3856. var onNone = constant(zero(result));
  3857. var onOnly = function (index) {
  3858. return tableSize.singleColumnWidth(result[index], step);
  3859. };
  3860. var onChange = function (index, next) {
  3861. if (step >= 0) {
  3862. var newNext = Math.max(tableSize.minCellWidth(), result[next] - step);
  3863. return zero(result.slice(0, index)).concat([
  3864. step,
  3865. newNext - result[next]
  3866. ]).concat(zero(result.slice(next + 1)));
  3867. } else {
  3868. var newThis = Math.max(tableSize.minCellWidth(), result[index] + step);
  3869. var diffx = result[index] - newThis;
  3870. return zero(result.slice(0, index)).concat([
  3871. newThis - result[index],
  3872. diffx
  3873. ]).concat(zero(result.slice(next + 1)));
  3874. }
  3875. };
  3876. var onLeft = onChange;
  3877. var onMiddle = function (_prev, index, next) {
  3878. return onChange(index, next);
  3879. };
  3880. var onRight = function (_prev, index) {
  3881. if (step >= 0) {
  3882. return zero(result.slice(0, index)).concat([step]);
  3883. } else {
  3884. var size = Math.max(tableSize.minCellWidth(), result[index] + step);
  3885. return zero(result.slice(0, index)).concat([size - result[index]]);
  3886. }
  3887. };
  3888. return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
  3889. };
  3890. var Deltas = { determine: determine };
  3891. var getSpan$1 = function (cell, type) {
  3892. return has$1(cell, type) && parseInt(get$1(cell, type), 10) > 1;
  3893. };
  3894. var hasColspan = function (cell) {
  3895. return getSpan$1(cell, 'colspan');
  3896. };
  3897. var hasRowspan = function (cell) {
  3898. return getSpan$1(cell, 'rowspan');
  3899. };
  3900. var getInt = function (element, property) {
  3901. return parseInt(get$2(element, property), 10);
  3902. };
  3903. var CellUtils = {
  3904. hasColspan: hasColspan,
  3905. hasRowspan: hasRowspan,
  3906. minWidth: constant(10),
  3907. minHeight: constant(10),
  3908. getInt: getInt
  3909. };
  3910. var getRaw$1 = function (cell, property, getter) {
  3911. return getRaw(cell, property).fold(function () {
  3912. return getter(cell) + 'px';
  3913. }, function (raw) {
  3914. return raw;
  3915. });
  3916. };
  3917. var getRawW = function (cell, tableSize) {
  3918. return getRaw$1(cell, 'width', function (e) {
  3919. return Sizes.getPixelWidth(e, tableSize);
  3920. });
  3921. };
  3922. var getRawH = function (cell) {
  3923. return getRaw$1(cell, 'height', Sizes.getHeight);
  3924. };
  3925. var getWidthFrom = function (warehouse, direction, getWidth, fallback, tableSize) {
  3926. var columns = Blocks.columns(warehouse);
  3927. var backups = map(columns, function (cellOption) {
  3928. return cellOption.map(direction.edge);
  3929. });
  3930. return map(columns, function (cellOption, c) {
  3931. var columnCell = cellOption.filter(not(CellUtils.hasColspan));
  3932. return columnCell.fold(function () {
  3933. var deduced = deduce(backups, c);
  3934. return fallback(deduced);
  3935. }, function (cell) {
  3936. return getWidth(cell, tableSize);
  3937. });
  3938. });
  3939. };
  3940. var getDeduced = function (deduced) {
  3941. return deduced.map(function (d) {
  3942. return d + 'px';
  3943. }).getOr('');
  3944. };
  3945. var getRawWidths = function (warehouse, direction, tableSize) {
  3946. return getWidthFrom(warehouse, direction, getRawW, getDeduced, tableSize);
  3947. };
  3948. var getPercentageWidths = function (warehouse, direction, tableSize) {
  3949. return getWidthFrom(warehouse, direction, Sizes.getPercentageWidth, function (deduced) {
  3950. return deduced.fold(function () {
  3951. return tableSize.minCellWidth();
  3952. }, function (cellWidth) {
  3953. return cellWidth / tableSize.pixelWidth() * 100;
  3954. });
  3955. }, tableSize);
  3956. };
  3957. var getPixelWidths = function (warehouse, direction, tableSize) {
  3958. return getWidthFrom(warehouse, direction, Sizes.getPixelWidth, function (deduced) {
  3959. return deduced.getOrThunk(tableSize.minCellWidth);
  3960. }, tableSize);
  3961. };
  3962. var getHeightFrom = function (warehouse, direction, getHeight, fallback) {
  3963. var rows = Blocks.rows(warehouse);
  3964. var backups = map(rows, function (cellOption) {
  3965. return cellOption.map(direction.edge);
  3966. });
  3967. return map(rows, function (cellOption, c) {
  3968. var rowCell = cellOption.filter(not(CellUtils.hasRowspan));
  3969. return rowCell.fold(function () {
  3970. var deduced = deduce(backups, c);
  3971. return fallback(deduced);
  3972. }, function (cell) {
  3973. return getHeight(cell);
  3974. });
  3975. });
  3976. };
  3977. var getPixelHeights = function (warehouse, direction) {
  3978. return getHeightFrom(warehouse, direction, Sizes.getHeight, function (deduced) {
  3979. return deduced.getOrThunk(CellUtils.minHeight);
  3980. });
  3981. };
  3982. var getRawHeights = function (warehouse, direction) {
  3983. return getHeightFrom(warehouse, direction, getRawH, getDeduced);
  3984. };
  3985. var ColumnSizes = {
  3986. getRawWidths: getRawWidths,
  3987. getPixelWidths: getPixelWidths,
  3988. getPercentageWidths: getPercentageWidths,
  3989. getPixelHeights: getPixelHeights,
  3990. getRawHeights: getRawHeights
  3991. };
  3992. var total = function (start, end, measures) {
  3993. var r = 0;
  3994. for (var i = start; i < end; i++) {
  3995. r += measures[i] !== undefined ? measures[i] : 0;
  3996. }
  3997. return r;
  3998. };
  3999. var recalculateWidth = function (warehouse, widths) {
  4000. var all = Warehouse.justCells(warehouse);
  4001. return map(all, function (cell) {
  4002. var width = total(cell.column(), cell.column() + cell.colspan(), widths);
  4003. return {
  4004. element: cell.element,
  4005. width: constant(width),
  4006. colspan: cell.colspan
  4007. };
  4008. });
  4009. };
  4010. var recalculateHeight = function (warehouse, heights) {
  4011. var all = Warehouse.justCells(warehouse);
  4012. return map(all, function (cell) {
  4013. var height = total(cell.row(), cell.row() + cell.rowspan(), heights);
  4014. return {
  4015. element: cell.element,
  4016. height: constant(height),
  4017. rowspan: cell.rowspan
  4018. };
  4019. });
  4020. };
  4021. var matchRowHeight = function (warehouse, heights) {
  4022. return map(warehouse.all(), function (row, i) {
  4023. return {
  4024. element: row.element,
  4025. height: constant(heights[i])
  4026. };
  4027. });
  4028. };
  4029. var Recalculations = {
  4030. recalculateWidth: recalculateWidth,
  4031. recalculateHeight: recalculateHeight,
  4032. matchRowHeight: matchRowHeight
  4033. };
  4034. var percentageSize = function (width, element) {
  4035. var floatWidth = parseFloat(width);
  4036. var pixelWidth = get$5(element);
  4037. var getCellDelta = function (delta) {
  4038. return delta / pixelWidth * 100;
  4039. };
  4040. var singleColumnWidth = function (w, _delta) {
  4041. return [100 - w];
  4042. };
  4043. var minCellWidth = function () {
  4044. return CellUtils.minWidth() / pixelWidth * 100;
  4045. };
  4046. var setTableWidth = function (table, _newWidths, delta) {
  4047. var ratio = delta / 100;
  4048. var change = ratio * floatWidth;
  4049. Sizes.setPercentageWidth(table, floatWidth + change);
  4050. };
  4051. return {
  4052. width: constant(floatWidth),
  4053. pixelWidth: constant(pixelWidth),
  4054. getWidths: ColumnSizes.getPercentageWidths,
  4055. getCellDelta: getCellDelta,
  4056. singleColumnWidth: singleColumnWidth,
  4057. minCellWidth: minCellWidth,
  4058. setElementWidth: Sizes.setPercentageWidth,
  4059. setTableWidth: setTableWidth
  4060. };
  4061. };
  4062. var pixelSize = function (width) {
  4063. var getCellDelta = identity;
  4064. var singleColumnWidth = function (w, delta) {
  4065. var newNext = Math.max(CellUtils.minWidth(), w + delta);
  4066. return [newNext - w];
  4067. };
  4068. var setTableWidth = function (table, newWidths, _delta) {
  4069. var total = foldr(newWidths, function (b, a) {
  4070. return b + a;
  4071. }, 0);
  4072. Sizes.setPixelWidth(table, total);
  4073. };
  4074. return {
  4075. width: constant(width),
  4076. pixelWidth: constant(width),
  4077. getWidths: ColumnSizes.getPixelWidths,
  4078. getCellDelta: getCellDelta,
  4079. singleColumnWidth: singleColumnWidth,
  4080. minCellWidth: CellUtils.minWidth,
  4081. setElementWidth: Sizes.setPixelWidth,
  4082. setTableWidth: setTableWidth
  4083. };
  4084. };
  4085. var chooseSize = function (element, width) {
  4086. var percentMatch = Sizes.percentageBasedSizeRegex().exec(width);
  4087. if (percentMatch !== null) {
  4088. return percentageSize(percentMatch[1], element);
  4089. }
  4090. var pixelMatch = Sizes.pixelBasedSizeRegex().exec(width);
  4091. if (pixelMatch !== null) {
  4092. var intWidth = parseInt(pixelMatch[1], 10);
  4093. return pixelSize(intWidth);
  4094. }
  4095. var fallbackWidth = get$5(element);
  4096. return pixelSize(fallbackWidth);
  4097. };
  4098. var getTableSize = function (element) {
  4099. var width = Sizes.getRawWidth(element);
  4100. return width.fold(function () {
  4101. var fallbackWidth = get$5(element);
  4102. return pixelSize(fallbackWidth);
  4103. }, function (w) {
  4104. return chooseSize(element, w);
  4105. });
  4106. };
  4107. var TableSize = { getTableSize: getTableSize };
  4108. var getWarehouse$1 = function (list) {
  4109. return Warehouse.generate(list);
  4110. };
  4111. var sumUp = function (newSize) {
  4112. return foldr(newSize, function (b, a) {
  4113. return b + a;
  4114. }, 0);
  4115. };
  4116. var getTableWarehouse = function (table) {
  4117. var list = DetailsList.fromTable(table);
  4118. return getWarehouse$1(list);
  4119. };
  4120. var adjustWidth = function (table, delta, index, direction) {
  4121. var tableSize = TableSize.getTableSize(table);
  4122. var step = tableSize.getCellDelta(delta);
  4123. var warehouse = getTableWarehouse(table);
  4124. var widths = tableSize.getWidths(warehouse, direction, tableSize);
  4125. var deltas = Deltas.determine(widths, index, step, tableSize);
  4126. var newWidths = map(deltas, function (dx, i) {
  4127. return dx + widths[i];
  4128. });
  4129. var newSizes = Recalculations.recalculateWidth(warehouse, newWidths);
  4130. each(newSizes, function (cell) {
  4131. tableSize.setElementWidth(cell.element(), cell.width());
  4132. });
  4133. if (index === warehouse.grid().columns() - 1) {
  4134. tableSize.setTableWidth(table, newWidths, step);
  4135. }
  4136. };
  4137. var adjustHeight = function (table, delta, index, direction) {
  4138. var warehouse = getTableWarehouse(table);
  4139. var heights = ColumnSizes.getPixelHeights(warehouse, direction);
  4140. var newHeights = map(heights, function (dy, i) {
  4141. return index === i ? Math.max(delta + dy, CellUtils.minHeight()) : dy;
  4142. });
  4143. var newCellSizes = Recalculations.recalculateHeight(warehouse, newHeights);
  4144. var newRowSizes = Recalculations.matchRowHeight(warehouse, newHeights);
  4145. each(newRowSizes, function (row) {
  4146. Sizes.setHeight(row.element(), row.height());
  4147. });
  4148. each(newCellSizes, function (cell) {
  4149. Sizes.setHeight(cell.element(), cell.height());
  4150. });
  4151. var total = sumUp(newHeights);
  4152. Sizes.setHeight(table, total);
  4153. };
  4154. var adjustWidthTo = function (table, list, direction) {
  4155. var tableSize = TableSize.getTableSize(table);
  4156. var warehouse = getWarehouse$1(list);
  4157. var widths = tableSize.getWidths(warehouse, direction, tableSize);
  4158. var newSizes = Recalculations.recalculateWidth(warehouse, widths);
  4159. each(newSizes, function (cell) {
  4160. tableSize.setElementWidth(cell.element(), cell.width());
  4161. });
  4162. if (newSizes.length > 0) {
  4163. tableSize.setTableWidth(table, widths, tableSize.getCellDelta(0));
  4164. }
  4165. };
  4166. var Adjustments = {
  4167. adjustWidth: adjustWidth,
  4168. adjustHeight: adjustHeight,
  4169. adjustWidthTo: adjustWidthTo
  4170. };
  4171. var base = function (handleUnsupported, required) {
  4172. return baseWith(handleUnsupported, required, {
  4173. validate: isFunction,
  4174. label: 'function'
  4175. });
  4176. };
  4177. var baseWith = function (handleUnsupported, required, pred) {
  4178. if (required.length === 0) {
  4179. throw new Error('You must specify at least one required field.');
  4180. }
  4181. validateStrArr('required', required);
  4182. checkDupes(required);
  4183. return function (obj) {
  4184. var keys$1 = keys(obj);
  4185. var allReqd = forall(required, function (req) {
  4186. return contains(keys$1, req);
  4187. });
  4188. if (!allReqd) {
  4189. reqMessage(required, keys$1);
  4190. }
  4191. handleUnsupported(required, keys$1);
  4192. var invalidKeys = filter(required, function (key) {
  4193. return !pred.validate(obj[key], key);
  4194. });
  4195. if (invalidKeys.length > 0) {
  4196. invalidTypeMessage(invalidKeys, pred.label);
  4197. }
  4198. return obj;
  4199. };
  4200. };
  4201. var handleExact = function (required, keys) {
  4202. var unsupported = filter(keys, function (key) {
  4203. return !contains(required, key);
  4204. });
  4205. if (unsupported.length > 0) {
  4206. unsuppMessage(unsupported);
  4207. }
  4208. };
  4209. var exactly = function (required) {
  4210. return base(handleExact, required);
  4211. };
  4212. var verifyGenerators = exactly([
  4213. 'cell',
  4214. 'row',
  4215. 'replace',
  4216. 'gap'
  4217. ]);
  4218. var elementToData = function (element) {
  4219. var colspan = has$1(element, 'colspan') ? parseInt(get$1(element, 'colspan'), 10) : 1;
  4220. var rowspan = has$1(element, 'rowspan') ? parseInt(get$1(element, 'rowspan'), 10) : 1;
  4221. return {
  4222. element: constant(element),
  4223. colspan: constant(colspan),
  4224. rowspan: constant(rowspan)
  4225. };
  4226. };
  4227. var modification = function (generators, toData) {
  4228. if (toData === void 0) {
  4229. toData = elementToData;
  4230. }
  4231. verifyGenerators(generators);
  4232. var position = Cell(Option.none());
  4233. var nu = function (data) {
  4234. return generators.cell(data);
  4235. };
  4236. var nuFrom = function (element) {
  4237. var data = toData(element);
  4238. return nu(data);
  4239. };
  4240. var add = function (element) {
  4241. var replacement = nuFrom(element);
  4242. if (position.get().isNone()) {
  4243. position.set(Option.some(replacement));
  4244. }
  4245. recent = Option.some({
  4246. item: element,
  4247. replacement: replacement
  4248. });
  4249. return replacement;
  4250. };
  4251. var recent = Option.none();
  4252. var getOrInit = function (element, comparator) {
  4253. return recent.fold(function () {
  4254. return add(element);
  4255. }, function (p) {
  4256. return comparator(element, p.item) ? p.replacement : add(element);
  4257. });
  4258. };
  4259. return {
  4260. getOrInit: getOrInit,
  4261. cursor: position.get
  4262. };
  4263. };
  4264. var transform = function (scope, tag) {
  4265. return function (generators) {
  4266. var position = Cell(Option.none());
  4267. verifyGenerators(generators);
  4268. var list = [];
  4269. var find$1 = function (element, comparator) {
  4270. return find(list, function (x) {
  4271. return comparator(x.item, element);
  4272. });
  4273. };
  4274. var makeNew = function (element) {
  4275. var attrs = { scope: scope };
  4276. var cell = generators.replace(element, tag, attrs);
  4277. list.push({
  4278. item: element,
  4279. sub: cell
  4280. });
  4281. if (position.get().isNone()) {
  4282. position.set(Option.some(cell));
  4283. }
  4284. return cell;
  4285. };
  4286. var replaceOrInit = function (element, comparator) {
  4287. return find$1(element, comparator).fold(function () {
  4288. return makeNew(element);
  4289. }, function (p) {
  4290. return comparator(element, p.item) ? p.sub : makeNew(element);
  4291. });
  4292. };
  4293. return {
  4294. replaceOrInit: replaceOrInit,
  4295. cursor: position.get
  4296. };
  4297. };
  4298. };
  4299. var merging = function (generators) {
  4300. verifyGenerators(generators);
  4301. var position = Cell(Option.none());
  4302. var combine = function (cell) {
  4303. if (position.get().isNone()) {
  4304. position.set(Option.some(cell));
  4305. }
  4306. return function () {
  4307. var raw = generators.cell({
  4308. element: constant(cell),
  4309. colspan: constant(1),
  4310. rowspan: constant(1)
  4311. });
  4312. remove$1(raw, 'width');
  4313. remove$1(cell, 'width');
  4314. return raw;
  4315. };
  4316. };
  4317. return {
  4318. combine: combine,
  4319. cursor: position.get
  4320. };
  4321. };
  4322. var Generators = {
  4323. modification: modification,
  4324. transform: transform,
  4325. merging: merging
  4326. };
  4327. var blockList = [
  4328. 'body',
  4329. 'p',
  4330. 'div',
  4331. 'article',
  4332. 'aside',
  4333. 'figcaption',
  4334. 'figure',
  4335. 'footer',
  4336. 'header',
  4337. 'nav',
  4338. 'section',
  4339. 'ol',
  4340. 'ul',
  4341. 'table',
  4342. 'thead',
  4343. 'tfoot',
  4344. 'tbody',
  4345. 'caption',
  4346. 'tr',
  4347. 'td',
  4348. 'th',
  4349. 'h1',
  4350. 'h2',
  4351. 'h3',
  4352. 'h4',
  4353. 'h5',
  4354. 'h6',
  4355. 'blockquote',
  4356. 'pre',
  4357. 'address'
  4358. ];
  4359. var isList = function (universe, item) {
  4360. var tagName = universe.property().name(item);
  4361. return contains([
  4362. 'ol',
  4363. 'ul'
  4364. ], tagName);
  4365. };
  4366. var isBlock = function (universe, item) {
  4367. var tagName = universe.property().name(item);
  4368. return contains(blockList, tagName);
  4369. };
  4370. var isFormatting = function (universe, item) {
  4371. var tagName = universe.property().name(item);
  4372. return contains([
  4373. 'address',
  4374. 'pre',
  4375. 'p',
  4376. 'h1',
  4377. 'h2',
  4378. 'h3',
  4379. 'h4',
  4380. 'h5',
  4381. 'h6'
  4382. ], tagName);
  4383. };
  4384. var isHeading = function (universe, item) {
  4385. var tagName = universe.property().name(item);
  4386. return contains([
  4387. 'h1',
  4388. 'h2',
  4389. 'h3',
  4390. 'h4',
  4391. 'h5',
  4392. 'h6'
  4393. ], tagName);
  4394. };
  4395. var isContainer = function (universe, item) {
  4396. return contains([
  4397. 'div',
  4398. 'li',
  4399. 'td',
  4400. 'th',
  4401. 'blockquote',
  4402. 'body',
  4403. 'caption'
  4404. ], universe.property().name(item));
  4405. };
  4406. var isEmptyTag = function (universe, item) {
  4407. return contains([
  4408. 'br',
  4409. 'img',
  4410. 'hr',
  4411. 'input'
  4412. ], universe.property().name(item));
  4413. };
  4414. var isFrame = function (universe, item) {
  4415. return universe.property().name(item) === 'iframe';
  4416. };
  4417. var isInline = function (universe, item) {
  4418. return !(isBlock(universe, item) || isEmptyTag(universe, item)) && universe.property().name(item) !== 'li';
  4419. };
  4420. var Structure = {
  4421. isBlock: isBlock,
  4422. isList: isList,
  4423. isFormatting: isFormatting,
  4424. isHeading: isHeading,
  4425. isContainer: isContainer,
  4426. isEmptyTag: isEmptyTag,
  4427. isFrame: isFrame,
  4428. isInline: isInline
  4429. };
  4430. var universe$1 = DomUniverse();
  4431. var isBlock$1 = function (element) {
  4432. return Structure.isBlock(universe$1, element);
  4433. };
  4434. var isList$1 = function (element) {
  4435. return Structure.isList(universe$1, element);
  4436. };
  4437. var isFormatting$1 = function (element) {
  4438. return Structure.isFormatting(universe$1, element);
  4439. };
  4440. var isHeading$1 = function (element) {
  4441. return Structure.isHeading(universe$1, element);
  4442. };
  4443. var isContainer$1 = function (element) {
  4444. return Structure.isContainer(universe$1, element);
  4445. };
  4446. var isEmptyTag$1 = function (element) {
  4447. return Structure.isEmptyTag(universe$1, element);
  4448. };
  4449. var isFrame$1 = function (element) {
  4450. return Structure.isFrame(universe$1, element);
  4451. };
  4452. var isInline$1 = function (element) {
  4453. return Structure.isInline(universe$1, element);
  4454. };
  4455. var DomStructure = {
  4456. isBlock: isBlock$1,
  4457. isList: isList$1,
  4458. isFormatting: isFormatting$1,
  4459. isHeading: isHeading$1,
  4460. isContainer: isContainer$1,
  4461. isEmptyTag: isEmptyTag$1,
  4462. isFrame: isFrame$1,
  4463. isInline: isInline$1
  4464. };
  4465. var merge$2 = function (cells) {
  4466. var isBr = function (el) {
  4467. return name(el) === 'br';
  4468. };
  4469. var advancedBr = function (children) {
  4470. return forall(children, function (c) {
  4471. return isBr(c) || isText(c) && get$3(c).trim().length === 0;
  4472. });
  4473. };
  4474. var isListItem = function (el) {
  4475. return name(el) === 'li' || ancestor(el, DomStructure.isList).isSome();
  4476. };
  4477. var siblingIsBlock = function (el) {
  4478. return nextSibling(el).map(function (rightSibling) {
  4479. if (DomStructure.isBlock(rightSibling)) {
  4480. return true;
  4481. }
  4482. if (DomStructure.isEmptyTag(rightSibling)) {
  4483. return name(rightSibling) === 'img' ? false : true;
  4484. }
  4485. return false;
  4486. }).getOr(false);
  4487. };
  4488. var markCell = function (cell) {
  4489. return last$1(cell).bind(function (rightEdge) {
  4490. var rightSiblingIsBlock = siblingIsBlock(rightEdge);
  4491. return parent(rightEdge).map(function (parent) {
  4492. return rightSiblingIsBlock === true || isListItem(parent) || isBr(rightEdge) || DomStructure.isBlock(parent) && !eq(cell, parent) ? [] : [Element.fromTag('br')];
  4493. });
  4494. }).getOr([]);
  4495. };
  4496. var markContent = function () {
  4497. var content = bind(cells, function (cell) {
  4498. var children$1 = children(cell);
  4499. return advancedBr(children$1) ? [] : children$1.concat(markCell(cell));
  4500. });
  4501. return content.length === 0 ? [Element.fromTag('br')] : content;
  4502. };
  4503. var contents = markContent();
  4504. empty(cells[0]);
  4505. append$1(cells[0], contents);
  4506. };
  4507. var TableContent = { merge: merge$2 };
  4508. var prune = function (table) {
  4509. var cells = TableLookup.cells(table);
  4510. if (cells.length === 0) {
  4511. remove$2(table);
  4512. }
  4513. };
  4514. var outcome = Immutable('grid', 'cursor');
  4515. var elementFromGrid = function (grid, row, column) {
  4516. return findIn(grid, row, column).orThunk(function () {
  4517. return findIn(grid, 0, 0);
  4518. });
  4519. };
  4520. var findIn = function (grid, row, column) {
  4521. return Option.from(grid[row]).bind(function (r) {
  4522. return Option.from(r.cells()[column]).bind(function (c) {
  4523. return Option.from(c.element());
  4524. });
  4525. });
  4526. };
  4527. var bundle = function (grid, row, column) {
  4528. return outcome(grid, findIn(grid, row, column));
  4529. };
  4530. var uniqueRows = function (details) {
  4531. return foldl(details, function (rest, detail) {
  4532. return exists(rest, function (currentDetail) {
  4533. return currentDetail.row() === detail.row();
  4534. }) ? rest : rest.concat([detail]);
  4535. }, []).sort(function (detailA, detailB) {
  4536. return detailA.row() - detailB.row();
  4537. });
  4538. };
  4539. var uniqueColumns = function (details) {
  4540. return foldl(details, function (rest, detail) {
  4541. return exists(rest, function (currentDetail) {
  4542. return currentDetail.column() === detail.column();
  4543. }) ? rest : rest.concat([detail]);
  4544. }, []).sort(function (detailA, detailB) {
  4545. return detailA.column() - detailB.column();
  4546. });
  4547. };
  4548. var insertRowBefore = function (grid, detail, comparator, genWrappers) {
  4549. var example = detail.row();
  4550. var targetIndex = detail.row();
  4551. var newGrid = ModificationOperations.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
  4552. return bundle(newGrid, targetIndex, detail.column());
  4553. };
  4554. var insertRowsBefore = function (grid, details, comparator, genWrappers) {
  4555. var example = details[0].row();
  4556. var targetIndex = details[0].row();
  4557. var rows = uniqueRows(details);
  4558. var newGrid = foldl(rows, function (newG, _row) {
  4559. return ModificationOperations.insertRowAt(newG, targetIndex, example, comparator, genWrappers.getOrInit);
  4560. }, grid);
  4561. return bundle(newGrid, targetIndex, details[0].column());
  4562. };
  4563. var insertRowAfter = function (grid, detail, comparator, genWrappers) {
  4564. var example = detail.row();
  4565. var targetIndex = detail.row() + detail.rowspan();
  4566. var newGrid = ModificationOperations.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
  4567. return bundle(newGrid, targetIndex, detail.column());
  4568. };
  4569. var insertRowsAfter = function (grid, details, comparator, genWrappers) {
  4570. var rows = uniqueRows(details);
  4571. var example = rows[rows.length - 1].row();
  4572. var targetIndex = rows[rows.length - 1].row() + rows[rows.length - 1].rowspan();
  4573. var newGrid = foldl(rows, function (newG, _row) {
  4574. return ModificationOperations.insertRowAt(newG, targetIndex, example, comparator, genWrappers.getOrInit);
  4575. }, grid);
  4576. return bundle(newGrid, targetIndex, details[0].column());
  4577. };
  4578. var insertColumnBefore = function (grid, detail, comparator, genWrappers) {
  4579. var example = detail.column();
  4580. var targetIndex = detail.column();
  4581. var newGrid = ModificationOperations.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
  4582. return bundle(newGrid, detail.row(), targetIndex);
  4583. };
  4584. var insertColumnsBefore = function (grid, details, comparator, genWrappers) {
  4585. var columns = uniqueColumns(details);
  4586. var example = columns[0].column();
  4587. var targetIndex = columns[0].column();
  4588. var newGrid = foldl(columns, function (newG, _row) {
  4589. return ModificationOperations.insertColumnAt(newG, targetIndex, example, comparator, genWrappers.getOrInit);
  4590. }, grid);
  4591. return bundle(newGrid, details[0].row(), targetIndex);
  4592. };
  4593. var insertColumnAfter = function (grid, detail, comparator, genWrappers) {
  4594. var example = detail.column();
  4595. var targetIndex = detail.column() + detail.colspan();
  4596. var newGrid = ModificationOperations.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
  4597. return bundle(newGrid, detail.row(), targetIndex);
  4598. };
  4599. var insertColumnsAfter = function (grid, details, comparator, genWrappers) {
  4600. var example = details[details.length - 1].column();
  4601. var targetIndex = details[details.length - 1].column() + details[details.length - 1].colspan();
  4602. var columns = uniqueColumns(details);
  4603. var newGrid = foldl(columns, function (newG, _row) {
  4604. return ModificationOperations.insertColumnAt(newG, targetIndex, example, comparator, genWrappers.getOrInit);
  4605. }, grid);
  4606. return bundle(newGrid, details[0].row(), targetIndex);
  4607. };
  4608. var makeRowHeader = function (grid, detail, comparator, genWrappers) {
  4609. var newGrid = TransformOperations.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
  4610. return bundle(newGrid, detail.row(), detail.column());
  4611. };
  4612. var makeColumnHeader = function (grid, detail, comparator, genWrappers) {
  4613. var newGrid = TransformOperations.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
  4614. return bundle(newGrid, detail.row(), detail.column());
  4615. };
  4616. var unmakeRowHeader = function (grid, detail, comparator, genWrappers) {
  4617. var newGrid = TransformOperations.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
  4618. return bundle(newGrid, detail.row(), detail.column());
  4619. };
  4620. var unmakeColumnHeader = function (grid, detail, comparator, genWrappers) {
  4621. var newGrid = TransformOperations.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
  4622. return bundle(newGrid, detail.row(), detail.column());
  4623. };
  4624. var splitCellIntoColumns$1 = function (grid, detail, comparator, genWrappers) {
  4625. var newGrid = ModificationOperations.splitCellIntoColumns(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
  4626. return bundle(newGrid, detail.row(), detail.column());
  4627. };
  4628. var splitCellIntoRows$1 = function (grid, detail, comparator, genWrappers) {
  4629. var newGrid = ModificationOperations.splitCellIntoRows(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
  4630. return bundle(newGrid, detail.row(), detail.column());
  4631. };
  4632. var eraseColumns = function (grid, details, _comparator, _genWrappers) {
  4633. var columns = uniqueColumns(details);
  4634. var newGrid = ModificationOperations.deleteColumnsAt(grid, columns[0].column(), columns[columns.length - 1].column());
  4635. var cursor = elementFromGrid(newGrid, details[0].row(), details[0].column());
  4636. return outcome(newGrid, cursor);
  4637. };
  4638. var eraseRows = function (grid, details, _comparator, _genWrappers) {
  4639. var rows = uniqueRows(details);
  4640. var newGrid = ModificationOperations.deleteRowsAt(grid, rows[0].row(), rows[rows.length - 1].row());
  4641. var cursor = elementFromGrid(newGrid, details[0].row(), details[0].column());
  4642. return outcome(newGrid, cursor);
  4643. };
  4644. var mergeCells = function (grid, mergable, comparator, _genWrappers) {
  4645. var cells = mergable.cells();
  4646. TableContent.merge(cells);
  4647. var newGrid = MergingOperations.merge(grid, mergable.bounds(), comparator, constant(cells[0]));
  4648. return outcome(newGrid, Option.from(cells[0]));
  4649. };
  4650. var unmergeCells = function (grid, unmergable, comparator, genWrappers) {
  4651. var newGrid = foldr(unmergable, function (b, cell) {
  4652. return MergingOperations.unmerge(b, cell, comparator, genWrappers.combine(cell));
  4653. }, grid);
  4654. return outcome(newGrid, Option.from(unmergable[0]));
  4655. };
  4656. var pasteCells = function (grid, pasteDetails, comparator, _genWrappers) {
  4657. var gridify = function (table, generators) {
  4658. var list = DetailsList.fromTable(table);
  4659. var wh = Warehouse.generate(list);
  4660. return Transitions.toGrid(wh, generators, true);
  4661. };
  4662. var gridB = gridify(pasteDetails.clipboard(), pasteDetails.generators());
  4663. var startAddress = address(pasteDetails.row(), pasteDetails.column());
  4664. var mergedGrid = TableMerge.merge(startAddress, grid, gridB, pasteDetails.generators(), comparator);
  4665. return mergedGrid.fold(function () {
  4666. return outcome(grid, Option.some(pasteDetails.element()));
  4667. }, function (nuGrid) {
  4668. var cursor = elementFromGrid(nuGrid, pasteDetails.row(), pasteDetails.column());
  4669. return outcome(nuGrid, cursor);
  4670. });
  4671. };
  4672. var gridifyRows = function (rows, generators, example) {
  4673. var pasteDetails = DetailsList.fromPastedRows(rows, example);
  4674. var wh = Warehouse.generate(pasteDetails);
  4675. return Transitions.toGrid(wh, generators, true);
  4676. };
  4677. var pasteRowsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  4678. var example = grid[pasteDetails.cells[0].row()];
  4679. var index = pasteDetails.cells[0].row();
  4680. var gridB = gridifyRows(pasteDetails.clipboard(), pasteDetails.generators(), example);
  4681. var mergedGrid = TableMerge.insert(index, grid, gridB, pasteDetails.generators(), comparator);
  4682. var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row(), pasteDetails.cells[0].column());
  4683. return outcome(mergedGrid, cursor);
  4684. };
  4685. var pasteRowsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  4686. var example = grid[pasteDetails.cells[0].row()];
  4687. var index = pasteDetails.cells[pasteDetails.cells.length - 1].row() + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan();
  4688. var gridB = gridifyRows(pasteDetails.clipboard(), pasteDetails.generators(), example);
  4689. var mergedGrid = TableMerge.insert(index, grid, gridB, pasteDetails.generators(), comparator);
  4690. var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row(), pasteDetails.cells[0].column());
  4691. return outcome(mergedGrid, cursor);
  4692. };
  4693. var resize = Adjustments.adjustWidthTo;
  4694. var TableOperations = {
  4695. insertRowBefore: run(insertRowBefore, onCell, noop, noop, Generators.modification),
  4696. insertRowsBefore: run(insertRowsBefore, onCells, noop, noop, Generators.modification),
  4697. insertRowAfter: run(insertRowAfter, onCell, noop, noop, Generators.modification),
  4698. insertRowsAfter: run(insertRowsAfter, onCells, noop, noop, Generators.modification),
  4699. insertColumnBefore: run(insertColumnBefore, onCell, resize, noop, Generators.modification),
  4700. insertColumnsBefore: run(insertColumnsBefore, onCells, resize, noop, Generators.modification),
  4701. insertColumnAfter: run(insertColumnAfter, onCell, resize, noop, Generators.modification),
  4702. insertColumnsAfter: run(insertColumnsAfter, onCells, resize, noop, Generators.modification),
  4703. splitCellIntoColumns: run(splitCellIntoColumns$1, onCell, resize, noop, Generators.modification),
  4704. splitCellIntoRows: run(splitCellIntoRows$1, onCell, noop, noop, Generators.modification),
  4705. eraseColumns: run(eraseColumns, onCells, resize, prune, Generators.modification),
  4706. eraseRows: run(eraseRows, onCells, noop, prune, Generators.modification),
  4707. makeColumnHeader: run(makeColumnHeader, onCell, noop, noop, Generators.transform('row', 'th')),
  4708. unmakeColumnHeader: run(unmakeColumnHeader, onCell, noop, noop, Generators.transform(null, 'td')),
  4709. makeRowHeader: run(makeRowHeader, onCell, noop, noop, Generators.transform('col', 'th')),
  4710. unmakeRowHeader: run(unmakeRowHeader, onCell, noop, noop, Generators.transform(null, 'td')),
  4711. mergeCells: run(mergeCells, onMergable, noop, noop, Generators.merging),
  4712. unmergeCells: run(unmergeCells, onUnmergable, resize, noop, Generators.merging),
  4713. pasteCells: run(pasteCells, onPaste, resize, noop, Generators.modification),
  4714. pasteRowsBefore: run(pasteRowsBefore, onPasteRows, noop, noop, Generators.modification),
  4715. pasteRowsAfter: run(pasteRowsAfter, onPasteRows, noop, noop, Generators.modification)
  4716. };
  4717. var getBody$1 = function (editor) {
  4718. return Element.fromDom(editor.getBody());
  4719. };
  4720. var getPixelWidth$1 = function (elm) {
  4721. return elm.getBoundingClientRect().width;
  4722. };
  4723. var getPixelHeight = function (elm) {
  4724. return elm.getBoundingClientRect().height;
  4725. };
  4726. var getIsRoot = function (editor) {
  4727. return function (element) {
  4728. return eq(element, getBody$1(editor));
  4729. };
  4730. };
  4731. var removePxSuffix = function (size) {
  4732. return size ? size.replace(/px$/, '') : '';
  4733. };
  4734. var addSizeSuffix = function (size) {
  4735. if (/^[0-9]+$/.test(size)) {
  4736. size += 'px';
  4737. }
  4738. return size;
  4739. };
  4740. var removeDataStyle = function (table) {
  4741. var dataStyleCells = descendants$1(table, 'td[data-mce-style],th[data-mce-style]');
  4742. remove(table, 'data-mce-style');
  4743. each(dataStyleCells, function (cell) {
  4744. remove(cell, 'data-mce-style');
  4745. });
  4746. };
  4747. var getDirection = function (element) {
  4748. return get$2(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4749. };
  4750. var ltr$1 = { isRtl: constant(false) };
  4751. var rtl$1 = { isRtl: constant(true) };
  4752. var directionAt = function (element) {
  4753. var dir = getDirection(element);
  4754. return dir === 'rtl' ? rtl$1 : ltr$1;
  4755. };
  4756. var Direction = { directionAt: directionAt };
  4757. var defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
  4758. var defaultStyles = {
  4759. 'border-collapse': 'collapse',
  4760. 'width': '100%'
  4761. };
  4762. var defaultAttributes = { border: '1' };
  4763. var getDefaultAttributes = function (editor) {
  4764. return editor.getParam('table_default_attributes', defaultAttributes, 'object');
  4765. };
  4766. var getDefaultStyles = function (editor) {
  4767. return editor.getParam('table_default_styles', defaultStyles, 'object');
  4768. };
  4769. var hasTableResizeBars = function (editor) {
  4770. return editor.getParam('table_resize_bars', true, 'boolean');
  4771. };
  4772. var hasTabNavigation = function (editor) {
  4773. return editor.getParam('table_tab_navigation', true, 'boolean');
  4774. };
  4775. var hasAdvancedCellTab = function (editor) {
  4776. return editor.getParam('table_cell_advtab', true, 'boolean');
  4777. };
  4778. var hasAdvancedRowTab = function (editor) {
  4779. return editor.getParam('table_row_advtab', true, 'boolean');
  4780. };
  4781. var hasAdvancedTableTab = function (editor) {
  4782. return editor.getParam('table_advtab', true, 'boolean');
  4783. };
  4784. var hasAppearanceOptions = function (editor) {
  4785. return editor.getParam('table_appearance_options', true, 'boolean');
  4786. };
  4787. var hasTableGrid = function (editor) {
  4788. return editor.getParam('table_grid', true, 'boolean');
  4789. };
  4790. var shouldStyleWithCss = function (editor) {
  4791. return editor.getParam('table_style_by_css', false, 'boolean');
  4792. };
  4793. var getCellClassList = function (editor) {
  4794. return editor.getParam('table_cell_class_list', [], 'array');
  4795. };
  4796. var getRowClassList = function (editor) {
  4797. return editor.getParam('table_row_class_list', [], 'array');
  4798. };
  4799. var getTableClassList = function (editor) {
  4800. return editor.getParam('table_class_list', [], 'array');
  4801. };
  4802. var isPercentagesForced = function (editor) {
  4803. return editor.getParam('table_responsive_width') === true;
  4804. };
  4805. var isPixelsForced = function (editor) {
  4806. return editor.getParam('table_responsive_width') === false;
  4807. };
  4808. var getToolbar = function (editor) {
  4809. return editor.getParam('table_toolbar', defaultTableToolbar);
  4810. };
  4811. var getCloneElements = function (editor) {
  4812. var cloneElements = editor.getParam('table_clone_elements');
  4813. if (isString(cloneElements)) {
  4814. return Option.some(cloneElements.split(/[ ,]/));
  4815. } else if (Array.isArray(cloneElements)) {
  4816. return Option.some(cloneElements);
  4817. } else {
  4818. return Option.none();
  4819. }
  4820. };
  4821. var hasObjectResizing = function (editor) {
  4822. var objectResizing = editor.getParam('object_resizing', true);
  4823. return isString(objectResizing) ? objectResizing === 'table' : objectResizing;
  4824. };
  4825. var fireNewRow = function (editor, row) {
  4826. return editor.fire('newrow', { node: row });
  4827. };
  4828. var fireNewCell = function (editor, cell) {
  4829. return editor.fire('newcell', { node: cell });
  4830. };
  4831. var fireObjectResizeStart = function (editor, target, width, height) {
  4832. editor.fire('ObjectResizeStart', {
  4833. target: target,
  4834. width: width,
  4835. height: height
  4836. });
  4837. };
  4838. var fireObjectResized = function (editor, target, width, height) {
  4839. editor.fire('ObjectResized', {
  4840. target: target,
  4841. width: width,
  4842. height: height
  4843. });
  4844. };
  4845. var fireTableSelectionChange = function (editor, cells, start, finish, otherCells) {
  4846. editor.fire('tableselectionchange', {
  4847. cells: cells,
  4848. start: start,
  4849. finish: finish,
  4850. otherCells: otherCells
  4851. });
  4852. };
  4853. var fireTableSelectionClear = function (editor) {
  4854. editor.fire('tableselectionclear');
  4855. };
  4856. var TableActions = function (editor, lazyWire) {
  4857. var isTableBody = function (editor) {
  4858. return name(getBody$1(editor)) === 'table';
  4859. };
  4860. var lastRowGuard = function (table) {
  4861. var size = TableGridSize.getGridSize(table);
  4862. return isTableBody(editor) === false || size.rows() > 1;
  4863. };
  4864. var lastColumnGuard = function (table) {
  4865. var size = TableGridSize.getGridSize(table);
  4866. return isTableBody(editor) === false || size.columns() > 1;
  4867. };
  4868. var cloneFormats = getCloneElements(editor);
  4869. var execute = function (operation, guard, mutate, lazyWire) {
  4870. return function (table, target) {
  4871. removeDataStyle(table);
  4872. var wire = lazyWire();
  4873. var doc = Element.fromDom(editor.getDoc());
  4874. var direction = TableDirection(Direction.directionAt);
  4875. var generators = TableFill.cellOperations(mutate, doc, cloneFormats);
  4876. return guard(table) ? operation(wire, table, target, generators, direction).bind(function (result) {
  4877. each(result.newRows(), function (row) {
  4878. fireNewRow(editor, row.dom());
  4879. });
  4880. each(result.newCells(), function (cell) {
  4881. fireNewCell(editor, cell.dom());
  4882. });
  4883. return result.cursor().map(function (cell) {
  4884. var rng = editor.dom.createRng();
  4885. rng.setStart(cell.dom(), 0);
  4886. rng.setEnd(cell.dom(), 0);
  4887. return rng;
  4888. });
  4889. }) : Option.none();
  4890. };
  4891. };
  4892. var deleteRow = execute(TableOperations.eraseRows, lastRowGuard, noop, lazyWire);
  4893. var deleteColumn = execute(TableOperations.eraseColumns, lastColumnGuard, noop, lazyWire);
  4894. var insertRowsBefore = execute(TableOperations.insertRowsBefore, always, noop, lazyWire);
  4895. var insertRowsAfter = execute(TableOperations.insertRowsAfter, always, noop, lazyWire);
  4896. var insertColumnsBefore = execute(TableOperations.insertColumnsBefore, always, CellMutations.halve, lazyWire);
  4897. var insertColumnsAfter = execute(TableOperations.insertColumnsAfter, always, CellMutations.halve, lazyWire);
  4898. var mergeCells = execute(TableOperations.mergeCells, always, noop, lazyWire);
  4899. var unmergeCells = execute(TableOperations.unmergeCells, always, noop, lazyWire);
  4900. var pasteRowsBefore = execute(TableOperations.pasteRowsBefore, always, noop, lazyWire);
  4901. var pasteRowsAfter = execute(TableOperations.pasteRowsAfter, always, noop, lazyWire);
  4902. var pasteCells = execute(TableOperations.pasteCells, always, noop, lazyWire);
  4903. return {
  4904. deleteRow: deleteRow,
  4905. deleteColumn: deleteColumn,
  4906. insertRowsBefore: insertRowsBefore,
  4907. insertRowsAfter: insertRowsAfter,
  4908. insertColumnsBefore: insertColumnsBefore,
  4909. insertColumnsAfter: insertColumnsAfter,
  4910. mergeCells: mergeCells,
  4911. unmergeCells: unmergeCells,
  4912. pasteRowsBefore: pasteRowsBefore,
  4913. pasteRowsAfter: pasteRowsAfter,
  4914. pasteCells: pasteCells
  4915. };
  4916. };
  4917. var copyRows = function (table, target, generators) {
  4918. var list = DetailsList.fromTable(table);
  4919. var house = Warehouse.generate(list);
  4920. var details = onCells(house, target);
  4921. return details.map(function (selectedCells) {
  4922. var grid = Transitions.toGrid(house, generators, false);
  4923. var slicedGrid = grid.slice(selectedCells[0].row(), selectedCells[selectedCells.length - 1].row() + selectedCells[selectedCells.length - 1].rowspan());
  4924. var slicedDetails = toDetailList(slicedGrid, generators);
  4925. return Redraw.copy(slicedDetails);
  4926. });
  4927. };
  4928. var CopyRows = { copyRows: copyRows };
  4929. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  4930. var getTDTHOverallStyle = function (dom, elm, name) {
  4931. var cells = dom.select('td,th', elm);
  4932. var firstChildStyle;
  4933. var checkChildren = function (firstChildStyle, elms) {
  4934. for (var i = 0; i < elms.length; i++) {
  4935. var currentStyle = dom.getStyle(elms[i], name);
  4936. if (typeof firstChildStyle === 'undefined') {
  4937. firstChildStyle = currentStyle;
  4938. }
  4939. if (firstChildStyle !== currentStyle) {
  4940. return '';
  4941. }
  4942. }
  4943. return firstChildStyle;
  4944. };
  4945. firstChildStyle = checkChildren(firstChildStyle, cells);
  4946. return firstChildStyle;
  4947. };
  4948. var applyAlign = function (editor, elm, name) {
  4949. if (name) {
  4950. editor.formatter.apply('align' + name, {}, elm);
  4951. }
  4952. };
  4953. var applyVAlign = function (editor, elm, name) {
  4954. if (name) {
  4955. editor.formatter.apply('valign' + name, {}, elm);
  4956. }
  4957. };
  4958. var unApplyAlign = function (editor, elm) {
  4959. global$1.each('left center right'.split(' '), function (name) {
  4960. editor.formatter.remove('align' + name, {}, elm);
  4961. });
  4962. };
  4963. var unApplyVAlign = function (editor, elm) {
  4964. global$1.each('top middle bottom'.split(' '), function (name) {
  4965. editor.formatter.remove('valign' + name, {}, elm);
  4966. });
  4967. };
  4968. var Styles$1 = {
  4969. applyAlign: applyAlign,
  4970. applyVAlign: applyVAlign,
  4971. unApplyAlign: unApplyAlign,
  4972. unApplyVAlign: unApplyVAlign,
  4973. getTDTHOverallStyle: getTDTHOverallStyle
  4974. };
  4975. var buildListItems = function (inputList, itemCallback, startItems) {
  4976. var appendItems = function (values, output) {
  4977. output = output || [];
  4978. global$1.each(values, function (item) {
  4979. var menuItem = { text: item.text || item.title };
  4980. if (item.menu) {
  4981. menuItem.menu = appendItems(item.menu);
  4982. } else {
  4983. menuItem.value = item.value;
  4984. if (itemCallback) {
  4985. itemCallback(menuItem);
  4986. }
  4987. }
  4988. output.push(menuItem);
  4989. });
  4990. return output;
  4991. };
  4992. return appendItems(inputList, startItems || []);
  4993. };
  4994. var extractAdvancedStyles = function (dom, elm) {
  4995. var rgbToHex = function (value) {
  4996. return startsWith(value, 'rgb') ? dom.toHex(value) : value;
  4997. };
  4998. var borderWidth = getRaw(Element.fromDom(elm), 'border-width').getOr('');
  4999. var borderStyle = getRaw(Element.fromDom(elm), 'border-style').getOr('');
  5000. var borderColor = getRaw(Element.fromDom(elm), 'border-color').map(rgbToHex).getOr('');
  5001. var bgColor = getRaw(Element.fromDom(elm), 'background-color').map(rgbToHex).getOr('');
  5002. return {
  5003. borderwidth: borderWidth,
  5004. borderstyle: borderStyle,
  5005. bordercolor: borderColor,
  5006. backgroundcolor: bgColor
  5007. };
  5008. };
  5009. var getSharedValues = function (data) {
  5010. var baseData = data[0];
  5011. var comparisonData = data.slice(1);
  5012. var keys$1 = keys(baseData);
  5013. each(comparisonData, function (items) {
  5014. each(keys$1, function (key) {
  5015. each$1(items, function (itemValue, itemKey) {
  5016. var comparisonValue = baseData[key];
  5017. if (comparisonValue !== '' && key === itemKey) {
  5018. if (comparisonValue !== itemValue) {
  5019. baseData[key] = '';
  5020. }
  5021. }
  5022. });
  5023. });
  5024. });
  5025. return baseData;
  5026. };
  5027. var getAdvancedTab = function (dialogName) {
  5028. var advTabItems = [
  5029. {
  5030. name: 'borderstyle',
  5031. type: 'selectbox',
  5032. label: 'Border style',
  5033. items: [
  5034. {
  5035. text: 'Select...',
  5036. value: ''
  5037. },
  5038. {
  5039. text: 'Solid',
  5040. value: 'solid'
  5041. },
  5042. {
  5043. text: 'Dotted',
  5044. value: 'dotted'
  5045. },
  5046. {
  5047. text: 'Dashed',
  5048. value: 'dashed'
  5049. },
  5050. {
  5051. text: 'Double',
  5052. value: 'double'
  5053. },
  5054. {
  5055. text: 'Groove',
  5056. value: 'groove'
  5057. },
  5058. {
  5059. text: 'Ridge',
  5060. value: 'ridge'
  5061. },
  5062. {
  5063. text: 'Inset',
  5064. value: 'inset'
  5065. },
  5066. {
  5067. text: 'Outset',
  5068. value: 'outset'
  5069. },
  5070. {
  5071. text: 'None',
  5072. value: 'none'
  5073. },
  5074. {
  5075. text: 'Hidden',
  5076. value: 'hidden'
  5077. }
  5078. ]
  5079. },
  5080. {
  5081. name: 'bordercolor',
  5082. type: 'colorinput',
  5083. label: 'Border color'
  5084. },
  5085. {
  5086. name: 'backgroundcolor',
  5087. type: 'colorinput',
  5088. label: 'Background color'
  5089. }
  5090. ];
  5091. var borderWidth = {
  5092. name: 'borderwidth',
  5093. type: 'input',
  5094. label: 'Border width'
  5095. };
  5096. var items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
  5097. return {
  5098. title: 'Advanced',
  5099. name: 'advanced',
  5100. items: items
  5101. };
  5102. };
  5103. var getAlignment = function (alignments, formatName, dataName, editor, elm) {
  5104. var alignmentData = {};
  5105. global$1.each(alignments.split(' '), function (name) {
  5106. if (editor.formatter.matchNode(elm, formatName + name)) {
  5107. alignmentData[dataName] = name;
  5108. }
  5109. });
  5110. if (!alignmentData[dataName]) {
  5111. alignmentData[dataName] = '';
  5112. }
  5113. return alignmentData;
  5114. };
  5115. var getHAlignment = curry(getAlignment, 'left center right');
  5116. var getVAlignment = curry(getAlignment, 'top middle bottom');
  5117. var extractDataFromSettings = function (editor, hasAdvTableTab) {
  5118. var style = getDefaultStyles(editor);
  5119. var attrs = getDefaultAttributes(editor);
  5120. var extractAdvancedStyleData = function (dom) {
  5121. var rgbToHex = function (value) {
  5122. return startsWith(value, 'rgb') ? dom.toHex(value) : value;
  5123. };
  5124. var borderStyle = get(style, 'border-style').getOr('');
  5125. var borderColor = get(style, 'border-color').getOr('');
  5126. var bgColor = get(style, 'background-color').getOr('');
  5127. return {
  5128. borderstyle: borderStyle,
  5129. bordercolor: rgbToHex(borderColor),
  5130. backgroundcolor: rgbToHex(bgColor)
  5131. };
  5132. };
  5133. var defaultData = {
  5134. height: '',
  5135. width: '100%',
  5136. cellspacing: '',
  5137. cellpadding: '',
  5138. caption: false,
  5139. class: '',
  5140. align: '',
  5141. border: ''
  5142. };
  5143. var getBorder = function () {
  5144. var borderWidth = style['border-width'];
  5145. if (shouldStyleWithCss(editor) && borderWidth) {
  5146. return { border: borderWidth };
  5147. }
  5148. return get(attrs, 'border').fold(function () {
  5149. return {};
  5150. }, function (border) {
  5151. return { border: border };
  5152. });
  5153. };
  5154. var dom = editor.dom;
  5155. var advStyle = hasAdvTableTab ? extractAdvancedStyleData(dom) : {};
  5156. var getCellPaddingCellSpacing = function () {
  5157. var spacing = get(style, 'border-spacing').or(get(attrs, 'cellspacing')).fold(function () {
  5158. return {};
  5159. }, function (cellspacing) {
  5160. return { cellspacing: cellspacing };
  5161. });
  5162. var padding = get(style, 'border-padding').or(get(attrs, 'cellpadding')).fold(function () {
  5163. return {};
  5164. }, function (cellpadding) {
  5165. return { cellpadding: cellpadding };
  5166. });
  5167. return __assign(__assign({}, spacing), padding);
  5168. };
  5169. var data = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
  5170. return data;
  5171. };
  5172. var extractDataFromTableElement = function (editor, elm, hasAdvTableTab) {
  5173. var getBorder = function (dom, elm) {
  5174. var optBorderWidth = getRaw(Element.fromDom(elm), 'border-width');
  5175. if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
  5176. return optBorderWidth.getOr('');
  5177. }
  5178. return dom.getAttrib(elm, 'border') || Styles$1.getTDTHOverallStyle(editor.dom, elm, 'border-width') || Styles$1.getTDTHOverallStyle(editor.dom, elm, 'border');
  5179. };
  5180. var dom = editor.dom;
  5181. var data = __assign(__assign({
  5182. width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
  5183. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  5184. cellspacing: dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing'),
  5185. cellpadding: dom.getAttrib(elm, 'cellpadding') || Styles$1.getTDTHOverallStyle(editor.dom, elm, 'padding'),
  5186. border: getBorder(dom, elm),
  5187. caption: !!dom.select('caption', elm)[0],
  5188. class: dom.getAttrib(elm, 'class', '')
  5189. }, getHAlignment('align', 'align', editor, elm)), hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
  5190. return data;
  5191. };
  5192. var extractDataFromRowElement = function (editor, elm, hasAdvancedRowTab) {
  5193. var dom = editor.dom;
  5194. var data = __assign(__assign({
  5195. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  5196. scope: dom.getAttrib(elm, 'scope'),
  5197. class: dom.getAttrib(elm, 'class', ''),
  5198. align: '',
  5199. type: elm.parentNode.nodeName.toLowerCase()
  5200. }, getHAlignment('align', 'align', editor, elm)), hasAdvancedRowTab ? extractAdvancedStyles(dom, elm) : {});
  5201. return data;
  5202. };
  5203. var extractDataFromCellElement = function (editor, elm, hasAdvancedCellTab) {
  5204. var dom = editor.dom;
  5205. var data = __assign(__assign(__assign({
  5206. width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
  5207. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  5208. scope: dom.getAttrib(elm, 'scope'),
  5209. celltype: elm.nodeName.toLowerCase(),
  5210. class: dom.getAttrib(elm, 'class', '')
  5211. }, getHAlignment('align', 'halign', editor, elm)), getVAlignment('valign', 'valign', editor, elm)), hasAdvancedCellTab ? extractAdvancedStyles(dom, elm) : {});
  5212. return data;
  5213. };
  5214. var Helpers = {
  5215. buildListItems: buildListItems,
  5216. extractAdvancedStyles: extractAdvancedStyles,
  5217. getSharedValues: getSharedValues,
  5218. getAdvancedTab: getAdvancedTab,
  5219. extractDataFromTableElement: extractDataFromTableElement,
  5220. extractDataFromRowElement: extractDataFromRowElement,
  5221. extractDataFromCellElement: extractDataFromCellElement,
  5222. extractDataFromSettings: extractDataFromSettings
  5223. };
  5224. var getClassList = function (editor) {
  5225. var rowClassList = getCellClassList(editor);
  5226. var classes = Helpers.buildListItems(rowClassList, function (item) {
  5227. if (item.value) {
  5228. item.textStyle = function () {
  5229. return editor.formatter.getCssText({
  5230. block: 'tr',
  5231. classes: [item.value]
  5232. });
  5233. };
  5234. }
  5235. });
  5236. if (rowClassList.length > 0) {
  5237. return Option.some({
  5238. name: 'class',
  5239. type: 'selectbox',
  5240. label: 'Class',
  5241. items: classes
  5242. });
  5243. }
  5244. return Option.none();
  5245. };
  5246. var children$3 = [
  5247. {
  5248. name: 'width',
  5249. type: 'input',
  5250. label: 'Width'
  5251. },
  5252. {
  5253. name: 'height',
  5254. type: 'input',
  5255. label: 'Height'
  5256. },
  5257. {
  5258. name: 'celltype',
  5259. type: 'selectbox',
  5260. label: 'Cell type',
  5261. items: [
  5262. {
  5263. text: 'Cell',
  5264. value: 'td'
  5265. },
  5266. {
  5267. text: 'Header cell',
  5268. value: 'th'
  5269. }
  5270. ]
  5271. },
  5272. {
  5273. name: 'scope',
  5274. type: 'selectbox',
  5275. label: 'Scope',
  5276. items: [
  5277. {
  5278. text: 'None',
  5279. value: ''
  5280. },
  5281. {
  5282. text: 'Row',
  5283. value: 'row'
  5284. },
  5285. {
  5286. text: 'Column',
  5287. value: 'col'
  5288. },
  5289. {
  5290. text: 'Row group',
  5291. value: 'rowgroup'
  5292. },
  5293. {
  5294. text: 'Column group',
  5295. value: 'colgroup'
  5296. }
  5297. ]
  5298. },
  5299. {
  5300. name: 'halign',
  5301. type: 'selectbox',
  5302. label: 'H Align',
  5303. items: [
  5304. {
  5305. text: 'None',
  5306. value: ''
  5307. },
  5308. {
  5309. text: 'Left',
  5310. value: 'left'
  5311. },
  5312. {
  5313. text: 'Center',
  5314. value: 'center'
  5315. },
  5316. {
  5317. text: 'Right',
  5318. value: 'right'
  5319. }
  5320. ]
  5321. },
  5322. {
  5323. name: 'valign',
  5324. type: 'selectbox',
  5325. label: 'V Align',
  5326. items: [
  5327. {
  5328. text: 'None',
  5329. value: ''
  5330. },
  5331. {
  5332. text: 'Top',
  5333. value: 'top'
  5334. },
  5335. {
  5336. text: 'Middle',
  5337. value: 'middle'
  5338. },
  5339. {
  5340. text: 'Bottom',
  5341. value: 'bottom'
  5342. }
  5343. ]
  5344. }
  5345. ];
  5346. var getItems = function (editor) {
  5347. return getClassList(editor).fold(function () {
  5348. return children$3;
  5349. }, function (classlist) {
  5350. return children$3.concat(classlist);
  5351. });
  5352. };
  5353. var CellDialogGeneralTab = { getItems: getItems };
  5354. var normal = function (dom, node) {
  5355. var setAttrib = function (attr, value) {
  5356. dom.setAttrib(node, attr, value);
  5357. };
  5358. var setStyle = function (prop, value) {
  5359. dom.setStyle(node, prop, value);
  5360. };
  5361. return {
  5362. setAttrib: setAttrib,
  5363. setStyle: setStyle
  5364. };
  5365. };
  5366. var ifTruthy = function (dom, node) {
  5367. var setAttrib = function (attr, value) {
  5368. if (value) {
  5369. dom.setAttrib(node, attr, value);
  5370. }
  5371. };
  5372. var setStyle = function (prop, value) {
  5373. if (value) {
  5374. dom.setStyle(node, prop, value);
  5375. }
  5376. };
  5377. return {
  5378. setAttrib: setAttrib,
  5379. setStyle: setStyle
  5380. };
  5381. };
  5382. var DomModifier = {
  5383. normal: normal,
  5384. ifTruthy: ifTruthy
  5385. };
  5386. var updateSimpleProps = function (modifiers, data) {
  5387. modifiers.setAttrib('scope', data.scope);
  5388. modifiers.setAttrib('class', data.class);
  5389. modifiers.setStyle('width', addSizeSuffix(data.width));
  5390. modifiers.setStyle('height', addSizeSuffix(data.height));
  5391. };
  5392. var updateAdvancedProps = function (modifiers, data) {
  5393. modifiers.setStyle('background-color', data.backgroundcolor);
  5394. modifiers.setStyle('border-color', data.bordercolor);
  5395. modifiers.setStyle('border-style', data.borderstyle);
  5396. modifiers.setStyle('border-width', addSizeSuffix(data.borderwidth));
  5397. };
  5398. var applyToSingle = function (editor, cells, data) {
  5399. var dom = editor.dom;
  5400. var cellElm = data.celltype && cells[0].nodeName.toLowerCase() !== data.celltype ? dom.rename(cells[0], data.celltype) : cells[0];
  5401. var modifiers = DomModifier.normal(dom, cellElm);
  5402. updateSimpleProps(modifiers, data);
  5403. if (hasAdvancedCellTab(editor)) {
  5404. updateAdvancedProps(modifiers, data);
  5405. }
  5406. Styles$1.unApplyAlign(editor, cellElm);
  5407. Styles$1.unApplyVAlign(editor, cellElm);
  5408. if (data.halign) {
  5409. Styles$1.applyAlign(editor, cellElm, data.halign);
  5410. }
  5411. if (data.valign) {
  5412. Styles$1.applyVAlign(editor, cellElm, data.valign);
  5413. }
  5414. };
  5415. var applyToMultiple = function (editor, cells, data) {
  5416. var dom = editor.dom;
  5417. global$1.each(cells, function (cellElm) {
  5418. if (data.celltype && cellElm.nodeName.toLowerCase() !== data.celltype) {
  5419. cellElm = dom.rename(cellElm, data.celltype);
  5420. }
  5421. var modifiers = DomModifier.ifTruthy(dom, cellElm);
  5422. updateSimpleProps(modifiers, data);
  5423. if (hasAdvancedCellTab(editor)) {
  5424. updateAdvancedProps(modifiers, data);
  5425. }
  5426. if (data.halign) {
  5427. Styles$1.applyAlign(editor, cellElm, data.halign);
  5428. }
  5429. if (data.valign) {
  5430. Styles$1.applyVAlign(editor, cellElm, data.valign);
  5431. }
  5432. });
  5433. };
  5434. var onSubmitCellForm = function (editor, cells, api) {
  5435. var data = api.getData();
  5436. api.close();
  5437. editor.undoManager.transact(function () {
  5438. var applicator = cells.length === 1 ? applyToSingle : applyToMultiple;
  5439. applicator(editor, cells, data);
  5440. editor.focus();
  5441. });
  5442. };
  5443. var open = function (editor) {
  5444. var cellElm, cells = [];
  5445. cells = editor.dom.select('td[data-mce-selected],th[data-mce-selected]');
  5446. cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
  5447. if (!cells.length && cellElm) {
  5448. cells.push(cellElm);
  5449. }
  5450. cellElm = cellElm || cells[0];
  5451. if (!cellElm) {
  5452. return;
  5453. }
  5454. var cellsData = global$1.map(cells, function (cellElm) {
  5455. return Helpers.extractDataFromCellElement(editor, cellElm, hasAdvancedCellTab(editor));
  5456. });
  5457. var data = Helpers.getSharedValues(cellsData);
  5458. var dialogTabPanel = {
  5459. type: 'tabpanel',
  5460. tabs: [
  5461. {
  5462. title: 'General',
  5463. name: 'general',
  5464. items: CellDialogGeneralTab.getItems(editor)
  5465. },
  5466. Helpers.getAdvancedTab('cell')
  5467. ]
  5468. };
  5469. var dialogPanel = {
  5470. type: 'panel',
  5471. items: [{
  5472. type: 'grid',
  5473. columns: 2,
  5474. items: CellDialogGeneralTab.getItems(editor)
  5475. }]
  5476. };
  5477. editor.windowManager.open({
  5478. title: 'Cell Properties',
  5479. size: 'normal',
  5480. body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
  5481. buttons: [
  5482. {
  5483. type: 'cancel',
  5484. name: 'cancel',
  5485. text: 'Cancel'
  5486. },
  5487. {
  5488. type: 'submit',
  5489. name: 'save',
  5490. text: 'Save',
  5491. primary: true
  5492. }
  5493. ],
  5494. initialData: data,
  5495. onSubmit: curry(onSubmitCellForm, editor, cells)
  5496. });
  5497. };
  5498. var CellDialog = { open: open };
  5499. var getClassList$1 = function (editor) {
  5500. var rowClassList = getRowClassList(editor);
  5501. var classes = Helpers.buildListItems(rowClassList, function (item) {
  5502. if (item.value) {
  5503. item.textStyle = function () {
  5504. return editor.formatter.getCssText({
  5505. block: 'tr',
  5506. classes: [item.value]
  5507. });
  5508. };
  5509. }
  5510. });
  5511. if (rowClassList.length > 0) {
  5512. return Option.some({
  5513. name: 'class',
  5514. type: 'selectbox',
  5515. label: 'Class',
  5516. items: classes
  5517. });
  5518. }
  5519. return Option.none();
  5520. };
  5521. var formChildren = [
  5522. {
  5523. type: 'selectbox',
  5524. name: 'type',
  5525. label: 'Row type',
  5526. items: [
  5527. {
  5528. text: 'Header',
  5529. value: 'thead'
  5530. },
  5531. {
  5532. text: 'Body',
  5533. value: 'tbody'
  5534. },
  5535. {
  5536. text: 'Footer',
  5537. value: 'tfoot'
  5538. }
  5539. ]
  5540. },
  5541. {
  5542. type: 'selectbox',
  5543. name: 'align',
  5544. label: 'Alignment',
  5545. items: [
  5546. {
  5547. text: 'None',
  5548. value: ''
  5549. },
  5550. {
  5551. text: 'Left',
  5552. value: 'left'
  5553. },
  5554. {
  5555. text: 'Center',
  5556. value: 'center'
  5557. },
  5558. {
  5559. text: 'Right',
  5560. value: 'right'
  5561. }
  5562. ]
  5563. },
  5564. {
  5565. label: 'Height',
  5566. name: 'height',
  5567. type: 'input'
  5568. }
  5569. ];
  5570. var getItems$1 = function (editor) {
  5571. return getClassList$1(editor).fold(function () {
  5572. return formChildren;
  5573. }, function (classes) {
  5574. return formChildren.concat(classes);
  5575. });
  5576. };
  5577. var RowDialogGeneralTab = { getItems: getItems$1 };
  5578. var switchRowType = function (dom, rowElm, toType) {
  5579. var tableElm = dom.getParent(rowElm, 'table');
  5580. var oldParentElm = rowElm.parentNode;
  5581. var parentElm = dom.select(toType, tableElm)[0];
  5582. if (!parentElm) {
  5583. parentElm = dom.create(toType);
  5584. if (tableElm.firstChild) {
  5585. if (tableElm.firstChild.nodeName === 'CAPTION') {
  5586. dom.insertAfter(parentElm, tableElm.firstChild);
  5587. } else {
  5588. tableElm.insertBefore(parentElm, tableElm.firstChild);
  5589. }
  5590. } else {
  5591. tableElm.appendChild(parentElm);
  5592. }
  5593. }
  5594. parentElm.appendChild(rowElm);
  5595. if (!oldParentElm.hasChildNodes()) {
  5596. dom.remove(oldParentElm);
  5597. }
  5598. };
  5599. var updateAdvancedProps$1 = function (modifier, data) {
  5600. modifier.setStyle('background-color', data.backgroundcolor);
  5601. modifier.setStyle('border-color', data.bordercolor);
  5602. modifier.setStyle('border-style', data.borderstyle);
  5603. };
  5604. var onSubmitRowForm = function (editor, rows, oldData, api) {
  5605. var dom = editor.dom;
  5606. var data = api.getData();
  5607. api.close();
  5608. var createModifier = rows.length === 1 ? DomModifier.normal : DomModifier.ifTruthy;
  5609. editor.undoManager.transact(function () {
  5610. global$1.each(rows, function (rowElm) {
  5611. if (data.type !== rowElm.parentNode.nodeName.toLowerCase()) {
  5612. switchRowType(editor.dom, rowElm, data.type);
  5613. }
  5614. var modifier = createModifier(dom, rowElm);
  5615. modifier.setAttrib('scope', data.scope);
  5616. modifier.setAttrib('class', data.class);
  5617. modifier.setStyle('height', addSizeSuffix(data.height));
  5618. if (hasAdvancedRowTab(editor)) {
  5619. updateAdvancedProps$1(modifier, data);
  5620. }
  5621. if (data.align !== oldData.align) {
  5622. Styles$1.unApplyAlign(editor, rowElm);
  5623. Styles$1.applyAlign(editor, rowElm, data.align);
  5624. }
  5625. });
  5626. editor.focus();
  5627. });
  5628. };
  5629. var open$1 = function (editor) {
  5630. var dom = editor.dom;
  5631. var tableElm, cellElm, rowElm;
  5632. var rows = [];
  5633. tableElm = dom.getParent(editor.selection.getStart(), 'table');
  5634. if (!tableElm) {
  5635. return;
  5636. }
  5637. cellElm = dom.getParent(editor.selection.getStart(), 'td,th');
  5638. global$1.each(tableElm.rows, function (row) {
  5639. global$1.each(row.cells, function (cell) {
  5640. if ((dom.getAttrib(cell, 'data-mce-selected') || cell === cellElm) && rows.indexOf(row) < 0) {
  5641. rows.push(row);
  5642. return false;
  5643. }
  5644. });
  5645. });
  5646. rowElm = rows[0];
  5647. if (!rowElm) {
  5648. return;
  5649. }
  5650. var rowsData = global$1.map(rows, function (rowElm) {
  5651. return Helpers.extractDataFromRowElement(editor, rowElm, hasAdvancedRowTab(editor));
  5652. });
  5653. var data = Helpers.getSharedValues(rowsData);
  5654. var dialogTabPanel = {
  5655. type: 'tabpanel',
  5656. tabs: [
  5657. {
  5658. title: 'General',
  5659. name: 'general',
  5660. items: RowDialogGeneralTab.getItems(editor)
  5661. },
  5662. Helpers.getAdvancedTab('row')
  5663. ]
  5664. };
  5665. var dialogPanel = {
  5666. type: 'panel',
  5667. items: [{
  5668. type: 'grid',
  5669. columns: 2,
  5670. items: RowDialogGeneralTab.getItems(editor)
  5671. }]
  5672. };
  5673. editor.windowManager.open({
  5674. title: 'Row Properties',
  5675. size: 'normal',
  5676. body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
  5677. buttons: [
  5678. {
  5679. type: 'cancel',
  5680. name: 'cancel',
  5681. text: 'Cancel'
  5682. },
  5683. {
  5684. type: 'submit',
  5685. name: 'save',
  5686. text: 'Save',
  5687. primary: true
  5688. }
  5689. ],
  5690. initialData: data,
  5691. onSubmit: curry(onSubmitRowForm, editor, rows, data)
  5692. });
  5693. };
  5694. var RowDialog = { open: open$1 };
  5695. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  5696. var shallow$1 = function (old, nu) {
  5697. return nu;
  5698. };
  5699. var baseMerge = function (merger) {
  5700. return function () {
  5701. var objects = new Array(arguments.length);
  5702. for (var i = 0; i < objects.length; i++) {
  5703. objects[i] = arguments[i];
  5704. }
  5705. if (objects.length === 0) {
  5706. throw new Error('Can\'t merge zero objects');
  5707. }
  5708. var ret = {};
  5709. for (var j = 0; j < objects.length; j++) {
  5710. var curObject = objects[j];
  5711. for (var key in curObject) {
  5712. if (hasOwnProperty$1.call(curObject, key)) {
  5713. ret[key] = merger(ret[key], curObject[key]);
  5714. }
  5715. }
  5716. }
  5717. return ret;
  5718. };
  5719. };
  5720. var merge$3 = baseMerge(shallow$1);
  5721. var global$2 = tinymce.util.Tools.resolve('tinymce.Env');
  5722. var DefaultRenderOptions = {
  5723. styles: {
  5724. 'border-collapse': 'collapse',
  5725. 'width': '100%'
  5726. },
  5727. attributes: { border: '1' },
  5728. percentages: true
  5729. };
  5730. var makeTable = function () {
  5731. return Element.fromTag('table');
  5732. };
  5733. var tableBody = function () {
  5734. return Element.fromTag('tbody');
  5735. };
  5736. var tableRow = function () {
  5737. return Element.fromTag('tr');
  5738. };
  5739. var tableHeaderCell = function () {
  5740. return Element.fromTag('th');
  5741. };
  5742. var tableCell = function () {
  5743. return Element.fromTag('td');
  5744. };
  5745. var render$1 = function (rows, columns, rowHeaders, columnHeaders, renderOpts) {
  5746. if (renderOpts === void 0) {
  5747. renderOpts = DefaultRenderOptions;
  5748. }
  5749. var table = makeTable();
  5750. setAll$1(table, renderOpts.styles);
  5751. setAll(table, renderOpts.attributes);
  5752. var tbody = tableBody();
  5753. append(table, tbody);
  5754. var trs = [];
  5755. for (var i = 0; i < rows; i++) {
  5756. var tr = tableRow();
  5757. for (var j = 0; j < columns; j++) {
  5758. var td = i < rowHeaders || j < columnHeaders ? tableHeaderCell() : tableCell();
  5759. if (j < columnHeaders) {
  5760. set(td, 'scope', 'row');
  5761. }
  5762. if (i < rowHeaders) {
  5763. set(td, 'scope', 'col');
  5764. }
  5765. append(td, Element.fromTag('br'));
  5766. if (renderOpts.percentages) {
  5767. set$1(td, 'width', 100 / columns + '%');
  5768. }
  5769. append(tr, td);
  5770. }
  5771. trs.push(tr);
  5772. }
  5773. append$1(tbody, trs);
  5774. return table;
  5775. };
  5776. var get$8 = function (element) {
  5777. return element.dom().innerHTML;
  5778. };
  5779. var getOuter$2 = function (element) {
  5780. var container = Element.fromTag('div');
  5781. var clone = Element.fromDom(element.dom().cloneNode(true));
  5782. append(container, clone);
  5783. return get$8(container);
  5784. };
  5785. var placeCaretInCell = function (editor, cell) {
  5786. editor.selection.select(cell.dom(), true);
  5787. editor.selection.collapse(true);
  5788. };
  5789. var selectFirstCellInTable = function (editor, tableElm) {
  5790. descendant$1(tableElm, 'td,th').each(curry(placeCaretInCell, editor));
  5791. };
  5792. var fireEvents = function (editor, table) {
  5793. each(descendants$1(table, 'tr'), function (row) {
  5794. fireNewRow(editor, row.dom());
  5795. each(descendants$1(row, 'th,td'), function (cell) {
  5796. fireNewCell(editor, cell.dom());
  5797. });
  5798. });
  5799. };
  5800. var isPercentage = function (width) {
  5801. return isString(width) && width.indexOf('%') !== -1;
  5802. };
  5803. var insert$1 = function (editor, columns, rows) {
  5804. var defaultStyles = getDefaultStyles(editor);
  5805. var options = {
  5806. styles: defaultStyles,
  5807. attributes: getDefaultAttributes(editor),
  5808. percentages: isPercentage(defaultStyles.width) && !isPixelsForced(editor)
  5809. };
  5810. var table = render$1(rows, columns, 0, 0, options);
  5811. set(table, 'data-mce-id', '__mce');
  5812. var html = getOuter$2(table);
  5813. editor.insertContent(html);
  5814. return descendant$1(getBody$1(editor), 'table[data-mce-id="__mce"]').map(function (table) {
  5815. if (isPixelsForced(editor)) {
  5816. set$1(table, 'width', get$2(table, 'width'));
  5817. }
  5818. remove(table, 'data-mce-id');
  5819. fireEvents(editor, table);
  5820. selectFirstCellInTable(editor, table);
  5821. return table.dom();
  5822. }).getOr(null);
  5823. };
  5824. var InsertTable = { insert: insert$1 };
  5825. var getItems$2 = function (editor, hasClasses, insertNewTable) {
  5826. var rowColCountItems = !insertNewTable ? [] : [
  5827. {
  5828. type: 'input',
  5829. name: 'cols',
  5830. label: 'Cols',
  5831. inputMode: 'numeric'
  5832. },
  5833. {
  5834. type: 'input',
  5835. name: 'rows',
  5836. label: 'Rows',
  5837. inputMode: 'numeric'
  5838. }
  5839. ];
  5840. var alwaysItems = [
  5841. {
  5842. type: 'input',
  5843. name: 'width',
  5844. label: 'Width'
  5845. },
  5846. {
  5847. type: 'input',
  5848. name: 'height',
  5849. label: 'Height'
  5850. }
  5851. ];
  5852. var appearanceItems = hasAppearanceOptions(editor) ? [
  5853. {
  5854. type: 'input',
  5855. name: 'cellspacing',
  5856. label: 'Cell spacing',
  5857. inputMode: 'numeric'
  5858. },
  5859. {
  5860. type: 'input',
  5861. name: 'cellpadding',
  5862. label: 'Cell padding',
  5863. inputMode: 'numeric'
  5864. },
  5865. {
  5866. type: 'input',
  5867. name: 'border',
  5868. label: 'Border width'
  5869. },
  5870. {
  5871. type: 'label',
  5872. label: 'Caption',
  5873. items: [{
  5874. type: 'checkbox',
  5875. name: 'caption',
  5876. label: 'Show caption'
  5877. }]
  5878. }
  5879. ] : [];
  5880. var alignmentItem = [{
  5881. type: 'selectbox',
  5882. name: 'align',
  5883. label: 'Alignment',
  5884. items: [
  5885. {
  5886. text: 'None',
  5887. value: ''
  5888. },
  5889. {
  5890. text: 'Left',
  5891. value: 'left'
  5892. },
  5893. {
  5894. text: 'Center',
  5895. value: 'center'
  5896. },
  5897. {
  5898. text: 'Right',
  5899. value: 'right'
  5900. }
  5901. ]
  5902. }];
  5903. var classListItem = hasClasses ? [{
  5904. type: 'selectbox',
  5905. name: 'class',
  5906. label: 'Class',
  5907. items: Helpers.buildListItems(getTableClassList(editor), function (item) {
  5908. if (item.value) {
  5909. item.textStyle = function () {
  5910. return editor.formatter.getCssText({
  5911. block: 'table',
  5912. classes: [item.value]
  5913. });
  5914. };
  5915. }
  5916. })
  5917. }] : [];
  5918. return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
  5919. };
  5920. var TableDialogGeneralTab = { getItems: getItems$2 };
  5921. var styleTDTH = function (dom, elm, name, value) {
  5922. if (elm.tagName === 'TD' || elm.tagName === 'TH') {
  5923. if (isString(name)) {
  5924. dom.setStyle(elm, name, value);
  5925. } else {
  5926. dom.setStyle(elm, name);
  5927. }
  5928. } else {
  5929. if (elm.children) {
  5930. for (var i = 0; i < elm.children.length; i++) {
  5931. styleTDTH(dom, elm.children[i], name, value);
  5932. }
  5933. }
  5934. }
  5935. };
  5936. var applyDataToElement = function (editor, tableElm, data) {
  5937. var dom = editor.dom;
  5938. var attrs = {};
  5939. var styles = {};
  5940. attrs.class = data.class;
  5941. styles.height = addSizeSuffix(data.height);
  5942. if (dom.getAttrib(tableElm, 'width') && !shouldStyleWithCss(editor)) {
  5943. attrs.width = removePxSuffix(data.width);
  5944. } else {
  5945. styles.width = addSizeSuffix(data.width);
  5946. }
  5947. if (shouldStyleWithCss(editor)) {
  5948. styles['border-width'] = addSizeSuffix(data.border);
  5949. styles['border-spacing'] = addSizeSuffix(data.cellspacing);
  5950. } else {
  5951. attrs.border = data.border;
  5952. attrs.cellpadding = data.cellpadding;
  5953. attrs.cellspacing = data.cellspacing;
  5954. }
  5955. if (shouldStyleWithCss(editor) && tableElm.children) {
  5956. for (var i = 0; i < tableElm.children.length; i++) {
  5957. styleTDTH(dom, tableElm.children[i], {
  5958. 'border-width': addSizeSuffix(data.border),
  5959. 'padding': addSizeSuffix(data.cellpadding)
  5960. });
  5961. if (hasAdvancedTableTab(editor)) {
  5962. styleTDTH(dom, tableElm.children[i], { 'border-color': data.bordercolor });
  5963. }
  5964. }
  5965. }
  5966. if (hasAdvancedTableTab(editor)) {
  5967. styles['background-color'] = data.backgroundcolor;
  5968. styles['border-color'] = data.bordercolor;
  5969. styles['border-style'] = data.borderstyle;
  5970. }
  5971. attrs.style = dom.serializeStyle(merge$3(getDefaultStyles(editor), styles));
  5972. dom.setAttribs(tableElm, merge$3(getDefaultAttributes(editor), attrs));
  5973. };
  5974. var onSubmitTableForm = function (editor, tableElm, api) {
  5975. var dom = editor.dom;
  5976. var captionElm;
  5977. var data = api.getData();
  5978. api.close();
  5979. if (data.class === '') {
  5980. delete data.class;
  5981. }
  5982. editor.undoManager.transact(function () {
  5983. if (!tableElm) {
  5984. var cols = parseInt(data.cols, 10) || 1;
  5985. var rows = parseInt(data.rows, 10) || 1;
  5986. tableElm = InsertTable.insert(editor, cols, rows);
  5987. }
  5988. applyDataToElement(editor, tableElm, data);
  5989. captionElm = dom.select('caption', tableElm)[0];
  5990. if (captionElm && !data.caption) {
  5991. dom.remove(captionElm);
  5992. }
  5993. if (!captionElm && data.caption) {
  5994. captionElm = dom.create('caption');
  5995. captionElm.innerHTML = !global$2.ie ? '<br data-mce-bogus="1"/>' : '\xA0';
  5996. tableElm.insertBefore(captionElm, tableElm.firstChild);
  5997. }
  5998. if (data.align === '') {
  5999. Styles$1.unApplyAlign(editor, tableElm);
  6000. } else {
  6001. Styles$1.applyAlign(editor, tableElm, data.align);
  6002. }
  6003. editor.focus();
  6004. editor.addVisual();
  6005. });
  6006. };
  6007. var open$2 = function (editor, insertNewTable) {
  6008. var dom = editor.dom;
  6009. var tableElm;
  6010. var data = Helpers.extractDataFromSettings(editor, hasAdvancedTableTab(editor));
  6011. if (insertNewTable === false) {
  6012. tableElm = dom.getParent(editor.selection.getStart(), 'table');
  6013. if (tableElm) {
  6014. data = Helpers.extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
  6015. } else {
  6016. if (hasAdvancedTableTab(editor)) {
  6017. data.borderstyle = '';
  6018. data.bordercolor = '';
  6019. data.backgroundcolor = '';
  6020. }
  6021. }
  6022. } else {
  6023. data.cols = '1';
  6024. data.rows = '1';
  6025. if (hasAdvancedTableTab(editor)) {
  6026. data.borderstyle = '';
  6027. data.bordercolor = '';
  6028. data.backgroundcolor = '';
  6029. }
  6030. }
  6031. var hasClasses = getTableClassList(editor).length > 0;
  6032. if (hasClasses) {
  6033. if (data.class) {
  6034. data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
  6035. }
  6036. }
  6037. var generalPanel = {
  6038. type: 'grid',
  6039. columns: 2,
  6040. items: TableDialogGeneralTab.getItems(editor, hasClasses, insertNewTable)
  6041. };
  6042. var nonAdvancedForm = function () {
  6043. return {
  6044. type: 'panel',
  6045. items: [generalPanel]
  6046. };
  6047. };
  6048. var advancedForm = function () {
  6049. return {
  6050. type: 'tabpanel',
  6051. tabs: [
  6052. {
  6053. title: 'General',
  6054. name: 'general',
  6055. items: [generalPanel]
  6056. },
  6057. Helpers.getAdvancedTab('table')
  6058. ]
  6059. };
  6060. };
  6061. var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
  6062. editor.windowManager.open({
  6063. title: 'Table Properties',
  6064. size: 'normal',
  6065. body: dialogBody,
  6066. onSubmit: curry(onSubmitTableForm, editor, tableElm),
  6067. buttons: [
  6068. {
  6069. type: 'cancel',
  6070. name: 'cancel',
  6071. text: 'Cancel'
  6072. },
  6073. {
  6074. type: 'submit',
  6075. name: 'save',
  6076. text: 'Save',
  6077. primary: true
  6078. }
  6079. ],
  6080. initialData: data
  6081. });
  6082. };
  6083. var TableDialog = { open: open$2 };
  6084. var getSelectionStartFromSelector = function (selector) {
  6085. return function (editor) {
  6086. return Option.from(editor.dom.getParent(editor.selection.getStart(), selector)).map(Element.fromDom);
  6087. };
  6088. };
  6089. var getSelectionStartCell = getSelectionStartFromSelector('th,td');
  6090. var getSelectionStartCellOrCaption = getSelectionStartFromSelector('th,td,caption');
  6091. var each$3 = global$1.each;
  6092. var registerCommands = function (editor, actions, cellSelection, selections, clipboardRows) {
  6093. var isRoot = getIsRoot(editor);
  6094. var eraseTable = function () {
  6095. getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  6096. var tableOpt = TableLookup.table(cellOrCaption, isRoot);
  6097. tableOpt.filter(not(isRoot)).each(function (table) {
  6098. var cursor = Element.fromText('');
  6099. after(table, cursor);
  6100. remove$2(table);
  6101. if (editor.dom.isEmpty(editor.getBody())) {
  6102. editor.setContent('');
  6103. editor.selection.setCursorLocation();
  6104. } else {
  6105. var rng = editor.dom.createRng();
  6106. rng.setStart(cursor.dom(), 0);
  6107. rng.setEnd(cursor.dom(), 0);
  6108. editor.selection.setRng(rng);
  6109. editor.nodeChanged();
  6110. }
  6111. });
  6112. });
  6113. };
  6114. var getTableFromCell = function (cell) {
  6115. return TableLookup.table(cell, isRoot);
  6116. };
  6117. var getSize = function (table) {
  6118. return {
  6119. width: getPixelWidth$1(table.dom()),
  6120. height: getPixelWidth$1(table.dom())
  6121. };
  6122. };
  6123. var resizeChange = function (editor, oldSize, table) {
  6124. var newSize = getSize(table);
  6125. if (oldSize.width !== newSize.width || oldSize.height !== newSize.height) {
  6126. fireObjectResizeStart(editor, table.dom(), oldSize.width, oldSize.height);
  6127. fireObjectResized(editor, table.dom(), newSize.width, newSize.height);
  6128. }
  6129. };
  6130. var actOnSelection = function (execute) {
  6131. getSelectionStartCell(editor).each(function (cell) {
  6132. getTableFromCell(cell).each(function (table) {
  6133. var targets = TableTargets.forMenu(selections, table, cell);
  6134. var beforeSize = getSize(table);
  6135. execute(table, targets).each(function (rng) {
  6136. resizeChange(editor, beforeSize, table);
  6137. editor.selection.setRng(rng);
  6138. editor.focus();
  6139. cellSelection.clear(table);
  6140. removeDataStyle(table);
  6141. });
  6142. });
  6143. });
  6144. };
  6145. var copyRowSelection = function (execute) {
  6146. return getSelectionStartCell(editor).map(function (cell) {
  6147. return getTableFromCell(cell).bind(function (table) {
  6148. var doc = Element.fromDom(editor.getDoc());
  6149. var targets = TableTargets.forMenu(selections, table, cell);
  6150. var generators = TableFill.cellOperations(noop, doc, Option.none());
  6151. return CopyRows.copyRows(table, targets, generators);
  6152. });
  6153. });
  6154. };
  6155. var pasteOnSelection = function (execute) {
  6156. clipboardRows.get().each(function (rows) {
  6157. var clonedRows = map(rows, function (row) {
  6158. return deep(row);
  6159. });
  6160. getSelectionStartCell(editor).each(function (cell) {
  6161. getTableFromCell(cell).each(function (table) {
  6162. var doc = Element.fromDom(editor.getDoc());
  6163. var generators = TableFill.paste(doc);
  6164. var targets = TableTargets.pasteRows(selections, table, cell, clonedRows, generators);
  6165. execute(table, targets).each(function (rng) {
  6166. editor.selection.setRng(rng);
  6167. editor.focus();
  6168. cellSelection.clear(table);
  6169. });
  6170. });
  6171. });
  6172. });
  6173. };
  6174. each$3({
  6175. mceTableSplitCells: function () {
  6176. actOnSelection(actions.unmergeCells);
  6177. },
  6178. mceTableMergeCells: function () {
  6179. actOnSelection(actions.mergeCells);
  6180. },
  6181. mceTableInsertRowBefore: function () {
  6182. actOnSelection(actions.insertRowsBefore);
  6183. },
  6184. mceTableInsertRowAfter: function () {
  6185. actOnSelection(actions.insertRowsAfter);
  6186. },
  6187. mceTableInsertColBefore: function () {
  6188. actOnSelection(actions.insertColumnsBefore);
  6189. },
  6190. mceTableInsertColAfter: function () {
  6191. actOnSelection(actions.insertColumnsAfter);
  6192. },
  6193. mceTableDeleteCol: function () {
  6194. actOnSelection(actions.deleteColumn);
  6195. },
  6196. mceTableDeleteRow: function () {
  6197. actOnSelection(actions.deleteRow);
  6198. },
  6199. mceTableCutRow: function (grid) {
  6200. copyRowSelection().each(function (selection) {
  6201. clipboardRows.set(selection);
  6202. actOnSelection(actions.deleteRow);
  6203. });
  6204. },
  6205. mceTableCopyRow: function (grid) {
  6206. copyRowSelection().each(function (selection) {
  6207. clipboardRows.set(selection);
  6208. });
  6209. },
  6210. mceTablePasteRowBefore: function (grid) {
  6211. pasteOnSelection(actions.pasteRowsBefore);
  6212. },
  6213. mceTablePasteRowAfter: function (grid) {
  6214. pasteOnSelection(actions.pasteRowsAfter);
  6215. },
  6216. mceTableDelete: eraseTable
  6217. }, function (func, name) {
  6218. editor.addCommand(name, func);
  6219. });
  6220. each$3({
  6221. mceInsertTable: curry(TableDialog.open, editor, true),
  6222. mceTableProps: curry(TableDialog.open, editor, false),
  6223. mceTableRowProps: curry(RowDialog.open, editor),
  6224. mceTableCellProps: curry(CellDialog.open, editor)
  6225. }, function (func, name) {
  6226. editor.addCommand(name, function () {
  6227. func();
  6228. });
  6229. });
  6230. };
  6231. var Commands = { registerCommands: registerCommands };
  6232. var only = function (element) {
  6233. var parent = Option.from(element.dom().documentElement).map(Element.fromDom).getOr(element);
  6234. return {
  6235. parent: constant(parent),
  6236. view: constant(element),
  6237. origin: constant(Position(0, 0))
  6238. };
  6239. };
  6240. var detached = function (editable, chrome) {
  6241. var origin = function () {
  6242. return absolute(chrome);
  6243. };
  6244. return {
  6245. parent: constant(chrome),
  6246. view: constant(editable),
  6247. origin: origin
  6248. };
  6249. };
  6250. var body$1 = function (editable, chrome) {
  6251. return {
  6252. parent: constant(chrome),
  6253. view: constant(editable),
  6254. origin: constant(Position(0, 0))
  6255. };
  6256. };
  6257. var ResizeWire = {
  6258. only: only,
  6259. detached: detached,
  6260. body: body$1
  6261. };
  6262. var Event = function (fields) {
  6263. var struct = Immutable.apply(null, fields);
  6264. var handlers = [];
  6265. var bind = function (handler) {
  6266. if (handler === undefined) {
  6267. throw new Error('Event bind error: undefined handler');
  6268. }
  6269. handlers.push(handler);
  6270. };
  6271. var unbind = function (handler) {
  6272. handlers = filter(handlers, function (h) {
  6273. return h !== handler;
  6274. });
  6275. };
  6276. var trigger = function () {
  6277. var args = [];
  6278. for (var _i = 0; _i < arguments.length; _i++) {
  6279. args[_i] = arguments[_i];
  6280. }
  6281. var event = struct.apply(null, args);
  6282. each(handlers, function (handler) {
  6283. handler(event);
  6284. });
  6285. };
  6286. return {
  6287. bind: bind,
  6288. unbind: unbind,
  6289. trigger: trigger
  6290. };
  6291. };
  6292. var create$1 = function (typeDefs) {
  6293. var registry = map$1(typeDefs, function (event) {
  6294. return {
  6295. bind: event.bind,
  6296. unbind: event.unbind
  6297. };
  6298. });
  6299. var trigger = map$1(typeDefs, function (event) {
  6300. return event.trigger;
  6301. });
  6302. return {
  6303. registry: registry,
  6304. trigger: trigger
  6305. };
  6306. };
  6307. var Events = { create: create$1 };
  6308. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  6309. return {
  6310. target: constant(target),
  6311. x: constant(x),
  6312. y: constant(y),
  6313. stop: stop,
  6314. prevent: prevent,
  6315. kill: kill,
  6316. raw: constant(raw)
  6317. };
  6318. };
  6319. var fromRawEvent = function (rawEvent) {
  6320. var target = Element.fromDom(rawEvent.target);
  6321. var stop = function () {
  6322. rawEvent.stopPropagation();
  6323. };
  6324. var prevent = function () {
  6325. rawEvent.preventDefault();
  6326. };
  6327. var kill = compose(prevent, stop);
  6328. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  6329. };
  6330. var handle = function (filter, handler) {
  6331. return function (rawEvent) {
  6332. if (!filter(rawEvent)) {
  6333. return;
  6334. }
  6335. handler(fromRawEvent(rawEvent));
  6336. };
  6337. };
  6338. var binder = function (element, event, filter, handler, useCapture) {
  6339. var wrapped = handle(filter, handler);
  6340. element.dom().addEventListener(event, wrapped, useCapture);
  6341. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  6342. };
  6343. var bind$1 = function (element, event, filter, handler) {
  6344. return binder(element, event, filter, handler, false);
  6345. };
  6346. var unbind = function (element, event, handler, useCapture) {
  6347. element.dom().removeEventListener(event, handler, useCapture);
  6348. };
  6349. var filter$1 = constant(true);
  6350. var bind$2 = function (element, event, handler) {
  6351. return bind$1(element, event, filter$1, handler);
  6352. };
  6353. var styles$1 = css('ephox-dragster');
  6354. var Styles$2 = { resolve: styles$1.resolve };
  6355. var Blocker = function (options) {
  6356. var settings = merge$3({ layerClass: Styles$2.resolve('blocker') }, options);
  6357. var div = Element.fromTag('div');
  6358. set(div, 'role', 'presentation');
  6359. setAll$1(div, {
  6360. position: 'fixed',
  6361. left: '0px',
  6362. top: '0px',
  6363. width: '100%',
  6364. height: '100%'
  6365. });
  6366. add$2(div, Styles$2.resolve('blocker'));
  6367. add$2(div, settings.layerClass);
  6368. var element = function () {
  6369. return div;
  6370. };
  6371. var destroy = function () {
  6372. remove$2(div);
  6373. };
  6374. return {
  6375. element: element,
  6376. destroy: destroy
  6377. };
  6378. };
  6379. var DragMode = exactly([
  6380. 'compare',
  6381. 'extract',
  6382. 'mutate',
  6383. 'sink'
  6384. ]);
  6385. var DragSink = exactly([
  6386. 'element',
  6387. 'start',
  6388. 'stop',
  6389. 'destroy'
  6390. ]);
  6391. var DragApi = exactly([
  6392. 'forceDrop',
  6393. 'drop',
  6394. 'move',
  6395. 'delayDrop'
  6396. ]);
  6397. var compare = function (old, nu) {
  6398. return Position(nu.left() - old.left(), nu.top() - old.top());
  6399. };
  6400. var extract$1 = function (event) {
  6401. return Option.some(Position(event.x(), event.y()));
  6402. };
  6403. var mutate = function (mutation, info) {
  6404. mutation.mutate(info.left(), info.top());
  6405. };
  6406. var sink = function (dragApi, settings) {
  6407. var blocker = Blocker(settings);
  6408. var mdown = bind$2(blocker.element(), 'mousedown', dragApi.forceDrop);
  6409. var mup = bind$2(blocker.element(), 'mouseup', dragApi.drop);
  6410. var mmove = bind$2(blocker.element(), 'mousemove', dragApi.move);
  6411. var mout = bind$2(blocker.element(), 'mouseout', dragApi.delayDrop);
  6412. var destroy = function () {
  6413. blocker.destroy();
  6414. mup.unbind();
  6415. mmove.unbind();
  6416. mout.unbind();
  6417. mdown.unbind();
  6418. };
  6419. var start = function (parent) {
  6420. append(parent, blocker.element());
  6421. };
  6422. var stop = function () {
  6423. remove$2(blocker.element());
  6424. };
  6425. return DragSink({
  6426. element: blocker.element,
  6427. start: start,
  6428. stop: stop,
  6429. destroy: destroy
  6430. });
  6431. };
  6432. var MouseDrag = DragMode({
  6433. compare: compare,
  6434. extract: extract$1,
  6435. sink: sink,
  6436. mutate: mutate
  6437. });
  6438. var last$2 = function (fn, rate) {
  6439. var timer = null;
  6440. var cancel = function () {
  6441. if (timer !== null) {
  6442. domGlobals.clearTimeout(timer);
  6443. timer = null;
  6444. }
  6445. };
  6446. var throttle = function () {
  6447. var args = [];
  6448. for (var _i = 0; _i < arguments.length; _i++) {
  6449. args[_i] = arguments[_i];
  6450. }
  6451. if (timer !== null) {
  6452. domGlobals.clearTimeout(timer);
  6453. }
  6454. timer = domGlobals.setTimeout(function () {
  6455. fn.apply(null, args);
  6456. timer = null;
  6457. }, rate);
  6458. };
  6459. return {
  6460. cancel: cancel,
  6461. throttle: throttle
  6462. };
  6463. };
  6464. function InDrag () {
  6465. var previous = Option.none();
  6466. var reset = function () {
  6467. previous = Option.none();
  6468. };
  6469. var update = function (mode, nu) {
  6470. var result = previous.map(function (old) {
  6471. return mode.compare(old, nu);
  6472. });
  6473. previous = Option.some(nu);
  6474. return result;
  6475. };
  6476. var onEvent = function (event, mode) {
  6477. var dataOption = mode.extract(event);
  6478. dataOption.each(function (data) {
  6479. var offset = update(mode, data);
  6480. offset.each(function (d) {
  6481. events.trigger.move(d);
  6482. });
  6483. });
  6484. };
  6485. var events = Events.create({ move: Event(['info']) });
  6486. return {
  6487. onEvent: onEvent,
  6488. reset: reset,
  6489. events: events.registry
  6490. };
  6491. }
  6492. function NoDrag () {
  6493. return {
  6494. onEvent: noop,
  6495. reset: noop
  6496. };
  6497. }
  6498. function Movement () {
  6499. var noDragState = NoDrag();
  6500. var inDragState = InDrag();
  6501. var dragState = noDragState;
  6502. var on = function () {
  6503. dragState.reset();
  6504. dragState = inDragState;
  6505. };
  6506. var off = function () {
  6507. dragState.reset();
  6508. dragState = noDragState;
  6509. };
  6510. var onEvent = function (event, mode) {
  6511. dragState.onEvent(event, mode);
  6512. };
  6513. var isOn = function () {
  6514. return dragState === inDragState;
  6515. };
  6516. return {
  6517. on: on,
  6518. off: off,
  6519. isOn: isOn,
  6520. onEvent: onEvent,
  6521. events: inDragState.events
  6522. };
  6523. }
  6524. var setup = function (mutation, mode, settings) {
  6525. var active = false;
  6526. var events = Events.create({
  6527. start: Event([]),
  6528. stop: Event([])
  6529. });
  6530. var movement = Movement();
  6531. var drop = function () {
  6532. sink.stop();
  6533. if (movement.isOn()) {
  6534. movement.off();
  6535. events.trigger.stop();
  6536. }
  6537. };
  6538. var throttledDrop = last$2(drop, 200);
  6539. var go = function (parent) {
  6540. sink.start(parent);
  6541. movement.on();
  6542. events.trigger.start();
  6543. };
  6544. var mousemove = function (event) {
  6545. throttledDrop.cancel();
  6546. movement.onEvent(event, mode);
  6547. };
  6548. movement.events.move.bind(function (event) {
  6549. mode.mutate(mutation, event.info());
  6550. });
  6551. var on = function () {
  6552. active = true;
  6553. };
  6554. var off = function () {
  6555. active = false;
  6556. };
  6557. var runIfActive = function (f) {
  6558. return function () {
  6559. var args = [];
  6560. for (var _i = 0; _i < arguments.length; _i++) {
  6561. args[_i] = arguments[_i];
  6562. }
  6563. if (active) {
  6564. f.apply(null, args);
  6565. }
  6566. };
  6567. };
  6568. var sink = mode.sink(DragApi({
  6569. forceDrop: drop,
  6570. drop: runIfActive(drop),
  6571. move: runIfActive(mousemove),
  6572. delayDrop: runIfActive(throttledDrop.throttle)
  6573. }), settings);
  6574. var destroy = function () {
  6575. sink.destroy();
  6576. };
  6577. return {
  6578. element: sink.element,
  6579. go: go,
  6580. on: on,
  6581. off: off,
  6582. destroy: destroy,
  6583. events: events.registry
  6584. };
  6585. };
  6586. var Dragging = { setup: setup };
  6587. var transform$1 = function (mutation, settings) {
  6588. if (settings === void 0) {
  6589. settings = {};
  6590. }
  6591. var mode = settings.mode !== undefined ? settings.mode : MouseDrag;
  6592. return Dragging.setup(mutation, mode, settings);
  6593. };
  6594. var Dragger = { transform: transform$1 };
  6595. var Mutation = function () {
  6596. var events = Events.create({
  6597. drag: Event([
  6598. 'xDelta',
  6599. 'yDelta'
  6600. ])
  6601. });
  6602. var mutate = function (x, y) {
  6603. events.trigger.drag(x, y);
  6604. };
  6605. return {
  6606. mutate: mutate,
  6607. events: events.registry
  6608. };
  6609. };
  6610. var BarMutation = function () {
  6611. var events = Events.create({
  6612. drag: Event([
  6613. 'xDelta',
  6614. 'yDelta',
  6615. 'target'
  6616. ])
  6617. });
  6618. var target = Option.none();
  6619. var delegate = Mutation();
  6620. delegate.events.drag.bind(function (event) {
  6621. target.each(function (t) {
  6622. events.trigger.drag(event.xDelta(), event.yDelta(), t);
  6623. });
  6624. });
  6625. var assign = function (t) {
  6626. target = Option.some(t);
  6627. };
  6628. var get = function () {
  6629. return target;
  6630. };
  6631. return {
  6632. assign: assign,
  6633. get: get,
  6634. mutate: delegate.mutate,
  6635. events: events.registry
  6636. };
  6637. };
  6638. var isContentEditableTrue = function (elm) {
  6639. return get$1(elm, 'contenteditable') === 'true';
  6640. };
  6641. var findClosestContentEditable = function (target, isRoot) {
  6642. return closest$1(target, '[contenteditable]', isRoot);
  6643. };
  6644. var resizeBarDragging = Styles.resolve('resizer-bar-dragging');
  6645. var BarManager = function (wire, direction, hdirection) {
  6646. var mutation = BarMutation();
  6647. var resizing = Dragger.transform(mutation, {});
  6648. var hoverTable = Option.none();
  6649. var getResizer = function (element, type) {
  6650. return Option.from(get$1(element, type));
  6651. };
  6652. mutation.events.drag.bind(function (event) {
  6653. getResizer(event.target(), 'data-row').each(function (_dataRow) {
  6654. var currentRow = CellUtils.getInt(event.target(), 'top');
  6655. set$1(event.target(), 'top', currentRow + event.yDelta() + 'px');
  6656. });
  6657. getResizer(event.target(), 'data-column').each(function (_dataCol) {
  6658. var currentCol = CellUtils.getInt(event.target(), 'left');
  6659. set$1(event.target(), 'left', currentCol + event.xDelta() + 'px');
  6660. });
  6661. });
  6662. var getDelta = function (target, dir) {
  6663. var newX = CellUtils.getInt(target, dir);
  6664. var oldX = parseInt(get$1(target, 'data-initial-' + dir), 10);
  6665. return newX - oldX;
  6666. };
  6667. resizing.events.stop.bind(function () {
  6668. mutation.get().each(function (target) {
  6669. hoverTable.each(function (table) {
  6670. getResizer(target, 'data-row').each(function (row) {
  6671. var delta = getDelta(target, 'top');
  6672. remove(target, 'data-initial-top');
  6673. events.trigger.adjustHeight(table, delta, parseInt(row, 10));
  6674. });
  6675. getResizer(target, 'data-column').each(function (column) {
  6676. var delta = getDelta(target, 'left');
  6677. remove(target, 'data-initial-left');
  6678. events.trigger.adjustWidth(table, delta, parseInt(column, 10));
  6679. });
  6680. Bars.refresh(wire, table, hdirection, direction);
  6681. });
  6682. });
  6683. });
  6684. var handler = function (target, dir) {
  6685. events.trigger.startAdjust();
  6686. mutation.assign(target);
  6687. set(target, 'data-initial-' + dir, parseInt(get$2(target, dir), 10));
  6688. add$2(target, resizeBarDragging);
  6689. set$1(target, 'opacity', '0.2');
  6690. resizing.go(wire.parent());
  6691. };
  6692. var mousedown = bind$2(wire.parent(), 'mousedown', function (event) {
  6693. if (Bars.isRowBar(event.target())) {
  6694. handler(event.target(), 'top');
  6695. }
  6696. if (Bars.isColBar(event.target())) {
  6697. handler(event.target(), 'left');
  6698. }
  6699. });
  6700. var isRoot = function (e) {
  6701. return eq(e, wire.view());
  6702. };
  6703. var findClosestEditableTable = function (target) {
  6704. return closest$1(target, 'table', isRoot).filter(function (table) {
  6705. return findClosestContentEditable(table, isRoot).exists(isContentEditableTrue);
  6706. });
  6707. };
  6708. var mouseover = bind$2(wire.view(), 'mouseover', function (event) {
  6709. findClosestEditableTable(event.target()).fold(function () {
  6710. if (inBody(event.target())) {
  6711. Bars.destroy(wire);
  6712. }
  6713. }, function (table) {
  6714. hoverTable = Option.some(table);
  6715. Bars.refresh(wire, table, hdirection, direction);
  6716. });
  6717. });
  6718. var destroy = function () {
  6719. mousedown.unbind();
  6720. mouseover.unbind();
  6721. resizing.destroy();
  6722. Bars.destroy(wire);
  6723. };
  6724. var refresh = function (tbl) {
  6725. Bars.refresh(wire, tbl, hdirection, direction);
  6726. };
  6727. var events = Events.create({
  6728. adjustHeight: Event([
  6729. 'table',
  6730. 'delta',
  6731. 'row'
  6732. ]),
  6733. adjustWidth: Event([
  6734. 'table',
  6735. 'delta',
  6736. 'column'
  6737. ]),
  6738. startAdjust: Event([])
  6739. });
  6740. return {
  6741. destroy: destroy,
  6742. refresh: refresh,
  6743. on: resizing.on,
  6744. off: resizing.off,
  6745. hideBars: curry(Bars.hide, wire),
  6746. showBars: curry(Bars.show, wire),
  6747. events: events.registry
  6748. };
  6749. };
  6750. var create$2 = function (wire, vdirection) {
  6751. var hdirection = BarPositions.height;
  6752. var manager = BarManager(wire, vdirection, hdirection);
  6753. var events = Events.create({
  6754. beforeResize: Event(['table']),
  6755. afterResize: Event(['table']),
  6756. startDrag: Event([])
  6757. });
  6758. manager.events.adjustHeight.bind(function (event) {
  6759. events.trigger.beforeResize(event.table());
  6760. var delta = hdirection.delta(event.delta(), event.table());
  6761. Adjustments.adjustHeight(event.table(), delta, event.row(), hdirection);
  6762. events.trigger.afterResize(event.table());
  6763. });
  6764. manager.events.startAdjust.bind(function (event) {
  6765. events.trigger.startDrag();
  6766. });
  6767. manager.events.adjustWidth.bind(function (event) {
  6768. events.trigger.beforeResize(event.table());
  6769. var delta = vdirection.delta(event.delta(), event.table());
  6770. Adjustments.adjustWidth(event.table(), delta, event.column(), vdirection);
  6771. events.trigger.afterResize(event.table());
  6772. });
  6773. return {
  6774. on: manager.on,
  6775. off: manager.off,
  6776. hideBars: manager.hideBars,
  6777. showBars: manager.showBars,
  6778. destroy: manager.destroy,
  6779. events: events.registry
  6780. };
  6781. };
  6782. var TableResize = { create: create$2 };
  6783. var createContainer = function () {
  6784. var container = Element.fromTag('div');
  6785. setAll$1(container, {
  6786. position: 'static',
  6787. height: '0',
  6788. width: '0',
  6789. padding: '0',
  6790. margin: '0',
  6791. border: '0'
  6792. });
  6793. append(body(), container);
  6794. return container;
  6795. };
  6796. var get$9 = function (editor, container) {
  6797. return editor.inline ? ResizeWire.body(getBody$1(editor), createContainer()) : ResizeWire.only(Element.fromDom(editor.getDoc()));
  6798. };
  6799. var remove$6 = function (editor, wire) {
  6800. if (editor.inline) {
  6801. remove$2(wire.parent());
  6802. }
  6803. };
  6804. var TableWire = {
  6805. get: get$9,
  6806. remove: remove$6
  6807. };
  6808. var calculatePercentageWidth = function (element, parent) {
  6809. return getPixelWidth$1(element.dom()) / getPixelWidth$1(parent.dom()) * 100 + '%';
  6810. };
  6811. var enforcePercentage = function (rawTable) {
  6812. var table = Element.fromDom(rawTable);
  6813. parent(table).map(function (parent) {
  6814. return calculatePercentageWidth(table, parent);
  6815. }).each(function (tablePercentage) {
  6816. set$1(table, 'width', tablePercentage);
  6817. each(descendants$1(table, 'tr'), function (tr) {
  6818. each(children(tr), function (td) {
  6819. set$1(td, 'width', calculatePercentageWidth(td, tr));
  6820. });
  6821. });
  6822. });
  6823. };
  6824. var enforcePixels = function (table) {
  6825. set$1(Element.fromDom(table), 'width', getPixelWidth$1(table).toString() + 'px');
  6826. };
  6827. var getResizeHandler = function (editor) {
  6828. var selectionRng = Option.none();
  6829. var resize = Option.none();
  6830. var wire = Option.none();
  6831. var percentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
  6832. var startW;
  6833. var startRawW;
  6834. var isTable = function (elm) {
  6835. return elm.nodeName === 'TABLE';
  6836. };
  6837. var getRawWidth = function (elm) {
  6838. var raw = editor.dom.getStyle(elm, 'width') || editor.dom.getAttrib(elm, 'width');
  6839. return Option.from(raw).filter(function (s) {
  6840. return s.length > 0;
  6841. });
  6842. };
  6843. var lazyResize = function () {
  6844. return resize;
  6845. };
  6846. var lazyWire = function () {
  6847. return wire.getOr(ResizeWire.only(Element.fromDom(editor.getBody())));
  6848. };
  6849. var destroy = function () {
  6850. resize.each(function (sz) {
  6851. sz.destroy();
  6852. });
  6853. wire.each(function (w) {
  6854. TableWire.remove(editor, w);
  6855. });
  6856. };
  6857. editor.on('init', function () {
  6858. var direction = TableDirection(Direction.directionAt);
  6859. var rawWire = TableWire.get(editor);
  6860. wire = Option.some(rawWire);
  6861. if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
  6862. var sz = TableResize.create(rawWire, direction);
  6863. sz.on();
  6864. sz.events.startDrag.bind(function (event) {
  6865. selectionRng = Option.some(editor.selection.getRng());
  6866. });
  6867. sz.events.beforeResize.bind(function (event) {
  6868. var rawTable = event.table().dom();
  6869. fireObjectResizeStart(editor, rawTable, getPixelWidth$1(rawTable), getPixelHeight(rawTable));
  6870. });
  6871. sz.events.afterResize.bind(function (event) {
  6872. var table = event.table();
  6873. var rawTable = table.dom();
  6874. removeDataStyle(table);
  6875. selectionRng.each(function (rng) {
  6876. editor.selection.setRng(rng);
  6877. editor.focus();
  6878. });
  6879. fireObjectResized(editor, rawTable, getPixelWidth$1(rawTable), getPixelHeight(rawTable));
  6880. editor.undoManager.add();
  6881. });
  6882. resize = Option.some(sz);
  6883. }
  6884. });
  6885. editor.on('ObjectResizeStart', function (e) {
  6886. var targetElm = e.target;
  6887. if (isTable(targetElm)) {
  6888. var tableHasPercentage = getRawWidth(targetElm).map(function (w) {
  6889. return percentageBasedSizeRegex.test(w);
  6890. }).getOr(false);
  6891. if (tableHasPercentage && isPixelsForced(editor)) {
  6892. enforcePixels(targetElm);
  6893. } else if (!tableHasPercentage && isPercentagesForced(editor)) {
  6894. enforcePercentage(targetElm);
  6895. }
  6896. startW = e.width;
  6897. startRawW = getRawWidth(targetElm).getOr('');
  6898. }
  6899. });
  6900. editor.on('ObjectResized', function (e) {
  6901. var targetElm = e.target;
  6902. if (isTable(targetElm)) {
  6903. var table = targetElm;
  6904. if (percentageBasedSizeRegex.test(startRawW)) {
  6905. var percentW = parseFloat(percentageBasedSizeRegex.exec(startRawW)[1]);
  6906. var targetPercentW = e.width * percentW / startW;
  6907. editor.dom.setStyle(table, 'width', targetPercentW + '%');
  6908. } else {
  6909. var newCellSizes_1 = [];
  6910. global$1.each(table.rows, function (row) {
  6911. global$1.each(row.cells, function (cell) {
  6912. var width = editor.dom.getStyle(cell, 'width', true);
  6913. newCellSizes_1.push({
  6914. cell: cell,
  6915. width: width
  6916. });
  6917. });
  6918. });
  6919. global$1.each(newCellSizes_1, function (newCellSize) {
  6920. editor.dom.setStyle(newCellSize.cell, 'width', newCellSize.width);
  6921. editor.dom.setAttrib(newCellSize.cell, 'width', null);
  6922. });
  6923. }
  6924. }
  6925. });
  6926. editor.on('SwitchMode', function () {
  6927. lazyResize().each(function (resize) {
  6928. if (editor.readonly) {
  6929. resize.hideBars();
  6930. } else {
  6931. resize.showBars();
  6932. }
  6933. });
  6934. });
  6935. return {
  6936. lazyResize: lazyResize,
  6937. lazyWire: lazyWire,
  6938. destroy: destroy
  6939. };
  6940. };
  6941. var adt$1 = Adt.generate([
  6942. { none: ['current'] },
  6943. { first: ['current'] },
  6944. {
  6945. middle: [
  6946. 'current',
  6947. 'target'
  6948. ]
  6949. },
  6950. { last: ['current'] }
  6951. ]);
  6952. var none$1 = function (current) {
  6953. if (current === void 0) {
  6954. current = undefined;
  6955. }
  6956. return adt$1.none(current);
  6957. };
  6958. var CellLocation = __assign(__assign({}, adt$1), { none: none$1 });
  6959. var detect$4 = function (current, isRoot) {
  6960. return TableLookup.table(current, isRoot).bind(function (table) {
  6961. var all = TableLookup.cells(table);
  6962. var index = findIndex(all, function (x) {
  6963. return eq(current, x);
  6964. });
  6965. return index.map(function (ind) {
  6966. return {
  6967. index: constant(ind),
  6968. all: constant(all)
  6969. };
  6970. });
  6971. });
  6972. };
  6973. var next = function (current, isRoot) {
  6974. var detection = detect$4(current, isRoot);
  6975. return detection.fold(function () {
  6976. return CellLocation.none(current);
  6977. }, function (info) {
  6978. return info.index() + 1 < info.all().length ? CellLocation.middle(current, info.all()[info.index() + 1]) : CellLocation.last(current);
  6979. });
  6980. };
  6981. var prev = function (current, isRoot) {
  6982. var detection = detect$4(current, isRoot);
  6983. return detection.fold(function () {
  6984. return CellLocation.none();
  6985. }, function (info) {
  6986. return info.index() - 1 >= 0 ? CellLocation.middle(current, info.all()[info.index() - 1]) : CellLocation.first(current);
  6987. });
  6988. };
  6989. var CellNavigation = {
  6990. next: next,
  6991. prev: prev
  6992. };
  6993. var create$3 = Immutable('start', 'soffset', 'finish', 'foffset');
  6994. var SimRange = { create: create$3 };
  6995. var adt$2 = Adt.generate([
  6996. { before: ['element'] },
  6997. {
  6998. on: [
  6999. 'element',
  7000. 'offset'
  7001. ]
  7002. },
  7003. { after: ['element'] }
  7004. ]);
  7005. var cata$1 = function (subject, onBefore, onOn, onAfter) {
  7006. return subject.fold(onBefore, onOn, onAfter);
  7007. };
  7008. var getStart = function (situ) {
  7009. return situ.fold(identity, identity, identity);
  7010. };
  7011. var before$2 = adt$2.before;
  7012. var on = adt$2.on;
  7013. var after$2 = adt$2.after;
  7014. var Situ = {
  7015. before: before$2,
  7016. on: on,
  7017. after: after$2,
  7018. cata: cata$1,
  7019. getStart: getStart
  7020. };
  7021. var adt$3 = Adt.generate([
  7022. { domRange: ['rng'] },
  7023. {
  7024. relative: [
  7025. 'startSitu',
  7026. 'finishSitu'
  7027. ]
  7028. },
  7029. {
  7030. exact: [
  7031. 'start',
  7032. 'soffset',
  7033. 'finish',
  7034. 'foffset'
  7035. ]
  7036. }
  7037. ]);
  7038. var exactFromRange = function (simRange) {
  7039. return adt$3.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  7040. };
  7041. var getStart$1 = function (selection) {
  7042. return selection.match({
  7043. domRange: function (rng) {
  7044. return Element.fromDom(rng.startContainer);
  7045. },
  7046. relative: function (startSitu, finishSitu) {
  7047. return Situ.getStart(startSitu);
  7048. },
  7049. exact: function (start, soffset, finish, foffset) {
  7050. return start;
  7051. }
  7052. });
  7053. };
  7054. var domRange = adt$3.domRange;
  7055. var relative = adt$3.relative;
  7056. var exact = adt$3.exact;
  7057. var getWin = function (selection) {
  7058. var start = getStart$1(selection);
  7059. return defaultView(start);
  7060. };
  7061. var range$1 = SimRange.create;
  7062. var Selection = {
  7063. domRange: domRange,
  7064. relative: relative,
  7065. exact: exact,
  7066. exactFromRange: exactFromRange,
  7067. getWin: getWin,
  7068. range: range$1
  7069. };
  7070. var selectNodeContents = function (win, element) {
  7071. var rng = win.document.createRange();
  7072. selectNodeContentsUsing(rng, element);
  7073. return rng;
  7074. };
  7075. var selectNodeContentsUsing = function (rng, element) {
  7076. rng.selectNodeContents(element.dom());
  7077. };
  7078. var setStart = function (rng, situ) {
  7079. situ.fold(function (e) {
  7080. rng.setStartBefore(e.dom());
  7081. }, function (e, o) {
  7082. rng.setStart(e.dom(), o);
  7083. }, function (e) {
  7084. rng.setStartAfter(e.dom());
  7085. });
  7086. };
  7087. var setFinish = function (rng, situ) {
  7088. situ.fold(function (e) {
  7089. rng.setEndBefore(e.dom());
  7090. }, function (e, o) {
  7091. rng.setEnd(e.dom(), o);
  7092. }, function (e) {
  7093. rng.setEndAfter(e.dom());
  7094. });
  7095. };
  7096. var relativeToNative = function (win, startSitu, finishSitu) {
  7097. var range = win.document.createRange();
  7098. setStart(range, startSitu);
  7099. setFinish(range, finishSitu);
  7100. return range;
  7101. };
  7102. var exactToNative = function (win, start, soffset, finish, foffset) {
  7103. var rng = win.document.createRange();
  7104. rng.setStart(start.dom(), soffset);
  7105. rng.setEnd(finish.dom(), foffset);
  7106. return rng;
  7107. };
  7108. var toRect = function (rect) {
  7109. return {
  7110. left: constant(rect.left),
  7111. top: constant(rect.top),
  7112. right: constant(rect.right),
  7113. bottom: constant(rect.bottom),
  7114. width: constant(rect.width),
  7115. height: constant(rect.height)
  7116. };
  7117. };
  7118. var getFirstRect = function (rng) {
  7119. var rects = rng.getClientRects();
  7120. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  7121. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  7122. };
  7123. var adt$4 = Adt.generate([
  7124. {
  7125. ltr: [
  7126. 'start',
  7127. 'soffset',
  7128. 'finish',
  7129. 'foffset'
  7130. ]
  7131. },
  7132. {
  7133. rtl: [
  7134. 'start',
  7135. 'soffset',
  7136. 'finish',
  7137. 'foffset'
  7138. ]
  7139. }
  7140. ]);
  7141. var fromRange = function (win, type, range) {
  7142. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  7143. };
  7144. var getRanges = function (win, selection) {
  7145. return selection.match({
  7146. domRange: function (rng) {
  7147. return {
  7148. ltr: constant(rng),
  7149. rtl: Option.none
  7150. };
  7151. },
  7152. relative: function (startSitu, finishSitu) {
  7153. return {
  7154. ltr: cached(function () {
  7155. return relativeToNative(win, startSitu, finishSitu);
  7156. }),
  7157. rtl: cached(function () {
  7158. return Option.some(relativeToNative(win, finishSitu, startSitu));
  7159. })
  7160. };
  7161. },
  7162. exact: function (start, soffset, finish, foffset) {
  7163. return {
  7164. ltr: cached(function () {
  7165. return exactToNative(win, start, soffset, finish, foffset);
  7166. }),
  7167. rtl: cached(function () {
  7168. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  7169. })
  7170. };
  7171. }
  7172. });
  7173. };
  7174. var doDiagnose = function (win, ranges) {
  7175. var rng = ranges.ltr();
  7176. if (rng.collapsed) {
  7177. var reversed = ranges.rtl().filter(function (rev) {
  7178. return rev.collapsed === false;
  7179. });
  7180. return reversed.map(function (rev) {
  7181. return adt$4.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  7182. }).getOrThunk(function () {
  7183. return fromRange(win, adt$4.ltr, rng);
  7184. });
  7185. } else {
  7186. return fromRange(win, adt$4.ltr, rng);
  7187. }
  7188. };
  7189. var diagnose = function (win, selection) {
  7190. var ranges = getRanges(win, selection);
  7191. return doDiagnose(win, ranges);
  7192. };
  7193. var asLtrRange = function (win, selection) {
  7194. var diagnosis = diagnose(win, selection);
  7195. return diagnosis.match({
  7196. ltr: function (start, soffset, finish, foffset) {
  7197. var rng = win.document.createRange();
  7198. rng.setStart(start.dom(), soffset);
  7199. rng.setEnd(finish.dom(), foffset);
  7200. return rng;
  7201. },
  7202. rtl: function (start, soffset, finish, foffset) {
  7203. var rng = win.document.createRange();
  7204. rng.setStart(finish.dom(), foffset);
  7205. rng.setEnd(start.dom(), soffset);
  7206. return rng;
  7207. }
  7208. });
  7209. };
  7210. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  7211. if (length === 0) {
  7212. return 0;
  7213. } else if (x === maxX) {
  7214. return length - 1;
  7215. }
  7216. var xDelta = maxX;
  7217. for (var i = 1; i < length; i++) {
  7218. var rect = rectForOffset(i);
  7219. var curDeltaX = Math.abs(x - rect.left);
  7220. if (y <= rect.bottom) {
  7221. if (y < rect.top || curDeltaX > xDelta) {
  7222. return i - 1;
  7223. } else {
  7224. xDelta = curDeltaX;
  7225. }
  7226. }
  7227. }
  7228. return 0;
  7229. };
  7230. var inRect = function (rect, x, y) {
  7231. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  7232. };
  7233. var locateOffset = function (doc, textnode, x, y, rect) {
  7234. var rangeForOffset = function (o) {
  7235. var r = doc.dom().createRange();
  7236. r.setStart(textnode.dom(), o);
  7237. r.collapse(true);
  7238. return r;
  7239. };
  7240. var rectForOffset = function (o) {
  7241. var r = rangeForOffset(o);
  7242. return r.getBoundingClientRect();
  7243. };
  7244. var length = get$3(textnode).length;
  7245. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  7246. return rangeForOffset(offset);
  7247. };
  7248. var locate = function (doc, node, x, y) {
  7249. var r = doc.dom().createRange();
  7250. r.selectNode(node.dom());
  7251. var rects = r.getClientRects();
  7252. var foundRect = findMap(rects, function (rect) {
  7253. return inRect(rect, x, y) ? Option.some(rect) : Option.none();
  7254. });
  7255. return foundRect.map(function (rect) {
  7256. return locateOffset(doc, node, x, y, rect);
  7257. });
  7258. };
  7259. var searchInChildren = function (doc, node, x, y) {
  7260. var r = doc.dom().createRange();
  7261. var nodes = children(node);
  7262. return findMap(nodes, function (n) {
  7263. r.selectNode(n.dom());
  7264. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none();
  7265. });
  7266. };
  7267. var locateNode = function (doc, node, x, y) {
  7268. return isText(node) ? locate(doc, node, x, y) : searchInChildren(doc, node, x, y);
  7269. };
  7270. var locate$1 = function (doc, node, x, y) {
  7271. var r = doc.dom().createRange();
  7272. r.selectNode(node.dom());
  7273. var rect = r.getBoundingClientRect();
  7274. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  7275. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  7276. return locateNode(doc, node, boundedX, boundedY);
  7277. };
  7278. var COLLAPSE_TO_LEFT = true;
  7279. var COLLAPSE_TO_RIGHT = false;
  7280. var getCollapseDirection = function (rect, x) {
  7281. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  7282. };
  7283. var createCollapsedNode = function (doc, target, collapseDirection) {
  7284. var r = doc.dom().createRange();
  7285. r.selectNode(target.dom());
  7286. r.collapse(collapseDirection);
  7287. return r;
  7288. };
  7289. var locateInElement = function (doc, node, x) {
  7290. var cursorRange = doc.dom().createRange();
  7291. cursorRange.selectNode(node.dom());
  7292. var rect = cursorRange.getBoundingClientRect();
  7293. var collapseDirection = getCollapseDirection(rect, x);
  7294. var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
  7295. return f(node).map(function (target) {
  7296. return createCollapsedNode(doc, target, collapseDirection);
  7297. });
  7298. };
  7299. var locateInEmpty = function (doc, node, x) {
  7300. var rect = node.dom().getBoundingClientRect();
  7301. var collapseDirection = getCollapseDirection(rect, x);
  7302. return Option.some(createCollapsedNode(doc, node, collapseDirection));
  7303. };
  7304. var search = function (doc, node, x) {
  7305. var f = children(node).length === 0 ? locateInEmpty : locateInElement;
  7306. return f(doc, node, x);
  7307. };
  7308. var caretPositionFromPoint = function (doc, x, y) {
  7309. return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) {
  7310. if (pos.offsetNode === null) {
  7311. return Option.none();
  7312. }
  7313. var r = doc.dom().createRange();
  7314. r.setStart(pos.offsetNode, pos.offset);
  7315. r.collapse();
  7316. return Option.some(r);
  7317. });
  7318. };
  7319. var caretRangeFromPoint = function (doc, x, y) {
  7320. return Option.from(doc.dom().caretRangeFromPoint(x, y));
  7321. };
  7322. var searchTextNodes = function (doc, node, x, y) {
  7323. var r = doc.dom().createRange();
  7324. r.selectNode(node.dom());
  7325. var rect = r.getBoundingClientRect();
  7326. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  7327. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  7328. return locate$1(doc, node, boundedX, boundedY);
  7329. };
  7330. var searchFromPoint = function (doc, x, y) {
  7331. return Element.fromPoint(doc, x, y).bind(function (elem) {
  7332. var fallback = function () {
  7333. return search(doc, elem, x);
  7334. };
  7335. return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  7336. });
  7337. };
  7338. var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
  7339. var fromPoint$1 = function (win, x, y) {
  7340. var doc = Element.fromDom(win.document);
  7341. return availableSearch(doc, x, y).map(function (rng) {
  7342. return SimRange.create(Element.fromDom(rng.startContainer), rng.startOffset, Element.fromDom(rng.endContainer), rng.endOffset);
  7343. });
  7344. };
  7345. var beforeSpecial = function (element, offset) {
  7346. var name$1 = name(element);
  7347. if ('input' === name$1) {
  7348. return Situ.after(element);
  7349. } else if (!contains([
  7350. 'br',
  7351. 'img'
  7352. ], name$1)) {
  7353. return Situ.on(element, offset);
  7354. } else {
  7355. return offset === 0 ? Situ.before(element) : Situ.after(element);
  7356. }
  7357. };
  7358. var preprocessRelative = function (startSitu, finishSitu) {
  7359. var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  7360. var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  7361. return Selection.relative(start, finish);
  7362. };
  7363. var preprocessExact = function (start, soffset, finish, foffset) {
  7364. var startSitu = beforeSpecial(start, soffset);
  7365. var finishSitu = beforeSpecial(finish, foffset);
  7366. return Selection.relative(startSitu, finishSitu);
  7367. };
  7368. var preprocess = function (selection) {
  7369. return selection.match({
  7370. domRange: function (rng) {
  7371. var start = Element.fromDom(rng.startContainer);
  7372. var finish = Element.fromDom(rng.endContainer);
  7373. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  7374. },
  7375. relative: preprocessRelative,
  7376. exact: preprocessExact
  7377. });
  7378. };
  7379. var makeRange = function (start, soffset, finish, foffset) {
  7380. var doc = owner(start);
  7381. var rng = doc.dom().createRange();
  7382. rng.setStart(start.dom(), soffset);
  7383. rng.setEnd(finish.dom(), foffset);
  7384. return rng;
  7385. };
  7386. var after$3 = function (start, soffset, finish, foffset) {
  7387. var r = makeRange(start, soffset, finish, foffset);
  7388. var same = eq(start, finish) && soffset === foffset;
  7389. return r.collapsed && !same;
  7390. };
  7391. var doSetNativeRange = function (win, rng) {
  7392. Option.from(win.getSelection()).each(function (selection) {
  7393. selection.removeAllRanges();
  7394. selection.addRange(rng);
  7395. });
  7396. };
  7397. var doSetRange = function (win, start, soffset, finish, foffset) {
  7398. var rng = exactToNative(win, start, soffset, finish, foffset);
  7399. doSetNativeRange(win, rng);
  7400. };
  7401. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  7402. selection.collapse(start.dom(), soffset);
  7403. selection.extend(finish.dom(), foffset);
  7404. };
  7405. var setRangeFromRelative = function (win, relative) {
  7406. return diagnose(win, relative).match({
  7407. ltr: function (start, soffset, finish, foffset) {
  7408. doSetRange(win, start, soffset, finish, foffset);
  7409. },
  7410. rtl: function (start, soffset, finish, foffset) {
  7411. var selection = win.getSelection();
  7412. if (selection.setBaseAndExtent) {
  7413. selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
  7414. } else if (selection.extend) {
  7415. try {
  7416. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  7417. } catch (e) {
  7418. doSetRange(win, finish, foffset, start, soffset);
  7419. }
  7420. } else {
  7421. doSetRange(win, finish, foffset, start, soffset);
  7422. }
  7423. }
  7424. });
  7425. };
  7426. var setExact = function (win, start, soffset, finish, foffset) {
  7427. var relative = preprocessExact(start, soffset, finish, foffset);
  7428. setRangeFromRelative(win, relative);
  7429. };
  7430. var setRelative = function (win, startSitu, finishSitu) {
  7431. var relative = preprocessRelative(startSitu, finishSitu);
  7432. setRangeFromRelative(win, relative);
  7433. };
  7434. var toNative = function (selection) {
  7435. var win = Selection.getWin(selection).dom();
  7436. var getDomRange = function (start, soffset, finish, foffset) {
  7437. return exactToNative(win, start, soffset, finish, foffset);
  7438. };
  7439. var filtered = preprocess(selection);
  7440. return diagnose(win, filtered).match({
  7441. ltr: getDomRange,
  7442. rtl: getDomRange
  7443. });
  7444. };
  7445. var readRange = function (selection) {
  7446. if (selection.rangeCount > 0) {
  7447. var firstRng = selection.getRangeAt(0);
  7448. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  7449. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  7450. } else {
  7451. return Option.none();
  7452. }
  7453. };
  7454. var doGetExact = function (selection) {
  7455. var anchor = Element.fromDom(selection.anchorNode);
  7456. var focus = Element.fromDom(selection.focusNode);
  7457. return after$3(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  7458. };
  7459. var setToElement = function (win, element) {
  7460. var rng = selectNodeContents(win, element);
  7461. doSetNativeRange(win, rng);
  7462. };
  7463. var getExact = function (win) {
  7464. return Option.from(win.getSelection()).filter(function (sel) {
  7465. return sel.rangeCount > 0;
  7466. }).bind(doGetExact);
  7467. };
  7468. var get$a = function (win) {
  7469. return getExact(win).map(function (range) {
  7470. return Selection.exact(range.start(), range.soffset(), range.finish(), range.foffset());
  7471. });
  7472. };
  7473. var getFirstRect$1 = function (win, selection) {
  7474. var rng = asLtrRange(win, selection);
  7475. return getFirstRect(rng);
  7476. };
  7477. var getAtPoint = function (win, x, y) {
  7478. return fromPoint$1(win, x, y);
  7479. };
  7480. var clear = function (win) {
  7481. var selection = win.getSelection();
  7482. selection.removeAllRanges();
  7483. };
  7484. var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK');
  7485. var forward = function (editor, isRoot, cell, lazyWire) {
  7486. return go(editor, isRoot, CellNavigation.next(cell), lazyWire);
  7487. };
  7488. var backward = function (editor, isRoot, cell, lazyWire) {
  7489. return go(editor, isRoot, CellNavigation.prev(cell), lazyWire);
  7490. };
  7491. var getCellFirstCursorPosition = function (editor, cell) {
  7492. var selection = Selection.exact(cell, 0, cell, 0);
  7493. return toNative(selection);
  7494. };
  7495. var getNewRowCursorPosition = function (editor, table) {
  7496. var rows = descendants$1(table, 'tr');
  7497. return last(rows).bind(function (last) {
  7498. return descendant$1(last, 'td,th').map(function (first) {
  7499. return getCellFirstCursorPosition(editor, first);
  7500. });
  7501. });
  7502. };
  7503. var go = function (editor, isRoot, cell, actions, lazyWire) {
  7504. return cell.fold(Option.none, Option.none, function (current, next) {
  7505. return first(next).map(function (cell) {
  7506. return getCellFirstCursorPosition(editor, cell);
  7507. });
  7508. }, function (current) {
  7509. return TableLookup.table(current, isRoot).bind(function (table) {
  7510. var targets = TableTargets.noMenu(current);
  7511. editor.undoManager.transact(function () {
  7512. actions.insertRowsAfter(table, targets);
  7513. });
  7514. return getNewRowCursorPosition(editor, table);
  7515. });
  7516. });
  7517. };
  7518. var rootElements = [
  7519. 'table',
  7520. 'li',
  7521. 'dl'
  7522. ];
  7523. var handle$1 = function (event, editor, actions, lazyWire) {
  7524. if (event.keyCode === global$3.TAB) {
  7525. var body_1 = getBody$1(editor);
  7526. var isRoot_1 = function (element) {
  7527. var name$1 = name(element);
  7528. return eq(element, body_1) || contains(rootElements, name$1);
  7529. };
  7530. var rng = editor.selection.getRng();
  7531. if (rng.collapsed) {
  7532. var start = Element.fromDom(rng.startContainer);
  7533. TableLookup.cell(start, isRoot_1).each(function (cell) {
  7534. event.preventDefault();
  7535. var navigation = event.shiftKey ? backward : forward;
  7536. var rng = navigation(editor, isRoot_1, cell, actions, lazyWire);
  7537. rng.each(function (range) {
  7538. editor.selection.setRng(range);
  7539. });
  7540. });
  7541. }
  7542. }
  7543. };
  7544. var TabContext = { handle: handle$1 };
  7545. var create$4 = Immutable('selection', 'kill');
  7546. var Response = { create: create$4 };
  7547. var create$5 = function (start, soffset, finish, foffset) {
  7548. return {
  7549. start: constant(Situ.on(start, soffset)),
  7550. finish: constant(Situ.on(finish, foffset))
  7551. };
  7552. };
  7553. var Situs = { create: create$5 };
  7554. var convertToRange = function (win, selection) {
  7555. var rng = asLtrRange(win, selection);
  7556. return SimRange.create(Element.fromDom(rng.startContainer), rng.startOffset, Element.fromDom(rng.endContainer), rng.endOffset);
  7557. };
  7558. var makeSitus = Situs.create;
  7559. var Util = {
  7560. convertToRange: convertToRange,
  7561. makeSitus: makeSitus
  7562. };
  7563. var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
  7564. if (!(eq(start, finish) && soffset === foffset)) {
  7565. return closest$1(start, 'td,th', isRoot).bind(function (s) {
  7566. return closest$1(finish, 'td,th', isRoot).bind(function (f) {
  7567. return detect$5(container, isRoot, s, f, selectRange);
  7568. });
  7569. });
  7570. } else {
  7571. return Option.none();
  7572. }
  7573. };
  7574. var detect$5 = function (container, isRoot, start, finish, selectRange) {
  7575. if (!eq(start, finish)) {
  7576. return CellSelection.identify(start, finish, isRoot).bind(function (cellSel) {
  7577. var boxes = cellSel.boxes().getOr([]);
  7578. if (boxes.length > 0) {
  7579. selectRange(container, boxes, cellSel.start(), cellSel.finish());
  7580. return Option.some(Response.create(Option.some(Util.makeSitus(start, 0, start, getEnd(start))), true));
  7581. } else {
  7582. return Option.none();
  7583. }
  7584. });
  7585. } else {
  7586. return Option.none();
  7587. }
  7588. };
  7589. var update = function (rows, columns, container, selected, annotations) {
  7590. var updateSelection = function (newSels) {
  7591. annotations.clearBeforeUpdate(container);
  7592. annotations.selectRange(container, newSels.boxes(), newSels.start(), newSels.finish());
  7593. return newSels.boxes();
  7594. };
  7595. return CellSelection.shiftSelection(selected, rows, columns, annotations.firstSelectedSelector(), annotations.lastSelectedSelector()).map(updateSelection);
  7596. };
  7597. var KeySelection = {
  7598. sync: sync,
  7599. detect: detect$5,
  7600. update: update
  7601. };
  7602. var traverse = Immutable('item', 'mode');
  7603. var backtrack = function (universe, item, _direction, transition) {
  7604. if (transition === void 0) {
  7605. transition = sidestep;
  7606. }
  7607. return universe.property().parent(item).map(function (p) {
  7608. return traverse(p, transition);
  7609. });
  7610. };
  7611. var sidestep = function (universe, item, direction, transition) {
  7612. if (transition === void 0) {
  7613. transition = advance;
  7614. }
  7615. return direction.sibling(universe, item).map(function (p) {
  7616. return traverse(p, transition);
  7617. });
  7618. };
  7619. var advance = function (universe, item, direction, transition) {
  7620. if (transition === void 0) {
  7621. transition = advance;
  7622. }
  7623. var children = universe.property().children(item);
  7624. var result = direction.first(children);
  7625. return result.map(function (r) {
  7626. return traverse(r, transition);
  7627. });
  7628. };
  7629. var successors = [
  7630. {
  7631. current: backtrack,
  7632. next: sidestep,
  7633. fallback: Option.none()
  7634. },
  7635. {
  7636. current: sidestep,
  7637. next: advance,
  7638. fallback: Option.some(backtrack)
  7639. },
  7640. {
  7641. current: advance,
  7642. next: advance,
  7643. fallback: Option.some(sidestep)
  7644. }
  7645. ];
  7646. var go$1 = function (universe, item, mode, direction, rules) {
  7647. if (rules === void 0) {
  7648. rules = successors;
  7649. }
  7650. var ruleOpt = find(rules, function (succ) {
  7651. return succ.current === mode;
  7652. });
  7653. return ruleOpt.bind(function (rule) {
  7654. return rule.current(universe, item, direction, rule.next).orThunk(function () {
  7655. return rule.fallback.bind(function (fb) {
  7656. return go$1(universe, item, fb, direction);
  7657. });
  7658. });
  7659. });
  7660. };
  7661. var left = function () {
  7662. var sibling = function (universe, item) {
  7663. return universe.query().prevSibling(item);
  7664. };
  7665. var first = function (children) {
  7666. return children.length > 0 ? Option.some(children[children.length - 1]) : Option.none();
  7667. };
  7668. return {
  7669. sibling: sibling,
  7670. first: first
  7671. };
  7672. };
  7673. var right = function () {
  7674. var sibling = function (universe, item) {
  7675. return universe.query().nextSibling(item);
  7676. };
  7677. var first = function (children) {
  7678. return children.length > 0 ? Option.some(children[0]) : Option.none();
  7679. };
  7680. return {
  7681. sibling: sibling,
  7682. first: first
  7683. };
  7684. };
  7685. var Walkers = {
  7686. left: left,
  7687. right: right
  7688. };
  7689. var hone = function (universe, item, predicate, mode, direction, isRoot) {
  7690. var next = go$1(universe, item, mode, direction);
  7691. return next.bind(function (n) {
  7692. if (isRoot(n.item())) {
  7693. return Option.none();
  7694. } else {
  7695. return predicate(n.item()) ? Option.some(n.item()) : hone(universe, n.item(), predicate, n.mode(), direction, isRoot);
  7696. }
  7697. });
  7698. };
  7699. var left$1 = function (universe, item, predicate, isRoot) {
  7700. return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
  7701. };
  7702. var right$1 = function (universe, item, predicate, isRoot) {
  7703. return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
  7704. };
  7705. var isLeaf = function (universe) {
  7706. return function (element) {
  7707. return universe.property().children(element).length === 0;
  7708. };
  7709. };
  7710. var before$3 = function (universe, item, isRoot) {
  7711. return seekLeft(universe, item, isLeaf(universe), isRoot);
  7712. };
  7713. var after$4 = function (universe, item, isRoot) {
  7714. return seekRight(universe, item, isLeaf(universe), isRoot);
  7715. };
  7716. var seekLeft = left$1;
  7717. var seekRight = right$1;
  7718. var universe$2 = DomUniverse();
  7719. var before$4 = function (element, isRoot) {
  7720. return before$3(universe$2, element, isRoot);
  7721. };
  7722. var after$5 = function (element, isRoot) {
  7723. return after$4(universe$2, element, isRoot);
  7724. };
  7725. var seekLeft$1 = function (element, predicate, isRoot) {
  7726. return seekLeft(universe$2, element, predicate, isRoot);
  7727. };
  7728. var seekRight$1 = function (element, predicate, isRoot) {
  7729. return seekRight(universe$2, element, predicate, isRoot);
  7730. };
  7731. var ancestor$2 = function (scope, predicate, isRoot) {
  7732. return ancestor(scope, predicate, isRoot).isSome();
  7733. };
  7734. var point = Immutable('element', 'offset');
  7735. var delta = Immutable('element', 'deltaOffset');
  7736. var range$2 = Immutable('element', 'start', 'finish');
  7737. var points = Immutable('begin', 'end');
  7738. var text = Immutable('element', 'text');
  7739. var adt$5 = Adt.generate([
  7740. { none: ['message'] },
  7741. { success: [] },
  7742. { failedUp: ['cell'] },
  7743. { failedDown: ['cell'] }
  7744. ]);
  7745. var isOverlapping = function (bridge, before, after) {
  7746. var beforeBounds = bridge.getRect(before);
  7747. var afterBounds = bridge.getRect(after);
  7748. return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
  7749. };
  7750. var isRow = function (elem) {
  7751. return closest$1(elem, 'tr');
  7752. };
  7753. var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
  7754. return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
  7755. return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
  7756. if (!eq(afterCell, beforeCell)) {
  7757. return DomParent.sharedOne(isRow, [
  7758. afterCell,
  7759. beforeCell
  7760. ]).fold(function () {
  7761. return isOverlapping(bridge, beforeCell, afterCell) ? adt$5.success() : failure(beforeCell);
  7762. }, function (_sharedRow) {
  7763. return failure(beforeCell);
  7764. });
  7765. } else {
  7766. return eq(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$5.none('in same cell');
  7767. }
  7768. });
  7769. }).getOr(adt$5.none('default'));
  7770. };
  7771. var cata$2 = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
  7772. return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
  7773. };
  7774. var BeforeAfter = __assign(__assign({}, adt$5), {
  7775. verify: verify,
  7776. cata: cata$2
  7777. });
  7778. var inAncestor = Immutable('ancestor', 'descendants', 'element', 'index');
  7779. var inParent = Immutable('parent', 'children', 'element', 'index');
  7780. var indexInParent = function (element) {
  7781. return parent(element).bind(function (parent) {
  7782. var children$1 = children(parent);
  7783. return indexOf(children$1, element).map(function (index) {
  7784. return inParent(parent, children$1, element, index);
  7785. });
  7786. });
  7787. };
  7788. var indexOf = function (elements, element) {
  7789. return findIndex(elements, curry(eq, element));
  7790. };
  7791. var isBr = function (elem) {
  7792. return name(elem) === 'br';
  7793. };
  7794. var gatherer = function (cand, gather, isRoot) {
  7795. return gather(cand, isRoot).bind(function (target) {
  7796. return isText(target) && get$3(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Option.some(target);
  7797. });
  7798. };
  7799. var handleBr = function (isRoot, element, direction) {
  7800. return direction.traverse(element).orThunk(function () {
  7801. return gatherer(element, direction.gather, isRoot);
  7802. }).map(direction.relative);
  7803. };
  7804. var findBr = function (element, offset) {
  7805. return child(element, offset).filter(isBr).orThunk(function () {
  7806. return child(element, offset - 1).filter(isBr);
  7807. });
  7808. };
  7809. var handleParent = function (isRoot, element, offset, direction) {
  7810. return findBr(element, offset).bind(function (br) {
  7811. return direction.traverse(br).fold(function () {
  7812. return gatherer(br, direction.gather, isRoot).map(direction.relative);
  7813. }, function (adjacent) {
  7814. return indexInParent(adjacent).map(function (info) {
  7815. return Situ.on(info.parent(), info.index());
  7816. });
  7817. });
  7818. });
  7819. };
  7820. var tryBr = function (isRoot, element, offset, direction) {
  7821. var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
  7822. return target.map(function (tgt) {
  7823. return {
  7824. start: constant(tgt),
  7825. finish: constant(tgt)
  7826. };
  7827. });
  7828. };
  7829. var process = function (analysis) {
  7830. return BeforeAfter.cata(analysis, function (message) {
  7831. return Option.none();
  7832. }, function () {
  7833. return Option.none();
  7834. }, function (cell) {
  7835. return Option.some(point(cell, 0));
  7836. }, function (cell) {
  7837. return Option.some(point(cell, getEnd(cell)));
  7838. });
  7839. };
  7840. var BrTags = {
  7841. tryBr: tryBr,
  7842. process: process
  7843. };
  7844. var nu$3 = MixedBag([
  7845. 'left',
  7846. 'top',
  7847. 'right',
  7848. 'bottom'
  7849. ], []);
  7850. var moveDown = function (caret, amount) {
  7851. return nu$3({
  7852. left: caret.left(),
  7853. top: caret.top() + amount,
  7854. right: caret.right(),
  7855. bottom: caret.bottom() + amount
  7856. });
  7857. };
  7858. var moveUp = function (caret, amount) {
  7859. return nu$3({
  7860. left: caret.left(),
  7861. top: caret.top() - amount,
  7862. right: caret.right(),
  7863. bottom: caret.bottom() - amount
  7864. });
  7865. };
  7866. var moveBottomTo = function (caret, bottom) {
  7867. var height = caret.bottom() - caret.top();
  7868. return nu$3({
  7869. left: caret.left(),
  7870. top: bottom - height,
  7871. right: caret.right(),
  7872. bottom: bottom
  7873. });
  7874. };
  7875. var moveTopTo = function (caret, top) {
  7876. var height = caret.bottom() - caret.top();
  7877. return nu$3({
  7878. left: caret.left(),
  7879. top: top,
  7880. right: caret.right(),
  7881. bottom: top + height
  7882. });
  7883. };
  7884. var translate = function (caret, xDelta, yDelta) {
  7885. return nu$3({
  7886. left: caret.left() + xDelta,
  7887. top: caret.top() + yDelta,
  7888. right: caret.right() + xDelta,
  7889. bottom: caret.bottom() + yDelta
  7890. });
  7891. };
  7892. var getTop$1 = function (caret) {
  7893. return caret.top();
  7894. };
  7895. var getBottom = function (caret) {
  7896. return caret.bottom();
  7897. };
  7898. var toString = function (caret) {
  7899. return '(' + caret.left() + ', ' + caret.top() + ') -> (' + caret.right() + ', ' + caret.bottom() + ')';
  7900. };
  7901. var Carets = {
  7902. nu: nu$3,
  7903. moveUp: moveUp,
  7904. moveDown: moveDown,
  7905. moveBottomTo: moveBottomTo,
  7906. moveTopTo: moveTopTo,
  7907. getTop: getTop$1,
  7908. getBottom: getBottom,
  7909. translate: translate,
  7910. toString: toString
  7911. };
  7912. var getPartialBox = function (bridge, element, offset) {
  7913. if (offset >= 0 && offset < getEnd(element)) {
  7914. return bridge.getRangedRect(element, offset, element, offset + 1);
  7915. } else if (offset > 0) {
  7916. return bridge.getRangedRect(element, offset - 1, element, offset);
  7917. }
  7918. return Option.none();
  7919. };
  7920. var toCaret = function (rect) {
  7921. return Carets.nu({
  7922. left: rect.left,
  7923. top: rect.top,
  7924. right: rect.right,
  7925. bottom: rect.bottom
  7926. });
  7927. };
  7928. var getElemBox = function (bridge, element) {
  7929. return Option.some(bridge.getRect(element));
  7930. };
  7931. var getBoxAt = function (bridge, element, offset) {
  7932. if (isElement(element)) {
  7933. return getElemBox(bridge, element).map(toCaret);
  7934. } else if (isText(element)) {
  7935. return getPartialBox(bridge, element, offset).map(toCaret);
  7936. } else {
  7937. return Option.none();
  7938. }
  7939. };
  7940. var getEntireBox = function (bridge, element) {
  7941. if (isElement(element)) {
  7942. return getElemBox(bridge, element).map(toCaret);
  7943. } else if (isText(element)) {
  7944. return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
  7945. } else {
  7946. return Option.none();
  7947. }
  7948. };
  7949. var Rectangles = {
  7950. getBoxAt: getBoxAt,
  7951. getEntireBox: getEntireBox
  7952. };
  7953. var JUMP_SIZE = 5;
  7954. var NUM_RETRIES = 100;
  7955. var adt$6 = Adt.generate([
  7956. { none: [] },
  7957. { retry: ['caret'] }
  7958. ]);
  7959. var isOutside = function (caret, box) {
  7960. return caret.left() < box.left() || Math.abs(box.right() - caret.left()) < 1 || caret.left() > box.right();
  7961. };
  7962. var inOutsideBlock = function (bridge, element, caret) {
  7963. return closest(element, DomStructure.isBlock).fold(constant(false), function (cell) {
  7964. return Rectangles.getEntireBox(bridge, cell).exists(function (box) {
  7965. return isOutside(caret, box);
  7966. });
  7967. });
  7968. };
  7969. var adjustDown = function (bridge, element, guessBox, original, caret) {
  7970. var lowerCaret = Carets.moveDown(caret, JUMP_SIZE);
  7971. if (Math.abs(guessBox.bottom() - original.bottom()) < 1) {
  7972. return adt$6.retry(lowerCaret);
  7973. } else if (guessBox.top() > caret.bottom()) {
  7974. return adt$6.retry(lowerCaret);
  7975. } else if (guessBox.top() === caret.bottom()) {
  7976. return adt$6.retry(Carets.moveDown(caret, 1));
  7977. } else {
  7978. return inOutsideBlock(bridge, element, caret) ? adt$6.retry(Carets.translate(lowerCaret, JUMP_SIZE, 0)) : adt$6.none();
  7979. }
  7980. };
  7981. var adjustUp = function (bridge, element, guessBox, original, caret) {
  7982. var higherCaret = Carets.moveUp(caret, JUMP_SIZE);
  7983. if (Math.abs(guessBox.top() - original.top()) < 1) {
  7984. return adt$6.retry(higherCaret);
  7985. } else if (guessBox.bottom() < caret.top()) {
  7986. return adt$6.retry(higherCaret);
  7987. } else if (guessBox.bottom() === caret.top()) {
  7988. return adt$6.retry(Carets.moveUp(caret, 1));
  7989. } else {
  7990. return inOutsideBlock(bridge, element, caret) ? adt$6.retry(Carets.translate(higherCaret, JUMP_SIZE, 0)) : adt$6.none();
  7991. }
  7992. };
  7993. var upMovement = {
  7994. point: Carets.getTop,
  7995. adjuster: adjustUp,
  7996. move: Carets.moveUp,
  7997. gather: before$4
  7998. };
  7999. var downMovement = {
  8000. point: Carets.getBottom,
  8001. adjuster: adjustDown,
  8002. move: Carets.moveDown,
  8003. gather: after$5
  8004. };
  8005. var isAtTable = function (bridge, x, y) {
  8006. return bridge.elementFromPoint(x, y).filter(function (elm) {
  8007. return name(elm) === 'table';
  8008. }).isSome();
  8009. };
  8010. var adjustForTable = function (bridge, movement, original, caret, numRetries) {
  8011. return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
  8012. };
  8013. var adjustTil = function (bridge, movement, original, caret, numRetries) {
  8014. if (numRetries === 0) {
  8015. return Option.some(caret);
  8016. }
  8017. if (isAtTable(bridge, caret.left(), movement.point(caret))) {
  8018. return adjustForTable(bridge, movement, original, caret, numRetries - 1);
  8019. }
  8020. return bridge.situsFromPoint(caret.left(), movement.point(caret)).bind(function (guess) {
  8021. return guess.start().fold(Option.none, function (element) {
  8022. return Rectangles.getEntireBox(bridge, element).bind(function (guessBox) {
  8023. return movement.adjuster(bridge, element, guessBox, original, caret).fold(Option.none, function (newCaret) {
  8024. return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
  8025. });
  8026. }).orThunk(function () {
  8027. return Option.some(caret);
  8028. });
  8029. }, Option.none);
  8030. });
  8031. };
  8032. var ieTryDown = function (bridge, caret) {
  8033. return bridge.situsFromPoint(caret.left(), caret.bottom() + JUMP_SIZE);
  8034. };
  8035. var ieTryUp = function (bridge, caret) {
  8036. return bridge.situsFromPoint(caret.left(), caret.top() - JUMP_SIZE);
  8037. };
  8038. var checkScroll = function (movement, adjusted, bridge) {
  8039. if (movement.point(adjusted) > bridge.getInnerHeight()) {
  8040. return Option.some(movement.point(adjusted) - bridge.getInnerHeight());
  8041. } else if (movement.point(adjusted) < 0) {
  8042. return Option.some(-movement.point(adjusted));
  8043. } else {
  8044. return Option.none();
  8045. }
  8046. };
  8047. var retry = function (movement, bridge, caret) {
  8048. var moved = movement.move(caret, JUMP_SIZE);
  8049. var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
  8050. return checkScroll(movement, adjusted, bridge).fold(function () {
  8051. return bridge.situsFromPoint(adjusted.left(), movement.point(adjusted));
  8052. }, function (delta) {
  8053. bridge.scrollBy(0, delta);
  8054. return bridge.situsFromPoint(adjusted.left(), movement.point(adjusted) - delta);
  8055. });
  8056. };
  8057. var Retries = {
  8058. tryUp: curry(retry, upMovement),
  8059. tryDown: curry(retry, downMovement),
  8060. ieTryUp: ieTryUp,
  8061. ieTryDown: ieTryDown,
  8062. getJumpSize: constant(JUMP_SIZE)
  8063. };
  8064. var MAX_RETRIES = 20;
  8065. var platform$2 = detect$3();
  8066. var findSpot = function (bridge, isRoot, direction) {
  8067. return bridge.getSelection().bind(function (sel) {
  8068. return BrTags.tryBr(isRoot, sel.finish(), sel.foffset(), direction).fold(function () {
  8069. return Option.some(point(sel.finish(), sel.foffset()));
  8070. }, function (brNeighbour) {
  8071. var range = bridge.fromSitus(brNeighbour);
  8072. var analysis = BeforeAfter.verify(bridge, sel.finish(), sel.foffset(), range.finish(), range.foffset(), direction.failure, isRoot);
  8073. return BrTags.process(analysis);
  8074. });
  8075. });
  8076. };
  8077. var scan = function (bridge, isRoot, element, offset, direction, numRetries) {
  8078. if (numRetries === 0) {
  8079. return Option.none();
  8080. }
  8081. return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
  8082. var range = bridge.fromSitus(situs);
  8083. var analysis = BeforeAfter.verify(bridge, element, offset, range.finish(), range.foffset(), direction.failure, isRoot);
  8084. return BeforeAfter.cata(analysis, function () {
  8085. return Option.none();
  8086. }, function () {
  8087. return Option.some(situs);
  8088. }, function (cell) {
  8089. if (eq(element, cell) && offset === 0) {
  8090. return tryAgain(bridge, element, offset, Carets.moveUp, direction);
  8091. } else {
  8092. return scan(bridge, isRoot, cell, 0, direction, numRetries - 1);
  8093. }
  8094. }, function (cell) {
  8095. if (eq(element, cell) && offset === getEnd(cell)) {
  8096. return tryAgain(bridge, element, offset, Carets.moveDown, direction);
  8097. } else {
  8098. return scan(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
  8099. }
  8100. });
  8101. });
  8102. };
  8103. var tryAgain = function (bridge, element, offset, move, direction) {
  8104. return Rectangles.getBoxAt(bridge, element, offset).bind(function (box) {
  8105. return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
  8106. });
  8107. };
  8108. var tryAt = function (bridge, direction, box) {
  8109. if (platform$2.browser.isChrome() || platform$2.browser.isSafari() || platform$2.browser.isFirefox() || platform$2.browser.isEdge()) {
  8110. return direction.otherRetry(bridge, box);
  8111. } else if (platform$2.browser.isIE()) {
  8112. return direction.ieRetry(bridge, box);
  8113. } else {
  8114. return Option.none();
  8115. }
  8116. };
  8117. var tryCursor = function (bridge, isRoot, element, offset, direction) {
  8118. return Rectangles.getBoxAt(bridge, element, offset).bind(function (box) {
  8119. return tryAt(bridge, direction, box);
  8120. });
  8121. };
  8122. var handle$2 = function (bridge, isRoot, direction) {
  8123. return findSpot(bridge, isRoot, direction).bind(function (spot) {
  8124. return scan(bridge, isRoot, spot.element(), spot.offset(), direction, MAX_RETRIES).map(bridge.fromSitus);
  8125. });
  8126. };
  8127. var TableKeys = { handle: handle$2 };
  8128. var detection = detect$3();
  8129. var inSameTable = function (elem, table) {
  8130. return ancestor$2(elem, function (e) {
  8131. return parent(e).exists(function (p) {
  8132. return eq(p, table);
  8133. });
  8134. });
  8135. };
  8136. var simulate = function (bridge, isRoot, direction, initial, anchor) {
  8137. return closest$1(initial, 'td,th', isRoot).bind(function (start) {
  8138. return closest$1(start, 'table', isRoot).bind(function (table) {
  8139. if (!inSameTable(anchor, table)) {
  8140. return Option.none();
  8141. }
  8142. return TableKeys.handle(bridge, isRoot, direction).bind(function (range) {
  8143. return closest$1(range.finish(), 'td,th', isRoot).map(function (finish) {
  8144. return {
  8145. start: constant(start),
  8146. finish: constant(finish),
  8147. range: constant(range)
  8148. };
  8149. });
  8150. });
  8151. });
  8152. });
  8153. };
  8154. var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
  8155. if (detection.browser.isIE()) {
  8156. return Option.none();
  8157. } else {
  8158. return precheck(initial, isRoot).orThunk(function () {
  8159. return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
  8160. var range = info.range();
  8161. return Response.create(Option.some(Util.makeSitus(range.start(), range.soffset(), range.finish(), range.foffset())), true);
  8162. });
  8163. });
  8164. }
  8165. };
  8166. var firstUpCheck = function (initial, isRoot) {
  8167. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  8168. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  8169. var rows = descendants$1(table, 'tr');
  8170. if (eq(startRow, rows[0])) {
  8171. return seekLeft$1(table, function (element) {
  8172. return last$1(element).isSome();
  8173. }, isRoot).map(function (last) {
  8174. var lastOffset = getEnd(last);
  8175. return Response.create(Option.some(Util.makeSitus(last, lastOffset, last, lastOffset)), true);
  8176. });
  8177. } else {
  8178. return Option.none();
  8179. }
  8180. });
  8181. });
  8182. };
  8183. var lastDownCheck = function (initial, isRoot) {
  8184. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  8185. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  8186. var rows = descendants$1(table, 'tr');
  8187. if (eq(startRow, rows[rows.length - 1])) {
  8188. return seekRight$1(table, function (element) {
  8189. return first(element).isSome();
  8190. }, isRoot).map(function (first) {
  8191. return Response.create(Option.some(Util.makeSitus(first, 0, first, 0)), true);
  8192. });
  8193. } else {
  8194. return Option.none();
  8195. }
  8196. });
  8197. });
  8198. };
  8199. var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
  8200. return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
  8201. return KeySelection.detect(container, isRoot, info.start(), info.finish(), selectRange);
  8202. });
  8203. };
  8204. var VerticalMovement = {
  8205. navigate: navigate,
  8206. select: select,
  8207. firstUpCheck: firstUpCheck,
  8208. lastDownCheck: lastDownCheck
  8209. };
  8210. var findCell = function (target, isRoot) {
  8211. return closest$1(target, 'td,th', isRoot);
  8212. };
  8213. function MouseSelection (bridge, container, isRoot, annotations) {
  8214. var cursor = Option.none();
  8215. var clearState = function () {
  8216. cursor = Option.none();
  8217. };
  8218. var mousedown = function (event) {
  8219. annotations.clear(container);
  8220. cursor = findCell(event.target(), isRoot);
  8221. };
  8222. var mouseover = function (event) {
  8223. cursor.each(function (start) {
  8224. annotations.clearBeforeUpdate(container);
  8225. findCell(event.target(), isRoot).each(function (finish) {
  8226. CellSelection.identify(start, finish, isRoot).each(function (cellSel) {
  8227. var boxes = cellSel.boxes().getOr([]);
  8228. if (boxes.length > 1 || boxes.length === 1 && !eq(start, finish)) {
  8229. annotations.selectRange(container, boxes, cellSel.start(), cellSel.finish());
  8230. bridge.selectContents(finish);
  8231. }
  8232. });
  8233. });
  8234. });
  8235. };
  8236. var mouseup = function (_event) {
  8237. cursor.each(clearState);
  8238. };
  8239. return {
  8240. mousedown: mousedown,
  8241. mouseover: mouseover,
  8242. mouseup: mouseup
  8243. };
  8244. }
  8245. var down = {
  8246. traverse: nextSibling,
  8247. gather: after$5,
  8248. relative: Situ.before,
  8249. otherRetry: Retries.tryDown,
  8250. ieRetry: Retries.ieTryDown,
  8251. failure: BeforeAfter.failedDown
  8252. };
  8253. var up = {
  8254. traverse: prevSibling,
  8255. gather: before$4,
  8256. relative: Situ.before,
  8257. otherRetry: Retries.tryUp,
  8258. ieRetry: Retries.ieTryUp,
  8259. failure: BeforeAfter.failedUp
  8260. };
  8261. var KeyDirection = {
  8262. down: down,
  8263. up: up
  8264. };
  8265. var isKey = function (key) {
  8266. return function (keycode) {
  8267. return keycode === key;
  8268. };
  8269. };
  8270. var isUp = isKey(38);
  8271. var isDown = isKey(40);
  8272. var isNavigation = function (keycode) {
  8273. return keycode >= 37 && keycode <= 40;
  8274. };
  8275. var SelectionKeys = {
  8276. ltr: {
  8277. isBackward: isKey(37),
  8278. isForward: isKey(39)
  8279. },
  8280. rtl: {
  8281. isBackward: isKey(39),
  8282. isForward: isKey(37)
  8283. },
  8284. isUp: isUp,
  8285. isDown: isDown,
  8286. isNavigation: isNavigation
  8287. };
  8288. var toRaw = function (sr) {
  8289. return {
  8290. left: sr.left(),
  8291. top: sr.top(),
  8292. right: sr.right(),
  8293. bottom: sr.bottom(),
  8294. width: sr.width(),
  8295. height: sr.height()
  8296. };
  8297. };
  8298. var Rect = { toRaw: toRaw };
  8299. var isSafari = detect$3().browser.isSafari();
  8300. var get$b = function (_DOC) {
  8301. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  8302. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  8303. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  8304. return Position(x, y);
  8305. };
  8306. var by = function (x, y, _DOC) {
  8307. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  8308. var win = doc.defaultView;
  8309. win.scrollBy(x, y);
  8310. };
  8311. var WindowBridge = function (win) {
  8312. var elementFromPoint = function (x, y) {
  8313. return Element.fromPoint(Element.fromDom(win.document), x, y);
  8314. };
  8315. var getRect = function (element) {
  8316. return element.dom().getBoundingClientRect();
  8317. };
  8318. var getRangedRect = function (start, soffset, finish, foffset) {
  8319. var sel = Selection.exact(start, soffset, finish, foffset);
  8320. return getFirstRect$1(win, sel).map(Rect.toRaw);
  8321. };
  8322. var getSelection = function () {
  8323. return get$a(win).map(function (exactAdt) {
  8324. return Util.convertToRange(win, exactAdt);
  8325. });
  8326. };
  8327. var fromSitus = function (situs) {
  8328. var relative = Selection.relative(situs.start(), situs.finish());
  8329. return Util.convertToRange(win, relative);
  8330. };
  8331. var situsFromPoint = function (x, y) {
  8332. return getAtPoint(win, x, y).map(function (exact) {
  8333. return Situs.create(exact.start(), exact.soffset(), exact.finish(), exact.foffset());
  8334. });
  8335. };
  8336. var clearSelection = function () {
  8337. clear(win);
  8338. };
  8339. var selectContents = function (element) {
  8340. setToElement(win, element);
  8341. };
  8342. var setSelection = function (sel) {
  8343. setExact(win, sel.start(), sel.soffset(), sel.finish(), sel.foffset());
  8344. };
  8345. var setRelativeSelection = function (start, finish) {
  8346. setRelative(win, start, finish);
  8347. };
  8348. var getInnerHeight = function () {
  8349. return win.innerHeight;
  8350. };
  8351. var getScrollY = function () {
  8352. var pos = get$b(Element.fromDom(win.document));
  8353. return pos.top();
  8354. };
  8355. var scrollBy = function (x, y) {
  8356. by(x, y, Element.fromDom(win.document));
  8357. };
  8358. return {
  8359. elementFromPoint: elementFromPoint,
  8360. getRect: getRect,
  8361. getRangedRect: getRangedRect,
  8362. getSelection: getSelection,
  8363. fromSitus: fromSitus,
  8364. situsFromPoint: situsFromPoint,
  8365. clearSelection: clearSelection,
  8366. setSelection: setSelection,
  8367. setRelativeSelection: setRelativeSelection,
  8368. selectContents: selectContents,
  8369. getInnerHeight: getInnerHeight,
  8370. getScrollY: getScrollY,
  8371. scrollBy: scrollBy
  8372. };
  8373. };
  8374. var rc = Immutable('rows', 'cols');
  8375. var mouse = function (win, container, isRoot, annotations) {
  8376. var bridge = WindowBridge(win);
  8377. var handlers = MouseSelection(bridge, container, isRoot, annotations);
  8378. return {
  8379. mousedown: handlers.mousedown,
  8380. mouseover: handlers.mouseover,
  8381. mouseup: handlers.mouseup
  8382. };
  8383. };
  8384. var keyboard = function (win, container, isRoot, annotations) {
  8385. var bridge = WindowBridge(win);
  8386. var clearToNavigate = function () {
  8387. annotations.clear(container);
  8388. return Option.none();
  8389. };
  8390. var keydown = function (event, start, soffset, finish, foffset, direction) {
  8391. var realEvent = event.raw();
  8392. var keycode = realEvent.which;
  8393. var shiftKey = realEvent.shiftKey === true;
  8394. var handler = CellSelection.retrieve(container, annotations.selectedSelector()).fold(function () {
  8395. if (SelectionKeys.isDown(keycode) && shiftKey) {
  8396. return curry(VerticalMovement.select, bridge, container, isRoot, KeyDirection.down, finish, start, annotations.selectRange);
  8397. } else if (SelectionKeys.isUp(keycode) && shiftKey) {
  8398. return curry(VerticalMovement.select, bridge, container, isRoot, KeyDirection.up, finish, start, annotations.selectRange);
  8399. } else if (SelectionKeys.isDown(keycode)) {
  8400. return curry(VerticalMovement.navigate, bridge, isRoot, KeyDirection.down, finish, start, VerticalMovement.lastDownCheck);
  8401. } else if (SelectionKeys.isUp(keycode)) {
  8402. return curry(VerticalMovement.navigate, bridge, isRoot, KeyDirection.up, finish, start, VerticalMovement.firstUpCheck);
  8403. } else {
  8404. return Option.none;
  8405. }
  8406. }, function (selected) {
  8407. var update = function (attempts) {
  8408. return function () {
  8409. var navigation = findMap(attempts, function (delta) {
  8410. return KeySelection.update(delta.rows(), delta.cols(), container, selected, annotations);
  8411. });
  8412. return navigation.fold(function () {
  8413. return CellSelection.getEdges(container, annotations.firstSelectedSelector(), annotations.lastSelectedSelector()).map(function (edges) {
  8414. var relative = SelectionKeys.isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
  8415. bridge.setRelativeSelection(Situ.on(edges.first(), 0), relative(edges.table()));
  8416. annotations.clear(container);
  8417. return Response.create(Option.none(), true);
  8418. });
  8419. }, function (_) {
  8420. return Option.some(Response.create(Option.none(), true));
  8421. });
  8422. };
  8423. };
  8424. if (SelectionKeys.isDown(keycode) && shiftKey) {
  8425. return update([rc(+1, 0)]);
  8426. } else if (SelectionKeys.isUp(keycode) && shiftKey) {
  8427. return update([rc(-1, 0)]);
  8428. } else if (direction.isBackward(keycode) && shiftKey) {
  8429. return update([
  8430. rc(0, -1),
  8431. rc(-1, 0)
  8432. ]);
  8433. } else if (direction.isForward(keycode) && shiftKey) {
  8434. return update([
  8435. rc(0, +1),
  8436. rc(+1, 0)
  8437. ]);
  8438. } else if (SelectionKeys.isNavigation(keycode) && shiftKey === false) {
  8439. return clearToNavigate;
  8440. } else {
  8441. return Option.none;
  8442. }
  8443. });
  8444. return handler();
  8445. };
  8446. var keyup = function (event, start, soffset, finish, foffset) {
  8447. return CellSelection.retrieve(container, annotations.selectedSelector()).fold(function () {
  8448. var realEvent = event.raw();
  8449. var keycode = realEvent.which;
  8450. var shiftKey = realEvent.shiftKey === true;
  8451. if (shiftKey === false) {
  8452. return Option.none();
  8453. }
  8454. if (SelectionKeys.isNavigation(keycode)) {
  8455. return KeySelection.sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
  8456. } else {
  8457. return Option.none();
  8458. }
  8459. }, Option.none);
  8460. };
  8461. return {
  8462. keydown: keydown,
  8463. keyup: keyup
  8464. };
  8465. };
  8466. var platform$3 = detect$3();
  8467. var external = function (win, container, isRoot, annotations) {
  8468. var bridge = WindowBridge(win);
  8469. return function (start, finish) {
  8470. annotations.clearBeforeUpdate(container);
  8471. CellSelection.identify(start, finish, isRoot).each(function (cellSel) {
  8472. var boxes = cellSel.boxes().getOr([]);
  8473. annotations.selectRange(container, boxes, cellSel.start(), cellSel.finish());
  8474. if (platform$3.deviceType.isTouch()) {
  8475. bridge.clearSelection();
  8476. } else {
  8477. bridge.selectContents(finish);
  8478. }
  8479. });
  8480. };
  8481. };
  8482. var InputHandlers = {
  8483. mouse: mouse,
  8484. keyboard: keyboard,
  8485. external: external
  8486. };
  8487. var remove$7 = function (element, classes) {
  8488. each(classes, function (x) {
  8489. remove$5(element, x);
  8490. });
  8491. };
  8492. var addClass = function (clazz) {
  8493. return function (element) {
  8494. add$2(element, clazz);
  8495. };
  8496. };
  8497. var removeClasses = function (classes) {
  8498. return function (element) {
  8499. remove$7(element, classes);
  8500. };
  8501. };
  8502. var byClass = function (ephemera) {
  8503. var addSelectionClass = addClass(ephemera.selected());
  8504. var removeSelectionClasses = removeClasses([
  8505. ephemera.selected(),
  8506. ephemera.lastSelected(),
  8507. ephemera.firstSelected()
  8508. ]);
  8509. var clear = function (container) {
  8510. var sels = descendants$1(container, ephemera.selectedSelector());
  8511. each(sels, removeSelectionClasses);
  8512. };
  8513. var selectRange = function (container, cells, start, finish) {
  8514. clear(container);
  8515. each(cells, addSelectionClass);
  8516. add$2(start, ephemera.firstSelected());
  8517. add$2(finish, ephemera.lastSelected());
  8518. };
  8519. return {
  8520. clearBeforeUpdate: clear,
  8521. clear: clear,
  8522. selectRange: selectRange,
  8523. selectedSelector: ephemera.selectedSelector,
  8524. firstSelectedSelector: ephemera.firstSelectedSelector,
  8525. lastSelectedSelector: ephemera.lastSelectedSelector
  8526. };
  8527. };
  8528. var byAttr = function (ephemera, onSelection, onClear) {
  8529. var removeSelectionAttributes = function (element) {
  8530. remove(element, ephemera.selected());
  8531. remove(element, ephemera.firstSelected());
  8532. remove(element, ephemera.lastSelected());
  8533. };
  8534. var addSelectionAttribute = function (element) {
  8535. set(element, ephemera.selected(), '1');
  8536. };
  8537. var clear = function (container) {
  8538. clearBeforeUpdate(container);
  8539. onClear();
  8540. };
  8541. var clearBeforeUpdate = function (container) {
  8542. var sels = descendants$1(container, ephemera.selectedSelector());
  8543. each(sels, removeSelectionAttributes);
  8544. };
  8545. var selectRange = function (container, cells, start, finish) {
  8546. clear(container);
  8547. each(cells, addSelectionAttribute);
  8548. set(start, ephemera.firstSelected(), '1');
  8549. set(finish, ephemera.lastSelected(), '1');
  8550. onSelection(cells, start, finish);
  8551. };
  8552. return {
  8553. clearBeforeUpdate: clearBeforeUpdate,
  8554. clear: clear,
  8555. selectRange: selectRange,
  8556. selectedSelector: ephemera.selectedSelector,
  8557. firstSelectedSelector: ephemera.firstSelectedSelector,
  8558. lastSelectedSelector: ephemera.lastSelectedSelector
  8559. };
  8560. };
  8561. var SelectionAnnotation = {
  8562. byClass: byClass,
  8563. byAttr: byAttr
  8564. };
  8565. var getUpOrLeftCells = function (grid, selectedCells, generators) {
  8566. var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row() + 1);
  8567. var upDetails = toDetailList(upGrid, generators);
  8568. return bind(upDetails, function (detail) {
  8569. var slicedCells = detail.cells().slice(0, selectedCells[selectedCells.length - 1].column() + 1);
  8570. return map(slicedCells, function (cell) {
  8571. return cell.element();
  8572. });
  8573. });
  8574. };
  8575. var getDownOrRightCells = function (grid, selectedCells, generators) {
  8576. var downGrid = grid.slice(selectedCells[0].row() + selectedCells[0].rowspan() - 1, grid.length);
  8577. var downDetails = toDetailList(downGrid, generators);
  8578. return bind(downDetails, function (detail) {
  8579. var slicedCells = detail.cells().slice(selectedCells[0].column() + selectedCells[0].colspan() - 1, +detail.cells().length);
  8580. return map(slicedCells, function (cell) {
  8581. return cell.element();
  8582. });
  8583. });
  8584. };
  8585. var getOtherCells = function (table, target, generators) {
  8586. var list = DetailsList.fromTable(table);
  8587. var house = Warehouse.generate(list);
  8588. var details = onCells(house, target);
  8589. return details.map(function (selectedCells) {
  8590. var grid = Transitions.toGrid(house, generators, false);
  8591. var upOrLeftCells = getUpOrLeftCells(grid, selectedCells, generators);
  8592. var downOrRightCells = getDownOrRightCells(grid, selectedCells, generators);
  8593. return {
  8594. upOrLeftCells: upOrLeftCells,
  8595. downOrRightCells: downOrRightCells
  8596. };
  8597. });
  8598. };
  8599. var OtherCells = { getOtherCells: getOtherCells };
  8600. var hasInternalTarget = function (e) {
  8601. return has$2(Element.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
  8602. };
  8603. function CellSelection$1 (editor, lazyResize, selectionTargets) {
  8604. var handlerStruct = MixedBag([
  8605. 'mousedown',
  8606. 'mouseover',
  8607. 'mouseup',
  8608. 'keyup',
  8609. 'keydown'
  8610. ], []);
  8611. var handlers = Option.none();
  8612. var cloneFormats = getCloneElements(editor);
  8613. var onSelection = function (cells, start, finish) {
  8614. selectionTargets.targets().each(function (targets) {
  8615. var tableOpt = TableLookup.table(start);
  8616. tableOpt.each(function (table) {
  8617. var doc = Element.fromDom(editor.getDoc());
  8618. var generators = TableFill.cellOperations(noop, doc, cloneFormats);
  8619. var otherCells = OtherCells.getOtherCells(table, targets, generators);
  8620. fireTableSelectionChange(editor, cells, start, finish, otherCells);
  8621. });
  8622. });
  8623. };
  8624. var onClear = function () {
  8625. fireTableSelectionClear(editor);
  8626. };
  8627. var annotations = SelectionAnnotation.byAttr(Ephemera, onSelection, onClear);
  8628. editor.on('init', function (e) {
  8629. var win = editor.getWin();
  8630. var body = getBody$1(editor);
  8631. var isRoot = getIsRoot(editor);
  8632. var syncSelection = function () {
  8633. var sel = editor.selection;
  8634. var start = Element.fromDom(sel.getStart());
  8635. var end = Element.fromDom(sel.getEnd());
  8636. var shared = DomParent.sharedOne(TableLookup.table, [
  8637. start,
  8638. end
  8639. ]);
  8640. shared.fold(function () {
  8641. annotations.clear(body);
  8642. }, noop);
  8643. };
  8644. var mouseHandlers = InputHandlers.mouse(win, body, isRoot, annotations);
  8645. var keyHandlers = InputHandlers.keyboard(win, body, isRoot, annotations);
  8646. var external = InputHandlers.external(win, body, isRoot, annotations);
  8647. var hasShiftKey = function (event) {
  8648. return event.raw().shiftKey === true;
  8649. };
  8650. editor.on('tableselectorchange', function (e) {
  8651. external(e.start, e.finish);
  8652. });
  8653. var handleResponse = function (event, response) {
  8654. if (!hasShiftKey(event)) {
  8655. return;
  8656. }
  8657. if (response.kill()) {
  8658. event.kill();
  8659. }
  8660. response.selection().each(function (ns) {
  8661. var relative = Selection.relative(ns.start(), ns.finish());
  8662. var rng = asLtrRange(win, relative);
  8663. editor.selection.setRng(rng);
  8664. });
  8665. };
  8666. var keyup = function (event) {
  8667. var wrappedEvent = wrapEvent(event);
  8668. if (wrappedEvent.raw().shiftKey && SelectionKeys.isNavigation(wrappedEvent.raw().which)) {
  8669. var rng = editor.selection.getRng();
  8670. var start = Element.fromDom(rng.startContainer);
  8671. var end = Element.fromDom(rng.endContainer);
  8672. keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
  8673. handleResponse(wrappedEvent, response);
  8674. });
  8675. }
  8676. };
  8677. var keydown = function (event) {
  8678. var wrappedEvent = wrapEvent(event);
  8679. lazyResize().each(function (resize) {
  8680. resize.hideBars();
  8681. });
  8682. var rng = editor.selection.getRng();
  8683. var startContainer = Element.fromDom(editor.selection.getStart());
  8684. var start = Element.fromDom(rng.startContainer);
  8685. var end = Element.fromDom(rng.endContainer);
  8686. var direction = Direction.directionAt(startContainer).isRtl() ? SelectionKeys.rtl : SelectionKeys.ltr;
  8687. keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
  8688. handleResponse(wrappedEvent, response);
  8689. });
  8690. lazyResize().each(function (resize) {
  8691. resize.showBars();
  8692. });
  8693. };
  8694. var isMouseEvent = function (event) {
  8695. return event.hasOwnProperty('x') && event.hasOwnProperty('y');
  8696. };
  8697. var wrapEvent = function (event) {
  8698. var target = Element.fromDom(event.target);
  8699. var stop = function () {
  8700. event.stopPropagation();
  8701. };
  8702. var prevent = function () {
  8703. event.preventDefault();
  8704. };
  8705. var kill = compose(prevent, stop);
  8706. return {
  8707. target: constant(target),
  8708. x: constant(isMouseEvent(event) ? event.x : null),
  8709. y: constant(isMouseEvent(event) ? event.y : null),
  8710. stop: stop,
  8711. prevent: prevent,
  8712. kill: kill,
  8713. raw: constant(event)
  8714. };
  8715. };
  8716. var isLeftMouse = function (raw) {
  8717. return raw.button === 0;
  8718. };
  8719. var isLeftButtonPressed = function (raw) {
  8720. if (raw.buttons === undefined) {
  8721. return true;
  8722. }
  8723. return (raw.buttons & 1) !== 0;
  8724. };
  8725. var mouseDown = function (e) {
  8726. if (isLeftMouse(e) && hasInternalTarget(e)) {
  8727. mouseHandlers.mousedown(wrapEvent(e));
  8728. }
  8729. };
  8730. var mouseOver = function (e) {
  8731. if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
  8732. mouseHandlers.mouseover(wrapEvent(e));
  8733. }
  8734. };
  8735. var mouseUp = function (e) {
  8736. if (isLeftMouse(e) && hasInternalTarget(e)) {
  8737. mouseHandlers.mouseup(wrapEvent(e));
  8738. }
  8739. };
  8740. var getDoubleTap = function () {
  8741. var lastTarget = Cell(Element.fromDom(body));
  8742. var lastTimeStamp = Cell(0);
  8743. var touchEnd = function (t) {
  8744. var target = Element.fromDom(t.target);
  8745. if (name(target) === 'td' || name(target) === 'th') {
  8746. var lT = lastTarget.get();
  8747. var lTS = lastTimeStamp.get();
  8748. if (eq(lT, target) && t.timeStamp - lTS < 300) {
  8749. t.preventDefault();
  8750. external(target, target);
  8751. }
  8752. }
  8753. lastTarget.set(target);
  8754. lastTimeStamp.set(t.timeStamp);
  8755. };
  8756. return { touchEnd: touchEnd };
  8757. };
  8758. var doubleTap = getDoubleTap();
  8759. editor.on('mousedown', mouseDown);
  8760. editor.on('mouseover', mouseOver);
  8761. editor.on('mouseup', mouseUp);
  8762. editor.on('touchend', doubleTap.touchEnd);
  8763. editor.on('keyup', keyup);
  8764. editor.on('keydown', keydown);
  8765. editor.on('NodeChange', syncSelection);
  8766. handlers = Option.some(handlerStruct({
  8767. mousedown: mouseDown,
  8768. mouseover: mouseOver,
  8769. mouseup: mouseUp,
  8770. keyup: keyup,
  8771. keydown: keydown
  8772. }));
  8773. });
  8774. var destroy = function () {
  8775. handlers.each(function (handlers) {
  8776. });
  8777. };
  8778. return {
  8779. clear: annotations.clear,
  8780. destroy: destroy
  8781. };
  8782. }
  8783. var Selections = function (editor) {
  8784. var get = function () {
  8785. var body = getBody$1(editor);
  8786. return TableSelection.retrieve(body, Ephemera.selectedSelector()).fold(function () {
  8787. if (editor.selection.getStart() === undefined) {
  8788. return SelectionTypes.none();
  8789. } else {
  8790. return SelectionTypes.single(editor.selection);
  8791. }
  8792. }, function (cells) {
  8793. return SelectionTypes.multiple(cells);
  8794. });
  8795. };
  8796. return { get: get };
  8797. };
  8798. var getSelectionTargets = function (editor, selections) {
  8799. var targets = Cell(Option.none());
  8800. var changeHandlers = Cell([]);
  8801. var findTargets = function () {
  8802. return getSelectionStartCellOrCaption(editor).bind(function (cellOrCaption) {
  8803. var table = TableLookup.table(cellOrCaption);
  8804. return table.map(function (table) {
  8805. if (name(cellOrCaption) === 'caption') {
  8806. return TableTargets.notCell(cellOrCaption);
  8807. } else {
  8808. return TableTargets.forMenu(selections, table, cellOrCaption);
  8809. }
  8810. });
  8811. });
  8812. };
  8813. var resetTargets = function () {
  8814. targets.set(cached(findTargets)());
  8815. each(changeHandlers.get(), function (handler) {
  8816. return handler();
  8817. });
  8818. };
  8819. var onSetup = function (api, isDisabled) {
  8820. var handler = function () {
  8821. return targets.get().fold(function () {
  8822. api.setDisabled(true);
  8823. }, function (targets) {
  8824. api.setDisabled(isDisabled(targets));
  8825. });
  8826. };
  8827. handler();
  8828. changeHandlers.set(changeHandlers.get().concat([handler]));
  8829. return function () {
  8830. changeHandlers.set(filter(changeHandlers.get(), function (h) {
  8831. return h !== handler;
  8832. }));
  8833. };
  8834. };
  8835. var onSetupTable = function (api) {
  8836. return onSetup(api, function (_) {
  8837. return false;
  8838. });
  8839. };
  8840. var onSetupCellOrRow = function (api) {
  8841. return onSetup(api, function (targets) {
  8842. return name(targets.element()) === 'caption';
  8843. });
  8844. };
  8845. var onSetupMergeable = function (api) {
  8846. return onSetup(api, function (targets) {
  8847. return targets.mergable().isNone();
  8848. });
  8849. };
  8850. var onSetupUnmergeable = function (api) {
  8851. return onSetup(api, function (targets) {
  8852. return targets.unmergable().isNone();
  8853. });
  8854. };
  8855. editor.on('NodeChange', resetTargets);
  8856. return {
  8857. onSetupTable: onSetupTable,
  8858. onSetupCellOrRow: onSetupCellOrRow,
  8859. onSetupMergeable: onSetupMergeable,
  8860. onSetupUnmergeable: onSetupUnmergeable,
  8861. resetTargets: resetTargets,
  8862. targets: function () {
  8863. return targets.get();
  8864. }
  8865. };
  8866. };
  8867. var addButtons = function (editor, selectionTargets) {
  8868. editor.ui.registry.addMenuButton('table', {
  8869. tooltip: 'Table',
  8870. icon: 'table',
  8871. fetch: function (callback) {
  8872. return callback('inserttable tableprops deletetable | cell row column');
  8873. }
  8874. });
  8875. var cmd = function (command) {
  8876. return function () {
  8877. return editor.execCommand(command);
  8878. };
  8879. };
  8880. editor.ui.registry.addButton('tableprops', {
  8881. tooltip: 'Table properties',
  8882. onAction: cmd('mceTableProps'),
  8883. icon: 'table',
  8884. onSetup: selectionTargets.onSetupTable
  8885. });
  8886. editor.ui.registry.addButton('tabledelete', {
  8887. tooltip: 'Delete table',
  8888. onAction: cmd('mceTableDelete'),
  8889. icon: 'table-delete-table',
  8890. onSetup: selectionTargets.onSetupTable
  8891. });
  8892. editor.ui.registry.addButton('tablecellprops', {
  8893. tooltip: 'Cell properties',
  8894. onAction: cmd('mceTableCellProps'),
  8895. icon: 'table-cell-properties',
  8896. onSetup: selectionTargets.onSetupCellOrRow
  8897. });
  8898. editor.ui.registry.addButton('tablemergecells', {
  8899. tooltip: 'Merge cells',
  8900. onAction: cmd('mceTableMergeCells'),
  8901. icon: 'table-merge-cells',
  8902. onSetup: selectionTargets.onSetupMergeable
  8903. });
  8904. editor.ui.registry.addButton('tablesplitcells', {
  8905. tooltip: 'Split cell',
  8906. onAction: cmd('mceTableSplitCells'),
  8907. icon: 'table-split-cells',
  8908. onSetup: selectionTargets.onSetupUnmergeable
  8909. });
  8910. editor.ui.registry.addButton('tableinsertrowbefore', {
  8911. tooltip: 'Insert row before',
  8912. onAction: cmd('mceTableInsertRowBefore'),
  8913. icon: 'table-insert-row-above',
  8914. onSetup: selectionTargets.onSetupCellOrRow
  8915. });
  8916. editor.ui.registry.addButton('tableinsertrowafter', {
  8917. tooltip: 'Insert row after',
  8918. onAction: cmd('mceTableInsertRowAfter'),
  8919. icon: 'table-insert-row-after',
  8920. onSetup: selectionTargets.onSetupCellOrRow
  8921. });
  8922. editor.ui.registry.addButton('tabledeleterow', {
  8923. tooltip: 'Delete row',
  8924. onAction: cmd('mceTableDeleteRow'),
  8925. icon: 'table-delete-row',
  8926. onSetup: selectionTargets.onSetupCellOrRow
  8927. });
  8928. editor.ui.registry.addButton('tablerowprops', {
  8929. tooltip: 'Row properties',
  8930. onAction: cmd('mceTableRowProps'),
  8931. icon: 'table-row-properties',
  8932. onSetup: selectionTargets.onSetupCellOrRow
  8933. });
  8934. editor.ui.registry.addButton('tableinsertcolbefore', {
  8935. tooltip: 'Insert column before',
  8936. onAction: cmd('mceTableInsertColBefore'),
  8937. icon: 'table-insert-column-before',
  8938. onSetup: selectionTargets.onSetupCellOrRow
  8939. });
  8940. editor.ui.registry.addButton('tableinsertcolafter', {
  8941. tooltip: 'Insert column after',
  8942. onAction: cmd('mceTableInsertColAfter'),
  8943. icon: 'table-insert-column-after',
  8944. onSetup: selectionTargets.onSetupCellOrRow
  8945. });
  8946. editor.ui.registry.addButton('tabledeletecol', {
  8947. tooltip: 'Delete column',
  8948. onAction: cmd('mceTableDeleteCol'),
  8949. icon: 'table-delete-column',
  8950. onSetup: selectionTargets.onSetupCellOrRow
  8951. });
  8952. editor.ui.registry.addButton('tablecutrow', {
  8953. tooltip: 'Cut row',
  8954. onAction: cmd('mceTableCutRow'),
  8955. icon: 'temporary-placeholder',
  8956. onSetup: selectionTargets.onSetupCellOrRow
  8957. });
  8958. editor.ui.registry.addButton('tablecopyrow', {
  8959. tooltip: 'Copy row',
  8960. onAction: cmd('mceTableCopyRow'),
  8961. icon: 'temporary-placeholder',
  8962. onSetup: selectionTargets.onSetupCellOrRow
  8963. });
  8964. editor.ui.registry.addButton('tablepasterowbefore', {
  8965. tooltip: 'Paste row before',
  8966. onAction: cmd('mceTablePasteRowBefore'),
  8967. icon: 'temporary-placeholder',
  8968. onSetup: selectionTargets.onSetupCellOrRow
  8969. });
  8970. editor.ui.registry.addButton('tablepasterowafter', {
  8971. tooltip: 'Paste row after',
  8972. onAction: cmd('mceTablePasteRowAfter'),
  8973. icon: 'temporary-placeholder',
  8974. onSetup: selectionTargets.onSetupCellOrRow
  8975. });
  8976. editor.ui.registry.addButton('tableinsertdialog', {
  8977. tooltip: 'Insert table',
  8978. onAction: cmd('mceInsertTable'),
  8979. icon: 'table'
  8980. });
  8981. };
  8982. var addToolbars = function (editor) {
  8983. var isTable = function (table) {
  8984. return editor.dom.is(table, 'table') && editor.getBody().contains(table);
  8985. };
  8986. var toolbar = getToolbar(editor);
  8987. if (toolbar.length > 0) {
  8988. editor.ui.registry.addContextToolbar('table', {
  8989. predicate: isTable,
  8990. items: toolbar,
  8991. scope: 'node',
  8992. position: 'node'
  8993. });
  8994. }
  8995. };
  8996. var Buttons = {
  8997. addButtons: addButtons,
  8998. addToolbars: addToolbars
  8999. };
  9000. var addMenuItems = function (editor, selectionTargets) {
  9001. var cmd = function (command) {
  9002. return function () {
  9003. return editor.execCommand(command);
  9004. };
  9005. };
  9006. var insertTableAction = function (_a) {
  9007. var numRows = _a.numRows, numColumns = _a.numColumns;
  9008. editor.undoManager.transact(function () {
  9009. InsertTable.insert(editor, numColumns, numRows);
  9010. });
  9011. editor.addVisual();
  9012. };
  9013. var tableProperties = {
  9014. text: 'Table properties',
  9015. onSetup: selectionTargets.onSetupTable,
  9016. onAction: cmd('mceTableProps')
  9017. };
  9018. var deleteTable = {
  9019. text: 'Delete table',
  9020. icon: 'table-delete-table',
  9021. onSetup: selectionTargets.onSetupTable,
  9022. onAction: cmd('mceTableDelete')
  9023. };
  9024. var rowItems = [
  9025. {
  9026. type: 'menuitem',
  9027. text: 'Insert row before',
  9028. icon: 'table-insert-row-above',
  9029. onAction: cmd('mceTableInsertRowBefore'),
  9030. onSetup: selectionTargets.onSetupCellOrRow
  9031. },
  9032. {
  9033. type: 'menuitem',
  9034. text: 'Insert row after',
  9035. icon: 'table-insert-row-after',
  9036. onAction: cmd('mceTableInsertRowAfter'),
  9037. onSetup: selectionTargets.onSetupCellOrRow
  9038. },
  9039. {
  9040. type: 'menuitem',
  9041. text: 'Delete row',
  9042. icon: 'table-delete-row',
  9043. onAction: cmd('mceTableDeleteRow'),
  9044. onSetup: selectionTargets.onSetupCellOrRow
  9045. },
  9046. {
  9047. type: 'menuitem',
  9048. text: 'Row properties',
  9049. icon: 'table-row-properties',
  9050. onAction: cmd('mceTableRowProps'),
  9051. onSetup: selectionTargets.onSetupCellOrRow
  9052. },
  9053. { type: 'separator' },
  9054. {
  9055. type: 'menuitem',
  9056. text: 'Cut row',
  9057. onAction: cmd('mceTableCutRow'),
  9058. onSetup: selectionTargets.onSetupCellOrRow
  9059. },
  9060. {
  9061. type: 'menuitem',
  9062. text: 'Copy row',
  9063. onAction: cmd('mceTableCopyRow'),
  9064. onSetup: selectionTargets.onSetupCellOrRow
  9065. },
  9066. {
  9067. type: 'menuitem',
  9068. text: 'Paste row before',
  9069. onAction: cmd('mceTablePasteRowBefore'),
  9070. onSetup: selectionTargets.onSetupCellOrRow
  9071. },
  9072. {
  9073. type: 'menuitem',
  9074. text: 'Paste row after',
  9075. onAction: cmd('mceTablePasteRowAfter'),
  9076. onSetup: selectionTargets.onSetupCellOrRow
  9077. }
  9078. ];
  9079. var row = {
  9080. type: 'nestedmenuitem',
  9081. text: 'Row',
  9082. getSubmenuItems: function () {
  9083. return rowItems;
  9084. }
  9085. };
  9086. var columnItems = [
  9087. {
  9088. type: 'menuitem',
  9089. text: 'Insert column before',
  9090. icon: 'table-insert-column-before',
  9091. onAction: cmd('mceTableInsertColBefore'),
  9092. onSetup: selectionTargets.onSetupCellOrRow
  9093. },
  9094. {
  9095. type: 'menuitem',
  9096. text: 'Insert column after',
  9097. icon: 'table-insert-column-after',
  9098. onAction: cmd('mceTableInsertColAfter'),
  9099. onSetup: selectionTargets.onSetupCellOrRow
  9100. },
  9101. {
  9102. type: 'menuitem',
  9103. text: 'Delete column',
  9104. icon: 'table-delete-column',
  9105. onAction: cmd('mceTableDeleteCol'),
  9106. onSetup: selectionTargets.onSetupCellOrRow
  9107. }
  9108. ];
  9109. var column = {
  9110. type: 'nestedmenuitem',
  9111. text: 'Column',
  9112. getSubmenuItems: function () {
  9113. return columnItems;
  9114. }
  9115. };
  9116. var cellItems = [
  9117. {
  9118. type: 'menuitem',
  9119. text: 'Cell properties',
  9120. icon: 'table-cell-properties',
  9121. onAction: cmd('mceTableCellProps'),
  9122. onSetup: selectionTargets.onSetupCellOrRow
  9123. },
  9124. {
  9125. type: 'menuitem',
  9126. text: 'Merge cells',
  9127. icon: 'table-merge-cells',
  9128. onAction: cmd('mceTableMergeCells'),
  9129. onSetup: selectionTargets.onSetupMergeable
  9130. },
  9131. {
  9132. type: 'menuitem',
  9133. text: 'Split cell',
  9134. icon: 'table-split-cells',
  9135. onAction: cmd('mceTableSplitCells'),
  9136. onSetup: selectionTargets.onSetupUnmergeable
  9137. }
  9138. ];
  9139. var cell = {
  9140. type: 'nestedmenuitem',
  9141. text: 'Cell',
  9142. getSubmenuItems: function () {
  9143. return cellItems;
  9144. }
  9145. };
  9146. if (hasTableGrid(editor) === false) {
  9147. editor.ui.registry.addMenuItem('inserttable', {
  9148. text: 'Table',
  9149. icon: 'table',
  9150. onAction: cmd('mceInsertTable')
  9151. });
  9152. } else {
  9153. editor.ui.registry.addNestedMenuItem('inserttable', {
  9154. text: 'Table',
  9155. icon: 'table',
  9156. getSubmenuItems: function () {
  9157. return [{
  9158. type: 'fancymenuitem',
  9159. fancytype: 'inserttable',
  9160. onAction: insertTableAction
  9161. }];
  9162. }
  9163. });
  9164. }
  9165. editor.ui.registry.addMenuItem('inserttabledialog', {
  9166. text: 'Insert table',
  9167. icon: 'table',
  9168. onAction: cmd('mceInsertTable')
  9169. });
  9170. editor.ui.registry.addMenuItem('tableprops', tableProperties);
  9171. editor.ui.registry.addMenuItem('deletetable', deleteTable);
  9172. editor.ui.registry.addNestedMenuItem('row', row);
  9173. editor.ui.registry.addNestedMenuItem('column', column);
  9174. editor.ui.registry.addNestedMenuItem('cell', cell);
  9175. editor.ui.registry.addContextMenu('table', {
  9176. update: function () {
  9177. selectionTargets.resetTargets();
  9178. return selectionTargets.targets().fold(function () {
  9179. return '';
  9180. }, function (targets) {
  9181. if (name(targets.element()) === 'caption') {
  9182. return 'tableprops deletetable';
  9183. } else {
  9184. return 'cell row column | tableprops deletetable';
  9185. }
  9186. });
  9187. }
  9188. });
  9189. return {
  9190. rowItems: rowItems,
  9191. columnItems: columnItems,
  9192. cellItems: cellItems
  9193. };
  9194. };
  9195. var MenuItems = { addMenuItems: addMenuItems };
  9196. var getClipboardRows = function (clipboardRows) {
  9197. return clipboardRows.get().fold(function () {
  9198. return;
  9199. }, function (rows) {
  9200. return map(rows, function (row) {
  9201. return row.dom();
  9202. });
  9203. });
  9204. };
  9205. var setClipboardRows = function (rows, clipboardRows) {
  9206. var sugarRows = map(rows, Element.fromDom);
  9207. clipboardRows.set(Option.from(sugarRows));
  9208. };
  9209. var getApi = function (editor, clipboardRows, resizeHandler, selectionTargets, menuItems) {
  9210. return {
  9211. insertTable: function (columns, rows) {
  9212. return InsertTable.insert(editor, columns, rows);
  9213. },
  9214. setClipboardRows: function (rows) {
  9215. return setClipboardRows(rows, clipboardRows);
  9216. },
  9217. getClipboardRows: function () {
  9218. return getClipboardRows(clipboardRows);
  9219. },
  9220. resizeHandler: resizeHandler,
  9221. menuItems: menuItems,
  9222. selectionTargets: selectionTargets
  9223. };
  9224. };
  9225. function Plugin(editor) {
  9226. var selections = Selections(editor);
  9227. var selectionTargets = getSelectionTargets(editor, selections);
  9228. var resizeHandler = getResizeHandler(editor);
  9229. var cellSelection = CellSelection$1(editor, resizeHandler.lazyResize, selectionTargets);
  9230. var actions = TableActions(editor, resizeHandler.lazyWire);
  9231. var clipboardRows = Cell(Option.none());
  9232. Commands.registerCommands(editor, actions, cellSelection, selections, clipboardRows);
  9233. Clipboard.registerEvents(editor, selections, actions, cellSelection);
  9234. var menuItems = MenuItems.addMenuItems(editor, selectionTargets);
  9235. Buttons.addButtons(editor, selectionTargets);
  9236. Buttons.addToolbars(editor);
  9237. editor.on('PreInit', function () {
  9238. editor.serializer.addTempAttr(Ephemera.firstSelected());
  9239. editor.serializer.addTempAttr(Ephemera.lastSelected());
  9240. });
  9241. if (hasTabNavigation(editor)) {
  9242. editor.on('keydown', function (e) {
  9243. TabContext.handle(e, editor, actions, resizeHandler.lazyWire);
  9244. });
  9245. }
  9246. editor.on('remove', function () {
  9247. resizeHandler.destroy();
  9248. cellSelection.destroy();
  9249. });
  9250. return getApi(editor, clipboardRows, resizeHandler, selectionTargets, menuItems);
  9251. }
  9252. function Plugin$1 () {
  9253. global.add('table', Plugin);
  9254. }
  9255. Plugin$1();
  9256. }(window));