plugin.js 340 KB

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