plugin.js 314 KB

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