plugin.js 389 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447
  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.9.1 (2021-08-27)
  8. */
  9. (function () {
  10. 'use strict';
  11. var typeOf = function (x) {
  12. var t = typeof x;
  13. if (x === null) {
  14. return 'null';
  15. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  16. return 'array';
  17. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  18. return 'string';
  19. } else {
  20. return t;
  21. }
  22. };
  23. var isType$1 = function (type) {
  24. return function (value) {
  25. return typeOf(value) === type;
  26. };
  27. };
  28. var isSimpleType = function (type) {
  29. return function (value) {
  30. return typeof value === type;
  31. };
  32. };
  33. var eq$2 = function (t) {
  34. return function (a) {
  35. return t === a;
  36. };
  37. };
  38. var isString = isType$1('string');
  39. var isObject = isType$1('object');
  40. var isArray = isType$1('array');
  41. var isNull = eq$2(null);
  42. var isBoolean = isSimpleType('boolean');
  43. var isUndefined = eq$2(undefined);
  44. var isNullable = function (a) {
  45. return a === null || a === undefined;
  46. };
  47. var isNonNullable = function (a) {
  48. return !isNullable(a);
  49. };
  50. var isFunction = isSimpleType('function');
  51. var isNumber = isSimpleType('number');
  52. var noop = function () {
  53. };
  54. var compose = function (fa, fb) {
  55. return function () {
  56. var args = [];
  57. for (var _i = 0; _i < arguments.length; _i++) {
  58. args[_i] = arguments[_i];
  59. }
  60. return fa(fb.apply(null, args));
  61. };
  62. };
  63. var compose1 = function (fbc, fab) {
  64. return function (a) {
  65. return fbc(fab(a));
  66. };
  67. };
  68. var constant = function (value) {
  69. return function () {
  70. return value;
  71. };
  72. };
  73. var identity = function (x) {
  74. return x;
  75. };
  76. var tripleEquals = function (a, b) {
  77. return a === b;
  78. };
  79. function curry(fn) {
  80. var initialArgs = [];
  81. for (var _i = 1; _i < arguments.length; _i++) {
  82. initialArgs[_i - 1] = arguments[_i];
  83. }
  84. return function () {
  85. var restArgs = [];
  86. for (var _i = 0; _i < arguments.length; _i++) {
  87. restArgs[_i] = arguments[_i];
  88. }
  89. var all = initialArgs.concat(restArgs);
  90. return fn.apply(null, all);
  91. };
  92. }
  93. var not = function (f) {
  94. return function (t) {
  95. return !f(t);
  96. };
  97. };
  98. var die = function (msg) {
  99. return function () {
  100. throw new Error(msg);
  101. };
  102. };
  103. var never = constant(false);
  104. var always = constant(true);
  105. var none$2 = function () {
  106. return NONE;
  107. };
  108. var NONE = function () {
  109. var call = function (thunk) {
  110. return thunk();
  111. };
  112. var id = identity;
  113. var me = {
  114. fold: function (n, _s) {
  115. return n();
  116. },
  117. isSome: never,
  118. isNone: always,
  119. getOr: id,
  120. getOrThunk: call,
  121. getOrDie: function (msg) {
  122. throw new Error(msg || 'error: getOrDie called on none.');
  123. },
  124. getOrNull: constant(null),
  125. getOrUndefined: constant(undefined),
  126. or: id,
  127. orThunk: call,
  128. map: none$2,
  129. each: noop,
  130. bind: none$2,
  131. exists: never,
  132. forall: always,
  133. filter: function () {
  134. return none$2();
  135. },
  136. toArray: function () {
  137. return [];
  138. },
  139. toString: constant('none()')
  140. };
  141. return me;
  142. }();
  143. var some = function (a) {
  144. var constant_a = constant(a);
  145. var self = function () {
  146. return me;
  147. };
  148. var bind = function (f) {
  149. return f(a);
  150. };
  151. var me = {
  152. fold: function (n, s) {
  153. return s(a);
  154. },
  155. isSome: always,
  156. isNone: never,
  157. getOr: constant_a,
  158. getOrThunk: constant_a,
  159. getOrDie: constant_a,
  160. getOrNull: constant_a,
  161. getOrUndefined: constant_a,
  162. or: self,
  163. orThunk: self,
  164. map: function (f) {
  165. return some(f(a));
  166. },
  167. each: function (f) {
  168. f(a);
  169. },
  170. bind: bind,
  171. exists: bind,
  172. forall: bind,
  173. filter: function (f) {
  174. return f(a) ? me : NONE;
  175. },
  176. toArray: function () {
  177. return [a];
  178. },
  179. toString: function () {
  180. return 'some(' + a + ')';
  181. }
  182. };
  183. return me;
  184. };
  185. var from$1 = function (value) {
  186. return value === null || value === undefined ? NONE : some(value);
  187. };
  188. var Optional = {
  189. some: some,
  190. none: none$2,
  191. from: from$1
  192. };
  193. var nativeSlice = Array.prototype.slice;
  194. var nativeIndexOf = Array.prototype.indexOf;
  195. var nativePush = Array.prototype.push;
  196. var rawIndexOf = function (ts, t) {
  197. return nativeIndexOf.call(ts, t);
  198. };
  199. var contains$2 = function (xs, x) {
  200. return rawIndexOf(xs, x) > -1;
  201. };
  202. var exists = function (xs, pred) {
  203. for (var i = 0, len = xs.length; i < len; i++) {
  204. var x = xs[i];
  205. if (pred(x, i)) {
  206. return true;
  207. }
  208. }
  209. return false;
  210. };
  211. var range$1 = function (num, f) {
  212. var r = [];
  213. for (var i = 0; i < num; i++) {
  214. r.push(f(i));
  215. }
  216. return r;
  217. };
  218. var map$1 = function (xs, f) {
  219. var len = xs.length;
  220. var r = new Array(len);
  221. for (var i = 0; i < len; i++) {
  222. var x = xs[i];
  223. r[i] = f(x, i);
  224. }
  225. return r;
  226. };
  227. var each$2 = function (xs, f) {
  228. for (var i = 0, len = xs.length; i < len; i++) {
  229. var x = xs[i];
  230. f(x, i);
  231. }
  232. };
  233. var eachr = function (xs, f) {
  234. for (var i = xs.length - 1; i >= 0; i--) {
  235. var x = xs[i];
  236. f(x, i);
  237. }
  238. };
  239. var partition = function (xs, pred) {
  240. var pass = [];
  241. var fail = [];
  242. for (var i = 0, len = xs.length; i < len; i++) {
  243. var x = xs[i];
  244. var arr = pred(x, i) ? pass : fail;
  245. arr.push(x);
  246. }
  247. return {
  248. pass: pass,
  249. fail: fail
  250. };
  251. };
  252. var filter$2 = function (xs, pred) {
  253. var r = [];
  254. for (var i = 0, len = xs.length; i < len; i++) {
  255. var x = xs[i];
  256. if (pred(x, i)) {
  257. r.push(x);
  258. }
  259. }
  260. return r;
  261. };
  262. var foldr = function (xs, f, acc) {
  263. eachr(xs, function (x, i) {
  264. acc = f(acc, x, i);
  265. });
  266. return acc;
  267. };
  268. var foldl = function (xs, f, acc) {
  269. each$2(xs, function (x, i) {
  270. acc = f(acc, x, i);
  271. });
  272. return acc;
  273. };
  274. var findUntil = function (xs, pred, until) {
  275. for (var i = 0, len = xs.length; i < len; i++) {
  276. var x = xs[i];
  277. if (pred(x, i)) {
  278. return Optional.some(x);
  279. } else if (until(x, i)) {
  280. break;
  281. }
  282. }
  283. return Optional.none();
  284. };
  285. var find$1 = function (xs, pred) {
  286. return findUntil(xs, pred, never);
  287. };
  288. var findIndex = function (xs, pred) {
  289. for (var i = 0, len = xs.length; i < len; i++) {
  290. var x = xs[i];
  291. if (pred(x, i)) {
  292. return Optional.some(i);
  293. }
  294. }
  295. return Optional.none();
  296. };
  297. var flatten$1 = function (xs) {
  298. var r = [];
  299. for (var i = 0, len = xs.length; i < len; ++i) {
  300. if (!isArray(xs[i])) {
  301. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  302. }
  303. nativePush.apply(r, xs[i]);
  304. }
  305. return r;
  306. };
  307. var bind$2 = function (xs, f) {
  308. return flatten$1(map$1(xs, f));
  309. };
  310. var forall = function (xs, pred) {
  311. for (var i = 0, len = xs.length; i < len; ++i) {
  312. var x = xs[i];
  313. if (pred(x, i) !== true) {
  314. return false;
  315. }
  316. }
  317. return true;
  318. };
  319. var reverse = function (xs) {
  320. var r = nativeSlice.call(xs, 0);
  321. r.reverse();
  322. return r;
  323. };
  324. var mapToObject = function (xs, f) {
  325. var r = {};
  326. for (var i = 0, len = xs.length; i < len; i++) {
  327. var x = xs[i];
  328. r[String(x)] = f(x, i);
  329. }
  330. return r;
  331. };
  332. var pure = function (x) {
  333. return [x];
  334. };
  335. var sort$1 = function (xs, comparator) {
  336. var copy = nativeSlice.call(xs, 0);
  337. copy.sort(comparator);
  338. return copy;
  339. };
  340. var get$d = function (xs, i) {
  341. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  342. };
  343. var head = function (xs) {
  344. return get$d(xs, 0);
  345. };
  346. var last$2 = function (xs) {
  347. return get$d(xs, xs.length - 1);
  348. };
  349. var findMap = function (arr, f) {
  350. for (var i = 0; i < arr.length; i++) {
  351. var r = f(arr[i], i);
  352. if (r.isSome()) {
  353. return r;
  354. }
  355. }
  356. return Optional.none();
  357. };
  358. var __assign = function () {
  359. __assign = Object.assign || function __assign(t) {
  360. for (var s, i = 1, n = arguments.length; i < n; i++) {
  361. s = arguments[i];
  362. for (var p in s)
  363. if (Object.prototype.hasOwnProperty.call(s, p))
  364. t[p] = s[p];
  365. }
  366. return t;
  367. };
  368. return __assign.apply(this, arguments);
  369. };
  370. function __spreadArray(to, from, pack) {
  371. if (pack || arguments.length === 2)
  372. for (var i = 0, l = from.length, ar; i < l; i++) {
  373. if (ar || !(i in from)) {
  374. if (!ar)
  375. ar = Array.prototype.slice.call(from, 0, i);
  376. ar[i] = from[i];
  377. }
  378. }
  379. return to.concat(ar || Array.prototype.slice.call(from));
  380. }
  381. var cached = function (f) {
  382. var called = false;
  383. var r;
  384. return function () {
  385. var args = [];
  386. for (var _i = 0; _i < arguments.length; _i++) {
  387. args[_i] = arguments[_i];
  388. }
  389. if (!called) {
  390. called = true;
  391. r = f.apply(null, args);
  392. }
  393. return r;
  394. };
  395. };
  396. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  397. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  398. var isiPhone = os.isiOS() && !isiPad;
  399. var isMobile = os.isiOS() || os.isAndroid();
  400. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  401. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  402. var isPhone = isiPhone || isMobile && !isTablet;
  403. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  404. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  405. return {
  406. isiPad: constant(isiPad),
  407. isiPhone: constant(isiPhone),
  408. isTablet: constant(isTablet),
  409. isPhone: constant(isPhone),
  410. isTouch: constant(isTouch),
  411. isAndroid: os.isAndroid,
  412. isiOS: os.isiOS,
  413. isWebView: constant(iOSwebview),
  414. isDesktop: constant(isDesktop)
  415. };
  416. };
  417. var firstMatch = function (regexes, s) {
  418. for (var i = 0; i < regexes.length; i++) {
  419. var x = regexes[i];
  420. if (x.test(s)) {
  421. return x;
  422. }
  423. }
  424. return undefined;
  425. };
  426. var find = function (regexes, agent) {
  427. var r = firstMatch(regexes, agent);
  428. if (!r) {
  429. return {
  430. major: 0,
  431. minor: 0
  432. };
  433. }
  434. var group = function (i) {
  435. return Number(agent.replace(r, '$' + i));
  436. };
  437. return nu$2(group(1), group(2));
  438. };
  439. var detect$6 = function (versionRegexes, agent) {
  440. var cleanedAgent = String(agent).toLowerCase();
  441. if (versionRegexes.length === 0) {
  442. return unknown$2();
  443. }
  444. return find(versionRegexes, cleanedAgent);
  445. };
  446. var unknown$2 = function () {
  447. return nu$2(0, 0);
  448. };
  449. var nu$2 = function (major, minor) {
  450. return {
  451. major: major,
  452. minor: minor
  453. };
  454. };
  455. var Version = {
  456. nu: nu$2,
  457. detect: detect$6,
  458. unknown: unknown$2
  459. };
  460. var detectBrowser$1 = function (browsers, userAgentData) {
  461. return findMap(userAgentData.brands, function (uaBrand) {
  462. var lcBrand = uaBrand.brand.toLowerCase();
  463. return find$1(browsers, function (browser) {
  464. var _a;
  465. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  466. }).map(function (info) {
  467. return {
  468. current: info.name,
  469. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  470. };
  471. });
  472. });
  473. };
  474. var detect$5 = function (candidates, userAgent) {
  475. var agent = String(userAgent).toLowerCase();
  476. return find$1(candidates, function (candidate) {
  477. return candidate.search(agent);
  478. });
  479. };
  480. var detectBrowser = function (browsers, userAgent) {
  481. return detect$5(browsers, userAgent).map(function (browser) {
  482. var version = Version.detect(browser.versionRegexes, userAgent);
  483. return {
  484. current: browser.name,
  485. version: version
  486. };
  487. });
  488. };
  489. var detectOs = function (oses, userAgent) {
  490. return detect$5(oses, userAgent).map(function (os) {
  491. var version = Version.detect(os.versionRegexes, userAgent);
  492. return {
  493. current: os.name,
  494. version: version
  495. };
  496. });
  497. };
  498. var removeFromStart = function (str, numChars) {
  499. return str.substring(numChars);
  500. };
  501. var checkRange = function (str, substr, start) {
  502. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  503. };
  504. var removeLeading = function (str, prefix) {
  505. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  506. };
  507. var contains$1 = function (str, substr) {
  508. return str.indexOf(substr) !== -1;
  509. };
  510. var startsWith = function (str, prefix) {
  511. return checkRange(str, prefix, 0);
  512. };
  513. var endsWith = function (str, suffix) {
  514. return checkRange(str, suffix, str.length - suffix.length);
  515. };
  516. var blank = function (r) {
  517. return function (s) {
  518. return s.replace(r, '');
  519. };
  520. };
  521. var trim = blank(/^\s+|\s+$/g);
  522. var isNotEmpty = function (s) {
  523. return s.length > 0;
  524. };
  525. var isEmpty$1 = function (s) {
  526. return !isNotEmpty(s);
  527. };
  528. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  529. var checkContains = function (target) {
  530. return function (uastring) {
  531. return contains$1(uastring, target);
  532. };
  533. };
  534. var browsers = [
  535. {
  536. name: 'Edge',
  537. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  538. search: function (uastring) {
  539. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  540. }
  541. },
  542. {
  543. name: 'Chrome',
  544. brand: 'Chromium',
  545. versionRegexes: [
  546. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  547. normalVersionRegex
  548. ],
  549. search: function (uastring) {
  550. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  551. }
  552. },
  553. {
  554. name: 'IE',
  555. versionRegexes: [
  556. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  557. /.*?rv:([0-9]+)\.([0-9]+).*/
  558. ],
  559. search: function (uastring) {
  560. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  561. }
  562. },
  563. {
  564. name: 'Opera',
  565. versionRegexes: [
  566. normalVersionRegex,
  567. /.*?opera\/([0-9]+)\.([0-9]+).*/
  568. ],
  569. search: checkContains('opera')
  570. },
  571. {
  572. name: 'Firefox',
  573. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  574. search: checkContains('firefox')
  575. },
  576. {
  577. name: 'Safari',
  578. versionRegexes: [
  579. normalVersionRegex,
  580. /.*?cpu os ([0-9]+)_([0-9]+).*/
  581. ],
  582. search: function (uastring) {
  583. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  584. }
  585. }
  586. ];
  587. var oses = [
  588. {
  589. name: 'Windows',
  590. search: checkContains('win'),
  591. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  592. },
  593. {
  594. name: 'iOS',
  595. search: function (uastring) {
  596. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  597. },
  598. versionRegexes: [
  599. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  600. /.*cpu os ([0-9]+)_([0-9]+).*/,
  601. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  602. ]
  603. },
  604. {
  605. name: 'Android',
  606. search: checkContains('android'),
  607. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  608. },
  609. {
  610. name: 'OSX',
  611. search: checkContains('mac os x'),
  612. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  613. },
  614. {
  615. name: 'Linux',
  616. search: checkContains('linux'),
  617. versionRegexes: []
  618. },
  619. {
  620. name: 'Solaris',
  621. search: checkContains('sunos'),
  622. versionRegexes: []
  623. },
  624. {
  625. name: 'FreeBSD',
  626. search: checkContains('freebsd'),
  627. versionRegexes: []
  628. },
  629. {
  630. name: 'ChromeOS',
  631. search: checkContains('cros'),
  632. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  633. }
  634. ];
  635. var PlatformInfo = {
  636. browsers: constant(browsers),
  637. oses: constant(oses)
  638. };
  639. var edge = 'Edge';
  640. var chrome = 'Chrome';
  641. var ie = 'IE';
  642. var opera = 'Opera';
  643. var firefox = 'Firefox';
  644. var safari = 'Safari';
  645. var unknown$1 = function () {
  646. return nu$1({
  647. current: undefined,
  648. version: Version.unknown()
  649. });
  650. };
  651. var nu$1 = function (info) {
  652. var current = info.current;
  653. var version = info.version;
  654. var isBrowser = function (name) {
  655. return function () {
  656. return current === name;
  657. };
  658. };
  659. return {
  660. current: current,
  661. version: version,
  662. isEdge: isBrowser(edge),
  663. isChrome: isBrowser(chrome),
  664. isIE: isBrowser(ie),
  665. isOpera: isBrowser(opera),
  666. isFirefox: isBrowser(firefox),
  667. isSafari: isBrowser(safari)
  668. };
  669. };
  670. var Browser = {
  671. unknown: unknown$1,
  672. nu: nu$1,
  673. edge: constant(edge),
  674. chrome: constant(chrome),
  675. ie: constant(ie),
  676. opera: constant(opera),
  677. firefox: constant(firefox),
  678. safari: constant(safari)
  679. };
  680. var windows = 'Windows';
  681. var ios = 'iOS';
  682. var android = 'Android';
  683. var linux = 'Linux';
  684. var osx = 'OSX';
  685. var solaris = 'Solaris';
  686. var freebsd = 'FreeBSD';
  687. var chromeos = 'ChromeOS';
  688. var unknown = function () {
  689. return nu({
  690. current: undefined,
  691. version: Version.unknown()
  692. });
  693. };
  694. var nu = function (info) {
  695. var current = info.current;
  696. var version = info.version;
  697. var isOS = function (name) {
  698. return function () {
  699. return current === name;
  700. };
  701. };
  702. return {
  703. current: current,
  704. version: version,
  705. isWindows: isOS(windows),
  706. isiOS: isOS(ios),
  707. isAndroid: isOS(android),
  708. isOSX: isOS(osx),
  709. isLinux: isOS(linux),
  710. isSolaris: isOS(solaris),
  711. isFreeBSD: isOS(freebsd),
  712. isChromeOS: isOS(chromeos)
  713. };
  714. };
  715. var OperatingSystem = {
  716. unknown: unknown,
  717. nu: nu,
  718. windows: constant(windows),
  719. ios: constant(ios),
  720. android: constant(android),
  721. linux: constant(linux),
  722. osx: constant(osx),
  723. solaris: constant(solaris),
  724. freebsd: constant(freebsd),
  725. chromeos: constant(chromeos)
  726. };
  727. var detect$4 = function (userAgent, userAgentDataOpt, mediaMatch) {
  728. var browsers = PlatformInfo.browsers();
  729. var oses = PlatformInfo.oses();
  730. var browser = userAgentDataOpt.bind(function (userAgentData) {
  731. return detectBrowser$1(browsers, userAgentData);
  732. }).orThunk(function () {
  733. return detectBrowser(browsers, userAgent);
  734. }).fold(Browser.unknown, Browser.nu);
  735. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  736. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  737. return {
  738. browser: browser,
  739. os: os,
  740. deviceType: deviceType
  741. };
  742. };
  743. var PlatformDetection = { detect: detect$4 };
  744. var mediaMatch = function (query) {
  745. return window.matchMedia(query).matches;
  746. };
  747. var platform = cached(function () {
  748. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  749. });
  750. var detect$3 = function () {
  751. return platform();
  752. };
  753. var compareDocumentPosition = function (a, b, match) {
  754. return (a.compareDocumentPosition(b) & match) !== 0;
  755. };
  756. var documentPositionContainedBy = function (a, b) {
  757. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  758. };
  759. var COMMENT = 8;
  760. var DOCUMENT = 9;
  761. var DOCUMENT_FRAGMENT = 11;
  762. var ELEMENT = 1;
  763. var TEXT = 3;
  764. var fromHtml$1 = function (html, scope) {
  765. var doc = scope || document;
  766. var div = doc.createElement('div');
  767. div.innerHTML = html;
  768. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  769. console.error('HTML does not have a single root node', html);
  770. throw new Error('HTML must have a single root node');
  771. }
  772. return fromDom$1(div.childNodes[0]);
  773. };
  774. var fromTag = function (tag, scope) {
  775. var doc = scope || document;
  776. var node = doc.createElement(tag);
  777. return fromDom$1(node);
  778. };
  779. var fromText = function (text, scope) {
  780. var doc = scope || document;
  781. var node = doc.createTextNode(text);
  782. return fromDom$1(node);
  783. };
  784. var fromDom$1 = function (node) {
  785. if (node === null || node === undefined) {
  786. throw new Error('Node cannot be null or undefined');
  787. }
  788. return { dom: node };
  789. };
  790. var fromPoint$1 = function (docElm, x, y) {
  791. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$1);
  792. };
  793. var SugarElement = {
  794. fromHtml: fromHtml$1,
  795. fromTag: fromTag,
  796. fromText: fromText,
  797. fromDom: fromDom$1,
  798. fromPoint: fromPoint$1
  799. };
  800. var is$2 = function (element, selector) {
  801. var dom = element.dom;
  802. if (dom.nodeType !== ELEMENT) {
  803. return false;
  804. } else {
  805. var elem = dom;
  806. if (elem.matches !== undefined) {
  807. return elem.matches(selector);
  808. } else if (elem.msMatchesSelector !== undefined) {
  809. return elem.msMatchesSelector(selector);
  810. } else if (elem.webkitMatchesSelector !== undefined) {
  811. return elem.webkitMatchesSelector(selector);
  812. } else if (elem.mozMatchesSelector !== undefined) {
  813. return elem.mozMatchesSelector(selector);
  814. } else {
  815. throw new Error('Browser lacks native selectors');
  816. }
  817. }
  818. };
  819. var bypassSelector = function (dom) {
  820. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  821. };
  822. var all$1 = function (selector, scope) {
  823. var base = scope === undefined ? document : scope.dom;
  824. return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), SugarElement.fromDom);
  825. };
  826. var one = function (selector, scope) {
  827. var base = scope === undefined ? document : scope.dom;
  828. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  829. };
  830. var eq$1 = function (e1, e2) {
  831. return e1.dom === e2.dom;
  832. };
  833. var regularContains = function (e1, e2) {
  834. var d1 = e1.dom;
  835. var d2 = e2.dom;
  836. return d1 === d2 ? false : d1.contains(d2);
  837. };
  838. var ieContains = function (e1, e2) {
  839. return documentPositionContainedBy(e1.dom, e2.dom);
  840. };
  841. var contains = function (e1, e2) {
  842. return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  843. };
  844. var is$1 = is$2;
  845. var keys = Object.keys;
  846. var hasOwnProperty = Object.hasOwnProperty;
  847. var each$1 = function (obj, f) {
  848. var props = keys(obj);
  849. for (var k = 0, len = props.length; k < len; k++) {
  850. var i = props[k];
  851. var x = obj[i];
  852. f(x, i);
  853. }
  854. };
  855. var map = function (obj, f) {
  856. return tupleMap(obj, function (x, i) {
  857. return {
  858. k: i,
  859. v: f(x, i)
  860. };
  861. });
  862. };
  863. var tupleMap = function (obj, f) {
  864. var r = {};
  865. each$1(obj, function (x, i) {
  866. var tuple = f(x, i);
  867. r[tuple.k] = tuple.v;
  868. });
  869. return r;
  870. };
  871. var objAcc = function (r) {
  872. return function (x, i) {
  873. r[i] = x;
  874. };
  875. };
  876. var internalFilter = function (obj, pred, onTrue, onFalse) {
  877. var r = {};
  878. each$1(obj, function (x, i) {
  879. (pred(x, i) ? onTrue : onFalse)(x, i);
  880. });
  881. return r;
  882. };
  883. var filter$1 = function (obj, pred) {
  884. var t = {};
  885. internalFilter(obj, pred, objAcc(t), noop);
  886. return t;
  887. };
  888. var mapToArray = function (obj, f) {
  889. var r = [];
  890. each$1(obj, function (value, name) {
  891. r.push(f(value, name));
  892. });
  893. return r;
  894. };
  895. var values = function (obj) {
  896. return mapToArray(obj, identity);
  897. };
  898. var size = function (obj) {
  899. return keys(obj).length;
  900. };
  901. var get$c = function (obj, key) {
  902. return has$1(obj, key) ? Optional.from(obj[key]) : Optional.none();
  903. };
  904. var has$1 = function (obj, key) {
  905. return hasOwnProperty.call(obj, key);
  906. };
  907. var hasNonNullableKey = function (obj, key) {
  908. return has$1(obj, key) && obj[key] !== undefined && obj[key] !== null;
  909. };
  910. var isEmpty = function (r) {
  911. for (var x in r) {
  912. if (hasOwnProperty.call(r, x)) {
  913. return false;
  914. }
  915. }
  916. return true;
  917. };
  918. var validSectionList = [
  919. 'tfoot',
  920. 'thead',
  921. 'tbody',
  922. 'colgroup'
  923. ];
  924. var isValidSection = function (parentName) {
  925. return contains$2(validSectionList, parentName);
  926. };
  927. var grid = function (rows, columns) {
  928. return {
  929. rows: rows,
  930. columns: columns
  931. };
  932. };
  933. var address = function (row, column) {
  934. return {
  935. row: row,
  936. column: column
  937. };
  938. };
  939. var detail = function (element, rowspan, colspan) {
  940. return {
  941. element: element,
  942. rowspan: rowspan,
  943. colspan: colspan
  944. };
  945. };
  946. var detailnew = function (element, rowspan, colspan, isNew) {
  947. return {
  948. element: element,
  949. rowspan: rowspan,
  950. colspan: colspan,
  951. isNew: isNew
  952. };
  953. };
  954. var extended = function (element, rowspan, colspan, row, column, isLocked) {
  955. return {
  956. element: element,
  957. rowspan: rowspan,
  958. colspan: colspan,
  959. row: row,
  960. column: column,
  961. isLocked: isLocked
  962. };
  963. };
  964. var rowdetail = function (element, cells, section) {
  965. return {
  966. element: element,
  967. cells: cells,
  968. section: section
  969. };
  970. };
  971. var rowdetailnew = function (element, cells, section, isNew) {
  972. return {
  973. element: element,
  974. cells: cells,
  975. section: section,
  976. isNew: isNew
  977. };
  978. };
  979. var elementnew = function (element, isNew, isLocked) {
  980. return {
  981. element: element,
  982. isNew: isNew,
  983. isLocked: isLocked
  984. };
  985. };
  986. var rowcells = function (element, cells, section, isNew) {
  987. return {
  988. element: element,
  989. cells: cells,
  990. section: section,
  991. isNew: isNew
  992. };
  993. };
  994. var bounds = function (startRow, startCol, finishRow, finishCol) {
  995. return {
  996. startRow: startRow,
  997. startCol: startCol,
  998. finishRow: finishRow,
  999. finishCol: finishCol
  1000. };
  1001. };
  1002. var columnext = function (element, colspan, column) {
  1003. return {
  1004. element: element,
  1005. colspan: colspan,
  1006. column: column
  1007. };
  1008. };
  1009. var colgroup = function (element, columns) {
  1010. return {
  1011. element: element,
  1012. columns: columns
  1013. };
  1014. };
  1015. typeof window !== 'undefined' ? window : Function('return this;')();
  1016. var name = function (element) {
  1017. var r = element.dom.nodeName;
  1018. return r.toLowerCase();
  1019. };
  1020. var type$1 = function (element) {
  1021. return element.dom.nodeType;
  1022. };
  1023. var isType = function (t) {
  1024. return function (element) {
  1025. return type$1(element) === t;
  1026. };
  1027. };
  1028. var isComment = function (element) {
  1029. return type$1(element) === COMMENT || name(element) === '#comment';
  1030. };
  1031. var isElement = isType(ELEMENT);
  1032. var isText = isType(TEXT);
  1033. var isDocument = isType(DOCUMENT);
  1034. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  1035. var isTag = function (tag) {
  1036. return function (e) {
  1037. return isElement(e) && name(e) === tag;
  1038. };
  1039. };
  1040. var owner = function (element) {
  1041. return SugarElement.fromDom(element.dom.ownerDocument);
  1042. };
  1043. var documentOrOwner = function (dos) {
  1044. return isDocument(dos) ? dos : owner(dos);
  1045. };
  1046. var defaultView = function (element) {
  1047. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1048. };
  1049. var parent = function (element) {
  1050. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1051. };
  1052. var parents = function (element, isRoot) {
  1053. var stop = isFunction(isRoot) ? isRoot : never;
  1054. var dom = element.dom;
  1055. var ret = [];
  1056. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1057. var rawParent = dom.parentNode;
  1058. var p = SugarElement.fromDom(rawParent);
  1059. ret.push(p);
  1060. if (stop(p) === true) {
  1061. break;
  1062. } else {
  1063. dom = rawParent;
  1064. }
  1065. }
  1066. return ret;
  1067. };
  1068. var offsetParent = function (element) {
  1069. return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
  1070. };
  1071. var prevSibling = function (element) {
  1072. return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1073. };
  1074. var nextSibling = function (element) {
  1075. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1076. };
  1077. var children$3 = function (element) {
  1078. return map$1(element.dom.childNodes, SugarElement.fromDom);
  1079. };
  1080. var child$3 = function (element, index) {
  1081. var cs = element.dom.childNodes;
  1082. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1083. };
  1084. var firstChild = function (element) {
  1085. return child$3(element, 0);
  1086. };
  1087. var isShadowRoot = function (dos) {
  1088. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  1089. };
  1090. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1091. var isSupported$1 = constant(supported);
  1092. var getRootNode = supported ? function (e) {
  1093. return SugarElement.fromDom(e.dom.getRootNode());
  1094. } : documentOrOwner;
  1095. var getShadowRoot = function (e) {
  1096. var r = getRootNode(e);
  1097. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1098. };
  1099. var getShadowHost = function (e) {
  1100. return SugarElement.fromDom(e.dom.host);
  1101. };
  1102. var getOriginalEventTarget = function (event) {
  1103. if (isSupported$1() && isNonNullable(event.target)) {
  1104. var el = SugarElement.fromDom(event.target);
  1105. if (isElement(el) && isOpenShadowHost(el)) {
  1106. if (event.composed && event.composedPath) {
  1107. var composedPath = event.composedPath();
  1108. if (composedPath) {
  1109. return head(composedPath);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. return Optional.from(event.target);
  1115. };
  1116. var isOpenShadowHost = function (element) {
  1117. return isNonNullable(element.dom.shadowRoot);
  1118. };
  1119. var inBody = function (element) {
  1120. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1121. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1122. return false;
  1123. }
  1124. var doc = dom.ownerDocument;
  1125. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1126. return doc.body.contains(dom);
  1127. }, compose1(inBody, getShadowHost));
  1128. };
  1129. var body$1 = function () {
  1130. return getBody$1(SugarElement.fromDom(document));
  1131. };
  1132. var getBody$1 = function (doc) {
  1133. var b = doc.dom.body;
  1134. if (b === null || b === undefined) {
  1135. throw new Error('Body is not available yet');
  1136. }
  1137. return SugarElement.fromDom(b);
  1138. };
  1139. var ancestors$4 = function (scope, predicate, isRoot) {
  1140. return filter$2(parents(scope, isRoot), predicate);
  1141. };
  1142. var children$2 = function (scope, predicate) {
  1143. return filter$2(children$3(scope), predicate);
  1144. };
  1145. var descendants$1 = function (scope, predicate) {
  1146. var result = [];
  1147. each$2(children$3(scope), function (x) {
  1148. if (predicate(x)) {
  1149. result = result.concat([x]);
  1150. }
  1151. result = result.concat(descendants$1(x, predicate));
  1152. });
  1153. return result;
  1154. };
  1155. var ancestors$3 = function (scope, selector, isRoot) {
  1156. return ancestors$4(scope, function (e) {
  1157. return is$2(e, selector);
  1158. }, isRoot);
  1159. };
  1160. var children$1 = function (scope, selector) {
  1161. return children$2(scope, function (e) {
  1162. return is$2(e, selector);
  1163. });
  1164. };
  1165. var descendants = function (scope, selector) {
  1166. return all$1(selector, scope);
  1167. };
  1168. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  1169. if (is(scope, a)) {
  1170. return Optional.some(scope);
  1171. } else if (isFunction(isRoot) && isRoot(scope)) {
  1172. return Optional.none();
  1173. } else {
  1174. return ancestor(scope, a, isRoot);
  1175. }
  1176. }
  1177. var ancestor$2 = function (scope, predicate, isRoot) {
  1178. var element = scope.dom;
  1179. var stop = isFunction(isRoot) ? isRoot : never;
  1180. while (element.parentNode) {
  1181. element = element.parentNode;
  1182. var el = SugarElement.fromDom(element);
  1183. if (predicate(el)) {
  1184. return Optional.some(el);
  1185. } else if (stop(el)) {
  1186. break;
  1187. }
  1188. }
  1189. return Optional.none();
  1190. };
  1191. var closest$2 = function (scope, predicate, isRoot) {
  1192. var is = function (s, test) {
  1193. return test(s);
  1194. };
  1195. return ClosestOrAncestor(is, ancestor$2, scope, predicate, isRoot);
  1196. };
  1197. var child$2 = function (scope, predicate) {
  1198. var pred = function (node) {
  1199. return predicate(SugarElement.fromDom(node));
  1200. };
  1201. var result = find$1(scope.dom.childNodes, pred);
  1202. return result.map(SugarElement.fromDom);
  1203. };
  1204. var descendant$1 = function (scope, predicate) {
  1205. var descend = function (node) {
  1206. for (var i = 0; i < node.childNodes.length; i++) {
  1207. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  1208. if (predicate(child_1)) {
  1209. return Optional.some(child_1);
  1210. }
  1211. var res = descend(node.childNodes[i]);
  1212. if (res.isSome()) {
  1213. return res;
  1214. }
  1215. }
  1216. return Optional.none();
  1217. };
  1218. return descend(scope.dom);
  1219. };
  1220. var ancestor$1 = function (scope, selector, isRoot) {
  1221. return ancestor$2(scope, function (e) {
  1222. return is$2(e, selector);
  1223. }, isRoot);
  1224. };
  1225. var child$1 = function (scope, selector) {
  1226. return child$2(scope, function (e) {
  1227. return is$2(e, selector);
  1228. });
  1229. };
  1230. var descendant = function (scope, selector) {
  1231. return one(selector, scope);
  1232. };
  1233. var closest$1 = function (scope, selector, isRoot) {
  1234. var is = function (element, selector) {
  1235. return is$2(element, selector);
  1236. };
  1237. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  1238. };
  1239. var rawSet = function (dom, key, value) {
  1240. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1241. dom.setAttribute(key, value + '');
  1242. } else {
  1243. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1244. throw new Error('Attribute value was not simple');
  1245. }
  1246. };
  1247. var set$2 = function (element, key, value) {
  1248. rawSet(element.dom, key, value);
  1249. };
  1250. var setAll$1 = function (element, attrs) {
  1251. var dom = element.dom;
  1252. each$1(attrs, function (v, k) {
  1253. rawSet(dom, k, v);
  1254. });
  1255. };
  1256. var get$b = function (element, key) {
  1257. var v = element.dom.getAttribute(key);
  1258. return v === null ? undefined : v;
  1259. };
  1260. var getOpt = function (element, key) {
  1261. return Optional.from(get$b(element, key));
  1262. };
  1263. var remove$7 = function (element, key) {
  1264. element.dom.removeAttribute(key);
  1265. };
  1266. var clone$2 = function (element) {
  1267. return foldl(element.dom.attributes, function (acc, attr) {
  1268. acc[attr.name] = attr.value;
  1269. return acc;
  1270. }, {});
  1271. };
  1272. var is = function (lhs, rhs, comparator) {
  1273. if (comparator === void 0) {
  1274. comparator = tripleEquals;
  1275. }
  1276. return lhs.exists(function (left) {
  1277. return comparator(left, rhs);
  1278. });
  1279. };
  1280. var cat = function (arr) {
  1281. var r = [];
  1282. var push = function (x) {
  1283. r.push(x);
  1284. };
  1285. for (var i = 0; i < arr.length; i++) {
  1286. arr[i].each(push);
  1287. }
  1288. return r;
  1289. };
  1290. var lift2 = function (oa, ob, f) {
  1291. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1292. };
  1293. var bindFrom = function (a, f) {
  1294. return a !== undefined && a !== null ? f(a) : Optional.none();
  1295. };
  1296. var flatten = function (oot) {
  1297. return oot.bind(identity);
  1298. };
  1299. var someIf = function (b, a) {
  1300. return b ? Optional.some(a) : Optional.none();
  1301. };
  1302. var isSupported = function (dom) {
  1303. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1304. };
  1305. var internalSet = function (dom, property, value) {
  1306. if (!isString(value)) {
  1307. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1308. throw new Error('CSS value must be a string: ' + value);
  1309. }
  1310. if (isSupported(dom)) {
  1311. dom.style.setProperty(property, value);
  1312. }
  1313. };
  1314. var internalRemove = function (dom, property) {
  1315. if (isSupported(dom)) {
  1316. dom.style.removeProperty(property);
  1317. }
  1318. };
  1319. var set$1 = function (element, property, value) {
  1320. var dom = element.dom;
  1321. internalSet(dom, property, value);
  1322. };
  1323. var setAll = function (element, css) {
  1324. var dom = element.dom;
  1325. each$1(css, function (v, k) {
  1326. internalSet(dom, k, v);
  1327. });
  1328. };
  1329. var get$a = function (element, property) {
  1330. var dom = element.dom;
  1331. var styles = window.getComputedStyle(dom);
  1332. var r = styles.getPropertyValue(property);
  1333. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1334. };
  1335. var getUnsafeProperty = function (dom, property) {
  1336. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1337. };
  1338. var getRaw$2 = function (element, property) {
  1339. var dom = element.dom;
  1340. var raw = getUnsafeProperty(dom, property);
  1341. return Optional.from(raw).filter(function (r) {
  1342. return r.length > 0;
  1343. });
  1344. };
  1345. var remove$6 = function (element, property) {
  1346. var dom = element.dom;
  1347. internalRemove(dom, property);
  1348. if (is(getOpt(element, 'style').map(trim), '')) {
  1349. remove$7(element, 'style');
  1350. }
  1351. };
  1352. var copy$2 = function (source, target) {
  1353. var sourceDom = source.dom;
  1354. var targetDom = target.dom;
  1355. if (isSupported(sourceDom) && isSupported(targetDom)) {
  1356. targetDom.style.cssText = sourceDom.style.cssText;
  1357. }
  1358. };
  1359. var getAttrValue = function (cell, name, fallback) {
  1360. if (fallback === void 0) {
  1361. fallback = 0;
  1362. }
  1363. return getOpt(cell, name).map(function (value) {
  1364. return parseInt(value, 10);
  1365. }).getOr(fallback);
  1366. };
  1367. var getSpan = function (cell, type) {
  1368. return getAttrValue(cell, type, 1);
  1369. };
  1370. var hasColspan = function (cell) {
  1371. return getSpan(cell, 'colspan') > 1;
  1372. };
  1373. var hasRowspan = function (cell) {
  1374. return getSpan(cell, 'rowspan') > 1;
  1375. };
  1376. var getCssValue = function (element, property) {
  1377. return parseInt(get$a(element, property), 10);
  1378. };
  1379. var minWidth = constant(10);
  1380. var minHeight = constant(10);
  1381. var firstLayer = function (scope, selector) {
  1382. return filterFirstLayer(scope, selector, always);
  1383. };
  1384. var filterFirstLayer = function (scope, selector, predicate) {
  1385. return bind$2(children$3(scope), function (x) {
  1386. if (is$2(x, selector)) {
  1387. return predicate(x) ? [x] : [];
  1388. } else {
  1389. return filterFirstLayer(x, selector, predicate);
  1390. }
  1391. });
  1392. };
  1393. var lookup = function (tags, element, isRoot) {
  1394. if (isRoot === void 0) {
  1395. isRoot = never;
  1396. }
  1397. if (isRoot(element)) {
  1398. return Optional.none();
  1399. }
  1400. if (contains$2(tags, name(element))) {
  1401. return Optional.some(element);
  1402. }
  1403. var isRootOrUpperTable = function (elm) {
  1404. return is$2(elm, 'table') || isRoot(elm);
  1405. };
  1406. return ancestor$1(element, tags.join(','), isRootOrUpperTable);
  1407. };
  1408. var cell = function (element, isRoot) {
  1409. return lookup([
  1410. 'td',
  1411. 'th'
  1412. ], element, isRoot);
  1413. };
  1414. var cells$1 = function (ancestor) {
  1415. return firstLayer(ancestor, 'th,td');
  1416. };
  1417. var columns$1 = function (ancestor) {
  1418. if (is$2(ancestor, 'colgroup')) {
  1419. return children$1(ancestor, 'col');
  1420. } else {
  1421. return bind$2(columnGroups(ancestor), function (columnGroup) {
  1422. return children$1(columnGroup, 'col');
  1423. });
  1424. }
  1425. };
  1426. var table = function (element, isRoot) {
  1427. return closest$1(element, 'table', isRoot);
  1428. };
  1429. var rows$1 = function (ancestor) {
  1430. return firstLayer(ancestor, 'tr');
  1431. };
  1432. var columnGroups = function (ancestor) {
  1433. return table(ancestor).fold(constant([]), function (table) {
  1434. return children$1(table, 'colgroup');
  1435. });
  1436. };
  1437. var fromRowsOrColGroups = function (elems, getSection) {
  1438. return map$1(elems, function (row) {
  1439. if (name(row) === 'colgroup') {
  1440. var cells = map$1(columns$1(row), function (column) {
  1441. var colspan = getAttrValue(column, 'span', 1);
  1442. return detail(column, 1, colspan);
  1443. });
  1444. return rowdetail(row, cells, 'colgroup');
  1445. } else {
  1446. var cells = map$1(cells$1(row), function (cell) {
  1447. var rowspan = getAttrValue(cell, 'rowspan', 1);
  1448. var colspan = getAttrValue(cell, 'colspan', 1);
  1449. return detail(cell, rowspan, colspan);
  1450. });
  1451. return rowdetail(row, cells, getSection(row));
  1452. }
  1453. });
  1454. };
  1455. var getParentSection = function (group) {
  1456. return parent(group).map(function (parent) {
  1457. var parentName = name(parent);
  1458. return isValidSection(parentName) ? parentName : 'tbody';
  1459. }).getOr('tbody');
  1460. };
  1461. var fromTable$1 = function (table) {
  1462. var rows = rows$1(table);
  1463. var columnGroups$1 = columnGroups(table);
  1464. var elems = __spreadArray(__spreadArray([], columnGroups$1), rows);
  1465. return fromRowsOrColGroups(elems, getParentSection);
  1466. };
  1467. var fromPastedRows = function (elems, section) {
  1468. return fromRowsOrColGroups(elems, function () {
  1469. return section;
  1470. });
  1471. };
  1472. var addCells = function (gridRow, index, cells) {
  1473. var existingCells = gridRow.cells;
  1474. var before = existingCells.slice(0, index);
  1475. var after = existingCells.slice(index);
  1476. var newCells = before.concat(cells).concat(after);
  1477. return setCells(gridRow, newCells);
  1478. };
  1479. var addCell = function (gridRow, index, cell) {
  1480. return addCells(gridRow, index, [cell]);
  1481. };
  1482. var mutateCell = function (gridRow, index, cell) {
  1483. var cells = gridRow.cells;
  1484. cells[index] = cell;
  1485. };
  1486. var setCells = function (gridRow, cells) {
  1487. return rowcells(gridRow.element, cells, gridRow.section, gridRow.isNew);
  1488. };
  1489. var mapCells = function (gridRow, f) {
  1490. var cells = gridRow.cells;
  1491. var r = map$1(cells, f);
  1492. return rowcells(gridRow.element, r, gridRow.section, gridRow.isNew);
  1493. };
  1494. var getCell = function (gridRow, index) {
  1495. return gridRow.cells[index];
  1496. };
  1497. var getCellElement = function (gridRow, index) {
  1498. return getCell(gridRow, index).element;
  1499. };
  1500. var cellLength = function (gridRow) {
  1501. return gridRow.cells.length;
  1502. };
  1503. var extractGridDetails = function (grid) {
  1504. var result = partition(grid, function (row) {
  1505. return row.section === 'colgroup';
  1506. });
  1507. return {
  1508. rows: result.fail,
  1509. cols: result.pass
  1510. };
  1511. };
  1512. var clone$1 = function (gridRow, cloneRow, cloneCell) {
  1513. var newCells = map$1(gridRow.cells, cloneCell);
  1514. return rowcells(cloneRow(gridRow.element), newCells, gridRow.section, true);
  1515. };
  1516. var LOCKED_COL_ATTR = 'data-snooker-locked-cols';
  1517. var getLockedColumnsFromTable = function (table) {
  1518. return getOpt(table, LOCKED_COL_ATTR).bind(function (lockedColStr) {
  1519. return Optional.from(lockedColStr.match(/\d+/g));
  1520. }).map(function (lockedCols) {
  1521. return mapToObject(lockedCols, always);
  1522. });
  1523. };
  1524. var getLockedColumnsFromGrid = function (grid) {
  1525. var locked = foldl(extractGridDetails(grid).rows, function (acc, row) {
  1526. each$2(row.cells, function (cell, idx) {
  1527. if (cell.isLocked) {
  1528. acc[idx] = true;
  1529. }
  1530. });
  1531. return acc;
  1532. }, {});
  1533. var lockedArr = mapToArray(locked, function (_val, key) {
  1534. return parseInt(key, 10);
  1535. });
  1536. return sort$1(lockedArr);
  1537. };
  1538. var key = function (row, column) {
  1539. return row + ',' + column;
  1540. };
  1541. var getAt = function (warehouse, row, column) {
  1542. return Optional.from(warehouse.access[key(row, column)]);
  1543. };
  1544. var findItem = function (warehouse, item, comparator) {
  1545. var filtered = filterItems(warehouse, function (detail) {
  1546. return comparator(item, detail.element);
  1547. });
  1548. return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
  1549. };
  1550. var filterItems = function (warehouse, predicate) {
  1551. var all = bind$2(warehouse.all, function (r) {
  1552. return r.cells;
  1553. });
  1554. return filter$2(all, predicate);
  1555. };
  1556. var generateColumns = function (rowData) {
  1557. var columnsGroup = {};
  1558. var index = 0;
  1559. each$2(rowData.cells, function (column) {
  1560. var colspan = column.colspan;
  1561. range$1(colspan, function (columnIndex) {
  1562. var colIndex = index + columnIndex;
  1563. columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
  1564. });
  1565. index += colspan;
  1566. });
  1567. return columnsGroup;
  1568. };
  1569. var generate$1 = function (list) {
  1570. var access = {};
  1571. var cells = [];
  1572. var columns = {};
  1573. var colgroups = [];
  1574. var tableOpt = head(list).map(function (rowData) {
  1575. return rowData.element;
  1576. }).bind(table);
  1577. var lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
  1578. var maxRows = 0;
  1579. var maxColumns = 0;
  1580. var rowCount = 0;
  1581. each$2(list, function (rowData) {
  1582. if (rowData.section === 'colgroup') {
  1583. columns = generateColumns(rowData);
  1584. colgroups = [colgroup(rowData.element, values(columns))];
  1585. } else {
  1586. var currentRow_1 = [];
  1587. each$2(rowData.cells, function (rowCell) {
  1588. var start = 0;
  1589. while (access[key(rowCount, start)] !== undefined) {
  1590. start++;
  1591. }
  1592. var isLocked = hasNonNullableKey(lockedColumns, start.toString());
  1593. var current = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start, isLocked);
  1594. for (var occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
  1595. for (var occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
  1596. var rowPosition = rowCount + occupiedRowPosition;
  1597. var columnPosition = start + occupiedColumnPosition;
  1598. var newpos = key(rowPosition, columnPosition);
  1599. access[newpos] = current;
  1600. maxColumns = Math.max(maxColumns, columnPosition + 1);
  1601. }
  1602. }
  1603. currentRow_1.push(current);
  1604. });
  1605. maxRows++;
  1606. cells.push(rowdetail(rowData.element, currentRow_1, rowData.section));
  1607. rowCount++;
  1608. }
  1609. });
  1610. var grid$1 = grid(maxRows, maxColumns);
  1611. return {
  1612. grid: grid$1,
  1613. access: access,
  1614. all: cells,
  1615. columns: columns,
  1616. colgroups: colgroups
  1617. };
  1618. };
  1619. var fromTable = function (table) {
  1620. var list = fromTable$1(table);
  1621. return generate$1(list);
  1622. };
  1623. var justCells = function (warehouse) {
  1624. return bind$2(warehouse.all, function (w) {
  1625. return w.cells;
  1626. });
  1627. };
  1628. var justColumns = function (warehouse) {
  1629. return values(warehouse.columns);
  1630. };
  1631. var hasColumns = function (warehouse) {
  1632. return keys(warehouse.columns).length > 0;
  1633. };
  1634. var getColumnAt = function (warehouse, columnIndex) {
  1635. return Optional.from(warehouse.columns[columnIndex]);
  1636. };
  1637. var Warehouse = {
  1638. fromTable: fromTable,
  1639. generate: generate$1,
  1640. getAt: getAt,
  1641. findItem: findItem,
  1642. filterItems: filterItems,
  1643. justCells: justCells,
  1644. justColumns: justColumns,
  1645. hasColumns: hasColumns,
  1646. getColumnAt: getColumnAt
  1647. };
  1648. var inSelection = function (bounds, detail) {
  1649. var leftEdge = detail.column;
  1650. var rightEdge = detail.column + detail.colspan - 1;
  1651. var topEdge = detail.row;
  1652. var bottomEdge = detail.row + detail.rowspan - 1;
  1653. return leftEdge <= bounds.finishCol && rightEdge >= bounds.startCol && (topEdge <= bounds.finishRow && bottomEdge >= bounds.startRow);
  1654. };
  1655. var isWithin = function (bounds, detail) {
  1656. return detail.column >= bounds.startCol && detail.column + detail.colspan - 1 <= bounds.finishCol && detail.row >= bounds.startRow && detail.row + detail.rowspan - 1 <= bounds.finishRow;
  1657. };
  1658. var isRectangular = function (warehouse, bounds) {
  1659. var isRect = true;
  1660. var detailIsWithin = curry(isWithin, bounds);
  1661. for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
  1662. for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
  1663. isRect = isRect && Warehouse.getAt(warehouse, i, j).exists(detailIsWithin);
  1664. }
  1665. }
  1666. return isRect ? Optional.some(bounds) : Optional.none();
  1667. };
  1668. var getBounds = function (detailA, detailB) {
  1669. 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));
  1670. };
  1671. var getAnyBox = function (warehouse, startCell, finishCell) {
  1672. var startCoords = Warehouse.findItem(warehouse, startCell, eq$1);
  1673. var finishCoords = Warehouse.findItem(warehouse, finishCell, eq$1);
  1674. return startCoords.bind(function (sc) {
  1675. return finishCoords.map(function (fc) {
  1676. return getBounds(sc, fc);
  1677. });
  1678. });
  1679. };
  1680. var getBox$1 = function (warehouse, startCell, finishCell) {
  1681. return getAnyBox(warehouse, startCell, finishCell).bind(function (bounds) {
  1682. return isRectangular(warehouse, bounds);
  1683. });
  1684. };
  1685. var moveBy$1 = function (warehouse, cell, row, column) {
  1686. return Warehouse.findItem(warehouse, cell, eq$1).bind(function (detail) {
  1687. var startRow = row > 0 ? detail.row + detail.rowspan - 1 : detail.row;
  1688. var startCol = column > 0 ? detail.column + detail.colspan - 1 : detail.column;
  1689. var dest = Warehouse.getAt(warehouse, startRow + row, startCol + column);
  1690. return dest.map(function (d) {
  1691. return d.element;
  1692. });
  1693. });
  1694. };
  1695. var intercepts$1 = function (warehouse, start, finish) {
  1696. return getAnyBox(warehouse, start, finish).map(function (bounds) {
  1697. var inside = Warehouse.filterItems(warehouse, curry(inSelection, bounds));
  1698. return map$1(inside, function (detail) {
  1699. return detail.element;
  1700. });
  1701. });
  1702. };
  1703. var parentCell = function (warehouse, innerCell) {
  1704. var isContainedBy = function (c1, c2) {
  1705. return contains(c2, c1);
  1706. };
  1707. return Warehouse.findItem(warehouse, innerCell, isContainedBy).map(function (detail) {
  1708. return detail.element;
  1709. });
  1710. };
  1711. var moveBy = function (cell, deltaRow, deltaColumn) {
  1712. return table(cell).bind(function (table) {
  1713. var warehouse = getWarehouse(table);
  1714. return moveBy$1(warehouse, cell, deltaRow, deltaColumn);
  1715. });
  1716. };
  1717. var intercepts = function (table, first, last) {
  1718. var warehouse = getWarehouse(table);
  1719. return intercepts$1(warehouse, first, last);
  1720. };
  1721. var nestedIntercepts = function (table, first, firstTable, last, lastTable) {
  1722. var warehouse = getWarehouse(table);
  1723. var optStartCell = eq$1(table, firstTable) ? Optional.some(first) : parentCell(warehouse, first);
  1724. var optLastCell = eq$1(table, lastTable) ? Optional.some(last) : parentCell(warehouse, last);
  1725. return optStartCell.bind(function (startCell) {
  1726. return optLastCell.bind(function (lastCell) {
  1727. return intercepts$1(warehouse, startCell, lastCell);
  1728. });
  1729. });
  1730. };
  1731. var getBox = function (table, first, last) {
  1732. var warehouse = getWarehouse(table);
  1733. return getBox$1(warehouse, first, last);
  1734. };
  1735. var getWarehouse = Warehouse.fromTable;
  1736. var before$4 = function (marker, element) {
  1737. var parent$1 = parent(marker);
  1738. parent$1.each(function (v) {
  1739. v.dom.insertBefore(element.dom, marker.dom);
  1740. });
  1741. };
  1742. var after$5 = function (marker, element) {
  1743. var sibling = nextSibling(marker);
  1744. sibling.fold(function () {
  1745. var parent$1 = parent(marker);
  1746. parent$1.each(function (v) {
  1747. append$1(v, element);
  1748. });
  1749. }, function (v) {
  1750. before$4(v, element);
  1751. });
  1752. };
  1753. var prepend = function (parent, element) {
  1754. var firstChild$1 = firstChild(parent);
  1755. firstChild$1.fold(function () {
  1756. append$1(parent, element);
  1757. }, function (v) {
  1758. parent.dom.insertBefore(element.dom, v.dom);
  1759. });
  1760. };
  1761. var append$1 = function (parent, element) {
  1762. parent.dom.appendChild(element.dom);
  1763. };
  1764. var appendAt = function (parent, element, index) {
  1765. child$3(parent, index).fold(function () {
  1766. append$1(parent, element);
  1767. }, function (v) {
  1768. before$4(v, element);
  1769. });
  1770. };
  1771. var wrap = function (element, wrapper) {
  1772. before$4(element, wrapper);
  1773. append$1(wrapper, element);
  1774. };
  1775. var before$3 = function (marker, elements) {
  1776. each$2(elements, function (x) {
  1777. before$4(marker, x);
  1778. });
  1779. };
  1780. var after$4 = function (marker, elements) {
  1781. each$2(elements, function (x, i) {
  1782. var e = i === 0 ? marker : elements[i - 1];
  1783. after$5(e, x);
  1784. });
  1785. };
  1786. var append = function (parent, elements) {
  1787. each$2(elements, function (x) {
  1788. append$1(parent, x);
  1789. });
  1790. };
  1791. var empty = function (element) {
  1792. element.dom.textContent = '';
  1793. each$2(children$3(element), function (rogue) {
  1794. remove$5(rogue);
  1795. });
  1796. };
  1797. var remove$5 = function (element) {
  1798. var dom = element.dom;
  1799. if (dom.parentNode !== null) {
  1800. dom.parentNode.removeChild(dom);
  1801. }
  1802. };
  1803. var unwrap = function (wrapper) {
  1804. var children = children$3(wrapper);
  1805. if (children.length > 0) {
  1806. before$3(wrapper, children);
  1807. }
  1808. remove$5(wrapper);
  1809. };
  1810. var NodeValue = function (is, name) {
  1811. var get = function (element) {
  1812. if (!is(element)) {
  1813. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  1814. }
  1815. return getOption(element).getOr('');
  1816. };
  1817. var getOption = function (element) {
  1818. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  1819. };
  1820. var set = function (element, value) {
  1821. if (!is(element)) {
  1822. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  1823. }
  1824. element.dom.nodeValue = value;
  1825. };
  1826. return {
  1827. get: get,
  1828. getOption: getOption,
  1829. set: set
  1830. };
  1831. };
  1832. var api$2 = NodeValue(isText, 'text');
  1833. var get$9 = function (element) {
  1834. return api$2.get(element);
  1835. };
  1836. var getOption = function (element) {
  1837. return api$2.getOption(element);
  1838. };
  1839. var set = function (element, value) {
  1840. return api$2.set(element, value);
  1841. };
  1842. var TagBoundaries = [
  1843. 'body',
  1844. 'p',
  1845. 'div',
  1846. 'article',
  1847. 'aside',
  1848. 'figcaption',
  1849. 'figure',
  1850. 'footer',
  1851. 'header',
  1852. 'nav',
  1853. 'section',
  1854. 'ol',
  1855. 'ul',
  1856. 'li',
  1857. 'table',
  1858. 'thead',
  1859. 'tbody',
  1860. 'tfoot',
  1861. 'caption',
  1862. 'tr',
  1863. 'td',
  1864. 'th',
  1865. 'h1',
  1866. 'h2',
  1867. 'h3',
  1868. 'h4',
  1869. 'h5',
  1870. 'h6',
  1871. 'blockquote',
  1872. 'pre',
  1873. 'address'
  1874. ];
  1875. function DomUniverse () {
  1876. var clone = function (element) {
  1877. return SugarElement.fromDom(element.dom.cloneNode(false));
  1878. };
  1879. var document = function (element) {
  1880. return documentOrOwner(element).dom;
  1881. };
  1882. var isBoundary = function (element) {
  1883. if (!isElement(element)) {
  1884. return false;
  1885. }
  1886. if (name(element) === 'body') {
  1887. return true;
  1888. }
  1889. return contains$2(TagBoundaries, name(element));
  1890. };
  1891. var isEmptyTag = function (element) {
  1892. if (!isElement(element)) {
  1893. return false;
  1894. }
  1895. return contains$2([
  1896. 'br',
  1897. 'img',
  1898. 'hr',
  1899. 'input'
  1900. ], name(element));
  1901. };
  1902. var isNonEditable = function (element) {
  1903. return isElement(element) && get$b(element, 'contenteditable') === 'false';
  1904. };
  1905. var comparePosition = function (element, other) {
  1906. return element.dom.compareDocumentPosition(other.dom);
  1907. };
  1908. var copyAttributesTo = function (source, destination) {
  1909. var as = clone$2(source);
  1910. setAll$1(destination, as);
  1911. };
  1912. var isSpecial = function (element) {
  1913. var tag = name(element);
  1914. return contains$2([
  1915. 'script',
  1916. 'noscript',
  1917. 'iframe',
  1918. 'noframes',
  1919. 'noembed',
  1920. 'title',
  1921. 'style',
  1922. 'textarea',
  1923. 'xmp'
  1924. ], tag);
  1925. };
  1926. var getLanguage = function (element) {
  1927. return isElement(element) ? getOpt(element, 'lang') : Optional.none();
  1928. };
  1929. return {
  1930. up: constant({
  1931. selector: ancestor$1,
  1932. closest: closest$1,
  1933. predicate: ancestor$2,
  1934. all: parents
  1935. }),
  1936. down: constant({
  1937. selector: descendants,
  1938. predicate: descendants$1
  1939. }),
  1940. styles: constant({
  1941. get: get$a,
  1942. getRaw: getRaw$2,
  1943. set: set$1,
  1944. remove: remove$6
  1945. }),
  1946. attrs: constant({
  1947. get: get$b,
  1948. set: set$2,
  1949. remove: remove$7,
  1950. copyTo: copyAttributesTo
  1951. }),
  1952. insert: constant({
  1953. before: before$4,
  1954. after: after$5,
  1955. afterAll: after$4,
  1956. append: append$1,
  1957. appendAll: append,
  1958. prepend: prepend,
  1959. wrap: wrap
  1960. }),
  1961. remove: constant({
  1962. unwrap: unwrap,
  1963. remove: remove$5
  1964. }),
  1965. create: constant({
  1966. nu: SugarElement.fromTag,
  1967. clone: clone,
  1968. text: SugarElement.fromText
  1969. }),
  1970. query: constant({
  1971. comparePosition: comparePosition,
  1972. prevSibling: prevSibling,
  1973. nextSibling: nextSibling
  1974. }),
  1975. property: constant({
  1976. children: children$3,
  1977. name: name,
  1978. parent: parent,
  1979. document: document,
  1980. isText: isText,
  1981. isComment: isComment,
  1982. isElement: isElement,
  1983. isSpecial: isSpecial,
  1984. getLanguage: getLanguage,
  1985. getText: get$9,
  1986. setText: set,
  1987. isBoundary: isBoundary,
  1988. isEmptyTag: isEmptyTag,
  1989. isNonEditable: isNonEditable
  1990. }),
  1991. eq: eq$1,
  1992. is: is$1
  1993. };
  1994. }
  1995. var all = function (universe, look, elements, f) {
  1996. var head = elements[0];
  1997. var tail = elements.slice(1);
  1998. return f(universe, look, head, tail);
  1999. };
  2000. var oneAll = function (universe, look, elements) {
  2001. return elements.length > 0 ? all(universe, look, elements, unsafeOne) : Optional.none();
  2002. };
  2003. var unsafeOne = function (universe, look, head, tail) {
  2004. var start = look(universe, head);
  2005. return foldr(tail, function (b, a) {
  2006. var current = look(universe, a);
  2007. return commonElement(universe, b, current);
  2008. }, start);
  2009. };
  2010. var commonElement = function (universe, start, end) {
  2011. return start.bind(function (s) {
  2012. return end.filter(curry(universe.eq, s));
  2013. });
  2014. };
  2015. var eq = function (universe, item) {
  2016. return curry(universe.eq, item);
  2017. };
  2018. var ancestors$2 = function (universe, start, end, isRoot) {
  2019. if (isRoot === void 0) {
  2020. isRoot = never;
  2021. }
  2022. var ps1 = [start].concat(universe.up().all(start));
  2023. var ps2 = [end].concat(universe.up().all(end));
  2024. var prune = function (path) {
  2025. var index = findIndex(path, isRoot);
  2026. return index.fold(function () {
  2027. return path;
  2028. }, function (ind) {
  2029. return path.slice(0, ind + 1);
  2030. });
  2031. };
  2032. var pruned1 = prune(ps1);
  2033. var pruned2 = prune(ps2);
  2034. var shared = find$1(pruned1, function (x) {
  2035. return exists(pruned2, eq(universe, x));
  2036. });
  2037. return {
  2038. firstpath: pruned1,
  2039. secondpath: pruned2,
  2040. shared: shared
  2041. };
  2042. };
  2043. var sharedOne$1 = oneAll;
  2044. var ancestors$1 = ancestors$2;
  2045. var universe$3 = DomUniverse();
  2046. var sharedOne = function (look, elements) {
  2047. return sharedOne$1(universe$3, function (_universe, element) {
  2048. return look(element);
  2049. }, elements);
  2050. };
  2051. var ancestors = function (start, finish, isRoot) {
  2052. return ancestors$1(universe$3, start, finish, isRoot);
  2053. };
  2054. var lookupTable = function (container) {
  2055. return ancestor$1(container, 'table');
  2056. };
  2057. var identify = function (start, finish, isRoot) {
  2058. var getIsRoot = function (rootTable) {
  2059. return function (element) {
  2060. return isRoot !== undefined && isRoot(element) || eq$1(element, rootTable);
  2061. };
  2062. };
  2063. if (eq$1(start, finish)) {
  2064. return Optional.some({
  2065. boxes: Optional.some([start]),
  2066. start: start,
  2067. finish: finish
  2068. });
  2069. } else {
  2070. return lookupTable(start).bind(function (startTable) {
  2071. return lookupTable(finish).bind(function (finishTable) {
  2072. if (eq$1(startTable, finishTable)) {
  2073. return Optional.some({
  2074. boxes: intercepts(startTable, start, finish),
  2075. start: start,
  2076. finish: finish
  2077. });
  2078. } else if (contains(startTable, finishTable)) {
  2079. var ancestorCells = ancestors$3(finish, 'td,th', getIsRoot(startTable));
  2080. var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
  2081. return Optional.some({
  2082. boxes: nestedIntercepts(startTable, start, startTable, finish, finishTable),
  2083. start: start,
  2084. finish: finishCell
  2085. });
  2086. } else if (contains(finishTable, startTable)) {
  2087. var ancestorCells = ancestors$3(start, 'td,th', getIsRoot(finishTable));
  2088. var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start;
  2089. return Optional.some({
  2090. boxes: nestedIntercepts(finishTable, start, startTable, finish, finishTable),
  2091. start: start,
  2092. finish: startCell
  2093. });
  2094. } else {
  2095. return ancestors(start, finish).shared.bind(function (lca) {
  2096. return closest$1(lca, 'table', isRoot).bind(function (lcaTable) {
  2097. var finishAncestorCells = ancestors$3(finish, 'td,th', getIsRoot(lcaTable));
  2098. var finishCell = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
  2099. var startAncestorCells = ancestors$3(start, 'td,th', getIsRoot(lcaTable));
  2100. var startCell = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start;
  2101. return Optional.some({
  2102. boxes: nestedIntercepts(lcaTable, start, startTable, finish, finishTable),
  2103. start: startCell,
  2104. finish: finishCell
  2105. });
  2106. });
  2107. });
  2108. }
  2109. });
  2110. });
  2111. }
  2112. };
  2113. var retrieve$1 = function (container, selector) {
  2114. var sels = descendants(container, selector);
  2115. return sels.length > 0 ? Optional.some(sels) : Optional.none();
  2116. };
  2117. var getLast = function (boxes, lastSelectedSelector) {
  2118. return find$1(boxes, function (box) {
  2119. return is$2(box, lastSelectedSelector);
  2120. });
  2121. };
  2122. var getEdges = function (container, firstSelectedSelector, lastSelectedSelector) {
  2123. return descendant(container, firstSelectedSelector).bind(function (first) {
  2124. return descendant(container, lastSelectedSelector).bind(function (last) {
  2125. return sharedOne(lookupTable, [
  2126. first,
  2127. last
  2128. ]).map(function (table) {
  2129. return {
  2130. first: first,
  2131. last: last,
  2132. table: table
  2133. };
  2134. });
  2135. });
  2136. });
  2137. };
  2138. var expandTo = function (finish, firstSelectedSelector) {
  2139. return ancestor$1(finish, 'table').bind(function (table) {
  2140. return descendant(table, firstSelectedSelector).bind(function (start) {
  2141. return identify(start, finish).bind(function (identified) {
  2142. return identified.boxes.map(function (boxes) {
  2143. return {
  2144. boxes: boxes,
  2145. start: identified.start,
  2146. finish: identified.finish
  2147. };
  2148. });
  2149. });
  2150. });
  2151. });
  2152. };
  2153. var shiftSelection = function (boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
  2154. return getLast(boxes, lastSelectedSelector).bind(function (last) {
  2155. return moveBy(last, deltaRow, deltaColumn).bind(function (finish) {
  2156. return expandTo(finish, firstSelectedSelector);
  2157. });
  2158. });
  2159. };
  2160. var retrieve = function (container, selector) {
  2161. return retrieve$1(container, selector);
  2162. };
  2163. var retrieveBox = function (container, firstSelectedSelector, lastSelectedSelector) {
  2164. return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function (edges) {
  2165. var isRoot = function (ancestor) {
  2166. return eq$1(container, ancestor);
  2167. };
  2168. var sectionSelector = 'thead,tfoot,tbody,table';
  2169. var firstAncestor = ancestor$1(edges.first, sectionSelector, isRoot);
  2170. var lastAncestor = ancestor$1(edges.last, sectionSelector, isRoot);
  2171. return firstAncestor.bind(function (fA) {
  2172. return lastAncestor.bind(function (lA) {
  2173. return eq$1(fA, lA) ? getBox(edges.table, edges.first, edges.last) : Optional.none();
  2174. });
  2175. });
  2176. });
  2177. };
  2178. var generate = function (cases) {
  2179. if (!isArray(cases)) {
  2180. throw new Error('cases must be an array');
  2181. }
  2182. if (cases.length === 0) {
  2183. throw new Error('there must be at least one case');
  2184. }
  2185. var constructors = [];
  2186. var adt = {};
  2187. each$2(cases, function (acase, count) {
  2188. var keys$1 = keys(acase);
  2189. if (keys$1.length !== 1) {
  2190. throw new Error('one and only one name per case');
  2191. }
  2192. var key = keys$1[0];
  2193. var value = acase[key];
  2194. if (adt[key] !== undefined) {
  2195. throw new Error('duplicate key detected:' + key);
  2196. } else if (key === 'cata') {
  2197. throw new Error('cannot have a case named cata (sorry)');
  2198. } else if (!isArray(value)) {
  2199. throw new Error('case arguments must be an array');
  2200. }
  2201. constructors.push(key);
  2202. adt[key] = function () {
  2203. var args = [];
  2204. for (var _i = 0; _i < arguments.length; _i++) {
  2205. args[_i] = arguments[_i];
  2206. }
  2207. var argLength = args.length;
  2208. if (argLength !== value.length) {
  2209. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2210. }
  2211. var match = function (branches) {
  2212. var branchKeys = keys(branches);
  2213. if (constructors.length !== branchKeys.length) {
  2214. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2215. }
  2216. var allReqd = forall(constructors, function (reqKey) {
  2217. return contains$2(branchKeys, reqKey);
  2218. });
  2219. if (!allReqd) {
  2220. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2221. }
  2222. return branches[key].apply(null, args);
  2223. };
  2224. return {
  2225. fold: function () {
  2226. var foldArgs = [];
  2227. for (var _i = 0; _i < arguments.length; _i++) {
  2228. foldArgs[_i] = arguments[_i];
  2229. }
  2230. if (foldArgs.length !== cases.length) {
  2231. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2232. }
  2233. var target = foldArgs[count];
  2234. return target.apply(null, args);
  2235. },
  2236. match: match,
  2237. log: function (label) {
  2238. console.log(label, {
  2239. constructors: constructors,
  2240. constructor: key,
  2241. params: args
  2242. });
  2243. }
  2244. };
  2245. };
  2246. });
  2247. return adt;
  2248. };
  2249. var Adt = { generate: generate };
  2250. var type = Adt.generate([
  2251. { none: [] },
  2252. { multiple: ['elements'] },
  2253. { single: ['element'] }
  2254. ]);
  2255. var cata$2 = function (subject, onNone, onMultiple, onSingle) {
  2256. return subject.fold(onNone, onMultiple, onSingle);
  2257. };
  2258. var none$1 = type.none;
  2259. var multiple = type.multiple;
  2260. var single = type.single;
  2261. var Selections = function (lazyRoot, getStart, selectedSelector) {
  2262. var get = function () {
  2263. return retrieve(lazyRoot(), selectedSelector).fold(function () {
  2264. return getStart().fold(none$1, single);
  2265. }, function (cells) {
  2266. return multiple(cells);
  2267. });
  2268. };
  2269. return { get: get };
  2270. };
  2271. var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  2272. var clone = function (original, isDeep) {
  2273. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2274. };
  2275. var shallow = function (original) {
  2276. return clone(original, false);
  2277. };
  2278. var deep = function (original) {
  2279. return clone(original, true);
  2280. };
  2281. var shallowAs = function (original, tag) {
  2282. var nu = SugarElement.fromTag(tag);
  2283. var attributes = clone$2(original);
  2284. setAll$1(nu, attributes);
  2285. return nu;
  2286. };
  2287. var copy$1 = function (original, tag) {
  2288. var nu = shallowAs(original, tag);
  2289. var cloneChildren = children$3(deep(original));
  2290. append(nu, cloneChildren);
  2291. return nu;
  2292. };
  2293. var mutate$1 = function (original, tag) {
  2294. var nu = shallowAs(original, tag);
  2295. before$4(original, nu);
  2296. var children = children$3(original);
  2297. append(nu, children);
  2298. remove$5(original);
  2299. return nu;
  2300. };
  2301. var Dimension = function (name, getOffset) {
  2302. var set = function (element, h) {
  2303. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  2304. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  2305. }
  2306. var dom = element.dom;
  2307. if (isSupported(dom)) {
  2308. dom.style[name] = h + 'px';
  2309. }
  2310. };
  2311. var get = function (element) {
  2312. var r = getOffset(element);
  2313. if (r <= 0 || r === null) {
  2314. var css = get$a(element, name);
  2315. return parseFloat(css) || 0;
  2316. }
  2317. return r;
  2318. };
  2319. var getOuter = get;
  2320. var aggregate = function (element, properties) {
  2321. return foldl(properties, function (acc, property) {
  2322. var val = get$a(element, property);
  2323. var value = val === undefined ? 0 : parseInt(val, 10);
  2324. return isNaN(value) ? acc : acc + value;
  2325. }, 0);
  2326. };
  2327. var max = function (element, value, properties) {
  2328. var cumulativeInclusions = aggregate(element, properties);
  2329. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  2330. return absoluteMax;
  2331. };
  2332. return {
  2333. set: set,
  2334. get: get,
  2335. getOuter: getOuter,
  2336. aggregate: aggregate,
  2337. max: max
  2338. };
  2339. };
  2340. var api$1 = Dimension('width', function (element) {
  2341. return element.dom.offsetWidth;
  2342. });
  2343. var get$8 = function (element) {
  2344. return api$1.get(element);
  2345. };
  2346. var getOuter$2 = function (element) {
  2347. return api$1.getOuter(element);
  2348. };
  2349. var columns = function (warehouse, isValidCell) {
  2350. if (isValidCell === void 0) {
  2351. isValidCell = always;
  2352. }
  2353. var grid = warehouse.grid;
  2354. var cols = range$1(grid.columns, identity);
  2355. var rowsArr = range$1(grid.rows, identity);
  2356. return map$1(cols, function (col) {
  2357. var getBlock = function () {
  2358. return bind$2(rowsArr, function (r) {
  2359. return Warehouse.getAt(warehouse, r, col).filter(function (detail) {
  2360. return detail.column === col;
  2361. }).toArray();
  2362. });
  2363. };
  2364. var isValid = function (detail) {
  2365. return detail.colspan === 1 && isValidCell(detail.element);
  2366. };
  2367. var getFallback = function () {
  2368. return Warehouse.getAt(warehouse, 0, col);
  2369. };
  2370. return decide(getBlock, isValid, getFallback);
  2371. });
  2372. };
  2373. var decide = function (getBlock, isValid, getFallback) {
  2374. var inBlock = getBlock();
  2375. var validInBlock = find$1(inBlock, isValid);
  2376. var detailOption = validInBlock.orThunk(function () {
  2377. return Optional.from(inBlock[0]).orThunk(getFallback);
  2378. });
  2379. return detailOption.map(function (detail) {
  2380. return detail.element;
  2381. });
  2382. };
  2383. var rows = function (warehouse) {
  2384. var grid = warehouse.grid;
  2385. var rowsArr = range$1(grid.rows, identity);
  2386. var cols = range$1(grid.columns, identity);
  2387. return map$1(rowsArr, function (row) {
  2388. var getBlock = function () {
  2389. return bind$2(cols, function (c) {
  2390. return Warehouse.getAt(warehouse, row, c).filter(function (detail) {
  2391. return detail.row === row;
  2392. }).fold(constant([]), function (detail) {
  2393. return [detail];
  2394. });
  2395. });
  2396. };
  2397. var isSingle = function (detail) {
  2398. return detail.rowspan === 1;
  2399. };
  2400. var getFallback = function () {
  2401. return Warehouse.getAt(warehouse, row, 0);
  2402. };
  2403. return decide(getBlock, isSingle, getFallback);
  2404. });
  2405. };
  2406. var deduce = function (xs, index) {
  2407. if (index < 0 || index >= xs.length - 1) {
  2408. return Optional.none();
  2409. }
  2410. var current = xs[index].fold(function () {
  2411. var rest = reverse(xs.slice(0, index));
  2412. return findMap(rest, function (a, i) {
  2413. return a.map(function (aa) {
  2414. return {
  2415. value: aa,
  2416. delta: i + 1
  2417. };
  2418. });
  2419. });
  2420. }, function (c) {
  2421. return Optional.some({
  2422. value: c,
  2423. delta: 0
  2424. });
  2425. });
  2426. var next = xs[index + 1].fold(function () {
  2427. var rest = xs.slice(index + 1);
  2428. return findMap(rest, function (a, i) {
  2429. return a.map(function (aa) {
  2430. return {
  2431. value: aa,
  2432. delta: i + 1
  2433. };
  2434. });
  2435. });
  2436. }, function (n) {
  2437. return Optional.some({
  2438. value: n,
  2439. delta: 1
  2440. });
  2441. });
  2442. return current.bind(function (c) {
  2443. return next.map(function (n) {
  2444. var extras = n.delta + c.delta;
  2445. return Math.abs(n.value - c.value) / extras;
  2446. });
  2447. });
  2448. };
  2449. var onDirection = function (isLtr, isRtl) {
  2450. return function (element) {
  2451. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  2452. };
  2453. };
  2454. var getDirection = function (element) {
  2455. return get$a(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  2456. };
  2457. var api = Dimension('height', function (element) {
  2458. var dom = element.dom;
  2459. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  2460. });
  2461. var get$7 = function (element) {
  2462. return api.get(element);
  2463. };
  2464. var getOuter$1 = function (element) {
  2465. return api.getOuter(element);
  2466. };
  2467. var r = function (left, top) {
  2468. var translate = function (x, y) {
  2469. return r(left + x, top + y);
  2470. };
  2471. return {
  2472. left: left,
  2473. top: top,
  2474. translate: translate
  2475. };
  2476. };
  2477. var SugarPosition = r;
  2478. var boxPosition = function (dom) {
  2479. var box = dom.getBoundingClientRect();
  2480. return SugarPosition(box.left, box.top);
  2481. };
  2482. var firstDefinedOrZero = function (a, b) {
  2483. if (a !== undefined) {
  2484. return a;
  2485. } else {
  2486. return b !== undefined ? b : 0;
  2487. }
  2488. };
  2489. var absolute = function (element) {
  2490. var doc = element.dom.ownerDocument;
  2491. var body = doc.body;
  2492. var win = doc.defaultView;
  2493. var html = doc.documentElement;
  2494. if (body === element.dom) {
  2495. return SugarPosition(body.offsetLeft, body.offsetTop);
  2496. }
  2497. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  2498. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  2499. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  2500. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  2501. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  2502. };
  2503. var viewport = function (element) {
  2504. var dom = element.dom;
  2505. var doc = dom.ownerDocument;
  2506. var body = doc.body;
  2507. if (body === dom) {
  2508. return SugarPosition(body.offsetLeft, body.offsetTop);
  2509. }
  2510. if (!inBody(element)) {
  2511. return SugarPosition(0, 0);
  2512. }
  2513. return boxPosition(dom);
  2514. };
  2515. var rowInfo = function (row, y) {
  2516. return {
  2517. row: row,
  2518. y: y
  2519. };
  2520. };
  2521. var colInfo = function (col, x) {
  2522. return {
  2523. col: col,
  2524. x: x
  2525. };
  2526. };
  2527. var rtlEdge = function (cell) {
  2528. var pos = absolute(cell);
  2529. return pos.left + getOuter$2(cell);
  2530. };
  2531. var ltrEdge = function (cell) {
  2532. return absolute(cell).left;
  2533. };
  2534. var getLeftEdge = function (index, cell) {
  2535. return colInfo(index, ltrEdge(cell));
  2536. };
  2537. var getRightEdge = function (index, cell) {
  2538. return colInfo(index, rtlEdge(cell));
  2539. };
  2540. var getTop$1 = function (cell) {
  2541. return absolute(cell).top;
  2542. };
  2543. var getTopEdge = function (index, cell) {
  2544. return rowInfo(index, getTop$1(cell));
  2545. };
  2546. var getBottomEdge = function (index, cell) {
  2547. return rowInfo(index, getTop$1(cell) + getOuter$1(cell));
  2548. };
  2549. var findPositions = function (getInnerEdge, getOuterEdge, array) {
  2550. if (array.length === 0) {
  2551. return [];
  2552. }
  2553. var lines = map$1(array.slice(1), function (cellOption, index) {
  2554. return cellOption.map(function (cell) {
  2555. return getInnerEdge(index, cell);
  2556. });
  2557. });
  2558. var lastLine = array[array.length - 1].map(function (cell) {
  2559. return getOuterEdge(array.length - 1, cell);
  2560. });
  2561. return lines.concat([lastLine]);
  2562. };
  2563. var negate = function (step) {
  2564. return -step;
  2565. };
  2566. var height = {
  2567. delta: identity,
  2568. positions: function (optElements) {
  2569. return findPositions(getTopEdge, getBottomEdge, optElements);
  2570. },
  2571. edge: getTop$1
  2572. };
  2573. var ltr$1 = {
  2574. delta: identity,
  2575. edge: ltrEdge,
  2576. positions: function (optElements) {
  2577. return findPositions(getLeftEdge, getRightEdge, optElements);
  2578. }
  2579. };
  2580. var rtl$1 = {
  2581. delta: negate,
  2582. edge: rtlEdge,
  2583. positions: function (optElements) {
  2584. return findPositions(getRightEdge, getLeftEdge, optElements);
  2585. }
  2586. };
  2587. var detect$2 = onDirection(ltr$1, rtl$1);
  2588. var width = {
  2589. delta: function (amount, table) {
  2590. return detect$2(table).delta(amount, table);
  2591. },
  2592. positions: function (cols, table) {
  2593. return detect$2(table).positions(cols, table);
  2594. },
  2595. edge: function (cell) {
  2596. return detect$2(cell).edge(cell);
  2597. }
  2598. };
  2599. var units = {
  2600. unsupportedLength: [
  2601. 'em',
  2602. 'ex',
  2603. 'cap',
  2604. 'ch',
  2605. 'ic',
  2606. 'rem',
  2607. 'lh',
  2608. 'rlh',
  2609. 'vw',
  2610. 'vh',
  2611. 'vi',
  2612. 'vb',
  2613. 'vmin',
  2614. 'vmax',
  2615. 'cm',
  2616. 'mm',
  2617. 'Q',
  2618. 'in',
  2619. 'pc',
  2620. 'pt',
  2621. 'px'
  2622. ],
  2623. fixed: [
  2624. 'px',
  2625. 'pt'
  2626. ],
  2627. relative: ['%'],
  2628. empty: ['']
  2629. };
  2630. var pattern = function () {
  2631. var decimalDigits = '[0-9]+';
  2632. var signedInteger = '[+-]?' + decimalDigits;
  2633. var exponentPart = '[eE]' + signedInteger;
  2634. var dot = '\\.';
  2635. var opt = function (input) {
  2636. return '(?:' + input + ')?';
  2637. };
  2638. var unsignedDecimalLiteral = [
  2639. 'Infinity',
  2640. decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  2641. dot + decimalDigits + opt(exponentPart),
  2642. decimalDigits + opt(exponentPart)
  2643. ].join('|');
  2644. var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
  2645. return new RegExp('^(' + float + ')(.*)$');
  2646. }();
  2647. var isUnit = function (unit, accepted) {
  2648. return exists(accepted, function (acc) {
  2649. return exists(units[acc], function (check) {
  2650. return unit === check;
  2651. });
  2652. });
  2653. };
  2654. var parse = function (input, accepted) {
  2655. var match = Optional.from(pattern.exec(input));
  2656. return match.bind(function (array) {
  2657. var value = Number(array[1]);
  2658. var unitRaw = array[2];
  2659. if (isUnit(unitRaw, accepted)) {
  2660. return Optional.some({
  2661. value: value,
  2662. unit: unitRaw
  2663. });
  2664. } else {
  2665. return Optional.none();
  2666. }
  2667. });
  2668. };
  2669. var needManualCalc = function () {
  2670. var browser = detect$3().browser;
  2671. return browser.isIE() || browser.isEdge();
  2672. };
  2673. var toNumber = function (px, fallback) {
  2674. var num = parseFloat(px);
  2675. return isNaN(num) ? fallback : num;
  2676. };
  2677. var getProp = function (elm, name, fallback) {
  2678. return toNumber(get$a(elm, name), fallback);
  2679. };
  2680. var getCalculatedHeight = function (cell) {
  2681. var height = cell.dom.getBoundingClientRect().height;
  2682. var boxSizing = get$a(cell, 'box-sizing');
  2683. if (boxSizing === 'border-box') {
  2684. return height;
  2685. } else {
  2686. var paddingTop = getProp(cell, 'padding-top', 0);
  2687. var paddingBottom = getProp(cell, 'padding-bottom', 0);
  2688. var borderTop = getProp(cell, 'border-top-width', 0);
  2689. var borderBottom = getProp(cell, 'border-bottom-width', 0);
  2690. var borders = borderTop + borderBottom;
  2691. return height - paddingTop - paddingBottom - borders;
  2692. }
  2693. };
  2694. var getCalculatedWidth = function (cell) {
  2695. var width = cell.dom.getBoundingClientRect().width;
  2696. var boxSizing = get$a(cell, 'box-sizing');
  2697. if (boxSizing === 'border-box') {
  2698. return width;
  2699. } else {
  2700. var paddingLeft = getProp(cell, 'padding-left', 0);
  2701. var paddingRight = getProp(cell, 'padding-right', 0);
  2702. var borderLeft = getProp(cell, 'border-left-width', 0);
  2703. var borderRight = getProp(cell, 'border-right-width', 0);
  2704. var borders = borderLeft + borderRight;
  2705. return width - paddingLeft - paddingRight - borders;
  2706. }
  2707. };
  2708. var getHeight$1 = function (cell) {
  2709. return needManualCalc() ? getCalculatedHeight(cell) : getProp(cell, 'height', get$7(cell));
  2710. };
  2711. var getWidth = function (cell) {
  2712. return needManualCalc() ? getCalculatedWidth(cell) : getProp(cell, 'width', get$8(cell));
  2713. };
  2714. var rPercentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
  2715. var rPixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
  2716. var getPercentSize = function (elm, getter) {
  2717. var relativeParent = offsetParent(elm).getOr(getBody$1(owner(elm)));
  2718. return getter(elm) / getter(relativeParent) * 100;
  2719. };
  2720. var setPixelWidth = function (cell, amount) {
  2721. set$1(cell, 'width', amount + 'px');
  2722. };
  2723. var setPercentageWidth = function (cell, amount) {
  2724. set$1(cell, 'width', amount + '%');
  2725. };
  2726. var setHeight = function (cell, amount) {
  2727. set$1(cell, 'height', amount + 'px');
  2728. };
  2729. var getHeightValue = function (cell) {
  2730. return getRaw$2(cell, 'height').getOrThunk(function () {
  2731. return getHeight$1(cell) + 'px';
  2732. });
  2733. };
  2734. var convert = function (cell, number, getter, setter) {
  2735. var newSize = table(cell).map(function (table) {
  2736. var total = getter(table);
  2737. return Math.floor(number / 100 * total);
  2738. }).getOr(number);
  2739. setter(cell, newSize);
  2740. return newSize;
  2741. };
  2742. var normalizePixelSize = function (value, cell, getter, setter) {
  2743. var number = parseInt(value, 10);
  2744. return endsWith(value, '%') && name(cell) !== 'table' ? convert(cell, number, getter, setter) : number;
  2745. };
  2746. var getTotalHeight = function (cell) {
  2747. var value = getHeightValue(cell);
  2748. if (!value) {
  2749. return get$7(cell);
  2750. }
  2751. return normalizePixelSize(value, cell, get$7, setHeight);
  2752. };
  2753. var get$6 = function (cell, type, f) {
  2754. var v = f(cell);
  2755. var span = getSpan(cell, type);
  2756. return v / span;
  2757. };
  2758. var getRawWidth$1 = function (element) {
  2759. var cssWidth = getRaw$2(element, 'width');
  2760. return cssWidth.fold(function () {
  2761. return Optional.from(get$b(element, 'width'));
  2762. }, function (width) {
  2763. return Optional.some(width);
  2764. });
  2765. };
  2766. var normalizePercentageWidth = function (cellWidth, tableSize) {
  2767. return cellWidth / tableSize.pixelWidth() * 100;
  2768. };
  2769. var choosePercentageSize = function (element, width, tableSize) {
  2770. var percentMatch = rPercentageBasedSizeRegex.exec(width);
  2771. if (percentMatch !== null) {
  2772. return parseFloat(percentMatch[1]);
  2773. } else {
  2774. var intWidth = getWidth(element);
  2775. return normalizePercentageWidth(intWidth, tableSize);
  2776. }
  2777. };
  2778. var getPercentageWidth = function (cell, tableSize) {
  2779. var width = getRawWidth$1(cell);
  2780. return width.fold(function () {
  2781. var intWidth = get$8(cell);
  2782. return normalizePercentageWidth(intWidth, tableSize);
  2783. }, function (w) {
  2784. return choosePercentageSize(cell, w, tableSize);
  2785. });
  2786. };
  2787. var normalizePixelWidth = function (cellWidth, tableSize) {
  2788. return cellWidth / 100 * tableSize.pixelWidth();
  2789. };
  2790. var choosePixelSize = function (element, width, tableSize) {
  2791. var pixelMatch = rPixelBasedSizeRegex.exec(width);
  2792. if (pixelMatch !== null) {
  2793. return parseInt(pixelMatch[1], 10);
  2794. }
  2795. var percentMatch = rPercentageBasedSizeRegex.exec(width);
  2796. if (percentMatch !== null) {
  2797. var floatWidth = parseFloat(percentMatch[1]);
  2798. return normalizePixelWidth(floatWidth, tableSize);
  2799. }
  2800. return getWidth(element);
  2801. };
  2802. var getPixelWidth$1 = function (cell, tableSize) {
  2803. var width = getRawWidth$1(cell);
  2804. return width.fold(function () {
  2805. return getWidth(cell);
  2806. }, function (w) {
  2807. return choosePixelSize(cell, w, tableSize);
  2808. });
  2809. };
  2810. var getHeight = function (cell) {
  2811. return get$6(cell, 'rowspan', getTotalHeight);
  2812. };
  2813. var getGenericWidth = function (cell) {
  2814. var width = getRawWidth$1(cell);
  2815. return width.bind(function (w) {
  2816. return parse(w, [
  2817. 'fixed',
  2818. 'relative',
  2819. 'empty'
  2820. ]);
  2821. });
  2822. };
  2823. var setGenericWidth = function (cell, amount, unit) {
  2824. set$1(cell, 'width', amount + unit);
  2825. };
  2826. var getPixelTableWidth = function (table) {
  2827. return get$8(table) + 'px';
  2828. };
  2829. var getPercentTableWidth$1 = function (table) {
  2830. return getPercentSize(table, get$8) + '%';
  2831. };
  2832. var isPercentSizing$1 = function (table) {
  2833. return getRawWidth$1(table).exists(function (size) {
  2834. return rPercentageBasedSizeRegex.test(size);
  2835. });
  2836. };
  2837. var isPixelSizing$1 = function (table) {
  2838. return getRawWidth$1(table).exists(function (size) {
  2839. return rPixelBasedSizeRegex.test(size);
  2840. });
  2841. };
  2842. var isNoneSizing$1 = function (table) {
  2843. return getRawWidth$1(table).isNone();
  2844. };
  2845. var percentageBasedSizeRegex = constant(rPercentageBasedSizeRegex);
  2846. var pixelBasedSizeRegex = constant(rPixelBasedSizeRegex);
  2847. var isCol$1 = isTag('col');
  2848. var getRaw$1 = function (cell, property, getter) {
  2849. return getRaw$2(cell, property).getOrThunk(function () {
  2850. return getter(cell) + 'px';
  2851. });
  2852. };
  2853. var getRawW = function (cell, tableSize) {
  2854. var fallback = function (e) {
  2855. return isCol$1(e) ? get$8(e) : getPixelWidth$1(e, tableSize);
  2856. };
  2857. return getRaw$1(cell, 'width', fallback);
  2858. };
  2859. var getRawH = function (cell) {
  2860. return getRaw$1(cell, 'height', getHeight);
  2861. };
  2862. var justCols = function (warehouse) {
  2863. return map$1(Warehouse.justColumns(warehouse), function (column) {
  2864. return Optional.from(column.element);
  2865. });
  2866. };
  2867. var hasRawStyle = function (cell, prop) {
  2868. return getRaw$2(cell, prop).isSome();
  2869. };
  2870. var isValidColumn = function (cell) {
  2871. return !isCol$1(cell) || hasRawStyle(cell, 'width');
  2872. };
  2873. var getDimension = function (cellOpt, index, backups, filter, getter, fallback) {
  2874. return cellOpt.filter(filter).fold(function () {
  2875. return fallback(deduce(backups, index));
  2876. }, function (cell) {
  2877. return getter(cell);
  2878. });
  2879. };
  2880. var getWidthFrom = function (warehouse, table, getWidth, fallback, tableSize) {
  2881. var columnCells = columns(warehouse, function (cell) {
  2882. return hasRawStyle(cell, 'width');
  2883. });
  2884. var columns$1 = Warehouse.hasColumns(warehouse) ? justCols(warehouse) : columnCells;
  2885. var backups = [Optional.some(width.edge(table))].concat(map$1(width.positions(columnCells, table), function (pos) {
  2886. return pos.map(function (p) {
  2887. return p.x;
  2888. });
  2889. }));
  2890. var colFilter = not(hasColspan);
  2891. return map$1(columns$1, function (cellOption, c) {
  2892. return getDimension(cellOption, c, backups, colFilter, function (column) {
  2893. if (isValidColumn(column)) {
  2894. return getWidth(column, tableSize);
  2895. } else {
  2896. var cell = bindFrom(columnCells[c], identity);
  2897. return getDimension(cell, c, backups, colFilter, function (cell) {
  2898. return fallback(Optional.some(get$8(cell)));
  2899. }, fallback);
  2900. }
  2901. }, fallback);
  2902. });
  2903. };
  2904. var getDeduced = function (deduced) {
  2905. return deduced.map(function (d) {
  2906. return d + 'px';
  2907. }).getOr('');
  2908. };
  2909. var getRawWidths = function (warehouse, table, tableSize) {
  2910. return getWidthFrom(warehouse, table, getRawW, getDeduced, tableSize);
  2911. };
  2912. var getPercentageWidths = function (warehouse, table, tableSize) {
  2913. return getWidthFrom(warehouse, table, getPercentageWidth, function (deduced) {
  2914. return deduced.fold(function () {
  2915. return tableSize.minCellWidth();
  2916. }, function (cellWidth) {
  2917. return cellWidth / tableSize.pixelWidth() * 100;
  2918. });
  2919. }, tableSize);
  2920. };
  2921. var getPixelWidths = function (warehouse, table, tableSize) {
  2922. return getWidthFrom(warehouse, table, getPixelWidth$1, function (deduced) {
  2923. return deduced.getOrThunk(tableSize.minCellWidth);
  2924. }, tableSize);
  2925. };
  2926. var getHeightFrom = function (warehouse, table, direction, getHeight, fallback) {
  2927. var rows$1 = rows(warehouse);
  2928. var backups = [Optional.some(direction.edge(table))].concat(map$1(direction.positions(rows$1, table), function (pos) {
  2929. return pos.map(function (p) {
  2930. return p.y;
  2931. });
  2932. }));
  2933. return map$1(rows$1, function (cellOption, c) {
  2934. return getDimension(cellOption, c, backups, not(hasRowspan), getHeight, fallback);
  2935. });
  2936. };
  2937. var getPixelHeights = function (warehouse, table, direction) {
  2938. return getHeightFrom(warehouse, table, direction, getHeight, function (deduced) {
  2939. return deduced.getOrThunk(minHeight);
  2940. });
  2941. };
  2942. var getRawHeights = function (warehouse, table, direction) {
  2943. return getHeightFrom(warehouse, table, direction, getRawH, getDeduced);
  2944. };
  2945. var Cell = function (initial) {
  2946. var value = initial;
  2947. var get = function () {
  2948. return value;
  2949. };
  2950. var set = function (v) {
  2951. value = v;
  2952. };
  2953. return {
  2954. get: get,
  2955. set: set
  2956. };
  2957. };
  2958. var noneSize = function (table) {
  2959. var getWidth = function () {
  2960. return get$8(table);
  2961. };
  2962. var zero = constant(0);
  2963. var getWidths = function (warehouse, tableSize) {
  2964. return getPixelWidths(warehouse, table, tableSize);
  2965. };
  2966. return {
  2967. width: getWidth,
  2968. pixelWidth: getWidth,
  2969. getWidths: getWidths,
  2970. getCellDelta: zero,
  2971. singleColumnWidth: constant([0]),
  2972. minCellWidth: zero,
  2973. setElementWidth: noop,
  2974. adjustTableWidth: noop,
  2975. isRelative: true,
  2976. label: 'none'
  2977. };
  2978. };
  2979. var percentageSize = function (initialWidth, table) {
  2980. var floatWidth = Cell(parseFloat(initialWidth));
  2981. var pixelWidth = Cell(get$8(table));
  2982. var getCellDelta = function (delta) {
  2983. return delta / pixelWidth.get() * 100;
  2984. };
  2985. var singleColumnWidth = function (w, _delta) {
  2986. return [100 - w];
  2987. };
  2988. var minCellWidth = function () {
  2989. return minWidth() / pixelWidth.get() * 100;
  2990. };
  2991. var adjustTableWidth = function (delta) {
  2992. var currentWidth = floatWidth.get();
  2993. var change = delta / 100 * currentWidth;
  2994. var newWidth = currentWidth + change;
  2995. setPercentageWidth(table, newWidth);
  2996. floatWidth.set(newWidth);
  2997. pixelWidth.set(get$8(table));
  2998. };
  2999. var getWidths = function (warehouse, tableSize) {
  3000. return getPercentageWidths(warehouse, table, tableSize);
  3001. };
  3002. return {
  3003. width: floatWidth.get,
  3004. pixelWidth: pixelWidth.get,
  3005. getWidths: getWidths,
  3006. getCellDelta: getCellDelta,
  3007. singleColumnWidth: singleColumnWidth,
  3008. minCellWidth: minCellWidth,
  3009. setElementWidth: setPercentageWidth,
  3010. adjustTableWidth: adjustTableWidth,
  3011. isRelative: true,
  3012. label: 'percent'
  3013. };
  3014. };
  3015. var pixelSize = function (initialWidth, table) {
  3016. var width = Cell(initialWidth);
  3017. var getWidth = width.get;
  3018. var getCellDelta = identity;
  3019. var singleColumnWidth = function (w, delta) {
  3020. var newNext = Math.max(minWidth(), w + delta);
  3021. return [newNext - w];
  3022. };
  3023. var adjustTableWidth = function (delta) {
  3024. var newWidth = getWidth() + delta;
  3025. setPixelWidth(table, newWidth);
  3026. width.set(newWidth);
  3027. };
  3028. var getWidths = function (warehouse, tableSize) {
  3029. return getPixelWidths(warehouse, table, tableSize);
  3030. };
  3031. return {
  3032. width: getWidth,
  3033. pixelWidth: getWidth,
  3034. getWidths: getWidths,
  3035. getCellDelta: getCellDelta,
  3036. singleColumnWidth: singleColumnWidth,
  3037. minCellWidth: minWidth,
  3038. setElementWidth: setPixelWidth,
  3039. adjustTableWidth: adjustTableWidth,
  3040. isRelative: false,
  3041. label: 'pixel'
  3042. };
  3043. };
  3044. var chooseSize = function (element, width) {
  3045. var percentMatch = percentageBasedSizeRegex().exec(width);
  3046. if (percentMatch !== null) {
  3047. return percentageSize(percentMatch[1], element);
  3048. }
  3049. var pixelMatch = pixelBasedSizeRegex().exec(width);
  3050. if (pixelMatch !== null) {
  3051. var intWidth = parseInt(pixelMatch[1], 10);
  3052. return pixelSize(intWidth, element);
  3053. }
  3054. var fallbackWidth = get$8(element);
  3055. return pixelSize(fallbackWidth, element);
  3056. };
  3057. var getTableSize = function (table) {
  3058. var width = getRawWidth$1(table);
  3059. return width.fold(function () {
  3060. return noneSize(table);
  3061. }, function (w) {
  3062. return chooseSize(table, w);
  3063. });
  3064. };
  3065. var TableSize = {
  3066. getTableSize: getTableSize,
  3067. pixelSize: pixelSize,
  3068. percentageSize: percentageSize,
  3069. noneSize: noneSize
  3070. };
  3071. var statsStruct = function (minRow, minCol, maxRow, maxCol, allCells, selectedCells) {
  3072. return {
  3073. minRow: minRow,
  3074. minCol: minCol,
  3075. maxRow: maxRow,
  3076. maxCol: maxCol,
  3077. allCells: allCells,
  3078. selectedCells: selectedCells
  3079. };
  3080. };
  3081. var findSelectedStats = function (house, isSelected) {
  3082. var totalColumns = house.grid.columns;
  3083. var totalRows = house.grid.rows;
  3084. var minRow = totalRows;
  3085. var minCol = totalColumns;
  3086. var maxRow = 0;
  3087. var maxCol = 0;
  3088. var allCells = [];
  3089. var selectedCells = [];
  3090. each$1(house.access, function (detail) {
  3091. allCells.push(detail);
  3092. if (isSelected(detail)) {
  3093. selectedCells.push(detail);
  3094. var startRow = detail.row;
  3095. var endRow = startRow + detail.rowspan - 1;
  3096. var startCol = detail.column;
  3097. var endCol = startCol + detail.colspan - 1;
  3098. if (startRow < minRow) {
  3099. minRow = startRow;
  3100. } else if (endRow > maxRow) {
  3101. maxRow = endRow;
  3102. }
  3103. if (startCol < minCol) {
  3104. minCol = startCol;
  3105. } else if (endCol > maxCol) {
  3106. maxCol = endCol;
  3107. }
  3108. }
  3109. });
  3110. return statsStruct(minRow, minCol, maxRow, maxCol, allCells, selectedCells);
  3111. };
  3112. var makeCell = function (list, seenSelected, rowIndex) {
  3113. var row = list[rowIndex].element;
  3114. var td = SugarElement.fromTag('td');
  3115. append$1(td, SugarElement.fromTag('br'));
  3116. var f = seenSelected ? append$1 : prepend;
  3117. f(row, td);
  3118. };
  3119. var fillInGaps = function (list, house, stats, isSelected) {
  3120. var totalColumns = house.grid.columns;
  3121. var totalRows = house.grid.rows;
  3122. for (var i = 0; i < totalRows; i++) {
  3123. var seenSelected = false;
  3124. for (var j = 0; j < totalColumns; j++) {
  3125. if (!(i < stats.minRow || i > stats.maxRow || j < stats.minCol || j > stats.maxCol)) {
  3126. var needCell = Warehouse.getAt(house, i, j).filter(isSelected).isNone();
  3127. if (needCell) {
  3128. makeCell(list, seenSelected, i);
  3129. } else {
  3130. seenSelected = true;
  3131. }
  3132. }
  3133. }
  3134. }
  3135. };
  3136. var clean = function (replica, stats, house, widthDelta) {
  3137. each$1(house.columns, function (col) {
  3138. if (col.column < stats.minCol || col.column > stats.maxCol) {
  3139. remove$5(col.element);
  3140. }
  3141. });
  3142. var emptyRows = filter$2(firstLayer(replica, 'tr'), function (row) {
  3143. return row.dom.childElementCount === 0;
  3144. });
  3145. each$2(emptyRows, remove$5);
  3146. if (stats.minCol === stats.maxCol || stats.minRow === stats.maxRow) {
  3147. each$2(firstLayer(replica, 'th,td'), function (cell) {
  3148. remove$7(cell, 'rowspan');
  3149. remove$7(cell, 'colspan');
  3150. });
  3151. }
  3152. remove$7(replica, LOCKED_COL_ATTR);
  3153. remove$7(replica, 'data-snooker-col-series');
  3154. var tableSize = TableSize.getTableSize(replica);
  3155. tableSize.adjustTableWidth(widthDelta);
  3156. };
  3157. var getTableWidthDelta = function (table, warehouse, tableSize, stats) {
  3158. if (stats.minCol === 0 && warehouse.grid.columns === stats.maxCol + 1) {
  3159. return 0;
  3160. }
  3161. var colWidths = getPixelWidths(warehouse, table, tableSize);
  3162. var allColsWidth = foldl(colWidths, function (acc, width) {
  3163. return acc + width;
  3164. }, 0);
  3165. var selectedColsWidth = foldl(colWidths.slice(stats.minCol, stats.maxCol + 1), function (acc, width) {
  3166. return acc + width;
  3167. }, 0);
  3168. var newWidth = selectedColsWidth / allColsWidth * tableSize.pixelWidth();
  3169. var delta = newWidth - tableSize.pixelWidth();
  3170. return tableSize.getCellDelta(delta);
  3171. };
  3172. var extract$1 = function (table, selectedSelector) {
  3173. var isSelected = function (detail) {
  3174. return is$2(detail.element, selectedSelector);
  3175. };
  3176. var replica = deep(table);
  3177. var list = fromTable$1(replica);
  3178. var tableSize = TableSize.getTableSize(table);
  3179. var replicaHouse = Warehouse.generate(list);
  3180. var replicaStats = findSelectedStats(replicaHouse, isSelected);
  3181. var selector = 'th:not(' + selectedSelector + ')' + ',td:not(' + selectedSelector + ')';
  3182. var unselectedCells = filterFirstLayer(replica, 'th,td', function (cell) {
  3183. return is$2(cell, selector);
  3184. });
  3185. each$2(unselectedCells, remove$5);
  3186. fillInGaps(list, replicaHouse, replicaStats, isSelected);
  3187. var house = Warehouse.fromTable(table);
  3188. var widthDelta = getTableWidthDelta(table, house, tableSize, replicaStats);
  3189. clean(replica, replicaStats, replicaHouse, widthDelta);
  3190. return replica;
  3191. };
  3192. var nbsp = '\xA0';
  3193. var getEnd = function (element) {
  3194. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  3195. return children$3(element).length;
  3196. }, function (v) {
  3197. return v.length;
  3198. });
  3199. };
  3200. var isTextNodeWithCursorPosition = function (el) {
  3201. return getOption(el).filter(function (text) {
  3202. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  3203. }).isSome();
  3204. };
  3205. var elementsWithCursorPosition = [
  3206. 'img',
  3207. 'br'
  3208. ];
  3209. var isCursorPosition = function (elem) {
  3210. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  3211. return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem));
  3212. };
  3213. var first = function (element) {
  3214. return descendant$1(element, isCursorPosition);
  3215. };
  3216. var last$1 = function (element) {
  3217. return descendantRtl(element, isCursorPosition);
  3218. };
  3219. var descendantRtl = function (scope, predicate) {
  3220. var descend = function (element) {
  3221. var children = children$3(element);
  3222. for (var i = children.length - 1; i >= 0; i--) {
  3223. var child = children[i];
  3224. if (predicate(child)) {
  3225. return Optional.some(child);
  3226. }
  3227. var res = descend(child);
  3228. if (res.isSome()) {
  3229. return res;
  3230. }
  3231. }
  3232. return Optional.none();
  3233. };
  3234. return descend(scope);
  3235. };
  3236. var transferableAttributes = {
  3237. scope: [
  3238. 'row',
  3239. 'col'
  3240. ]
  3241. };
  3242. var createCell = function (doc) {
  3243. return function () {
  3244. var td = SugarElement.fromTag('td', doc.dom);
  3245. append$1(td, SugarElement.fromTag('br', doc.dom));
  3246. return td;
  3247. };
  3248. };
  3249. var createCol = function (doc) {
  3250. return function () {
  3251. return SugarElement.fromTag('col', doc.dom);
  3252. };
  3253. };
  3254. var createColgroup = function (doc) {
  3255. return function () {
  3256. return SugarElement.fromTag('colgroup', doc.dom);
  3257. };
  3258. };
  3259. var createRow$1 = function (doc) {
  3260. return function () {
  3261. return SugarElement.fromTag('tr', doc.dom);
  3262. };
  3263. };
  3264. var replace$1 = function (cell, tag, attrs) {
  3265. var replica = copy$1(cell, tag);
  3266. each$1(attrs, function (v, k) {
  3267. if (v === null) {
  3268. remove$7(replica, k);
  3269. } else {
  3270. set$2(replica, k, v);
  3271. }
  3272. });
  3273. return replica;
  3274. };
  3275. var pasteReplace = function (cell) {
  3276. return cell;
  3277. };
  3278. var cloneFormats = function (oldCell, newCell, formats) {
  3279. var first$1 = first(oldCell);
  3280. return first$1.map(function (firstText) {
  3281. var formatSelector = formats.join(',');
  3282. var parents = ancestors$3(firstText, formatSelector, function (element) {
  3283. return eq$1(element, oldCell);
  3284. });
  3285. return foldr(parents, function (last, parent) {
  3286. var clonedFormat = shallow(parent);
  3287. remove$7(clonedFormat, 'contenteditable');
  3288. append$1(last, clonedFormat);
  3289. return clonedFormat;
  3290. }, newCell);
  3291. }).getOr(newCell);
  3292. };
  3293. var cloneAppropriateAttributes = function (original, clone) {
  3294. each$1(transferableAttributes, function (validAttributes, attributeName) {
  3295. return getOpt(original, attributeName).filter(function (attribute) {
  3296. return contains$2(validAttributes, attribute);
  3297. }).each(function (attribute) {
  3298. return set$2(clone, attributeName, attribute);
  3299. });
  3300. });
  3301. };
  3302. var cellOperations = function (mutate, doc, formatsToClone) {
  3303. var cloneCss = function (prev, clone) {
  3304. copy$2(prev.element, clone);
  3305. remove$6(clone, 'height');
  3306. if (prev.colspan !== 1) {
  3307. remove$6(clone, 'width');
  3308. }
  3309. };
  3310. var newCell = function (prev) {
  3311. var td = SugarElement.fromTag(name(prev.element), doc.dom);
  3312. var formats = formatsToClone.getOr([
  3313. 'strong',
  3314. 'em',
  3315. 'b',
  3316. 'i',
  3317. 'span',
  3318. 'font',
  3319. 'h1',
  3320. 'h2',
  3321. 'h3',
  3322. 'h4',
  3323. 'h5',
  3324. 'h6',
  3325. 'p',
  3326. 'div'
  3327. ]);
  3328. var lastNode = formats.length > 0 ? cloneFormats(prev.element, td, formats) : td;
  3329. append$1(lastNode, SugarElement.fromTag('br'));
  3330. cloneCss(prev, td);
  3331. cloneAppropriateAttributes(prev.element, td);
  3332. mutate(prev.element, td);
  3333. return td;
  3334. };
  3335. var newCol = function (prev) {
  3336. var col = SugarElement.fromTag(name(prev.element), doc.dom);
  3337. cloneCss(prev, col);
  3338. mutate(prev.element, col);
  3339. return col;
  3340. };
  3341. return {
  3342. col: newCol,
  3343. colgroup: createColgroup(doc),
  3344. row: createRow$1(doc),
  3345. cell: newCell,
  3346. replace: replace$1,
  3347. gap: createCell(doc)
  3348. };
  3349. };
  3350. var paste$1 = function (doc) {
  3351. return {
  3352. col: createCol(doc),
  3353. colgroup: createColgroup(doc),
  3354. row: createRow$1(doc),
  3355. cell: createCell(doc),
  3356. replace: pasteReplace,
  3357. gap: createCell(doc)
  3358. };
  3359. };
  3360. var fromHtml = function (html, scope) {
  3361. var doc = scope || document;
  3362. var div = doc.createElement('div');
  3363. div.innerHTML = html;
  3364. return children$3(SugarElement.fromDom(div));
  3365. };
  3366. var fromDom = function (nodes) {
  3367. return map$1(nodes, SugarElement.fromDom);
  3368. };
  3369. var getNodeName = function (elm) {
  3370. return elm.nodeName.toLowerCase();
  3371. };
  3372. var getBody = function (editor) {
  3373. return SugarElement.fromDom(editor.getBody());
  3374. };
  3375. var getPixelWidth = function (elm) {
  3376. return elm.getBoundingClientRect().width;
  3377. };
  3378. var getPixelHeight = function (elm) {
  3379. return elm.getBoundingClientRect().height;
  3380. };
  3381. var getIsRoot = function (editor) {
  3382. return function (element) {
  3383. return eq$1(element, getBody(editor));
  3384. };
  3385. };
  3386. var removePxSuffix = function (size) {
  3387. return size ? size.replace(/px$/, '') : '';
  3388. };
  3389. var addPxSuffix = function (size) {
  3390. return /^\d+(\.\d+)?$/.test(size) ? size + 'px' : size;
  3391. };
  3392. var removeDataStyle = function (table) {
  3393. remove$7(table, 'data-mce-style');
  3394. var removeStyleAttribute = function (element) {
  3395. return remove$7(element, 'data-mce-style');
  3396. };
  3397. each$2(cells$1(table), removeStyleAttribute);
  3398. each$2(columns$1(table), removeStyleAttribute);
  3399. };
  3400. var getRawWidth = function (editor, elm) {
  3401. var raw = editor.dom.getStyle(elm, 'width') || editor.dom.getAttrib(elm, 'width');
  3402. return Optional.from(raw).filter(isNotEmpty);
  3403. };
  3404. var isPercentage$1 = function (value) {
  3405. return /^(\d+(\.\d+)?)%$/.test(value);
  3406. };
  3407. var isPixel = function (value) {
  3408. return /^(\d+(\.\d+)?)px$/.test(value);
  3409. };
  3410. var getSelectionStart = function (editor) {
  3411. return SugarElement.fromDom(editor.selection.getStart());
  3412. };
  3413. var getSelectionEnd = function (editor) {
  3414. return SugarElement.fromDom(editor.selection.getEnd());
  3415. };
  3416. var selection = function (selections) {
  3417. return cata$2(selections.get(), constant([]), identity, pure);
  3418. };
  3419. var unmergable = function (selections) {
  3420. var hasSpan = function (elem, type) {
  3421. return getOpt(elem, type).exists(function (span) {
  3422. return parseInt(span, 10) > 1;
  3423. });
  3424. };
  3425. var hasRowOrColSpan = function (elem) {
  3426. return hasSpan(elem, 'rowspan') || hasSpan(elem, 'colspan');
  3427. };
  3428. var candidates = selection(selections);
  3429. return candidates.length > 0 && forall(candidates, hasRowOrColSpan) ? Optional.some(candidates) : Optional.none();
  3430. };
  3431. var mergable = function (table, selections, ephemera) {
  3432. return cata$2(selections.get(), Optional.none, function (cells) {
  3433. if (cells.length <= 1) {
  3434. return Optional.none();
  3435. } else {
  3436. return retrieveBox(table, ephemera.firstSelectedSelector, ephemera.lastSelectedSelector).map(function (bounds) {
  3437. return {
  3438. bounds: bounds,
  3439. cells: cells
  3440. };
  3441. });
  3442. }
  3443. }, Optional.none);
  3444. };
  3445. var strSelected = 'data-mce-selected';
  3446. var strSelectedSelector = 'td[' + strSelected + '],th[' + strSelected + ']';
  3447. var strAttributeSelector = '[' + strSelected + ']';
  3448. var strFirstSelected = 'data-mce-first-selected';
  3449. var strFirstSelectedSelector = 'td[' + strFirstSelected + '],th[' + strFirstSelected + ']';
  3450. var strLastSelected = 'data-mce-last-selected';
  3451. var strLastSelectedSelector = 'td[' + strLastSelected + '],th[' + strLastSelected + ']';
  3452. var attributeSelector = strAttributeSelector;
  3453. var ephemera = {
  3454. selected: strSelected,
  3455. selectedSelector: strSelectedSelector,
  3456. firstSelected: strFirstSelected,
  3457. firstSelectedSelector: strFirstSelectedSelector,
  3458. lastSelected: strLastSelected,
  3459. lastSelectedSelector: strLastSelectedSelector
  3460. };
  3461. var noMenu = function (cell) {
  3462. return {
  3463. element: cell,
  3464. mergable: Optional.none(),
  3465. unmergable: Optional.none(),
  3466. selection: [cell]
  3467. };
  3468. };
  3469. var forMenu = function (selections, table, cell) {
  3470. return {
  3471. element: cell,
  3472. mergable: mergable(table, selections, ephemera),
  3473. unmergable: unmergable(selections),
  3474. selection: selection(selections)
  3475. };
  3476. };
  3477. var paste = function (element, clipboard, generators) {
  3478. return {
  3479. element: element,
  3480. clipboard: clipboard,
  3481. generators: generators
  3482. };
  3483. };
  3484. var pasteRows = function (selections, cell, clipboard, generators) {
  3485. return {
  3486. selection: selection(selections),
  3487. clipboard: clipboard,
  3488. generators: generators
  3489. };
  3490. };
  3491. var getSelectionCellFallback = function (element) {
  3492. return table(element).bind(function (table) {
  3493. return retrieve(table, ephemera.firstSelectedSelector);
  3494. }).fold(constant(element), function (cells) {
  3495. return cells[0];
  3496. });
  3497. };
  3498. var getSelectionFromSelector = function (selector) {
  3499. return function (initCell, isRoot) {
  3500. var cellName = name(initCell);
  3501. var cell = cellName === 'col' || cellName === 'colgroup' ? getSelectionCellFallback(initCell) : initCell;
  3502. return closest$1(cell, selector, isRoot);
  3503. };
  3504. };
  3505. var getSelectionCellOrCaption = getSelectionFromSelector('th,td,caption');
  3506. var getSelectionCell = getSelectionFromSelector('th,td');
  3507. var getCellsFromSelection = function (selections) {
  3508. return selection(selections);
  3509. };
  3510. var getRowsFromSelection = function (selected, selector) {
  3511. var cellOpt = getSelectionCell(selected);
  3512. var rowsOpt = cellOpt.bind(function (cell) {
  3513. return table(cell);
  3514. }).map(function (table) {
  3515. return rows$1(table);
  3516. });
  3517. return lift2(cellOpt, rowsOpt, function (cell, rows) {
  3518. return filter$2(rows, function (row) {
  3519. return exists(fromDom(row.dom.cells), function (rowCell) {
  3520. return get$b(rowCell, selector) === '1' || eq$1(rowCell, cell);
  3521. });
  3522. });
  3523. }).getOr([]);
  3524. };
  3525. var extractSelected = function (cells) {
  3526. return table(cells[0]).map(function (table) {
  3527. var replica = extract$1(table, attributeSelector);
  3528. removeDataStyle(replica);
  3529. return [replica];
  3530. });
  3531. };
  3532. var serializeElements = function (editor, elements) {
  3533. return map$1(elements, function (elm) {
  3534. return editor.selection.serializer.serialize(elm.dom, {});
  3535. }).join('');
  3536. };
  3537. var getTextContent = function (elements) {
  3538. return map$1(elements, function (element) {
  3539. return element.dom.innerText;
  3540. }).join('');
  3541. };
  3542. var registerEvents = function (editor, selections, actions, cellSelection) {
  3543. editor.on('BeforeGetContent', function (e) {
  3544. var multiCellContext = function (cells) {
  3545. e.preventDefault();
  3546. extractSelected(cells).each(function (elements) {
  3547. e.content = e.format === 'text' ? getTextContent(elements) : serializeElements(editor, elements);
  3548. });
  3549. };
  3550. if (e.selection === true) {
  3551. cata$2(selections.get(), noop, multiCellContext, noop);
  3552. }
  3553. });
  3554. editor.on('BeforeSetContent', function (e) {
  3555. if (e.selection === true && e.paste === true) {
  3556. var selectedCells = getCellsFromSelection(selections);
  3557. head(selectedCells).each(function (cell) {
  3558. table(cell).each(function (table) {
  3559. var elements = filter$2(fromHtml(e.content), function (content) {
  3560. return name(content) !== 'meta';
  3561. });
  3562. var isTable = isTag('table');
  3563. if (elements.length === 1 && isTable(elements[0])) {
  3564. e.preventDefault();
  3565. var doc = SugarElement.fromDom(editor.getDoc());
  3566. var generators = paste$1(doc);
  3567. var targets = paste(cell, elements[0], generators);
  3568. actions.pasteCells(table, targets).each(function () {
  3569. editor.focus();
  3570. });
  3571. }
  3572. });
  3573. });
  3574. }
  3575. });
  3576. };
  3577. var adt$7 = Adt.generate([
  3578. { none: [] },
  3579. { only: ['index'] },
  3580. {
  3581. left: [
  3582. 'index',
  3583. 'next'
  3584. ]
  3585. },
  3586. {
  3587. middle: [
  3588. 'prev',
  3589. 'index',
  3590. 'next'
  3591. ]
  3592. },
  3593. {
  3594. right: [
  3595. 'prev',
  3596. 'index'
  3597. ]
  3598. }
  3599. ]);
  3600. var ColumnContext = __assign({}, adt$7);
  3601. var neighbours = function (input, index) {
  3602. if (input.length === 0) {
  3603. return ColumnContext.none();
  3604. }
  3605. if (input.length === 1) {
  3606. return ColumnContext.only(0);
  3607. }
  3608. if (index === 0) {
  3609. return ColumnContext.left(0, 1);
  3610. }
  3611. if (index === input.length - 1) {
  3612. return ColumnContext.right(index - 1, index);
  3613. }
  3614. if (index > 0 && index < input.length - 1) {
  3615. return ColumnContext.middle(index - 1, index, index + 1);
  3616. }
  3617. return ColumnContext.none();
  3618. };
  3619. var determine = function (input, column, step, tableSize, resize) {
  3620. var result = input.slice(0);
  3621. var context = neighbours(input, column);
  3622. var onNone = constant(map$1(result, constant(0)));
  3623. var onOnly = function (index) {
  3624. return tableSize.singleColumnWidth(result[index], step);
  3625. };
  3626. var onLeft = function (index, next) {
  3627. return resize.calcLeftEdgeDeltas(result, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
  3628. };
  3629. var onMiddle = function (prev, index, next) {
  3630. return resize.calcMiddleDeltas(result, prev, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
  3631. };
  3632. var onRight = function (prev, index) {
  3633. return resize.calcRightEdgeDeltas(result, prev, index, step, tableSize.minCellWidth(), tableSize.isRelative);
  3634. };
  3635. return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
  3636. };
  3637. var total = function (start, end, measures) {
  3638. var r = 0;
  3639. for (var i = start; i < end; i++) {
  3640. r += measures[i] !== undefined ? measures[i] : 0;
  3641. }
  3642. return r;
  3643. };
  3644. var recalculateWidthForCells = function (warehouse, widths) {
  3645. var all = Warehouse.justCells(warehouse);
  3646. return map$1(all, function (cell) {
  3647. var width = total(cell.column, cell.column + cell.colspan, widths);
  3648. return {
  3649. element: cell.element,
  3650. width: width,
  3651. colspan: cell.colspan
  3652. };
  3653. });
  3654. };
  3655. var recalculateWidthForColumns = function (warehouse, widths) {
  3656. var groups = Warehouse.justColumns(warehouse);
  3657. return map$1(groups, function (column, index) {
  3658. return {
  3659. element: column.element,
  3660. width: widths[index],
  3661. colspan: column.colspan
  3662. };
  3663. });
  3664. };
  3665. var recalculateHeightForCells = function (warehouse, heights) {
  3666. var all = Warehouse.justCells(warehouse);
  3667. return map$1(all, function (cell) {
  3668. var height = total(cell.row, cell.row + cell.rowspan, heights);
  3669. return {
  3670. element: cell.element,
  3671. height: height,
  3672. rowspan: cell.rowspan
  3673. };
  3674. });
  3675. };
  3676. var matchRowHeight = function (warehouse, heights) {
  3677. return map$1(warehouse.all, function (row, i) {
  3678. return {
  3679. element: row.element,
  3680. height: heights[i]
  3681. };
  3682. });
  3683. };
  3684. var sumUp = function (newSize) {
  3685. return foldr(newSize, function (b, a) {
  3686. return b + a;
  3687. }, 0);
  3688. };
  3689. var recalculate = function (warehouse, widths) {
  3690. if (Warehouse.hasColumns(warehouse)) {
  3691. return recalculateWidthForColumns(warehouse, widths);
  3692. } else {
  3693. return recalculateWidthForCells(warehouse, widths);
  3694. }
  3695. };
  3696. var recalculateAndApply = function (warehouse, widths, tableSize) {
  3697. var newSizes = recalculate(warehouse, widths);
  3698. each$2(newSizes, function (cell) {
  3699. tableSize.setElementWidth(cell.element, cell.width);
  3700. });
  3701. };
  3702. var adjustWidth = function (table, delta, index, resizing, tableSize) {
  3703. var warehouse = Warehouse.fromTable(table);
  3704. var step = tableSize.getCellDelta(delta);
  3705. var widths = tableSize.getWidths(warehouse, tableSize);
  3706. var isLastColumn = index === warehouse.grid.columns - 1;
  3707. var clampedStep = resizing.clampTableDelta(widths, index, step, tableSize.minCellWidth(), isLastColumn);
  3708. var deltas = determine(widths, index, clampedStep, tableSize, resizing);
  3709. var newWidths = map$1(deltas, function (dx, i) {
  3710. return dx + widths[i];
  3711. });
  3712. recalculateAndApply(warehouse, newWidths, tableSize);
  3713. resizing.resizeTable(tableSize.adjustTableWidth, clampedStep, isLastColumn);
  3714. };
  3715. var adjustHeight = function (table, delta, index, direction) {
  3716. var warehouse = Warehouse.fromTable(table);
  3717. var heights = getPixelHeights(warehouse, table, direction);
  3718. var newHeights = map$1(heights, function (dy, i) {
  3719. return index === i ? Math.max(delta + dy, minHeight()) : dy;
  3720. });
  3721. var newCellSizes = recalculateHeightForCells(warehouse, newHeights);
  3722. var newRowSizes = matchRowHeight(warehouse, newHeights);
  3723. each$2(newRowSizes, function (row) {
  3724. setHeight(row.element, row.height);
  3725. });
  3726. each$2(newCellSizes, function (cell) {
  3727. setHeight(cell.element, cell.height);
  3728. });
  3729. var total = sumUp(newHeights);
  3730. setHeight(table, total);
  3731. };
  3732. var adjustAndRedistributeWidths$1 = function (_table, list, details, tableSize, resizeBehaviour) {
  3733. var warehouse = Warehouse.generate(list);
  3734. var sizes = tableSize.getWidths(warehouse, tableSize);
  3735. var tablePixelWidth = tableSize.pixelWidth();
  3736. var _a = resizeBehaviour.calcRedestributedWidths(sizes, tablePixelWidth, details.pixelDelta, tableSize.isRelative), newSizes = _a.newSizes, delta = _a.delta;
  3737. recalculateAndApply(warehouse, newSizes, tableSize);
  3738. tableSize.adjustTableWidth(delta);
  3739. };
  3740. var adjustWidthTo = function (_table, list, _info, tableSize) {
  3741. var warehouse = Warehouse.generate(list);
  3742. var widths = tableSize.getWidths(warehouse, tableSize);
  3743. recalculateAndApply(warehouse, widths, tableSize);
  3744. };
  3745. var zero = function (array) {
  3746. return map$1(array, constant(0));
  3747. };
  3748. var surround = function (sizes, startIndex, endIndex, results, f) {
  3749. return f(sizes.slice(0, startIndex)).concat(results).concat(f(sizes.slice(endIndex)));
  3750. };
  3751. var clampDeltaHelper = function (predicate) {
  3752. return function (sizes, index, delta, minCellSize) {
  3753. if (!predicate(delta)) {
  3754. return delta;
  3755. } else {
  3756. var newSize = Math.max(minCellSize, sizes[index] - Math.abs(delta));
  3757. var diff = Math.abs(newSize - sizes[index]);
  3758. return delta >= 0 ? diff : -diff;
  3759. }
  3760. };
  3761. };
  3762. var clampNegativeDelta = clampDeltaHelper(function (delta) {
  3763. return delta < 0;
  3764. });
  3765. var clampDelta = clampDeltaHelper(always);
  3766. var resizeTable = function () {
  3767. var calcFixedDeltas = function (sizes, index, next, delta, minCellSize) {
  3768. var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
  3769. return surround(sizes, index, next + 1, [
  3770. clampedDelta,
  3771. 0
  3772. ], zero);
  3773. };
  3774. var calcRelativeDeltas = function (sizes, index, delta, minCellSize) {
  3775. var ratio = (100 + delta) / 100;
  3776. var newThis = Math.max(minCellSize, (sizes[index] + delta) / ratio);
  3777. return map$1(sizes, function (size, idx) {
  3778. var newSize = idx === index ? newThis : size / ratio;
  3779. return newSize - size;
  3780. });
  3781. };
  3782. var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize, isRelative) {
  3783. if (isRelative) {
  3784. return calcRelativeDeltas(sizes, index, delta, minCellSize);
  3785. } else {
  3786. return calcFixedDeltas(sizes, index, next, delta, minCellSize);
  3787. }
  3788. };
  3789. var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize, isRelative) {
  3790. return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize, isRelative);
  3791. };
  3792. var resizeTable = function (resizer, delta) {
  3793. return resizer(delta);
  3794. };
  3795. var calcRightEdgeDeltas = function (sizes, _prev, index, delta, minCellSize, isRelative) {
  3796. if (isRelative) {
  3797. return calcRelativeDeltas(sizes, index, delta, minCellSize);
  3798. } else {
  3799. var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
  3800. return zero(sizes.slice(0, index)).concat([clampedDelta]);
  3801. }
  3802. };
  3803. var calcRedestributedWidths = function (sizes, totalWidth, pixelDelta, isRelative) {
  3804. if (isRelative) {
  3805. var tableWidth = totalWidth + pixelDelta;
  3806. var ratio_1 = tableWidth / totalWidth;
  3807. var newSizes = map$1(sizes, function (size) {
  3808. return size / ratio_1;
  3809. });
  3810. return {
  3811. delta: ratio_1 * 100 - 100,
  3812. newSizes: newSizes
  3813. };
  3814. } else {
  3815. return {
  3816. delta: pixelDelta,
  3817. newSizes: sizes
  3818. };
  3819. }
  3820. };
  3821. return {
  3822. resizeTable: resizeTable,
  3823. clampTableDelta: clampNegativeDelta,
  3824. calcLeftEdgeDeltas: calcLeftEdgeDeltas,
  3825. calcMiddleDeltas: calcMiddleDeltas,
  3826. calcRightEdgeDeltas: calcRightEdgeDeltas,
  3827. calcRedestributedWidths: calcRedestributedWidths
  3828. };
  3829. };
  3830. var preserveTable = function () {
  3831. var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize) {
  3832. var idx = delta >= 0 ? next : index;
  3833. var clampedDelta = clampDelta(sizes, idx, delta, minCellSize);
  3834. return surround(sizes, index, next + 1, [
  3835. clampedDelta,
  3836. -clampedDelta
  3837. ], zero);
  3838. };
  3839. var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize) {
  3840. return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize);
  3841. };
  3842. var resizeTable = function (resizer, delta, isLastColumn) {
  3843. if (isLastColumn) {
  3844. resizer(delta);
  3845. }
  3846. };
  3847. var calcRightEdgeDeltas = function (sizes, _prev, _index, delta, _minCellSize, isRelative) {
  3848. if (isRelative) {
  3849. return zero(sizes);
  3850. } else {
  3851. var diff = delta / sizes.length;
  3852. return map$1(sizes, constant(diff));
  3853. }
  3854. };
  3855. var clampTableDelta = function (sizes, index, delta, minCellSize, isLastColumn) {
  3856. if (isLastColumn) {
  3857. if (delta >= 0) {
  3858. return delta;
  3859. } else {
  3860. var maxDelta = foldl(sizes, function (a, b) {
  3861. return a + b - minCellSize;
  3862. }, 0);
  3863. return Math.max(-maxDelta, delta);
  3864. }
  3865. } else {
  3866. return clampNegativeDelta(sizes, index, delta, minCellSize);
  3867. }
  3868. };
  3869. var calcRedestributedWidths = function (sizes, _totalWidth, _pixelDelta, _isRelative) {
  3870. return {
  3871. delta: 0,
  3872. newSizes: sizes
  3873. };
  3874. };
  3875. return {
  3876. resizeTable: resizeTable,
  3877. clampTableDelta: clampTableDelta,
  3878. calcLeftEdgeDeltas: calcLeftEdgeDeltas,
  3879. calcMiddleDeltas: calcMiddleDeltas,
  3880. calcRightEdgeDeltas: calcRightEdgeDeltas,
  3881. calcRedestributedWidths: calcRedestributedWidths
  3882. };
  3883. };
  3884. var only = function (element, isResizable) {
  3885. var parent = Optional.from(element.dom.documentElement).map(SugarElement.fromDom).getOr(element);
  3886. return {
  3887. parent: constant(parent),
  3888. view: constant(element),
  3889. origin: constant(SugarPosition(0, 0)),
  3890. isResizable: isResizable
  3891. };
  3892. };
  3893. var detached = function (editable, chrome, isResizable) {
  3894. var origin = function () {
  3895. return absolute(chrome);
  3896. };
  3897. return {
  3898. parent: constant(chrome),
  3899. view: constant(editable),
  3900. origin: origin,
  3901. isResizable: isResizable
  3902. };
  3903. };
  3904. var body = function (editable, chrome, isResizable) {
  3905. return {
  3906. parent: constant(chrome),
  3907. view: constant(editable),
  3908. origin: constant(SugarPosition(0, 0)),
  3909. isResizable: isResizable
  3910. };
  3911. };
  3912. var ResizeWire = {
  3913. only: only,
  3914. detached: detached,
  3915. body: body
  3916. };
  3917. var adt$6 = Adt.generate([
  3918. { invalid: ['raw'] },
  3919. { pixels: ['value'] },
  3920. { percent: ['value'] }
  3921. ]);
  3922. var validateFor = function (suffix, type, value) {
  3923. var rawAmount = value.substring(0, value.length - suffix.length);
  3924. var amount = parseFloat(rawAmount);
  3925. return rawAmount === amount.toString() ? type(amount) : adt$6.invalid(value);
  3926. };
  3927. var from = function (value) {
  3928. if (endsWith(value, '%')) {
  3929. return validateFor('%', adt$6.percent, value);
  3930. }
  3931. if (endsWith(value, 'px')) {
  3932. return validateFor('px', adt$6.pixels, value);
  3933. }
  3934. return adt$6.invalid(value);
  3935. };
  3936. var Size = __assign(__assign({}, adt$6), { from: from });
  3937. var redistributeToPercent = function (widths, totalWidth) {
  3938. return map$1(widths, function (w) {
  3939. var colType = Size.from(w);
  3940. return colType.fold(function () {
  3941. return w;
  3942. }, function (px) {
  3943. var ratio = px / totalWidth * 100;
  3944. return ratio + '%';
  3945. }, function (pc) {
  3946. return pc + '%';
  3947. });
  3948. });
  3949. };
  3950. var redistributeToPx = function (widths, totalWidth, newTotalWidth) {
  3951. var scale = newTotalWidth / totalWidth;
  3952. return map$1(widths, function (w) {
  3953. var colType = Size.from(w);
  3954. return colType.fold(function () {
  3955. return w;
  3956. }, function (px) {
  3957. return px * scale + 'px';
  3958. }, function (pc) {
  3959. return pc / 100 * newTotalWidth + 'px';
  3960. });
  3961. });
  3962. };
  3963. var redistributeEmpty = function (newWidthType, columns) {
  3964. var f = newWidthType.fold(function () {
  3965. return constant('');
  3966. }, function (pixels) {
  3967. var num = pixels / columns;
  3968. return constant(num + 'px');
  3969. }, function () {
  3970. var num = 100 / columns;
  3971. return constant(num + '%');
  3972. });
  3973. return range$1(columns, f);
  3974. };
  3975. var redistributeValues = function (newWidthType, widths, totalWidth) {
  3976. return newWidthType.fold(function () {
  3977. return widths;
  3978. }, function (px) {
  3979. return redistributeToPx(widths, totalWidth, px);
  3980. }, function (_pc) {
  3981. return redistributeToPercent(widths, totalWidth);
  3982. });
  3983. };
  3984. var redistribute$1 = function (widths, totalWidth, newWidth) {
  3985. var newType = Size.from(newWidth);
  3986. var floats = forall(widths, function (s) {
  3987. return s === '0px';
  3988. }) ? redistributeEmpty(newType, widths.length) : redistributeValues(newType, widths, totalWidth);
  3989. return normalize(floats);
  3990. };
  3991. var sum = function (values, fallback) {
  3992. if (values.length === 0) {
  3993. return fallback;
  3994. }
  3995. return foldr(values, function (rest, v) {
  3996. return Size.from(v).fold(constant(0), identity, identity) + rest;
  3997. }, 0);
  3998. };
  3999. var roundDown = function (num, unit) {
  4000. var floored = Math.floor(num);
  4001. return {
  4002. value: floored + unit,
  4003. remainder: num - floored
  4004. };
  4005. };
  4006. var add$3 = function (value, amount) {
  4007. return Size.from(value).fold(constant(value), function (px) {
  4008. return px + amount + 'px';
  4009. }, function (pc) {
  4010. return pc + amount + '%';
  4011. });
  4012. };
  4013. var normalize = function (values) {
  4014. if (values.length === 0) {
  4015. return values;
  4016. }
  4017. var scan = foldr(values, function (rest, value) {
  4018. var info = Size.from(value).fold(function () {
  4019. return {
  4020. value: value,
  4021. remainder: 0
  4022. };
  4023. }, function (num) {
  4024. return roundDown(num, 'px');
  4025. }, function (num) {
  4026. return {
  4027. value: num + '%',
  4028. remainder: 0
  4029. };
  4030. });
  4031. return {
  4032. output: [info.value].concat(rest.output),
  4033. remainder: rest.remainder + info.remainder
  4034. };
  4035. }, {
  4036. output: [],
  4037. remainder: 0
  4038. });
  4039. var r = scan.output;
  4040. return r.slice(0, r.length - 1).concat([add$3(r[r.length - 1], Math.round(scan.remainder))]);
  4041. };
  4042. var validate = Size.from;
  4043. var redistributeToW = function (newWidths, cells, unit) {
  4044. each$2(cells, function (cell) {
  4045. var widths = newWidths.slice(cell.column, cell.colspan + cell.column);
  4046. var w = sum(widths, minWidth());
  4047. set$1(cell.element, 'width', w + unit);
  4048. });
  4049. };
  4050. var redistributeToColumns = function (newWidths, columns, unit) {
  4051. each$2(columns, function (column, index) {
  4052. var width = sum([newWidths[index]], minWidth());
  4053. set$1(column.element, 'width', width + unit);
  4054. });
  4055. };
  4056. var redistributeToH = function (newHeights, rows, cells, unit) {
  4057. each$2(cells, function (cell) {
  4058. var heights = newHeights.slice(cell.row, cell.rowspan + cell.row);
  4059. var h = sum(heights, minHeight());
  4060. set$1(cell.element, 'height', h + unit);
  4061. });
  4062. each$2(rows, function (row, i) {
  4063. set$1(row.element, 'height', newHeights[i]);
  4064. });
  4065. };
  4066. var getUnit = function (newSize) {
  4067. return validate(newSize).fold(constant('px'), constant('px'), constant('%'));
  4068. };
  4069. var redistribute = function (table, optWidth, optHeight, tableSize) {
  4070. var warehouse = Warehouse.fromTable(table);
  4071. var rows = warehouse.all;
  4072. var cells = Warehouse.justCells(warehouse);
  4073. var columns = Warehouse.justColumns(warehouse);
  4074. optWidth.each(function (newWidth) {
  4075. var widthUnit = getUnit(newWidth);
  4076. var totalWidth = get$8(table);
  4077. var oldWidths = getRawWidths(warehouse, table, tableSize);
  4078. var nuWidths = redistribute$1(oldWidths, totalWidth, newWidth);
  4079. if (Warehouse.hasColumns(warehouse)) {
  4080. redistributeToColumns(nuWidths, columns, widthUnit);
  4081. } else {
  4082. redistributeToW(nuWidths, cells, widthUnit);
  4083. }
  4084. set$1(table, 'width', newWidth);
  4085. });
  4086. optHeight.each(function (newHeight) {
  4087. var hUnit = getUnit(newHeight);
  4088. var totalHeight = get$7(table);
  4089. var oldHeights = getRawHeights(warehouse, table, height);
  4090. var nuHeights = redistribute$1(oldHeights, totalHeight, newHeight);
  4091. redistributeToH(nuHeights, rows, cells, hUnit);
  4092. set$1(table, 'height', newHeight);
  4093. });
  4094. };
  4095. var isPercentSizing = isPercentSizing$1;
  4096. var isPixelSizing = isPixelSizing$1;
  4097. var isNoneSizing = isNoneSizing$1;
  4098. var getPercentTableWidth = getPercentTableWidth$1;
  4099. var getGridSize = function (table) {
  4100. var warehouse = Warehouse.fromTable(table);
  4101. return warehouse.grid;
  4102. };
  4103. var Event = function (fields) {
  4104. var handlers = [];
  4105. var bind = function (handler) {
  4106. if (handler === undefined) {
  4107. throw new Error('Event bind error: undefined handler');
  4108. }
  4109. handlers.push(handler);
  4110. };
  4111. var unbind = function (handler) {
  4112. handlers = filter$2(handlers, function (h) {
  4113. return h !== handler;
  4114. });
  4115. };
  4116. var trigger = function () {
  4117. var args = [];
  4118. for (var _i = 0; _i < arguments.length; _i++) {
  4119. args[_i] = arguments[_i];
  4120. }
  4121. var event = {};
  4122. each$2(fields, function (name, i) {
  4123. event[name] = args[i];
  4124. });
  4125. each$2(handlers, function (handler) {
  4126. handler(event);
  4127. });
  4128. };
  4129. return {
  4130. bind: bind,
  4131. unbind: unbind,
  4132. trigger: trigger
  4133. };
  4134. };
  4135. var create$4 = function (typeDefs) {
  4136. var registry = map(typeDefs, function (event) {
  4137. return {
  4138. bind: event.bind,
  4139. unbind: event.unbind
  4140. };
  4141. });
  4142. var trigger = map(typeDefs, function (event) {
  4143. return event.trigger;
  4144. });
  4145. return {
  4146. registry: registry,
  4147. trigger: trigger
  4148. };
  4149. };
  4150. var last = function (fn, rate) {
  4151. var timer = null;
  4152. var cancel = function () {
  4153. if (!isNull(timer)) {
  4154. clearTimeout(timer);
  4155. timer = null;
  4156. }
  4157. };
  4158. var throttle = function () {
  4159. var args = [];
  4160. for (var _i = 0; _i < arguments.length; _i++) {
  4161. args[_i] = arguments[_i];
  4162. }
  4163. cancel();
  4164. timer = setTimeout(function () {
  4165. timer = null;
  4166. fn.apply(null, args);
  4167. }, rate);
  4168. };
  4169. return {
  4170. cancel: cancel,
  4171. throttle: throttle
  4172. };
  4173. };
  4174. var sort = function (arr) {
  4175. return arr.slice(0).sort();
  4176. };
  4177. var reqMessage = function (required, keys) {
  4178. throw new Error('All required keys (' + sort(required).join(', ') + ') were not specified. Specified keys were: ' + sort(keys).join(', ') + '.');
  4179. };
  4180. var unsuppMessage = function (unsupported) {
  4181. throw new Error('Unsupported keys for object: ' + sort(unsupported).join(', '));
  4182. };
  4183. var validateStrArr = function (label, array) {
  4184. if (!isArray(array)) {
  4185. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  4186. }
  4187. each$2(array, function (a) {
  4188. if (!isString(a)) {
  4189. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  4190. }
  4191. });
  4192. };
  4193. var invalidTypeMessage = function (incorrect, type) {
  4194. throw new Error('All values need to be of type: ' + type + '. Keys (' + sort(incorrect).join(', ') + ') were not.');
  4195. };
  4196. var checkDupes = function (everything) {
  4197. var sorted = sort(everything);
  4198. var dupe = find$1(sorted, function (s, i) {
  4199. return i < sorted.length - 1 && s === sorted[i + 1];
  4200. });
  4201. dupe.each(function (d) {
  4202. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  4203. });
  4204. };
  4205. var base = function (handleUnsupported, required) {
  4206. return baseWith(handleUnsupported, required, {
  4207. validate: isFunction,
  4208. label: 'function'
  4209. });
  4210. };
  4211. var baseWith = function (handleUnsupported, required, pred) {
  4212. if (required.length === 0) {
  4213. throw new Error('You must specify at least one required field.');
  4214. }
  4215. validateStrArr('required', required);
  4216. checkDupes(required);
  4217. return function (obj) {
  4218. var keys$1 = keys(obj);
  4219. var allReqd = forall(required, function (req) {
  4220. return contains$2(keys$1, req);
  4221. });
  4222. if (!allReqd) {
  4223. reqMessage(required, keys$1);
  4224. }
  4225. handleUnsupported(required, keys$1);
  4226. var invalidKeys = filter$2(required, function (key) {
  4227. return !pred.validate(obj[key], key);
  4228. });
  4229. if (invalidKeys.length > 0) {
  4230. invalidTypeMessage(invalidKeys, pred.label);
  4231. }
  4232. return obj;
  4233. };
  4234. };
  4235. var handleExact = function (required, keys) {
  4236. var unsupported = filter$2(keys, function (key) {
  4237. return !contains$2(required, key);
  4238. });
  4239. if (unsupported.length > 0) {
  4240. unsuppMessage(unsupported);
  4241. }
  4242. };
  4243. var exactly = function (required) {
  4244. return base(handleExact, required);
  4245. };
  4246. var DragMode = exactly([
  4247. 'compare',
  4248. 'extract',
  4249. 'mutate',
  4250. 'sink'
  4251. ]);
  4252. var DragSink = exactly([
  4253. 'element',
  4254. 'start',
  4255. 'stop',
  4256. 'destroy'
  4257. ]);
  4258. var DragApi = exactly([
  4259. 'forceDrop',
  4260. 'drop',
  4261. 'move',
  4262. 'delayDrop'
  4263. ]);
  4264. var InDrag = function () {
  4265. var previous = Optional.none();
  4266. var reset = function () {
  4267. previous = Optional.none();
  4268. };
  4269. var update = function (mode, nu) {
  4270. var result = previous.map(function (old) {
  4271. return mode.compare(old, nu);
  4272. });
  4273. previous = Optional.some(nu);
  4274. return result;
  4275. };
  4276. var onEvent = function (event, mode) {
  4277. var dataOption = mode.extract(event);
  4278. dataOption.each(function (data) {
  4279. var offset = update(mode, data);
  4280. offset.each(function (d) {
  4281. events.trigger.move(d);
  4282. });
  4283. });
  4284. };
  4285. var events = create$4({ move: Event(['info']) });
  4286. return {
  4287. onEvent: onEvent,
  4288. reset: reset,
  4289. events: events.registry
  4290. };
  4291. };
  4292. var NoDrag = function () {
  4293. var events = create$4({ move: Event(['info']) });
  4294. return {
  4295. onEvent: noop,
  4296. reset: noop,
  4297. events: events.registry
  4298. };
  4299. };
  4300. var Movement = function () {
  4301. var noDragState = NoDrag();
  4302. var inDragState = InDrag();
  4303. var dragState = noDragState;
  4304. var on = function () {
  4305. dragState.reset();
  4306. dragState = inDragState;
  4307. };
  4308. var off = function () {
  4309. dragState.reset();
  4310. dragState = noDragState;
  4311. };
  4312. var onEvent = function (event, mode) {
  4313. dragState.onEvent(event, mode);
  4314. };
  4315. var isOn = function () {
  4316. return dragState === inDragState;
  4317. };
  4318. return {
  4319. on: on,
  4320. off: off,
  4321. isOn: isOn,
  4322. onEvent: onEvent,
  4323. events: inDragState.events
  4324. };
  4325. };
  4326. var setup = function (mutation, mode, settings) {
  4327. var active = false;
  4328. var events = create$4({
  4329. start: Event([]),
  4330. stop: Event([])
  4331. });
  4332. var movement = Movement();
  4333. var drop = function () {
  4334. sink.stop();
  4335. if (movement.isOn()) {
  4336. movement.off();
  4337. events.trigger.stop();
  4338. }
  4339. };
  4340. var throttledDrop = last(drop, 200);
  4341. var go = function (parent) {
  4342. sink.start(parent);
  4343. movement.on();
  4344. events.trigger.start();
  4345. };
  4346. var mousemove = function (event) {
  4347. throttledDrop.cancel();
  4348. movement.onEvent(event, mode);
  4349. };
  4350. movement.events.move.bind(function (event) {
  4351. mode.mutate(mutation, event.info);
  4352. });
  4353. var on = function () {
  4354. active = true;
  4355. };
  4356. var off = function () {
  4357. active = false;
  4358. };
  4359. var runIfActive = function (f) {
  4360. return function () {
  4361. var args = [];
  4362. for (var _i = 0; _i < arguments.length; _i++) {
  4363. args[_i] = arguments[_i];
  4364. }
  4365. if (active) {
  4366. f.apply(null, args);
  4367. }
  4368. };
  4369. };
  4370. var sink = mode.sink(DragApi({
  4371. forceDrop: drop,
  4372. drop: runIfActive(drop),
  4373. move: runIfActive(mousemove),
  4374. delayDrop: runIfActive(throttledDrop.throttle)
  4375. }), settings);
  4376. var destroy = function () {
  4377. sink.destroy();
  4378. };
  4379. return {
  4380. element: sink.element,
  4381. go: go,
  4382. on: on,
  4383. off: off,
  4384. destroy: destroy,
  4385. events: events.registry
  4386. };
  4387. };
  4388. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  4389. return {
  4390. target: target,
  4391. x: x,
  4392. y: y,
  4393. stop: stop,
  4394. prevent: prevent,
  4395. kill: kill,
  4396. raw: raw
  4397. };
  4398. };
  4399. var fromRawEvent$1 = function (rawEvent) {
  4400. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  4401. var stop = function () {
  4402. return rawEvent.stopPropagation();
  4403. };
  4404. var prevent = function () {
  4405. return rawEvent.preventDefault();
  4406. };
  4407. var kill = compose(prevent, stop);
  4408. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  4409. };
  4410. var handle$2 = function (filter, handler) {
  4411. return function (rawEvent) {
  4412. if (filter(rawEvent)) {
  4413. handler(fromRawEvent$1(rawEvent));
  4414. }
  4415. };
  4416. };
  4417. var binder = function (element, event, filter, handler, useCapture) {
  4418. var wrapped = handle$2(filter, handler);
  4419. element.dom.addEventListener(event, wrapped, useCapture);
  4420. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  4421. };
  4422. var bind$1 = function (element, event, filter, handler) {
  4423. return binder(element, event, filter, handler, false);
  4424. };
  4425. var unbind = function (element, event, handler, useCapture) {
  4426. element.dom.removeEventListener(event, handler, useCapture);
  4427. };
  4428. var filter = always;
  4429. var bind = function (element, event, handler) {
  4430. return bind$1(element, event, filter, handler);
  4431. };
  4432. var fromRawEvent = fromRawEvent$1;
  4433. var read = function (element, attr) {
  4434. var value = get$b(element, attr);
  4435. return value === undefined || value === '' ? [] : value.split(' ');
  4436. };
  4437. var add$2 = function (element, attr, id) {
  4438. var old = read(element, attr);
  4439. var nu = old.concat([id]);
  4440. set$2(element, attr, nu.join(' '));
  4441. return true;
  4442. };
  4443. var remove$4 = function (element, attr, id) {
  4444. var nu = filter$2(read(element, attr), function (v) {
  4445. return v !== id;
  4446. });
  4447. if (nu.length > 0) {
  4448. set$2(element, attr, nu.join(' '));
  4449. } else {
  4450. remove$7(element, attr);
  4451. }
  4452. return false;
  4453. };
  4454. var supports = function (element) {
  4455. return element.dom.classList !== undefined;
  4456. };
  4457. var get$5 = function (element) {
  4458. return read(element, 'class');
  4459. };
  4460. var add$1 = function (element, clazz) {
  4461. return add$2(element, 'class', clazz);
  4462. };
  4463. var remove$3 = function (element, clazz) {
  4464. return remove$4(element, 'class', clazz);
  4465. };
  4466. var add = function (element, clazz) {
  4467. if (supports(element)) {
  4468. element.dom.classList.add(clazz);
  4469. } else {
  4470. add$1(element, clazz);
  4471. }
  4472. };
  4473. var cleanClass = function (element) {
  4474. var classList = supports(element) ? element.dom.classList : get$5(element);
  4475. if (classList.length === 0) {
  4476. remove$7(element, 'class');
  4477. }
  4478. };
  4479. var remove$2 = function (element, clazz) {
  4480. if (supports(element)) {
  4481. var classList = element.dom.classList;
  4482. classList.remove(clazz);
  4483. } else {
  4484. remove$3(element, clazz);
  4485. }
  4486. cleanClass(element);
  4487. };
  4488. var has = function (element, clazz) {
  4489. return supports(element) && element.dom.classList.contains(clazz);
  4490. };
  4491. var css = function (namespace) {
  4492. var dashNamespace = namespace.replace(/\./g, '-');
  4493. var resolve = function (str) {
  4494. return dashNamespace + '-' + str;
  4495. };
  4496. return { resolve: resolve };
  4497. };
  4498. var styles$1 = css('ephox-dragster');
  4499. var resolve$1 = styles$1.resolve;
  4500. var Blocker = function (options) {
  4501. var settings = __assign({ layerClass: resolve$1('blocker') }, options);
  4502. var div = SugarElement.fromTag('div');
  4503. set$2(div, 'role', 'presentation');
  4504. setAll(div, {
  4505. position: 'fixed',
  4506. left: '0px',
  4507. top: '0px',
  4508. width: '100%',
  4509. height: '100%'
  4510. });
  4511. add(div, resolve$1('blocker'));
  4512. add(div, settings.layerClass);
  4513. var element = constant(div);
  4514. var destroy = function () {
  4515. remove$5(div);
  4516. };
  4517. return {
  4518. element: element,
  4519. destroy: destroy
  4520. };
  4521. };
  4522. var compare = function (old, nu) {
  4523. return SugarPosition(nu.left - old.left, nu.top - old.top);
  4524. };
  4525. var extract = function (event) {
  4526. return Optional.some(SugarPosition(event.x, event.y));
  4527. };
  4528. var mutate = function (mutation, info) {
  4529. mutation.mutate(info.left, info.top);
  4530. };
  4531. var sink = function (dragApi, settings) {
  4532. var blocker = Blocker(settings);
  4533. var mdown = bind(blocker.element(), 'mousedown', dragApi.forceDrop);
  4534. var mup = bind(blocker.element(), 'mouseup', dragApi.drop);
  4535. var mmove = bind(blocker.element(), 'mousemove', dragApi.move);
  4536. var mout = bind(blocker.element(), 'mouseout', dragApi.delayDrop);
  4537. var destroy = function () {
  4538. blocker.destroy();
  4539. mup.unbind();
  4540. mmove.unbind();
  4541. mout.unbind();
  4542. mdown.unbind();
  4543. };
  4544. var start = function (parent) {
  4545. append$1(parent, blocker.element());
  4546. };
  4547. var stop = function () {
  4548. remove$5(blocker.element());
  4549. };
  4550. return DragSink({
  4551. element: blocker.element,
  4552. start: start,
  4553. stop: stop,
  4554. destroy: destroy
  4555. });
  4556. };
  4557. var MouseDrag = DragMode({
  4558. compare: compare,
  4559. extract: extract,
  4560. sink: sink,
  4561. mutate: mutate
  4562. });
  4563. var transform$1 = function (mutation, settings) {
  4564. if (settings === void 0) {
  4565. settings = {};
  4566. }
  4567. var mode = settings.mode !== undefined ? settings.mode : MouseDrag;
  4568. return setup(mutation, mode, settings);
  4569. };
  4570. var closest = function (target) {
  4571. return closest$1(target, '[contenteditable]');
  4572. };
  4573. var isEditable$1 = function (element, assumeEditable) {
  4574. if (assumeEditable === void 0) {
  4575. assumeEditable = false;
  4576. }
  4577. if (!detect$3().browser.isIE() && inBody(element)) {
  4578. return element.dom.isContentEditable;
  4579. } else {
  4580. return closest(element).fold(constant(assumeEditable), function (editable) {
  4581. return getRaw(editable) === 'true';
  4582. });
  4583. }
  4584. };
  4585. var getRaw = function (element) {
  4586. return element.dom.contentEditable;
  4587. };
  4588. var styles = css('ephox-snooker');
  4589. var resolve = styles.resolve;
  4590. var Mutation = function () {
  4591. var events = create$4({
  4592. drag: Event([
  4593. 'xDelta',
  4594. 'yDelta'
  4595. ])
  4596. });
  4597. var mutate = function (x, y) {
  4598. events.trigger.drag(x, y);
  4599. };
  4600. return {
  4601. mutate: mutate,
  4602. events: events.registry
  4603. };
  4604. };
  4605. var BarMutation = function () {
  4606. var events = create$4({
  4607. drag: Event([
  4608. 'xDelta',
  4609. 'yDelta',
  4610. 'target'
  4611. ])
  4612. });
  4613. var target = Optional.none();
  4614. var delegate = Mutation();
  4615. delegate.events.drag.bind(function (event) {
  4616. target.each(function (t) {
  4617. events.trigger.drag(event.xDelta, event.yDelta, t);
  4618. });
  4619. });
  4620. var assign = function (t) {
  4621. target = Optional.some(t);
  4622. };
  4623. var get = function () {
  4624. return target;
  4625. };
  4626. return {
  4627. assign: assign,
  4628. get: get,
  4629. mutate: delegate.mutate,
  4630. events: events.registry
  4631. };
  4632. };
  4633. var col = function (column, x, y, w, h) {
  4634. var bar = SugarElement.fromTag('div');
  4635. setAll(bar, {
  4636. position: 'absolute',
  4637. left: x - w / 2 + 'px',
  4638. top: y + 'px',
  4639. height: h + 'px',
  4640. width: w + 'px'
  4641. });
  4642. setAll$1(bar, {
  4643. 'data-column': column,
  4644. 'role': 'presentation'
  4645. });
  4646. return bar;
  4647. };
  4648. var row = function (r, x, y, w, h) {
  4649. var bar = SugarElement.fromTag('div');
  4650. setAll(bar, {
  4651. position: 'absolute',
  4652. left: x + 'px',
  4653. top: y - h / 2 + 'px',
  4654. height: h + 'px',
  4655. width: w + 'px'
  4656. });
  4657. setAll$1(bar, {
  4658. 'data-row': r,
  4659. 'role': 'presentation'
  4660. });
  4661. return bar;
  4662. };
  4663. var resizeBar = resolve('resizer-bar');
  4664. var resizeRowBar = resolve('resizer-rows');
  4665. var resizeColBar = resolve('resizer-cols');
  4666. var BAR_THICKNESS = 7;
  4667. var resizableRows = function (warehouse, isResizable) {
  4668. return bind$2(warehouse.all, function (row, i) {
  4669. return isResizable(row.element) ? [i] : [];
  4670. });
  4671. };
  4672. var resizableColumns = function (warehouse, isResizable) {
  4673. var resizableCols = [];
  4674. range$1(warehouse.grid.columns, function (index) {
  4675. var colElmOpt = Warehouse.getColumnAt(warehouse, index).map(function (col) {
  4676. return col.element;
  4677. });
  4678. if (colElmOpt.forall(isResizable)) {
  4679. resizableCols.push(index);
  4680. }
  4681. });
  4682. return filter$2(resizableCols, function (colIndex) {
  4683. var columnCells = Warehouse.filterItems(warehouse, function (cell) {
  4684. return cell.column === colIndex;
  4685. });
  4686. return forall(columnCells, function (cell) {
  4687. return isResizable(cell.element);
  4688. });
  4689. });
  4690. };
  4691. var destroy = function (wire) {
  4692. var previous = descendants(wire.parent(), '.' + resizeBar);
  4693. each$2(previous, remove$5);
  4694. };
  4695. var drawBar = function (wire, positions, create) {
  4696. var origin = wire.origin();
  4697. each$2(positions, function (cpOption) {
  4698. cpOption.each(function (cp) {
  4699. var bar = create(origin, cp);
  4700. add(bar, resizeBar);
  4701. append$1(wire.parent(), bar);
  4702. });
  4703. });
  4704. };
  4705. var refreshCol = function (wire, colPositions, position, tableHeight) {
  4706. drawBar(wire, colPositions, function (origin, cp) {
  4707. var colBar = col(cp.col, cp.x - origin.left, position.top - origin.top, BAR_THICKNESS, tableHeight);
  4708. add(colBar, resizeColBar);
  4709. return colBar;
  4710. });
  4711. };
  4712. var refreshRow = function (wire, rowPositions, position, tableWidth) {
  4713. drawBar(wire, rowPositions, function (origin, cp) {
  4714. var rowBar = row(cp.row, position.left - origin.left, cp.y - origin.top, tableWidth, BAR_THICKNESS);
  4715. add(rowBar, resizeRowBar);
  4716. return rowBar;
  4717. });
  4718. };
  4719. var refreshGrid = function (warhouse, wire, table, rows, cols) {
  4720. var position = absolute(table);
  4721. var isResizable = wire.isResizable;
  4722. var rowPositions = rows.length > 0 ? height.positions(rows, table) : [];
  4723. var resizableRowBars = rowPositions.length > 0 ? resizableRows(warhouse, isResizable) : [];
  4724. var resizableRowPositions = filter$2(rowPositions, function (_pos, i) {
  4725. return exists(resizableRowBars, function (barIndex) {
  4726. return i === barIndex;
  4727. });
  4728. });
  4729. refreshRow(wire, resizableRowPositions, position, getOuter$2(table));
  4730. var colPositions = cols.length > 0 ? width.positions(cols, table) : [];
  4731. var resizableColBars = colPositions.length > 0 ? resizableColumns(warhouse, isResizable) : [];
  4732. var resizableColPositions = filter$2(colPositions, function (_pos, i) {
  4733. return exists(resizableColBars, function (barIndex) {
  4734. return i === barIndex;
  4735. });
  4736. });
  4737. refreshCol(wire, resizableColPositions, position, getOuter$1(table));
  4738. };
  4739. var refresh = function (wire, table) {
  4740. destroy(wire);
  4741. if (wire.isResizable(table)) {
  4742. var warehouse = Warehouse.fromTable(table);
  4743. var rows$1 = rows(warehouse);
  4744. var cols = columns(warehouse);
  4745. refreshGrid(warehouse, wire, table, rows$1, cols);
  4746. }
  4747. };
  4748. var each = function (wire, f) {
  4749. var bars = descendants(wire.parent(), '.' + resizeBar);
  4750. each$2(bars, f);
  4751. };
  4752. var hide = function (wire) {
  4753. each(wire, function (bar) {
  4754. set$1(bar, 'display', 'none');
  4755. });
  4756. };
  4757. var show = function (wire) {
  4758. each(wire, function (bar) {
  4759. set$1(bar, 'display', 'block');
  4760. });
  4761. };
  4762. var isRowBar = function (element) {
  4763. return has(element, resizeRowBar);
  4764. };
  4765. var isColBar = function (element) {
  4766. return has(element, resizeColBar);
  4767. };
  4768. var resizeBarDragging = resolve('resizer-bar-dragging');
  4769. var BarManager = function (wire) {
  4770. var mutation = BarMutation();
  4771. var resizing = transform$1(mutation, {});
  4772. var hoverTable = Optional.none();
  4773. var getResizer = function (element, type) {
  4774. return Optional.from(get$b(element, type));
  4775. };
  4776. mutation.events.drag.bind(function (event) {
  4777. getResizer(event.target, 'data-row').each(function (_dataRow) {
  4778. var currentRow = getCssValue(event.target, 'top');
  4779. set$1(event.target, 'top', currentRow + event.yDelta + 'px');
  4780. });
  4781. getResizer(event.target, 'data-column').each(function (_dataCol) {
  4782. var currentCol = getCssValue(event.target, 'left');
  4783. set$1(event.target, 'left', currentCol + event.xDelta + 'px');
  4784. });
  4785. });
  4786. var getDelta = function (target, dir) {
  4787. var newX = getCssValue(target, dir);
  4788. var oldX = getAttrValue(target, 'data-initial-' + dir, 0);
  4789. return newX - oldX;
  4790. };
  4791. resizing.events.stop.bind(function () {
  4792. mutation.get().each(function (target) {
  4793. hoverTable.each(function (table) {
  4794. getResizer(target, 'data-row').each(function (row) {
  4795. var delta = getDelta(target, 'top');
  4796. remove$7(target, 'data-initial-top');
  4797. events.trigger.adjustHeight(table, delta, parseInt(row, 10));
  4798. });
  4799. getResizer(target, 'data-column').each(function (column) {
  4800. var delta = getDelta(target, 'left');
  4801. remove$7(target, 'data-initial-left');
  4802. events.trigger.adjustWidth(table, delta, parseInt(column, 10));
  4803. });
  4804. refresh(wire, table);
  4805. });
  4806. });
  4807. });
  4808. var handler = function (target, dir) {
  4809. events.trigger.startAdjust();
  4810. mutation.assign(target);
  4811. set$2(target, 'data-initial-' + dir, getCssValue(target, dir));
  4812. add(target, resizeBarDragging);
  4813. set$1(target, 'opacity', '0.2');
  4814. resizing.go(wire.parent());
  4815. };
  4816. var mousedown = bind(wire.parent(), 'mousedown', function (event) {
  4817. if (isRowBar(event.target)) {
  4818. handler(event.target, 'top');
  4819. }
  4820. if (isColBar(event.target)) {
  4821. handler(event.target, 'left');
  4822. }
  4823. });
  4824. var isRoot = function (e) {
  4825. return eq$1(e, wire.view());
  4826. };
  4827. var findClosestEditableTable = function (target) {
  4828. return closest$1(target, 'table', isRoot).filter(isEditable$1);
  4829. };
  4830. var mouseover = bind(wire.view(), 'mouseover', function (event) {
  4831. findClosestEditableTable(event.target).fold(function () {
  4832. if (inBody(event.target)) {
  4833. destroy(wire);
  4834. }
  4835. }, function (table) {
  4836. hoverTable = Optional.some(table);
  4837. refresh(wire, table);
  4838. });
  4839. });
  4840. var destroy$1 = function () {
  4841. mousedown.unbind();
  4842. mouseover.unbind();
  4843. resizing.destroy();
  4844. destroy(wire);
  4845. };
  4846. var refresh$1 = function (tbl) {
  4847. refresh(wire, tbl);
  4848. };
  4849. var events = create$4({
  4850. adjustHeight: Event([
  4851. 'table',
  4852. 'delta',
  4853. 'row'
  4854. ]),
  4855. adjustWidth: Event([
  4856. 'table',
  4857. 'delta',
  4858. 'column'
  4859. ]),
  4860. startAdjust: Event([])
  4861. });
  4862. return {
  4863. destroy: destroy$1,
  4864. refresh: refresh$1,
  4865. on: resizing.on,
  4866. off: resizing.off,
  4867. hideBars: curry(hide, wire),
  4868. showBars: curry(show, wire),
  4869. events: events.registry
  4870. };
  4871. };
  4872. var create$3 = function (wire, resizing, lazySizing) {
  4873. var hdirection = height;
  4874. var vdirection = width;
  4875. var manager = BarManager(wire);
  4876. var events = create$4({
  4877. beforeResize: Event([
  4878. 'table',
  4879. 'type'
  4880. ]),
  4881. afterResize: Event([
  4882. 'table',
  4883. 'type'
  4884. ]),
  4885. startDrag: Event([])
  4886. });
  4887. manager.events.adjustHeight.bind(function (event) {
  4888. var table = event.table;
  4889. events.trigger.beforeResize(table, 'row');
  4890. var delta = hdirection.delta(event.delta, table);
  4891. adjustHeight(table, delta, event.row, hdirection);
  4892. events.trigger.afterResize(table, 'row');
  4893. });
  4894. manager.events.startAdjust.bind(function (_event) {
  4895. events.trigger.startDrag();
  4896. });
  4897. manager.events.adjustWidth.bind(function (event) {
  4898. var table = event.table;
  4899. events.trigger.beforeResize(table, 'col');
  4900. var delta = vdirection.delta(event.delta, table);
  4901. var tableSize = lazySizing(table);
  4902. adjustWidth(table, delta, event.column, resizing, tableSize);
  4903. events.trigger.afterResize(table, 'col');
  4904. });
  4905. return {
  4906. on: manager.on,
  4907. off: manager.off,
  4908. hideBars: manager.hideBars,
  4909. showBars: manager.showBars,
  4910. destroy: manager.destroy,
  4911. events: events.registry
  4912. };
  4913. };
  4914. var TableResize = { create: create$3 };
  4915. var fireNewRow = function (editor, row) {
  4916. return editor.fire('newrow', { node: row });
  4917. };
  4918. var fireNewCell = function (editor, cell) {
  4919. return editor.fire('newcell', { node: cell });
  4920. };
  4921. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  4922. editor.fire('ObjectResizeStart', {
  4923. target: target,
  4924. width: width,
  4925. height: height,
  4926. origin: origin
  4927. });
  4928. };
  4929. var fireObjectResized = function (editor, target, width, height, origin) {
  4930. editor.fire('ObjectResized', {
  4931. target: target,
  4932. width: width,
  4933. height: height,
  4934. origin: origin
  4935. });
  4936. };
  4937. var fireTableSelectionChange = function (editor, cells, start, finish, otherCells) {
  4938. editor.fire('TableSelectionChange', {
  4939. cells: cells,
  4940. start: start,
  4941. finish: finish,
  4942. otherCells: otherCells
  4943. });
  4944. };
  4945. var fireTableSelectionClear = function (editor) {
  4946. editor.fire('TableSelectionClear');
  4947. };
  4948. var fireTableModified = function (editor, table, data) {
  4949. editor.fire('TableModified', __assign(__assign({}, data), { table: table }));
  4950. };
  4951. var styleModified = {
  4952. structure: false,
  4953. style: true
  4954. };
  4955. var structureModified = {
  4956. structure: true,
  4957. style: false
  4958. };
  4959. var styleAndStructureModified = {
  4960. structure: true,
  4961. style: true
  4962. };
  4963. var defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
  4964. var defaultStyles = {
  4965. 'border-collapse': 'collapse',
  4966. 'width': '100%'
  4967. };
  4968. var defaultCellBorderWidths = range$1(5, function (i) {
  4969. var size = i + 1 + 'px';
  4970. return {
  4971. title: size,
  4972. value: size
  4973. };
  4974. });
  4975. var defaultCellBorderStyles = map$1([
  4976. 'Solid',
  4977. 'Dotted',
  4978. 'Dashed',
  4979. 'Double',
  4980. 'Groove',
  4981. 'Ridge',
  4982. 'Inset',
  4983. 'Outset',
  4984. 'None',
  4985. 'Hidden'
  4986. ], function (type) {
  4987. return {
  4988. title: type,
  4989. value: type.toLowerCase()
  4990. };
  4991. });
  4992. var determineDefaultStyles = function (editor) {
  4993. if (isPixelsForced(editor)) {
  4994. var editorWidth = editor.getBody().offsetWidth;
  4995. return __assign(__assign({}, defaultStyles), { width: editorWidth + 'px' });
  4996. } else if (isResponsiveForced(editor)) {
  4997. return filter$1(defaultStyles, function (_value, key) {
  4998. return key !== 'width';
  4999. });
  5000. } else {
  5001. return defaultStyles;
  5002. }
  5003. };
  5004. var defaultAttributes = { border: '1' };
  5005. var defaultColumnResizingBehaviour = 'preservetable';
  5006. var getTableSizingMode = function (editor) {
  5007. return editor.getParam('table_sizing_mode', 'auto');
  5008. };
  5009. var getTableResponseWidth = function (editor) {
  5010. return editor.getParam('table_responsive_width');
  5011. };
  5012. var getTableBorderWidths = function (editor) {
  5013. return editor.getParam('table_border_widths', defaultCellBorderWidths, 'array');
  5014. };
  5015. var getTableBorderStyles = function (editor) {
  5016. return editor.getParam('table_border_styles', defaultCellBorderStyles, 'array');
  5017. };
  5018. var getDefaultAttributes = function (editor) {
  5019. return editor.getParam('table_default_attributes', defaultAttributes, 'object');
  5020. };
  5021. var getDefaultStyles = function (editor) {
  5022. return editor.getParam('table_default_styles', determineDefaultStyles(editor), 'object');
  5023. };
  5024. var hasTableResizeBars = function (editor) {
  5025. return editor.getParam('table_resize_bars', true, 'boolean');
  5026. };
  5027. var hasTabNavigation = function (editor) {
  5028. return editor.getParam('table_tab_navigation', true, 'boolean');
  5029. };
  5030. var hasAdvancedCellTab = function (editor) {
  5031. return editor.getParam('table_cell_advtab', true, 'boolean');
  5032. };
  5033. var hasAdvancedRowTab = function (editor) {
  5034. return editor.getParam('table_row_advtab', true, 'boolean');
  5035. };
  5036. var hasAdvancedTableTab = function (editor) {
  5037. return editor.getParam('table_advtab', true, 'boolean');
  5038. };
  5039. var hasAppearanceOptions = function (editor) {
  5040. return editor.getParam('table_appearance_options', true, 'boolean');
  5041. };
  5042. var hasTableGrid = function (editor) {
  5043. return editor.getParam('table_grid', true, 'boolean');
  5044. };
  5045. var shouldStyleWithCss = function (editor) {
  5046. return editor.getParam('table_style_by_css', false, 'boolean');
  5047. };
  5048. var getCellClassList = function (editor) {
  5049. return editor.getParam('table_cell_class_list', [], 'array');
  5050. };
  5051. var getRowClassList = function (editor) {
  5052. return editor.getParam('table_row_class_list', [], 'array');
  5053. };
  5054. var getTableClassList = function (editor) {
  5055. return editor.getParam('table_class_list', [], 'array');
  5056. };
  5057. var isPercentagesForced = function (editor) {
  5058. return getTableSizingMode(editor) === 'relative' || getTableResponseWidth(editor) === true;
  5059. };
  5060. var isPixelsForced = function (editor) {
  5061. return getTableSizingMode(editor) === 'fixed' || getTableResponseWidth(editor) === false;
  5062. };
  5063. var isResponsiveForced = function (editor) {
  5064. return getTableSizingMode(editor) === 'responsive';
  5065. };
  5066. var getToolbar = function (editor) {
  5067. return editor.getParam('table_toolbar', defaultTableToolbar);
  5068. };
  5069. var useColumnGroup = function (editor) {
  5070. return editor.getParam('table_use_colgroups', false, 'boolean');
  5071. };
  5072. var getTableHeaderType = function (editor) {
  5073. var defaultValue = 'section';
  5074. var value = editor.getParam('table_header_type', defaultValue, 'string');
  5075. var validValues = [
  5076. 'section',
  5077. 'cells',
  5078. 'sectionCells',
  5079. 'auto'
  5080. ];
  5081. if (!contains$2(validValues, value)) {
  5082. return defaultValue;
  5083. } else {
  5084. return value;
  5085. }
  5086. };
  5087. var getColumnResizingBehaviour = function (editor) {
  5088. var validModes = [
  5089. 'preservetable',
  5090. 'resizetable'
  5091. ];
  5092. var givenMode = editor.getParam('table_column_resizing', defaultColumnResizingBehaviour, 'string');
  5093. return find$1(validModes, function (mode) {
  5094. return mode === givenMode;
  5095. }).getOr(defaultColumnResizingBehaviour);
  5096. };
  5097. var isPreserveTableColumnResizing = function (editor) {
  5098. return getColumnResizingBehaviour(editor) === 'preservetable';
  5099. };
  5100. var isResizeTableColumnResizing = function (editor) {
  5101. return getColumnResizingBehaviour(editor) === 'resizetable';
  5102. };
  5103. var getCloneElements = function (editor) {
  5104. var cloneElements = editor.getParam('table_clone_elements');
  5105. if (isString(cloneElements)) {
  5106. return Optional.some(cloneElements.split(/[ ,]/));
  5107. } else if (Array.isArray(cloneElements)) {
  5108. return Optional.some(cloneElements);
  5109. } else {
  5110. return Optional.none();
  5111. }
  5112. };
  5113. var hasObjectResizing = function (editor) {
  5114. var objectResizing = editor.getParam('object_resizing', true);
  5115. return isString(objectResizing) ? objectResizing === 'table' : objectResizing;
  5116. };
  5117. var getTableBackgroundColorMap = function (editor) {
  5118. return editor.getParam('table_background_color_map', [], 'array');
  5119. };
  5120. var getTableBorderColorMap = function (editor) {
  5121. return editor.getParam('table_border_color_map', [], 'array');
  5122. };
  5123. var get$4 = function (editor, table) {
  5124. if (isPercentagesForced(editor)) {
  5125. var width = getRawWidth(editor, table.dom).filter(isPercentage$1).getOrThunk(function () {
  5126. return getPercentTableWidth(table);
  5127. });
  5128. return TableSize.percentageSize(width, table);
  5129. } else if (isPixelsForced(editor)) {
  5130. return TableSize.pixelSize(get$8(table), table);
  5131. } else {
  5132. return TableSize.getTableSize(table);
  5133. }
  5134. };
  5135. var cleanupLegacyAttributes = function (element) {
  5136. remove$7(element, 'width');
  5137. };
  5138. var convertToPercentSize = function (table, tableSize) {
  5139. var newWidth = getPercentTableWidth$1(table);
  5140. redistribute(table, Optional.some(newWidth), Optional.none(), tableSize);
  5141. cleanupLegacyAttributes(table);
  5142. };
  5143. var convertToPixelSize = function (table, tableSize) {
  5144. var newWidth = getPixelTableWidth(table);
  5145. redistribute(table, Optional.some(newWidth), Optional.none(), tableSize);
  5146. cleanupLegacyAttributes(table);
  5147. };
  5148. var convertToNoneSize = function (table) {
  5149. remove$6(table, 'width');
  5150. var columns = columns$1(table);
  5151. var rowElements = columns.length > 0 ? columns : cells$1(table);
  5152. each$2(rowElements, function (cell) {
  5153. remove$6(cell, 'width');
  5154. cleanupLegacyAttributes(cell);
  5155. });
  5156. cleanupLegacyAttributes(table);
  5157. };
  5158. var enforcePercentage = function (editor, table) {
  5159. var tableSizing = get$4(editor, table);
  5160. convertToPercentSize(table, tableSizing);
  5161. };
  5162. var enforcePixels = function (editor, table) {
  5163. var tableSizing = get$4(editor, table);
  5164. convertToPixelSize(table, tableSizing);
  5165. };
  5166. var enforceNone = convertToNoneSize;
  5167. var syncPixels = function (table) {
  5168. var warehouse = Warehouse.fromTable(table);
  5169. if (!Warehouse.hasColumns(warehouse)) {
  5170. each$2(cells$1(table), function (cell) {
  5171. var computedWidth = get$a(cell, 'width');
  5172. set$1(cell, 'width', computedWidth);
  5173. remove$7(cell, 'width');
  5174. });
  5175. }
  5176. };
  5177. var createContainer = function () {
  5178. var container = SugarElement.fromTag('div');
  5179. setAll(container, {
  5180. position: 'static',
  5181. height: '0',
  5182. width: '0',
  5183. padding: '0',
  5184. margin: '0',
  5185. border: '0'
  5186. });
  5187. append$1(body$1(), container);
  5188. return container;
  5189. };
  5190. var get$3 = function (editor, isResizable) {
  5191. return editor.inline ? ResizeWire.body(getBody(editor), createContainer(), isResizable) : ResizeWire.only(SugarElement.fromDom(editor.getDoc()), isResizable);
  5192. };
  5193. var remove$1 = function (editor, wire) {
  5194. if (editor.inline) {
  5195. remove$5(wire.parent());
  5196. }
  5197. };
  5198. var barResizerPrefix = 'bar-';
  5199. var isResizable = function (elm) {
  5200. return get$b(elm, 'data-mce-resize') !== 'false';
  5201. };
  5202. var getResizeHandler = function (editor) {
  5203. var selectionRng = Optional.none();
  5204. var resize = Optional.none();
  5205. var wire = Optional.none();
  5206. var startW;
  5207. var startRawW;
  5208. var isTable = function (elm) {
  5209. return elm.nodeName === 'TABLE';
  5210. };
  5211. var lazyResize = function () {
  5212. return resize;
  5213. };
  5214. var lazyWire = function () {
  5215. return wire.getOr(ResizeWire.only(SugarElement.fromDom(editor.getBody()), isResizable));
  5216. };
  5217. var lazySizing = function (table) {
  5218. return get$4(editor, table);
  5219. };
  5220. var lazyResizingBehaviour = function () {
  5221. return isPreserveTableColumnResizing(editor) ? preserveTable() : resizeTable();
  5222. };
  5223. var getNumColumns = function (table) {
  5224. return getGridSize(table).columns;
  5225. };
  5226. var afterCornerResize = function (table, origin, width) {
  5227. var isRightEdgeResize = endsWith(origin, 'e');
  5228. if (startRawW === '') {
  5229. enforcePercentage(editor, table);
  5230. }
  5231. if (width !== startW && startRawW !== '') {
  5232. set$1(table, 'width', startRawW);
  5233. var resizing = lazyResizingBehaviour();
  5234. var tableSize = lazySizing(table);
  5235. var col = isPreserveTableColumnResizing(editor) || isRightEdgeResize ? getNumColumns(table) - 1 : 0;
  5236. adjustWidth(table, width - startW, col, resizing, tableSize);
  5237. } else if (isPercentage$1(startRawW)) {
  5238. var percentW = parseFloat(startRawW.replace('%', ''));
  5239. var targetPercentW = width * percentW / startW;
  5240. set$1(table, 'width', targetPercentW + '%');
  5241. }
  5242. if (isPixel(startRawW)) {
  5243. syncPixels(table);
  5244. }
  5245. };
  5246. var destroy = function () {
  5247. resize.each(function (sz) {
  5248. sz.destroy();
  5249. });
  5250. wire.each(function (w) {
  5251. remove$1(editor, w);
  5252. });
  5253. };
  5254. editor.on('init', function () {
  5255. var rawWire = get$3(editor, isResizable);
  5256. wire = Optional.some(rawWire);
  5257. if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
  5258. var resizing = lazyResizingBehaviour();
  5259. var sz = TableResize.create(rawWire, resizing, lazySizing);
  5260. sz.on();
  5261. sz.events.startDrag.bind(function (_event) {
  5262. selectionRng = Optional.some(editor.selection.getRng());
  5263. });
  5264. sz.events.beforeResize.bind(function (event) {
  5265. var rawTable = event.table.dom;
  5266. fireObjectResizeStart(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
  5267. });
  5268. sz.events.afterResize.bind(function (event) {
  5269. var table = event.table;
  5270. var rawTable = table.dom;
  5271. removeDataStyle(table);
  5272. selectionRng.each(function (rng) {
  5273. editor.selection.setRng(rng);
  5274. editor.focus();
  5275. });
  5276. fireObjectResized(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
  5277. editor.undoManager.add();
  5278. });
  5279. resize = Optional.some(sz);
  5280. }
  5281. });
  5282. editor.on('ObjectResizeStart', function (e) {
  5283. var targetElm = e.target;
  5284. if (isTable(targetElm)) {
  5285. var table = SugarElement.fromDom(targetElm);
  5286. each$2(editor.dom.select('.mce-clonedresizable'), function (clone) {
  5287. editor.dom.addClass(clone, 'mce-' + getColumnResizingBehaviour(editor) + '-columns');
  5288. });
  5289. if (!isPixelSizing(table) && isPixelsForced(editor)) {
  5290. enforcePixels(editor, table);
  5291. } else if (!isPercentSizing(table) && isPercentagesForced(editor)) {
  5292. enforcePercentage(editor, table);
  5293. }
  5294. if (isNoneSizing(table) && startsWith(e.origin, barResizerPrefix)) {
  5295. enforcePercentage(editor, table);
  5296. }
  5297. startW = e.width;
  5298. startRawW = isResponsiveForced(editor) ? '' : getRawWidth(editor, targetElm).getOr('');
  5299. }
  5300. });
  5301. editor.on('ObjectResized', function (e) {
  5302. var targetElm = e.target;
  5303. if (isTable(targetElm)) {
  5304. var table = SugarElement.fromDom(targetElm);
  5305. var origin_1 = e.origin;
  5306. if (startsWith(origin_1, 'corner-')) {
  5307. afterCornerResize(table, origin_1, e.width);
  5308. }
  5309. removeDataStyle(table);
  5310. fireTableModified(editor, table.dom, styleModified);
  5311. }
  5312. });
  5313. editor.on('SwitchMode', function () {
  5314. lazyResize().each(function (resize) {
  5315. if (editor.mode.isReadOnly()) {
  5316. resize.hideBars();
  5317. } else {
  5318. resize.showBars();
  5319. }
  5320. });
  5321. });
  5322. return {
  5323. lazyResize: lazyResize,
  5324. lazyWire: lazyWire,
  5325. destroy: destroy
  5326. };
  5327. };
  5328. var point = function (element, offset) {
  5329. return {
  5330. element: element,
  5331. offset: offset
  5332. };
  5333. };
  5334. var scan$1 = function (universe, element, direction) {
  5335. if (universe.property().isText(element) && universe.property().getText(element).trim().length === 0 || universe.property().isComment(element)) {
  5336. return direction(element).bind(function (elem) {
  5337. return scan$1(universe, elem, direction).orThunk(function () {
  5338. return Optional.some(elem);
  5339. });
  5340. });
  5341. } else {
  5342. return Optional.none();
  5343. }
  5344. };
  5345. var toEnd = function (universe, element) {
  5346. if (universe.property().isText(element)) {
  5347. return universe.property().getText(element).length;
  5348. }
  5349. var children = universe.property().children(element);
  5350. return children.length;
  5351. };
  5352. var freefallRtl$2 = function (universe, element) {
  5353. var candidate = scan$1(universe, element, universe.query().prevSibling).getOr(element);
  5354. if (universe.property().isText(candidate)) {
  5355. return point(candidate, toEnd(universe, candidate));
  5356. }
  5357. var children = universe.property().children(candidate);
  5358. return children.length > 0 ? freefallRtl$2(universe, children[children.length - 1]) : point(candidate, toEnd(universe, candidate));
  5359. };
  5360. var freefallRtl$1 = freefallRtl$2;
  5361. var universe$2 = DomUniverse();
  5362. var freefallRtl = function (element) {
  5363. return freefallRtl$1(universe$2, element);
  5364. };
  5365. var halve = function (main, other) {
  5366. var colspan = getSpan(main, 'colspan');
  5367. if (colspan === 1) {
  5368. var width = getGenericWidth(main);
  5369. width.each(function (w) {
  5370. var newWidth = w.value / 2;
  5371. setGenericWidth(main, newWidth, w.unit);
  5372. setGenericWidth(other, newWidth, w.unit);
  5373. });
  5374. }
  5375. };
  5376. var isTableHeaderCell = isTag('th');
  5377. var getRowHeaderType = function (isHeaderRow, isHeaderCells) {
  5378. if (isHeaderRow && isHeaderCells) {
  5379. return 'sectionCells';
  5380. } else if (isHeaderRow) {
  5381. return 'section';
  5382. } else {
  5383. return 'cells';
  5384. }
  5385. };
  5386. var getRowType$1 = function (row) {
  5387. var isHeaderRow = row.section === 'thead';
  5388. var isHeaderCells = is(findCommonCellType(row.cells), 'th');
  5389. if (isHeaderRow || isHeaderCells) {
  5390. return {
  5391. type: 'header',
  5392. subType: getRowHeaderType(isHeaderRow, isHeaderCells)
  5393. };
  5394. } else if (row.section === 'tfoot') {
  5395. return { type: 'footer' };
  5396. } else {
  5397. return { type: 'body' };
  5398. }
  5399. };
  5400. var findCommonCellType = function (cells) {
  5401. var headerCells = filter$2(cells, function (cell) {
  5402. return isTableHeaderCell(cell.element);
  5403. });
  5404. if (headerCells.length === 0) {
  5405. return Optional.some('td');
  5406. } else if (headerCells.length === cells.length) {
  5407. return Optional.some('th');
  5408. } else {
  5409. return Optional.none();
  5410. }
  5411. };
  5412. var findCommonRowType = function (rows) {
  5413. var rowTypes = map$1(rows, function (row) {
  5414. return getRowType$1(row).type;
  5415. });
  5416. var hasHeader = contains$2(rowTypes, 'header');
  5417. var hasFooter = contains$2(rowTypes, 'footer');
  5418. if (!hasHeader && !hasFooter) {
  5419. return Optional.some('body');
  5420. } else {
  5421. var hasBody = contains$2(rowTypes, 'body');
  5422. if (hasHeader && !hasBody && !hasFooter) {
  5423. return Optional.some('header');
  5424. } else if (!hasHeader && !hasBody && hasFooter) {
  5425. return Optional.some('footer');
  5426. } else {
  5427. return Optional.none();
  5428. }
  5429. }
  5430. };
  5431. var findTableRowHeaderType = function (warehouse) {
  5432. return findMap(warehouse.all, function (row) {
  5433. var rowType = getRowType$1(row);
  5434. return rowType.type === 'header' ? Optional.from(rowType.subType) : Optional.none();
  5435. });
  5436. };
  5437. var transformCell = function (cell, comparator, substitution) {
  5438. return elementnew(substitution(cell.element, comparator), true, cell.isLocked);
  5439. };
  5440. var transformRow = function (row, section) {
  5441. return row.section !== section ? rowcells(row.element, row.cells, section, row.isNew) : row;
  5442. };
  5443. var section = function () {
  5444. return {
  5445. transformRow: transformRow,
  5446. transformCell: function (cell, comparator, substitution) {
  5447. var newCell = substitution(cell.element, comparator);
  5448. var fixedCell = name(newCell) !== 'td' ? mutate$1(newCell, 'td') : newCell;
  5449. return elementnew(fixedCell, cell.isNew, cell.isLocked);
  5450. }
  5451. };
  5452. };
  5453. var sectionCells = function () {
  5454. return {
  5455. transformRow: transformRow,
  5456. transformCell: transformCell
  5457. };
  5458. };
  5459. var cells = function () {
  5460. return {
  5461. transformRow: function (row, section) {
  5462. var newSection = section === 'thead' ? 'tbody' : section;
  5463. return transformRow(row, newSection);
  5464. },
  5465. transformCell: transformCell
  5466. };
  5467. };
  5468. var fallback = function () {
  5469. return {
  5470. transformRow: identity,
  5471. transformCell: transformCell
  5472. };
  5473. };
  5474. var getTableSectionType = function (table, fallback) {
  5475. var warehouse = Warehouse.fromTable(table);
  5476. var type = findTableRowHeaderType(warehouse).getOr(fallback);
  5477. switch (type) {
  5478. case 'section':
  5479. return section();
  5480. case 'sectionCells':
  5481. return sectionCells();
  5482. case 'cells':
  5483. return cells();
  5484. }
  5485. };
  5486. var TableSection = {
  5487. getTableSectionType: getTableSectionType,
  5488. section: section,
  5489. sectionCells: sectionCells,
  5490. cells: cells,
  5491. fallback: fallback
  5492. };
  5493. var setIfNot = function (element, property, value, ignore) {
  5494. if (value === ignore) {
  5495. remove$7(element, property);
  5496. } else {
  5497. set$2(element, property, value);
  5498. }
  5499. };
  5500. var insert$1 = function (table, selector, element) {
  5501. last$2(children$1(table, selector)).fold(function () {
  5502. return prepend(table, element);
  5503. }, function (child) {
  5504. return after$5(child, element);
  5505. });
  5506. };
  5507. var generateSection = function (table, sectionName) {
  5508. var section = child$1(table, sectionName).getOrThunk(function () {
  5509. var newSection = SugarElement.fromTag(sectionName, owner(table).dom);
  5510. if (sectionName === 'thead') {
  5511. insert$1(table, 'caption,colgroup', newSection);
  5512. } else if (sectionName === 'colgroup') {
  5513. insert$1(table, 'caption', newSection);
  5514. } else {
  5515. append$1(table, newSection);
  5516. }
  5517. return newSection;
  5518. });
  5519. empty(section);
  5520. return section;
  5521. };
  5522. var render$1 = function (table, grid) {
  5523. var newRows = [];
  5524. var newCells = [];
  5525. var syncRows = function (gridSection) {
  5526. return map$1(gridSection, function (row) {
  5527. if (row.isNew) {
  5528. newRows.push(row.element);
  5529. }
  5530. var tr = row.element;
  5531. empty(tr);
  5532. each$2(row.cells, function (cell) {
  5533. if (cell.isNew) {
  5534. newCells.push(cell.element);
  5535. }
  5536. setIfNot(cell.element, 'colspan', cell.colspan, 1);
  5537. setIfNot(cell.element, 'rowspan', cell.rowspan, 1);
  5538. append$1(tr, cell.element);
  5539. });
  5540. return tr;
  5541. });
  5542. };
  5543. var syncColGroup = function (gridSection) {
  5544. return bind$2(gridSection, function (colGroup) {
  5545. return map$1(colGroup.cells, function (col) {
  5546. setIfNot(col.element, 'span', col.colspan, 1);
  5547. return col.element;
  5548. });
  5549. });
  5550. };
  5551. var renderSection = function (gridSection, sectionName) {
  5552. var section = generateSection(table, sectionName);
  5553. var sync = sectionName === 'colgroup' ? syncColGroup : syncRows;
  5554. var sectionElems = sync(gridSection);
  5555. append(section, sectionElems);
  5556. };
  5557. var removeSection = function (sectionName) {
  5558. child$1(table, sectionName).each(remove$5);
  5559. };
  5560. var renderOrRemoveSection = function (gridSection, sectionName) {
  5561. if (gridSection.length > 0) {
  5562. renderSection(gridSection, sectionName);
  5563. } else {
  5564. removeSection(sectionName);
  5565. }
  5566. };
  5567. var headSection = [];
  5568. var bodySection = [];
  5569. var footSection = [];
  5570. var columnGroupsSection = [];
  5571. each$2(grid, function (row) {
  5572. switch (row.section) {
  5573. case 'thead':
  5574. headSection.push(row);
  5575. break;
  5576. case 'tbody':
  5577. bodySection.push(row);
  5578. break;
  5579. case 'tfoot':
  5580. footSection.push(row);
  5581. break;
  5582. case 'colgroup':
  5583. columnGroupsSection.push(row);
  5584. break;
  5585. }
  5586. });
  5587. renderOrRemoveSection(columnGroupsSection, 'colgroup');
  5588. renderOrRemoveSection(headSection, 'thead');
  5589. renderOrRemoveSection(bodySection, 'tbody');
  5590. renderOrRemoveSection(footSection, 'tfoot');
  5591. return {
  5592. newRows: newRows,
  5593. newCells: newCells
  5594. };
  5595. };
  5596. var copy = function (grid) {
  5597. return map$1(grid, function (row) {
  5598. var tr = shallow(row.element);
  5599. each$2(row.cells, function (cell) {
  5600. var clonedCell = deep(cell.element);
  5601. setIfNot(clonedCell, 'colspan', cell.colspan, 1);
  5602. setIfNot(clonedCell, 'rowspan', cell.rowspan, 1);
  5603. append$1(tr, clonedCell);
  5604. });
  5605. return tr;
  5606. });
  5607. };
  5608. var getColumn = function (grid, index) {
  5609. return map$1(grid, function (row) {
  5610. return getCell(row, index);
  5611. });
  5612. };
  5613. var getRow = function (grid, index) {
  5614. return grid[index];
  5615. };
  5616. var findDiff = function (xs, comp) {
  5617. if (xs.length === 0) {
  5618. return 0;
  5619. }
  5620. var first = xs[0];
  5621. var index = findIndex(xs, function (x) {
  5622. return !comp(first.element, x.element);
  5623. });
  5624. return index.getOr(xs.length);
  5625. };
  5626. var subgrid = function (grid, row, column, comparator) {
  5627. var restOfRow = getRow(grid, row).cells.slice(column);
  5628. var endColIndex = findDiff(restOfRow, comparator);
  5629. var restOfColumn = getColumn(grid, column).slice(row);
  5630. var endRowIndex = findDiff(restOfColumn, comparator);
  5631. return {
  5632. colspan: endColIndex,
  5633. rowspan: endRowIndex
  5634. };
  5635. };
  5636. var toDetails = function (grid, comparator) {
  5637. var seen = map$1(grid, function (row) {
  5638. return map$1(row.cells, never);
  5639. });
  5640. var updateSeen = function (rowIndex, columnIndex, rowspan, colspan) {
  5641. for (var row = rowIndex; row < rowIndex + rowspan; row++) {
  5642. for (var column = columnIndex; column < columnIndex + colspan; column++) {
  5643. seen[row][column] = true;
  5644. }
  5645. }
  5646. };
  5647. return map$1(grid, function (row, rowIndex) {
  5648. var details = bind$2(row.cells, function (cell, columnIndex) {
  5649. if (seen[rowIndex][columnIndex] === false) {
  5650. var result = subgrid(grid, rowIndex, columnIndex, comparator);
  5651. updateSeen(rowIndex, columnIndex, result.rowspan, result.colspan);
  5652. return [detailnew(cell.element, result.rowspan, result.colspan, cell.isNew)];
  5653. } else {
  5654. return [];
  5655. }
  5656. });
  5657. return rowdetailnew(row.element, details, row.section, row.isNew);
  5658. });
  5659. };
  5660. var toGrid = function (warehouse, generators, isNew) {
  5661. var grid = [];
  5662. each$2(warehouse.colgroups, function (colgroup) {
  5663. var cols = map$1(colgroup.columns, function (column) {
  5664. return elementnew(column.element, isNew, false);
  5665. });
  5666. grid.push(rowcells(colgroup.element, cols, 'colgroup', isNew));
  5667. });
  5668. for (var rowIndex = 0; rowIndex < warehouse.grid.rows; rowIndex++) {
  5669. var rowCells = [];
  5670. for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
  5671. var element = Warehouse.getAt(warehouse, rowIndex, columnIndex).map(function (item) {
  5672. return elementnew(item.element, isNew, item.isLocked);
  5673. }).getOrThunk(function () {
  5674. return elementnew(generators.gap(), true, false);
  5675. });
  5676. rowCells.push(element);
  5677. }
  5678. var rowDetail = warehouse.all[rowIndex];
  5679. var row = rowcells(rowDetail.element, rowCells, rowDetail.section, isNew);
  5680. grid.push(row);
  5681. }
  5682. return grid;
  5683. };
  5684. var fromWarehouse = function (warehouse, generators) {
  5685. return toGrid(warehouse, generators, false);
  5686. };
  5687. var toDetailList = function (grid) {
  5688. return toDetails(grid, eq$1);
  5689. };
  5690. var findInWarehouse = function (warehouse, element) {
  5691. return findMap(warehouse.all, function (r) {
  5692. return find$1(r.cells, function (e) {
  5693. return eq$1(element, e.element);
  5694. });
  5695. });
  5696. };
  5697. var extractCells = function (warehouse, target, predicate) {
  5698. var details = map$1(target.selection, function (cell$1) {
  5699. return cell(cell$1).bind(function (lc) {
  5700. return findInWarehouse(warehouse, lc);
  5701. }).filter(predicate);
  5702. });
  5703. var cells = cat(details);
  5704. return someIf(cells.length > 0, cells);
  5705. };
  5706. var run = function (operation, extract, adjustment, postAction, genWrappers) {
  5707. return function (wire, table, target, generators, behaviours) {
  5708. var warehouse = Warehouse.fromTable(table);
  5709. var tableSection = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.section).getOrThunk(TableSection.fallback);
  5710. var output = extract(warehouse, target).map(function (info) {
  5711. var model = fromWarehouse(warehouse, generators);
  5712. var result = operation(model, info, eq$1, genWrappers(generators), tableSection);
  5713. var lockedColumns = getLockedColumnsFromGrid(result.grid);
  5714. var grid = toDetailList(result.grid);
  5715. return {
  5716. info: info,
  5717. grid: grid,
  5718. cursor: result.cursor,
  5719. lockedColumns: lockedColumns
  5720. };
  5721. });
  5722. return output.bind(function (out) {
  5723. var newElements = render$1(table, out.grid);
  5724. var tableSizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.sizing).getOrThunk(function () {
  5725. return TableSize.getTableSize(table);
  5726. });
  5727. var resizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.resize).getOrThunk(preserveTable);
  5728. adjustment(table, out.grid, out.info, {
  5729. sizing: tableSizing,
  5730. resize: resizing,
  5731. section: tableSection
  5732. });
  5733. postAction(table);
  5734. refresh(wire, table);
  5735. remove$7(table, LOCKED_COL_ATTR);
  5736. if (out.lockedColumns.length > 0) {
  5737. set$2(table, LOCKED_COL_ATTR, out.lockedColumns.join(','));
  5738. }
  5739. return Optional.some({
  5740. cursor: out.cursor,
  5741. newRows: newElements.newRows,
  5742. newCells: newElements.newCells
  5743. });
  5744. });
  5745. };
  5746. };
  5747. var onPaste = function (warehouse, target) {
  5748. return cell(target.element).bind(function (cell) {
  5749. return findInWarehouse(warehouse, cell).map(function (details) {
  5750. var value = __assign(__assign({}, details), {
  5751. generators: target.generators,
  5752. clipboard: target.clipboard
  5753. });
  5754. return value;
  5755. });
  5756. });
  5757. };
  5758. var onPasteByEditor = function (warehouse, target) {
  5759. return extractCells(warehouse, target, always).map(function (cells) {
  5760. return {
  5761. cells: cells,
  5762. generators: target.generators,
  5763. clipboard: target.clipboard
  5764. };
  5765. });
  5766. };
  5767. var onMergable = function (_warehouse, target) {
  5768. return target.mergable;
  5769. };
  5770. var onUnmergable = function (_warehouse, target) {
  5771. return target.unmergable;
  5772. };
  5773. var onCells = function (warehouse, target) {
  5774. return extractCells(warehouse, target, always);
  5775. };
  5776. var onUnlockedCells = function (warehouse, target) {
  5777. return extractCells(warehouse, target, function (detail) {
  5778. return !detail.isLocked;
  5779. });
  5780. };
  5781. var isUnlockedTableCell = function (warehouse, cell) {
  5782. return findInWarehouse(warehouse, cell).exists(function (detail) {
  5783. return !detail.isLocked;
  5784. });
  5785. };
  5786. var allUnlocked = function (warehouse, cells) {
  5787. return forall(cells, function (cell) {
  5788. return isUnlockedTableCell(warehouse, cell);
  5789. });
  5790. };
  5791. var onUnlockedMergable = function (warehouse, target) {
  5792. return onMergable(warehouse, target).filter(function (mergeable) {
  5793. return allUnlocked(warehouse, mergeable.cells);
  5794. });
  5795. };
  5796. var onUnlockedUnmergable = function (warehouse, target) {
  5797. return onUnmergable(warehouse, target).filter(function (cells) {
  5798. return allUnlocked(warehouse, cells);
  5799. });
  5800. };
  5801. var merge$2 = function (grid, bounds, comparator, substitution) {
  5802. var rows = extractGridDetails(grid).rows;
  5803. if (rows.length === 0) {
  5804. return grid;
  5805. }
  5806. for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
  5807. for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
  5808. var row = rows[i];
  5809. var isLocked = getCell(row, j).isLocked;
  5810. mutateCell(row, j, elementnew(substitution(), false, isLocked));
  5811. }
  5812. }
  5813. return grid;
  5814. };
  5815. var unmerge = function (grid, target, comparator, substitution) {
  5816. var rows = extractGridDetails(grid).rows;
  5817. var first = true;
  5818. for (var i = 0; i < rows.length; i++) {
  5819. for (var j = 0; j < cellLength(rows[0]); j++) {
  5820. var row = rows[i];
  5821. var currentCell = getCell(row, j);
  5822. var currentCellElm = currentCell.element;
  5823. var isToReplace = comparator(currentCellElm, target);
  5824. if (isToReplace === true && first === false) {
  5825. mutateCell(row, j, elementnew(substitution(), true, currentCell.isLocked));
  5826. } else if (isToReplace === true) {
  5827. first = false;
  5828. }
  5829. }
  5830. }
  5831. return grid;
  5832. };
  5833. var uniqueCells = function (row, comparator) {
  5834. return foldl(row, function (rest, cell) {
  5835. return exists(rest, function (currentCell) {
  5836. return comparator(currentCell.element, cell.element);
  5837. }) ? rest : rest.concat([cell]);
  5838. }, []);
  5839. };
  5840. var splitCols = function (grid, index, comparator, substitution) {
  5841. if (index > 0 && index < grid[0].cells.length) {
  5842. each$2(grid, function (row) {
  5843. var prevCell = row.cells[index - 1];
  5844. var current = row.cells[index];
  5845. var isToReplace = comparator(current.element, prevCell.element);
  5846. if (isToReplace) {
  5847. mutateCell(row, index, elementnew(substitution(), true, current.isLocked));
  5848. }
  5849. });
  5850. }
  5851. return grid;
  5852. };
  5853. var splitRows = function (grid, index, comparator, substitution) {
  5854. var rows = extractGridDetails(grid).rows;
  5855. if (index > 0 && index < rows.length) {
  5856. var rowPrevCells = rows[index - 1].cells;
  5857. var cells = uniqueCells(rowPrevCells, comparator);
  5858. each$2(cells, function (cell) {
  5859. var replacement = Optional.none();
  5860. for (var i = index; i < rows.length; i++) {
  5861. var _loop_1 = function (j) {
  5862. var row = rows[i];
  5863. var current = getCell(row, j);
  5864. var isToReplace = comparator(current.element, cell.element);
  5865. if (isToReplace) {
  5866. if (replacement.isNone()) {
  5867. replacement = Optional.some(substitution());
  5868. }
  5869. replacement.each(function (sub) {
  5870. mutateCell(row, j, elementnew(sub, true, current.isLocked));
  5871. });
  5872. }
  5873. };
  5874. for (var j = 0; j < cellLength(rows[0]); j++) {
  5875. _loop_1(j);
  5876. }
  5877. }
  5878. });
  5879. }
  5880. return grid;
  5881. };
  5882. var value$1 = function (o) {
  5883. var or = function (_opt) {
  5884. return value$1(o);
  5885. };
  5886. var orThunk = function (_f) {
  5887. return value$1(o);
  5888. };
  5889. var map = function (f) {
  5890. return value$1(f(o));
  5891. };
  5892. var mapError = function (_f) {
  5893. return value$1(o);
  5894. };
  5895. var each = function (f) {
  5896. f(o);
  5897. };
  5898. var bind = function (f) {
  5899. return f(o);
  5900. };
  5901. var fold = function (_, onValue) {
  5902. return onValue(o);
  5903. };
  5904. var exists = function (f) {
  5905. return f(o);
  5906. };
  5907. var forall = function (f) {
  5908. return f(o);
  5909. };
  5910. var toOptional = function () {
  5911. return Optional.some(o);
  5912. };
  5913. return {
  5914. isValue: always,
  5915. isError: never,
  5916. getOr: constant(o),
  5917. getOrThunk: constant(o),
  5918. getOrDie: constant(o),
  5919. or: or,
  5920. orThunk: orThunk,
  5921. fold: fold,
  5922. map: map,
  5923. mapError: mapError,
  5924. each: each,
  5925. bind: bind,
  5926. exists: exists,
  5927. forall: forall,
  5928. toOptional: toOptional
  5929. };
  5930. };
  5931. var error = function (message) {
  5932. var getOrThunk = function (f) {
  5933. return f();
  5934. };
  5935. var getOrDie = function () {
  5936. return die(String(message))();
  5937. };
  5938. var or = identity;
  5939. var orThunk = function (f) {
  5940. return f();
  5941. };
  5942. var map = function (_f) {
  5943. return error(message);
  5944. };
  5945. var mapError = function (f) {
  5946. return error(f(message));
  5947. };
  5948. var bind = function (_f) {
  5949. return error(message);
  5950. };
  5951. var fold = function (onError, _) {
  5952. return onError(message);
  5953. };
  5954. return {
  5955. isValue: never,
  5956. isError: always,
  5957. getOr: identity,
  5958. getOrThunk: getOrThunk,
  5959. getOrDie: getOrDie,
  5960. or: or,
  5961. orThunk: orThunk,
  5962. fold: fold,
  5963. map: map,
  5964. mapError: mapError,
  5965. each: noop,
  5966. bind: bind,
  5967. exists: never,
  5968. forall: always,
  5969. toOptional: Optional.none
  5970. };
  5971. };
  5972. var fromOption = function (opt, err) {
  5973. return opt.fold(function () {
  5974. return error(err);
  5975. }, value$1);
  5976. };
  5977. var Result = {
  5978. value: value$1,
  5979. error: error,
  5980. fromOption: fromOption
  5981. };
  5982. var measure = function (startAddress, gridA, gridB) {
  5983. if (startAddress.row >= gridA.length || startAddress.column > cellLength(gridA[0])) {
  5984. return Result.error('invalid start address out of table bounds, row: ' + startAddress.row + ', column: ' + startAddress.column);
  5985. }
  5986. var rowRemainder = gridA.slice(startAddress.row);
  5987. var colRemainder = rowRemainder[0].cells.slice(startAddress.column);
  5988. var colRequired = cellLength(gridB[0]);
  5989. var rowRequired = gridB.length;
  5990. return Result.value({
  5991. rowDelta: rowRemainder.length - rowRequired,
  5992. colDelta: colRemainder.length - colRequired
  5993. });
  5994. };
  5995. var measureWidth = function (gridA, gridB) {
  5996. var colLengthA = cellLength(gridA[0]);
  5997. var colLengthB = cellLength(gridB[0]);
  5998. return {
  5999. rowDelta: 0,
  6000. colDelta: colLengthA - colLengthB
  6001. };
  6002. };
  6003. var measureHeight = function (gridA, gridB) {
  6004. var rowLengthA = gridA.length;
  6005. var rowLengthB = gridB.length;
  6006. return {
  6007. rowDelta: rowLengthA - rowLengthB,
  6008. colDelta: 0
  6009. };
  6010. };
  6011. var generateElements = function (amount, row, generators, isLocked) {
  6012. var generator = row.section === 'colgroup' ? generators.col : generators.cell;
  6013. return range$1(amount, function (idx) {
  6014. return elementnew(generator(), true, isLocked(idx));
  6015. });
  6016. };
  6017. var rowFill = function (grid, amount, generators, lockedColumns) {
  6018. var exampleRow = grid[grid.length - 1];
  6019. return grid.concat(range$1(amount, function () {
  6020. var generator = exampleRow.section === 'colgroup' ? generators.colgroup : generators.row;
  6021. var row = clone$1(exampleRow, generator, identity);
  6022. var elements = generateElements(row.cells.length, row, generators, function (idx) {
  6023. return has$1(lockedColumns, idx.toString());
  6024. });
  6025. return setCells(row, elements);
  6026. }));
  6027. };
  6028. var colFill = function (grid, amount, generators, startIndex) {
  6029. return map$1(grid, function (row) {
  6030. var newChildren = generateElements(amount, row, generators, never);
  6031. return addCells(row, startIndex, newChildren);
  6032. });
  6033. };
  6034. var lockedColFill = function (grid, generators, lockedColumns) {
  6035. return map$1(grid, function (row) {
  6036. return foldl(lockedColumns, function (acc, colNum) {
  6037. var newChild = generateElements(1, row, generators, always)[0];
  6038. return addCell(acc, colNum, newChild);
  6039. }, row);
  6040. });
  6041. };
  6042. var tailor = function (gridA, delta, generators) {
  6043. var fillCols = delta.colDelta < 0 ? colFill : identity;
  6044. var fillRows = delta.rowDelta < 0 ? rowFill : identity;
  6045. var lockedColumns = getLockedColumnsFromGrid(gridA);
  6046. var gridWidth = cellLength(gridA[0]);
  6047. var isLastColLocked = exists(lockedColumns, function (locked) {
  6048. return locked === gridWidth - 1;
  6049. });
  6050. var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta), generators, isLastColLocked ? gridWidth - 1 : gridWidth);
  6051. var newLockedColumns = getLockedColumnsFromGrid(modifiedCols);
  6052. return fillRows(modifiedCols, Math.abs(delta.rowDelta), generators, mapToObject(newLockedColumns, always));
  6053. };
  6054. var isSpanning = function (grid, row, col, comparator) {
  6055. var candidate = getCell(grid[row], col);
  6056. var matching = curry(comparator, candidate.element);
  6057. var currentRow = grid[row];
  6058. 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)));
  6059. };
  6060. var mergeTables = function (startAddress, gridA, gridB, generator, comparator, lockedColumns) {
  6061. var startRow = startAddress.row;
  6062. var startCol = startAddress.column;
  6063. var mergeHeight = gridB.length;
  6064. var mergeWidth = cellLength(gridB[0]);
  6065. var endRow = startRow + mergeHeight;
  6066. var endCol = startCol + mergeWidth + lockedColumns.length;
  6067. var lockedColumnObj = mapToObject(lockedColumns, always);
  6068. for (var r = startRow; r < endRow; r++) {
  6069. var skippedCol = 0;
  6070. for (var c = startCol; c < endCol; c++) {
  6071. if (lockedColumnObj[c]) {
  6072. skippedCol++;
  6073. continue;
  6074. }
  6075. if (isSpanning(gridA, r, c, comparator)) {
  6076. unmerge(gridA, getCellElement(gridA[r], c), comparator, generator.cell);
  6077. }
  6078. var gridBColIndex = c - startCol - skippedCol;
  6079. var newCell = getCell(gridB[r - startRow], gridBColIndex);
  6080. var newCellElm = newCell.element;
  6081. var replacement = generator.replace(newCellElm);
  6082. mutateCell(gridA[r], c, elementnew(replacement, true, newCell.isLocked));
  6083. }
  6084. }
  6085. return gridA;
  6086. };
  6087. var getValidStartAddress = function (currentStartAddress, grid, lockedColumns) {
  6088. var gridColLength = cellLength(grid[0]);
  6089. var adjustedRowAddress = extractGridDetails(grid).cols.length + currentStartAddress.row;
  6090. var possibleColAddresses = range$1(gridColLength - currentStartAddress.column, function (num) {
  6091. return num + currentStartAddress.column;
  6092. });
  6093. var validColAddress = find$1(possibleColAddresses, function (num) {
  6094. return forall(lockedColumns, function (col) {
  6095. return col !== num;
  6096. });
  6097. }).getOr(gridColLength - 1);
  6098. return {
  6099. row: adjustedRowAddress,
  6100. column: validColAddress
  6101. };
  6102. };
  6103. var getLockedColumnsWithinBounds = function (startAddress, grid, lockedColumns) {
  6104. return filter$2(lockedColumns, function (colNum) {
  6105. return colNum >= startAddress.column && colNum <= cellLength(grid[0]) + startAddress.column;
  6106. });
  6107. };
  6108. var merge$1 = function (startAddress, gridA, gridB, generator, comparator) {
  6109. var lockedColumns = getLockedColumnsFromGrid(gridA);
  6110. var validStartAddress = getValidStartAddress(startAddress, gridA, lockedColumns);
  6111. var gridBRows = extractGridDetails(gridB).rows;
  6112. var lockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, lockedColumns);
  6113. var result = measure(validStartAddress, gridA, gridBRows);
  6114. return result.map(function (diff) {
  6115. var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - lockedColumnsWithinBounds.length });
  6116. var fittedGrid = tailor(gridA, delta, generator);
  6117. var newLockedColumns = getLockedColumnsFromGrid(fittedGrid);
  6118. var newLockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, newLockedColumns);
  6119. return mergeTables(validStartAddress, fittedGrid, gridBRows, generator, comparator, newLockedColumnsWithinBounds);
  6120. });
  6121. };
  6122. var insertCols = function (index, gridA, gridB, generator, comparator) {
  6123. splitCols(gridA, index, comparator, generator.cell);
  6124. var delta = measureHeight(gridB, gridA);
  6125. var fittedNewGrid = tailor(gridB, delta, generator);
  6126. var secondDelta = measureHeight(gridA, fittedNewGrid);
  6127. var fittedOldGrid = tailor(gridA, secondDelta, generator);
  6128. return map$1(fittedOldGrid, function (gridRow, i) {
  6129. return addCells(gridRow, index, fittedNewGrid[i].cells);
  6130. });
  6131. };
  6132. var insertRows = function (index, gridA, gridB, generator, comparator) {
  6133. splitRows(gridA, index, comparator, generator.cell);
  6134. var locked = getLockedColumnsFromGrid(gridA);
  6135. var diff = measureWidth(gridA, gridB);
  6136. var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - locked.length });
  6137. var fittedOldGrid = tailor(gridA, delta, generator);
  6138. var _a = extractGridDetails(fittedOldGrid), oldCols = _a.cols, oldRows = _a.rows;
  6139. var newLocked = getLockedColumnsFromGrid(fittedOldGrid);
  6140. var secondDiff = measureWidth(gridB, gridA);
  6141. var secondDelta = __assign(__assign({}, secondDiff), { colDelta: secondDiff.colDelta + newLocked.length });
  6142. var fittedGridB = lockedColFill(gridB, generator, newLocked);
  6143. var fittedNewGrid = tailor(fittedGridB, secondDelta, generator);
  6144. return oldCols.concat(oldRows.slice(0, index)).concat(fittedNewGrid).concat(oldRows.slice(index, oldRows.length));
  6145. };
  6146. var cloneRow = function (row, cloneCell, comparator, substitution) {
  6147. return clone$1(row, function (elem) {
  6148. return substitution(elem, comparator);
  6149. }, cloneCell);
  6150. };
  6151. var insertRowAt = function (grid, index, example, comparator, substitution) {
  6152. var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
  6153. var before = rows.slice(0, index);
  6154. var after = rows.slice(index);
  6155. var newRow = cloneRow(rows[example], function (ex, c) {
  6156. var withinSpan = index > 0 && index < rows.length && comparator(getCellElement(rows[index - 1], c), getCellElement(rows[index], c));
  6157. var ret = withinSpan ? getCell(rows[index], c) : elementnew(substitution(ex.element, comparator), true, ex.isLocked);
  6158. return ret;
  6159. }, comparator, substitution);
  6160. return cols.concat(before).concat([newRow]).concat(after);
  6161. };
  6162. var getElementFor = function (row, column, section, withinSpan, example, comparator, substitution) {
  6163. if (section === 'colgroup' || !withinSpan) {
  6164. var cell = getCell(row, example);
  6165. return elementnew(substitution(cell.element, comparator), true, false);
  6166. } else {
  6167. return getCell(row, column);
  6168. }
  6169. };
  6170. var insertColumnAt = function (grid, index, example, comparator, substitution) {
  6171. return map$1(grid, function (row) {
  6172. var withinSpan = index > 0 && index < cellLength(row) && comparator(getCellElement(row, index - 1), getCellElement(row, index));
  6173. var sub = getElementFor(row, index, row.section, withinSpan, example, comparator, substitution);
  6174. return addCell(row, index, sub);
  6175. });
  6176. };
  6177. var deleteColumnsAt = function (grid, columns) {
  6178. return bind$2(grid, function (row) {
  6179. var existingCells = row.cells;
  6180. var cells = foldr(columns, function (acc, column) {
  6181. return column >= 0 && column < acc.length ? acc.slice(0, column).concat(acc.slice(column + 1)) : acc;
  6182. }, existingCells);
  6183. return cells.length > 0 ? [rowcells(row.element, cells, row.section, row.isNew)] : [];
  6184. });
  6185. };
  6186. var deleteRowsAt = function (grid, start, finish) {
  6187. var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
  6188. return cols.concat(rows.slice(0, start)).concat(rows.slice(finish + 1));
  6189. };
  6190. var replace = function (cell, comparator, substitute) {
  6191. return elementnew(substitute(cell.element, comparator), true, cell.isLocked);
  6192. };
  6193. var replaceIn = function (grid, targets, comparator, substitute, replacer) {
  6194. var isTarget = function (cell) {
  6195. return exists(targets, function (target) {
  6196. return comparator(cell.element, target.element);
  6197. });
  6198. };
  6199. return map$1(grid, function (row) {
  6200. return mapCells(row, function (cell) {
  6201. return isTarget(cell) ? replacer(cell, comparator, substitute) : cell;
  6202. });
  6203. });
  6204. };
  6205. var notStartRow = function (grid, rowIndex, colIndex, comparator) {
  6206. return getCellElement(grid[rowIndex], colIndex) !== undefined && (rowIndex > 0 && comparator(getCellElement(grid[rowIndex - 1], colIndex), getCellElement(grid[rowIndex], colIndex)));
  6207. };
  6208. var notStartColumn = function (row, index, comparator) {
  6209. return index > 0 && comparator(getCellElement(row, index - 1), getCellElement(row, index));
  6210. };
  6211. var replaceColumn = function (grid, index, comparator, substitution) {
  6212. var rows = extractGridDetails(grid).rows;
  6213. var targets = bind$2(rows, function (row, i) {
  6214. var alreadyAdded = notStartRow(rows, i, index, comparator) || notStartColumn(row, index, comparator);
  6215. return alreadyAdded ? [] : [getCell(row, index)];
  6216. });
  6217. return replaceIn(grid, targets, comparator, substitution, replace);
  6218. };
  6219. var replaceRow = function (grid, index, section, comparator, substitution, tableSection) {
  6220. var _a = extractGridDetails(grid), cols = _a.cols, rows = _a.rows;
  6221. var targetRow = rows[index];
  6222. var targets = bind$2(targetRow.cells, function (item, i) {
  6223. var alreadyAdded = notStartRow(rows, index, i, comparator) || notStartColumn(targetRow, i, comparator);
  6224. return alreadyAdded ? [] : [item];
  6225. });
  6226. var newRows = __spreadArray([], rows);
  6227. newRows[index] = tableSection.transformRow(targetRow, section);
  6228. return replaceIn(cols.concat(newRows), targets, comparator, substitution, tableSection.transformCell);
  6229. };
  6230. var replaceCell = function (grid, rowIndex, columnIndex, comparator, substitution) {
  6231. var rows = extractGridDetails(grid).rows;
  6232. var targetRow = rows[rowIndex];
  6233. var targetCell = getCell(targetRow, columnIndex);
  6234. return replaceIn(grid, [targetCell], comparator, substitution, replace);
  6235. };
  6236. var uniqueColumns = function (details) {
  6237. var uniqueCheck = function (rest, detail) {
  6238. var columnExists = exists(rest, function (currentDetail) {
  6239. return currentDetail.column === detail.column;
  6240. });
  6241. return columnExists ? rest : rest.concat([detail]);
  6242. };
  6243. return foldl(details, uniqueCheck, []).sort(function (detailA, detailB) {
  6244. return detailA.column - detailB.column;
  6245. });
  6246. };
  6247. var isCol = isTag('col');
  6248. var isColgroup = isTag('colgroup');
  6249. var isRow$1 = function (element) {
  6250. return name(element) === 'tr' || isColgroup(element);
  6251. };
  6252. var elementToData = function (element) {
  6253. var colspan = getAttrValue(element, 'colspan', 1);
  6254. var rowspan = getAttrValue(element, 'rowspan', 1);
  6255. return {
  6256. element: element,
  6257. colspan: colspan,
  6258. rowspan: rowspan
  6259. };
  6260. };
  6261. var modification = function (generators, toData) {
  6262. if (toData === void 0) {
  6263. toData = elementToData;
  6264. }
  6265. var nuCell = function (data) {
  6266. return isCol(data.element) ? generators.col(data) : generators.cell(data);
  6267. };
  6268. var nuRow = function (data) {
  6269. return isColgroup(data.element) ? generators.colgroup(data) : generators.row(data);
  6270. };
  6271. var add = function (element) {
  6272. if (isRow$1(element)) {
  6273. return nuRow({ element: element });
  6274. } else {
  6275. var replacement = nuCell(toData(element));
  6276. recent = Optional.some({
  6277. item: element,
  6278. replacement: replacement
  6279. });
  6280. return replacement;
  6281. }
  6282. };
  6283. var recent = Optional.none();
  6284. var getOrInit = function (element, comparator) {
  6285. return recent.fold(function () {
  6286. return add(element);
  6287. }, function (p) {
  6288. return comparator(element, p.item) ? p.replacement : add(element);
  6289. });
  6290. };
  6291. return { getOrInit: getOrInit };
  6292. };
  6293. var transform = function (tag, scope) {
  6294. return function (generators) {
  6295. var list = [];
  6296. var find = function (element, comparator) {
  6297. return find$1(list, function (x) {
  6298. return comparator(x.item, element);
  6299. });
  6300. };
  6301. var makeNew = function (element) {
  6302. var attrs = isUndefined(scope) ? {} : { scope: scope };
  6303. var cell = generators.replace(element, tag, attrs);
  6304. list.push({
  6305. item: element,
  6306. sub: cell
  6307. });
  6308. return cell;
  6309. };
  6310. var replaceOrInit = function (element, comparator) {
  6311. if (isRow$1(element) || isCol(element)) {
  6312. return element;
  6313. } else {
  6314. return find(element, comparator).fold(function () {
  6315. return makeNew(element);
  6316. }, function (p) {
  6317. return comparator(element, p.item) ? p.sub : makeNew(element);
  6318. });
  6319. }
  6320. };
  6321. return { replaceOrInit: replaceOrInit };
  6322. };
  6323. };
  6324. var getScopeAttribute = function (cell) {
  6325. return getOpt(cell, 'scope').map(function (attribute) {
  6326. return attribute.substr(0, 3);
  6327. });
  6328. };
  6329. var merging = function (generators) {
  6330. var unmerge = function (cell) {
  6331. var scope = getScopeAttribute(cell);
  6332. scope.each(function (attribute) {
  6333. return set$2(cell, 'scope', attribute);
  6334. });
  6335. return function () {
  6336. var raw = generators.cell({
  6337. element: cell,
  6338. colspan: 1,
  6339. rowspan: 1
  6340. });
  6341. remove$6(raw, 'width');
  6342. remove$6(cell, 'width');
  6343. scope.each(function (attribute) {
  6344. return set$2(raw, 'scope', attribute);
  6345. });
  6346. return raw;
  6347. };
  6348. };
  6349. var merge = function (cells) {
  6350. var getScopeProperty = function () {
  6351. var stringAttributes = cat(map$1(cells, getScopeAttribute));
  6352. if (stringAttributes.length === 0) {
  6353. return Optional.none();
  6354. } else {
  6355. var baseScope_1 = stringAttributes[0];
  6356. var scopes_1 = [
  6357. 'row',
  6358. 'col'
  6359. ];
  6360. var isMixed = exists(stringAttributes, function (attribute) {
  6361. return attribute !== baseScope_1 && contains$2(scopes_1, attribute);
  6362. });
  6363. return isMixed ? Optional.none() : Optional.from(baseScope_1);
  6364. }
  6365. };
  6366. remove$6(cells[0], 'width');
  6367. getScopeProperty().fold(function () {
  6368. return remove$7(cells[0], 'scope');
  6369. }, function (attribute) {
  6370. return set$2(cells[0], 'scope', attribute + 'group');
  6371. });
  6372. return constant(cells[0]);
  6373. };
  6374. return {
  6375. unmerge: unmerge,
  6376. merge: merge
  6377. };
  6378. };
  6379. var Generators = {
  6380. modification: modification,
  6381. transform: transform,
  6382. merging: merging
  6383. };
  6384. var blockList = [
  6385. 'body',
  6386. 'p',
  6387. 'div',
  6388. 'article',
  6389. 'aside',
  6390. 'figcaption',
  6391. 'figure',
  6392. 'footer',
  6393. 'header',
  6394. 'nav',
  6395. 'section',
  6396. 'ol',
  6397. 'ul',
  6398. 'table',
  6399. 'thead',
  6400. 'tfoot',
  6401. 'tbody',
  6402. 'caption',
  6403. 'tr',
  6404. 'td',
  6405. 'th',
  6406. 'h1',
  6407. 'h2',
  6408. 'h3',
  6409. 'h4',
  6410. 'h5',
  6411. 'h6',
  6412. 'blockquote',
  6413. 'pre',
  6414. 'address'
  6415. ];
  6416. var isList$1 = function (universe, item) {
  6417. var tagName = universe.property().name(item);
  6418. return contains$2([
  6419. 'ol',
  6420. 'ul'
  6421. ], tagName);
  6422. };
  6423. var isBlock$1 = function (universe, item) {
  6424. var tagName = universe.property().name(item);
  6425. return contains$2(blockList, tagName);
  6426. };
  6427. var isEmptyTag$1 = function (universe, item) {
  6428. return contains$2([
  6429. 'br',
  6430. 'img',
  6431. 'hr',
  6432. 'input'
  6433. ], universe.property().name(item));
  6434. };
  6435. var universe$1 = DomUniverse();
  6436. var isBlock = function (element) {
  6437. return isBlock$1(universe$1, element);
  6438. };
  6439. var isList = function (element) {
  6440. return isList$1(universe$1, element);
  6441. };
  6442. var isEmptyTag = function (element) {
  6443. return isEmptyTag$1(universe$1, element);
  6444. };
  6445. var merge = function (cells) {
  6446. var isBr = function (el) {
  6447. return name(el) === 'br';
  6448. };
  6449. var advancedBr = function (children) {
  6450. return forall(children, function (c) {
  6451. return isBr(c) || isText(c) && get$9(c).trim().length === 0;
  6452. });
  6453. };
  6454. var isListItem = function (el) {
  6455. return name(el) === 'li' || ancestor$2(el, isList).isSome();
  6456. };
  6457. var siblingIsBlock = function (el) {
  6458. return nextSibling(el).map(function (rightSibling) {
  6459. if (isBlock(rightSibling)) {
  6460. return true;
  6461. }
  6462. if (isEmptyTag(rightSibling)) {
  6463. return name(rightSibling) === 'img' ? false : true;
  6464. }
  6465. return false;
  6466. }).getOr(false);
  6467. };
  6468. var markCell = function (cell) {
  6469. return last$1(cell).bind(function (rightEdge) {
  6470. var rightSiblingIsBlock = siblingIsBlock(rightEdge);
  6471. return parent(rightEdge).map(function (parent) {
  6472. return rightSiblingIsBlock === true || isListItem(parent) || isBr(rightEdge) || isBlock(parent) && !eq$1(cell, parent) ? [] : [SugarElement.fromTag('br')];
  6473. });
  6474. }).getOr([]);
  6475. };
  6476. var markContent = function () {
  6477. var content = bind$2(cells, function (cell) {
  6478. var children = children$3(cell);
  6479. return advancedBr(children) ? [] : children.concat(markCell(cell));
  6480. });
  6481. return content.length === 0 ? [SugarElement.fromTag('br')] : content;
  6482. };
  6483. var contents = markContent();
  6484. empty(cells[0]);
  6485. append(cells[0], contents);
  6486. };
  6487. var isEditable = function (elem) {
  6488. return isEditable$1(elem, true);
  6489. };
  6490. var prune = function (table) {
  6491. var cells = cells$1(table);
  6492. if (cells.length === 0) {
  6493. remove$5(table);
  6494. }
  6495. };
  6496. var outcome = function (grid, cursor) {
  6497. return {
  6498. grid: grid,
  6499. cursor: cursor
  6500. };
  6501. };
  6502. var findEditableCursorPosition = function (rows) {
  6503. return findMap(rows, function (row) {
  6504. return findMap(row.cells, function (cell) {
  6505. var elem = cell.element;
  6506. return someIf(isEditable(elem), elem);
  6507. });
  6508. });
  6509. };
  6510. var elementFromGrid = function (grid, row, column) {
  6511. var _a, _b;
  6512. var rows = extractGridDetails(grid).rows;
  6513. return Optional.from((_b = (_a = rows[row]) === null || _a === void 0 ? void 0 : _a.cells[column]) === null || _b === void 0 ? void 0 : _b.element).filter(isEditable).orThunk(function () {
  6514. return findEditableCursorPosition(rows);
  6515. });
  6516. };
  6517. var bundle = function (grid, row, column) {
  6518. var cursorElement = elementFromGrid(grid, row, column);
  6519. return outcome(grid, cursorElement);
  6520. };
  6521. var uniqueRows = function (details) {
  6522. var rowCompilation = function (rest, detail) {
  6523. var rowExists = exists(rest, function (currentDetail) {
  6524. return currentDetail.row === detail.row;
  6525. });
  6526. return rowExists ? rest : rest.concat([detail]);
  6527. };
  6528. return foldl(details, rowCompilation, []).sort(function (detailA, detailB) {
  6529. return detailA.row - detailB.row;
  6530. });
  6531. };
  6532. var opInsertRowsBefore = function (grid, details, comparator, genWrappers) {
  6533. var targetIndex = details[0].row;
  6534. var rows = uniqueRows(details);
  6535. var newGrid = foldr(rows, function (acc, row) {
  6536. var newG = insertRowAt(acc.grid, targetIndex, row.row + acc.delta, comparator, genWrappers.getOrInit);
  6537. return {
  6538. grid: newG,
  6539. delta: acc.delta + 1
  6540. };
  6541. }, {
  6542. grid: grid,
  6543. delta: 0
  6544. }).grid;
  6545. return bundle(newGrid, targetIndex, details[0].column);
  6546. };
  6547. var opInsertRowsAfter = function (grid, details, comparator, genWrappers) {
  6548. var rows = uniqueRows(details);
  6549. var target = rows[rows.length - 1];
  6550. var targetIndex = target.row + target.rowspan;
  6551. var newGrid = foldr(rows, function (newG, row) {
  6552. return insertRowAt(newG, targetIndex, row.row, comparator, genWrappers.getOrInit);
  6553. }, grid);
  6554. return bundle(newGrid, targetIndex, details[0].column);
  6555. };
  6556. var opInsertColumnsBefore = function (grid, extractDetail, comparator, genWrappers) {
  6557. var details = extractDetail.details;
  6558. var columns = uniqueColumns(details);
  6559. var targetIndex = columns[0].column;
  6560. var newGrid = foldr(columns, function (acc, col) {
  6561. var newG = insertColumnAt(acc.grid, targetIndex, col.column + acc.delta, comparator, genWrappers.getOrInit);
  6562. return {
  6563. grid: newG,
  6564. delta: acc.delta + 1
  6565. };
  6566. }, {
  6567. grid: grid,
  6568. delta: 0
  6569. }).grid;
  6570. return bundle(newGrid, details[0].row, targetIndex);
  6571. };
  6572. var opInsertColumnsAfter = function (grid, extractDetail, comparator, genWrappers) {
  6573. var details = extractDetail.details;
  6574. var target = details[details.length - 1];
  6575. var targetIndex = target.column + target.colspan;
  6576. var columns = uniqueColumns(details);
  6577. var newGrid = foldr(columns, function (newG, col) {
  6578. return insertColumnAt(newG, targetIndex, col.column, comparator, genWrappers.getOrInit);
  6579. }, grid);
  6580. return bundle(newGrid, details[0].row, targetIndex);
  6581. };
  6582. var opMakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
  6583. var replacer = function (currentGrid, column) {
  6584. return replaceColumn(currentGrid, column.column, comparator, genWrappers.replaceOrInit);
  6585. };
  6586. var columns = uniqueColumns(details);
  6587. var newGrid = foldl(columns, replacer, initialGrid);
  6588. return bundle(newGrid, details[0].row, details[0].column);
  6589. };
  6590. var opMakeCellsHeader = function (initialGrid, details, comparator, genWrappers) {
  6591. var replacer = function (currentGrid, detail) {
  6592. return replaceCell(currentGrid, detail.row, detail.column, comparator, genWrappers.replaceOrInit);
  6593. };
  6594. var newGrid = foldl(details, replacer, initialGrid);
  6595. return bundle(newGrid, details[0].row, details[0].column);
  6596. };
  6597. var opUnmakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
  6598. var replacer = function (currentGrid, column) {
  6599. return replaceColumn(currentGrid, column.column, comparator, genWrappers.replaceOrInit);
  6600. };
  6601. var columns = uniqueColumns(details);
  6602. var newGrid = foldl(columns, replacer, initialGrid);
  6603. return bundle(newGrid, details[0].row, details[0].column);
  6604. };
  6605. var opUnmakeCellsHeader = function (initialGrid, details, comparator, genWrappers) {
  6606. var replacer = function (currentGrid, detail) {
  6607. return replaceCell(currentGrid, detail.row, detail.column, comparator, genWrappers.replaceOrInit);
  6608. };
  6609. var newGrid = foldl(details, replacer, initialGrid);
  6610. return bundle(newGrid, details[0].row, details[0].column);
  6611. };
  6612. var makeRowsSection = function (section) {
  6613. return function (initialGrid, details, comparator, genWrappers, tableSection) {
  6614. var replacer = function (currentGrid, detail) {
  6615. return replaceRow(currentGrid, detail.row, section, comparator, genWrappers.replaceOrInit, tableSection);
  6616. };
  6617. var rows = uniqueRows(details);
  6618. var newGrid = foldl(rows, replacer, initialGrid);
  6619. return bundle(newGrid, details[0].row, details[0].column);
  6620. };
  6621. };
  6622. var opMakeRowsHeader = makeRowsSection('thead');
  6623. var opMakeRowsBody = makeRowsSection('tbody');
  6624. var opMakeRowsFooter = makeRowsSection('tfoot');
  6625. var opEraseColumns = function (grid, extractDetail, _comparator, _genWrappers) {
  6626. var columns = uniqueColumns(extractDetail.details);
  6627. var newGrid = deleteColumnsAt(grid, map$1(columns, function (column) {
  6628. return column.column;
  6629. }));
  6630. var maxColIndex = newGrid.length > 0 ? newGrid[0].cells.length - 1 : 0;
  6631. return bundle(newGrid, columns[0].row, Math.min(columns[0].column, maxColIndex));
  6632. };
  6633. var opEraseRows = function (grid, details, _comparator, _genWrappers) {
  6634. var rows = uniqueRows(details);
  6635. var newGrid = deleteRowsAt(grid, rows[0].row, rows[rows.length - 1].row);
  6636. var maxRowIndex = newGrid.length > 0 ? newGrid.length - 1 : 0;
  6637. return bundle(newGrid, Math.min(details[0].row, maxRowIndex), details[0].column);
  6638. };
  6639. var opMergeCells = function (grid, mergable, comparator, genWrappers) {
  6640. var cells = mergable.cells;
  6641. merge(cells);
  6642. var newGrid = merge$2(grid, mergable.bounds, comparator, genWrappers.merge(cells));
  6643. return outcome(newGrid, Optional.from(cells[0]));
  6644. };
  6645. var opUnmergeCells = function (grid, unmergable, comparator, genWrappers) {
  6646. var unmerge$1 = function (b, cell) {
  6647. return unmerge(b, cell, comparator, genWrappers.unmerge(cell));
  6648. };
  6649. var newGrid = foldr(unmergable, unmerge$1, grid);
  6650. return outcome(newGrid, Optional.from(unmergable[0]));
  6651. };
  6652. var opPasteCells = function (grid, pasteDetails, comparator, _genWrappers) {
  6653. var gridify = function (table, generators) {
  6654. var wh = Warehouse.fromTable(table);
  6655. return toGrid(wh, generators, true);
  6656. };
  6657. var gridB = gridify(pasteDetails.clipboard, pasteDetails.generators);
  6658. var startAddress = address(pasteDetails.row, pasteDetails.column);
  6659. var mergedGrid = merge$1(startAddress, grid, gridB, pasteDetails.generators, comparator);
  6660. return mergedGrid.fold(function () {
  6661. return outcome(grid, Optional.some(pasteDetails.element));
  6662. }, function (newGrid) {
  6663. return bundle(newGrid, pasteDetails.row, pasteDetails.column);
  6664. });
  6665. };
  6666. var gridifyRows = function (rows, generators, context) {
  6667. var pasteDetails = fromPastedRows(rows, context.section);
  6668. var wh = Warehouse.generate(pasteDetails);
  6669. return toGrid(wh, generators, true);
  6670. };
  6671. var opPasteColsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  6672. var rows = extractGridDetails(grid).rows;
  6673. var index = pasteDetails.cells[0].column;
  6674. var context = rows[pasteDetails.cells[0].row];
  6675. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6676. var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
  6677. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6678. };
  6679. var opPasteColsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  6680. var rows = extractGridDetails(grid).rows;
  6681. var index = pasteDetails.cells[pasteDetails.cells.length - 1].column + pasteDetails.cells[pasteDetails.cells.length - 1].colspan;
  6682. var context = rows[pasteDetails.cells[0].row];
  6683. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6684. var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
  6685. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6686. };
  6687. var opPasteRowsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  6688. var rows = extractGridDetails(grid).rows;
  6689. var index = pasteDetails.cells[0].row;
  6690. var context = rows[index];
  6691. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6692. var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
  6693. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6694. };
  6695. var opPasteRowsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  6696. var rows = extractGridDetails(grid).rows;
  6697. var index = pasteDetails.cells[pasteDetails.cells.length - 1].row + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan;
  6698. var context = rows[pasteDetails.cells[0].row];
  6699. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6700. var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
  6701. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6702. };
  6703. var opGetColumnsType = function (table, target) {
  6704. var house = Warehouse.fromTable(table);
  6705. var details = onCells(house, target);
  6706. return details.bind(function (selectedCells) {
  6707. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  6708. var minColRange = selectedCells[0].column;
  6709. var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
  6710. var selectedColumnCells = flatten$1(map$1(house.all, function (row) {
  6711. return filter$2(row.cells, function (cell) {
  6712. return cell.column >= minColRange && cell.column < maxColRange;
  6713. });
  6714. }));
  6715. return findCommonCellType(selectedColumnCells);
  6716. }).getOr('');
  6717. };
  6718. var opGetCellsType = function (table, target) {
  6719. var house = Warehouse.fromTable(table);
  6720. var details = onCells(house, target);
  6721. return details.bind(findCommonCellType).getOr('');
  6722. };
  6723. var opGetRowsType = function (table, target) {
  6724. var house = Warehouse.fromTable(table);
  6725. var details = onCells(house, target);
  6726. return details.bind(function (selectedCells) {
  6727. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  6728. var minRowRange = selectedCells[0].row;
  6729. var maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
  6730. var selectedRows = house.all.slice(minRowRange, maxRowRange);
  6731. return findCommonRowType(selectedRows);
  6732. }).getOr('');
  6733. };
  6734. var resize = function (table, list, details, behaviours) {
  6735. return adjustWidthTo(table, list, details, behaviours.sizing);
  6736. };
  6737. var adjustAndRedistributeWidths = function (table, list, details, behaviours) {
  6738. return adjustAndRedistributeWidths$1(table, list, details, behaviours.sizing, behaviours.resize);
  6739. };
  6740. var firstColumnIsLocked = function (_warehouse, details) {
  6741. return exists(details, function (detail) {
  6742. return detail.column === 0 && detail.isLocked;
  6743. });
  6744. };
  6745. var lastColumnIsLocked = function (warehouse, details) {
  6746. return exists(details, function (detail) {
  6747. return detail.column + detail.colspan >= warehouse.grid.columns && detail.isLocked;
  6748. });
  6749. };
  6750. var getColumnsWidth = function (warehouse, details) {
  6751. var columns$1 = columns(warehouse);
  6752. var uniqueCols = uniqueColumns(details);
  6753. return foldl(uniqueCols, function (acc, detail) {
  6754. var column = columns$1[detail.column];
  6755. var colWidth = column.map(getOuter$2).getOr(0);
  6756. return acc + colWidth;
  6757. }, 0);
  6758. };
  6759. var insertColumnsExtractor = function (before) {
  6760. return function (warehouse, target) {
  6761. return onCells(warehouse, target).filter(function (details) {
  6762. var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
  6763. return !checkLocked(warehouse, details);
  6764. }).map(function (details) {
  6765. return {
  6766. details: details,
  6767. pixelDelta: getColumnsWidth(warehouse, details)
  6768. };
  6769. });
  6770. };
  6771. };
  6772. var eraseColumnsExtractor = function (warehouse, target) {
  6773. return onUnlockedCells(warehouse, target).map(function (details) {
  6774. return {
  6775. details: details,
  6776. pixelDelta: -getColumnsWidth(warehouse, details)
  6777. };
  6778. });
  6779. };
  6780. var pasteColumnsExtractor = function (before) {
  6781. return function (warehouse, target) {
  6782. return onPasteByEditor(warehouse, target).filter(function (details) {
  6783. var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
  6784. return !checkLocked(warehouse, details.cells);
  6785. });
  6786. };
  6787. };
  6788. var insertRowsBefore = run(opInsertRowsBefore, onCells, noop, noop, Generators.modification);
  6789. var insertRowsAfter = run(opInsertRowsAfter, onCells, noop, noop, Generators.modification);
  6790. var insertColumnsBefore = run(opInsertColumnsBefore, insertColumnsExtractor(true), adjustAndRedistributeWidths, noop, Generators.modification);
  6791. var insertColumnsAfter = run(opInsertColumnsAfter, insertColumnsExtractor(false), adjustAndRedistributeWidths, noop, Generators.modification);
  6792. var eraseColumns = run(opEraseColumns, eraseColumnsExtractor, adjustAndRedistributeWidths, prune, Generators.modification);
  6793. var eraseRows = run(opEraseRows, onCells, noop, prune, Generators.modification);
  6794. var makeColumnsHeader = run(opMakeColumnsHeader, onUnlockedCells, noop, noop, Generators.transform('th', 'row'));
  6795. var unmakeColumnsHeader = run(opUnmakeColumnsHeader, onUnlockedCells, noop, noop, Generators.transform('td', null));
  6796. var makeRowsHeader = run(opMakeRowsHeader, onUnlockedCells, noop, noop, Generators.transform('th', 'col'));
  6797. var makeRowsBody = run(opMakeRowsBody, onUnlockedCells, noop, noop, Generators.transform('td', null));
  6798. var makeRowsFooter = run(opMakeRowsFooter, onUnlockedCells, noop, noop, Generators.transform('td', null));
  6799. var makeCellsHeader = run(opMakeCellsHeader, onUnlockedCells, noop, noop, Generators.transform('th'));
  6800. var unmakeCellsHeader = run(opUnmakeCellsHeader, onUnlockedCells, noop, noop, Generators.transform('td'));
  6801. var mergeCells = run(opMergeCells, onUnlockedMergable, resize, noop, Generators.merging);
  6802. var unmergeCells = run(opUnmergeCells, onUnlockedUnmergable, resize, noop, Generators.merging);
  6803. var pasteCells = run(opPasteCells, onPaste, resize, noop, Generators.modification);
  6804. var pasteColsBefore = run(opPasteColsBefore, pasteColumnsExtractor(true), noop, noop, Generators.modification);
  6805. var pasteColsAfter = run(opPasteColsAfter, pasteColumnsExtractor(false), noop, noop, Generators.modification);
  6806. var pasteRowsBefore = run(opPasteRowsBefore, onPasteByEditor, noop, noop, Generators.modification);
  6807. var pasteRowsAfter = run(opPasteRowsAfter, onPasteByEditor, noop, noop, Generators.modification);
  6808. var getColumnsType = opGetColumnsType;
  6809. var getCellsType = opGetCellsType;
  6810. var getRowsType = opGetRowsType;
  6811. var TableActions = function (editor, cellSelection, lazyWire) {
  6812. var isTableBody = function (editor) {
  6813. return name(getBody(editor)) === 'table';
  6814. };
  6815. var lastRowGuard = function (table) {
  6816. return isTableBody(editor) === false || getGridSize(table).rows > 1;
  6817. };
  6818. var lastColumnGuard = function (table) {
  6819. return isTableBody(editor) === false || getGridSize(table).columns > 1;
  6820. };
  6821. var cloneFormats = getCloneElements(editor);
  6822. var colMutationOp = isResizeTableColumnResizing(editor) ? noop : halve;
  6823. var getTableSectionType = function (table) {
  6824. switch (getTableHeaderType(editor)) {
  6825. case 'section':
  6826. return TableSection.section();
  6827. case 'sectionCells':
  6828. return TableSection.sectionCells();
  6829. case 'cells':
  6830. return TableSection.cells();
  6831. default:
  6832. return TableSection.getTableSectionType(table, 'section');
  6833. }
  6834. };
  6835. var setSelectionFromAction = function (table, result) {
  6836. return result.cursor.fold(function () {
  6837. var cells = cells$1(table);
  6838. return head(cells).filter(inBody).map(function (firstCell) {
  6839. cellSelection.clear(table);
  6840. var rng = editor.dom.createRng();
  6841. rng.selectNode(firstCell.dom);
  6842. editor.selection.setRng(rng);
  6843. set$2(firstCell, 'data-mce-selected', '1');
  6844. return rng;
  6845. });
  6846. }, function (cell) {
  6847. var des = freefallRtl(cell);
  6848. var rng = editor.dom.createRng();
  6849. rng.setStart(des.element.dom, des.offset);
  6850. rng.setEnd(des.element.dom, des.offset);
  6851. editor.selection.setRng(rng);
  6852. cellSelection.clear(table);
  6853. return Optional.some(rng);
  6854. });
  6855. };
  6856. var execute = function (operation, guard, mutate, lazyWire, effect) {
  6857. return function (table, target, noEvents) {
  6858. if (noEvents === void 0) {
  6859. noEvents = false;
  6860. }
  6861. removeDataStyle(table);
  6862. var wire = lazyWire();
  6863. var doc = SugarElement.fromDom(editor.getDoc());
  6864. var generators = cellOperations(mutate, doc, cloneFormats);
  6865. var behaviours = {
  6866. sizing: get$4(editor, table),
  6867. resize: isResizeTableColumnResizing(editor) ? resizeTable() : preserveTable(),
  6868. section: getTableSectionType(table)
  6869. };
  6870. return guard(table) ? operation(wire, table, target, generators, behaviours).bind(function (result) {
  6871. each$2(result.newRows, function (row) {
  6872. fireNewRow(editor, row.dom);
  6873. });
  6874. each$2(result.newCells, function (cell) {
  6875. fireNewCell(editor, cell.dom);
  6876. });
  6877. var range = setSelectionFromAction(table, result);
  6878. if (inBody(table)) {
  6879. removeDataStyle(table);
  6880. if (!noEvents) {
  6881. fireTableModified(editor, table.dom, effect);
  6882. }
  6883. }
  6884. return range.map(function (rng) {
  6885. return {
  6886. rng: rng,
  6887. effect: effect
  6888. };
  6889. });
  6890. }) : Optional.none();
  6891. };
  6892. };
  6893. var deleteRow = execute(eraseRows, lastRowGuard, noop, lazyWire, structureModified);
  6894. var deleteColumn = execute(eraseColumns, lastColumnGuard, noop, lazyWire, structureModified);
  6895. var insertRowsBefore$1 = execute(insertRowsBefore, always, noop, lazyWire, structureModified);
  6896. var insertRowsAfter$1 = execute(insertRowsAfter, always, noop, lazyWire, structureModified);
  6897. var insertColumnsBefore$1 = execute(insertColumnsBefore, always, colMutationOp, lazyWire, structureModified);
  6898. var insertColumnsAfter$1 = execute(insertColumnsAfter, always, colMutationOp, lazyWire, structureModified);
  6899. var mergeCells$1 = execute(mergeCells, always, noop, lazyWire, structureModified);
  6900. var unmergeCells$1 = execute(unmergeCells, always, noop, lazyWire, structureModified);
  6901. var pasteColsBefore$1 = execute(pasteColsBefore, always, noop, lazyWire, structureModified);
  6902. var pasteColsAfter$1 = execute(pasteColsAfter, always, noop, lazyWire, structureModified);
  6903. var pasteRowsBefore$1 = execute(pasteRowsBefore, always, noop, lazyWire, structureModified);
  6904. var pasteRowsAfter$1 = execute(pasteRowsAfter, always, noop, lazyWire, structureModified);
  6905. var pasteCells$1 = execute(pasteCells, always, noop, lazyWire, styleAndStructureModified);
  6906. var makeCellsHeader$1 = execute(makeCellsHeader, always, noop, lazyWire, structureModified);
  6907. var unmakeCellsHeader$1 = execute(unmakeCellsHeader, always, noop, lazyWire, structureModified);
  6908. var makeColumnsHeader$1 = execute(makeColumnsHeader, always, noop, lazyWire, structureModified);
  6909. var unmakeColumnsHeader$1 = execute(unmakeColumnsHeader, always, noop, lazyWire, structureModified);
  6910. var makeRowsHeader$1 = execute(makeRowsHeader, always, noop, lazyWire, structureModified);
  6911. var makeRowsBody$1 = execute(makeRowsBody, always, noop, lazyWire, structureModified);
  6912. var makeRowsFooter$1 = execute(makeRowsFooter, always, noop, lazyWire, structureModified);
  6913. var getTableCellType = getCellsType;
  6914. var getTableColType = getColumnsType;
  6915. var getTableRowType = getRowsType;
  6916. return {
  6917. deleteRow: deleteRow,
  6918. deleteColumn: deleteColumn,
  6919. insertRowsBefore: insertRowsBefore$1,
  6920. insertRowsAfter: insertRowsAfter$1,
  6921. insertColumnsBefore: insertColumnsBefore$1,
  6922. insertColumnsAfter: insertColumnsAfter$1,
  6923. mergeCells: mergeCells$1,
  6924. unmergeCells: unmergeCells$1,
  6925. pasteColsBefore: pasteColsBefore$1,
  6926. pasteColsAfter: pasteColsAfter$1,
  6927. pasteRowsBefore: pasteRowsBefore$1,
  6928. pasteRowsAfter: pasteRowsAfter$1,
  6929. pasteCells: pasteCells$1,
  6930. makeCellsHeader: makeCellsHeader$1,
  6931. unmakeCellsHeader: unmakeCellsHeader$1,
  6932. makeColumnsHeader: makeColumnsHeader$1,
  6933. unmakeColumnsHeader: unmakeColumnsHeader$1,
  6934. makeRowsHeader: makeRowsHeader$1,
  6935. makeRowsBody: makeRowsBody$1,
  6936. makeRowsFooter: makeRowsFooter$1,
  6937. getTableRowType: getTableRowType,
  6938. getTableCellType: getTableCellType,
  6939. getTableColType: getTableColType
  6940. };
  6941. };
  6942. var DefaultRenderOptions = {
  6943. styles: {
  6944. 'border-collapse': 'collapse',
  6945. 'width': '100%'
  6946. },
  6947. attributes: { border: '1' },
  6948. colGroups: false
  6949. };
  6950. var tableHeaderCell = function () {
  6951. return SugarElement.fromTag('th');
  6952. };
  6953. var tableCell = function () {
  6954. return SugarElement.fromTag('td');
  6955. };
  6956. var tableColumn = function () {
  6957. return SugarElement.fromTag('col');
  6958. };
  6959. var createRow = function (columns, rowHeaders, columnHeaders, rowIndex) {
  6960. var tr = SugarElement.fromTag('tr');
  6961. for (var j = 0; j < columns; j++) {
  6962. var td = rowIndex < rowHeaders || j < columnHeaders ? tableHeaderCell() : tableCell();
  6963. if (j < columnHeaders) {
  6964. set$2(td, 'scope', 'row');
  6965. }
  6966. if (rowIndex < rowHeaders) {
  6967. set$2(td, 'scope', 'col');
  6968. }
  6969. append$1(td, SugarElement.fromTag('br'));
  6970. append$1(tr, td);
  6971. }
  6972. return tr;
  6973. };
  6974. var createGroupRow = function (columns) {
  6975. var columnGroup = SugarElement.fromTag('colgroup');
  6976. range$1(columns, function () {
  6977. return append$1(columnGroup, tableColumn());
  6978. });
  6979. return columnGroup;
  6980. };
  6981. var createRows = function (rows, columns, rowHeaders, columnHeaders) {
  6982. return range$1(rows, function (r) {
  6983. return createRow(columns, rowHeaders, columnHeaders, r);
  6984. });
  6985. };
  6986. var render = function (rows, columns, rowHeaders, columnHeaders, headerType, renderOpts) {
  6987. if (renderOpts === void 0) {
  6988. renderOpts = DefaultRenderOptions;
  6989. }
  6990. var table = SugarElement.fromTag('table');
  6991. var rowHeadersGoInThead = headerType !== 'cells';
  6992. setAll(table, renderOpts.styles);
  6993. setAll$1(table, renderOpts.attributes);
  6994. if (renderOpts.colGroups) {
  6995. append$1(table, createGroupRow(columns));
  6996. }
  6997. var actualRowHeaders = Math.min(rows, rowHeaders);
  6998. if (rowHeadersGoInThead && rowHeaders > 0) {
  6999. var thead = SugarElement.fromTag('thead');
  7000. append$1(table, thead);
  7001. var theadRowHeaders = headerType === 'sectionCells' ? actualRowHeaders : 0;
  7002. var theadRows = createRows(rowHeaders, columns, theadRowHeaders, columnHeaders);
  7003. append(thead, theadRows);
  7004. }
  7005. var tbody = SugarElement.fromTag('tbody');
  7006. append$1(table, tbody);
  7007. var numRows = rowHeadersGoInThead ? rows - actualRowHeaders : rows;
  7008. var numRowHeaders = rowHeadersGoInThead ? 0 : rowHeaders;
  7009. var tbodyRows = createRows(numRows, columns, numRowHeaders, columnHeaders);
  7010. append(tbody, tbodyRows);
  7011. return table;
  7012. };
  7013. var get$2 = function (element) {
  7014. return element.dom.innerHTML;
  7015. };
  7016. var getOuter = function (element) {
  7017. var container = SugarElement.fromTag('div');
  7018. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  7019. append$1(container, clone);
  7020. return get$2(container);
  7021. };
  7022. var placeCaretInCell = function (editor, cell) {
  7023. editor.selection.select(cell.dom, true);
  7024. editor.selection.collapse(true);
  7025. };
  7026. var selectFirstCellInTable = function (editor, tableElm) {
  7027. descendant(tableElm, 'td,th').each(curry(placeCaretInCell, editor));
  7028. };
  7029. var fireEvents = function (editor, table) {
  7030. each$2(descendants(table, 'tr'), function (row) {
  7031. fireNewRow(editor, row.dom);
  7032. each$2(descendants(row, 'th,td'), function (cell) {
  7033. fireNewCell(editor, cell.dom);
  7034. });
  7035. });
  7036. };
  7037. var isPercentage = function (width) {
  7038. return isString(width) && width.indexOf('%') !== -1;
  7039. };
  7040. var insert = function (editor, columns, rows, colHeaders, rowHeaders) {
  7041. var defaultStyles = getDefaultStyles(editor);
  7042. var options = {
  7043. styles: defaultStyles,
  7044. attributes: getDefaultAttributes(editor),
  7045. colGroups: useColumnGroup(editor)
  7046. };
  7047. editor.undoManager.ignore(function () {
  7048. var table = render(rows, columns, rowHeaders, colHeaders, getTableHeaderType(editor), options);
  7049. set$2(table, 'data-mce-id', '__mce');
  7050. var html = getOuter(table);
  7051. editor.insertContent(html);
  7052. editor.addVisual();
  7053. });
  7054. return descendant(getBody(editor), 'table[data-mce-id="__mce"]').map(function (table) {
  7055. if (isPixelsForced(editor)) {
  7056. enforcePixels(editor, table);
  7057. } else if (isResponsiveForced(editor)) {
  7058. enforceNone(table);
  7059. } else if (isPercentagesForced(editor) || isPercentage(defaultStyles.width)) {
  7060. enforcePercentage(editor, table);
  7061. }
  7062. removeDataStyle(table);
  7063. remove$7(table, 'data-mce-id');
  7064. fireEvents(editor, table);
  7065. selectFirstCellInTable(editor, table);
  7066. return table.dom;
  7067. }).getOr(null);
  7068. };
  7069. var insertTableWithDataValidation = function (editor, rows, columns, options, errorMsg) {
  7070. if (options === void 0) {
  7071. options = {};
  7072. }
  7073. var checkInput = function (val) {
  7074. return isNumber(val) && val > 0;
  7075. };
  7076. if (checkInput(rows) && checkInput(columns)) {
  7077. var headerRows = options.headerRows || 0;
  7078. var headerColumns = options.headerColumns || 0;
  7079. return insert(editor, columns, rows, headerColumns, headerRows);
  7080. } else {
  7081. console.error(errorMsg);
  7082. return null;
  7083. }
  7084. };
  7085. var getClipboardElements = function (getClipboard) {
  7086. return function () {
  7087. return getClipboard().fold(function () {
  7088. return [];
  7089. }, function (elems) {
  7090. return map$1(elems, function (e) {
  7091. return e.dom;
  7092. });
  7093. });
  7094. };
  7095. };
  7096. var setClipboardElements = function (setClipboard) {
  7097. return function (elems) {
  7098. var elmsOpt = elems.length > 0 ? Optional.some(fromDom(elems)) : Optional.none();
  7099. setClipboard(elmsOpt);
  7100. };
  7101. };
  7102. var insertTable = function (editor) {
  7103. return function (columns, rows, options) {
  7104. if (options === void 0) {
  7105. options = {};
  7106. }
  7107. var table = insertTableWithDataValidation(editor, rows, columns, options, 'Invalid values for insertTable - rows and columns values are required to insert a table.');
  7108. editor.undoManager.add();
  7109. return table;
  7110. };
  7111. };
  7112. var getApi = function (editor, clipboard, resizeHandler, selectionTargets) {
  7113. return {
  7114. insertTable: insertTable(editor),
  7115. setClipboardRows: setClipboardElements(clipboard.setRows),
  7116. getClipboardRows: getClipboardElements(clipboard.getRows),
  7117. setClipboardCols: setClipboardElements(clipboard.setColumns),
  7118. getClipboardCols: getClipboardElements(clipboard.getColumns),
  7119. resizeHandler: resizeHandler,
  7120. selectionTargets: selectionTargets
  7121. };
  7122. };
  7123. var constrainSpan = function (element, property, value) {
  7124. var currentColspan = getAttrValue(element, property, 1);
  7125. if (value === 1 || currentColspan <= 1) {
  7126. remove$7(element, property);
  7127. } else {
  7128. set$2(element, property, Math.min(value, currentColspan));
  7129. }
  7130. };
  7131. var generateColGroup = function (house, minColRange, maxColRange) {
  7132. if (Warehouse.hasColumns(house)) {
  7133. var colsToCopy = filter$2(Warehouse.justColumns(house), function (col) {
  7134. return col.column >= minColRange && col.column < maxColRange;
  7135. });
  7136. var copiedCols = map$1(colsToCopy, function (c) {
  7137. var clonedCol = deep(c.element);
  7138. constrainSpan(clonedCol, 'span', maxColRange - minColRange);
  7139. return clonedCol;
  7140. });
  7141. var fakeColgroup = SugarElement.fromTag('colgroup');
  7142. append(fakeColgroup, copiedCols);
  7143. return [fakeColgroup];
  7144. } else {
  7145. return [];
  7146. }
  7147. };
  7148. var generateRows = function (house, minColRange, maxColRange) {
  7149. return map$1(house.all, function (row) {
  7150. var cellsToCopy = filter$2(row.cells, function (cell) {
  7151. return cell.column >= minColRange && cell.column < maxColRange;
  7152. });
  7153. var copiedCells = map$1(cellsToCopy, function (cell) {
  7154. var clonedCell = deep(cell.element);
  7155. constrainSpan(clonedCell, 'colspan', maxColRange - minColRange);
  7156. return clonedCell;
  7157. });
  7158. var fakeTR = SugarElement.fromTag('tr');
  7159. append(fakeTR, copiedCells);
  7160. return fakeTR;
  7161. });
  7162. };
  7163. var copyCols = function (table, target) {
  7164. var house = Warehouse.fromTable(table);
  7165. var details = onUnlockedCells(house, target);
  7166. return details.map(function (selectedCells) {
  7167. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  7168. var minColRange = selectedCells[0].column;
  7169. var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
  7170. var fakeColGroups = generateColGroup(house, minColRange, maxColRange);
  7171. var fakeRows = generateRows(house, minColRange, maxColRange);
  7172. return __spreadArray(__spreadArray([], fakeColGroups), fakeRows);
  7173. });
  7174. };
  7175. var copyRows = function (table, target, generators) {
  7176. var warehouse = Warehouse.fromTable(table);
  7177. var details = onCells(warehouse, target);
  7178. return details.bind(function (selectedCells) {
  7179. var grid = toGrid(warehouse, generators, false);
  7180. var rows = extractGridDetails(grid).rows;
  7181. var slicedGrid = rows.slice(selectedCells[0].row, selectedCells[selectedCells.length - 1].row + selectedCells[selectedCells.length - 1].rowspan);
  7182. var filteredGrid = bind$2(slicedGrid, function (row) {
  7183. var newCells = filter$2(row.cells, function (cell) {
  7184. return !cell.isLocked;
  7185. });
  7186. return newCells.length > 0 ? [__assign(__assign({}, row), { cells: newCells })] : [];
  7187. });
  7188. var slicedDetails = toDetailList(filteredGrid);
  7189. return someIf(slicedDetails.length > 0, slicedDetails);
  7190. }).map(function (slicedDetails) {
  7191. return copy(slicedDetails);
  7192. });
  7193. };
  7194. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  7195. var getTDTHOverallStyle = function (dom, elm, name) {
  7196. var cells = dom.select('td,th', elm);
  7197. var firstChildStyle;
  7198. var checkChildren = function (firstChildStyle, elms) {
  7199. for (var i = 0; i < elms.length; i++) {
  7200. var currentStyle = dom.getStyle(elms[i], name);
  7201. if (typeof firstChildStyle === 'undefined') {
  7202. firstChildStyle = currentStyle;
  7203. }
  7204. if (firstChildStyle !== currentStyle) {
  7205. return '';
  7206. }
  7207. }
  7208. return firstChildStyle;
  7209. };
  7210. return checkChildren(firstChildStyle, cells);
  7211. };
  7212. var applyAlign = function (editor, elm, name) {
  7213. if (name) {
  7214. editor.formatter.apply('align' + name, {}, elm);
  7215. }
  7216. };
  7217. var applyVAlign = function (editor, elm, name) {
  7218. if (name) {
  7219. editor.formatter.apply('valign' + name, {}, elm);
  7220. }
  7221. };
  7222. var unApplyAlign = function (editor, elm) {
  7223. global$2.each('left center right'.split(' '), function (name) {
  7224. editor.formatter.remove('align' + name, {}, elm);
  7225. });
  7226. };
  7227. var unApplyVAlign = function (editor, elm) {
  7228. global$2.each('top middle bottom'.split(' '), function (name) {
  7229. editor.formatter.remove('valign' + name, {}, elm);
  7230. });
  7231. };
  7232. var verticalAlignValues = [
  7233. {
  7234. text: 'None',
  7235. value: ''
  7236. },
  7237. {
  7238. text: 'Top',
  7239. value: 'top'
  7240. },
  7241. {
  7242. text: 'Middle',
  7243. value: 'middle'
  7244. },
  7245. {
  7246. text: 'Bottom',
  7247. value: 'bottom'
  7248. }
  7249. ];
  7250. var hexColour = function (value) {
  7251. return { value: value };
  7252. };
  7253. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  7254. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  7255. var isHexString = function (hex) {
  7256. return shorthandRegex.test(hex) || longformRegex.test(hex);
  7257. };
  7258. var normalizeHex = function (hex) {
  7259. return removeLeading(hex, '#').toUpperCase();
  7260. };
  7261. var fromString$1 = function (hex) {
  7262. return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  7263. };
  7264. var toHex = function (component) {
  7265. var hex = component.toString(16);
  7266. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  7267. };
  7268. var fromRgba = function (rgbaColour) {
  7269. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  7270. return hexColour(value);
  7271. };
  7272. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  7273. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  7274. var rgbaColour = function (red, green, blue, alpha) {
  7275. return {
  7276. red: red,
  7277. green: green,
  7278. blue: blue,
  7279. alpha: alpha
  7280. };
  7281. };
  7282. var fromStringValues = function (red, green, blue, alpha) {
  7283. var r = parseInt(red, 10);
  7284. var g = parseInt(green, 10);
  7285. var b = parseInt(blue, 10);
  7286. var a = parseFloat(alpha);
  7287. return rgbaColour(r, g, b, a);
  7288. };
  7289. var fromString = function (rgbaString) {
  7290. if (rgbaString === 'transparent') {
  7291. return Optional.some(rgbaColour(0, 0, 0, 0));
  7292. }
  7293. var rgbMatch = rgbRegex.exec(rgbaString);
  7294. if (rgbMatch !== null) {
  7295. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  7296. }
  7297. var rgbaMatch = rgbaRegex.exec(rgbaString);
  7298. if (rgbaMatch !== null) {
  7299. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  7300. }
  7301. return Optional.none();
  7302. };
  7303. var anyToHex = function (color) {
  7304. return fromString$1(color).orThunk(function () {
  7305. return fromString(color).map(fromRgba);
  7306. }).getOrThunk(function () {
  7307. var canvas = document.createElement('canvas');
  7308. canvas.height = 1;
  7309. canvas.width = 1;
  7310. var canvasContext = canvas.getContext('2d');
  7311. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  7312. canvasContext.fillStyle = '#FFFFFF';
  7313. canvasContext.fillStyle = color;
  7314. canvasContext.fillRect(0, 0, 1, 1);
  7315. var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  7316. var r = rgba[0];
  7317. var g = rgba[1];
  7318. var b = rgba[2];
  7319. var a = rgba[3];
  7320. return fromRgba(rgbaColour(r, g, b, a));
  7321. });
  7322. };
  7323. var singleton = function (doRevoke) {
  7324. var subject = Cell(Optional.none());
  7325. var revoke = function () {
  7326. return subject.get().each(doRevoke);
  7327. };
  7328. var clear = function () {
  7329. revoke();
  7330. subject.set(Optional.none());
  7331. };
  7332. var isSet = function () {
  7333. return subject.get().isSome();
  7334. };
  7335. var get = function () {
  7336. return subject.get();
  7337. };
  7338. var set = function (s) {
  7339. revoke();
  7340. subject.set(Optional.some(s));
  7341. };
  7342. return {
  7343. clear: clear,
  7344. isSet: isSet,
  7345. get: get,
  7346. set: set
  7347. };
  7348. };
  7349. var unbindable = function () {
  7350. return singleton(function (s) {
  7351. return s.unbind();
  7352. });
  7353. };
  7354. var value = function () {
  7355. var subject = singleton(noop);
  7356. var on = function (f) {
  7357. return subject.get().each(f);
  7358. };
  7359. return __assign(__assign({}, subject), { on: on });
  7360. };
  7361. var onSetupToggle = function (editor, selections, formatName, formatValue) {
  7362. return function (api) {
  7363. var boundCallback = unbindable();
  7364. var isNone = isEmpty$1(formatValue);
  7365. var init = function () {
  7366. var selectedCells = getCellsFromSelection(selections);
  7367. var checkNode = function (cell) {
  7368. return editor.formatter.match(formatName, { value: formatValue }, cell.dom, isNone);
  7369. };
  7370. if (isNone) {
  7371. api.setActive(!exists(selectedCells, checkNode));
  7372. boundCallback.set(editor.formatter.formatChanged(formatName, function (match) {
  7373. return api.setActive(!match);
  7374. }, true));
  7375. } else {
  7376. api.setActive(forall(selectedCells, checkNode));
  7377. boundCallback.set(editor.formatter.formatChanged(formatName, api.setActive, false, { value: formatValue }));
  7378. }
  7379. };
  7380. editor.initialized ? init() : editor.on('init', init);
  7381. return boundCallback.clear;
  7382. };
  7383. };
  7384. var isListGroup = function (item) {
  7385. return hasNonNullableKey(item, 'menu');
  7386. };
  7387. var buildListItems = function (items) {
  7388. return map$1(items, function (item) {
  7389. var text = item.text || item.title;
  7390. if (isListGroup(item)) {
  7391. return {
  7392. text: text,
  7393. items: buildListItems(item.menu)
  7394. };
  7395. } else {
  7396. return {
  7397. text: text,
  7398. value: item.value
  7399. };
  7400. }
  7401. });
  7402. };
  7403. var buildMenuItems = function (editor, selections, items, format, onAction) {
  7404. return map$1(items, function (item) {
  7405. var text = item.text || item.title;
  7406. if (isListGroup(item)) {
  7407. return {
  7408. type: 'nestedmenuitem',
  7409. text: text,
  7410. getSubmenuItems: function () {
  7411. return buildMenuItems(editor, selections, item.menu, format, onAction);
  7412. }
  7413. };
  7414. } else {
  7415. return {
  7416. text: text,
  7417. type: 'togglemenuitem',
  7418. onAction: function () {
  7419. return onAction(item.value);
  7420. },
  7421. onSetup: onSetupToggle(editor, selections, format, item.value)
  7422. };
  7423. }
  7424. });
  7425. };
  7426. var applyTableCellStyle = function (editor, style) {
  7427. return function (value) {
  7428. var _a;
  7429. editor.execCommand('mceTableApplyCellStyle', false, (_a = {}, _a[style] = value, _a));
  7430. };
  7431. };
  7432. var filterNoneItem = function (list) {
  7433. return bind$2(list, function (item) {
  7434. if (isListGroup(item)) {
  7435. return [__assign(__assign({}, item), { menu: filterNoneItem(item.menu) })];
  7436. } else {
  7437. return isNotEmpty(item.value) ? [item] : [];
  7438. }
  7439. });
  7440. };
  7441. var generateMenuItemsCallback = function (editor, selections, items, format, onAction) {
  7442. return function (callback) {
  7443. return callback(buildMenuItems(editor, selections, items, format, onAction));
  7444. };
  7445. };
  7446. var buildColorMenu = function (editor, colorList, style) {
  7447. var colorMap = map$1(colorList, function (entry) {
  7448. return {
  7449. text: entry.title,
  7450. value: '#' + anyToHex(entry.value).value,
  7451. type: 'choiceitem'
  7452. };
  7453. });
  7454. return [{
  7455. type: 'fancymenuitem',
  7456. fancytype: 'colorswatch',
  7457. initData: {
  7458. colors: colorMap.length > 0 ? colorMap : undefined,
  7459. allowCustomColors: false
  7460. },
  7461. onAction: function (data) {
  7462. var _a;
  7463. var value = data.value === 'remove' ? '' : data.value;
  7464. editor.execCommand('mceTableApplyCellStyle', false, (_a = {}, _a[style] = value, _a));
  7465. }
  7466. }];
  7467. };
  7468. var changeRowHeader = function (editor) {
  7469. return function () {
  7470. var currentType = editor.queryCommandValue('mceTableRowType');
  7471. var newType = currentType === 'header' ? 'body' : 'header';
  7472. editor.execCommand('mceTableRowType', false, { type: newType });
  7473. };
  7474. };
  7475. var changeColumnHeader = function (editor) {
  7476. return function () {
  7477. var currentType = editor.queryCommandValue('mceTableColType');
  7478. var newType = currentType === 'th' ? 'td' : 'th';
  7479. editor.execCommand('mceTableColType', false, { type: newType });
  7480. };
  7481. };
  7482. var getClassList$1 = function (editor) {
  7483. var classes = buildListItems(getCellClassList(editor));
  7484. if (classes.length > 0) {
  7485. return Optional.some({
  7486. name: 'class',
  7487. type: 'listbox',
  7488. label: 'Class',
  7489. items: classes
  7490. });
  7491. }
  7492. return Optional.none();
  7493. };
  7494. var children = [
  7495. {
  7496. name: 'width',
  7497. type: 'input',
  7498. label: 'Width'
  7499. },
  7500. {
  7501. name: 'height',
  7502. type: 'input',
  7503. label: 'Height'
  7504. },
  7505. {
  7506. name: 'celltype',
  7507. type: 'listbox',
  7508. label: 'Cell type',
  7509. items: [
  7510. {
  7511. text: 'Cell',
  7512. value: 'td'
  7513. },
  7514. {
  7515. text: 'Header cell',
  7516. value: 'th'
  7517. }
  7518. ]
  7519. },
  7520. {
  7521. name: 'scope',
  7522. type: 'listbox',
  7523. label: 'Scope',
  7524. items: [
  7525. {
  7526. text: 'None',
  7527. value: ''
  7528. },
  7529. {
  7530. text: 'Row',
  7531. value: 'row'
  7532. },
  7533. {
  7534. text: 'Column',
  7535. value: 'col'
  7536. },
  7537. {
  7538. text: 'Row group',
  7539. value: 'rowgroup'
  7540. },
  7541. {
  7542. text: 'Column group',
  7543. value: 'colgroup'
  7544. }
  7545. ]
  7546. },
  7547. {
  7548. name: 'halign',
  7549. type: 'listbox',
  7550. label: 'Horizontal align',
  7551. items: [
  7552. {
  7553. text: 'None',
  7554. value: ''
  7555. },
  7556. {
  7557. text: 'Left',
  7558. value: 'left'
  7559. },
  7560. {
  7561. text: 'Center',
  7562. value: 'center'
  7563. },
  7564. {
  7565. text: 'Right',
  7566. value: 'right'
  7567. }
  7568. ]
  7569. },
  7570. {
  7571. name: 'valign',
  7572. type: 'listbox',
  7573. label: 'Vertical align',
  7574. items: verticalAlignValues
  7575. }
  7576. ];
  7577. var getItems$2 = function (editor) {
  7578. return children.concat(getClassList$1(editor).toArray());
  7579. };
  7580. var getAdvancedTab = function (editor, dialogName) {
  7581. var emptyBorderStyle = [{
  7582. text: 'Select...',
  7583. value: ''
  7584. }];
  7585. var advTabItems = [
  7586. {
  7587. name: 'borderstyle',
  7588. type: 'listbox',
  7589. label: 'Border style',
  7590. items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
  7591. },
  7592. {
  7593. name: 'bordercolor',
  7594. type: 'colorinput',
  7595. label: 'Border color'
  7596. },
  7597. {
  7598. name: 'backgroundcolor',
  7599. type: 'colorinput',
  7600. label: 'Background color'
  7601. }
  7602. ];
  7603. var borderWidth = {
  7604. name: 'borderwidth',
  7605. type: 'input',
  7606. label: 'Border width'
  7607. };
  7608. var items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
  7609. return {
  7610. title: 'Advanced',
  7611. name: 'advanced',
  7612. items: items
  7613. };
  7614. };
  7615. var modifiers = function (testTruthy) {
  7616. return function (editor, node) {
  7617. var dom = editor.dom;
  7618. var setAttrib = function (attr, value) {
  7619. if (!testTruthy || value) {
  7620. dom.setAttrib(node, attr, value);
  7621. }
  7622. };
  7623. var setStyle = function (prop, value) {
  7624. if (!testTruthy || value) {
  7625. dom.setStyle(node, prop, value);
  7626. }
  7627. };
  7628. var setFormat = function (formatName, value) {
  7629. if (!testTruthy || value) {
  7630. if (value === '') {
  7631. editor.formatter.remove(formatName, { value: null }, node, true);
  7632. } else {
  7633. editor.formatter.apply(formatName, { value: value }, node);
  7634. }
  7635. }
  7636. };
  7637. return {
  7638. setAttrib: setAttrib,
  7639. setStyle: setStyle,
  7640. setFormat: setFormat
  7641. };
  7642. };
  7643. };
  7644. var DomModifier = {
  7645. normal: modifiers(false),
  7646. ifTruthy: modifiers(true)
  7647. };
  7648. var rgbToHex = function (dom) {
  7649. return function (value) {
  7650. return startsWith(value, 'rgb') ? dom.toHex(value) : value;
  7651. };
  7652. };
  7653. var extractAdvancedStyles = function (dom, elm) {
  7654. var element = SugarElement.fromDom(elm);
  7655. return {
  7656. borderwidth: getRaw$2(element, 'border-width').getOr(''),
  7657. borderstyle: getRaw$2(element, 'border-style').getOr(''),
  7658. bordercolor: getRaw$2(element, 'border-color').map(rgbToHex(dom)).getOr(''),
  7659. backgroundcolor: getRaw$2(element, 'background-color').map(rgbToHex(dom)).getOr('')
  7660. };
  7661. };
  7662. var getSharedValues = function (data) {
  7663. var baseData = data[0];
  7664. var comparisonData = data.slice(1);
  7665. each$2(comparisonData, function (items) {
  7666. each$2(keys(baseData), function (key) {
  7667. each$1(items, function (itemValue, itemKey) {
  7668. var comparisonValue = baseData[key];
  7669. if (comparisonValue !== '' && key === itemKey) {
  7670. if (comparisonValue !== itemValue) {
  7671. baseData[key] = '';
  7672. }
  7673. }
  7674. });
  7675. });
  7676. });
  7677. return baseData;
  7678. };
  7679. var getAlignment = function (formats, formatName, editor, elm) {
  7680. return find$1(formats, function (name) {
  7681. return !isUndefined(editor.formatter.matchNode(elm, formatName + name));
  7682. }).getOr('');
  7683. };
  7684. var getHAlignment = curry(getAlignment, [
  7685. 'left',
  7686. 'center',
  7687. 'right'
  7688. ], 'align');
  7689. var getVAlignment = curry(getAlignment, [
  7690. 'top',
  7691. 'middle',
  7692. 'bottom'
  7693. ], 'valign');
  7694. var extractDataFromSettings = function (editor, hasAdvTableTab) {
  7695. var style = getDefaultStyles(editor);
  7696. var attrs = getDefaultAttributes(editor);
  7697. var extractAdvancedStyleData = function (dom) {
  7698. return {
  7699. borderstyle: get$c(style, 'border-style').getOr(''),
  7700. bordercolor: rgbToHex(dom)(get$c(style, 'border-color').getOr('')),
  7701. backgroundcolor: rgbToHex(dom)(get$c(style, 'background-color').getOr(''))
  7702. };
  7703. };
  7704. var defaultData = {
  7705. height: '',
  7706. width: '100%',
  7707. cellspacing: '',
  7708. cellpadding: '',
  7709. caption: false,
  7710. class: '',
  7711. align: '',
  7712. border: ''
  7713. };
  7714. var getBorder = function () {
  7715. var borderWidth = style['border-width'];
  7716. if (shouldStyleWithCss(editor) && borderWidth) {
  7717. return { border: borderWidth };
  7718. }
  7719. return get$c(attrs, 'border').fold(function () {
  7720. return {};
  7721. }, function (border) {
  7722. return { border: border };
  7723. });
  7724. };
  7725. var advStyle = hasAdvTableTab ? extractAdvancedStyleData(editor.dom) : {};
  7726. var getCellPaddingCellSpacing = function () {
  7727. var spacing = get$c(style, 'border-spacing').or(get$c(attrs, 'cellspacing')).fold(function () {
  7728. return {};
  7729. }, function (cellspacing) {
  7730. return { cellspacing: cellspacing };
  7731. });
  7732. var padding = get$c(style, 'border-padding').or(get$c(attrs, 'cellpadding')).fold(function () {
  7733. return {};
  7734. }, function (cellpadding) {
  7735. return { cellpadding: cellpadding };
  7736. });
  7737. return __assign(__assign({}, spacing), padding);
  7738. };
  7739. var data = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
  7740. return data;
  7741. };
  7742. var getRowType = function (elm) {
  7743. return table(SugarElement.fromDom(elm)).map(function (table) {
  7744. var target = { selection: fromDom(elm.cells) };
  7745. return getRowsType(table, target);
  7746. }).getOr('');
  7747. };
  7748. var extractDataFromTableElement = function (editor, elm, hasAdvTableTab) {
  7749. var getBorder = function (dom, elm) {
  7750. var optBorderWidth = getRaw$2(SugarElement.fromDom(elm), 'border-width');
  7751. if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
  7752. return optBorderWidth.getOr('');
  7753. }
  7754. return dom.getAttrib(elm, 'border') || getTDTHOverallStyle(editor.dom, elm, 'border-width') || getTDTHOverallStyle(editor.dom, elm, 'border');
  7755. };
  7756. var dom = editor.dom;
  7757. var cellspacing = shouldStyleWithCss(editor) ? dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing') : dom.getAttrib(elm, 'cellspacing') || dom.getStyle(elm, 'border-spacing');
  7758. var cellpadding = shouldStyleWithCss(editor) ? getTDTHOverallStyle(dom, elm, 'padding') || dom.getAttrib(elm, 'cellpadding') : dom.getAttrib(elm, 'cellpadding') || getTDTHOverallStyle(dom, elm, 'padding');
  7759. return __assign({
  7760. width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
  7761. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  7762. cellspacing: cellspacing,
  7763. cellpadding: cellpadding,
  7764. border: getBorder(dom, elm),
  7765. caption: !!dom.select('caption', elm)[0],
  7766. class: dom.getAttrib(elm, 'class', ''),
  7767. align: getHAlignment(editor, elm)
  7768. }, hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
  7769. };
  7770. var extractDataFromRowElement = function (editor, elm, hasAdvancedRowTab) {
  7771. var dom = editor.dom;
  7772. return __assign({
  7773. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  7774. class: dom.getAttrib(elm, 'class', ''),
  7775. type: getRowType(elm),
  7776. align: getHAlignment(editor, elm)
  7777. }, hasAdvancedRowTab ? extractAdvancedStyles(dom, elm) : {});
  7778. };
  7779. var extractDataFromCellElement = function (editor, cell, hasAdvancedCellTab, column) {
  7780. var dom = editor.dom;
  7781. var colElm = column.getOr(cell);
  7782. var getStyle = function (element, style) {
  7783. return dom.getStyle(element, style) || dom.getAttrib(element, style);
  7784. };
  7785. return __assign({
  7786. width: getStyle(colElm, 'width'),
  7787. height: getStyle(cell, 'height'),
  7788. scope: dom.getAttrib(cell, 'scope'),
  7789. celltype: getNodeName(cell),
  7790. class: dom.getAttrib(cell, 'class', ''),
  7791. halign: getHAlignment(editor, cell),
  7792. valign: getVAlignment(editor, cell)
  7793. }, hasAdvancedCellTab ? extractAdvancedStyles(dom, cell) : {});
  7794. };
  7795. var getSelectedCells = function (table, cells) {
  7796. var warehouse = Warehouse.fromTable(table);
  7797. var allCells = Warehouse.justCells(warehouse);
  7798. var filtered = filter$2(allCells, function (cellA) {
  7799. return exists(cells, function (cellB) {
  7800. return eq$1(cellA.element, cellB);
  7801. });
  7802. });
  7803. return map$1(filtered, function (cell) {
  7804. return {
  7805. element: cell.element.dom,
  7806. column: Warehouse.getColumnAt(warehouse, cell.column).map(function (col) {
  7807. return col.element.dom;
  7808. })
  7809. };
  7810. });
  7811. };
  7812. var updateSimpleProps$1 = function (modifier, colModifier, data) {
  7813. modifier.setAttrib('scope', data.scope);
  7814. modifier.setAttrib('class', data.class);
  7815. modifier.setStyle('height', addPxSuffix(data.height));
  7816. colModifier.setStyle('width', addPxSuffix(data.width));
  7817. };
  7818. var updateAdvancedProps$1 = function (modifier, data) {
  7819. modifier.setFormat('tablecellbackgroundcolor', data.backgroundcolor);
  7820. modifier.setFormat('tablecellbordercolor', data.bordercolor);
  7821. modifier.setFormat('tablecellborderstyle', data.borderstyle);
  7822. modifier.setFormat('tablecellborderwidth', addPxSuffix(data.borderwidth));
  7823. };
  7824. var applyStyleData$1 = function (editor, cells, data) {
  7825. var isSingleCell = cells.length === 1;
  7826. each$2(cells, function (item) {
  7827. var cellElm = item.element;
  7828. var modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
  7829. var colModifier = item.column.map(function (col) {
  7830. return isSingleCell ? DomModifier.normal(editor, col) : DomModifier.ifTruthy(editor, col);
  7831. }).getOr(modifier);
  7832. updateSimpleProps$1(modifier, colModifier, data);
  7833. if (hasAdvancedCellTab(editor)) {
  7834. updateAdvancedProps$1(modifier, data);
  7835. }
  7836. if (isSingleCell) {
  7837. unApplyAlign(editor, cellElm);
  7838. unApplyVAlign(editor, cellElm);
  7839. }
  7840. if (data.halign) {
  7841. applyAlign(editor, cellElm, data.halign);
  7842. }
  7843. if (data.valign) {
  7844. applyVAlign(editor, cellElm, data.valign);
  7845. }
  7846. });
  7847. };
  7848. var applyStructureData$1 = function (editor, data) {
  7849. editor.execCommand('mceTableCellType', false, {
  7850. type: data.celltype,
  7851. no_events: true
  7852. });
  7853. };
  7854. var applyCellData = function (editor, cells, oldData, data) {
  7855. var modifiedData = filter$1(data, function (value, key) {
  7856. return oldData[key] !== value;
  7857. });
  7858. if (size(modifiedData) > 0 && cells.length >= 1) {
  7859. table(cells[0]).each(function (table) {
  7860. var selectedCells = getSelectedCells(table, cells);
  7861. var styleModified = size(filter$1(modifiedData, function (_value, key) {
  7862. return key !== 'scope' && key !== 'celltype';
  7863. })) > 0;
  7864. var structureModified = has$1(modifiedData, 'celltype');
  7865. if (styleModified || has$1(modifiedData, 'scope')) {
  7866. applyStyleData$1(editor, selectedCells, data);
  7867. }
  7868. if (structureModified) {
  7869. applyStructureData$1(editor, data);
  7870. }
  7871. fireTableModified(editor, table.dom, {
  7872. structure: structureModified,
  7873. style: styleModified
  7874. });
  7875. });
  7876. }
  7877. };
  7878. var onSubmitCellForm = function (editor, cells, oldData, api) {
  7879. var data = api.getData();
  7880. api.close();
  7881. editor.undoManager.transact(function () {
  7882. applyCellData(editor, cells, oldData, data);
  7883. editor.focus();
  7884. });
  7885. };
  7886. var getData = function (editor, cells) {
  7887. var cellsData = table(cells[0]).map(function (table) {
  7888. return map$1(getSelectedCells(table, cells), function (item) {
  7889. return extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column);
  7890. });
  7891. });
  7892. return getSharedValues(cellsData.getOrDie());
  7893. };
  7894. var open$2 = function (editor, selections) {
  7895. var cells = getCellsFromSelection(selections);
  7896. if (cells.length === 0) {
  7897. return;
  7898. }
  7899. var data = getData(editor, cells);
  7900. var dialogTabPanel = {
  7901. type: 'tabpanel',
  7902. tabs: [
  7903. {
  7904. title: 'General',
  7905. name: 'general',
  7906. items: getItems$2(editor)
  7907. },
  7908. getAdvancedTab(editor, 'cell')
  7909. ]
  7910. };
  7911. var dialogPanel = {
  7912. type: 'panel',
  7913. items: [{
  7914. type: 'grid',
  7915. columns: 2,
  7916. items: getItems$2(editor)
  7917. }]
  7918. };
  7919. editor.windowManager.open({
  7920. title: 'Cell Properties',
  7921. size: 'normal',
  7922. body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
  7923. buttons: [
  7924. {
  7925. type: 'cancel',
  7926. name: 'cancel',
  7927. text: 'Cancel'
  7928. },
  7929. {
  7930. type: 'submit',
  7931. name: 'save',
  7932. text: 'Save',
  7933. primary: true
  7934. }
  7935. ],
  7936. initialData: data,
  7937. onSubmit: curry(onSubmitCellForm, editor, cells, data)
  7938. });
  7939. };
  7940. var getClassList = function (editor) {
  7941. var classes = buildListItems(getRowClassList(editor));
  7942. if (classes.length > 0) {
  7943. return Optional.some({
  7944. name: 'class',
  7945. type: 'listbox',
  7946. label: 'Class',
  7947. items: classes
  7948. });
  7949. }
  7950. return Optional.none();
  7951. };
  7952. var formChildren = [
  7953. {
  7954. type: 'listbox',
  7955. name: 'type',
  7956. label: 'Row type',
  7957. items: [
  7958. {
  7959. text: 'Header',
  7960. value: 'header'
  7961. },
  7962. {
  7963. text: 'Body',
  7964. value: 'body'
  7965. },
  7966. {
  7967. text: 'Footer',
  7968. value: 'footer'
  7969. }
  7970. ]
  7971. },
  7972. {
  7973. type: 'listbox',
  7974. name: 'align',
  7975. label: 'Alignment',
  7976. items: [
  7977. {
  7978. text: 'None',
  7979. value: ''
  7980. },
  7981. {
  7982. text: 'Left',
  7983. value: 'left'
  7984. },
  7985. {
  7986. text: 'Center',
  7987. value: 'center'
  7988. },
  7989. {
  7990. text: 'Right',
  7991. value: 'right'
  7992. }
  7993. ]
  7994. },
  7995. {
  7996. label: 'Height',
  7997. name: 'height',
  7998. type: 'input'
  7999. }
  8000. ];
  8001. var getItems$1 = function (editor) {
  8002. return formChildren.concat(getClassList(editor).toArray());
  8003. };
  8004. var updateSimpleProps = function (modifier, data) {
  8005. modifier.setAttrib('class', data.class);
  8006. modifier.setStyle('height', addPxSuffix(data.height));
  8007. };
  8008. var updateAdvancedProps = function (modifier, data) {
  8009. modifier.setStyle('background-color', data.backgroundcolor);
  8010. modifier.setStyle('border-color', data.bordercolor);
  8011. modifier.setStyle('border-style', data.borderstyle);
  8012. };
  8013. var applyStyleData = function (editor, rows, data, oldData) {
  8014. var isSingleRow = rows.length === 1;
  8015. each$2(rows, function (rowElm) {
  8016. var modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
  8017. updateSimpleProps(modifier, data);
  8018. if (hasAdvancedRowTab(editor)) {
  8019. updateAdvancedProps(modifier, data);
  8020. }
  8021. if (data.align !== oldData.align) {
  8022. unApplyAlign(editor, rowElm);
  8023. applyAlign(editor, rowElm, data.align);
  8024. }
  8025. });
  8026. };
  8027. var applyStructureData = function (editor, data) {
  8028. editor.execCommand('mceTableRowType', false, {
  8029. type: data.type,
  8030. no_events: true
  8031. });
  8032. };
  8033. var applyRowData = function (editor, rows, oldData, data) {
  8034. var modifiedData = filter$1(data, function (value, key) {
  8035. return oldData[key] !== value;
  8036. });
  8037. if (size(modifiedData) > 0) {
  8038. var typeModified_1 = has$1(modifiedData, 'type');
  8039. var styleModified_1 = typeModified_1 ? size(modifiedData) > 1 : true;
  8040. if (styleModified_1) {
  8041. applyStyleData(editor, rows, data, oldData);
  8042. }
  8043. if (typeModified_1) {
  8044. applyStructureData(editor, data);
  8045. }
  8046. table(SugarElement.fromDom(rows[0])).each(function (table) {
  8047. return fireTableModified(editor, table.dom, {
  8048. structure: typeModified_1,
  8049. style: styleModified_1
  8050. });
  8051. });
  8052. }
  8053. };
  8054. var onSubmitRowForm = function (editor, rows, oldData, api) {
  8055. var data = api.getData();
  8056. api.close();
  8057. editor.undoManager.transact(function () {
  8058. applyRowData(editor, rows, oldData, data);
  8059. editor.focus();
  8060. });
  8061. };
  8062. var open$1 = function (editor) {
  8063. var rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
  8064. if (rows.length === 0) {
  8065. return;
  8066. }
  8067. var rowsData = map$1(rows, function (rowElm) {
  8068. return extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor));
  8069. });
  8070. var data = getSharedValues(rowsData);
  8071. var dialogTabPanel = {
  8072. type: 'tabpanel',
  8073. tabs: [
  8074. {
  8075. title: 'General',
  8076. name: 'general',
  8077. items: getItems$1(editor)
  8078. },
  8079. getAdvancedTab(editor, 'row')
  8080. ]
  8081. };
  8082. var dialogPanel = {
  8083. type: 'panel',
  8084. items: [{
  8085. type: 'grid',
  8086. columns: 2,
  8087. items: getItems$1(editor)
  8088. }]
  8089. };
  8090. editor.windowManager.open({
  8091. title: 'Row Properties',
  8092. size: 'normal',
  8093. body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
  8094. buttons: [
  8095. {
  8096. type: 'cancel',
  8097. name: 'cancel',
  8098. text: 'Cancel'
  8099. },
  8100. {
  8101. type: 'submit',
  8102. name: 'save',
  8103. text: 'Save',
  8104. primary: true
  8105. }
  8106. ],
  8107. initialData: data,
  8108. onSubmit: curry(onSubmitRowForm, editor, map$1(rows, function (r) {
  8109. return r.dom;
  8110. }), data)
  8111. });
  8112. };
  8113. var getItems = function (editor, classes, insertNewTable) {
  8114. var rowColCountItems = !insertNewTable ? [] : [
  8115. {
  8116. type: 'input',
  8117. name: 'cols',
  8118. label: 'Cols',
  8119. inputMode: 'numeric'
  8120. },
  8121. {
  8122. type: 'input',
  8123. name: 'rows',
  8124. label: 'Rows',
  8125. inputMode: 'numeric'
  8126. }
  8127. ];
  8128. var alwaysItems = [
  8129. {
  8130. type: 'input',
  8131. name: 'width',
  8132. label: 'Width'
  8133. },
  8134. {
  8135. type: 'input',
  8136. name: 'height',
  8137. label: 'Height'
  8138. }
  8139. ];
  8140. var appearanceItems = hasAppearanceOptions(editor) ? [
  8141. {
  8142. type: 'input',
  8143. name: 'cellspacing',
  8144. label: 'Cell spacing',
  8145. inputMode: 'numeric'
  8146. },
  8147. {
  8148. type: 'input',
  8149. name: 'cellpadding',
  8150. label: 'Cell padding',
  8151. inputMode: 'numeric'
  8152. },
  8153. {
  8154. type: 'input',
  8155. name: 'border',
  8156. label: 'Border width'
  8157. },
  8158. {
  8159. type: 'label',
  8160. label: 'Caption',
  8161. items: [{
  8162. type: 'checkbox',
  8163. name: 'caption',
  8164. label: 'Show caption'
  8165. }]
  8166. }
  8167. ] : [];
  8168. var alignmentItem = [{
  8169. type: 'listbox',
  8170. name: 'align',
  8171. label: 'Alignment',
  8172. items: [
  8173. {
  8174. text: 'None',
  8175. value: ''
  8176. },
  8177. {
  8178. text: 'Left',
  8179. value: 'left'
  8180. },
  8181. {
  8182. text: 'Center',
  8183. value: 'center'
  8184. },
  8185. {
  8186. text: 'Right',
  8187. value: 'right'
  8188. }
  8189. ]
  8190. }];
  8191. var classListItem = classes.length > 0 ? [{
  8192. type: 'listbox',
  8193. name: 'class',
  8194. label: 'Class',
  8195. items: classes
  8196. }] : [];
  8197. return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
  8198. };
  8199. var styleTDTH = function (dom, elm, name, value) {
  8200. if (elm.tagName === 'TD' || elm.tagName === 'TH') {
  8201. if (isString(name)) {
  8202. dom.setStyle(elm, name, value);
  8203. } else {
  8204. dom.setStyle(elm, name);
  8205. }
  8206. } else {
  8207. if (elm.children) {
  8208. for (var i = 0; i < elm.children.length; i++) {
  8209. styleTDTH(dom, elm.children[i], name, value);
  8210. }
  8211. }
  8212. }
  8213. };
  8214. var applyDataToElement = function (editor, tableElm, data) {
  8215. var dom = editor.dom;
  8216. var attrs = {};
  8217. var styles = {};
  8218. attrs.class = data.class;
  8219. styles.height = addPxSuffix(data.height);
  8220. if (dom.getAttrib(tableElm, 'width') && !shouldStyleWithCss(editor)) {
  8221. attrs.width = removePxSuffix(data.width);
  8222. } else {
  8223. styles.width = addPxSuffix(data.width);
  8224. }
  8225. if (shouldStyleWithCss(editor)) {
  8226. styles['border-width'] = addPxSuffix(data.border);
  8227. styles['border-spacing'] = addPxSuffix(data.cellspacing);
  8228. } else {
  8229. attrs.border = data.border;
  8230. attrs.cellpadding = data.cellpadding;
  8231. attrs.cellspacing = data.cellspacing;
  8232. }
  8233. if (shouldStyleWithCss(editor) && tableElm.children) {
  8234. for (var i = 0; i < tableElm.children.length; i++) {
  8235. styleTDTH(dom, tableElm.children[i], {
  8236. 'border-width': addPxSuffix(data.border),
  8237. 'padding': addPxSuffix(data.cellpadding)
  8238. });
  8239. if (hasAdvancedTableTab(editor)) {
  8240. styleTDTH(dom, tableElm.children[i], { 'border-color': data.bordercolor });
  8241. }
  8242. }
  8243. }
  8244. if (hasAdvancedTableTab(editor)) {
  8245. styles['background-color'] = data.backgroundcolor;
  8246. styles['border-color'] = data.bordercolor;
  8247. styles['border-style'] = data.borderstyle;
  8248. }
  8249. attrs.style = dom.serializeStyle(__assign(__assign({}, getDefaultStyles(editor)), styles));
  8250. dom.setAttribs(tableElm, __assign(__assign({}, getDefaultAttributes(editor)), attrs));
  8251. };
  8252. var onSubmitTableForm = function (editor, tableElm, oldData, api) {
  8253. var dom = editor.dom;
  8254. var data = api.getData();
  8255. var modifiedData = filter$1(data, function (value, key) {
  8256. return oldData[key] !== value;
  8257. });
  8258. api.close();
  8259. if (data.class === '') {
  8260. delete data.class;
  8261. }
  8262. editor.undoManager.transact(function () {
  8263. if (!tableElm) {
  8264. var cols = parseInt(data.cols, 10) || 1;
  8265. var rows = parseInt(data.rows, 10) || 1;
  8266. tableElm = insert(editor, cols, rows, 0, 0);
  8267. }
  8268. if (size(modifiedData) > 0) {
  8269. applyDataToElement(editor, tableElm, data);
  8270. var captionElm = dom.select('caption', tableElm)[0];
  8271. if (captionElm && !data.caption || !captionElm && data.caption) {
  8272. editor.execCommand('mceTableToggleCaption');
  8273. }
  8274. if (data.align === '') {
  8275. unApplyAlign(editor, tableElm);
  8276. } else {
  8277. applyAlign(editor, tableElm, data.align);
  8278. }
  8279. }
  8280. editor.focus();
  8281. editor.addVisual();
  8282. if (size(modifiedData) > 0) {
  8283. var captionModified = has$1(modifiedData, 'caption');
  8284. var styleModified = captionModified ? size(modifiedData) > 1 : true;
  8285. fireTableModified(editor, tableElm, {
  8286. structure: captionModified,
  8287. style: styleModified
  8288. });
  8289. }
  8290. });
  8291. };
  8292. var open = function (editor, insertNewTable) {
  8293. var dom = editor.dom;
  8294. var tableElm;
  8295. var data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
  8296. if (insertNewTable === false) {
  8297. tableElm = dom.getParent(editor.selection.getStart(), 'table', editor.getBody());
  8298. if (tableElm) {
  8299. data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
  8300. } else {
  8301. if (hasAdvancedTableTab(editor)) {
  8302. data.borderstyle = '';
  8303. data.bordercolor = '';
  8304. data.backgroundcolor = '';
  8305. }
  8306. }
  8307. } else {
  8308. data.cols = '1';
  8309. data.rows = '1';
  8310. if (hasAdvancedTableTab(editor)) {
  8311. data.borderstyle = '';
  8312. data.bordercolor = '';
  8313. data.backgroundcolor = '';
  8314. }
  8315. }
  8316. var classes = buildListItems(getTableClassList(editor));
  8317. if (classes.length > 0) {
  8318. if (data.class) {
  8319. data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
  8320. }
  8321. }
  8322. var generalPanel = {
  8323. type: 'grid',
  8324. columns: 2,
  8325. items: getItems(editor, classes, insertNewTable)
  8326. };
  8327. var nonAdvancedForm = function () {
  8328. return {
  8329. type: 'panel',
  8330. items: [generalPanel]
  8331. };
  8332. };
  8333. var advancedForm = function () {
  8334. return {
  8335. type: 'tabpanel',
  8336. tabs: [
  8337. {
  8338. title: 'General',
  8339. name: 'general',
  8340. items: [generalPanel]
  8341. },
  8342. getAdvancedTab(editor, 'table')
  8343. ]
  8344. };
  8345. };
  8346. var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
  8347. editor.windowManager.open({
  8348. title: 'Table Properties',
  8349. size: 'normal',
  8350. body: dialogBody,
  8351. onSubmit: curry(onSubmitTableForm, editor, tableElm, data),
  8352. buttons: [
  8353. {
  8354. type: 'cancel',
  8355. name: 'cancel',
  8356. text: 'Cancel'
  8357. },
  8358. {
  8359. type: 'submit',
  8360. name: 'save',
  8361. text: 'Save',
  8362. primary: true
  8363. }
  8364. ],
  8365. initialData: data
  8366. });
  8367. };
  8368. var getSelectionStartCellOrCaption = function (editor) {
  8369. return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  8370. };
  8371. var getSelectionStartCell = function (editor) {
  8372. return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
  8373. };
  8374. var registerCommands = function (editor, actions, cellSelection, selections, clipboard) {
  8375. var isRoot = getIsRoot(editor);
  8376. var eraseTable = function () {
  8377. return getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8378. table(cellOrCaption, isRoot).filter(not(isRoot)).each(function (table) {
  8379. var cursor = SugarElement.fromText('');
  8380. after$5(table, cursor);
  8381. remove$5(table);
  8382. if (editor.dom.isEmpty(editor.getBody())) {
  8383. editor.setContent('');
  8384. editor.selection.setCursorLocation();
  8385. } else {
  8386. var rng = editor.dom.createRng();
  8387. rng.setStart(cursor.dom, 0);
  8388. rng.setEnd(cursor.dom, 0);
  8389. editor.selection.setRng(rng);
  8390. editor.nodeChanged();
  8391. }
  8392. });
  8393. });
  8394. };
  8395. var setSizingMode = function (sizing) {
  8396. return getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8397. var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
  8398. if (!isForcedSizing) {
  8399. table(cellOrCaption, isRoot).each(function (table) {
  8400. if (sizing === 'relative' && !isPercentSizing(table)) {
  8401. enforcePercentage(editor, table);
  8402. } else if (sizing === 'fixed' && !isPixelSizing(table)) {
  8403. enforcePixels(editor, table);
  8404. } else if (sizing === 'responsive' && !isNoneSizing(table)) {
  8405. enforceNone(table);
  8406. }
  8407. removeDataStyle(table);
  8408. fireTableModified(editor, table.dom, structureModified);
  8409. });
  8410. }
  8411. });
  8412. };
  8413. var getTableFromCell = function (cell) {
  8414. return table(cell, isRoot);
  8415. };
  8416. var performActionOnSelection = function (action) {
  8417. return getSelectionStartCell(editor).bind(function (cell) {
  8418. return getTableFromCell(cell).map(function (table) {
  8419. return action(table, cell);
  8420. });
  8421. });
  8422. };
  8423. var toggleTableClass = function (_ui, clazz) {
  8424. performActionOnSelection(function (table) {
  8425. editor.formatter.toggle('tableclass', { value: clazz }, table.dom);
  8426. fireTableModified(editor, table.dom, styleModified);
  8427. });
  8428. };
  8429. var toggleTableCellClass = function (_ui, clazz) {
  8430. performActionOnSelection(function (table) {
  8431. var selectedCells = getCellsFromSelection(selections);
  8432. var allHaveClass = forall(selectedCells, function (cell) {
  8433. return editor.formatter.match('tablecellclass', { value: clazz }, cell.dom);
  8434. });
  8435. var formatterAction = allHaveClass ? editor.formatter.remove : editor.formatter.apply;
  8436. each$2(selectedCells, function (cell) {
  8437. return formatterAction('tablecellclass', { value: clazz }, cell.dom);
  8438. });
  8439. fireTableModified(editor, table.dom, styleModified);
  8440. });
  8441. };
  8442. var toggleCaption = function () {
  8443. getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8444. table(cellOrCaption, isRoot).each(function (table) {
  8445. child$1(table, 'caption').fold(function () {
  8446. var caption = SugarElement.fromTag('caption');
  8447. append$1(caption, SugarElement.fromText('Caption'));
  8448. appendAt(table, caption, 0);
  8449. editor.selection.setCursorLocation(caption.dom, 0);
  8450. }, function (caption) {
  8451. if (isTag('caption')(cellOrCaption)) {
  8452. one('td', table).each(function (td) {
  8453. return editor.selection.setCursorLocation(td.dom, 0);
  8454. });
  8455. }
  8456. remove$5(caption);
  8457. });
  8458. fireTableModified(editor, table.dom, structureModified);
  8459. });
  8460. });
  8461. };
  8462. var postExecute = function (_data) {
  8463. editor.focus();
  8464. };
  8465. var actOnSelection = function (execute, noEvents) {
  8466. if (noEvents === void 0) {
  8467. noEvents = false;
  8468. }
  8469. return performActionOnSelection(function (table, startCell) {
  8470. var targets = forMenu(selections, table, startCell);
  8471. execute(table, targets, noEvents).each(postExecute);
  8472. });
  8473. };
  8474. var copyRowSelection = function () {
  8475. return performActionOnSelection(function (table, startCell) {
  8476. var targets = forMenu(selections, table, startCell);
  8477. var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), Optional.none());
  8478. return copyRows(table, targets, generators);
  8479. });
  8480. };
  8481. var copyColSelection = function () {
  8482. return performActionOnSelection(function (table, startCell) {
  8483. var targets = forMenu(selections, table, startCell);
  8484. return copyCols(table, targets);
  8485. });
  8486. };
  8487. var pasteOnSelection = function (execute, getRows) {
  8488. return getRows().each(function (rows) {
  8489. var clonedRows = map$1(rows, function (row) {
  8490. return deep(row);
  8491. });
  8492. performActionOnSelection(function (table, startCell) {
  8493. var generators = paste$1(SugarElement.fromDom(editor.getDoc()));
  8494. var targets = pasteRows(selections, startCell, clonedRows, generators);
  8495. execute(table, targets).each(postExecute);
  8496. });
  8497. });
  8498. };
  8499. var actOnType = function (getAction) {
  8500. return function (_ui, args) {
  8501. return get$c(args, 'type').each(function (type) {
  8502. actOnSelection(getAction(type), args.no_events);
  8503. });
  8504. };
  8505. };
  8506. each$1({
  8507. mceTableSplitCells: function () {
  8508. return actOnSelection(actions.unmergeCells);
  8509. },
  8510. mceTableMergeCells: function () {
  8511. return actOnSelection(actions.mergeCells);
  8512. },
  8513. mceTableInsertRowBefore: function () {
  8514. return actOnSelection(actions.insertRowsBefore);
  8515. },
  8516. mceTableInsertRowAfter: function () {
  8517. return actOnSelection(actions.insertRowsAfter);
  8518. },
  8519. mceTableInsertColBefore: function () {
  8520. return actOnSelection(actions.insertColumnsBefore);
  8521. },
  8522. mceTableInsertColAfter: function () {
  8523. return actOnSelection(actions.insertColumnsAfter);
  8524. },
  8525. mceTableDeleteCol: function () {
  8526. return actOnSelection(actions.deleteColumn);
  8527. },
  8528. mceTableDeleteRow: function () {
  8529. return actOnSelection(actions.deleteRow);
  8530. },
  8531. mceTableCutCol: function () {
  8532. return copyColSelection().each(function (selection) {
  8533. clipboard.setColumns(selection);
  8534. actOnSelection(actions.deleteColumn);
  8535. });
  8536. },
  8537. mceTableCutRow: function () {
  8538. return copyRowSelection().each(function (selection) {
  8539. clipboard.setRows(selection);
  8540. actOnSelection(actions.deleteRow);
  8541. });
  8542. },
  8543. mceTableCopyCol: function () {
  8544. return copyColSelection().each(function (selection) {
  8545. return clipboard.setColumns(selection);
  8546. });
  8547. },
  8548. mceTableCopyRow: function () {
  8549. return copyRowSelection().each(function (selection) {
  8550. return clipboard.setRows(selection);
  8551. });
  8552. },
  8553. mceTablePasteColBefore: function () {
  8554. return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
  8555. },
  8556. mceTablePasteColAfter: function () {
  8557. return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
  8558. },
  8559. mceTablePasteRowBefore: function () {
  8560. return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
  8561. },
  8562. mceTablePasteRowAfter: function () {
  8563. return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
  8564. },
  8565. mceTableDelete: eraseTable,
  8566. mceTableCellToggleClass: toggleTableCellClass,
  8567. mceTableToggleClass: toggleTableClass,
  8568. mceTableToggleCaption: toggleCaption,
  8569. mceTableSizingMode: function (_ui, sizing) {
  8570. return setSizingMode(sizing);
  8571. },
  8572. mceTableCellType: actOnType(function (type) {
  8573. return type === 'th' ? actions.makeCellsHeader : actions.unmakeCellsHeader;
  8574. }),
  8575. mceTableColType: actOnType(function (type) {
  8576. return type === 'th' ? actions.makeColumnsHeader : actions.unmakeColumnsHeader;
  8577. }),
  8578. mceTableRowType: actOnType(function (type) {
  8579. switch (type) {
  8580. case 'header':
  8581. return actions.makeRowsHeader;
  8582. case 'footer':
  8583. return actions.makeRowsFooter;
  8584. default:
  8585. return actions.makeRowsBody;
  8586. }
  8587. })
  8588. }, function (func, name) {
  8589. return editor.addCommand(name, func);
  8590. });
  8591. each$1({
  8592. mceTableProps: curry(open, editor, false),
  8593. mceTableRowProps: curry(open$1, editor),
  8594. mceTableCellProps: curry(open$2, editor, selections)
  8595. }, function (func, name) {
  8596. return editor.addCommand(name, function () {
  8597. return func();
  8598. });
  8599. });
  8600. editor.addCommand('mceInsertTable', function (_ui, args) {
  8601. if (isObject(args) && keys(args).length > 0) {
  8602. insertTableWithDataValidation(editor, args.rows, args.columns, args.options, 'Invalid values for mceInsertTable - rows and columns values are required to insert a table.');
  8603. } else {
  8604. open(editor, true);
  8605. }
  8606. });
  8607. editor.addCommand('mceTableApplyCellStyle', function (_ui, args) {
  8608. var getFormatName = function (style) {
  8609. return 'tablecell' + style.toLowerCase().replace('-', '');
  8610. };
  8611. if (!isObject(args)) {
  8612. return;
  8613. }
  8614. var cells = getCellsFromSelection(selections);
  8615. if (cells.length === 0) {
  8616. return;
  8617. }
  8618. var validArgs = filter$1(args, function (value, style) {
  8619. return editor.formatter.has(getFormatName(style)) && isString(value);
  8620. });
  8621. if (isEmpty(validArgs)) {
  8622. return;
  8623. }
  8624. each$1(validArgs, function (value, style) {
  8625. each$2(cells, function (cell) {
  8626. DomModifier.normal(editor, cell.dom).setFormat(getFormatName(style), value);
  8627. });
  8628. });
  8629. getTableFromCell(cells[0]).each(function (table) {
  8630. return fireTableModified(editor, table.dom, styleModified);
  8631. });
  8632. });
  8633. };
  8634. var registerQueryCommands = function (editor, actions, selections) {
  8635. var isRoot = getIsRoot(editor);
  8636. var lookupOnSelection = function (action) {
  8637. return getSelectionCell(getSelectionStart(editor)).bind(function (cell) {
  8638. return table(cell, isRoot).map(function (table) {
  8639. var targets = forMenu(selections, table, cell);
  8640. return action(table, targets);
  8641. });
  8642. }).getOr('');
  8643. };
  8644. each$1({
  8645. mceTableRowType: function () {
  8646. return lookupOnSelection(actions.getTableRowType);
  8647. },
  8648. mceTableCellType: function () {
  8649. return lookupOnSelection(actions.getTableCellType);
  8650. },
  8651. mceTableColType: function () {
  8652. return lookupOnSelection(actions.getTableColType);
  8653. }
  8654. }, function (func, name) {
  8655. return editor.addQueryValueHandler(name, func);
  8656. });
  8657. };
  8658. var Clipboard = function () {
  8659. var rows = value();
  8660. var cols = value();
  8661. return {
  8662. getRows: rows.get,
  8663. setRows: function (r) {
  8664. r.fold(rows.clear, rows.set);
  8665. cols.clear();
  8666. },
  8667. clearRows: rows.clear,
  8668. getColumns: cols.get,
  8669. setColumns: function (c) {
  8670. c.fold(cols.clear, cols.set);
  8671. rows.clear();
  8672. },
  8673. clearColumns: cols.clear
  8674. };
  8675. };
  8676. var genericBase = {
  8677. remove_similar: true,
  8678. inherit: false
  8679. };
  8680. var cellBase = __assign({ selector: 'td,th' }, genericBase);
  8681. var cellFormats = {
  8682. tablecellbackgroundcolor: __assign({ styles: { backgroundColor: '%value' } }, cellBase),
  8683. tablecellverticalalign: __assign({ styles: { 'vertical-align': '%value' } }, cellBase),
  8684. tablecellbordercolor: __assign({ styles: { borderColor: '%value' } }, cellBase),
  8685. tablecellclass: __assign({ classes: ['%value'] }, cellBase),
  8686. tableclass: __assign({
  8687. selector: 'table',
  8688. classes: ['%value']
  8689. }, genericBase),
  8690. tablecellborderstyle: __assign({ styles: { borderStyle: '%value' } }, cellBase),
  8691. tablecellborderwidth: __assign({ styles: { borderWidth: '%value' } }, cellBase)
  8692. };
  8693. var registerFormats = function (editor) {
  8694. editor.formatter.register(cellFormats);
  8695. };
  8696. var adt$5 = Adt.generate([
  8697. { none: ['current'] },
  8698. { first: ['current'] },
  8699. {
  8700. middle: [
  8701. 'current',
  8702. 'target'
  8703. ]
  8704. },
  8705. { last: ['current'] }
  8706. ]);
  8707. var none = function (current) {
  8708. if (current === void 0) {
  8709. current = undefined;
  8710. }
  8711. return adt$5.none(current);
  8712. };
  8713. var CellLocation = __assign(__assign({}, adt$5), { none: none });
  8714. var walk = function (all, current, index, direction, isEligible) {
  8715. if (isEligible === void 0) {
  8716. isEligible = always;
  8717. }
  8718. var forwards = direction === 1;
  8719. if (!forwards && index <= 0) {
  8720. return CellLocation.first(all[0]);
  8721. } else if (forwards && index >= all.length - 1) {
  8722. return CellLocation.last(all[all.length - 1]);
  8723. } else {
  8724. var newIndex = index + direction;
  8725. var elem = all[newIndex];
  8726. return isEligible(elem) ? CellLocation.middle(current, elem) : walk(all, current, newIndex, direction, isEligible);
  8727. }
  8728. };
  8729. var detect$1 = function (current, isRoot) {
  8730. return table(current, isRoot).bind(function (table) {
  8731. var all = cells$1(table);
  8732. var index = findIndex(all, function (x) {
  8733. return eq$1(current, x);
  8734. });
  8735. return index.map(function (index) {
  8736. return {
  8737. index: index,
  8738. all: all
  8739. };
  8740. });
  8741. });
  8742. };
  8743. var next = function (current, isEligible, isRoot) {
  8744. var detection = detect$1(current, isRoot);
  8745. return detection.fold(function () {
  8746. return CellLocation.none(current);
  8747. }, function (info) {
  8748. return walk(info.all, current, info.index, 1, isEligible);
  8749. });
  8750. };
  8751. var prev = function (current, isEligible, isRoot) {
  8752. var detection = detect$1(current, isRoot);
  8753. return detection.fold(function () {
  8754. return CellLocation.none();
  8755. }, function (info) {
  8756. return walk(info.all, current, info.index, -1, isEligible);
  8757. });
  8758. };
  8759. var create$2 = function (start, soffset, finish, foffset) {
  8760. return {
  8761. start: start,
  8762. soffset: soffset,
  8763. finish: finish,
  8764. foffset: foffset
  8765. };
  8766. };
  8767. var SimRange = { create: create$2 };
  8768. var adt$4 = Adt.generate([
  8769. { before: ['element'] },
  8770. {
  8771. on: [
  8772. 'element',
  8773. 'offset'
  8774. ]
  8775. },
  8776. { after: ['element'] }
  8777. ]);
  8778. var cata$1 = function (subject, onBefore, onOn, onAfter) {
  8779. return subject.fold(onBefore, onOn, onAfter);
  8780. };
  8781. var getStart$1 = function (situ) {
  8782. return situ.fold(identity, identity, identity);
  8783. };
  8784. var before$2 = adt$4.before;
  8785. var on = adt$4.on;
  8786. var after$3 = adt$4.after;
  8787. var Situ = {
  8788. before: before$2,
  8789. on: on,
  8790. after: after$3,
  8791. cata: cata$1,
  8792. getStart: getStart$1
  8793. };
  8794. var adt$3 = Adt.generate([
  8795. { domRange: ['rng'] },
  8796. {
  8797. relative: [
  8798. 'startSitu',
  8799. 'finishSitu'
  8800. ]
  8801. },
  8802. {
  8803. exact: [
  8804. 'start',
  8805. 'soffset',
  8806. 'finish',
  8807. 'foffset'
  8808. ]
  8809. }
  8810. ]);
  8811. var exactFromRange = function (simRange) {
  8812. return adt$3.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  8813. };
  8814. var getStart = function (selection) {
  8815. return selection.match({
  8816. domRange: function (rng) {
  8817. return SugarElement.fromDom(rng.startContainer);
  8818. },
  8819. relative: function (startSitu, _finishSitu) {
  8820. return Situ.getStart(startSitu);
  8821. },
  8822. exact: function (start, _soffset, _finish, _foffset) {
  8823. return start;
  8824. }
  8825. });
  8826. };
  8827. var domRange = adt$3.domRange;
  8828. var relative = adt$3.relative;
  8829. var exact = adt$3.exact;
  8830. var getWin = function (selection) {
  8831. var start = getStart(selection);
  8832. return defaultView(start);
  8833. };
  8834. var range = SimRange.create;
  8835. var SimSelection = {
  8836. domRange: domRange,
  8837. relative: relative,
  8838. exact: exact,
  8839. exactFromRange: exactFromRange,
  8840. getWin: getWin,
  8841. range: range
  8842. };
  8843. var selectNode = function (win, element) {
  8844. var rng = win.document.createRange();
  8845. rng.selectNode(element.dom);
  8846. return rng;
  8847. };
  8848. var selectNodeContents = function (win, element) {
  8849. var rng = win.document.createRange();
  8850. selectNodeContentsUsing(rng, element);
  8851. return rng;
  8852. };
  8853. var selectNodeContentsUsing = function (rng, element) {
  8854. return rng.selectNodeContents(element.dom);
  8855. };
  8856. var setStart = function (rng, situ) {
  8857. situ.fold(function (e) {
  8858. rng.setStartBefore(e.dom);
  8859. }, function (e, o) {
  8860. rng.setStart(e.dom, o);
  8861. }, function (e) {
  8862. rng.setStartAfter(e.dom);
  8863. });
  8864. };
  8865. var setFinish = function (rng, situ) {
  8866. situ.fold(function (e) {
  8867. rng.setEndBefore(e.dom);
  8868. }, function (e, o) {
  8869. rng.setEnd(e.dom, o);
  8870. }, function (e) {
  8871. rng.setEndAfter(e.dom);
  8872. });
  8873. };
  8874. var relativeToNative = function (win, startSitu, finishSitu) {
  8875. var range = win.document.createRange();
  8876. setStart(range, startSitu);
  8877. setFinish(range, finishSitu);
  8878. return range;
  8879. };
  8880. var exactToNative = function (win, start, soffset, finish, foffset) {
  8881. var rng = win.document.createRange();
  8882. rng.setStart(start.dom, soffset);
  8883. rng.setEnd(finish.dom, foffset);
  8884. return rng;
  8885. };
  8886. var toRect = function (rect) {
  8887. return {
  8888. left: rect.left,
  8889. top: rect.top,
  8890. right: rect.right,
  8891. bottom: rect.bottom,
  8892. width: rect.width,
  8893. height: rect.height
  8894. };
  8895. };
  8896. var getFirstRect$1 = function (rng) {
  8897. var rects = rng.getClientRects();
  8898. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  8899. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  8900. };
  8901. var adt$2 = Adt.generate([
  8902. {
  8903. ltr: [
  8904. 'start',
  8905. 'soffset',
  8906. 'finish',
  8907. 'foffset'
  8908. ]
  8909. },
  8910. {
  8911. rtl: [
  8912. 'start',
  8913. 'soffset',
  8914. 'finish',
  8915. 'foffset'
  8916. ]
  8917. }
  8918. ]);
  8919. var fromRange = function (win, type, range) {
  8920. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  8921. };
  8922. var getRanges = function (win, selection) {
  8923. return selection.match({
  8924. domRange: function (rng) {
  8925. return {
  8926. ltr: constant(rng),
  8927. rtl: Optional.none
  8928. };
  8929. },
  8930. relative: function (startSitu, finishSitu) {
  8931. return {
  8932. ltr: cached(function () {
  8933. return relativeToNative(win, startSitu, finishSitu);
  8934. }),
  8935. rtl: cached(function () {
  8936. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  8937. })
  8938. };
  8939. },
  8940. exact: function (start, soffset, finish, foffset) {
  8941. return {
  8942. ltr: cached(function () {
  8943. return exactToNative(win, start, soffset, finish, foffset);
  8944. }),
  8945. rtl: cached(function () {
  8946. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  8947. })
  8948. };
  8949. }
  8950. });
  8951. };
  8952. var doDiagnose = function (win, ranges) {
  8953. var rng = ranges.ltr();
  8954. if (rng.collapsed) {
  8955. var reversed = ranges.rtl().filter(function (rev) {
  8956. return rev.collapsed === false;
  8957. });
  8958. return reversed.map(function (rev) {
  8959. return adt$2.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  8960. }).getOrThunk(function () {
  8961. return fromRange(win, adt$2.ltr, rng);
  8962. });
  8963. } else {
  8964. return fromRange(win, adt$2.ltr, rng);
  8965. }
  8966. };
  8967. var diagnose = function (win, selection) {
  8968. var ranges = getRanges(win, selection);
  8969. return doDiagnose(win, ranges);
  8970. };
  8971. var asLtrRange = function (win, selection) {
  8972. var diagnosis = diagnose(win, selection);
  8973. return diagnosis.match({
  8974. ltr: function (start, soffset, finish, foffset) {
  8975. var rng = win.document.createRange();
  8976. rng.setStart(start.dom, soffset);
  8977. rng.setEnd(finish.dom, foffset);
  8978. return rng;
  8979. },
  8980. rtl: function (start, soffset, finish, foffset) {
  8981. var rng = win.document.createRange();
  8982. rng.setStart(finish.dom, foffset);
  8983. rng.setEnd(start.dom, soffset);
  8984. return rng;
  8985. }
  8986. });
  8987. };
  8988. adt$2.ltr;
  8989. adt$2.rtl;
  8990. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  8991. if (length === 0) {
  8992. return 0;
  8993. } else if (x === maxX) {
  8994. return length - 1;
  8995. }
  8996. var xDelta = maxX;
  8997. for (var i = 1; i < length; i++) {
  8998. var rect = rectForOffset(i);
  8999. var curDeltaX = Math.abs(x - rect.left);
  9000. if (y <= rect.bottom) {
  9001. if (y < rect.top || curDeltaX > xDelta) {
  9002. return i - 1;
  9003. } else {
  9004. xDelta = curDeltaX;
  9005. }
  9006. }
  9007. }
  9008. return 0;
  9009. };
  9010. var inRect = function (rect, x, y) {
  9011. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  9012. };
  9013. var locateOffset = function (doc, textnode, x, y, rect) {
  9014. var rangeForOffset = function (o) {
  9015. var r = doc.dom.createRange();
  9016. r.setStart(textnode.dom, o);
  9017. r.collapse(true);
  9018. return r;
  9019. };
  9020. var rectForOffset = function (o) {
  9021. var r = rangeForOffset(o);
  9022. return r.getBoundingClientRect();
  9023. };
  9024. var length = get$9(textnode).length;
  9025. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  9026. return rangeForOffset(offset);
  9027. };
  9028. var locate$1 = function (doc, node, x, y) {
  9029. var r = doc.dom.createRange();
  9030. r.selectNode(node.dom);
  9031. var rects = r.getClientRects();
  9032. var foundRect = findMap(rects, function (rect) {
  9033. return inRect(rect, x, y) ? Optional.some(rect) : Optional.none();
  9034. });
  9035. return foundRect.map(function (rect) {
  9036. return locateOffset(doc, node, x, y, rect);
  9037. });
  9038. };
  9039. var searchInChildren = function (doc, node, x, y) {
  9040. var r = doc.dom.createRange();
  9041. var nodes = children$3(node);
  9042. return findMap(nodes, function (n) {
  9043. r.selectNode(n.dom);
  9044. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Optional.none();
  9045. });
  9046. };
  9047. var locateNode = function (doc, node, x, y) {
  9048. return isText(node) ? locate$1(doc, node, x, y) : searchInChildren(doc, node, x, y);
  9049. };
  9050. var locate = function (doc, node, x, y) {
  9051. var r = doc.dom.createRange();
  9052. r.selectNode(node.dom);
  9053. var rect = r.getBoundingClientRect();
  9054. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  9055. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  9056. return locateNode(doc, node, boundedX, boundedY);
  9057. };
  9058. var COLLAPSE_TO_LEFT = true;
  9059. var COLLAPSE_TO_RIGHT = false;
  9060. var getCollapseDirection = function (rect, x) {
  9061. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  9062. };
  9063. var createCollapsedNode = function (doc, target, collapseDirection) {
  9064. var r = doc.dom.createRange();
  9065. r.selectNode(target.dom);
  9066. r.collapse(collapseDirection);
  9067. return r;
  9068. };
  9069. var locateInElement = function (doc, node, x) {
  9070. var cursorRange = doc.dom.createRange();
  9071. cursorRange.selectNode(node.dom);
  9072. var rect = cursorRange.getBoundingClientRect();
  9073. var collapseDirection = getCollapseDirection(rect, x);
  9074. var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
  9075. return f(node).map(function (target) {
  9076. return createCollapsedNode(doc, target, collapseDirection);
  9077. });
  9078. };
  9079. var locateInEmpty = function (doc, node, x) {
  9080. var rect = node.dom.getBoundingClientRect();
  9081. var collapseDirection = getCollapseDirection(rect, x);
  9082. return Optional.some(createCollapsedNode(doc, node, collapseDirection));
  9083. };
  9084. var search = function (doc, node, x) {
  9085. var f = children$3(node).length === 0 ? locateInEmpty : locateInElement;
  9086. return f(doc, node, x);
  9087. };
  9088. var caretPositionFromPoint = function (doc, x, y) {
  9089. var _a, _b;
  9090. return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y)).bind(function (pos) {
  9091. if (pos.offsetNode === null) {
  9092. return Optional.none();
  9093. }
  9094. var r = doc.dom.createRange();
  9095. r.setStart(pos.offsetNode, pos.offset);
  9096. r.collapse();
  9097. return Optional.some(r);
  9098. });
  9099. };
  9100. var caretRangeFromPoint = function (doc, x, y) {
  9101. var _a, _b;
  9102. return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y));
  9103. };
  9104. var searchTextNodes = function (doc, node, x, y) {
  9105. var r = doc.dom.createRange();
  9106. r.selectNode(node.dom);
  9107. var rect = r.getBoundingClientRect();
  9108. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  9109. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  9110. return locate(doc, node, boundedX, boundedY);
  9111. };
  9112. var searchFromPoint = function (doc, x, y) {
  9113. return SugarElement.fromPoint(doc, x, y).bind(function (elem) {
  9114. var fallback = function () {
  9115. return search(doc, elem, x);
  9116. };
  9117. return children$3(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  9118. });
  9119. };
  9120. var availableSearch = function () {
  9121. if (document.caretPositionFromPoint) {
  9122. return caretPositionFromPoint;
  9123. } else if (document.caretRangeFromPoint) {
  9124. return caretRangeFromPoint;
  9125. } else {
  9126. return searchFromPoint;
  9127. }
  9128. }();
  9129. var fromPoint = function (win, x, y) {
  9130. var doc = SugarElement.fromDom(win.document);
  9131. return availableSearch(doc, x, y).map(function (rng) {
  9132. return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
  9133. });
  9134. };
  9135. var beforeSpecial = function (element, offset) {
  9136. var name$1 = name(element);
  9137. if ('input' === name$1) {
  9138. return Situ.after(element);
  9139. } else if (!contains$2([
  9140. 'br',
  9141. 'img'
  9142. ], name$1)) {
  9143. return Situ.on(element, offset);
  9144. } else {
  9145. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9146. }
  9147. };
  9148. var preprocessRelative = function (startSitu, finishSitu) {
  9149. var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9150. var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9151. return SimSelection.relative(start, finish);
  9152. };
  9153. var preprocessExact = function (start, soffset, finish, foffset) {
  9154. var startSitu = beforeSpecial(start, soffset);
  9155. var finishSitu = beforeSpecial(finish, foffset);
  9156. return SimSelection.relative(startSitu, finishSitu);
  9157. };
  9158. var preprocess = function (selection) {
  9159. return selection.match({
  9160. domRange: function (rng) {
  9161. var start = SugarElement.fromDom(rng.startContainer);
  9162. var finish = SugarElement.fromDom(rng.endContainer);
  9163. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  9164. },
  9165. relative: preprocessRelative,
  9166. exact: preprocessExact
  9167. });
  9168. };
  9169. var makeRange = function (start, soffset, finish, foffset) {
  9170. var doc = owner(start);
  9171. var rng = doc.dom.createRange();
  9172. rng.setStart(start.dom, soffset);
  9173. rng.setEnd(finish.dom, foffset);
  9174. return rng;
  9175. };
  9176. var after$2 = function (start, soffset, finish, foffset) {
  9177. var r = makeRange(start, soffset, finish, foffset);
  9178. var same = eq$1(start, finish) && soffset === foffset;
  9179. return r.collapsed && !same;
  9180. };
  9181. var getNativeSelection = function (win) {
  9182. return Optional.from(win.getSelection());
  9183. };
  9184. var doSetNativeRange = function (win, rng) {
  9185. getNativeSelection(win).each(function (selection) {
  9186. selection.removeAllRanges();
  9187. selection.addRange(rng);
  9188. });
  9189. };
  9190. var doSetRange = function (win, start, soffset, finish, foffset) {
  9191. var rng = exactToNative(win, start, soffset, finish, foffset);
  9192. doSetNativeRange(win, rng);
  9193. };
  9194. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9195. selection.collapse(start.dom, soffset);
  9196. selection.extend(finish.dom, foffset);
  9197. };
  9198. var setRangeFromRelative = function (win, relative) {
  9199. return diagnose(win, relative).match({
  9200. ltr: function (start, soffset, finish, foffset) {
  9201. doSetRange(win, start, soffset, finish, foffset);
  9202. },
  9203. rtl: function (start, soffset, finish, foffset) {
  9204. getNativeSelection(win).each(function (selection) {
  9205. if (selection.setBaseAndExtent) {
  9206. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9207. } else if (selection.extend) {
  9208. try {
  9209. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9210. } catch (e) {
  9211. doSetRange(win, finish, foffset, start, soffset);
  9212. }
  9213. } else {
  9214. doSetRange(win, finish, foffset, start, soffset);
  9215. }
  9216. });
  9217. }
  9218. });
  9219. };
  9220. var setExact = function (win, start, soffset, finish, foffset) {
  9221. var relative = preprocessExact(start, soffset, finish, foffset);
  9222. setRangeFromRelative(win, relative);
  9223. };
  9224. var setRelative = function (win, startSitu, finishSitu) {
  9225. var relative = preprocessRelative(startSitu, finishSitu);
  9226. setRangeFromRelative(win, relative);
  9227. };
  9228. var toNative = function (selection) {
  9229. var win = SimSelection.getWin(selection).dom;
  9230. var getDomRange = function (start, soffset, finish, foffset) {
  9231. return exactToNative(win, start, soffset, finish, foffset);
  9232. };
  9233. var filtered = preprocess(selection);
  9234. return diagnose(win, filtered).match({
  9235. ltr: getDomRange,
  9236. rtl: getDomRange
  9237. });
  9238. };
  9239. var readRange = function (selection) {
  9240. if (selection.rangeCount > 0) {
  9241. var firstRng = selection.getRangeAt(0);
  9242. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9243. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9244. } else {
  9245. return Optional.none();
  9246. }
  9247. };
  9248. var doGetExact = function (selection) {
  9249. if (selection.anchorNode === null || selection.focusNode === null) {
  9250. return readRange(selection);
  9251. } else {
  9252. var anchor = SugarElement.fromDom(selection.anchorNode);
  9253. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9254. return after$2(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9255. }
  9256. };
  9257. var setToElement = function (win, element, selectNodeContents$1) {
  9258. if (selectNodeContents$1 === void 0) {
  9259. selectNodeContents$1 = true;
  9260. }
  9261. var rngGetter = selectNodeContents$1 ? selectNodeContents : selectNode;
  9262. var rng = rngGetter(win, element);
  9263. doSetNativeRange(win, rng);
  9264. };
  9265. var getExact = function (win) {
  9266. return getNativeSelection(win).filter(function (sel) {
  9267. return sel.rangeCount > 0;
  9268. }).bind(doGetExact);
  9269. };
  9270. var get$1 = function (win) {
  9271. return getExact(win).map(function (range) {
  9272. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9273. });
  9274. };
  9275. var getFirstRect = function (win, selection) {
  9276. var rng = asLtrRange(win, selection);
  9277. return getFirstRect$1(rng);
  9278. };
  9279. var getAtPoint = function (win, x, y) {
  9280. return fromPoint(win, x, y);
  9281. };
  9282. var clear = function (win) {
  9283. getNativeSelection(win).each(function (selection) {
  9284. return selection.removeAllRanges();
  9285. });
  9286. };
  9287. var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');
  9288. var forward = function (editor, isRoot, cell) {
  9289. return go$1(editor, isRoot, next(cell, isEditable$1));
  9290. };
  9291. var backward = function (editor, isRoot, cell) {
  9292. return go$1(editor, isRoot, prev(cell, isEditable$1));
  9293. };
  9294. var getCellFirstCursorPosition = function (editor, cell) {
  9295. var selection = SimSelection.exact(cell, 0, cell, 0);
  9296. return toNative(selection);
  9297. };
  9298. var go$1 = function (editor, isRoot, cell) {
  9299. return cell.fold(Optional.none, Optional.none, function (current, next) {
  9300. return first(next).map(function (cell) {
  9301. return getCellFirstCursorPosition(editor, cell);
  9302. });
  9303. }, function (current) {
  9304. editor.execCommand('mceTableInsertRowAfter');
  9305. return forward(editor, isRoot, current);
  9306. });
  9307. };
  9308. var rootElements = [
  9309. 'table',
  9310. 'li',
  9311. 'dl'
  9312. ];
  9313. var handle$1 = function (event, editor, cellSelection) {
  9314. if (event.keyCode === global$1.TAB) {
  9315. var body_1 = getBody(editor);
  9316. var isRoot_1 = function (element) {
  9317. var name$1 = name(element);
  9318. return eq$1(element, body_1) || contains$2(rootElements, name$1);
  9319. };
  9320. var rng = editor.selection.getRng();
  9321. var container = SugarElement.fromDom(event.shiftKey ? rng.startContainer : rng.endContainer);
  9322. cell(container, isRoot_1).each(function (cell) {
  9323. event.preventDefault();
  9324. table(cell, isRoot_1).each(cellSelection.clear);
  9325. editor.selection.collapse(event.shiftKey);
  9326. var navigation = event.shiftKey ? backward : forward;
  9327. var rng = navigation(editor, isRoot_1, cell);
  9328. rng.each(function (range) {
  9329. editor.selection.setRng(range);
  9330. });
  9331. });
  9332. }
  9333. };
  9334. var create$1 = function (selection, kill) {
  9335. return {
  9336. selection: selection,
  9337. kill: kill
  9338. };
  9339. };
  9340. var Response = { create: create$1 };
  9341. var create = function (start, soffset, finish, foffset) {
  9342. return {
  9343. start: Situ.on(start, soffset),
  9344. finish: Situ.on(finish, foffset)
  9345. };
  9346. };
  9347. var Situs = { create: create };
  9348. var convertToRange = function (win, selection) {
  9349. var rng = asLtrRange(win, selection);
  9350. return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
  9351. };
  9352. var makeSitus = Situs.create;
  9353. var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
  9354. if (!(eq$1(start, finish) && soffset === foffset)) {
  9355. return closest$1(start, 'td,th', isRoot).bind(function (s) {
  9356. return closest$1(finish, 'td,th', isRoot).bind(function (f) {
  9357. return detect(container, isRoot, s, f, selectRange);
  9358. });
  9359. });
  9360. } else {
  9361. return Optional.none();
  9362. }
  9363. };
  9364. var detect = function (container, isRoot, start, finish, selectRange) {
  9365. if (!eq$1(start, finish)) {
  9366. return identify(start, finish, isRoot).bind(function (cellSel) {
  9367. var boxes = cellSel.boxes.getOr([]);
  9368. if (boxes.length > 1) {
  9369. selectRange(container, boxes, cellSel.start, cellSel.finish);
  9370. return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
  9371. } else {
  9372. return Optional.none();
  9373. }
  9374. });
  9375. } else {
  9376. return Optional.none();
  9377. }
  9378. };
  9379. var update = function (rows, columns, container, selected, annotations) {
  9380. var updateSelection = function (newSels) {
  9381. annotations.clearBeforeUpdate(container);
  9382. annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
  9383. return newSels.boxes;
  9384. };
  9385. return shiftSelection(selected, rows, columns, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
  9386. };
  9387. var traverse = function (item, mode) {
  9388. return {
  9389. item: item,
  9390. mode: mode
  9391. };
  9392. };
  9393. var backtrack = function (universe, item, _direction, transition) {
  9394. if (transition === void 0) {
  9395. transition = sidestep;
  9396. }
  9397. return universe.property().parent(item).map(function (p) {
  9398. return traverse(p, transition);
  9399. });
  9400. };
  9401. var sidestep = function (universe, item, direction, transition) {
  9402. if (transition === void 0) {
  9403. transition = advance;
  9404. }
  9405. return direction.sibling(universe, item).map(function (p) {
  9406. return traverse(p, transition);
  9407. });
  9408. };
  9409. var advance = function (universe, item, direction, transition) {
  9410. if (transition === void 0) {
  9411. transition = advance;
  9412. }
  9413. var children = universe.property().children(item);
  9414. var result = direction.first(children);
  9415. return result.map(function (r) {
  9416. return traverse(r, transition);
  9417. });
  9418. };
  9419. var successors = [
  9420. {
  9421. current: backtrack,
  9422. next: sidestep,
  9423. fallback: Optional.none()
  9424. },
  9425. {
  9426. current: sidestep,
  9427. next: advance,
  9428. fallback: Optional.some(backtrack)
  9429. },
  9430. {
  9431. current: advance,
  9432. next: advance,
  9433. fallback: Optional.some(sidestep)
  9434. }
  9435. ];
  9436. var go = function (universe, item, mode, direction, rules) {
  9437. if (rules === void 0) {
  9438. rules = successors;
  9439. }
  9440. var ruleOpt = find$1(rules, function (succ) {
  9441. return succ.current === mode;
  9442. });
  9443. return ruleOpt.bind(function (rule) {
  9444. return rule.current(universe, item, direction, rule.next).orThunk(function () {
  9445. return rule.fallback.bind(function (fb) {
  9446. return go(universe, item, fb, direction);
  9447. });
  9448. });
  9449. });
  9450. };
  9451. var left$1 = function () {
  9452. var sibling = function (universe, item) {
  9453. return universe.query().prevSibling(item);
  9454. };
  9455. var first = function (children) {
  9456. return children.length > 0 ? Optional.some(children[children.length - 1]) : Optional.none();
  9457. };
  9458. return {
  9459. sibling: sibling,
  9460. first: first
  9461. };
  9462. };
  9463. var right$1 = function () {
  9464. var sibling = function (universe, item) {
  9465. return universe.query().nextSibling(item);
  9466. };
  9467. var first = function (children) {
  9468. return children.length > 0 ? Optional.some(children[0]) : Optional.none();
  9469. };
  9470. return {
  9471. sibling: sibling,
  9472. first: first
  9473. };
  9474. };
  9475. var Walkers = {
  9476. left: left$1,
  9477. right: right$1
  9478. };
  9479. var hone = function (universe, item, predicate, mode, direction, isRoot) {
  9480. var next = go(universe, item, mode, direction);
  9481. return next.bind(function (n) {
  9482. if (isRoot(n.item)) {
  9483. return Optional.none();
  9484. } else {
  9485. return predicate(n.item) ? Optional.some(n.item) : hone(universe, n.item, predicate, n.mode, direction, isRoot);
  9486. }
  9487. });
  9488. };
  9489. var left = function (universe, item, predicate, isRoot) {
  9490. return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
  9491. };
  9492. var right = function (universe, item, predicate, isRoot) {
  9493. return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
  9494. };
  9495. var isLeaf = function (universe) {
  9496. return function (element) {
  9497. return universe.property().children(element).length === 0;
  9498. };
  9499. };
  9500. var before$1 = function (universe, item, isRoot) {
  9501. return seekLeft$1(universe, item, isLeaf(universe), isRoot);
  9502. };
  9503. var after$1 = function (universe, item, isRoot) {
  9504. return seekRight$1(universe, item, isLeaf(universe), isRoot);
  9505. };
  9506. var seekLeft$1 = left;
  9507. var seekRight$1 = right;
  9508. var universe = DomUniverse();
  9509. var before = function (element, isRoot) {
  9510. return before$1(universe, element, isRoot);
  9511. };
  9512. var after = function (element, isRoot) {
  9513. return after$1(universe, element, isRoot);
  9514. };
  9515. var seekLeft = function (element, predicate, isRoot) {
  9516. return seekLeft$1(universe, element, predicate, isRoot);
  9517. };
  9518. var seekRight = function (element, predicate, isRoot) {
  9519. return seekRight$1(universe, element, predicate, isRoot);
  9520. };
  9521. var ancestor = function (scope, predicate, isRoot) {
  9522. return ancestor$2(scope, predicate, isRoot).isSome();
  9523. };
  9524. var adt$1 = Adt.generate([
  9525. { none: ['message'] },
  9526. { success: [] },
  9527. { failedUp: ['cell'] },
  9528. { failedDown: ['cell'] }
  9529. ]);
  9530. var isOverlapping = function (bridge, before, after) {
  9531. var beforeBounds = bridge.getRect(before);
  9532. var afterBounds = bridge.getRect(after);
  9533. return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
  9534. };
  9535. var isRow = function (elem) {
  9536. return closest$1(elem, 'tr');
  9537. };
  9538. var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
  9539. return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
  9540. return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
  9541. if (!eq$1(afterCell, beforeCell)) {
  9542. return sharedOne(isRow, [
  9543. afterCell,
  9544. beforeCell
  9545. ]).fold(function () {
  9546. return isOverlapping(bridge, beforeCell, afterCell) ? adt$1.success() : failure(beforeCell);
  9547. }, function (_sharedRow) {
  9548. return failure(beforeCell);
  9549. });
  9550. } else {
  9551. return eq$1(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$1.none('in same cell');
  9552. }
  9553. });
  9554. }).getOr(adt$1.none('default'));
  9555. };
  9556. var cata = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
  9557. return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
  9558. };
  9559. var BeforeAfter = __assign(__assign({}, adt$1), {
  9560. verify: verify,
  9561. cata: cata
  9562. });
  9563. var inParent = function (parent, children, element, index) {
  9564. return {
  9565. parent: parent,
  9566. children: children,
  9567. element: element,
  9568. index: index
  9569. };
  9570. };
  9571. var indexInParent = function (element) {
  9572. return parent(element).bind(function (parent) {
  9573. var children = children$3(parent);
  9574. return indexOf(children, element).map(function (index) {
  9575. return inParent(parent, children, element, index);
  9576. });
  9577. });
  9578. };
  9579. var indexOf = function (elements, element) {
  9580. return findIndex(elements, curry(eq$1, element));
  9581. };
  9582. var isBr = function (elem) {
  9583. return name(elem) === 'br';
  9584. };
  9585. var gatherer = function (cand, gather, isRoot) {
  9586. return gather(cand, isRoot).bind(function (target) {
  9587. return isText(target) && get$9(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
  9588. });
  9589. };
  9590. var handleBr = function (isRoot, element, direction) {
  9591. return direction.traverse(element).orThunk(function () {
  9592. return gatherer(element, direction.gather, isRoot);
  9593. }).map(direction.relative);
  9594. };
  9595. var findBr = function (element, offset) {
  9596. return child$3(element, offset).filter(isBr).orThunk(function () {
  9597. return child$3(element, offset - 1).filter(isBr);
  9598. });
  9599. };
  9600. var handleParent = function (isRoot, element, offset, direction) {
  9601. return findBr(element, offset).bind(function (br) {
  9602. return direction.traverse(br).fold(function () {
  9603. return gatherer(br, direction.gather, isRoot).map(direction.relative);
  9604. }, function (adjacent) {
  9605. return indexInParent(adjacent).map(function (info) {
  9606. return Situ.on(info.parent, info.index);
  9607. });
  9608. });
  9609. });
  9610. };
  9611. var tryBr = function (isRoot, element, offset, direction) {
  9612. var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
  9613. return target.map(function (tgt) {
  9614. return {
  9615. start: tgt,
  9616. finish: tgt
  9617. };
  9618. });
  9619. };
  9620. var process = function (analysis) {
  9621. return BeforeAfter.cata(analysis, function (_message) {
  9622. return Optional.none();
  9623. }, function () {
  9624. return Optional.none();
  9625. }, function (cell) {
  9626. return Optional.some(point(cell, 0));
  9627. }, function (cell) {
  9628. return Optional.some(point(cell, getEnd(cell)));
  9629. });
  9630. };
  9631. var moveDown = function (caret, amount) {
  9632. return {
  9633. left: caret.left,
  9634. top: caret.top + amount,
  9635. right: caret.right,
  9636. bottom: caret.bottom + amount
  9637. };
  9638. };
  9639. var moveUp = function (caret, amount) {
  9640. return {
  9641. left: caret.left,
  9642. top: caret.top - amount,
  9643. right: caret.right,
  9644. bottom: caret.bottom - amount
  9645. };
  9646. };
  9647. var translate = function (caret, xDelta, yDelta) {
  9648. return {
  9649. left: caret.left + xDelta,
  9650. top: caret.top + yDelta,
  9651. right: caret.right + xDelta,
  9652. bottom: caret.bottom + yDelta
  9653. };
  9654. };
  9655. var getTop = function (caret) {
  9656. return caret.top;
  9657. };
  9658. var getBottom = function (caret) {
  9659. return caret.bottom;
  9660. };
  9661. var getPartialBox = function (bridge, element, offset) {
  9662. if (offset >= 0 && offset < getEnd(element)) {
  9663. return bridge.getRangedRect(element, offset, element, offset + 1);
  9664. } else if (offset > 0) {
  9665. return bridge.getRangedRect(element, offset - 1, element, offset);
  9666. }
  9667. return Optional.none();
  9668. };
  9669. var toCaret = function (rect) {
  9670. return {
  9671. left: rect.left,
  9672. top: rect.top,
  9673. right: rect.right,
  9674. bottom: rect.bottom
  9675. };
  9676. };
  9677. var getElemBox = function (bridge, element) {
  9678. return Optional.some(bridge.getRect(element));
  9679. };
  9680. var getBoxAt = function (bridge, element, offset) {
  9681. if (isElement(element)) {
  9682. return getElemBox(bridge, element).map(toCaret);
  9683. } else if (isText(element)) {
  9684. return getPartialBox(bridge, element, offset).map(toCaret);
  9685. } else {
  9686. return Optional.none();
  9687. }
  9688. };
  9689. var getEntireBox = function (bridge, element) {
  9690. if (isElement(element)) {
  9691. return getElemBox(bridge, element).map(toCaret);
  9692. } else if (isText(element)) {
  9693. return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
  9694. } else {
  9695. return Optional.none();
  9696. }
  9697. };
  9698. var JUMP_SIZE = 5;
  9699. var NUM_RETRIES = 100;
  9700. var adt = Adt.generate([
  9701. { none: [] },
  9702. { retry: ['caret'] }
  9703. ]);
  9704. var isOutside = function (caret, box) {
  9705. return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
  9706. };
  9707. var inOutsideBlock = function (bridge, element, caret) {
  9708. return closest$2(element, isBlock).fold(never, function (cell) {
  9709. return getEntireBox(bridge, cell).exists(function (box) {
  9710. return isOutside(caret, box);
  9711. });
  9712. });
  9713. };
  9714. var adjustDown = function (bridge, element, guessBox, original, caret) {
  9715. var lowerCaret = moveDown(caret, JUMP_SIZE);
  9716. if (Math.abs(guessBox.bottom - original.bottom) < 1) {
  9717. return adt.retry(lowerCaret);
  9718. } else if (guessBox.top > caret.bottom) {
  9719. return adt.retry(lowerCaret);
  9720. } else if (guessBox.top === caret.bottom) {
  9721. return adt.retry(moveDown(caret, 1));
  9722. } else {
  9723. return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt.none();
  9724. }
  9725. };
  9726. var adjustUp = function (bridge, element, guessBox, original, caret) {
  9727. var higherCaret = moveUp(caret, JUMP_SIZE);
  9728. if (Math.abs(guessBox.top - original.top) < 1) {
  9729. return adt.retry(higherCaret);
  9730. } else if (guessBox.bottom < caret.top) {
  9731. return adt.retry(higherCaret);
  9732. } else if (guessBox.bottom === caret.top) {
  9733. return adt.retry(moveUp(caret, 1));
  9734. } else {
  9735. return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt.none();
  9736. }
  9737. };
  9738. var upMovement = {
  9739. point: getTop,
  9740. adjuster: adjustUp,
  9741. move: moveUp,
  9742. gather: before
  9743. };
  9744. var downMovement = {
  9745. point: getBottom,
  9746. adjuster: adjustDown,
  9747. move: moveDown,
  9748. gather: after
  9749. };
  9750. var isAtTable = function (bridge, x, y) {
  9751. return bridge.elementFromPoint(x, y).filter(function (elm) {
  9752. return name(elm) === 'table';
  9753. }).isSome();
  9754. };
  9755. var adjustForTable = function (bridge, movement, original, caret, numRetries) {
  9756. return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
  9757. };
  9758. var adjustTil = function (bridge, movement, original, caret, numRetries) {
  9759. if (numRetries === 0) {
  9760. return Optional.some(caret);
  9761. }
  9762. if (isAtTable(bridge, caret.left, movement.point(caret))) {
  9763. return adjustForTable(bridge, movement, original, caret, numRetries - 1);
  9764. }
  9765. return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function (guess) {
  9766. return guess.start.fold(Optional.none, function (element) {
  9767. return getEntireBox(bridge, element).bind(function (guessBox) {
  9768. return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function (newCaret) {
  9769. return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
  9770. });
  9771. }).orThunk(function () {
  9772. return Optional.some(caret);
  9773. });
  9774. }, Optional.none);
  9775. });
  9776. };
  9777. var ieTryDown = function (bridge, caret) {
  9778. return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
  9779. };
  9780. var ieTryUp = function (bridge, caret) {
  9781. return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
  9782. };
  9783. var checkScroll = function (movement, adjusted, bridge) {
  9784. if (movement.point(adjusted) > bridge.getInnerHeight()) {
  9785. return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
  9786. } else if (movement.point(adjusted) < 0) {
  9787. return Optional.some(-movement.point(adjusted));
  9788. } else {
  9789. return Optional.none();
  9790. }
  9791. };
  9792. var retry = function (movement, bridge, caret) {
  9793. var moved = movement.move(caret, JUMP_SIZE);
  9794. var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
  9795. return checkScroll(movement, adjusted, bridge).fold(function () {
  9796. return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
  9797. }, function (delta) {
  9798. bridge.scrollBy(0, delta);
  9799. return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
  9800. });
  9801. };
  9802. var Retries = {
  9803. tryUp: curry(retry, upMovement),
  9804. tryDown: curry(retry, downMovement),
  9805. ieTryUp: ieTryUp,
  9806. ieTryDown: ieTryDown,
  9807. getJumpSize: constant(JUMP_SIZE)
  9808. };
  9809. var MAX_RETRIES = 20;
  9810. var findSpot = function (bridge, isRoot, direction) {
  9811. return bridge.getSelection().bind(function (sel) {
  9812. return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function () {
  9813. return Optional.some(point(sel.finish, sel.foffset));
  9814. }, function (brNeighbour) {
  9815. var range = bridge.fromSitus(brNeighbour);
  9816. var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range.finish, range.foffset, direction.failure, isRoot);
  9817. return process(analysis);
  9818. });
  9819. });
  9820. };
  9821. var scan = function (bridge, isRoot, element, offset, direction, numRetries) {
  9822. if (numRetries === 0) {
  9823. return Optional.none();
  9824. }
  9825. return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
  9826. var range = bridge.fromSitus(situs);
  9827. var analysis = BeforeAfter.verify(bridge, element, offset, range.finish, range.foffset, direction.failure, isRoot);
  9828. return BeforeAfter.cata(analysis, function () {
  9829. return Optional.none();
  9830. }, function () {
  9831. return Optional.some(situs);
  9832. }, function (cell) {
  9833. if (eq$1(element, cell) && offset === 0) {
  9834. return tryAgain(bridge, element, offset, moveUp, direction);
  9835. } else {
  9836. return scan(bridge, isRoot, cell, 0, direction, numRetries - 1);
  9837. }
  9838. }, function (cell) {
  9839. if (eq$1(element, cell) && offset === getEnd(cell)) {
  9840. return tryAgain(bridge, element, offset, moveDown, direction);
  9841. } else {
  9842. return scan(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
  9843. }
  9844. });
  9845. });
  9846. };
  9847. var tryAgain = function (bridge, element, offset, move, direction) {
  9848. return getBoxAt(bridge, element, offset).bind(function (box) {
  9849. return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
  9850. });
  9851. };
  9852. var tryAt = function (bridge, direction, box) {
  9853. var browser = detect$3().browser;
  9854. if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
  9855. return direction.otherRetry(bridge, box);
  9856. } else if (browser.isIE()) {
  9857. return direction.ieRetry(bridge, box);
  9858. } else {
  9859. return Optional.none();
  9860. }
  9861. };
  9862. var tryCursor = function (bridge, isRoot, element, offset, direction) {
  9863. return getBoxAt(bridge, element, offset).bind(function (box) {
  9864. return tryAt(bridge, direction, box);
  9865. });
  9866. };
  9867. var handle = function (bridge, isRoot, direction) {
  9868. return findSpot(bridge, isRoot, direction).bind(function (spot) {
  9869. return scan(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
  9870. });
  9871. };
  9872. var inSameTable = function (elem, table) {
  9873. return ancestor(elem, function (e) {
  9874. return parent(e).exists(function (p) {
  9875. return eq$1(p, table);
  9876. });
  9877. });
  9878. };
  9879. var simulate = function (bridge, isRoot, direction, initial, anchor) {
  9880. return closest$1(initial, 'td,th', isRoot).bind(function (start) {
  9881. return closest$1(start, 'table', isRoot).bind(function (table) {
  9882. if (!inSameTable(anchor, table)) {
  9883. return Optional.none();
  9884. }
  9885. return handle(bridge, isRoot, direction).bind(function (range) {
  9886. return closest$1(range.finish, 'td,th', isRoot).map(function (finish) {
  9887. return {
  9888. start: start,
  9889. finish: finish,
  9890. range: range
  9891. };
  9892. });
  9893. });
  9894. });
  9895. });
  9896. };
  9897. var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
  9898. if (detect$3().browser.isIE()) {
  9899. return Optional.none();
  9900. } else {
  9901. return precheck(initial, isRoot).orThunk(function () {
  9902. return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
  9903. var range = info.range;
  9904. return Response.create(Optional.some(makeSitus(range.start, range.soffset, range.finish, range.foffset)), true);
  9905. });
  9906. });
  9907. }
  9908. };
  9909. var firstUpCheck = function (initial, isRoot) {
  9910. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  9911. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  9912. var rows = descendants(table, 'tr');
  9913. if (eq$1(startRow, rows[0])) {
  9914. return seekLeft(table, function (element) {
  9915. return last$1(element).isSome();
  9916. }, isRoot).map(function (last) {
  9917. var lastOffset = getEnd(last);
  9918. return Response.create(Optional.some(makeSitus(last, lastOffset, last, lastOffset)), true);
  9919. });
  9920. } else {
  9921. return Optional.none();
  9922. }
  9923. });
  9924. });
  9925. };
  9926. var lastDownCheck = function (initial, isRoot) {
  9927. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  9928. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  9929. var rows = descendants(table, 'tr');
  9930. if (eq$1(startRow, rows[rows.length - 1])) {
  9931. return seekRight(table, function (element) {
  9932. return first(element).isSome();
  9933. }, isRoot).map(function (first) {
  9934. return Response.create(Optional.some(makeSitus(first, 0, first, 0)), true);
  9935. });
  9936. } else {
  9937. return Optional.none();
  9938. }
  9939. });
  9940. });
  9941. };
  9942. var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
  9943. return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
  9944. return detect(container, isRoot, info.start, info.finish, selectRange);
  9945. });
  9946. };
  9947. var findCell = function (target, isRoot) {
  9948. return closest$1(target, 'td,th', isRoot);
  9949. };
  9950. var MouseSelection = function (bridge, container, isRoot, annotations) {
  9951. var cursor = value();
  9952. var clearstate = cursor.clear;
  9953. var applySelection = function (event) {
  9954. cursor.on(function (start) {
  9955. annotations.clearBeforeUpdate(container);
  9956. findCell(event.target, isRoot).each(function (finish) {
  9957. identify(start, finish, isRoot).each(function (cellSel) {
  9958. var boxes = cellSel.boxes.getOr([]);
  9959. if (boxes.length === 1) {
  9960. var singleCell = boxes[0];
  9961. var isNonEditableCell = getRaw(singleCell) === 'false';
  9962. var isCellClosestContentEditable = is(closest(event.target), singleCell, eq$1);
  9963. if (isNonEditableCell && isCellClosestContentEditable) {
  9964. annotations.selectRange(container, boxes, singleCell, singleCell);
  9965. bridge.selectContents(singleCell);
  9966. }
  9967. } else if (boxes.length > 1) {
  9968. annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
  9969. bridge.selectContents(finish);
  9970. }
  9971. });
  9972. });
  9973. });
  9974. };
  9975. var mousedown = function (event) {
  9976. annotations.clear(container);
  9977. findCell(event.target, isRoot).each(cursor.set);
  9978. };
  9979. var mouseover = function (event) {
  9980. applySelection(event);
  9981. };
  9982. var mouseup = function (event) {
  9983. applySelection(event);
  9984. clearstate();
  9985. };
  9986. return {
  9987. clearstate: clearstate,
  9988. mousedown: mousedown,
  9989. mouseover: mouseover,
  9990. mouseup: mouseup
  9991. };
  9992. };
  9993. var down = {
  9994. traverse: nextSibling,
  9995. gather: after,
  9996. relative: Situ.before,
  9997. otherRetry: Retries.tryDown,
  9998. ieRetry: Retries.ieTryDown,
  9999. failure: BeforeAfter.failedDown
  10000. };
  10001. var up = {
  10002. traverse: prevSibling,
  10003. gather: before,
  10004. relative: Situ.before,
  10005. otherRetry: Retries.tryUp,
  10006. ieRetry: Retries.ieTryUp,
  10007. failure: BeforeAfter.failedUp
  10008. };
  10009. var isKey = function (key) {
  10010. return function (keycode) {
  10011. return keycode === key;
  10012. };
  10013. };
  10014. var isUp = isKey(38);
  10015. var isDown = isKey(40);
  10016. var isNavigation = function (keycode) {
  10017. return keycode >= 37 && keycode <= 40;
  10018. };
  10019. var ltr = {
  10020. isBackward: isKey(37),
  10021. isForward: isKey(39)
  10022. };
  10023. var rtl = {
  10024. isBackward: isKey(39),
  10025. isForward: isKey(37)
  10026. };
  10027. var get = function (_DOC) {
  10028. var doc = _DOC !== undefined ? _DOC.dom : document;
  10029. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  10030. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  10031. return SugarPosition(x, y);
  10032. };
  10033. var by = function (x, y, _DOC) {
  10034. var doc = _DOC !== undefined ? _DOC.dom : document;
  10035. var win = doc.defaultView;
  10036. if (win) {
  10037. win.scrollBy(x, y);
  10038. }
  10039. };
  10040. var WindowBridge = function (win) {
  10041. var elementFromPoint = function (x, y) {
  10042. return SugarElement.fromPoint(SugarElement.fromDom(win.document), x, y);
  10043. };
  10044. var getRect = function (element) {
  10045. return element.dom.getBoundingClientRect();
  10046. };
  10047. var getRangedRect = function (start, soffset, finish, foffset) {
  10048. var sel = SimSelection.exact(start, soffset, finish, foffset);
  10049. return getFirstRect(win, sel);
  10050. };
  10051. var getSelection = function () {
  10052. return get$1(win).map(function (exactAdt) {
  10053. return convertToRange(win, exactAdt);
  10054. });
  10055. };
  10056. var fromSitus = function (situs) {
  10057. var relative = SimSelection.relative(situs.start, situs.finish);
  10058. return convertToRange(win, relative);
  10059. };
  10060. var situsFromPoint = function (x, y) {
  10061. return getAtPoint(win, x, y).map(function (exact) {
  10062. return Situs.create(exact.start, exact.soffset, exact.finish, exact.foffset);
  10063. });
  10064. };
  10065. var clearSelection = function () {
  10066. clear(win);
  10067. };
  10068. var collapseSelection = function (toStart) {
  10069. if (toStart === void 0) {
  10070. toStart = false;
  10071. }
  10072. get$1(win).each(function (sel) {
  10073. return sel.fold(function (rng) {
  10074. return rng.collapse(toStart);
  10075. }, function (startSitu, finishSitu) {
  10076. var situ = toStart ? startSitu : finishSitu;
  10077. setRelative(win, situ, situ);
  10078. }, function (start, soffset, finish, foffset) {
  10079. var node = toStart ? start : finish;
  10080. var offset = toStart ? soffset : foffset;
  10081. setExact(win, node, offset, node, offset);
  10082. });
  10083. });
  10084. };
  10085. var selectNode = function (element) {
  10086. setToElement(win, element, false);
  10087. };
  10088. var selectContents = function (element) {
  10089. setToElement(win, element);
  10090. };
  10091. var setSelection = function (sel) {
  10092. setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
  10093. };
  10094. var setRelativeSelection = function (start, finish) {
  10095. setRelative(win, start, finish);
  10096. };
  10097. var getInnerHeight = function () {
  10098. return win.innerHeight;
  10099. };
  10100. var getScrollY = function () {
  10101. var pos = get(SugarElement.fromDom(win.document));
  10102. return pos.top;
  10103. };
  10104. var scrollBy = function (x, y) {
  10105. by(x, y, SugarElement.fromDom(win.document));
  10106. };
  10107. return {
  10108. elementFromPoint: elementFromPoint,
  10109. getRect: getRect,
  10110. getRangedRect: getRangedRect,
  10111. getSelection: getSelection,
  10112. fromSitus: fromSitus,
  10113. situsFromPoint: situsFromPoint,
  10114. clearSelection: clearSelection,
  10115. collapseSelection: collapseSelection,
  10116. setSelection: setSelection,
  10117. setRelativeSelection: setRelativeSelection,
  10118. selectNode: selectNode,
  10119. selectContents: selectContents,
  10120. getInnerHeight: getInnerHeight,
  10121. getScrollY: getScrollY,
  10122. scrollBy: scrollBy
  10123. };
  10124. };
  10125. var rc = function (rows, cols) {
  10126. return {
  10127. rows: rows,
  10128. cols: cols
  10129. };
  10130. };
  10131. var mouse = function (win, container, isRoot, annotations) {
  10132. var bridge = WindowBridge(win);
  10133. var handlers = MouseSelection(bridge, container, isRoot, annotations);
  10134. return {
  10135. clearstate: handlers.clearstate,
  10136. mousedown: handlers.mousedown,
  10137. mouseover: handlers.mouseover,
  10138. mouseup: handlers.mouseup
  10139. };
  10140. };
  10141. var keyboard = function (win, container, isRoot, annotations) {
  10142. var bridge = WindowBridge(win);
  10143. var clearToNavigate = function () {
  10144. annotations.clear(container);
  10145. return Optional.none();
  10146. };
  10147. var keydown = function (event, start, soffset, finish, foffset, direction) {
  10148. var realEvent = event.raw;
  10149. var keycode = realEvent.which;
  10150. var shiftKey = realEvent.shiftKey === true;
  10151. var handler = retrieve$1(container, annotations.selectedSelector).fold(function () {
  10152. if (isDown(keycode) && shiftKey) {
  10153. return curry(select, bridge, container, isRoot, down, finish, start, annotations.selectRange);
  10154. } else if (isUp(keycode) && shiftKey) {
  10155. return curry(select, bridge, container, isRoot, up, finish, start, annotations.selectRange);
  10156. } else if (isDown(keycode)) {
  10157. return curry(navigate, bridge, isRoot, down, finish, start, lastDownCheck);
  10158. } else if (isUp(keycode)) {
  10159. return curry(navigate, bridge, isRoot, up, finish, start, firstUpCheck);
  10160. } else {
  10161. return Optional.none;
  10162. }
  10163. }, function (selected) {
  10164. var update$1 = function (attempts) {
  10165. return function () {
  10166. var navigation = findMap(attempts, function (delta) {
  10167. return update(delta.rows, delta.cols, container, selected, annotations);
  10168. });
  10169. return navigation.fold(function () {
  10170. return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function (edges) {
  10171. var relative = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
  10172. bridge.setRelativeSelection(Situ.on(edges.first, 0), relative(edges.table));
  10173. annotations.clear(container);
  10174. return Response.create(Optional.none(), true);
  10175. });
  10176. }, function (_) {
  10177. return Optional.some(Response.create(Optional.none(), true));
  10178. });
  10179. };
  10180. };
  10181. if (isDown(keycode) && shiftKey) {
  10182. return update$1([rc(+1, 0)]);
  10183. } else if (isUp(keycode) && shiftKey) {
  10184. return update$1([rc(-1, 0)]);
  10185. } else if (direction.isBackward(keycode) && shiftKey) {
  10186. return update$1([
  10187. rc(0, -1),
  10188. rc(-1, 0)
  10189. ]);
  10190. } else if (direction.isForward(keycode) && shiftKey) {
  10191. return update$1([
  10192. rc(0, +1),
  10193. rc(+1, 0)
  10194. ]);
  10195. } else if (isNavigation(keycode) && shiftKey === false) {
  10196. return clearToNavigate;
  10197. } else {
  10198. return Optional.none;
  10199. }
  10200. });
  10201. return handler();
  10202. };
  10203. var keyup = function (event, start, soffset, finish, foffset) {
  10204. return retrieve$1(container, annotations.selectedSelector).fold(function () {
  10205. var realEvent = event.raw;
  10206. var keycode = realEvent.which;
  10207. var shiftKey = realEvent.shiftKey === true;
  10208. if (shiftKey === false) {
  10209. return Optional.none();
  10210. }
  10211. if (isNavigation(keycode)) {
  10212. return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
  10213. } else {
  10214. return Optional.none();
  10215. }
  10216. }, Optional.none);
  10217. };
  10218. return {
  10219. keydown: keydown,
  10220. keyup: keyup
  10221. };
  10222. };
  10223. var external = function (win, container, isRoot, annotations) {
  10224. var bridge = WindowBridge(win);
  10225. return function (start, finish) {
  10226. annotations.clearBeforeUpdate(container);
  10227. identify(start, finish, isRoot).each(function (cellSel) {
  10228. var boxes = cellSel.boxes.getOr([]);
  10229. annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
  10230. bridge.selectContents(finish);
  10231. bridge.collapseSelection();
  10232. });
  10233. };
  10234. };
  10235. var remove = function (element, classes) {
  10236. each$2(classes, function (x) {
  10237. remove$2(element, x);
  10238. });
  10239. };
  10240. var addClass = function (clazz) {
  10241. return function (element) {
  10242. add(element, clazz);
  10243. };
  10244. };
  10245. var removeClasses = function (classes) {
  10246. return function (element) {
  10247. remove(element, classes);
  10248. };
  10249. };
  10250. var byClass = function (ephemera) {
  10251. var addSelectionClass = addClass(ephemera.selected);
  10252. var removeSelectionClasses = removeClasses([
  10253. ephemera.selected,
  10254. ephemera.lastSelected,
  10255. ephemera.firstSelected
  10256. ]);
  10257. var clear = function (container) {
  10258. var sels = descendants(container, ephemera.selectedSelector);
  10259. each$2(sels, removeSelectionClasses);
  10260. };
  10261. var selectRange = function (container, cells, start, finish) {
  10262. clear(container);
  10263. each$2(cells, addSelectionClass);
  10264. add(start, ephemera.firstSelected);
  10265. add(finish, ephemera.lastSelected);
  10266. };
  10267. return {
  10268. clearBeforeUpdate: clear,
  10269. clear: clear,
  10270. selectRange: selectRange,
  10271. selectedSelector: ephemera.selectedSelector,
  10272. firstSelectedSelector: ephemera.firstSelectedSelector,
  10273. lastSelectedSelector: ephemera.lastSelectedSelector
  10274. };
  10275. };
  10276. var byAttr = function (ephemera, onSelection, onClear) {
  10277. var removeSelectionAttributes = function (element) {
  10278. remove$7(element, ephemera.selected);
  10279. remove$7(element, ephemera.firstSelected);
  10280. remove$7(element, ephemera.lastSelected);
  10281. };
  10282. var addSelectionAttribute = function (element) {
  10283. set$2(element, ephemera.selected, '1');
  10284. };
  10285. var clear = function (container) {
  10286. clearBeforeUpdate(container);
  10287. onClear();
  10288. };
  10289. var clearBeforeUpdate = function (container) {
  10290. var sels = descendants(container, ephemera.selectedSelector);
  10291. each$2(sels, removeSelectionAttributes);
  10292. };
  10293. var selectRange = function (container, cells, start, finish) {
  10294. clear(container);
  10295. each$2(cells, addSelectionAttribute);
  10296. set$2(start, ephemera.firstSelected, '1');
  10297. set$2(finish, ephemera.lastSelected, '1');
  10298. onSelection(cells, start, finish);
  10299. };
  10300. return {
  10301. clearBeforeUpdate: clearBeforeUpdate,
  10302. clear: clear,
  10303. selectRange: selectRange,
  10304. selectedSelector: ephemera.selectedSelector,
  10305. firstSelectedSelector: ephemera.firstSelectedSelector,
  10306. lastSelectedSelector: ephemera.lastSelectedSelector
  10307. };
  10308. };
  10309. var SelectionAnnotation = {
  10310. byClass: byClass,
  10311. byAttr: byAttr
  10312. };
  10313. var getUpOrLeftCells = function (grid, selectedCells) {
  10314. var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row + 1);
  10315. var upDetails = toDetailList(upGrid);
  10316. return bind$2(upDetails, function (detail) {
  10317. var slicedCells = detail.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
  10318. return map$1(slicedCells, function (cell) {
  10319. return cell.element;
  10320. });
  10321. });
  10322. };
  10323. var getDownOrRightCells = function (grid, selectedCells) {
  10324. var downGrid = grid.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid.length);
  10325. var downDetails = toDetailList(downGrid);
  10326. return bind$2(downDetails, function (detail) {
  10327. var slicedCells = detail.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail.cells.length);
  10328. return map$1(slicedCells, function (cell) {
  10329. return cell.element;
  10330. });
  10331. });
  10332. };
  10333. var getOtherCells = function (table, target, generators) {
  10334. var warehouse = Warehouse.fromTable(table);
  10335. var details = onCells(warehouse, target);
  10336. return details.map(function (selectedCells) {
  10337. var grid = toGrid(warehouse, generators, false);
  10338. var upOrLeftCells = getUpOrLeftCells(grid, selectedCells);
  10339. var downOrRightCells = getDownOrRightCells(grid, selectedCells);
  10340. return {
  10341. upOrLeftCells: upOrLeftCells,
  10342. downOrRightCells: downOrRightCells
  10343. };
  10344. });
  10345. };
  10346. var global = tinymce.util.Tools.resolve('tinymce.Env');
  10347. var hasInternalTarget = function (e) {
  10348. return has(SugarElement.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
  10349. };
  10350. function CellSelection (editor, lazyResize, selectionTargets) {
  10351. var onSelection = function (cells, start, finish) {
  10352. selectionTargets.targets().each(function (targets) {
  10353. var tableOpt = table(start);
  10354. tableOpt.each(function (table) {
  10355. var cloneFormats = getCloneElements(editor);
  10356. var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), cloneFormats);
  10357. var otherCells = getOtherCells(table, targets, generators);
  10358. fireTableSelectionChange(editor, cells, start, finish, otherCells);
  10359. });
  10360. });
  10361. };
  10362. var onClear = function () {
  10363. return fireTableSelectionClear(editor);
  10364. };
  10365. var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
  10366. editor.on('init', function (_e) {
  10367. var win = editor.getWin();
  10368. var body = getBody(editor);
  10369. var isRoot = getIsRoot(editor);
  10370. var syncSelection = function () {
  10371. var sel = editor.selection;
  10372. var start = SugarElement.fromDom(sel.getStart());
  10373. var end = SugarElement.fromDom(sel.getEnd());
  10374. var shared = sharedOne(table, [
  10375. start,
  10376. end
  10377. ]);
  10378. shared.fold(function () {
  10379. return annotations.clear(body);
  10380. }, noop);
  10381. };
  10382. var mouseHandlers = mouse(win, body, isRoot, annotations);
  10383. var keyHandlers = keyboard(win, body, isRoot, annotations);
  10384. var external$1 = external(win, body, isRoot, annotations);
  10385. var hasShiftKey = function (event) {
  10386. return event.raw.shiftKey === true;
  10387. };
  10388. editor.on('TableSelectorChange', function (e) {
  10389. return external$1(e.start, e.finish);
  10390. });
  10391. var handleResponse = function (event, response) {
  10392. if (!hasShiftKey(event)) {
  10393. return;
  10394. }
  10395. if (response.kill) {
  10396. event.kill();
  10397. }
  10398. response.selection.each(function (ns) {
  10399. var relative = SimSelection.relative(ns.start, ns.finish);
  10400. var rng = asLtrRange(win, relative);
  10401. editor.selection.setRng(rng);
  10402. });
  10403. };
  10404. var keyup = function (event) {
  10405. var wrappedEvent = fromRawEvent(event);
  10406. if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
  10407. var rng = editor.selection.getRng();
  10408. var start = SugarElement.fromDom(rng.startContainer);
  10409. var end = SugarElement.fromDom(rng.endContainer);
  10410. keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
  10411. handleResponse(wrappedEvent, response);
  10412. });
  10413. }
  10414. };
  10415. var keydown = function (event) {
  10416. var wrappedEvent = fromRawEvent(event);
  10417. lazyResize().each(function (resize) {
  10418. return resize.hideBars();
  10419. });
  10420. var rng = editor.selection.getRng();
  10421. var start = SugarElement.fromDom(rng.startContainer);
  10422. var end = SugarElement.fromDom(rng.endContainer);
  10423. var direction = onDirection(ltr, rtl)(SugarElement.fromDom(editor.selection.getStart()));
  10424. keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
  10425. handleResponse(wrappedEvent, response);
  10426. });
  10427. lazyResize().each(function (resize) {
  10428. return resize.showBars();
  10429. });
  10430. };
  10431. var isLeftMouse = function (raw) {
  10432. return raw.button === 0;
  10433. };
  10434. var isLeftButtonPressed = function (raw) {
  10435. if (raw.buttons === undefined) {
  10436. return true;
  10437. }
  10438. if (global.browser.isEdge() && raw.buttons === 0) {
  10439. return true;
  10440. }
  10441. return (raw.buttons & 1) !== 0;
  10442. };
  10443. var dragStart = function (_e) {
  10444. mouseHandlers.clearstate();
  10445. };
  10446. var mouseDown = function (e) {
  10447. if (isLeftMouse(e) && hasInternalTarget(e)) {
  10448. mouseHandlers.mousedown(fromRawEvent(e));
  10449. }
  10450. };
  10451. var mouseOver = function (e) {
  10452. if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
  10453. mouseHandlers.mouseover(fromRawEvent(e));
  10454. }
  10455. };
  10456. var mouseUp = function (e) {
  10457. if (isLeftMouse(e) && hasInternalTarget(e)) {
  10458. mouseHandlers.mouseup(fromRawEvent(e));
  10459. }
  10460. };
  10461. var getDoubleTap = function () {
  10462. var lastTarget = Cell(SugarElement.fromDom(body));
  10463. var lastTimeStamp = Cell(0);
  10464. var touchEnd = function (t) {
  10465. var target = SugarElement.fromDom(t.target);
  10466. if (name(target) === 'td' || name(target) === 'th') {
  10467. var lT = lastTarget.get();
  10468. var lTS = lastTimeStamp.get();
  10469. if (eq$1(lT, target) && t.timeStamp - lTS < 300) {
  10470. t.preventDefault();
  10471. external$1(target, target);
  10472. }
  10473. }
  10474. lastTarget.set(target);
  10475. lastTimeStamp.set(t.timeStamp);
  10476. };
  10477. return { touchEnd: touchEnd };
  10478. };
  10479. var doubleTap = getDoubleTap();
  10480. editor.on('dragstart', dragStart);
  10481. editor.on('mousedown', mouseDown);
  10482. editor.on('mouseover', mouseOver);
  10483. editor.on('mouseup', mouseUp);
  10484. editor.on('touchend', doubleTap.touchEnd);
  10485. editor.on('keyup', keyup);
  10486. editor.on('keydown', keydown);
  10487. editor.on('NodeChange', syncSelection);
  10488. });
  10489. return { clear: annotations.clear };
  10490. }
  10491. var child = function (scope, selector) {
  10492. return child$1(scope, selector).isSome();
  10493. };
  10494. var getSelectionTargets = function (editor, selections) {
  10495. var targets = Cell(Optional.none());
  10496. var changeHandlers = Cell([]);
  10497. var selectionDetails = Optional.none();
  10498. var isCaption = isTag('caption');
  10499. var isDisabledForSelection = function (key) {
  10500. return selectionDetails.forall(function (details) {
  10501. return !details[key];
  10502. });
  10503. };
  10504. var getStart = function () {
  10505. return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  10506. };
  10507. var getEnd = function () {
  10508. return getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
  10509. };
  10510. var findTargets = function () {
  10511. return getStart().bind(function (startCellOrCaption) {
  10512. return flatten(lift2(table(startCellOrCaption), getEnd().bind(table), function (startTable, endTable) {
  10513. if (eq$1(startTable, endTable)) {
  10514. if (isCaption(startCellOrCaption)) {
  10515. return Optional.some(noMenu(startCellOrCaption));
  10516. } else {
  10517. return Optional.some(forMenu(selections, startTable, startCellOrCaption));
  10518. }
  10519. }
  10520. return Optional.none();
  10521. }));
  10522. });
  10523. };
  10524. var getExtractedDetails = function (targets) {
  10525. var tableOpt = table(targets.element);
  10526. return tableOpt.map(function (table) {
  10527. var warehouse = Warehouse.fromTable(table);
  10528. var selectedCells = onCells(warehouse, targets).getOr([]);
  10529. var locked = foldl(selectedCells, function (acc, cell) {
  10530. if (cell.isLocked) {
  10531. acc.onAny = true;
  10532. if (cell.column === 0) {
  10533. acc.onFirst = true;
  10534. } else if (cell.column + cell.colspan >= warehouse.grid.columns) {
  10535. acc.onLast = true;
  10536. }
  10537. }
  10538. return acc;
  10539. }, {
  10540. onAny: false,
  10541. onFirst: false,
  10542. onLast: false
  10543. });
  10544. return {
  10545. mergeable: onUnlockedMergable(warehouse, targets).isSome(),
  10546. unmergeable: onUnlockedUnmergable(warehouse, targets).isSome(),
  10547. locked: locked
  10548. };
  10549. });
  10550. };
  10551. var resetTargets = function () {
  10552. targets.set(cached(findTargets)());
  10553. selectionDetails = targets.get().bind(getExtractedDetails);
  10554. each$2(changeHandlers.get(), function (handler) {
  10555. return handler();
  10556. });
  10557. };
  10558. var setupHandler = function (handler) {
  10559. handler();
  10560. changeHandlers.set(changeHandlers.get().concat([handler]));
  10561. return function () {
  10562. changeHandlers.set(filter$2(changeHandlers.get(), function (h) {
  10563. return h !== handler;
  10564. }));
  10565. };
  10566. };
  10567. var onSetup = function (api, isDisabled) {
  10568. return setupHandler(function () {
  10569. return targets.get().fold(function () {
  10570. api.setDisabled(true);
  10571. }, function (targets) {
  10572. api.setDisabled(isDisabled(targets));
  10573. });
  10574. });
  10575. };
  10576. var onSetupWithToggle = function (api, isDisabled, isActive) {
  10577. return setupHandler(function () {
  10578. return targets.get().fold(function () {
  10579. api.setDisabled(true);
  10580. api.setActive(false);
  10581. }, function (targets) {
  10582. api.setDisabled(isDisabled(targets));
  10583. api.setActive(isActive(targets));
  10584. });
  10585. });
  10586. };
  10587. var isDisabledFromLocked = function (lockedDisable) {
  10588. return selectionDetails.exists(function (details) {
  10589. return details.locked[lockedDisable];
  10590. });
  10591. };
  10592. var onSetupTable = function (api) {
  10593. return onSetup(api, function (_) {
  10594. return false;
  10595. });
  10596. };
  10597. var onSetupCellOrRow = function (api) {
  10598. return onSetup(api, function (targets) {
  10599. return isCaption(targets.element);
  10600. });
  10601. };
  10602. var onSetupColumn = function (lockedDisable) {
  10603. return function (api) {
  10604. return onSetup(api, function (targets) {
  10605. return isCaption(targets.element) || isDisabledFromLocked(lockedDisable);
  10606. });
  10607. };
  10608. };
  10609. var onSetupPasteable = function (getClipboardData) {
  10610. return function (api) {
  10611. return onSetup(api, function (targets) {
  10612. return isCaption(targets.element) || getClipboardData().isNone();
  10613. });
  10614. };
  10615. };
  10616. var onSetupPasteableColumn = function (getClipboardData, lockedDisable) {
  10617. return function (api) {
  10618. return onSetup(api, function (targets) {
  10619. return isCaption(targets.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable);
  10620. });
  10621. };
  10622. };
  10623. var onSetupMergeable = function (api) {
  10624. return onSetup(api, function (_targets) {
  10625. return isDisabledForSelection('mergeable');
  10626. });
  10627. };
  10628. var onSetupUnmergeable = function (api) {
  10629. return onSetup(api, function (_targets) {
  10630. return isDisabledForSelection('unmergeable');
  10631. });
  10632. };
  10633. var onSetupTableWithCaption = function (api) {
  10634. return onSetupWithToggle(api, never, function (targets) {
  10635. var tableOpt = table(targets.element, getIsRoot(editor));
  10636. return tableOpt.exists(function (table) {
  10637. return child(table, 'caption');
  10638. });
  10639. });
  10640. };
  10641. var onSetupTableHeaders = function (command, headerType) {
  10642. return function (api) {
  10643. return onSetupWithToggle(api, function (targets) {
  10644. return isCaption(targets.element);
  10645. }, function () {
  10646. return editor.queryCommandValue(command) === headerType;
  10647. });
  10648. };
  10649. };
  10650. var onSetupTableRowHeaders = onSetupTableHeaders('mceTableRowType', 'header');
  10651. var onSetupTableColumnHeaders = onSetupTableHeaders('mceTableColType', 'th');
  10652. editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
  10653. return {
  10654. onSetupTable: onSetupTable,
  10655. onSetupCellOrRow: onSetupCellOrRow,
  10656. onSetupColumn: onSetupColumn,
  10657. onSetupPasteable: onSetupPasteable,
  10658. onSetupPasteableColumn: onSetupPasteableColumn,
  10659. onSetupMergeable: onSetupMergeable,
  10660. onSetupUnmergeable: onSetupUnmergeable,
  10661. resetTargets: resetTargets,
  10662. onSetupTableWithCaption: onSetupTableWithCaption,
  10663. onSetupTableRowHeaders: onSetupTableRowHeaders,
  10664. onSetupTableColumnHeaders: onSetupTableColumnHeaders,
  10665. targets: targets.get
  10666. };
  10667. };
  10668. var addButtons = function (editor, selections, selectionTargets, clipboard) {
  10669. editor.ui.registry.addMenuButton('table', {
  10670. tooltip: 'Table',
  10671. icon: 'table',
  10672. fetch: function (callback) {
  10673. return callback('inserttable | cell row column | advtablesort | tableprops deletetable');
  10674. }
  10675. });
  10676. var cmd = function (command) {
  10677. return function () {
  10678. return editor.execCommand(command);
  10679. };
  10680. };
  10681. editor.ui.registry.addButton('tableprops', {
  10682. tooltip: 'Table properties',
  10683. onAction: cmd('mceTableProps'),
  10684. icon: 'table',
  10685. onSetup: selectionTargets.onSetupTable
  10686. });
  10687. editor.ui.registry.addButton('tabledelete', {
  10688. tooltip: 'Delete table',
  10689. onAction: cmd('mceTableDelete'),
  10690. icon: 'table-delete-table',
  10691. onSetup: selectionTargets.onSetupTable
  10692. });
  10693. editor.ui.registry.addButton('tablecellprops', {
  10694. tooltip: 'Cell properties',
  10695. onAction: cmd('mceTableCellProps'),
  10696. icon: 'table-cell-properties',
  10697. onSetup: selectionTargets.onSetupCellOrRow
  10698. });
  10699. editor.ui.registry.addButton('tablemergecells', {
  10700. tooltip: 'Merge cells',
  10701. onAction: cmd('mceTableMergeCells'),
  10702. icon: 'table-merge-cells',
  10703. onSetup: selectionTargets.onSetupMergeable
  10704. });
  10705. editor.ui.registry.addButton('tablesplitcells', {
  10706. tooltip: 'Split cell',
  10707. onAction: cmd('mceTableSplitCells'),
  10708. icon: 'table-split-cells',
  10709. onSetup: selectionTargets.onSetupUnmergeable
  10710. });
  10711. editor.ui.registry.addButton('tableinsertrowbefore', {
  10712. tooltip: 'Insert row before',
  10713. onAction: cmd('mceTableInsertRowBefore'),
  10714. icon: 'table-insert-row-above',
  10715. onSetup: selectionTargets.onSetupCellOrRow
  10716. });
  10717. editor.ui.registry.addButton('tableinsertrowafter', {
  10718. tooltip: 'Insert row after',
  10719. onAction: cmd('mceTableInsertRowAfter'),
  10720. icon: 'table-insert-row-after',
  10721. onSetup: selectionTargets.onSetupCellOrRow
  10722. });
  10723. editor.ui.registry.addButton('tabledeleterow', {
  10724. tooltip: 'Delete row',
  10725. onAction: cmd('mceTableDeleteRow'),
  10726. icon: 'table-delete-row',
  10727. onSetup: selectionTargets.onSetupCellOrRow
  10728. });
  10729. editor.ui.registry.addButton('tablerowprops', {
  10730. tooltip: 'Row properties',
  10731. onAction: cmd('mceTableRowProps'),
  10732. icon: 'table-row-properties',
  10733. onSetup: selectionTargets.onSetupCellOrRow
  10734. });
  10735. editor.ui.registry.addButton('tableinsertcolbefore', {
  10736. tooltip: 'Insert column before',
  10737. onAction: cmd('mceTableInsertColBefore'),
  10738. icon: 'table-insert-column-before',
  10739. onSetup: selectionTargets.onSetupColumn('onFirst')
  10740. });
  10741. editor.ui.registry.addButton('tableinsertcolafter', {
  10742. tooltip: 'Insert column after',
  10743. onAction: cmd('mceTableInsertColAfter'),
  10744. icon: 'table-insert-column-after',
  10745. onSetup: selectionTargets.onSetupColumn('onLast')
  10746. });
  10747. editor.ui.registry.addButton('tabledeletecol', {
  10748. tooltip: 'Delete column',
  10749. onAction: cmd('mceTableDeleteCol'),
  10750. icon: 'table-delete-column',
  10751. onSetup: selectionTargets.onSetupColumn('onAny')
  10752. });
  10753. editor.ui.registry.addButton('tablecutrow', {
  10754. tooltip: 'Cut row',
  10755. icon: 'cut-row',
  10756. onAction: cmd('mceTableCutRow'),
  10757. onSetup: selectionTargets.onSetupCellOrRow
  10758. });
  10759. editor.ui.registry.addButton('tablecopyrow', {
  10760. tooltip: 'Copy row',
  10761. icon: 'duplicate-row',
  10762. onAction: cmd('mceTableCopyRow'),
  10763. onSetup: selectionTargets.onSetupCellOrRow
  10764. });
  10765. editor.ui.registry.addButton('tablepasterowbefore', {
  10766. tooltip: 'Paste row before',
  10767. icon: 'paste-row-before',
  10768. onAction: cmd('mceTablePasteRowBefore'),
  10769. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10770. });
  10771. editor.ui.registry.addButton('tablepasterowafter', {
  10772. tooltip: 'Paste row after',
  10773. icon: 'paste-row-after',
  10774. onAction: cmd('mceTablePasteRowAfter'),
  10775. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10776. });
  10777. editor.ui.registry.addButton('tablecutcol', {
  10778. tooltip: 'Cut column',
  10779. icon: 'cut-column',
  10780. onAction: cmd('mceTableCutCol'),
  10781. onSetup: selectionTargets.onSetupColumn('onAny')
  10782. });
  10783. editor.ui.registry.addButton('tablecopycol', {
  10784. tooltip: 'Copy column',
  10785. icon: 'duplicate-column',
  10786. onAction: cmd('mceTableCopyCol'),
  10787. onSetup: selectionTargets.onSetupColumn('onAny')
  10788. });
  10789. editor.ui.registry.addButton('tablepastecolbefore', {
  10790. tooltip: 'Paste column before',
  10791. icon: 'paste-column-before',
  10792. onAction: cmd('mceTablePasteColBefore'),
  10793. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
  10794. });
  10795. editor.ui.registry.addButton('tablepastecolafter', {
  10796. tooltip: 'Paste column after',
  10797. icon: 'paste-column-after',
  10798. onAction: cmd('mceTablePasteColAfter'),
  10799. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
  10800. });
  10801. editor.ui.registry.addButton('tableinsertdialog', {
  10802. tooltip: 'Insert table',
  10803. onAction: cmd('mceInsertTable'),
  10804. icon: 'table'
  10805. });
  10806. var tableClassList = filterNoneItem(getTableClassList(editor));
  10807. if (tableClassList.length !== 0) {
  10808. editor.ui.registry.addMenuButton('tableclass', {
  10809. icon: 'table-classes',
  10810. tooltip: 'Table styles',
  10811. fetch: generateMenuItemsCallback(editor, selections, tableClassList, 'tableclass', function (value) {
  10812. return editor.execCommand('mceTableToggleClass', false, value);
  10813. }),
  10814. onSetup: selectionTargets.onSetupTable
  10815. });
  10816. }
  10817. var tableCellClassList = filterNoneItem(getCellClassList(editor));
  10818. if (tableCellClassList.length !== 0) {
  10819. editor.ui.registry.addMenuButton('tablecellclass', {
  10820. icon: 'table-cell-classes',
  10821. tooltip: 'Cell styles',
  10822. fetch: generateMenuItemsCallback(editor, selections, tableCellClassList, 'tablecellclass', function (value) {
  10823. return editor.execCommand('mceTableCellToggleClass', false, value);
  10824. }),
  10825. onSetup: selectionTargets.onSetupCellOrRow
  10826. });
  10827. }
  10828. editor.ui.registry.addMenuButton('tablecellvalign', {
  10829. icon: 'vertical-align',
  10830. tooltip: 'Vertical align',
  10831. fetch: generateMenuItemsCallback(editor, selections, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
  10832. onSetup: selectionTargets.onSetupCellOrRow
  10833. });
  10834. editor.ui.registry.addMenuButton('tablecellborderwidth', {
  10835. icon: 'border-width',
  10836. tooltip: 'Border width',
  10837. fetch: generateMenuItemsCallback(editor, selections, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
  10838. onSetup: selectionTargets.onSetupCellOrRow
  10839. });
  10840. editor.ui.registry.addMenuButton('tablecellborderstyle', {
  10841. icon: 'border-style',
  10842. tooltip: 'Border style',
  10843. fetch: generateMenuItemsCallback(editor, selections, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
  10844. onSetup: selectionTargets.onSetupCellOrRow
  10845. });
  10846. editor.ui.registry.addToggleButton('tablecaption', {
  10847. tooltip: 'Table caption',
  10848. onAction: cmd('mceTableToggleCaption'),
  10849. icon: 'table-caption',
  10850. onSetup: selectionTargets.onSetupTableWithCaption
  10851. });
  10852. editor.ui.registry.addMenuButton('tablecellbackgroundcolor', {
  10853. icon: 'cell-background-color',
  10854. tooltip: 'Background color',
  10855. fetch: function (callback) {
  10856. return callback(buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color'));
  10857. },
  10858. onSetup: selectionTargets.onSetupCellOrRow
  10859. });
  10860. editor.ui.registry.addMenuButton('tablecellbordercolor', {
  10861. icon: 'cell-border-color',
  10862. tooltip: 'Border color',
  10863. fetch: function (callback) {
  10864. return callback(buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color'));
  10865. },
  10866. onSetup: selectionTargets.onSetupCellOrRow
  10867. });
  10868. editor.ui.registry.addToggleButton('tablerowheader', {
  10869. tooltip: 'Row header',
  10870. icon: 'table-top-header',
  10871. onAction: changeRowHeader(editor),
  10872. onSetup: selectionTargets.onSetupTableRowHeaders
  10873. });
  10874. editor.ui.registry.addToggleButton('tablecolheader', {
  10875. tooltip: 'Column header',
  10876. icon: 'table-left-header',
  10877. onAction: changeColumnHeader(editor),
  10878. onSetup: selectionTargets.onSetupTableColumnHeaders
  10879. });
  10880. };
  10881. var addToolbars = function (editor) {
  10882. var isTable = function (table) {
  10883. return editor.dom.is(table, 'table') && editor.getBody().contains(table);
  10884. };
  10885. var toolbar = getToolbar(editor);
  10886. if (toolbar.length > 0) {
  10887. editor.ui.registry.addContextToolbar('table', {
  10888. predicate: isTable,
  10889. items: toolbar,
  10890. scope: 'node',
  10891. position: 'node'
  10892. });
  10893. }
  10894. };
  10895. var addMenuItems = function (editor, selections, selectionTargets, clipboard) {
  10896. var cmd = function (command) {
  10897. return function () {
  10898. return editor.execCommand(command);
  10899. };
  10900. };
  10901. var insertTableAction = function (data) {
  10902. editor.execCommand('mceInsertTable', false, {
  10903. rows: data.numRows,
  10904. columns: data.numColumns
  10905. });
  10906. };
  10907. var tableProperties = {
  10908. text: 'Table properties',
  10909. onSetup: selectionTargets.onSetupTable,
  10910. onAction: cmd('mceTableProps')
  10911. };
  10912. var deleteTable = {
  10913. text: 'Delete table',
  10914. icon: 'table-delete-table',
  10915. onSetup: selectionTargets.onSetupTable,
  10916. onAction: cmd('mceTableDelete')
  10917. };
  10918. editor.ui.registry.addMenuItem('tableinsertrowbefore', {
  10919. text: 'Insert row before',
  10920. icon: 'table-insert-row-above',
  10921. onAction: cmd('mceTableInsertRowBefore'),
  10922. onSetup: selectionTargets.onSetupCellOrRow
  10923. });
  10924. editor.ui.registry.addMenuItem('tableinsertrowafter', {
  10925. text: 'Insert row after',
  10926. icon: 'table-insert-row-after',
  10927. onAction: cmd('mceTableInsertRowAfter'),
  10928. onSetup: selectionTargets.onSetupCellOrRow
  10929. });
  10930. editor.ui.registry.addMenuItem('tabledeleterow', {
  10931. text: 'Delete row',
  10932. icon: 'table-delete-row',
  10933. onAction: cmd('mceTableDeleteRow'),
  10934. onSetup: selectionTargets.onSetupCellOrRow
  10935. });
  10936. editor.ui.registry.addMenuItem('tablerowprops', {
  10937. text: 'Row properties',
  10938. icon: 'table-row-properties',
  10939. onAction: cmd('mceTableRowProps'),
  10940. onSetup: selectionTargets.onSetupCellOrRow
  10941. });
  10942. editor.ui.registry.addMenuItem('tablecutrow', {
  10943. text: 'Cut row',
  10944. icon: 'cut-row',
  10945. onAction: cmd('mceTableCutRow'),
  10946. onSetup: selectionTargets.onSetupCellOrRow
  10947. });
  10948. editor.ui.registry.addMenuItem('tablecopyrow', {
  10949. text: 'Copy row',
  10950. icon: 'duplicate-row',
  10951. onAction: cmd('mceTableCopyRow'),
  10952. onSetup: selectionTargets.onSetupCellOrRow
  10953. });
  10954. editor.ui.registry.addMenuItem('tablepasterowbefore', {
  10955. text: 'Paste row before',
  10956. icon: 'paste-row-before',
  10957. onAction: cmd('mceTablePasteRowBefore'),
  10958. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10959. });
  10960. editor.ui.registry.addMenuItem('tablepasterowafter', {
  10961. text: 'Paste row after',
  10962. icon: 'paste-row-after',
  10963. onAction: cmd('mceTablePasteRowAfter'),
  10964. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10965. });
  10966. var row = {
  10967. type: 'nestedmenuitem',
  10968. text: 'Row',
  10969. getSubmenuItems: constant('tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter')
  10970. };
  10971. editor.ui.registry.addMenuItem('tableinsertcolumnbefore', {
  10972. text: 'Insert column before',
  10973. icon: 'table-insert-column-before',
  10974. onAction: cmd('mceTableInsertColBefore'),
  10975. onSetup: selectionTargets.onSetupColumn('onFirst')
  10976. });
  10977. editor.ui.registry.addMenuItem('tableinsertcolumnafter', {
  10978. text: 'Insert column after',
  10979. icon: 'table-insert-column-after',
  10980. onAction: cmd('mceTableInsertColAfter'),
  10981. onSetup: selectionTargets.onSetupColumn('onLast')
  10982. });
  10983. editor.ui.registry.addMenuItem('tabledeletecolumn', {
  10984. text: 'Delete column',
  10985. icon: 'table-delete-column',
  10986. onAction: cmd('mceTableDeleteCol'),
  10987. onSetup: selectionTargets.onSetupColumn('onAny')
  10988. });
  10989. editor.ui.registry.addMenuItem('tablecutcolumn', {
  10990. text: 'Cut column',
  10991. icon: 'cut-column',
  10992. onAction: cmd('mceTableCutCol'),
  10993. onSetup: selectionTargets.onSetupColumn('onAny')
  10994. });
  10995. editor.ui.registry.addMenuItem('tablecopycolumn', {
  10996. text: 'Copy column',
  10997. icon: 'duplicate-column',
  10998. onAction: cmd('mceTableCopyCol'),
  10999. onSetup: selectionTargets.onSetupColumn('onAny')
  11000. });
  11001. editor.ui.registry.addMenuItem('tablepastecolumnbefore', {
  11002. text: 'Paste column before',
  11003. icon: 'paste-column-before',
  11004. onAction: cmd('mceTablePasteColBefore'),
  11005. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
  11006. });
  11007. editor.ui.registry.addMenuItem('tablepastecolumnafter', {
  11008. text: 'Paste column after',
  11009. icon: 'paste-column-after',
  11010. onAction: cmd('mceTablePasteColAfter'),
  11011. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
  11012. });
  11013. var column = {
  11014. type: 'nestedmenuitem',
  11015. text: 'Column',
  11016. getSubmenuItems: constant('tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter')
  11017. };
  11018. editor.ui.registry.addMenuItem('tablecellprops', {
  11019. text: 'Cell properties',
  11020. icon: 'table-cell-properties',
  11021. onAction: cmd('mceTableCellProps'),
  11022. onSetup: selectionTargets.onSetupCellOrRow
  11023. });
  11024. editor.ui.registry.addMenuItem('tablemergecells', {
  11025. text: 'Merge cells',
  11026. icon: 'table-merge-cells',
  11027. onAction: cmd('mceTableMergeCells'),
  11028. onSetup: selectionTargets.onSetupMergeable
  11029. });
  11030. editor.ui.registry.addMenuItem('tablesplitcells', {
  11031. text: 'Split cell',
  11032. icon: 'table-split-cells',
  11033. onAction: cmd('mceTableSplitCells'),
  11034. onSetup: selectionTargets.onSetupUnmergeable
  11035. });
  11036. var cell = {
  11037. type: 'nestedmenuitem',
  11038. text: 'Cell',
  11039. getSubmenuItems: constant('tablecellprops tablemergecells tablesplitcells')
  11040. };
  11041. if (hasTableGrid(editor) === false) {
  11042. editor.ui.registry.addMenuItem('inserttable', {
  11043. text: 'Table',
  11044. icon: 'table',
  11045. onAction: cmd('mceInsertTable')
  11046. });
  11047. } else {
  11048. editor.ui.registry.addNestedMenuItem('inserttable', {
  11049. text: 'Table',
  11050. icon: 'table',
  11051. getSubmenuItems: function () {
  11052. return [{
  11053. type: 'fancymenuitem',
  11054. fancytype: 'inserttable',
  11055. onAction: insertTableAction
  11056. }];
  11057. }
  11058. });
  11059. }
  11060. editor.ui.registry.addMenuItem('inserttabledialog', {
  11061. text: 'Insert table',
  11062. icon: 'table',
  11063. onAction: cmd('mceInsertTable')
  11064. });
  11065. editor.ui.registry.addMenuItem('tableprops', tableProperties);
  11066. editor.ui.registry.addMenuItem('deletetable', deleteTable);
  11067. editor.ui.registry.addNestedMenuItem('row', row);
  11068. editor.ui.registry.addNestedMenuItem('column', column);
  11069. editor.ui.registry.addNestedMenuItem('cell', cell);
  11070. editor.ui.registry.addContextMenu('table', {
  11071. update: function () {
  11072. selectionTargets.resetTargets();
  11073. return selectionTargets.targets().fold(constant(''), function (targets) {
  11074. if (name(targets.element) === 'caption') {
  11075. return 'tableprops deletetable';
  11076. } else {
  11077. return 'cell row column | advtablesort | tableprops deletetable';
  11078. }
  11079. });
  11080. }
  11081. });
  11082. var tableClassList = filterNoneItem(getTableClassList(editor));
  11083. if (tableClassList.length !== 0) {
  11084. editor.ui.registry.addNestedMenuItem('tableclass', {
  11085. icon: 'table-classes',
  11086. text: 'Table styles',
  11087. getSubmenuItems: function () {
  11088. return buildMenuItems(editor, selections, tableClassList, 'tableclass', function (value) {
  11089. return editor.execCommand('mceTableToggleClass', false, value);
  11090. });
  11091. },
  11092. onSetup: selectionTargets.onSetupTable
  11093. });
  11094. }
  11095. var tableCellClassList = filterNoneItem(getCellClassList(editor));
  11096. if (tableCellClassList.length !== 0) {
  11097. editor.ui.registry.addNestedMenuItem('tablecellclass', {
  11098. icon: 'table-cell-classes',
  11099. text: 'Cell styles',
  11100. getSubmenuItems: function () {
  11101. return buildMenuItems(editor, selections, tableCellClassList, 'tablecellclass', function (value) {
  11102. return editor.execCommand('mceTableCellToggleClass', false, value);
  11103. });
  11104. },
  11105. onSetup: selectionTargets.onSetupCellOrRow
  11106. });
  11107. }
  11108. editor.ui.registry.addNestedMenuItem('tablecellvalign', {
  11109. icon: 'vertical-align',
  11110. text: 'Vertical align',
  11111. getSubmenuItems: function () {
  11112. return buildMenuItems(editor, selections, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align'));
  11113. },
  11114. onSetup: selectionTargets.onSetupCellOrRow
  11115. });
  11116. editor.ui.registry.addNestedMenuItem('tablecellborderwidth', {
  11117. icon: 'border-width',
  11118. text: 'Border width',
  11119. getSubmenuItems: function () {
  11120. return buildMenuItems(editor, selections, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width'));
  11121. },
  11122. onSetup: selectionTargets.onSetupCellOrRow
  11123. });
  11124. editor.ui.registry.addNestedMenuItem('tablecellborderstyle', {
  11125. icon: 'border-style',
  11126. text: 'Border style',
  11127. getSubmenuItems: function () {
  11128. return buildMenuItems(editor, selections, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style'));
  11129. },
  11130. onSetup: selectionTargets.onSetupCellOrRow
  11131. });
  11132. editor.ui.registry.addToggleMenuItem('tablecaption', {
  11133. icon: 'table-caption',
  11134. text: 'Table caption',
  11135. onAction: cmd('mceTableToggleCaption'),
  11136. onSetup: selectionTargets.onSetupTableWithCaption
  11137. });
  11138. editor.ui.registry.addNestedMenuItem('tablecellbackgroundcolor', {
  11139. icon: 'cell-background-color',
  11140. text: 'Background color',
  11141. getSubmenuItems: function () {
  11142. return buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color');
  11143. },
  11144. onSetup: selectionTargets.onSetupCellOrRow
  11145. });
  11146. editor.ui.registry.addNestedMenuItem('tablecellbordercolor', {
  11147. icon: 'cell-border-color',
  11148. text: 'Border color',
  11149. getSubmenuItems: function () {
  11150. return buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color');
  11151. },
  11152. onSetup: selectionTargets.onSetupCellOrRow
  11153. });
  11154. editor.ui.registry.addToggleMenuItem('tablerowheader', {
  11155. text: 'Row header',
  11156. icon: 'table-top-header',
  11157. onAction: changeRowHeader(editor),
  11158. onSetup: selectionTargets.onSetupTableRowHeaders
  11159. });
  11160. editor.ui.registry.addToggleMenuItem('tablecolheader', {
  11161. text: 'Column header',
  11162. icon: 'table-left-header',
  11163. onAction: changeColumnHeader(editor),
  11164. onSetup: selectionTargets.onSetupTableColumnHeaders
  11165. });
  11166. };
  11167. var Plugin = function (editor) {
  11168. var selections = Selections(function () {
  11169. return getBody(editor);
  11170. }, function () {
  11171. return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
  11172. }, ephemera.selectedSelector);
  11173. var selectionTargets = getSelectionTargets(editor, selections);
  11174. var resizeHandler = getResizeHandler(editor);
  11175. var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
  11176. var actions = TableActions(editor, cellSelection, resizeHandler.lazyWire);
  11177. var clipboard = Clipboard();
  11178. registerCommands(editor, actions, cellSelection, selections, clipboard);
  11179. registerQueryCommands(editor, actions, selections);
  11180. registerEvents(editor, selections, actions);
  11181. addMenuItems(editor, selections, selectionTargets, clipboard);
  11182. addButtons(editor, selections, selectionTargets, clipboard);
  11183. addToolbars(editor);
  11184. editor.on('PreInit', function () {
  11185. editor.serializer.addTempAttr(ephemera.firstSelected);
  11186. editor.serializer.addTempAttr(ephemera.lastSelected);
  11187. registerFormats(editor);
  11188. });
  11189. if (hasTabNavigation(editor)) {
  11190. editor.on('keydown', function (e) {
  11191. handle$1(e, editor, cellSelection);
  11192. });
  11193. }
  11194. editor.on('remove', function () {
  11195. resizeHandler.destroy();
  11196. });
  11197. return getApi(editor, clipboard, resizeHandler, selectionTargets);
  11198. };
  11199. function Plugin$1 () {
  11200. global$3.add('table', Plugin);
  11201. }
  11202. Plugin$1();
  11203. }());