plugin.js 392 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510
  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.10.2 (2021-11-17)
  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 toFloat = function (value) {
  529. var num = parseFloat(value);
  530. return isNaN(num) ? Optional.none() : Optional.some(num);
  531. };
  532. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  533. var checkContains = function (target) {
  534. return function (uastring) {
  535. return contains$1(uastring, target);
  536. };
  537. };
  538. var browsers = [
  539. {
  540. name: 'Edge',
  541. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  542. search: function (uastring) {
  543. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  544. }
  545. },
  546. {
  547. name: 'Chrome',
  548. brand: 'Chromium',
  549. versionRegexes: [
  550. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  551. normalVersionRegex
  552. ],
  553. search: function (uastring) {
  554. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  555. }
  556. },
  557. {
  558. name: 'IE',
  559. versionRegexes: [
  560. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  561. /.*?rv:([0-9]+)\.([0-9]+).*/
  562. ],
  563. search: function (uastring) {
  564. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  565. }
  566. },
  567. {
  568. name: 'Opera',
  569. versionRegexes: [
  570. normalVersionRegex,
  571. /.*?opera\/([0-9]+)\.([0-9]+).*/
  572. ],
  573. search: checkContains('opera')
  574. },
  575. {
  576. name: 'Firefox',
  577. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  578. search: checkContains('firefox')
  579. },
  580. {
  581. name: 'Safari',
  582. versionRegexes: [
  583. normalVersionRegex,
  584. /.*?cpu os ([0-9]+)_([0-9]+).*/
  585. ],
  586. search: function (uastring) {
  587. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  588. }
  589. }
  590. ];
  591. var oses = [
  592. {
  593. name: 'Windows',
  594. search: checkContains('win'),
  595. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  596. },
  597. {
  598. name: 'iOS',
  599. search: function (uastring) {
  600. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  601. },
  602. versionRegexes: [
  603. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  604. /.*cpu os ([0-9]+)_([0-9]+).*/,
  605. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  606. ]
  607. },
  608. {
  609. name: 'Android',
  610. search: checkContains('android'),
  611. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  612. },
  613. {
  614. name: 'OSX',
  615. search: checkContains('mac os x'),
  616. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  617. },
  618. {
  619. name: 'Linux',
  620. search: checkContains('linux'),
  621. versionRegexes: []
  622. },
  623. {
  624. name: 'Solaris',
  625. search: checkContains('sunos'),
  626. versionRegexes: []
  627. },
  628. {
  629. name: 'FreeBSD',
  630. search: checkContains('freebsd'),
  631. versionRegexes: []
  632. },
  633. {
  634. name: 'ChromeOS',
  635. search: checkContains('cros'),
  636. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  637. }
  638. ];
  639. var PlatformInfo = {
  640. browsers: constant(browsers),
  641. oses: constant(oses)
  642. };
  643. var edge = 'Edge';
  644. var chrome = 'Chrome';
  645. var ie = 'IE';
  646. var opera = 'Opera';
  647. var firefox = 'Firefox';
  648. var safari = 'Safari';
  649. var unknown$1 = function () {
  650. return nu$1({
  651. current: undefined,
  652. version: Version.unknown()
  653. });
  654. };
  655. var nu$1 = function (info) {
  656. var current = info.current;
  657. var version = info.version;
  658. var isBrowser = function (name) {
  659. return function () {
  660. return current === name;
  661. };
  662. };
  663. return {
  664. current: current,
  665. version: version,
  666. isEdge: isBrowser(edge),
  667. isChrome: isBrowser(chrome),
  668. isIE: isBrowser(ie),
  669. isOpera: isBrowser(opera),
  670. isFirefox: isBrowser(firefox),
  671. isSafari: isBrowser(safari)
  672. };
  673. };
  674. var Browser = {
  675. unknown: unknown$1,
  676. nu: nu$1,
  677. edge: constant(edge),
  678. chrome: constant(chrome),
  679. ie: constant(ie),
  680. opera: constant(opera),
  681. firefox: constant(firefox),
  682. safari: constant(safari)
  683. };
  684. var windows = 'Windows';
  685. var ios = 'iOS';
  686. var android = 'Android';
  687. var linux = 'Linux';
  688. var osx = 'OSX';
  689. var solaris = 'Solaris';
  690. var freebsd = 'FreeBSD';
  691. var chromeos = 'ChromeOS';
  692. var unknown = function () {
  693. return nu({
  694. current: undefined,
  695. version: Version.unknown()
  696. });
  697. };
  698. var nu = function (info) {
  699. var current = info.current;
  700. var version = info.version;
  701. var isOS = function (name) {
  702. return function () {
  703. return current === name;
  704. };
  705. };
  706. return {
  707. current: current,
  708. version: version,
  709. isWindows: isOS(windows),
  710. isiOS: isOS(ios),
  711. isAndroid: isOS(android),
  712. isOSX: isOS(osx),
  713. isLinux: isOS(linux),
  714. isSolaris: isOS(solaris),
  715. isFreeBSD: isOS(freebsd),
  716. isChromeOS: isOS(chromeos)
  717. };
  718. };
  719. var OperatingSystem = {
  720. unknown: unknown,
  721. nu: nu,
  722. windows: constant(windows),
  723. ios: constant(ios),
  724. android: constant(android),
  725. linux: constant(linux),
  726. osx: constant(osx),
  727. solaris: constant(solaris),
  728. freebsd: constant(freebsd),
  729. chromeos: constant(chromeos)
  730. };
  731. var detect$4 = function (userAgent, userAgentDataOpt, mediaMatch) {
  732. var browsers = PlatformInfo.browsers();
  733. var oses = PlatformInfo.oses();
  734. var browser = userAgentDataOpt.bind(function (userAgentData) {
  735. return detectBrowser$1(browsers, userAgentData);
  736. }).orThunk(function () {
  737. return detectBrowser(browsers, userAgent);
  738. }).fold(Browser.unknown, Browser.nu);
  739. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  740. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  741. return {
  742. browser: browser,
  743. os: os,
  744. deviceType: deviceType
  745. };
  746. };
  747. var PlatformDetection = { detect: detect$4 };
  748. var mediaMatch = function (query) {
  749. return window.matchMedia(query).matches;
  750. };
  751. var platform = cached(function () {
  752. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  753. });
  754. var detect$3 = function () {
  755. return platform();
  756. };
  757. var compareDocumentPosition = function (a, b, match) {
  758. return (a.compareDocumentPosition(b) & match) !== 0;
  759. };
  760. var documentPositionContainedBy = function (a, b) {
  761. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  762. };
  763. var COMMENT = 8;
  764. var DOCUMENT = 9;
  765. var DOCUMENT_FRAGMENT = 11;
  766. var ELEMENT = 1;
  767. var TEXT = 3;
  768. var fromHtml$1 = function (html, scope) {
  769. var doc = scope || document;
  770. var div = doc.createElement('div');
  771. div.innerHTML = html;
  772. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  773. console.error('HTML does not have a single root node', html);
  774. throw new Error('HTML must have a single root node');
  775. }
  776. return fromDom$1(div.childNodes[0]);
  777. };
  778. var fromTag = function (tag, scope) {
  779. var doc = scope || document;
  780. var node = doc.createElement(tag);
  781. return fromDom$1(node);
  782. };
  783. var fromText = function (text, scope) {
  784. var doc = scope || document;
  785. var node = doc.createTextNode(text);
  786. return fromDom$1(node);
  787. };
  788. var fromDom$1 = function (node) {
  789. if (node === null || node === undefined) {
  790. throw new Error('Node cannot be null or undefined');
  791. }
  792. return { dom: node };
  793. };
  794. var fromPoint$1 = function (docElm, x, y) {
  795. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$1);
  796. };
  797. var SugarElement = {
  798. fromHtml: fromHtml$1,
  799. fromTag: fromTag,
  800. fromText: fromText,
  801. fromDom: fromDom$1,
  802. fromPoint: fromPoint$1
  803. };
  804. var is$2 = function (element, selector) {
  805. var dom = element.dom;
  806. if (dom.nodeType !== ELEMENT) {
  807. return false;
  808. } else {
  809. var elem = dom;
  810. if (elem.matches !== undefined) {
  811. return elem.matches(selector);
  812. } else if (elem.msMatchesSelector !== undefined) {
  813. return elem.msMatchesSelector(selector);
  814. } else if (elem.webkitMatchesSelector !== undefined) {
  815. return elem.webkitMatchesSelector(selector);
  816. } else if (elem.mozMatchesSelector !== undefined) {
  817. return elem.mozMatchesSelector(selector);
  818. } else {
  819. throw new Error('Browser lacks native selectors');
  820. }
  821. }
  822. };
  823. var bypassSelector = function (dom) {
  824. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  825. };
  826. var all$1 = function (selector, scope) {
  827. var base = scope === undefined ? document : scope.dom;
  828. return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), SugarElement.fromDom);
  829. };
  830. var one = function (selector, scope) {
  831. var base = scope === undefined ? document : scope.dom;
  832. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  833. };
  834. var eq$1 = function (e1, e2) {
  835. return e1.dom === e2.dom;
  836. };
  837. var regularContains = function (e1, e2) {
  838. var d1 = e1.dom;
  839. var d2 = e2.dom;
  840. return d1 === d2 ? false : d1.contains(d2);
  841. };
  842. var ieContains = function (e1, e2) {
  843. return documentPositionContainedBy(e1.dom, e2.dom);
  844. };
  845. var contains = function (e1, e2) {
  846. return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  847. };
  848. var is$1 = is$2;
  849. var keys = Object.keys;
  850. var hasOwnProperty = Object.hasOwnProperty;
  851. var each$1 = function (obj, f) {
  852. var props = keys(obj);
  853. for (var k = 0, len = props.length; k < len; k++) {
  854. var i = props[k];
  855. var x = obj[i];
  856. f(x, i);
  857. }
  858. };
  859. var map = function (obj, f) {
  860. return tupleMap(obj, function (x, i) {
  861. return {
  862. k: i,
  863. v: f(x, i)
  864. };
  865. });
  866. };
  867. var tupleMap = function (obj, f) {
  868. var r = {};
  869. each$1(obj, function (x, i) {
  870. var tuple = f(x, i);
  871. r[tuple.k] = tuple.v;
  872. });
  873. return r;
  874. };
  875. var objAcc = function (r) {
  876. return function (x, i) {
  877. r[i] = x;
  878. };
  879. };
  880. var internalFilter = function (obj, pred, onTrue, onFalse) {
  881. var r = {};
  882. each$1(obj, function (x, i) {
  883. (pred(x, i) ? onTrue : onFalse)(x, i);
  884. });
  885. return r;
  886. };
  887. var filter$1 = function (obj, pred) {
  888. var t = {};
  889. internalFilter(obj, pred, objAcc(t), noop);
  890. return t;
  891. };
  892. var mapToArray = function (obj, f) {
  893. var r = [];
  894. each$1(obj, function (value, name) {
  895. r.push(f(value, name));
  896. });
  897. return r;
  898. };
  899. var values = function (obj) {
  900. return mapToArray(obj, identity);
  901. };
  902. var size = function (obj) {
  903. return keys(obj).length;
  904. };
  905. var get$c = function (obj, key) {
  906. return has$1(obj, key) ? Optional.from(obj[key]) : Optional.none();
  907. };
  908. var has$1 = function (obj, key) {
  909. return hasOwnProperty.call(obj, key);
  910. };
  911. var hasNonNullableKey = function (obj, key) {
  912. return has$1(obj, key) && obj[key] !== undefined && obj[key] !== null;
  913. };
  914. var isEmpty = function (r) {
  915. for (var x in r) {
  916. if (hasOwnProperty.call(r, x)) {
  917. return false;
  918. }
  919. }
  920. return true;
  921. };
  922. var validSectionList = [
  923. 'tfoot',
  924. 'thead',
  925. 'tbody',
  926. 'colgroup'
  927. ];
  928. var isValidSection = function (parentName) {
  929. return contains$2(validSectionList, parentName);
  930. };
  931. var grid = function (rows, columns) {
  932. return {
  933. rows: rows,
  934. columns: columns
  935. };
  936. };
  937. var address = function (row, column) {
  938. return {
  939. row: row,
  940. column: column
  941. };
  942. };
  943. var detail = function (element, rowspan, colspan) {
  944. return {
  945. element: element,
  946. rowspan: rowspan,
  947. colspan: colspan
  948. };
  949. };
  950. var detailnew = function (element, rowspan, colspan, isNew) {
  951. return {
  952. element: element,
  953. rowspan: rowspan,
  954. colspan: colspan,
  955. isNew: isNew
  956. };
  957. };
  958. var extended = function (element, rowspan, colspan, row, column, isLocked) {
  959. return {
  960. element: element,
  961. rowspan: rowspan,
  962. colspan: colspan,
  963. row: row,
  964. column: column,
  965. isLocked: isLocked
  966. };
  967. };
  968. var rowdetail = function (element, cells, section) {
  969. return {
  970. element: element,
  971. cells: cells,
  972. section: section
  973. };
  974. };
  975. var rowdetailnew = function (element, cells, section, isNew) {
  976. return {
  977. element: element,
  978. cells: cells,
  979. section: section,
  980. isNew: isNew
  981. };
  982. };
  983. var elementnew = function (element, isNew, isLocked) {
  984. return {
  985. element: element,
  986. isNew: isNew,
  987. isLocked: isLocked
  988. };
  989. };
  990. var rowcells = function (element, cells, section, isNew) {
  991. return {
  992. element: element,
  993. cells: cells,
  994. section: section,
  995. isNew: isNew
  996. };
  997. };
  998. var bounds = function (startRow, startCol, finishRow, finishCol) {
  999. return {
  1000. startRow: startRow,
  1001. startCol: startCol,
  1002. finishRow: finishRow,
  1003. finishCol: finishCol
  1004. };
  1005. };
  1006. var columnext = function (element, colspan, column) {
  1007. return {
  1008. element: element,
  1009. colspan: colspan,
  1010. column: column
  1011. };
  1012. };
  1013. var colgroup = function (element, columns) {
  1014. return {
  1015. element: element,
  1016. columns: columns
  1017. };
  1018. };
  1019. typeof window !== 'undefined' ? window : Function('return this;')();
  1020. var name = function (element) {
  1021. var r = element.dom.nodeName;
  1022. return r.toLowerCase();
  1023. };
  1024. var type$1 = function (element) {
  1025. return element.dom.nodeType;
  1026. };
  1027. var isType = function (t) {
  1028. return function (element) {
  1029. return type$1(element) === t;
  1030. };
  1031. };
  1032. var isComment = function (element) {
  1033. return type$1(element) === COMMENT || name(element) === '#comment';
  1034. };
  1035. var isElement = isType(ELEMENT);
  1036. var isText = isType(TEXT);
  1037. var isDocument = isType(DOCUMENT);
  1038. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  1039. var isTag = function (tag) {
  1040. return function (e) {
  1041. return isElement(e) && name(e) === tag;
  1042. };
  1043. };
  1044. var owner = function (element) {
  1045. return SugarElement.fromDom(element.dom.ownerDocument);
  1046. };
  1047. var documentOrOwner = function (dos) {
  1048. return isDocument(dos) ? dos : owner(dos);
  1049. };
  1050. var defaultView = function (element) {
  1051. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1052. };
  1053. var parent = function (element) {
  1054. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1055. };
  1056. var parentElement = function (element) {
  1057. return Optional.from(element.dom.parentElement).map(SugarElement.fromDom);
  1058. };
  1059. var parents = function (element, isRoot) {
  1060. var stop = isFunction(isRoot) ? isRoot : never;
  1061. var dom = element.dom;
  1062. var ret = [];
  1063. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1064. var rawParent = dom.parentNode;
  1065. var p = SugarElement.fromDom(rawParent);
  1066. ret.push(p);
  1067. if (stop(p) === true) {
  1068. break;
  1069. } else {
  1070. dom = rawParent;
  1071. }
  1072. }
  1073. return ret;
  1074. };
  1075. var prevSibling = function (element) {
  1076. return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1077. };
  1078. var nextSibling = function (element) {
  1079. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1080. };
  1081. var children$3 = function (element) {
  1082. return map$1(element.dom.childNodes, SugarElement.fromDom);
  1083. };
  1084. var child$3 = function (element, index) {
  1085. var cs = element.dom.childNodes;
  1086. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1087. };
  1088. var firstChild = function (element) {
  1089. return child$3(element, 0);
  1090. };
  1091. var isShadowRoot = function (dos) {
  1092. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  1093. };
  1094. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1095. var isSupported$1 = constant(supported);
  1096. var getRootNode = supported ? function (e) {
  1097. return SugarElement.fromDom(e.dom.getRootNode());
  1098. } : documentOrOwner;
  1099. var getShadowRoot = function (e) {
  1100. var r = getRootNode(e);
  1101. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1102. };
  1103. var getShadowHost = function (e) {
  1104. return SugarElement.fromDom(e.dom.host);
  1105. };
  1106. var getOriginalEventTarget = function (event) {
  1107. if (isSupported$1() && isNonNullable(event.target)) {
  1108. var el = SugarElement.fromDom(event.target);
  1109. if (isElement(el) && isOpenShadowHost(el)) {
  1110. if (event.composed && event.composedPath) {
  1111. var composedPath = event.composedPath();
  1112. if (composedPath) {
  1113. return head(composedPath);
  1114. }
  1115. }
  1116. }
  1117. }
  1118. return Optional.from(event.target);
  1119. };
  1120. var isOpenShadowHost = function (element) {
  1121. return isNonNullable(element.dom.shadowRoot);
  1122. };
  1123. var inBody = function (element) {
  1124. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1125. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1126. return false;
  1127. }
  1128. var doc = dom.ownerDocument;
  1129. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1130. return doc.body.contains(dom);
  1131. }, compose1(inBody, getShadowHost));
  1132. };
  1133. var body$1 = function () {
  1134. return getBody$1(SugarElement.fromDom(document));
  1135. };
  1136. var getBody$1 = function (doc) {
  1137. var b = doc.dom.body;
  1138. if (b === null || b === undefined) {
  1139. throw new Error('Body is not available yet');
  1140. }
  1141. return SugarElement.fromDom(b);
  1142. };
  1143. var ancestors$4 = function (scope, predicate, isRoot) {
  1144. return filter$2(parents(scope, isRoot), predicate);
  1145. };
  1146. var children$2 = function (scope, predicate) {
  1147. return filter$2(children$3(scope), predicate);
  1148. };
  1149. var descendants$1 = function (scope, predicate) {
  1150. var result = [];
  1151. each$2(children$3(scope), function (x) {
  1152. if (predicate(x)) {
  1153. result = result.concat([x]);
  1154. }
  1155. result = result.concat(descendants$1(x, predicate));
  1156. });
  1157. return result;
  1158. };
  1159. var ancestors$3 = function (scope, selector, isRoot) {
  1160. return ancestors$4(scope, function (e) {
  1161. return is$2(e, selector);
  1162. }, isRoot);
  1163. };
  1164. var children$1 = function (scope, selector) {
  1165. return children$2(scope, function (e) {
  1166. return is$2(e, selector);
  1167. });
  1168. };
  1169. var descendants = function (scope, selector) {
  1170. return all$1(selector, scope);
  1171. };
  1172. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  1173. if (is(scope, a)) {
  1174. return Optional.some(scope);
  1175. } else if (isFunction(isRoot) && isRoot(scope)) {
  1176. return Optional.none();
  1177. } else {
  1178. return ancestor(scope, a, isRoot);
  1179. }
  1180. }
  1181. var ancestor$2 = function (scope, predicate, isRoot) {
  1182. var element = scope.dom;
  1183. var stop = isFunction(isRoot) ? isRoot : never;
  1184. while (element.parentNode) {
  1185. element = element.parentNode;
  1186. var el = SugarElement.fromDom(element);
  1187. if (predicate(el)) {
  1188. return Optional.some(el);
  1189. } else if (stop(el)) {
  1190. break;
  1191. }
  1192. }
  1193. return Optional.none();
  1194. };
  1195. var closest$2 = function (scope, predicate, isRoot) {
  1196. var is = function (s, test) {
  1197. return test(s);
  1198. };
  1199. return ClosestOrAncestor(is, ancestor$2, scope, predicate, isRoot);
  1200. };
  1201. var child$2 = function (scope, predicate) {
  1202. var pred = function (node) {
  1203. return predicate(SugarElement.fromDom(node));
  1204. };
  1205. var result = find$1(scope.dom.childNodes, pred);
  1206. return result.map(SugarElement.fromDom);
  1207. };
  1208. var descendant$1 = function (scope, predicate) {
  1209. var descend = function (node) {
  1210. for (var i = 0; i < node.childNodes.length; i++) {
  1211. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  1212. if (predicate(child_1)) {
  1213. return Optional.some(child_1);
  1214. }
  1215. var res = descend(node.childNodes[i]);
  1216. if (res.isSome()) {
  1217. return res;
  1218. }
  1219. }
  1220. return Optional.none();
  1221. };
  1222. return descend(scope.dom);
  1223. };
  1224. var ancestor$1 = function (scope, selector, isRoot) {
  1225. return ancestor$2(scope, function (e) {
  1226. return is$2(e, selector);
  1227. }, isRoot);
  1228. };
  1229. var child$1 = function (scope, selector) {
  1230. return child$2(scope, function (e) {
  1231. return is$2(e, selector);
  1232. });
  1233. };
  1234. var descendant = function (scope, selector) {
  1235. return one(selector, scope);
  1236. };
  1237. var closest$1 = function (scope, selector, isRoot) {
  1238. var is = function (element, selector) {
  1239. return is$2(element, selector);
  1240. };
  1241. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  1242. };
  1243. var rawSet = function (dom, key, value) {
  1244. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1245. dom.setAttribute(key, value + '');
  1246. } else {
  1247. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1248. throw new Error('Attribute value was not simple');
  1249. }
  1250. };
  1251. var set$2 = function (element, key, value) {
  1252. rawSet(element.dom, key, value);
  1253. };
  1254. var setAll$1 = function (element, attrs) {
  1255. var dom = element.dom;
  1256. each$1(attrs, function (v, k) {
  1257. rawSet(dom, k, v);
  1258. });
  1259. };
  1260. var setOptions = function (element, attrs) {
  1261. each$1(attrs, function (v, k) {
  1262. v.fold(function () {
  1263. remove$7(element, k);
  1264. }, function (value) {
  1265. rawSet(element.dom, k, value);
  1266. });
  1267. });
  1268. };
  1269. var get$b = function (element, key) {
  1270. var v = element.dom.getAttribute(key);
  1271. return v === null ? undefined : v;
  1272. };
  1273. var getOpt = function (element, key) {
  1274. return Optional.from(get$b(element, key));
  1275. };
  1276. var remove$7 = function (element, key) {
  1277. element.dom.removeAttribute(key);
  1278. };
  1279. var clone$2 = function (element) {
  1280. return foldl(element.dom.attributes, function (acc, attr) {
  1281. acc[attr.name] = attr.value;
  1282. return acc;
  1283. }, {});
  1284. };
  1285. var is = function (lhs, rhs, comparator) {
  1286. if (comparator === void 0) {
  1287. comparator = tripleEquals;
  1288. }
  1289. return lhs.exists(function (left) {
  1290. return comparator(left, rhs);
  1291. });
  1292. };
  1293. var cat = function (arr) {
  1294. var r = [];
  1295. var push = function (x) {
  1296. r.push(x);
  1297. };
  1298. for (var i = 0; i < arr.length; i++) {
  1299. arr[i].each(push);
  1300. }
  1301. return r;
  1302. };
  1303. var lift2 = function (oa, ob, f) {
  1304. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1305. };
  1306. var bindFrom = function (a, f) {
  1307. return a !== undefined && a !== null ? f(a) : Optional.none();
  1308. };
  1309. var flatten = function (oot) {
  1310. return oot.bind(identity);
  1311. };
  1312. var someIf = function (b, a) {
  1313. return b ? Optional.some(a) : Optional.none();
  1314. };
  1315. var isSupported = function (dom) {
  1316. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1317. };
  1318. var internalSet = function (dom, property, value) {
  1319. if (!isString(value)) {
  1320. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1321. throw new Error('CSS value must be a string: ' + value);
  1322. }
  1323. if (isSupported(dom)) {
  1324. dom.style.setProperty(property, value);
  1325. }
  1326. };
  1327. var internalRemove = function (dom, property) {
  1328. if (isSupported(dom)) {
  1329. dom.style.removeProperty(property);
  1330. }
  1331. };
  1332. var set$1 = function (element, property, value) {
  1333. var dom = element.dom;
  1334. internalSet(dom, property, value);
  1335. };
  1336. var setAll = function (element, css) {
  1337. var dom = element.dom;
  1338. each$1(css, function (v, k) {
  1339. internalSet(dom, k, v);
  1340. });
  1341. };
  1342. var get$a = function (element, property) {
  1343. var dom = element.dom;
  1344. var styles = window.getComputedStyle(dom);
  1345. var r = styles.getPropertyValue(property);
  1346. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1347. };
  1348. var getUnsafeProperty = function (dom, property) {
  1349. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1350. };
  1351. var getRaw$2 = function (element, property) {
  1352. var dom = element.dom;
  1353. var raw = getUnsafeProperty(dom, property);
  1354. return Optional.from(raw).filter(function (r) {
  1355. return r.length > 0;
  1356. });
  1357. };
  1358. var remove$6 = function (element, property) {
  1359. var dom = element.dom;
  1360. internalRemove(dom, property);
  1361. if (is(getOpt(element, 'style').map(trim), '')) {
  1362. remove$7(element, 'style');
  1363. }
  1364. };
  1365. var copy$2 = function (source, target) {
  1366. var sourceDom = source.dom;
  1367. var targetDom = target.dom;
  1368. if (isSupported(sourceDom) && isSupported(targetDom)) {
  1369. targetDom.style.cssText = sourceDom.style.cssText;
  1370. }
  1371. };
  1372. var getAttrValue = function (cell, name, fallback) {
  1373. if (fallback === void 0) {
  1374. fallback = 0;
  1375. }
  1376. return getOpt(cell, name).map(function (value) {
  1377. return parseInt(value, 10);
  1378. }).getOr(fallback);
  1379. };
  1380. var getSpan = function (cell, type) {
  1381. return getAttrValue(cell, type, 1);
  1382. };
  1383. var hasColspan = function (cellOrCol) {
  1384. if (isTag('col')(cellOrCol)) {
  1385. return getAttrValue(cellOrCol, 'span', 1) > 1;
  1386. } else {
  1387. return getSpan(cellOrCol, 'colspan') > 1;
  1388. }
  1389. };
  1390. var hasRowspan = function (cell) {
  1391. return getSpan(cell, 'rowspan') > 1;
  1392. };
  1393. var getCssValue = function (element, property) {
  1394. return parseInt(get$a(element, property), 10);
  1395. };
  1396. var minWidth = constant(10);
  1397. var minHeight = constant(10);
  1398. var firstLayer = function (scope, selector) {
  1399. return filterFirstLayer(scope, selector, always);
  1400. };
  1401. var filterFirstLayer = function (scope, selector, predicate) {
  1402. return bind$2(children$3(scope), function (x) {
  1403. if (is$2(x, selector)) {
  1404. return predicate(x) ? [x] : [];
  1405. } else {
  1406. return filterFirstLayer(x, selector, predicate);
  1407. }
  1408. });
  1409. };
  1410. var lookup = function (tags, element, isRoot) {
  1411. if (isRoot === void 0) {
  1412. isRoot = never;
  1413. }
  1414. if (isRoot(element)) {
  1415. return Optional.none();
  1416. }
  1417. if (contains$2(tags, name(element))) {
  1418. return Optional.some(element);
  1419. }
  1420. var isRootOrUpperTable = function (elm) {
  1421. return is$2(elm, 'table') || isRoot(elm);
  1422. };
  1423. return ancestor$1(element, tags.join(','), isRootOrUpperTable);
  1424. };
  1425. var cell = function (element, isRoot) {
  1426. return lookup([
  1427. 'td',
  1428. 'th'
  1429. ], element, isRoot);
  1430. };
  1431. var cells$1 = function (ancestor) {
  1432. return firstLayer(ancestor, 'th,td');
  1433. };
  1434. var columns$1 = function (ancestor) {
  1435. if (is$2(ancestor, 'colgroup')) {
  1436. return children$1(ancestor, 'col');
  1437. } else {
  1438. return bind$2(columnGroups(ancestor), function (columnGroup) {
  1439. return children$1(columnGroup, 'col');
  1440. });
  1441. }
  1442. };
  1443. var table = function (element, isRoot) {
  1444. return closest$1(element, 'table', isRoot);
  1445. };
  1446. var rows$1 = function (ancestor) {
  1447. return firstLayer(ancestor, 'tr');
  1448. };
  1449. var columnGroups = function (ancestor) {
  1450. return table(ancestor).fold(constant([]), function (table) {
  1451. return children$1(table, 'colgroup');
  1452. });
  1453. };
  1454. var fromRowsOrColGroups = function (elems, getSection) {
  1455. return map$1(elems, function (row) {
  1456. if (name(row) === 'colgroup') {
  1457. var cells = map$1(columns$1(row), function (column) {
  1458. var colspan = getAttrValue(column, 'span', 1);
  1459. return detail(column, 1, colspan);
  1460. });
  1461. return rowdetail(row, cells, 'colgroup');
  1462. } else {
  1463. var cells = map$1(cells$1(row), function (cell) {
  1464. var rowspan = getAttrValue(cell, 'rowspan', 1);
  1465. var colspan = getAttrValue(cell, 'colspan', 1);
  1466. return detail(cell, rowspan, colspan);
  1467. });
  1468. return rowdetail(row, cells, getSection(row));
  1469. }
  1470. });
  1471. };
  1472. var getParentSection = function (group) {
  1473. return parent(group).map(function (parent) {
  1474. var parentName = name(parent);
  1475. return isValidSection(parentName) ? parentName : 'tbody';
  1476. }).getOr('tbody');
  1477. };
  1478. var fromTable$1 = function (table) {
  1479. var rows = rows$1(table);
  1480. var columnGroups$1 = columnGroups(table);
  1481. var elems = __spreadArray(__spreadArray([], columnGroups$1, true), rows, true);
  1482. return fromRowsOrColGroups(elems, getParentSection);
  1483. };
  1484. var fromPastedRows = function (elems, section) {
  1485. return fromRowsOrColGroups(elems, function () {
  1486. return section;
  1487. });
  1488. };
  1489. var addCells = function (gridRow, index, cells) {
  1490. var existingCells = gridRow.cells;
  1491. var before = existingCells.slice(0, index);
  1492. var after = existingCells.slice(index);
  1493. var newCells = before.concat(cells).concat(after);
  1494. return setCells(gridRow, newCells);
  1495. };
  1496. var addCell = function (gridRow, index, cell) {
  1497. return addCells(gridRow, index, [cell]);
  1498. };
  1499. var mutateCell = function (gridRow, index, cell) {
  1500. var cells = gridRow.cells;
  1501. cells[index] = cell;
  1502. };
  1503. var setCells = function (gridRow, cells) {
  1504. return rowcells(gridRow.element, cells, gridRow.section, gridRow.isNew);
  1505. };
  1506. var mapCells = function (gridRow, f) {
  1507. var cells = gridRow.cells;
  1508. var r = map$1(cells, f);
  1509. return rowcells(gridRow.element, r, gridRow.section, gridRow.isNew);
  1510. };
  1511. var getCell = function (gridRow, index) {
  1512. return gridRow.cells[index];
  1513. };
  1514. var getCellElement = function (gridRow, index) {
  1515. return getCell(gridRow, index).element;
  1516. };
  1517. var cellLength = function (gridRow) {
  1518. return gridRow.cells.length;
  1519. };
  1520. var extractGridDetails = function (grid) {
  1521. var result = partition(grid, function (row) {
  1522. return row.section === 'colgroup';
  1523. });
  1524. return {
  1525. rows: result.fail,
  1526. cols: result.pass
  1527. };
  1528. };
  1529. var clone$1 = function (gridRow, cloneRow, cloneCell) {
  1530. var newCells = map$1(gridRow.cells, cloneCell);
  1531. return rowcells(cloneRow(gridRow.element), newCells, gridRow.section, true);
  1532. };
  1533. var LOCKED_COL_ATTR = 'data-snooker-locked-cols';
  1534. var getLockedColumnsFromTable = function (table) {
  1535. return getOpt(table, LOCKED_COL_ATTR).bind(function (lockedColStr) {
  1536. return Optional.from(lockedColStr.match(/\d+/g));
  1537. }).map(function (lockedCols) {
  1538. return mapToObject(lockedCols, always);
  1539. });
  1540. };
  1541. var getLockedColumnsFromGrid = function (grid) {
  1542. var locked = foldl(extractGridDetails(grid).rows, function (acc, row) {
  1543. each$2(row.cells, function (cell, idx) {
  1544. if (cell.isLocked) {
  1545. acc[idx] = true;
  1546. }
  1547. });
  1548. return acc;
  1549. }, {});
  1550. var lockedArr = mapToArray(locked, function (_val, key) {
  1551. return parseInt(key, 10);
  1552. });
  1553. return sort$1(lockedArr);
  1554. };
  1555. var key = function (row, column) {
  1556. return row + ',' + column;
  1557. };
  1558. var getAt = function (warehouse, row, column) {
  1559. return Optional.from(warehouse.access[key(row, column)]);
  1560. };
  1561. var findItem = function (warehouse, item, comparator) {
  1562. var filtered = filterItems(warehouse, function (detail) {
  1563. return comparator(item, detail.element);
  1564. });
  1565. return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
  1566. };
  1567. var filterItems = function (warehouse, predicate) {
  1568. var all = bind$2(warehouse.all, function (r) {
  1569. return r.cells;
  1570. });
  1571. return filter$2(all, predicate);
  1572. };
  1573. var generateColumns = function (rowData) {
  1574. var columnsGroup = {};
  1575. var index = 0;
  1576. each$2(rowData.cells, function (column) {
  1577. var colspan = column.colspan;
  1578. range$1(colspan, function (columnIndex) {
  1579. var colIndex = index + columnIndex;
  1580. columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
  1581. });
  1582. index += colspan;
  1583. });
  1584. return columnsGroup;
  1585. };
  1586. var generate$1 = function (list) {
  1587. var access = {};
  1588. var cells = [];
  1589. var tableOpt = head(list).map(function (rowData) {
  1590. return rowData.element;
  1591. }).bind(table);
  1592. var lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
  1593. var maxRows = 0;
  1594. var maxColumns = 0;
  1595. var rowCount = 0;
  1596. var _a = partition(list, function (rowData) {
  1597. return rowData.section === 'colgroup';
  1598. }), colgroupRows = _a.pass, rows = _a.fail;
  1599. each$2(rows, function (rowData) {
  1600. var currentRow = [];
  1601. each$2(rowData.cells, function (rowCell) {
  1602. var start = 0;
  1603. while (access[key(rowCount, start)] !== undefined) {
  1604. start++;
  1605. }
  1606. var isLocked = hasNonNullableKey(lockedColumns, start.toString());
  1607. var current = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start, isLocked);
  1608. for (var occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
  1609. for (var occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
  1610. var rowPosition = rowCount + occupiedRowPosition;
  1611. var columnPosition = start + occupiedColumnPosition;
  1612. var newpos = key(rowPosition, columnPosition);
  1613. access[newpos] = current;
  1614. maxColumns = Math.max(maxColumns, columnPosition + 1);
  1615. }
  1616. }
  1617. currentRow.push(current);
  1618. });
  1619. maxRows++;
  1620. cells.push(rowdetail(rowData.element, currentRow, rowData.section));
  1621. rowCount++;
  1622. });
  1623. var _b = last$2(colgroupRows).map(function (rowData) {
  1624. var columns = generateColumns(rowData);
  1625. var colgroup$1 = colgroup(rowData.element, values(columns));
  1626. return {
  1627. colgroups: [colgroup$1],
  1628. columns: columns
  1629. };
  1630. }).getOrThunk(function () {
  1631. return {
  1632. colgroups: [],
  1633. columns: {}
  1634. };
  1635. }), columns = _b.columns, colgroups = _b.colgroups;
  1636. var grid$1 = grid(maxRows, maxColumns);
  1637. return {
  1638. grid: grid$1,
  1639. access: access,
  1640. all: cells,
  1641. columns: columns,
  1642. colgroups: colgroups
  1643. };
  1644. };
  1645. var fromTable = function (table) {
  1646. var list = fromTable$1(table);
  1647. return generate$1(list);
  1648. };
  1649. var justCells = function (warehouse) {
  1650. return bind$2(warehouse.all, function (w) {
  1651. return w.cells;
  1652. });
  1653. };
  1654. var justColumns = function (warehouse) {
  1655. return values(warehouse.columns);
  1656. };
  1657. var hasColumns = function (warehouse) {
  1658. return keys(warehouse.columns).length > 0;
  1659. };
  1660. var getColumnAt = function (warehouse, columnIndex) {
  1661. return Optional.from(warehouse.columns[columnIndex]);
  1662. };
  1663. var Warehouse = {
  1664. fromTable: fromTable,
  1665. generate: generate$1,
  1666. getAt: getAt,
  1667. findItem: findItem,
  1668. filterItems: filterItems,
  1669. justCells: justCells,
  1670. justColumns: justColumns,
  1671. hasColumns: hasColumns,
  1672. getColumnAt: getColumnAt
  1673. };
  1674. var inSelection = function (bounds, detail) {
  1675. var leftEdge = detail.column;
  1676. var rightEdge = detail.column + detail.colspan - 1;
  1677. var topEdge = detail.row;
  1678. var bottomEdge = detail.row + detail.rowspan - 1;
  1679. return leftEdge <= bounds.finishCol && rightEdge >= bounds.startCol && (topEdge <= bounds.finishRow && bottomEdge >= bounds.startRow);
  1680. };
  1681. var isWithin = function (bounds, detail) {
  1682. return detail.column >= bounds.startCol && detail.column + detail.colspan - 1 <= bounds.finishCol && detail.row >= bounds.startRow && detail.row + detail.rowspan - 1 <= bounds.finishRow;
  1683. };
  1684. var isRectangular = function (warehouse, bounds) {
  1685. var isRect = true;
  1686. var detailIsWithin = curry(isWithin, bounds);
  1687. for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
  1688. for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
  1689. isRect = isRect && Warehouse.getAt(warehouse, i, j).exists(detailIsWithin);
  1690. }
  1691. }
  1692. return isRect ? Optional.some(bounds) : Optional.none();
  1693. };
  1694. var getBounds = function (detailA, detailB) {
  1695. 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));
  1696. };
  1697. var getAnyBox = function (warehouse, startCell, finishCell) {
  1698. var startCoords = Warehouse.findItem(warehouse, startCell, eq$1);
  1699. var finishCoords = Warehouse.findItem(warehouse, finishCell, eq$1);
  1700. return startCoords.bind(function (sc) {
  1701. return finishCoords.map(function (fc) {
  1702. return getBounds(sc, fc);
  1703. });
  1704. });
  1705. };
  1706. var getBox$1 = function (warehouse, startCell, finishCell) {
  1707. return getAnyBox(warehouse, startCell, finishCell).bind(function (bounds) {
  1708. return isRectangular(warehouse, bounds);
  1709. });
  1710. };
  1711. var moveBy$1 = function (warehouse, cell, row, column) {
  1712. return Warehouse.findItem(warehouse, cell, eq$1).bind(function (detail) {
  1713. var startRow = row > 0 ? detail.row + detail.rowspan - 1 : detail.row;
  1714. var startCol = column > 0 ? detail.column + detail.colspan - 1 : detail.column;
  1715. var dest = Warehouse.getAt(warehouse, startRow + row, startCol + column);
  1716. return dest.map(function (d) {
  1717. return d.element;
  1718. });
  1719. });
  1720. };
  1721. var intercepts$1 = function (warehouse, start, finish) {
  1722. return getAnyBox(warehouse, start, finish).map(function (bounds) {
  1723. var inside = Warehouse.filterItems(warehouse, curry(inSelection, bounds));
  1724. return map$1(inside, function (detail) {
  1725. return detail.element;
  1726. });
  1727. });
  1728. };
  1729. var parentCell = function (warehouse, innerCell) {
  1730. var isContainedBy = function (c1, c2) {
  1731. return contains(c2, c1);
  1732. };
  1733. return Warehouse.findItem(warehouse, innerCell, isContainedBy).map(function (detail) {
  1734. return detail.element;
  1735. });
  1736. };
  1737. var moveBy = function (cell, deltaRow, deltaColumn) {
  1738. return table(cell).bind(function (table) {
  1739. var warehouse = getWarehouse(table);
  1740. return moveBy$1(warehouse, cell, deltaRow, deltaColumn);
  1741. });
  1742. };
  1743. var intercepts = function (table, first, last) {
  1744. var warehouse = getWarehouse(table);
  1745. return intercepts$1(warehouse, first, last);
  1746. };
  1747. var nestedIntercepts = function (table, first, firstTable, last, lastTable) {
  1748. var warehouse = getWarehouse(table);
  1749. var optStartCell = eq$1(table, firstTable) ? Optional.some(first) : parentCell(warehouse, first);
  1750. var optLastCell = eq$1(table, lastTable) ? Optional.some(last) : parentCell(warehouse, last);
  1751. return optStartCell.bind(function (startCell) {
  1752. return optLastCell.bind(function (lastCell) {
  1753. return intercepts$1(warehouse, startCell, lastCell);
  1754. });
  1755. });
  1756. };
  1757. var getBox = function (table, first, last) {
  1758. var warehouse = getWarehouse(table);
  1759. return getBox$1(warehouse, first, last);
  1760. };
  1761. var getWarehouse = Warehouse.fromTable;
  1762. var before$4 = function (marker, element) {
  1763. var parent$1 = parent(marker);
  1764. parent$1.each(function (v) {
  1765. v.dom.insertBefore(element.dom, marker.dom);
  1766. });
  1767. };
  1768. var after$5 = function (marker, element) {
  1769. var sibling = nextSibling(marker);
  1770. sibling.fold(function () {
  1771. var parent$1 = parent(marker);
  1772. parent$1.each(function (v) {
  1773. append$1(v, element);
  1774. });
  1775. }, function (v) {
  1776. before$4(v, element);
  1777. });
  1778. };
  1779. var prepend = function (parent, element) {
  1780. var firstChild$1 = firstChild(parent);
  1781. firstChild$1.fold(function () {
  1782. append$1(parent, element);
  1783. }, function (v) {
  1784. parent.dom.insertBefore(element.dom, v.dom);
  1785. });
  1786. };
  1787. var append$1 = function (parent, element) {
  1788. parent.dom.appendChild(element.dom);
  1789. };
  1790. var appendAt = function (parent, element, index) {
  1791. child$3(parent, index).fold(function () {
  1792. append$1(parent, element);
  1793. }, function (v) {
  1794. before$4(v, element);
  1795. });
  1796. };
  1797. var wrap = function (element, wrapper) {
  1798. before$4(element, wrapper);
  1799. append$1(wrapper, element);
  1800. };
  1801. var before$3 = function (marker, elements) {
  1802. each$2(elements, function (x) {
  1803. before$4(marker, x);
  1804. });
  1805. };
  1806. var after$4 = function (marker, elements) {
  1807. each$2(elements, function (x, i) {
  1808. var e = i === 0 ? marker : elements[i - 1];
  1809. after$5(e, x);
  1810. });
  1811. };
  1812. var append = function (parent, elements) {
  1813. each$2(elements, function (x) {
  1814. append$1(parent, x);
  1815. });
  1816. };
  1817. var empty = function (element) {
  1818. element.dom.textContent = '';
  1819. each$2(children$3(element), function (rogue) {
  1820. remove$5(rogue);
  1821. });
  1822. };
  1823. var remove$5 = function (element) {
  1824. var dom = element.dom;
  1825. if (dom.parentNode !== null) {
  1826. dom.parentNode.removeChild(dom);
  1827. }
  1828. };
  1829. var unwrap = function (wrapper) {
  1830. var children = children$3(wrapper);
  1831. if (children.length > 0) {
  1832. before$3(wrapper, children);
  1833. }
  1834. remove$5(wrapper);
  1835. };
  1836. var NodeValue = function (is, name) {
  1837. var get = function (element) {
  1838. if (!is(element)) {
  1839. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  1840. }
  1841. return getOption(element).getOr('');
  1842. };
  1843. var getOption = function (element) {
  1844. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  1845. };
  1846. var set = function (element, value) {
  1847. if (!is(element)) {
  1848. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  1849. }
  1850. element.dom.nodeValue = value;
  1851. };
  1852. return {
  1853. get: get,
  1854. getOption: getOption,
  1855. set: set
  1856. };
  1857. };
  1858. var api$2 = NodeValue(isText, 'text');
  1859. var get$9 = function (element) {
  1860. return api$2.get(element);
  1861. };
  1862. var getOption = function (element) {
  1863. return api$2.getOption(element);
  1864. };
  1865. var set = function (element, value) {
  1866. return api$2.set(element, value);
  1867. };
  1868. var TagBoundaries = [
  1869. 'body',
  1870. 'p',
  1871. 'div',
  1872. 'article',
  1873. 'aside',
  1874. 'figcaption',
  1875. 'figure',
  1876. 'footer',
  1877. 'header',
  1878. 'nav',
  1879. 'section',
  1880. 'ol',
  1881. 'ul',
  1882. 'li',
  1883. 'table',
  1884. 'thead',
  1885. 'tbody',
  1886. 'tfoot',
  1887. 'caption',
  1888. 'tr',
  1889. 'td',
  1890. 'th',
  1891. 'h1',
  1892. 'h2',
  1893. 'h3',
  1894. 'h4',
  1895. 'h5',
  1896. 'h6',
  1897. 'blockquote',
  1898. 'pre',
  1899. 'address'
  1900. ];
  1901. function DomUniverse () {
  1902. var clone = function (element) {
  1903. return SugarElement.fromDom(element.dom.cloneNode(false));
  1904. };
  1905. var document = function (element) {
  1906. return documentOrOwner(element).dom;
  1907. };
  1908. var isBoundary = function (element) {
  1909. if (!isElement(element)) {
  1910. return false;
  1911. }
  1912. if (name(element) === 'body') {
  1913. return true;
  1914. }
  1915. return contains$2(TagBoundaries, name(element));
  1916. };
  1917. var isEmptyTag = function (element) {
  1918. if (!isElement(element)) {
  1919. return false;
  1920. }
  1921. return contains$2([
  1922. 'br',
  1923. 'img',
  1924. 'hr',
  1925. 'input'
  1926. ], name(element));
  1927. };
  1928. var isNonEditable = function (element) {
  1929. return isElement(element) && get$b(element, 'contenteditable') === 'false';
  1930. };
  1931. var comparePosition = function (element, other) {
  1932. return element.dom.compareDocumentPosition(other.dom);
  1933. };
  1934. var copyAttributesTo = function (source, destination) {
  1935. var as = clone$2(source);
  1936. setAll$1(destination, as);
  1937. };
  1938. var isSpecial = function (element) {
  1939. var tag = name(element);
  1940. return contains$2([
  1941. 'script',
  1942. 'noscript',
  1943. 'iframe',
  1944. 'noframes',
  1945. 'noembed',
  1946. 'title',
  1947. 'style',
  1948. 'textarea',
  1949. 'xmp'
  1950. ], tag);
  1951. };
  1952. var getLanguage = function (element) {
  1953. return isElement(element) ? getOpt(element, 'lang') : Optional.none();
  1954. };
  1955. return {
  1956. up: constant({
  1957. selector: ancestor$1,
  1958. closest: closest$1,
  1959. predicate: ancestor$2,
  1960. all: parents
  1961. }),
  1962. down: constant({
  1963. selector: descendants,
  1964. predicate: descendants$1
  1965. }),
  1966. styles: constant({
  1967. get: get$a,
  1968. getRaw: getRaw$2,
  1969. set: set$1,
  1970. remove: remove$6
  1971. }),
  1972. attrs: constant({
  1973. get: get$b,
  1974. set: set$2,
  1975. remove: remove$7,
  1976. copyTo: copyAttributesTo
  1977. }),
  1978. insert: constant({
  1979. before: before$4,
  1980. after: after$5,
  1981. afterAll: after$4,
  1982. append: append$1,
  1983. appendAll: append,
  1984. prepend: prepend,
  1985. wrap: wrap
  1986. }),
  1987. remove: constant({
  1988. unwrap: unwrap,
  1989. remove: remove$5
  1990. }),
  1991. create: constant({
  1992. nu: SugarElement.fromTag,
  1993. clone: clone,
  1994. text: SugarElement.fromText
  1995. }),
  1996. query: constant({
  1997. comparePosition: comparePosition,
  1998. prevSibling: prevSibling,
  1999. nextSibling: nextSibling
  2000. }),
  2001. property: constant({
  2002. children: children$3,
  2003. name: name,
  2004. parent: parent,
  2005. document: document,
  2006. isText: isText,
  2007. isComment: isComment,
  2008. isElement: isElement,
  2009. isSpecial: isSpecial,
  2010. getLanguage: getLanguage,
  2011. getText: get$9,
  2012. setText: set,
  2013. isBoundary: isBoundary,
  2014. isEmptyTag: isEmptyTag,
  2015. isNonEditable: isNonEditable
  2016. }),
  2017. eq: eq$1,
  2018. is: is$1
  2019. };
  2020. }
  2021. var all = function (universe, look, elements, f) {
  2022. var head = elements[0];
  2023. var tail = elements.slice(1);
  2024. return f(universe, look, head, tail);
  2025. };
  2026. var oneAll = function (universe, look, elements) {
  2027. return elements.length > 0 ? all(universe, look, elements, unsafeOne) : Optional.none();
  2028. };
  2029. var unsafeOne = function (universe, look, head, tail) {
  2030. var start = look(universe, head);
  2031. return foldr(tail, function (b, a) {
  2032. var current = look(universe, a);
  2033. return commonElement(universe, b, current);
  2034. }, start);
  2035. };
  2036. var commonElement = function (universe, start, end) {
  2037. return start.bind(function (s) {
  2038. return end.filter(curry(universe.eq, s));
  2039. });
  2040. };
  2041. var eq = function (universe, item) {
  2042. return curry(universe.eq, item);
  2043. };
  2044. var ancestors$2 = function (universe, start, end, isRoot) {
  2045. if (isRoot === void 0) {
  2046. isRoot = never;
  2047. }
  2048. var ps1 = [start].concat(universe.up().all(start));
  2049. var ps2 = [end].concat(universe.up().all(end));
  2050. var prune = function (path) {
  2051. var index = findIndex(path, isRoot);
  2052. return index.fold(function () {
  2053. return path;
  2054. }, function (ind) {
  2055. return path.slice(0, ind + 1);
  2056. });
  2057. };
  2058. var pruned1 = prune(ps1);
  2059. var pruned2 = prune(ps2);
  2060. var shared = find$1(pruned1, function (x) {
  2061. return exists(pruned2, eq(universe, x));
  2062. });
  2063. return {
  2064. firstpath: pruned1,
  2065. secondpath: pruned2,
  2066. shared: shared
  2067. };
  2068. };
  2069. var sharedOne$1 = oneAll;
  2070. var ancestors$1 = ancestors$2;
  2071. var universe$3 = DomUniverse();
  2072. var sharedOne = function (look, elements) {
  2073. return sharedOne$1(universe$3, function (_universe, element) {
  2074. return look(element);
  2075. }, elements);
  2076. };
  2077. var ancestors = function (start, finish, isRoot) {
  2078. return ancestors$1(universe$3, start, finish, isRoot);
  2079. };
  2080. var lookupTable = function (container) {
  2081. return ancestor$1(container, 'table');
  2082. };
  2083. var identify = function (start, finish, isRoot) {
  2084. var getIsRoot = function (rootTable) {
  2085. return function (element) {
  2086. return isRoot !== undefined && isRoot(element) || eq$1(element, rootTable);
  2087. };
  2088. };
  2089. if (eq$1(start, finish)) {
  2090. return Optional.some({
  2091. boxes: Optional.some([start]),
  2092. start: start,
  2093. finish: finish
  2094. });
  2095. } else {
  2096. return lookupTable(start).bind(function (startTable) {
  2097. return lookupTable(finish).bind(function (finishTable) {
  2098. if (eq$1(startTable, finishTable)) {
  2099. return Optional.some({
  2100. boxes: intercepts(startTable, start, finish),
  2101. start: start,
  2102. finish: finish
  2103. });
  2104. } else if (contains(startTable, finishTable)) {
  2105. var ancestorCells = ancestors$3(finish, 'td,th', getIsRoot(startTable));
  2106. var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
  2107. return Optional.some({
  2108. boxes: nestedIntercepts(startTable, start, startTable, finish, finishTable),
  2109. start: start,
  2110. finish: finishCell
  2111. });
  2112. } else if (contains(finishTable, startTable)) {
  2113. var ancestorCells = ancestors$3(start, 'td,th', getIsRoot(finishTable));
  2114. var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start;
  2115. return Optional.some({
  2116. boxes: nestedIntercepts(finishTable, start, startTable, finish, finishTable),
  2117. start: start,
  2118. finish: startCell
  2119. });
  2120. } else {
  2121. return ancestors(start, finish).shared.bind(function (lca) {
  2122. return closest$1(lca, 'table', isRoot).bind(function (lcaTable) {
  2123. var finishAncestorCells = ancestors$3(finish, 'td,th', getIsRoot(lcaTable));
  2124. var finishCell = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
  2125. var startAncestorCells = ancestors$3(start, 'td,th', getIsRoot(lcaTable));
  2126. var startCell = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start;
  2127. return Optional.some({
  2128. boxes: nestedIntercepts(lcaTable, start, startTable, finish, finishTable),
  2129. start: startCell,
  2130. finish: finishCell
  2131. });
  2132. });
  2133. });
  2134. }
  2135. });
  2136. });
  2137. }
  2138. };
  2139. var retrieve$1 = function (container, selector) {
  2140. var sels = descendants(container, selector);
  2141. return sels.length > 0 ? Optional.some(sels) : Optional.none();
  2142. };
  2143. var getLast = function (boxes, lastSelectedSelector) {
  2144. return find$1(boxes, function (box) {
  2145. return is$2(box, lastSelectedSelector);
  2146. });
  2147. };
  2148. var getEdges = function (container, firstSelectedSelector, lastSelectedSelector) {
  2149. return descendant(container, firstSelectedSelector).bind(function (first) {
  2150. return descendant(container, lastSelectedSelector).bind(function (last) {
  2151. return sharedOne(lookupTable, [
  2152. first,
  2153. last
  2154. ]).map(function (table) {
  2155. return {
  2156. first: first,
  2157. last: last,
  2158. table: table
  2159. };
  2160. });
  2161. });
  2162. });
  2163. };
  2164. var expandTo = function (finish, firstSelectedSelector) {
  2165. return ancestor$1(finish, 'table').bind(function (table) {
  2166. return descendant(table, firstSelectedSelector).bind(function (start) {
  2167. return identify(start, finish).bind(function (identified) {
  2168. return identified.boxes.map(function (boxes) {
  2169. return {
  2170. boxes: boxes,
  2171. start: identified.start,
  2172. finish: identified.finish
  2173. };
  2174. });
  2175. });
  2176. });
  2177. });
  2178. };
  2179. var shiftSelection = function (boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
  2180. return getLast(boxes, lastSelectedSelector).bind(function (last) {
  2181. return moveBy(last, deltaRow, deltaColumn).bind(function (finish) {
  2182. return expandTo(finish, firstSelectedSelector);
  2183. });
  2184. });
  2185. };
  2186. var retrieve = function (container, selector) {
  2187. return retrieve$1(container, selector);
  2188. };
  2189. var retrieveBox = function (container, firstSelectedSelector, lastSelectedSelector) {
  2190. return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function (edges) {
  2191. var isRoot = function (ancestor) {
  2192. return eq$1(container, ancestor);
  2193. };
  2194. var sectionSelector = 'thead,tfoot,tbody,table';
  2195. var firstAncestor = ancestor$1(edges.first, sectionSelector, isRoot);
  2196. var lastAncestor = ancestor$1(edges.last, sectionSelector, isRoot);
  2197. return firstAncestor.bind(function (fA) {
  2198. return lastAncestor.bind(function (lA) {
  2199. return eq$1(fA, lA) ? getBox(edges.table, edges.first, edges.last) : Optional.none();
  2200. });
  2201. });
  2202. });
  2203. };
  2204. var generate = function (cases) {
  2205. if (!isArray(cases)) {
  2206. throw new Error('cases must be an array');
  2207. }
  2208. if (cases.length === 0) {
  2209. throw new Error('there must be at least one case');
  2210. }
  2211. var constructors = [];
  2212. var adt = {};
  2213. each$2(cases, function (acase, count) {
  2214. var keys$1 = keys(acase);
  2215. if (keys$1.length !== 1) {
  2216. throw new Error('one and only one name per case');
  2217. }
  2218. var key = keys$1[0];
  2219. var value = acase[key];
  2220. if (adt[key] !== undefined) {
  2221. throw new Error('duplicate key detected:' + key);
  2222. } else if (key === 'cata') {
  2223. throw new Error('cannot have a case named cata (sorry)');
  2224. } else if (!isArray(value)) {
  2225. throw new Error('case arguments must be an array');
  2226. }
  2227. constructors.push(key);
  2228. adt[key] = function () {
  2229. var args = [];
  2230. for (var _i = 0; _i < arguments.length; _i++) {
  2231. args[_i] = arguments[_i];
  2232. }
  2233. var argLength = args.length;
  2234. if (argLength !== value.length) {
  2235. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2236. }
  2237. var match = function (branches) {
  2238. var branchKeys = keys(branches);
  2239. if (constructors.length !== branchKeys.length) {
  2240. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2241. }
  2242. var allReqd = forall(constructors, function (reqKey) {
  2243. return contains$2(branchKeys, reqKey);
  2244. });
  2245. if (!allReqd) {
  2246. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2247. }
  2248. return branches[key].apply(null, args);
  2249. };
  2250. return {
  2251. fold: function () {
  2252. var foldArgs = [];
  2253. for (var _i = 0; _i < arguments.length; _i++) {
  2254. foldArgs[_i] = arguments[_i];
  2255. }
  2256. if (foldArgs.length !== cases.length) {
  2257. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2258. }
  2259. var target = foldArgs[count];
  2260. return target.apply(null, args);
  2261. },
  2262. match: match,
  2263. log: function (label) {
  2264. console.log(label, {
  2265. constructors: constructors,
  2266. constructor: key,
  2267. params: args
  2268. });
  2269. }
  2270. };
  2271. };
  2272. });
  2273. return adt;
  2274. };
  2275. var Adt = { generate: generate };
  2276. var type = Adt.generate([
  2277. { none: [] },
  2278. { multiple: ['elements'] },
  2279. { single: ['element'] }
  2280. ]);
  2281. var cata$2 = function (subject, onNone, onMultiple, onSingle) {
  2282. return subject.fold(onNone, onMultiple, onSingle);
  2283. };
  2284. var none$1 = type.none;
  2285. var multiple = type.multiple;
  2286. var single = type.single;
  2287. var Selections = function (lazyRoot, getStart, selectedSelector) {
  2288. var get = function () {
  2289. return retrieve(lazyRoot(), selectedSelector).fold(function () {
  2290. return getStart().fold(none$1, single);
  2291. }, function (cells) {
  2292. return multiple(cells);
  2293. });
  2294. };
  2295. return { get: get };
  2296. };
  2297. var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  2298. var clone = function (original, isDeep) {
  2299. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2300. };
  2301. var shallow = function (original) {
  2302. return clone(original, false);
  2303. };
  2304. var deep = function (original) {
  2305. return clone(original, true);
  2306. };
  2307. var shallowAs = function (original, tag) {
  2308. var nu = SugarElement.fromTag(tag);
  2309. var attributes = clone$2(original);
  2310. setAll$1(nu, attributes);
  2311. return nu;
  2312. };
  2313. var copy$1 = function (original, tag) {
  2314. var nu = shallowAs(original, tag);
  2315. var cloneChildren = children$3(deep(original));
  2316. append(nu, cloneChildren);
  2317. return nu;
  2318. };
  2319. var mutate$1 = function (original, tag) {
  2320. var nu = shallowAs(original, tag);
  2321. before$4(original, nu);
  2322. var children = children$3(original);
  2323. append(nu, children);
  2324. remove$5(original);
  2325. return nu;
  2326. };
  2327. var Dimension = function (name, getOffset) {
  2328. var set = function (element, h) {
  2329. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  2330. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  2331. }
  2332. var dom = element.dom;
  2333. if (isSupported(dom)) {
  2334. dom.style[name] = h + 'px';
  2335. }
  2336. };
  2337. var get = function (element) {
  2338. var r = getOffset(element);
  2339. if (r <= 0 || r === null) {
  2340. var css = get$a(element, name);
  2341. return parseFloat(css) || 0;
  2342. }
  2343. return r;
  2344. };
  2345. var getOuter = get;
  2346. var aggregate = function (element, properties) {
  2347. return foldl(properties, function (acc, property) {
  2348. var val = get$a(element, property);
  2349. var value = val === undefined ? 0 : parseInt(val, 10);
  2350. return isNaN(value) ? acc : acc + value;
  2351. }, 0);
  2352. };
  2353. var max = function (element, value, properties) {
  2354. var cumulativeInclusions = aggregate(element, properties);
  2355. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  2356. return absoluteMax;
  2357. };
  2358. return {
  2359. set: set,
  2360. get: get,
  2361. getOuter: getOuter,
  2362. aggregate: aggregate,
  2363. max: max
  2364. };
  2365. };
  2366. var needManualCalc = function () {
  2367. var browser = detect$3().browser;
  2368. return browser.isIE() || browser.isEdge();
  2369. };
  2370. var toNumber = function (px, fallback) {
  2371. return toFloat(px).getOr(fallback);
  2372. };
  2373. var getProp = function (element, name, fallback) {
  2374. return toNumber(get$a(element, name), fallback);
  2375. };
  2376. var getBoxSizing = function (element) {
  2377. return get$a(element, 'box-sizing');
  2378. };
  2379. var calcContentBoxSize = function (element, size, upper, lower) {
  2380. var paddingUpper = getProp(element, 'padding-' + upper, 0);
  2381. var paddingLower = getProp(element, 'padding-' + lower, 0);
  2382. var borderUpper = getProp(element, 'border-' + upper + '-width', 0);
  2383. var borderLower = getProp(element, 'border-' + lower + '-width', 0);
  2384. return size - paddingUpper - paddingLower - borderUpper - borderLower;
  2385. };
  2386. var getCalculatedHeight = function (element, boxSizing) {
  2387. var dom = element.dom;
  2388. var height = dom.getBoundingClientRect().height || dom.offsetHeight;
  2389. return boxSizing === 'border-box' ? height : calcContentBoxSize(element, height, 'top', 'bottom');
  2390. };
  2391. var getCalculatedWidth = function (element, boxSizing) {
  2392. var dom = element.dom;
  2393. var width = dom.getBoundingClientRect().width || dom.offsetWidth;
  2394. return boxSizing === 'border-box' ? width : calcContentBoxSize(element, width, 'left', 'right');
  2395. };
  2396. var getHeight$1 = function (element) {
  2397. return needManualCalc() ? getCalculatedHeight(element, getBoxSizing(element)) : getProp(element, 'height', element.dom.offsetHeight);
  2398. };
  2399. var getWidth = function (element) {
  2400. return needManualCalc() ? getCalculatedWidth(element, getBoxSizing(element)) : getProp(element, 'width', element.dom.offsetWidth);
  2401. };
  2402. var getInnerWidth = function (element) {
  2403. return getCalculatedWidth(element, 'content-box');
  2404. };
  2405. var api$1 = Dimension('width', function (element) {
  2406. return element.dom.offsetWidth;
  2407. });
  2408. var get$8 = function (element) {
  2409. return api$1.get(element);
  2410. };
  2411. var getOuter$2 = function (element) {
  2412. return api$1.getOuter(element);
  2413. };
  2414. var getInner = getInnerWidth;
  2415. var getRuntime$1 = getWidth;
  2416. var columns = function (warehouse, isValidCell) {
  2417. if (isValidCell === void 0) {
  2418. isValidCell = always;
  2419. }
  2420. var grid = warehouse.grid;
  2421. var cols = range$1(grid.columns, identity);
  2422. var rowsArr = range$1(grid.rows, identity);
  2423. return map$1(cols, function (col) {
  2424. var getBlock = function () {
  2425. return bind$2(rowsArr, function (r) {
  2426. return Warehouse.getAt(warehouse, r, col).filter(function (detail) {
  2427. return detail.column === col;
  2428. }).toArray();
  2429. });
  2430. };
  2431. var isValid = function (detail) {
  2432. return detail.colspan === 1 && isValidCell(detail.element);
  2433. };
  2434. var getFallback = function () {
  2435. return Warehouse.getAt(warehouse, 0, col);
  2436. };
  2437. return decide(getBlock, isValid, getFallback);
  2438. });
  2439. };
  2440. var decide = function (getBlock, isValid, getFallback) {
  2441. var inBlock = getBlock();
  2442. var validInBlock = find$1(inBlock, isValid);
  2443. var detailOption = validInBlock.orThunk(function () {
  2444. return Optional.from(inBlock[0]).orThunk(getFallback);
  2445. });
  2446. return detailOption.map(function (detail) {
  2447. return detail.element;
  2448. });
  2449. };
  2450. var rows = function (warehouse) {
  2451. var grid = warehouse.grid;
  2452. var rowsArr = range$1(grid.rows, identity);
  2453. var cols = range$1(grid.columns, identity);
  2454. return map$1(rowsArr, function (row) {
  2455. var getBlock = function () {
  2456. return bind$2(cols, function (c) {
  2457. return Warehouse.getAt(warehouse, row, c).filter(function (detail) {
  2458. return detail.row === row;
  2459. }).fold(constant([]), function (detail) {
  2460. return [detail];
  2461. });
  2462. });
  2463. };
  2464. var isSingle = function (detail) {
  2465. return detail.rowspan === 1;
  2466. };
  2467. var getFallback = function () {
  2468. return Warehouse.getAt(warehouse, row, 0);
  2469. };
  2470. return decide(getBlock, isSingle, getFallback);
  2471. });
  2472. };
  2473. var deduce = function (xs, index) {
  2474. if (index < 0 || index >= xs.length - 1) {
  2475. return Optional.none();
  2476. }
  2477. var current = xs[index].fold(function () {
  2478. var rest = reverse(xs.slice(0, index));
  2479. return findMap(rest, function (a, i) {
  2480. return a.map(function (aa) {
  2481. return {
  2482. value: aa,
  2483. delta: i + 1
  2484. };
  2485. });
  2486. });
  2487. }, function (c) {
  2488. return Optional.some({
  2489. value: c,
  2490. delta: 0
  2491. });
  2492. });
  2493. var next = xs[index + 1].fold(function () {
  2494. var rest = xs.slice(index + 1);
  2495. return findMap(rest, function (a, i) {
  2496. return a.map(function (aa) {
  2497. return {
  2498. value: aa,
  2499. delta: i + 1
  2500. };
  2501. });
  2502. });
  2503. }, function (n) {
  2504. return Optional.some({
  2505. value: n,
  2506. delta: 1
  2507. });
  2508. });
  2509. return current.bind(function (c) {
  2510. return next.map(function (n) {
  2511. var extras = n.delta + c.delta;
  2512. return Math.abs(n.value - c.value) / extras;
  2513. });
  2514. });
  2515. };
  2516. var onDirection = function (isLtr, isRtl) {
  2517. return function (element) {
  2518. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  2519. };
  2520. };
  2521. var getDirection = function (element) {
  2522. return get$a(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  2523. };
  2524. var api = Dimension('height', function (element) {
  2525. var dom = element.dom;
  2526. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  2527. });
  2528. var get$7 = function (element) {
  2529. return api.get(element);
  2530. };
  2531. var getOuter$1 = function (element) {
  2532. return api.getOuter(element);
  2533. };
  2534. var getRuntime = getHeight$1;
  2535. var r = function (left, top) {
  2536. var translate = function (x, y) {
  2537. return r(left + x, top + y);
  2538. };
  2539. return {
  2540. left: left,
  2541. top: top,
  2542. translate: translate
  2543. };
  2544. };
  2545. var SugarPosition = r;
  2546. var boxPosition = function (dom) {
  2547. var box = dom.getBoundingClientRect();
  2548. return SugarPosition(box.left, box.top);
  2549. };
  2550. var firstDefinedOrZero = function (a, b) {
  2551. if (a !== undefined) {
  2552. return a;
  2553. } else {
  2554. return b !== undefined ? b : 0;
  2555. }
  2556. };
  2557. var absolute = function (element) {
  2558. var doc = element.dom.ownerDocument;
  2559. var body = doc.body;
  2560. var win = doc.defaultView;
  2561. var html = doc.documentElement;
  2562. if (body === element.dom) {
  2563. return SugarPosition(body.offsetLeft, body.offsetTop);
  2564. }
  2565. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  2566. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  2567. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  2568. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  2569. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  2570. };
  2571. var viewport = function (element) {
  2572. var dom = element.dom;
  2573. var doc = dom.ownerDocument;
  2574. var body = doc.body;
  2575. if (body === dom) {
  2576. return SugarPosition(body.offsetLeft, body.offsetTop);
  2577. }
  2578. if (!inBody(element)) {
  2579. return SugarPosition(0, 0);
  2580. }
  2581. return boxPosition(dom);
  2582. };
  2583. var rowInfo = function (row, y) {
  2584. return {
  2585. row: row,
  2586. y: y
  2587. };
  2588. };
  2589. var colInfo = function (col, x) {
  2590. return {
  2591. col: col,
  2592. x: x
  2593. };
  2594. };
  2595. var rtlEdge = function (cell) {
  2596. var pos = absolute(cell);
  2597. return pos.left + getOuter$2(cell);
  2598. };
  2599. var ltrEdge = function (cell) {
  2600. return absolute(cell).left;
  2601. };
  2602. var getLeftEdge = function (index, cell) {
  2603. return colInfo(index, ltrEdge(cell));
  2604. };
  2605. var getRightEdge = function (index, cell) {
  2606. return colInfo(index, rtlEdge(cell));
  2607. };
  2608. var getTop$1 = function (cell) {
  2609. return absolute(cell).top;
  2610. };
  2611. var getTopEdge = function (index, cell) {
  2612. return rowInfo(index, getTop$1(cell));
  2613. };
  2614. var getBottomEdge = function (index, cell) {
  2615. return rowInfo(index, getTop$1(cell) + getOuter$1(cell));
  2616. };
  2617. var findPositions = function (getInnerEdge, getOuterEdge, array) {
  2618. if (array.length === 0) {
  2619. return [];
  2620. }
  2621. var lines = map$1(array.slice(1), function (cellOption, index) {
  2622. return cellOption.map(function (cell) {
  2623. return getInnerEdge(index, cell);
  2624. });
  2625. });
  2626. var lastLine = array[array.length - 1].map(function (cell) {
  2627. return getOuterEdge(array.length - 1, cell);
  2628. });
  2629. return lines.concat([lastLine]);
  2630. };
  2631. var negate = function (step) {
  2632. return -step;
  2633. };
  2634. var height = {
  2635. delta: identity,
  2636. positions: function (optElements) {
  2637. return findPositions(getTopEdge, getBottomEdge, optElements);
  2638. },
  2639. edge: getTop$1
  2640. };
  2641. var ltr$1 = {
  2642. delta: identity,
  2643. edge: ltrEdge,
  2644. positions: function (optElements) {
  2645. return findPositions(getLeftEdge, getRightEdge, optElements);
  2646. }
  2647. };
  2648. var rtl$1 = {
  2649. delta: negate,
  2650. edge: rtlEdge,
  2651. positions: function (optElements) {
  2652. return findPositions(getRightEdge, getLeftEdge, optElements);
  2653. }
  2654. };
  2655. var detect$2 = onDirection(ltr$1, rtl$1);
  2656. var width = {
  2657. delta: function (amount, table) {
  2658. return detect$2(table).delta(amount, table);
  2659. },
  2660. positions: function (cols, table) {
  2661. return detect$2(table).positions(cols, table);
  2662. },
  2663. edge: function (cell) {
  2664. return detect$2(cell).edge(cell);
  2665. }
  2666. };
  2667. var units = {
  2668. unsupportedLength: [
  2669. 'em',
  2670. 'ex',
  2671. 'cap',
  2672. 'ch',
  2673. 'ic',
  2674. 'rem',
  2675. 'lh',
  2676. 'rlh',
  2677. 'vw',
  2678. 'vh',
  2679. 'vi',
  2680. 'vb',
  2681. 'vmin',
  2682. 'vmax',
  2683. 'cm',
  2684. 'mm',
  2685. 'Q',
  2686. 'in',
  2687. 'pc',
  2688. 'pt',
  2689. 'px'
  2690. ],
  2691. fixed: [
  2692. 'px',
  2693. 'pt'
  2694. ],
  2695. relative: ['%'],
  2696. empty: ['']
  2697. };
  2698. var pattern = function () {
  2699. var decimalDigits = '[0-9]+';
  2700. var signedInteger = '[+-]?' + decimalDigits;
  2701. var exponentPart = '[eE]' + signedInteger;
  2702. var dot = '\\.';
  2703. var opt = function (input) {
  2704. return '(?:' + input + ')?';
  2705. };
  2706. var unsignedDecimalLiteral = [
  2707. 'Infinity',
  2708. decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  2709. dot + decimalDigits + opt(exponentPart),
  2710. decimalDigits + opt(exponentPart)
  2711. ].join('|');
  2712. var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
  2713. return new RegExp('^(' + float + ')(.*)$');
  2714. }();
  2715. var isUnit = function (unit, accepted) {
  2716. return exists(accepted, function (acc) {
  2717. return exists(units[acc], function (check) {
  2718. return unit === check;
  2719. });
  2720. });
  2721. };
  2722. var parse = function (input, accepted) {
  2723. var match = Optional.from(pattern.exec(input));
  2724. return match.bind(function (array) {
  2725. var value = Number(array[1]);
  2726. var unitRaw = array[2];
  2727. if (isUnit(unitRaw, accepted)) {
  2728. return Optional.some({
  2729. value: value,
  2730. unit: unitRaw
  2731. });
  2732. } else {
  2733. return Optional.none();
  2734. }
  2735. });
  2736. };
  2737. var rPercentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
  2738. var rPixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
  2739. var isCol$2 = isTag('col');
  2740. var getPercentSize = function (elm, outerGetter, innerGetter) {
  2741. var relativeParent = parentElement(elm).getOrThunk(function () {
  2742. return getBody$1(owner(elm));
  2743. });
  2744. return outerGetter(elm) / innerGetter(relativeParent) * 100;
  2745. };
  2746. var setPixelWidth = function (cell, amount) {
  2747. set$1(cell, 'width', amount + 'px');
  2748. };
  2749. var setPercentageWidth = function (cell, amount) {
  2750. set$1(cell, 'width', amount + '%');
  2751. };
  2752. var setHeight = function (cell, amount) {
  2753. set$1(cell, 'height', amount + 'px');
  2754. };
  2755. var getHeightValue = function (cell) {
  2756. return getRuntime(cell) + 'px';
  2757. };
  2758. var convert = function (cell, number, getter, setter) {
  2759. var newSize = table(cell).map(function (table) {
  2760. var total = getter(table);
  2761. return Math.floor(number / 100 * total);
  2762. }).getOr(number);
  2763. setter(cell, newSize);
  2764. return newSize;
  2765. };
  2766. var normalizePixelSize = function (value, cell, getter, setter) {
  2767. var number = parseFloat(value);
  2768. return endsWith(value, '%') && name(cell) !== 'table' ? convert(cell, number, getter, setter) : number;
  2769. };
  2770. var getTotalHeight = function (cell) {
  2771. var value = getHeightValue(cell);
  2772. if (!value) {
  2773. return get$7(cell);
  2774. }
  2775. return normalizePixelSize(value, cell, get$7, setHeight);
  2776. };
  2777. var get$6 = function (cell, type, f) {
  2778. var v = f(cell);
  2779. var span = getSpan(cell, type);
  2780. return v / span;
  2781. };
  2782. var getRaw$1 = function (element, prop) {
  2783. return getRaw$2(element, prop).orThunk(function () {
  2784. return getOpt(element, prop).map(function (val) {
  2785. return val + 'px';
  2786. });
  2787. });
  2788. };
  2789. var getRawWidth$1 = function (element) {
  2790. return getRaw$1(element, 'width');
  2791. };
  2792. var getRawHeight = function (element) {
  2793. return getRaw$1(element, 'height');
  2794. };
  2795. var getPercentageWidth = function (cell) {
  2796. return getPercentSize(cell, get$8, getInner);
  2797. };
  2798. var getPixelWidth$1 = function (cell) {
  2799. return isCol$2(cell) ? get$8(cell) : getRuntime$1(cell);
  2800. };
  2801. var getHeight = function (cell) {
  2802. return get$6(cell, 'rowspan', getTotalHeight);
  2803. };
  2804. var getGenericWidth = function (cell) {
  2805. var width = getRawWidth$1(cell);
  2806. return width.bind(function (w) {
  2807. return parse(w, [
  2808. 'fixed',
  2809. 'relative',
  2810. 'empty'
  2811. ]);
  2812. });
  2813. };
  2814. var setGenericWidth = function (cell, amount, unit) {
  2815. set$1(cell, 'width', amount + unit);
  2816. };
  2817. var getPixelTableWidth = function (table) {
  2818. return get$8(table) + 'px';
  2819. };
  2820. var getPercentTableWidth = function (table) {
  2821. return getPercentSize(table, get$8, getInner) + '%';
  2822. };
  2823. var isPercentSizing$1 = function (table) {
  2824. return getRawWidth$1(table).exists(function (size) {
  2825. return rPercentageBasedSizeRegex.test(size);
  2826. });
  2827. };
  2828. var isPixelSizing$1 = function (table) {
  2829. return getRawWidth$1(table).exists(function (size) {
  2830. return rPixelBasedSizeRegex.test(size);
  2831. });
  2832. };
  2833. var isNoneSizing$1 = function (table) {
  2834. return getRawWidth$1(table).isNone();
  2835. };
  2836. var percentageBasedSizeRegex = constant(rPercentageBasedSizeRegex);
  2837. var isCol$1 = isTag('col');
  2838. var getRawW = function (cell) {
  2839. return getRawWidth$1(cell).getOrThunk(function () {
  2840. return getPixelWidth$1(cell) + 'px';
  2841. });
  2842. };
  2843. var getRawH = function (cell) {
  2844. return getRawHeight(cell).getOrThunk(function () {
  2845. return getHeight(cell) + 'px';
  2846. });
  2847. };
  2848. var justCols = function (warehouse) {
  2849. return map$1(Warehouse.justColumns(warehouse), function (column) {
  2850. return Optional.from(column.element);
  2851. });
  2852. };
  2853. var isValidColumn = function (cell) {
  2854. var browser = detect$3().browser;
  2855. var supportsColWidths = browser.isChrome() || browser.isFirefox();
  2856. return isCol$1(cell) ? supportsColWidths : true;
  2857. };
  2858. var getDimension = function (cellOpt, index, backups, filter, getter, fallback) {
  2859. return cellOpt.filter(filter).fold(function () {
  2860. return fallback(deduce(backups, index));
  2861. }, function (cell) {
  2862. return getter(cell);
  2863. });
  2864. };
  2865. var getWidthFrom = function (warehouse, table, getWidth, fallback) {
  2866. var columnCells = columns(warehouse);
  2867. var columns$1 = Warehouse.hasColumns(warehouse) ? justCols(warehouse) : columnCells;
  2868. var backups = [Optional.some(width.edge(table))].concat(map$1(width.positions(columnCells, table), function (pos) {
  2869. return pos.map(function (p) {
  2870. return p.x;
  2871. });
  2872. }));
  2873. var colFilter = not(hasColspan);
  2874. return map$1(columns$1, function (cellOption, c) {
  2875. return getDimension(cellOption, c, backups, colFilter, function (column) {
  2876. if (isValidColumn(column)) {
  2877. return getWidth(column);
  2878. } else {
  2879. var cell = bindFrom(columnCells[c], identity);
  2880. return getDimension(cell, c, backups, colFilter, function (cell) {
  2881. return fallback(Optional.some(get$8(cell)));
  2882. }, fallback);
  2883. }
  2884. }, fallback);
  2885. });
  2886. };
  2887. var getDeduced = function (deduced) {
  2888. return deduced.map(function (d) {
  2889. return d + 'px';
  2890. }).getOr('');
  2891. };
  2892. var getRawWidths = function (warehouse, table) {
  2893. return getWidthFrom(warehouse, table, getRawW, getDeduced);
  2894. };
  2895. var getPercentageWidths = function (warehouse, table, tableSize) {
  2896. return getWidthFrom(warehouse, table, getPercentageWidth, function (deduced) {
  2897. return deduced.fold(function () {
  2898. return tableSize.minCellWidth();
  2899. }, function (cellWidth) {
  2900. return cellWidth / tableSize.pixelWidth() * 100;
  2901. });
  2902. });
  2903. };
  2904. var getPixelWidths = function (warehouse, table, tableSize) {
  2905. return getWidthFrom(warehouse, table, getPixelWidth$1, function (deduced) {
  2906. return deduced.getOrThunk(tableSize.minCellWidth);
  2907. });
  2908. };
  2909. var getHeightFrom = function (warehouse, table, direction, getHeight, fallback) {
  2910. var rows$1 = rows(warehouse);
  2911. var backups = [Optional.some(direction.edge(table))].concat(map$1(direction.positions(rows$1, table), function (pos) {
  2912. return pos.map(function (p) {
  2913. return p.y;
  2914. });
  2915. }));
  2916. return map$1(rows$1, function (cellOption, c) {
  2917. return getDimension(cellOption, c, backups, not(hasRowspan), getHeight, fallback);
  2918. });
  2919. };
  2920. var getPixelHeights = function (warehouse, table, direction) {
  2921. return getHeightFrom(warehouse, table, direction, getHeight, function (deduced) {
  2922. return deduced.getOrThunk(minHeight);
  2923. });
  2924. };
  2925. var getRawHeights = function (warehouse, table, direction) {
  2926. return getHeightFrom(warehouse, table, direction, getRawH, getDeduced);
  2927. };
  2928. var widthLookup = function (table, getter) {
  2929. return function () {
  2930. if (inBody(table)) {
  2931. return getter(table);
  2932. } else {
  2933. return parseFloat(getRaw$2(table, 'width').getOr('0'));
  2934. }
  2935. };
  2936. };
  2937. var noneSize = function (table) {
  2938. var getWidth = widthLookup(table, get$8);
  2939. var zero = constant(0);
  2940. var getWidths = function (warehouse, tableSize) {
  2941. return getPixelWidths(warehouse, table, tableSize);
  2942. };
  2943. return {
  2944. width: getWidth,
  2945. pixelWidth: getWidth,
  2946. getWidths: getWidths,
  2947. getCellDelta: zero,
  2948. singleColumnWidth: constant([0]),
  2949. minCellWidth: zero,
  2950. setElementWidth: noop,
  2951. adjustTableWidth: noop,
  2952. isRelative: true,
  2953. label: 'none'
  2954. };
  2955. };
  2956. var percentageSize = function (table) {
  2957. var getFloatWidth = widthLookup(table, function (elem) {
  2958. return parseFloat(getPercentTableWidth(elem));
  2959. });
  2960. var getWidth = widthLookup(table, get$8);
  2961. var getCellDelta = function (delta) {
  2962. return delta / getWidth() * 100;
  2963. };
  2964. var singleColumnWidth = function (w, _delta) {
  2965. return [100 - w];
  2966. };
  2967. var minCellWidth = function () {
  2968. return minWidth() / getWidth() * 100;
  2969. };
  2970. var adjustTableWidth = function (delta) {
  2971. var currentWidth = getFloatWidth();
  2972. var change = delta / 100 * currentWidth;
  2973. var newWidth = currentWidth + change;
  2974. setPercentageWidth(table, newWidth);
  2975. };
  2976. var getWidths = function (warehouse, tableSize) {
  2977. return getPercentageWidths(warehouse, table, tableSize);
  2978. };
  2979. return {
  2980. width: getFloatWidth,
  2981. pixelWidth: getWidth,
  2982. getWidths: getWidths,
  2983. getCellDelta: getCellDelta,
  2984. singleColumnWidth: singleColumnWidth,
  2985. minCellWidth: minCellWidth,
  2986. setElementWidth: setPercentageWidth,
  2987. adjustTableWidth: adjustTableWidth,
  2988. isRelative: true,
  2989. label: 'percent'
  2990. };
  2991. };
  2992. var pixelSize = function (table) {
  2993. var getWidth = widthLookup(table, get$8);
  2994. var getCellDelta = identity;
  2995. var singleColumnWidth = function (w, delta) {
  2996. var newNext = Math.max(minWidth(), w + delta);
  2997. return [newNext - w];
  2998. };
  2999. var adjustTableWidth = function (delta) {
  3000. var newWidth = getWidth() + delta;
  3001. setPixelWidth(table, newWidth);
  3002. };
  3003. var getWidths = function (warehouse, tableSize) {
  3004. return getPixelWidths(warehouse, table, tableSize);
  3005. };
  3006. return {
  3007. width: getWidth,
  3008. pixelWidth: getWidth,
  3009. getWidths: getWidths,
  3010. getCellDelta: getCellDelta,
  3011. singleColumnWidth: singleColumnWidth,
  3012. minCellWidth: minWidth,
  3013. setElementWidth: setPixelWidth,
  3014. adjustTableWidth: adjustTableWidth,
  3015. isRelative: false,
  3016. label: 'pixel'
  3017. };
  3018. };
  3019. var chooseSize = function (element, width) {
  3020. var percentMatch = percentageBasedSizeRegex().exec(width);
  3021. if (percentMatch !== null) {
  3022. return percentageSize(element);
  3023. } else {
  3024. return pixelSize(element);
  3025. }
  3026. };
  3027. var getTableSize = function (table) {
  3028. var width = getRawWidth$1(table);
  3029. return width.fold(function () {
  3030. return noneSize(table);
  3031. }, function (w) {
  3032. return chooseSize(table, w);
  3033. });
  3034. };
  3035. var TableSize = {
  3036. getTableSize: getTableSize,
  3037. pixelSize: pixelSize,
  3038. percentageSize: percentageSize,
  3039. noneSize: noneSize
  3040. };
  3041. var statsStruct = function (minRow, minCol, maxRow, maxCol, allCells, selectedCells) {
  3042. return {
  3043. minRow: minRow,
  3044. minCol: minCol,
  3045. maxRow: maxRow,
  3046. maxCol: maxCol,
  3047. allCells: allCells,
  3048. selectedCells: selectedCells
  3049. };
  3050. };
  3051. var findSelectedStats = function (house, isSelected) {
  3052. var totalColumns = house.grid.columns;
  3053. var totalRows = house.grid.rows;
  3054. var minRow = totalRows;
  3055. var minCol = totalColumns;
  3056. var maxRow = 0;
  3057. var maxCol = 0;
  3058. var allCells = [];
  3059. var selectedCells = [];
  3060. each$1(house.access, function (detail) {
  3061. allCells.push(detail);
  3062. if (isSelected(detail)) {
  3063. selectedCells.push(detail);
  3064. var startRow = detail.row;
  3065. var endRow = startRow + detail.rowspan - 1;
  3066. var startCol = detail.column;
  3067. var endCol = startCol + detail.colspan - 1;
  3068. if (startRow < minRow) {
  3069. minRow = startRow;
  3070. } else if (endRow > maxRow) {
  3071. maxRow = endRow;
  3072. }
  3073. if (startCol < minCol) {
  3074. minCol = startCol;
  3075. } else if (endCol > maxCol) {
  3076. maxCol = endCol;
  3077. }
  3078. }
  3079. });
  3080. return statsStruct(minRow, minCol, maxRow, maxCol, allCells, selectedCells);
  3081. };
  3082. var makeCell = function (list, seenSelected, rowIndex) {
  3083. var row = list[rowIndex].element;
  3084. var td = SugarElement.fromTag('td');
  3085. append$1(td, SugarElement.fromTag('br'));
  3086. var f = seenSelected ? append$1 : prepend;
  3087. f(row, td);
  3088. };
  3089. var fillInGaps = function (list, house, stats, isSelected) {
  3090. var totalColumns = house.grid.columns;
  3091. var totalRows = house.grid.rows;
  3092. for (var i = 0; i < totalRows; i++) {
  3093. var seenSelected = false;
  3094. for (var j = 0; j < totalColumns; j++) {
  3095. if (!(i < stats.minRow || i > stats.maxRow || j < stats.minCol || j > stats.maxCol)) {
  3096. var needCell = Warehouse.getAt(house, i, j).filter(isSelected).isNone();
  3097. if (needCell) {
  3098. makeCell(list, seenSelected, i);
  3099. } else {
  3100. seenSelected = true;
  3101. }
  3102. }
  3103. }
  3104. }
  3105. };
  3106. var clean = function (replica, stats, house, widthDelta) {
  3107. each$1(house.columns, function (col) {
  3108. if (col.column < stats.minCol || col.column > stats.maxCol) {
  3109. remove$5(col.element);
  3110. }
  3111. });
  3112. var emptyRows = filter$2(firstLayer(replica, 'tr'), function (row) {
  3113. return row.dom.childElementCount === 0;
  3114. });
  3115. each$2(emptyRows, remove$5);
  3116. if (stats.minCol === stats.maxCol || stats.minRow === stats.maxRow) {
  3117. each$2(firstLayer(replica, 'th,td'), function (cell) {
  3118. remove$7(cell, 'rowspan');
  3119. remove$7(cell, 'colspan');
  3120. });
  3121. }
  3122. remove$7(replica, LOCKED_COL_ATTR);
  3123. remove$7(replica, 'data-snooker-col-series');
  3124. var tableSize = TableSize.getTableSize(replica);
  3125. tableSize.adjustTableWidth(widthDelta);
  3126. };
  3127. var getTableWidthDelta = function (table, warehouse, tableSize, stats) {
  3128. if (stats.minCol === 0 && warehouse.grid.columns === stats.maxCol + 1) {
  3129. return 0;
  3130. }
  3131. var colWidths = getPixelWidths(warehouse, table, tableSize);
  3132. var allColsWidth = foldl(colWidths, function (acc, width) {
  3133. return acc + width;
  3134. }, 0);
  3135. var selectedColsWidth = foldl(colWidths.slice(stats.minCol, stats.maxCol + 1), function (acc, width) {
  3136. return acc + width;
  3137. }, 0);
  3138. var newWidth = selectedColsWidth / allColsWidth * tableSize.pixelWidth();
  3139. var delta = newWidth - tableSize.pixelWidth();
  3140. return tableSize.getCellDelta(delta);
  3141. };
  3142. var extract$1 = function (table, selectedSelector) {
  3143. var isSelected = function (detail) {
  3144. return is$2(detail.element, selectedSelector);
  3145. };
  3146. var replica = deep(table);
  3147. var list = fromTable$1(replica);
  3148. var tableSize = TableSize.getTableSize(table);
  3149. var replicaHouse = Warehouse.generate(list);
  3150. var replicaStats = findSelectedStats(replicaHouse, isSelected);
  3151. var selector = 'th:not(' + selectedSelector + ')' + ',td:not(' + selectedSelector + ')';
  3152. var unselectedCells = filterFirstLayer(replica, 'th,td', function (cell) {
  3153. return is$2(cell, selector);
  3154. });
  3155. each$2(unselectedCells, remove$5);
  3156. fillInGaps(list, replicaHouse, replicaStats, isSelected);
  3157. var house = Warehouse.fromTable(table);
  3158. var widthDelta = getTableWidthDelta(table, house, tableSize, replicaStats);
  3159. clean(replica, replicaStats, replicaHouse, widthDelta);
  3160. return replica;
  3161. };
  3162. var nbsp = '\xA0';
  3163. var getEnd = function (element) {
  3164. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  3165. return children$3(element).length;
  3166. }, function (v) {
  3167. return v.length;
  3168. });
  3169. };
  3170. var isTextNodeWithCursorPosition = function (el) {
  3171. return getOption(el).filter(function (text) {
  3172. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  3173. }).isSome();
  3174. };
  3175. var elementsWithCursorPosition = [
  3176. 'img',
  3177. 'br'
  3178. ];
  3179. var isCursorPosition = function (elem) {
  3180. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  3181. return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem));
  3182. };
  3183. var first = function (element) {
  3184. return descendant$1(element, isCursorPosition);
  3185. };
  3186. var last$1 = function (element) {
  3187. return descendantRtl(element, isCursorPosition);
  3188. };
  3189. var descendantRtl = function (scope, predicate) {
  3190. var descend = function (element) {
  3191. var children = children$3(element);
  3192. for (var i = children.length - 1; i >= 0; i--) {
  3193. var child = children[i];
  3194. if (predicate(child)) {
  3195. return Optional.some(child);
  3196. }
  3197. var res = descend(child);
  3198. if (res.isSome()) {
  3199. return res;
  3200. }
  3201. }
  3202. return Optional.none();
  3203. };
  3204. return descend(scope);
  3205. };
  3206. var transferableAttributes = {
  3207. scope: [
  3208. 'row',
  3209. 'col'
  3210. ]
  3211. };
  3212. var createCell = function (doc) {
  3213. return function () {
  3214. var td = SugarElement.fromTag('td', doc.dom);
  3215. append$1(td, SugarElement.fromTag('br', doc.dom));
  3216. return td;
  3217. };
  3218. };
  3219. var createCol = function (doc) {
  3220. return function () {
  3221. return SugarElement.fromTag('col', doc.dom);
  3222. };
  3223. };
  3224. var createColgroup = function (doc) {
  3225. return function () {
  3226. return SugarElement.fromTag('colgroup', doc.dom);
  3227. };
  3228. };
  3229. var createRow$1 = function (doc) {
  3230. return function () {
  3231. return SugarElement.fromTag('tr', doc.dom);
  3232. };
  3233. };
  3234. var replace$1 = function (cell, tag, attrs) {
  3235. var replica = copy$1(cell, tag);
  3236. each$1(attrs, function (v, k) {
  3237. if (v === null) {
  3238. remove$7(replica, k);
  3239. } else {
  3240. set$2(replica, k, v);
  3241. }
  3242. });
  3243. return replica;
  3244. };
  3245. var pasteReplace = function (cell) {
  3246. return cell;
  3247. };
  3248. var cloneFormats = function (oldCell, newCell, formats) {
  3249. var first$1 = first(oldCell);
  3250. return first$1.map(function (firstText) {
  3251. var formatSelector = formats.join(',');
  3252. var parents = ancestors$3(firstText, formatSelector, function (element) {
  3253. return eq$1(element, oldCell);
  3254. });
  3255. return foldr(parents, function (last, parent) {
  3256. var clonedFormat = shallow(parent);
  3257. remove$7(clonedFormat, 'contenteditable');
  3258. append$1(last, clonedFormat);
  3259. return clonedFormat;
  3260. }, newCell);
  3261. }).getOr(newCell);
  3262. };
  3263. var cloneAppropriateAttributes = function (original, clone) {
  3264. each$1(transferableAttributes, function (validAttributes, attributeName) {
  3265. return getOpt(original, attributeName).filter(function (attribute) {
  3266. return contains$2(validAttributes, attribute);
  3267. }).each(function (attribute) {
  3268. return set$2(clone, attributeName, attribute);
  3269. });
  3270. });
  3271. };
  3272. var cellOperations = function (mutate, doc, formatsToClone) {
  3273. var cloneCss = function (prev, clone) {
  3274. copy$2(prev.element, clone);
  3275. remove$6(clone, 'height');
  3276. if (prev.colspan !== 1) {
  3277. remove$6(clone, 'width');
  3278. }
  3279. };
  3280. var newCell = function (prev) {
  3281. var td = SugarElement.fromTag(name(prev.element), doc.dom);
  3282. var formats = formatsToClone.getOr([
  3283. 'strong',
  3284. 'em',
  3285. 'b',
  3286. 'i',
  3287. 'span',
  3288. 'font',
  3289. 'h1',
  3290. 'h2',
  3291. 'h3',
  3292. 'h4',
  3293. 'h5',
  3294. 'h6',
  3295. 'p',
  3296. 'div'
  3297. ]);
  3298. var lastNode = formats.length > 0 ? cloneFormats(prev.element, td, formats) : td;
  3299. append$1(lastNode, SugarElement.fromTag('br'));
  3300. cloneCss(prev, td);
  3301. cloneAppropriateAttributes(prev.element, td);
  3302. mutate(prev.element, td);
  3303. return td;
  3304. };
  3305. var newCol = function (prev) {
  3306. var col = SugarElement.fromTag(name(prev.element), doc.dom);
  3307. cloneCss(prev, col);
  3308. mutate(prev.element, col);
  3309. return col;
  3310. };
  3311. return {
  3312. col: newCol,
  3313. colgroup: createColgroup(doc),
  3314. row: createRow$1(doc),
  3315. cell: newCell,
  3316. replace: replace$1,
  3317. colGap: createCol(doc),
  3318. gap: createCell(doc)
  3319. };
  3320. };
  3321. var paste$1 = function (doc) {
  3322. return {
  3323. col: createCol(doc),
  3324. colgroup: createColgroup(doc),
  3325. row: createRow$1(doc),
  3326. cell: createCell(doc),
  3327. replace: pasteReplace,
  3328. colGap: createCol(doc),
  3329. gap: createCell(doc)
  3330. };
  3331. };
  3332. var fromHtml = function (html, scope) {
  3333. var doc = scope || document;
  3334. var div = doc.createElement('div');
  3335. div.innerHTML = html;
  3336. return children$3(SugarElement.fromDom(div));
  3337. };
  3338. var fromDom = function (nodes) {
  3339. return map$1(nodes, SugarElement.fromDom);
  3340. };
  3341. var getNodeName = function (elm) {
  3342. return elm.nodeName.toLowerCase();
  3343. };
  3344. var getBody = function (editor) {
  3345. return SugarElement.fromDom(editor.getBody());
  3346. };
  3347. var getPixelWidth = function (elm) {
  3348. return elm.getBoundingClientRect().width;
  3349. };
  3350. var getPixelHeight = function (elm) {
  3351. return elm.getBoundingClientRect().height;
  3352. };
  3353. var getIsRoot = function (editor) {
  3354. return function (element) {
  3355. return eq$1(element, getBody(editor));
  3356. };
  3357. };
  3358. var removePxSuffix = function (size) {
  3359. return size ? size.replace(/px$/, '') : '';
  3360. };
  3361. var addPxSuffix = function (size) {
  3362. return /^\d+(\.\d+)?$/.test(size) ? size + 'px' : size;
  3363. };
  3364. var removeDataStyle = function (table) {
  3365. remove$7(table, 'data-mce-style');
  3366. var removeStyleAttribute = function (element) {
  3367. return remove$7(element, 'data-mce-style');
  3368. };
  3369. each$2(cells$1(table), removeStyleAttribute);
  3370. each$2(columns$1(table), removeStyleAttribute);
  3371. each$2(rows$1(table), removeStyleAttribute);
  3372. };
  3373. var getRawWidth = function (editor, elm) {
  3374. var raw = editor.dom.getStyle(elm, 'width') || editor.dom.getAttrib(elm, 'width');
  3375. return Optional.from(raw).filter(isNotEmpty);
  3376. };
  3377. var isPercentage$1 = function (value) {
  3378. return /^(\d+(\.\d+)?)%$/.test(value);
  3379. };
  3380. var isPixel = function (value) {
  3381. return /^(\d+(\.\d+)?)px$/.test(value);
  3382. };
  3383. var getSelectionStart = function (editor) {
  3384. return SugarElement.fromDom(editor.selection.getStart());
  3385. };
  3386. var getSelectionEnd = function (editor) {
  3387. return SugarElement.fromDom(editor.selection.getEnd());
  3388. };
  3389. var selection = function (selections) {
  3390. return cata$2(selections.get(), constant([]), identity, pure);
  3391. };
  3392. var unmergable = function (selections) {
  3393. var hasSpan = function (elem, type) {
  3394. return getOpt(elem, type).exists(function (span) {
  3395. return parseInt(span, 10) > 1;
  3396. });
  3397. };
  3398. var hasRowOrColSpan = function (elem) {
  3399. return hasSpan(elem, 'rowspan') || hasSpan(elem, 'colspan');
  3400. };
  3401. var candidates = selection(selections);
  3402. return candidates.length > 0 && forall(candidates, hasRowOrColSpan) ? Optional.some(candidates) : Optional.none();
  3403. };
  3404. var mergable = function (table, selections, ephemera) {
  3405. return cata$2(selections.get(), Optional.none, function (cells) {
  3406. if (cells.length <= 1) {
  3407. return Optional.none();
  3408. } else {
  3409. return retrieveBox(table, ephemera.firstSelectedSelector, ephemera.lastSelectedSelector).map(function (bounds) {
  3410. return {
  3411. bounds: bounds,
  3412. cells: cells
  3413. };
  3414. });
  3415. }
  3416. }, Optional.none);
  3417. };
  3418. var strSelected = 'data-mce-selected';
  3419. var strSelectedSelector = 'td[' + strSelected + '],th[' + strSelected + ']';
  3420. var strAttributeSelector = '[' + strSelected + ']';
  3421. var strFirstSelected = 'data-mce-first-selected';
  3422. var strFirstSelectedSelector = 'td[' + strFirstSelected + '],th[' + strFirstSelected + ']';
  3423. var strLastSelected = 'data-mce-last-selected';
  3424. var strLastSelectedSelector = 'td[' + strLastSelected + '],th[' + strLastSelected + ']';
  3425. var attributeSelector = strAttributeSelector;
  3426. var ephemera = {
  3427. selected: strSelected,
  3428. selectedSelector: strSelectedSelector,
  3429. firstSelected: strFirstSelected,
  3430. firstSelectedSelector: strFirstSelectedSelector,
  3431. lastSelected: strLastSelected,
  3432. lastSelectedSelector: strLastSelectedSelector
  3433. };
  3434. var noMenu = function (cell) {
  3435. return {
  3436. element: cell,
  3437. mergable: Optional.none(),
  3438. unmergable: Optional.none(),
  3439. selection: [cell]
  3440. };
  3441. };
  3442. var forMenu = function (selections, table, cell) {
  3443. return {
  3444. element: cell,
  3445. mergable: mergable(table, selections, ephemera),
  3446. unmergable: unmergable(selections),
  3447. selection: selection(selections)
  3448. };
  3449. };
  3450. var paste = function (element, clipboard, generators) {
  3451. return {
  3452. element: element,
  3453. clipboard: clipboard,
  3454. generators: generators
  3455. };
  3456. };
  3457. var pasteRows = function (selections, cell, clipboard, generators) {
  3458. return {
  3459. selection: selection(selections),
  3460. clipboard: clipboard,
  3461. generators: generators
  3462. };
  3463. };
  3464. var getSelectionCellFallback = function (element) {
  3465. return table(element).bind(function (table) {
  3466. return retrieve(table, ephemera.firstSelectedSelector);
  3467. }).fold(constant(element), function (cells) {
  3468. return cells[0];
  3469. });
  3470. };
  3471. var getSelectionFromSelector = function (selector) {
  3472. return function (initCell, isRoot) {
  3473. var cellName = name(initCell);
  3474. var cell = cellName === 'col' || cellName === 'colgroup' ? getSelectionCellFallback(initCell) : initCell;
  3475. return closest$1(cell, selector, isRoot);
  3476. };
  3477. };
  3478. var getSelectionCellOrCaption = getSelectionFromSelector('th,td,caption');
  3479. var getSelectionCell = getSelectionFromSelector('th,td');
  3480. var getCellsFromSelection = function (selections) {
  3481. return selection(selections);
  3482. };
  3483. var getRowsFromSelection = function (selected, selector) {
  3484. var cellOpt = getSelectionCell(selected);
  3485. var rowsOpt = cellOpt.bind(function (cell) {
  3486. return table(cell);
  3487. }).map(function (table) {
  3488. return rows$1(table);
  3489. });
  3490. return lift2(cellOpt, rowsOpt, function (cell, rows) {
  3491. return filter$2(rows, function (row) {
  3492. return exists(fromDom(row.dom.cells), function (rowCell) {
  3493. return get$b(rowCell, selector) === '1' || eq$1(rowCell, cell);
  3494. });
  3495. });
  3496. }).getOr([]);
  3497. };
  3498. var extractSelected = function (cells) {
  3499. return table(cells[0]).map(function (table) {
  3500. var replica = extract$1(table, attributeSelector);
  3501. removeDataStyle(replica);
  3502. return [replica];
  3503. });
  3504. };
  3505. var serializeElements = function (editor, elements) {
  3506. return map$1(elements, function (elm) {
  3507. return editor.selection.serializer.serialize(elm.dom, {});
  3508. }).join('');
  3509. };
  3510. var getTextContent = function (elements) {
  3511. return map$1(elements, function (element) {
  3512. return element.dom.innerText;
  3513. }).join('');
  3514. };
  3515. var registerEvents = function (editor, selections, actions) {
  3516. editor.on('BeforeGetContent', function (e) {
  3517. var multiCellContext = function (cells) {
  3518. e.preventDefault();
  3519. extractSelected(cells).each(function (elements) {
  3520. e.content = e.format === 'text' ? getTextContent(elements) : serializeElements(editor, elements);
  3521. });
  3522. };
  3523. if (e.selection === true) {
  3524. cata$2(selections.get(), noop, multiCellContext, noop);
  3525. }
  3526. });
  3527. editor.on('BeforeSetContent', function (e) {
  3528. if (e.selection === true && e.paste === true) {
  3529. var selectedCells = getCellsFromSelection(selections);
  3530. head(selectedCells).each(function (cell) {
  3531. table(cell).each(function (table) {
  3532. var elements = filter$2(fromHtml(e.content), function (content) {
  3533. return name(content) !== 'meta';
  3534. });
  3535. var isTable = isTag('table');
  3536. if (elements.length === 1 && isTable(elements[0])) {
  3537. e.preventDefault();
  3538. var doc = SugarElement.fromDom(editor.getDoc());
  3539. var generators = paste$1(doc);
  3540. var targets = paste(cell, elements[0], generators);
  3541. actions.pasteCells(table, targets).each(function () {
  3542. editor.focus();
  3543. });
  3544. }
  3545. });
  3546. });
  3547. }
  3548. });
  3549. };
  3550. var adt$7 = Adt.generate([
  3551. { none: [] },
  3552. { only: ['index'] },
  3553. {
  3554. left: [
  3555. 'index',
  3556. 'next'
  3557. ]
  3558. },
  3559. {
  3560. middle: [
  3561. 'prev',
  3562. 'index',
  3563. 'next'
  3564. ]
  3565. },
  3566. {
  3567. right: [
  3568. 'prev',
  3569. 'index'
  3570. ]
  3571. }
  3572. ]);
  3573. var ColumnContext = __assign({}, adt$7);
  3574. var neighbours = function (input, index) {
  3575. if (input.length === 0) {
  3576. return ColumnContext.none();
  3577. }
  3578. if (input.length === 1) {
  3579. return ColumnContext.only(0);
  3580. }
  3581. if (index === 0) {
  3582. return ColumnContext.left(0, 1);
  3583. }
  3584. if (index === input.length - 1) {
  3585. return ColumnContext.right(index - 1, index);
  3586. }
  3587. if (index > 0 && index < input.length - 1) {
  3588. return ColumnContext.middle(index - 1, index, index + 1);
  3589. }
  3590. return ColumnContext.none();
  3591. };
  3592. var determine = function (input, column, step, tableSize, resize) {
  3593. var result = input.slice(0);
  3594. var context = neighbours(input, column);
  3595. var onNone = constant(map$1(result, constant(0)));
  3596. var onOnly = function (index) {
  3597. return tableSize.singleColumnWidth(result[index], step);
  3598. };
  3599. var onLeft = function (index, next) {
  3600. return resize.calcLeftEdgeDeltas(result, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
  3601. };
  3602. var onMiddle = function (prev, index, next) {
  3603. return resize.calcMiddleDeltas(result, prev, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
  3604. };
  3605. var onRight = function (prev, index) {
  3606. return resize.calcRightEdgeDeltas(result, prev, index, step, tableSize.minCellWidth(), tableSize.isRelative);
  3607. };
  3608. return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
  3609. };
  3610. var total = function (start, end, measures) {
  3611. var r = 0;
  3612. for (var i = start; i < end; i++) {
  3613. r += measures[i] !== undefined ? measures[i] : 0;
  3614. }
  3615. return r;
  3616. };
  3617. var recalculateWidthForCells = function (warehouse, widths) {
  3618. var all = Warehouse.justCells(warehouse);
  3619. return map$1(all, function (cell) {
  3620. var width = total(cell.column, cell.column + cell.colspan, widths);
  3621. return {
  3622. element: cell.element,
  3623. width: width,
  3624. colspan: cell.colspan
  3625. };
  3626. });
  3627. };
  3628. var recalculateWidthForColumns = function (warehouse, widths) {
  3629. var groups = Warehouse.justColumns(warehouse);
  3630. return map$1(groups, function (column, index) {
  3631. return {
  3632. element: column.element,
  3633. width: widths[index],
  3634. colspan: column.colspan
  3635. };
  3636. });
  3637. };
  3638. var recalculateHeightForCells = function (warehouse, heights) {
  3639. var all = Warehouse.justCells(warehouse);
  3640. return map$1(all, function (cell) {
  3641. var height = total(cell.row, cell.row + cell.rowspan, heights);
  3642. return {
  3643. element: cell.element,
  3644. height: height,
  3645. rowspan: cell.rowspan
  3646. };
  3647. });
  3648. };
  3649. var matchRowHeight = function (warehouse, heights) {
  3650. return map$1(warehouse.all, function (row, i) {
  3651. return {
  3652. element: row.element,
  3653. height: heights[i]
  3654. };
  3655. });
  3656. };
  3657. var sumUp = function (newSize) {
  3658. return foldr(newSize, function (b, a) {
  3659. return b + a;
  3660. }, 0);
  3661. };
  3662. var recalculate = function (warehouse, widths) {
  3663. if (Warehouse.hasColumns(warehouse)) {
  3664. return recalculateWidthForColumns(warehouse, widths);
  3665. } else {
  3666. return recalculateWidthForCells(warehouse, widths);
  3667. }
  3668. };
  3669. var recalculateAndApply = function (warehouse, widths, tableSize) {
  3670. var newSizes = recalculate(warehouse, widths);
  3671. each$2(newSizes, function (cell) {
  3672. tableSize.setElementWidth(cell.element, cell.width);
  3673. });
  3674. };
  3675. var adjustWidth = function (table, delta, index, resizing, tableSize) {
  3676. var warehouse = Warehouse.fromTable(table);
  3677. var step = tableSize.getCellDelta(delta);
  3678. var widths = tableSize.getWidths(warehouse, tableSize);
  3679. var isLastColumn = index === warehouse.grid.columns - 1;
  3680. var clampedStep = resizing.clampTableDelta(widths, index, step, tableSize.minCellWidth(), isLastColumn);
  3681. var deltas = determine(widths, index, clampedStep, tableSize, resizing);
  3682. var newWidths = map$1(deltas, function (dx, i) {
  3683. return dx + widths[i];
  3684. });
  3685. recalculateAndApply(warehouse, newWidths, tableSize);
  3686. resizing.resizeTable(tableSize.adjustTableWidth, clampedStep, isLastColumn);
  3687. };
  3688. var adjustHeight = function (table, delta, index, direction) {
  3689. var warehouse = Warehouse.fromTable(table);
  3690. var heights = getPixelHeights(warehouse, table, direction);
  3691. var newHeights = map$1(heights, function (dy, i) {
  3692. return index === i ? Math.max(delta + dy, minHeight()) : dy;
  3693. });
  3694. var newCellSizes = recalculateHeightForCells(warehouse, newHeights);
  3695. var newRowSizes = matchRowHeight(warehouse, newHeights);
  3696. each$2(newRowSizes, function (row) {
  3697. setHeight(row.element, row.height);
  3698. });
  3699. each$2(newCellSizes, function (cell) {
  3700. setHeight(cell.element, cell.height);
  3701. });
  3702. var total = sumUp(newHeights);
  3703. setHeight(table, total);
  3704. };
  3705. var adjustAndRedistributeWidths$1 = function (_table, list, details, tableSize, resizeBehaviour) {
  3706. var warehouse = Warehouse.generate(list);
  3707. var sizes = tableSize.getWidths(warehouse, tableSize);
  3708. var tablePixelWidth = tableSize.pixelWidth();
  3709. var _a = resizeBehaviour.calcRedestributedWidths(sizes, tablePixelWidth, details.pixelDelta, tableSize.isRelative), newSizes = _a.newSizes, delta = _a.delta;
  3710. recalculateAndApply(warehouse, newSizes, tableSize);
  3711. tableSize.adjustTableWidth(delta);
  3712. };
  3713. var adjustWidthTo = function (_table, list, _info, tableSize) {
  3714. var warehouse = Warehouse.generate(list);
  3715. var widths = tableSize.getWidths(warehouse, tableSize);
  3716. recalculateAndApply(warehouse, widths, tableSize);
  3717. };
  3718. var zero = function (array) {
  3719. return map$1(array, constant(0));
  3720. };
  3721. var surround = function (sizes, startIndex, endIndex, results, f) {
  3722. return f(sizes.slice(0, startIndex)).concat(results).concat(f(sizes.slice(endIndex)));
  3723. };
  3724. var clampDeltaHelper = function (predicate) {
  3725. return function (sizes, index, delta, minCellSize) {
  3726. if (!predicate(delta)) {
  3727. return delta;
  3728. } else {
  3729. var newSize = Math.max(minCellSize, sizes[index] - Math.abs(delta));
  3730. var diff = Math.abs(newSize - sizes[index]);
  3731. return delta >= 0 ? diff : -diff;
  3732. }
  3733. };
  3734. };
  3735. var clampNegativeDelta = clampDeltaHelper(function (delta) {
  3736. return delta < 0;
  3737. });
  3738. var clampDelta = clampDeltaHelper(always);
  3739. var resizeTable = function () {
  3740. var calcFixedDeltas = function (sizes, index, next, delta, minCellSize) {
  3741. var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
  3742. return surround(sizes, index, next + 1, [
  3743. clampedDelta,
  3744. 0
  3745. ], zero);
  3746. };
  3747. var calcRelativeDeltas = function (sizes, index, delta, minCellSize) {
  3748. var ratio = (100 + delta) / 100;
  3749. var newThis = Math.max(minCellSize, (sizes[index] + delta) / ratio);
  3750. return map$1(sizes, function (size, idx) {
  3751. var newSize = idx === index ? newThis : size / ratio;
  3752. return newSize - size;
  3753. });
  3754. };
  3755. var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize, isRelative) {
  3756. if (isRelative) {
  3757. return calcRelativeDeltas(sizes, index, delta, minCellSize);
  3758. } else {
  3759. return calcFixedDeltas(sizes, index, next, delta, minCellSize);
  3760. }
  3761. };
  3762. var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize, isRelative) {
  3763. return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize, isRelative);
  3764. };
  3765. var resizeTable = function (resizer, delta) {
  3766. return resizer(delta);
  3767. };
  3768. var calcRightEdgeDeltas = function (sizes, _prev, index, delta, minCellSize, isRelative) {
  3769. if (isRelative) {
  3770. return calcRelativeDeltas(sizes, index, delta, minCellSize);
  3771. } else {
  3772. var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
  3773. return zero(sizes.slice(0, index)).concat([clampedDelta]);
  3774. }
  3775. };
  3776. var calcRedestributedWidths = function (sizes, totalWidth, pixelDelta, isRelative) {
  3777. if (isRelative) {
  3778. var tableWidth = totalWidth + pixelDelta;
  3779. var ratio_1 = tableWidth / totalWidth;
  3780. var newSizes = map$1(sizes, function (size) {
  3781. return size / ratio_1;
  3782. });
  3783. return {
  3784. delta: ratio_1 * 100 - 100,
  3785. newSizes: newSizes
  3786. };
  3787. } else {
  3788. return {
  3789. delta: pixelDelta,
  3790. newSizes: sizes
  3791. };
  3792. }
  3793. };
  3794. return {
  3795. resizeTable: resizeTable,
  3796. clampTableDelta: clampNegativeDelta,
  3797. calcLeftEdgeDeltas: calcLeftEdgeDeltas,
  3798. calcMiddleDeltas: calcMiddleDeltas,
  3799. calcRightEdgeDeltas: calcRightEdgeDeltas,
  3800. calcRedestributedWidths: calcRedestributedWidths
  3801. };
  3802. };
  3803. var preserveTable = function () {
  3804. var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize) {
  3805. var idx = delta >= 0 ? next : index;
  3806. var clampedDelta = clampDelta(sizes, idx, delta, minCellSize);
  3807. return surround(sizes, index, next + 1, [
  3808. clampedDelta,
  3809. -clampedDelta
  3810. ], zero);
  3811. };
  3812. var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize) {
  3813. return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize);
  3814. };
  3815. var resizeTable = function (resizer, delta, isLastColumn) {
  3816. if (isLastColumn) {
  3817. resizer(delta);
  3818. }
  3819. };
  3820. var calcRightEdgeDeltas = function (sizes, _prev, _index, delta, _minCellSize, isRelative) {
  3821. if (isRelative) {
  3822. return zero(sizes);
  3823. } else {
  3824. var diff = delta / sizes.length;
  3825. return map$1(sizes, constant(diff));
  3826. }
  3827. };
  3828. var clampTableDelta = function (sizes, index, delta, minCellSize, isLastColumn) {
  3829. if (isLastColumn) {
  3830. if (delta >= 0) {
  3831. return delta;
  3832. } else {
  3833. var maxDelta = foldl(sizes, function (a, b) {
  3834. return a + b - minCellSize;
  3835. }, 0);
  3836. return Math.max(-maxDelta, delta);
  3837. }
  3838. } else {
  3839. return clampNegativeDelta(sizes, index, delta, minCellSize);
  3840. }
  3841. };
  3842. var calcRedestributedWidths = function (sizes, _totalWidth, _pixelDelta, _isRelative) {
  3843. return {
  3844. delta: 0,
  3845. newSizes: sizes
  3846. };
  3847. };
  3848. return {
  3849. resizeTable: resizeTable,
  3850. clampTableDelta: clampTableDelta,
  3851. calcLeftEdgeDeltas: calcLeftEdgeDeltas,
  3852. calcMiddleDeltas: calcMiddleDeltas,
  3853. calcRightEdgeDeltas: calcRightEdgeDeltas,
  3854. calcRedestributedWidths: calcRedestributedWidths
  3855. };
  3856. };
  3857. var only = function (element, isResizable) {
  3858. var parent = Optional.from(element.dom.documentElement).map(SugarElement.fromDom).getOr(element);
  3859. return {
  3860. parent: constant(parent),
  3861. view: constant(element),
  3862. origin: constant(SugarPosition(0, 0)),
  3863. isResizable: isResizable
  3864. };
  3865. };
  3866. var detached = function (editable, chrome, isResizable) {
  3867. var origin = function () {
  3868. return absolute(chrome);
  3869. };
  3870. return {
  3871. parent: constant(chrome),
  3872. view: constant(editable),
  3873. origin: origin,
  3874. isResizable: isResizable
  3875. };
  3876. };
  3877. var body = function (editable, chrome, isResizable) {
  3878. return {
  3879. parent: constant(chrome),
  3880. view: constant(editable),
  3881. origin: constant(SugarPosition(0, 0)),
  3882. isResizable: isResizable
  3883. };
  3884. };
  3885. var ResizeWire = {
  3886. only: only,
  3887. detached: detached,
  3888. body: body
  3889. };
  3890. var adt$6 = Adt.generate([
  3891. { invalid: ['raw'] },
  3892. { pixels: ['value'] },
  3893. { percent: ['value'] }
  3894. ]);
  3895. var validateFor = function (suffix, type, value) {
  3896. var rawAmount = value.substring(0, value.length - suffix.length);
  3897. var amount = parseFloat(rawAmount);
  3898. return rawAmount === amount.toString() ? type(amount) : adt$6.invalid(value);
  3899. };
  3900. var from = function (value) {
  3901. if (endsWith(value, '%')) {
  3902. return validateFor('%', adt$6.percent, value);
  3903. }
  3904. if (endsWith(value, 'px')) {
  3905. return validateFor('px', adt$6.pixels, value);
  3906. }
  3907. return adt$6.invalid(value);
  3908. };
  3909. var Size = __assign(__assign({}, adt$6), { from: from });
  3910. var redistributeToPercent = function (widths, totalWidth) {
  3911. return map$1(widths, function (w) {
  3912. var colType = Size.from(w);
  3913. return colType.fold(function () {
  3914. return w;
  3915. }, function (px) {
  3916. var ratio = px / totalWidth * 100;
  3917. return ratio + '%';
  3918. }, function (pc) {
  3919. return pc + '%';
  3920. });
  3921. });
  3922. };
  3923. var redistributeToPx = function (widths, totalWidth, newTotalWidth) {
  3924. var scale = newTotalWidth / totalWidth;
  3925. return map$1(widths, function (w) {
  3926. var colType = Size.from(w);
  3927. return colType.fold(function () {
  3928. return w;
  3929. }, function (px) {
  3930. return px * scale + 'px';
  3931. }, function (pc) {
  3932. return pc / 100 * newTotalWidth + 'px';
  3933. });
  3934. });
  3935. };
  3936. var redistributeEmpty = function (newWidthType, columns) {
  3937. var f = newWidthType.fold(function () {
  3938. return constant('');
  3939. }, function (pixels) {
  3940. var num = pixels / columns;
  3941. return constant(num + 'px');
  3942. }, function () {
  3943. var num = 100 / columns;
  3944. return constant(num + '%');
  3945. });
  3946. return range$1(columns, f);
  3947. };
  3948. var redistributeValues = function (newWidthType, widths, totalWidth) {
  3949. return newWidthType.fold(function () {
  3950. return widths;
  3951. }, function (px) {
  3952. return redistributeToPx(widths, totalWidth, px);
  3953. }, function (_pc) {
  3954. return redistributeToPercent(widths, totalWidth);
  3955. });
  3956. };
  3957. var redistribute$1 = function (widths, totalWidth, newWidth) {
  3958. var newType = Size.from(newWidth);
  3959. var floats = forall(widths, function (s) {
  3960. return s === '0px';
  3961. }) ? redistributeEmpty(newType, widths.length) : redistributeValues(newType, widths, totalWidth);
  3962. return normalize(floats);
  3963. };
  3964. var sum = function (values, fallback) {
  3965. if (values.length === 0) {
  3966. return fallback;
  3967. }
  3968. return foldr(values, function (rest, v) {
  3969. return Size.from(v).fold(constant(0), identity, identity) + rest;
  3970. }, 0);
  3971. };
  3972. var roundDown = function (num, unit) {
  3973. var floored = Math.floor(num);
  3974. return {
  3975. value: floored + unit,
  3976. remainder: num - floored
  3977. };
  3978. };
  3979. var add$3 = function (value, amount) {
  3980. return Size.from(value).fold(constant(value), function (px) {
  3981. return px + amount + 'px';
  3982. }, function (pc) {
  3983. return pc + amount + '%';
  3984. });
  3985. };
  3986. var normalize = function (values) {
  3987. if (values.length === 0) {
  3988. return values;
  3989. }
  3990. var scan = foldr(values, function (rest, value) {
  3991. var info = Size.from(value).fold(function () {
  3992. return {
  3993. value: value,
  3994. remainder: 0
  3995. };
  3996. }, function (num) {
  3997. return roundDown(num, 'px');
  3998. }, function (num) {
  3999. return {
  4000. value: num + '%',
  4001. remainder: 0
  4002. };
  4003. });
  4004. return {
  4005. output: [info.value].concat(rest.output),
  4006. remainder: rest.remainder + info.remainder
  4007. };
  4008. }, {
  4009. output: [],
  4010. remainder: 0
  4011. });
  4012. var r = scan.output;
  4013. return r.slice(0, r.length - 1).concat([add$3(r[r.length - 1], Math.round(scan.remainder))]);
  4014. };
  4015. var validate = Size.from;
  4016. var redistributeToW = function (newWidths, cells, unit) {
  4017. each$2(cells, function (cell) {
  4018. var widths = newWidths.slice(cell.column, cell.colspan + cell.column);
  4019. var w = sum(widths, minWidth());
  4020. set$1(cell.element, 'width', w + unit);
  4021. });
  4022. };
  4023. var redistributeToColumns = function (newWidths, columns, unit) {
  4024. each$2(columns, function (column, index) {
  4025. var width = sum([newWidths[index]], minWidth());
  4026. set$1(column.element, 'width', width + unit);
  4027. });
  4028. };
  4029. var redistributeToH = function (newHeights, rows, cells, unit) {
  4030. each$2(cells, function (cell) {
  4031. var heights = newHeights.slice(cell.row, cell.rowspan + cell.row);
  4032. var h = sum(heights, minHeight());
  4033. set$1(cell.element, 'height', h + unit);
  4034. });
  4035. each$2(rows, function (row, i) {
  4036. set$1(row.element, 'height', newHeights[i]);
  4037. });
  4038. };
  4039. var getUnit = function (newSize) {
  4040. return validate(newSize).fold(constant('px'), constant('px'), constant('%'));
  4041. };
  4042. var redistribute = function (table, optWidth, optHeight) {
  4043. var warehouse = Warehouse.fromTable(table);
  4044. var rows = warehouse.all;
  4045. var cells = Warehouse.justCells(warehouse);
  4046. var columns = Warehouse.justColumns(warehouse);
  4047. optWidth.each(function (newWidth) {
  4048. var widthUnit = getUnit(newWidth);
  4049. var totalWidth = get$8(table);
  4050. var oldWidths = getRawWidths(warehouse, table);
  4051. var nuWidths = redistribute$1(oldWidths, totalWidth, newWidth);
  4052. if (Warehouse.hasColumns(warehouse)) {
  4053. redistributeToColumns(nuWidths, columns, widthUnit);
  4054. } else {
  4055. redistributeToW(nuWidths, cells, widthUnit);
  4056. }
  4057. set$1(table, 'width', newWidth);
  4058. });
  4059. optHeight.each(function (newHeight) {
  4060. var hUnit = getUnit(newHeight);
  4061. var totalHeight = get$7(table);
  4062. var oldHeights = getRawHeights(warehouse, table, height);
  4063. var nuHeights = redistribute$1(oldHeights, totalHeight, newHeight);
  4064. redistributeToH(nuHeights, rows, cells, hUnit);
  4065. set$1(table, 'height', newHeight);
  4066. });
  4067. };
  4068. var isPercentSizing = isPercentSizing$1;
  4069. var isPixelSizing = isPixelSizing$1;
  4070. var isNoneSizing = isNoneSizing$1;
  4071. var getGridSize = function (table) {
  4072. var warehouse = Warehouse.fromTable(table);
  4073. return warehouse.grid;
  4074. };
  4075. var Event = function (fields) {
  4076. var handlers = [];
  4077. var bind = function (handler) {
  4078. if (handler === undefined) {
  4079. throw new Error('Event bind error: undefined handler');
  4080. }
  4081. handlers.push(handler);
  4082. };
  4083. var unbind = function (handler) {
  4084. handlers = filter$2(handlers, function (h) {
  4085. return h !== handler;
  4086. });
  4087. };
  4088. var trigger = function () {
  4089. var args = [];
  4090. for (var _i = 0; _i < arguments.length; _i++) {
  4091. args[_i] = arguments[_i];
  4092. }
  4093. var event = {};
  4094. each$2(fields, function (name, i) {
  4095. event[name] = args[i];
  4096. });
  4097. each$2(handlers, function (handler) {
  4098. handler(event);
  4099. });
  4100. };
  4101. return {
  4102. bind: bind,
  4103. unbind: unbind,
  4104. trigger: trigger
  4105. };
  4106. };
  4107. var create$4 = function (typeDefs) {
  4108. var registry = map(typeDefs, function (event) {
  4109. return {
  4110. bind: event.bind,
  4111. unbind: event.unbind
  4112. };
  4113. });
  4114. var trigger = map(typeDefs, function (event) {
  4115. return event.trigger;
  4116. });
  4117. return {
  4118. registry: registry,
  4119. trigger: trigger
  4120. };
  4121. };
  4122. var last = function (fn, rate) {
  4123. var timer = null;
  4124. var cancel = function () {
  4125. if (!isNull(timer)) {
  4126. clearTimeout(timer);
  4127. timer = null;
  4128. }
  4129. };
  4130. var throttle = function () {
  4131. var args = [];
  4132. for (var _i = 0; _i < arguments.length; _i++) {
  4133. args[_i] = arguments[_i];
  4134. }
  4135. cancel();
  4136. timer = setTimeout(function () {
  4137. timer = null;
  4138. fn.apply(null, args);
  4139. }, rate);
  4140. };
  4141. return {
  4142. cancel: cancel,
  4143. throttle: throttle
  4144. };
  4145. };
  4146. var sort = function (arr) {
  4147. return arr.slice(0).sort();
  4148. };
  4149. var reqMessage = function (required, keys) {
  4150. throw new Error('All required keys (' + sort(required).join(', ') + ') were not specified. Specified keys were: ' + sort(keys).join(', ') + '.');
  4151. };
  4152. var unsuppMessage = function (unsupported) {
  4153. throw new Error('Unsupported keys for object: ' + sort(unsupported).join(', '));
  4154. };
  4155. var validateStrArr = function (label, array) {
  4156. if (!isArray(array)) {
  4157. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  4158. }
  4159. each$2(array, function (a) {
  4160. if (!isString(a)) {
  4161. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  4162. }
  4163. });
  4164. };
  4165. var invalidTypeMessage = function (incorrect, type) {
  4166. throw new Error('All values need to be of type: ' + type + '. Keys (' + sort(incorrect).join(', ') + ') were not.');
  4167. };
  4168. var checkDupes = function (everything) {
  4169. var sorted = sort(everything);
  4170. var dupe = find$1(sorted, function (s, i) {
  4171. return i < sorted.length - 1 && s === sorted[i + 1];
  4172. });
  4173. dupe.each(function (d) {
  4174. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  4175. });
  4176. };
  4177. var base = function (handleUnsupported, required) {
  4178. return baseWith(handleUnsupported, required, {
  4179. validate: isFunction,
  4180. label: 'function'
  4181. });
  4182. };
  4183. var baseWith = function (handleUnsupported, required, pred) {
  4184. if (required.length === 0) {
  4185. throw new Error('You must specify at least one required field.');
  4186. }
  4187. validateStrArr('required', required);
  4188. checkDupes(required);
  4189. return function (obj) {
  4190. var keys$1 = keys(obj);
  4191. var allReqd = forall(required, function (req) {
  4192. return contains$2(keys$1, req);
  4193. });
  4194. if (!allReqd) {
  4195. reqMessage(required, keys$1);
  4196. }
  4197. handleUnsupported(required, keys$1);
  4198. var invalidKeys = filter$2(required, function (key) {
  4199. return !pred.validate(obj[key], key);
  4200. });
  4201. if (invalidKeys.length > 0) {
  4202. invalidTypeMessage(invalidKeys, pred.label);
  4203. }
  4204. return obj;
  4205. };
  4206. };
  4207. var handleExact = function (required, keys) {
  4208. var unsupported = filter$2(keys, function (key) {
  4209. return !contains$2(required, key);
  4210. });
  4211. if (unsupported.length > 0) {
  4212. unsuppMessage(unsupported);
  4213. }
  4214. };
  4215. var exactly = function (required) {
  4216. return base(handleExact, required);
  4217. };
  4218. var DragMode = exactly([
  4219. 'compare',
  4220. 'extract',
  4221. 'mutate',
  4222. 'sink'
  4223. ]);
  4224. var DragSink = exactly([
  4225. 'element',
  4226. 'start',
  4227. 'stop',
  4228. 'destroy'
  4229. ]);
  4230. var DragApi = exactly([
  4231. 'forceDrop',
  4232. 'drop',
  4233. 'move',
  4234. 'delayDrop'
  4235. ]);
  4236. var InDrag = function () {
  4237. var previous = Optional.none();
  4238. var reset = function () {
  4239. previous = Optional.none();
  4240. };
  4241. var update = function (mode, nu) {
  4242. var result = previous.map(function (old) {
  4243. return mode.compare(old, nu);
  4244. });
  4245. previous = Optional.some(nu);
  4246. return result;
  4247. };
  4248. var onEvent = function (event, mode) {
  4249. var dataOption = mode.extract(event);
  4250. dataOption.each(function (data) {
  4251. var offset = update(mode, data);
  4252. offset.each(function (d) {
  4253. events.trigger.move(d);
  4254. });
  4255. });
  4256. };
  4257. var events = create$4({ move: Event(['info']) });
  4258. return {
  4259. onEvent: onEvent,
  4260. reset: reset,
  4261. events: events.registry
  4262. };
  4263. };
  4264. var NoDrag = function () {
  4265. var events = create$4({ move: Event(['info']) });
  4266. return {
  4267. onEvent: noop,
  4268. reset: noop,
  4269. events: events.registry
  4270. };
  4271. };
  4272. var Movement = function () {
  4273. var noDragState = NoDrag();
  4274. var inDragState = InDrag();
  4275. var dragState = noDragState;
  4276. var on = function () {
  4277. dragState.reset();
  4278. dragState = inDragState;
  4279. };
  4280. var off = function () {
  4281. dragState.reset();
  4282. dragState = noDragState;
  4283. };
  4284. var onEvent = function (event, mode) {
  4285. dragState.onEvent(event, mode);
  4286. };
  4287. var isOn = function () {
  4288. return dragState === inDragState;
  4289. };
  4290. return {
  4291. on: on,
  4292. off: off,
  4293. isOn: isOn,
  4294. onEvent: onEvent,
  4295. events: inDragState.events
  4296. };
  4297. };
  4298. var setup = function (mutation, mode, settings) {
  4299. var active = false;
  4300. var events = create$4({
  4301. start: Event([]),
  4302. stop: Event([])
  4303. });
  4304. var movement = Movement();
  4305. var drop = function () {
  4306. sink.stop();
  4307. if (movement.isOn()) {
  4308. movement.off();
  4309. events.trigger.stop();
  4310. }
  4311. };
  4312. var throttledDrop = last(drop, 200);
  4313. var go = function (parent) {
  4314. sink.start(parent);
  4315. movement.on();
  4316. events.trigger.start();
  4317. };
  4318. var mousemove = function (event) {
  4319. throttledDrop.cancel();
  4320. movement.onEvent(event, mode);
  4321. };
  4322. movement.events.move.bind(function (event) {
  4323. mode.mutate(mutation, event.info);
  4324. });
  4325. var on = function () {
  4326. active = true;
  4327. };
  4328. var off = function () {
  4329. active = false;
  4330. };
  4331. var runIfActive = function (f) {
  4332. return function () {
  4333. var args = [];
  4334. for (var _i = 0; _i < arguments.length; _i++) {
  4335. args[_i] = arguments[_i];
  4336. }
  4337. if (active) {
  4338. f.apply(null, args);
  4339. }
  4340. };
  4341. };
  4342. var sink = mode.sink(DragApi({
  4343. forceDrop: drop,
  4344. drop: runIfActive(drop),
  4345. move: runIfActive(mousemove),
  4346. delayDrop: runIfActive(throttledDrop.throttle)
  4347. }), settings);
  4348. var destroy = function () {
  4349. sink.destroy();
  4350. };
  4351. return {
  4352. element: sink.element,
  4353. go: go,
  4354. on: on,
  4355. off: off,
  4356. destroy: destroy,
  4357. events: events.registry
  4358. };
  4359. };
  4360. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  4361. return {
  4362. target: target,
  4363. x: x,
  4364. y: y,
  4365. stop: stop,
  4366. prevent: prevent,
  4367. kill: kill,
  4368. raw: raw
  4369. };
  4370. };
  4371. var fromRawEvent$1 = function (rawEvent) {
  4372. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  4373. var stop = function () {
  4374. return rawEvent.stopPropagation();
  4375. };
  4376. var prevent = function () {
  4377. return rawEvent.preventDefault();
  4378. };
  4379. var kill = compose(prevent, stop);
  4380. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  4381. };
  4382. var handle$2 = function (filter, handler) {
  4383. return function (rawEvent) {
  4384. if (filter(rawEvent)) {
  4385. handler(fromRawEvent$1(rawEvent));
  4386. }
  4387. };
  4388. };
  4389. var binder = function (element, event, filter, handler, useCapture) {
  4390. var wrapped = handle$2(filter, handler);
  4391. element.dom.addEventListener(event, wrapped, useCapture);
  4392. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  4393. };
  4394. var bind$1 = function (element, event, filter, handler) {
  4395. return binder(element, event, filter, handler, false);
  4396. };
  4397. var unbind = function (element, event, handler, useCapture) {
  4398. element.dom.removeEventListener(event, handler, useCapture);
  4399. };
  4400. var filter = always;
  4401. var bind = function (element, event, handler) {
  4402. return bind$1(element, event, filter, handler);
  4403. };
  4404. var fromRawEvent = fromRawEvent$1;
  4405. var read = function (element, attr) {
  4406. var value = get$b(element, attr);
  4407. return value === undefined || value === '' ? [] : value.split(' ');
  4408. };
  4409. var add$2 = function (element, attr, id) {
  4410. var old = read(element, attr);
  4411. var nu = old.concat([id]);
  4412. set$2(element, attr, nu.join(' '));
  4413. return true;
  4414. };
  4415. var remove$4 = function (element, attr, id) {
  4416. var nu = filter$2(read(element, attr), function (v) {
  4417. return v !== id;
  4418. });
  4419. if (nu.length > 0) {
  4420. set$2(element, attr, nu.join(' '));
  4421. } else {
  4422. remove$7(element, attr);
  4423. }
  4424. return false;
  4425. };
  4426. var supports = function (element) {
  4427. return element.dom.classList !== undefined;
  4428. };
  4429. var get$5 = function (element) {
  4430. return read(element, 'class');
  4431. };
  4432. var add$1 = function (element, clazz) {
  4433. return add$2(element, 'class', clazz);
  4434. };
  4435. var remove$3 = function (element, clazz) {
  4436. return remove$4(element, 'class', clazz);
  4437. };
  4438. var add = function (element, clazz) {
  4439. if (supports(element)) {
  4440. element.dom.classList.add(clazz);
  4441. } else {
  4442. add$1(element, clazz);
  4443. }
  4444. };
  4445. var cleanClass = function (element) {
  4446. var classList = supports(element) ? element.dom.classList : get$5(element);
  4447. if (classList.length === 0) {
  4448. remove$7(element, 'class');
  4449. }
  4450. };
  4451. var remove$2 = function (element, clazz) {
  4452. if (supports(element)) {
  4453. var classList = element.dom.classList;
  4454. classList.remove(clazz);
  4455. } else {
  4456. remove$3(element, clazz);
  4457. }
  4458. cleanClass(element);
  4459. };
  4460. var has = function (element, clazz) {
  4461. return supports(element) && element.dom.classList.contains(clazz);
  4462. };
  4463. var css = function (namespace) {
  4464. var dashNamespace = namespace.replace(/\./g, '-');
  4465. var resolve = function (str) {
  4466. return dashNamespace + '-' + str;
  4467. };
  4468. return { resolve: resolve };
  4469. };
  4470. var styles$1 = css('ephox-dragster');
  4471. var resolve$1 = styles$1.resolve;
  4472. var Blocker = function (options) {
  4473. var settings = __assign({ layerClass: resolve$1('blocker') }, options);
  4474. var div = SugarElement.fromTag('div');
  4475. set$2(div, 'role', 'presentation');
  4476. setAll(div, {
  4477. position: 'fixed',
  4478. left: '0px',
  4479. top: '0px',
  4480. width: '100%',
  4481. height: '100%'
  4482. });
  4483. add(div, resolve$1('blocker'));
  4484. add(div, settings.layerClass);
  4485. var element = constant(div);
  4486. var destroy = function () {
  4487. remove$5(div);
  4488. };
  4489. return {
  4490. element: element,
  4491. destroy: destroy
  4492. };
  4493. };
  4494. var compare = function (old, nu) {
  4495. return SugarPosition(nu.left - old.left, nu.top - old.top);
  4496. };
  4497. var extract = function (event) {
  4498. return Optional.some(SugarPosition(event.x, event.y));
  4499. };
  4500. var mutate = function (mutation, info) {
  4501. mutation.mutate(info.left, info.top);
  4502. };
  4503. var sink = function (dragApi, settings) {
  4504. var blocker = Blocker(settings);
  4505. var mdown = bind(blocker.element(), 'mousedown', dragApi.forceDrop);
  4506. var mup = bind(blocker.element(), 'mouseup', dragApi.drop);
  4507. var mmove = bind(blocker.element(), 'mousemove', dragApi.move);
  4508. var mout = bind(blocker.element(), 'mouseout', dragApi.delayDrop);
  4509. var destroy = function () {
  4510. blocker.destroy();
  4511. mup.unbind();
  4512. mmove.unbind();
  4513. mout.unbind();
  4514. mdown.unbind();
  4515. };
  4516. var start = function (parent) {
  4517. append$1(parent, blocker.element());
  4518. };
  4519. var stop = function () {
  4520. remove$5(blocker.element());
  4521. };
  4522. return DragSink({
  4523. element: blocker.element,
  4524. start: start,
  4525. stop: stop,
  4526. destroy: destroy
  4527. });
  4528. };
  4529. var MouseDrag = DragMode({
  4530. compare: compare,
  4531. extract: extract,
  4532. sink: sink,
  4533. mutate: mutate
  4534. });
  4535. var transform$1 = function (mutation, settings) {
  4536. if (settings === void 0) {
  4537. settings = {};
  4538. }
  4539. var mode = settings.mode !== undefined ? settings.mode : MouseDrag;
  4540. return setup(mutation, mode, settings);
  4541. };
  4542. var closest = function (target) {
  4543. return closest$1(target, '[contenteditable]');
  4544. };
  4545. var isEditable$1 = function (element, assumeEditable) {
  4546. if (assumeEditable === void 0) {
  4547. assumeEditable = false;
  4548. }
  4549. if (!detect$3().browser.isIE() && inBody(element)) {
  4550. return element.dom.isContentEditable;
  4551. } else {
  4552. return closest(element).fold(constant(assumeEditable), function (editable) {
  4553. return getRaw(editable) === 'true';
  4554. });
  4555. }
  4556. };
  4557. var getRaw = function (element) {
  4558. return element.dom.contentEditable;
  4559. };
  4560. var styles = css('ephox-snooker');
  4561. var resolve = styles.resolve;
  4562. var Mutation = function () {
  4563. var events = create$4({
  4564. drag: Event([
  4565. 'xDelta',
  4566. 'yDelta'
  4567. ])
  4568. });
  4569. var mutate = function (x, y) {
  4570. events.trigger.drag(x, y);
  4571. };
  4572. return {
  4573. mutate: mutate,
  4574. events: events.registry
  4575. };
  4576. };
  4577. var BarMutation = function () {
  4578. var events = create$4({
  4579. drag: Event([
  4580. 'xDelta',
  4581. 'yDelta',
  4582. 'target'
  4583. ])
  4584. });
  4585. var target = Optional.none();
  4586. var delegate = Mutation();
  4587. delegate.events.drag.bind(function (event) {
  4588. target.each(function (t) {
  4589. events.trigger.drag(event.xDelta, event.yDelta, t);
  4590. });
  4591. });
  4592. var assign = function (t) {
  4593. target = Optional.some(t);
  4594. };
  4595. var get = function () {
  4596. return target;
  4597. };
  4598. return {
  4599. assign: assign,
  4600. get: get,
  4601. mutate: delegate.mutate,
  4602. events: events.registry
  4603. };
  4604. };
  4605. var col = function (column, x, y, w, h) {
  4606. var bar = SugarElement.fromTag('div');
  4607. setAll(bar, {
  4608. position: 'absolute',
  4609. left: x - w / 2 + 'px',
  4610. top: y + 'px',
  4611. height: h + 'px',
  4612. width: w + 'px'
  4613. });
  4614. setAll$1(bar, {
  4615. 'data-column': column,
  4616. 'role': 'presentation'
  4617. });
  4618. return bar;
  4619. };
  4620. var row = function (r, x, y, w, h) {
  4621. var bar = SugarElement.fromTag('div');
  4622. setAll(bar, {
  4623. position: 'absolute',
  4624. left: x + 'px',
  4625. top: y - h / 2 + 'px',
  4626. height: h + 'px',
  4627. width: w + 'px'
  4628. });
  4629. setAll$1(bar, {
  4630. 'data-row': r,
  4631. 'role': 'presentation'
  4632. });
  4633. return bar;
  4634. };
  4635. var resizeBar = resolve('resizer-bar');
  4636. var resizeRowBar = resolve('resizer-rows');
  4637. var resizeColBar = resolve('resizer-cols');
  4638. var BAR_THICKNESS = 7;
  4639. var resizableRows = function (warehouse, isResizable) {
  4640. return bind$2(warehouse.all, function (row, i) {
  4641. return isResizable(row.element) ? [i] : [];
  4642. });
  4643. };
  4644. var resizableColumns = function (warehouse, isResizable) {
  4645. var resizableCols = [];
  4646. range$1(warehouse.grid.columns, function (index) {
  4647. var colElmOpt = Warehouse.getColumnAt(warehouse, index).map(function (col) {
  4648. return col.element;
  4649. });
  4650. if (colElmOpt.forall(isResizable)) {
  4651. resizableCols.push(index);
  4652. }
  4653. });
  4654. return filter$2(resizableCols, function (colIndex) {
  4655. var columnCells = Warehouse.filterItems(warehouse, function (cell) {
  4656. return cell.column === colIndex;
  4657. });
  4658. return forall(columnCells, function (cell) {
  4659. return isResizable(cell.element);
  4660. });
  4661. });
  4662. };
  4663. var destroy = function (wire) {
  4664. var previous = descendants(wire.parent(), '.' + resizeBar);
  4665. each$2(previous, remove$5);
  4666. };
  4667. var drawBar = function (wire, positions, create) {
  4668. var origin = wire.origin();
  4669. each$2(positions, function (cpOption) {
  4670. cpOption.each(function (cp) {
  4671. var bar = create(origin, cp);
  4672. add(bar, resizeBar);
  4673. append$1(wire.parent(), bar);
  4674. });
  4675. });
  4676. };
  4677. var refreshCol = function (wire, colPositions, position, tableHeight) {
  4678. drawBar(wire, colPositions, function (origin, cp) {
  4679. var colBar = col(cp.col, cp.x - origin.left, position.top - origin.top, BAR_THICKNESS, tableHeight);
  4680. add(colBar, resizeColBar);
  4681. return colBar;
  4682. });
  4683. };
  4684. var refreshRow = function (wire, rowPositions, position, tableWidth) {
  4685. drawBar(wire, rowPositions, function (origin, cp) {
  4686. var rowBar = row(cp.row, position.left - origin.left, cp.y - origin.top, tableWidth, BAR_THICKNESS);
  4687. add(rowBar, resizeRowBar);
  4688. return rowBar;
  4689. });
  4690. };
  4691. var refreshGrid = function (warhouse, wire, table, rows, cols) {
  4692. var position = absolute(table);
  4693. var isResizable = wire.isResizable;
  4694. var rowPositions = rows.length > 0 ? height.positions(rows, table) : [];
  4695. var resizableRowBars = rowPositions.length > 0 ? resizableRows(warhouse, isResizable) : [];
  4696. var resizableRowPositions = filter$2(rowPositions, function (_pos, i) {
  4697. return exists(resizableRowBars, function (barIndex) {
  4698. return i === barIndex;
  4699. });
  4700. });
  4701. refreshRow(wire, resizableRowPositions, position, getOuter$2(table));
  4702. var colPositions = cols.length > 0 ? width.positions(cols, table) : [];
  4703. var resizableColBars = colPositions.length > 0 ? resizableColumns(warhouse, isResizable) : [];
  4704. var resizableColPositions = filter$2(colPositions, function (_pos, i) {
  4705. return exists(resizableColBars, function (barIndex) {
  4706. return i === barIndex;
  4707. });
  4708. });
  4709. refreshCol(wire, resizableColPositions, position, getOuter$1(table));
  4710. };
  4711. var refresh = function (wire, table) {
  4712. destroy(wire);
  4713. if (wire.isResizable(table)) {
  4714. var warehouse = Warehouse.fromTable(table);
  4715. var rows$1 = rows(warehouse);
  4716. var cols = columns(warehouse);
  4717. refreshGrid(warehouse, wire, table, rows$1, cols);
  4718. }
  4719. };
  4720. var each = function (wire, f) {
  4721. var bars = descendants(wire.parent(), '.' + resizeBar);
  4722. each$2(bars, f);
  4723. };
  4724. var hide = function (wire) {
  4725. each(wire, function (bar) {
  4726. set$1(bar, 'display', 'none');
  4727. });
  4728. };
  4729. var show = function (wire) {
  4730. each(wire, function (bar) {
  4731. set$1(bar, 'display', 'block');
  4732. });
  4733. };
  4734. var isRowBar = function (element) {
  4735. return has(element, resizeRowBar);
  4736. };
  4737. var isColBar = function (element) {
  4738. return has(element, resizeColBar);
  4739. };
  4740. var resizeBarDragging = resolve('resizer-bar-dragging');
  4741. var BarManager = function (wire) {
  4742. var mutation = BarMutation();
  4743. var resizing = transform$1(mutation, {});
  4744. var hoverTable = Optional.none();
  4745. var getResizer = function (element, type) {
  4746. return Optional.from(get$b(element, type));
  4747. };
  4748. mutation.events.drag.bind(function (event) {
  4749. getResizer(event.target, 'data-row').each(function (_dataRow) {
  4750. var currentRow = getCssValue(event.target, 'top');
  4751. set$1(event.target, 'top', currentRow + event.yDelta + 'px');
  4752. });
  4753. getResizer(event.target, 'data-column').each(function (_dataCol) {
  4754. var currentCol = getCssValue(event.target, 'left');
  4755. set$1(event.target, 'left', currentCol + event.xDelta + 'px');
  4756. });
  4757. });
  4758. var getDelta = function (target, dir) {
  4759. var newX = getCssValue(target, dir);
  4760. var oldX = getAttrValue(target, 'data-initial-' + dir, 0);
  4761. return newX - oldX;
  4762. };
  4763. resizing.events.stop.bind(function () {
  4764. mutation.get().each(function (target) {
  4765. hoverTable.each(function (table) {
  4766. getResizer(target, 'data-row').each(function (row) {
  4767. var delta = getDelta(target, 'top');
  4768. remove$7(target, 'data-initial-top');
  4769. events.trigger.adjustHeight(table, delta, parseInt(row, 10));
  4770. });
  4771. getResizer(target, 'data-column').each(function (column) {
  4772. var delta = getDelta(target, 'left');
  4773. remove$7(target, 'data-initial-left');
  4774. events.trigger.adjustWidth(table, delta, parseInt(column, 10));
  4775. });
  4776. refresh(wire, table);
  4777. });
  4778. });
  4779. });
  4780. var handler = function (target, dir) {
  4781. events.trigger.startAdjust();
  4782. mutation.assign(target);
  4783. set$2(target, 'data-initial-' + dir, getCssValue(target, dir));
  4784. add(target, resizeBarDragging);
  4785. set$1(target, 'opacity', '0.2');
  4786. resizing.go(wire.parent());
  4787. };
  4788. var mousedown = bind(wire.parent(), 'mousedown', function (event) {
  4789. if (isRowBar(event.target)) {
  4790. handler(event.target, 'top');
  4791. }
  4792. if (isColBar(event.target)) {
  4793. handler(event.target, 'left');
  4794. }
  4795. });
  4796. var isRoot = function (e) {
  4797. return eq$1(e, wire.view());
  4798. };
  4799. var findClosestEditableTable = function (target) {
  4800. return closest$1(target, 'table', isRoot).filter(isEditable$1);
  4801. };
  4802. var mouseover = bind(wire.view(), 'mouseover', function (event) {
  4803. findClosestEditableTable(event.target).fold(function () {
  4804. if (inBody(event.target)) {
  4805. destroy(wire);
  4806. }
  4807. }, function (table) {
  4808. hoverTable = Optional.some(table);
  4809. refresh(wire, table);
  4810. });
  4811. });
  4812. var destroy$1 = function () {
  4813. mousedown.unbind();
  4814. mouseover.unbind();
  4815. resizing.destroy();
  4816. destroy(wire);
  4817. };
  4818. var refresh$1 = function (tbl) {
  4819. refresh(wire, tbl);
  4820. };
  4821. var events = create$4({
  4822. adjustHeight: Event([
  4823. 'table',
  4824. 'delta',
  4825. 'row'
  4826. ]),
  4827. adjustWidth: Event([
  4828. 'table',
  4829. 'delta',
  4830. 'column'
  4831. ]),
  4832. startAdjust: Event([])
  4833. });
  4834. return {
  4835. destroy: destroy$1,
  4836. refresh: refresh$1,
  4837. on: resizing.on,
  4838. off: resizing.off,
  4839. hideBars: curry(hide, wire),
  4840. showBars: curry(show, wire),
  4841. events: events.registry
  4842. };
  4843. };
  4844. var create$3 = function (wire, resizing, lazySizing) {
  4845. var hdirection = height;
  4846. var vdirection = width;
  4847. var manager = BarManager(wire);
  4848. var events = create$4({
  4849. beforeResize: Event([
  4850. 'table',
  4851. 'type'
  4852. ]),
  4853. afterResize: Event([
  4854. 'table',
  4855. 'type'
  4856. ]),
  4857. startDrag: Event([])
  4858. });
  4859. manager.events.adjustHeight.bind(function (event) {
  4860. var table = event.table;
  4861. events.trigger.beforeResize(table, 'row');
  4862. var delta = hdirection.delta(event.delta, table);
  4863. adjustHeight(table, delta, event.row, hdirection);
  4864. events.trigger.afterResize(table, 'row');
  4865. });
  4866. manager.events.startAdjust.bind(function (_event) {
  4867. events.trigger.startDrag();
  4868. });
  4869. manager.events.adjustWidth.bind(function (event) {
  4870. var table = event.table;
  4871. events.trigger.beforeResize(table, 'col');
  4872. var delta = vdirection.delta(event.delta, table);
  4873. var tableSize = lazySizing(table);
  4874. adjustWidth(table, delta, event.column, resizing, tableSize);
  4875. events.trigger.afterResize(table, 'col');
  4876. });
  4877. return {
  4878. on: manager.on,
  4879. off: manager.off,
  4880. hideBars: manager.hideBars,
  4881. showBars: manager.showBars,
  4882. destroy: manager.destroy,
  4883. events: events.registry
  4884. };
  4885. };
  4886. var TableResize = { create: create$3 };
  4887. var fireNewRow = function (editor, row) {
  4888. return editor.fire('newrow', { node: row });
  4889. };
  4890. var fireNewCell = function (editor, cell) {
  4891. return editor.fire('newcell', { node: cell });
  4892. };
  4893. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  4894. editor.fire('ObjectResizeStart', {
  4895. target: target,
  4896. width: width,
  4897. height: height,
  4898. origin: origin
  4899. });
  4900. };
  4901. var fireObjectResized = function (editor, target, width, height, origin) {
  4902. editor.fire('ObjectResized', {
  4903. target: target,
  4904. width: width,
  4905. height: height,
  4906. origin: origin
  4907. });
  4908. };
  4909. var fireTableSelectionChange = function (editor, cells, start, finish, otherCells) {
  4910. editor.fire('TableSelectionChange', {
  4911. cells: cells,
  4912. start: start,
  4913. finish: finish,
  4914. otherCells: otherCells
  4915. });
  4916. };
  4917. var fireTableSelectionClear = function (editor) {
  4918. editor.fire('TableSelectionClear');
  4919. };
  4920. var fireTableModified = function (editor, table, data) {
  4921. editor.fire('TableModified', __assign(__assign({}, data), { table: table }));
  4922. };
  4923. var styleModified = {
  4924. structure: false,
  4925. style: true
  4926. };
  4927. var structureModified = {
  4928. structure: true,
  4929. style: false
  4930. };
  4931. var styleAndStructureModified = {
  4932. structure: true,
  4933. style: true
  4934. };
  4935. var defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
  4936. var defaultStyles = {
  4937. 'border-collapse': 'collapse',
  4938. 'width': '100%'
  4939. };
  4940. var defaultCellBorderWidths = range$1(5, function (i) {
  4941. var size = i + 1 + 'px';
  4942. return {
  4943. title: size,
  4944. value: size
  4945. };
  4946. });
  4947. var defaultCellBorderStyles = map$1([
  4948. 'Solid',
  4949. 'Dotted',
  4950. 'Dashed',
  4951. 'Double',
  4952. 'Groove',
  4953. 'Ridge',
  4954. 'Inset',
  4955. 'Outset',
  4956. 'None',
  4957. 'Hidden'
  4958. ], function (type) {
  4959. return {
  4960. title: type,
  4961. value: type.toLowerCase()
  4962. };
  4963. });
  4964. var determineDefaultStyles = function (editor) {
  4965. var _a;
  4966. if (isPixelsForced(editor)) {
  4967. var dom = editor.dom;
  4968. var parentBlock = (_a = dom.getParent(editor.selection.getStart(), dom.isBlock)) !== null && _a !== void 0 ? _a : editor.getBody();
  4969. var contentWidth = getInner(SugarElement.fromDom(parentBlock));
  4970. return __assign(__assign({}, defaultStyles), { width: contentWidth + 'px' });
  4971. } else if (isResponsiveForced(editor)) {
  4972. return filter$1(defaultStyles, function (_value, key) {
  4973. return key !== 'width';
  4974. });
  4975. } else {
  4976. return defaultStyles;
  4977. }
  4978. };
  4979. var defaultAttributes = { border: '1' };
  4980. var defaultColumnResizingBehaviour = 'preservetable';
  4981. var getTableSizingMode = function (editor) {
  4982. return editor.getParam('table_sizing_mode', 'auto');
  4983. };
  4984. var getTableResponseWidth = function (editor) {
  4985. return editor.getParam('table_responsive_width');
  4986. };
  4987. var getTableBorderWidths = function (editor) {
  4988. return editor.getParam('table_border_widths', defaultCellBorderWidths, 'array');
  4989. };
  4990. var getTableBorderStyles = function (editor) {
  4991. return editor.getParam('table_border_styles', defaultCellBorderStyles, 'array');
  4992. };
  4993. var getDefaultAttributes = function (editor) {
  4994. return editor.getParam('table_default_attributes', defaultAttributes, 'object');
  4995. };
  4996. var getDefaultStyles = function (editor) {
  4997. return editor.getParam('table_default_styles', determineDefaultStyles(editor), 'object');
  4998. };
  4999. var hasTableResizeBars = function (editor) {
  5000. return editor.getParam('table_resize_bars', true, 'boolean');
  5001. };
  5002. var hasTabNavigation = function (editor) {
  5003. return editor.getParam('table_tab_navigation', true, 'boolean');
  5004. };
  5005. var hasAdvancedCellTab = function (editor) {
  5006. return editor.getParam('table_cell_advtab', true, 'boolean');
  5007. };
  5008. var hasAdvancedRowTab = function (editor) {
  5009. return editor.getParam('table_row_advtab', true, 'boolean');
  5010. };
  5011. var hasAdvancedTableTab = function (editor) {
  5012. return editor.getParam('table_advtab', true, 'boolean');
  5013. };
  5014. var hasAppearanceOptions = function (editor) {
  5015. return editor.getParam('table_appearance_options', true, 'boolean');
  5016. };
  5017. var hasTableGrid = function (editor) {
  5018. return editor.getParam('table_grid', true, 'boolean');
  5019. };
  5020. var shouldStyleWithCss = function (editor) {
  5021. return editor.getParam('table_style_by_css', false, 'boolean');
  5022. };
  5023. var getCellClassList = function (editor) {
  5024. return editor.getParam('table_cell_class_list', [], 'array');
  5025. };
  5026. var getRowClassList = function (editor) {
  5027. return editor.getParam('table_row_class_list', [], 'array');
  5028. };
  5029. var getTableClassList = function (editor) {
  5030. return editor.getParam('table_class_list', [], 'array');
  5031. };
  5032. var isPercentagesForced = function (editor) {
  5033. return getTableSizingMode(editor) === 'relative' || getTableResponseWidth(editor) === true;
  5034. };
  5035. var isPixelsForced = function (editor) {
  5036. return getTableSizingMode(editor) === 'fixed' || getTableResponseWidth(editor) === false;
  5037. };
  5038. var isResponsiveForced = function (editor) {
  5039. return getTableSizingMode(editor) === 'responsive';
  5040. };
  5041. var getToolbar = function (editor) {
  5042. return editor.getParam('table_toolbar', defaultTableToolbar);
  5043. };
  5044. var useColumnGroup = function (editor) {
  5045. return editor.getParam('table_use_colgroups', false, 'boolean');
  5046. };
  5047. var getTableHeaderType = function (editor) {
  5048. var defaultValue = 'section';
  5049. var value = editor.getParam('table_header_type', defaultValue, 'string');
  5050. var validValues = [
  5051. 'section',
  5052. 'cells',
  5053. 'sectionCells',
  5054. 'auto'
  5055. ];
  5056. if (!contains$2(validValues, value)) {
  5057. return defaultValue;
  5058. } else {
  5059. return value;
  5060. }
  5061. };
  5062. var getColumnResizingBehaviour = function (editor) {
  5063. var validModes = [
  5064. 'preservetable',
  5065. 'resizetable'
  5066. ];
  5067. var givenMode = editor.getParam('table_column_resizing', defaultColumnResizingBehaviour, 'string');
  5068. return find$1(validModes, function (mode) {
  5069. return mode === givenMode;
  5070. }).getOr(defaultColumnResizingBehaviour);
  5071. };
  5072. var isPreserveTableColumnResizing = function (editor) {
  5073. return getColumnResizingBehaviour(editor) === 'preservetable';
  5074. };
  5075. var isResizeTableColumnResizing = function (editor) {
  5076. return getColumnResizingBehaviour(editor) === 'resizetable';
  5077. };
  5078. var getCloneElements = function (editor) {
  5079. var cloneElements = editor.getParam('table_clone_elements');
  5080. if (isString(cloneElements)) {
  5081. return Optional.some(cloneElements.split(/[ ,]/));
  5082. } else if (Array.isArray(cloneElements)) {
  5083. return Optional.some(cloneElements);
  5084. } else {
  5085. return Optional.none();
  5086. }
  5087. };
  5088. var hasObjectResizing = function (editor) {
  5089. var objectResizing = editor.getParam('object_resizing', true);
  5090. return isString(objectResizing) ? objectResizing === 'table' : objectResizing;
  5091. };
  5092. var getTableBackgroundColorMap = function (editor) {
  5093. return editor.getParam('table_background_color_map', [], 'array');
  5094. };
  5095. var getTableBorderColorMap = function (editor) {
  5096. return editor.getParam('table_border_color_map', [], 'array');
  5097. };
  5098. var get$4 = function (editor, table) {
  5099. if (isPercentagesForced(editor)) {
  5100. return TableSize.percentageSize(table);
  5101. } else if (isPixelsForced(editor)) {
  5102. return TableSize.pixelSize(table);
  5103. } else {
  5104. return TableSize.getTableSize(table);
  5105. }
  5106. };
  5107. var cleanupLegacyAttributes = function (element) {
  5108. remove$7(element, 'width');
  5109. };
  5110. var convertToPercentSize = function (table) {
  5111. var newWidth = getPercentTableWidth(table);
  5112. redistribute(table, Optional.some(newWidth), Optional.none());
  5113. cleanupLegacyAttributes(table);
  5114. };
  5115. var convertToPixelSize = function (table) {
  5116. var newWidth = getPixelTableWidth(table);
  5117. redistribute(table, Optional.some(newWidth), Optional.none());
  5118. cleanupLegacyAttributes(table);
  5119. };
  5120. var convertToNoneSize = function (table) {
  5121. remove$6(table, 'width');
  5122. var columns = columns$1(table);
  5123. var rowElements = columns.length > 0 ? columns : cells$1(table);
  5124. each$2(rowElements, function (cell) {
  5125. remove$6(cell, 'width');
  5126. cleanupLegacyAttributes(cell);
  5127. });
  5128. cleanupLegacyAttributes(table);
  5129. };
  5130. var enforcePercentage = convertToPercentSize;
  5131. var enforcePixels = convertToPixelSize;
  5132. var enforceNone = convertToNoneSize;
  5133. var syncPixels = function (table) {
  5134. var warehouse = Warehouse.fromTable(table);
  5135. if (!Warehouse.hasColumns(warehouse)) {
  5136. each$2(cells$1(table), function (cell) {
  5137. var computedWidth = get$a(cell, 'width');
  5138. set$1(cell, 'width', computedWidth);
  5139. remove$7(cell, 'width');
  5140. });
  5141. }
  5142. };
  5143. var createContainer = function () {
  5144. var container = SugarElement.fromTag('div');
  5145. setAll(container, {
  5146. position: 'static',
  5147. height: '0',
  5148. width: '0',
  5149. padding: '0',
  5150. margin: '0',
  5151. border: '0'
  5152. });
  5153. append$1(body$1(), container);
  5154. return container;
  5155. };
  5156. var get$3 = function (editor, isResizable) {
  5157. return editor.inline ? ResizeWire.body(getBody(editor), createContainer(), isResizable) : ResizeWire.only(SugarElement.fromDom(editor.getDoc()), isResizable);
  5158. };
  5159. var remove$1 = function (editor, wire) {
  5160. if (editor.inline) {
  5161. remove$5(wire.parent());
  5162. }
  5163. };
  5164. var barResizerPrefix = 'bar-';
  5165. var isResizable = function (elm) {
  5166. return get$b(elm, 'data-mce-resize') !== 'false';
  5167. };
  5168. var getResizeHandler = function (editor) {
  5169. var selectionRng = Optional.none();
  5170. var resize = Optional.none();
  5171. var wire = Optional.none();
  5172. var startW;
  5173. var startRawW;
  5174. var isTable = function (elm) {
  5175. return elm.nodeName === 'TABLE';
  5176. };
  5177. var lazyResize = function () {
  5178. return resize;
  5179. };
  5180. var lazyWire = function () {
  5181. return wire.getOr(ResizeWire.only(SugarElement.fromDom(editor.getBody()), isResizable));
  5182. };
  5183. var lazySizing = function (table) {
  5184. return get$4(editor, table);
  5185. };
  5186. var lazyResizingBehaviour = function () {
  5187. return isPreserveTableColumnResizing(editor) ? preserveTable() : resizeTable();
  5188. };
  5189. var getNumColumns = function (table) {
  5190. return getGridSize(table).columns;
  5191. };
  5192. var afterCornerResize = function (table, origin, width) {
  5193. var isRightEdgeResize = endsWith(origin, 'e');
  5194. if (startRawW === '') {
  5195. enforcePercentage(table);
  5196. }
  5197. if (width !== startW && startRawW !== '') {
  5198. set$1(table, 'width', startRawW);
  5199. var resizing = lazyResizingBehaviour();
  5200. var tableSize = lazySizing(table);
  5201. var col = isPreserveTableColumnResizing(editor) || isRightEdgeResize ? getNumColumns(table) - 1 : 0;
  5202. adjustWidth(table, width - startW, col, resizing, tableSize);
  5203. } else if (isPercentage$1(startRawW)) {
  5204. var percentW = parseFloat(startRawW.replace('%', ''));
  5205. var targetPercentW = width * percentW / startW;
  5206. set$1(table, 'width', targetPercentW + '%');
  5207. }
  5208. if (isPixel(startRawW)) {
  5209. syncPixels(table);
  5210. }
  5211. };
  5212. var destroy = function () {
  5213. resize.each(function (sz) {
  5214. sz.destroy();
  5215. });
  5216. wire.each(function (w) {
  5217. remove$1(editor, w);
  5218. });
  5219. };
  5220. editor.on('init', function () {
  5221. var rawWire = get$3(editor, isResizable);
  5222. wire = Optional.some(rawWire);
  5223. if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
  5224. var resizing = lazyResizingBehaviour();
  5225. var sz = TableResize.create(rawWire, resizing, lazySizing);
  5226. sz.on();
  5227. sz.events.startDrag.bind(function (_event) {
  5228. selectionRng = Optional.some(editor.selection.getRng());
  5229. });
  5230. sz.events.beforeResize.bind(function (event) {
  5231. var rawTable = event.table.dom;
  5232. fireObjectResizeStart(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
  5233. });
  5234. sz.events.afterResize.bind(function (event) {
  5235. var table = event.table;
  5236. var rawTable = table.dom;
  5237. removeDataStyle(table);
  5238. selectionRng.each(function (rng) {
  5239. editor.selection.setRng(rng);
  5240. editor.focus();
  5241. });
  5242. fireObjectResized(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
  5243. editor.undoManager.add();
  5244. });
  5245. resize = Optional.some(sz);
  5246. }
  5247. });
  5248. editor.on('ObjectResizeStart', function (e) {
  5249. var targetElm = e.target;
  5250. if (isTable(targetElm)) {
  5251. var table = SugarElement.fromDom(targetElm);
  5252. each$2(editor.dom.select('.mce-clonedresizable'), function (clone) {
  5253. editor.dom.addClass(clone, 'mce-' + getColumnResizingBehaviour(editor) + '-columns');
  5254. });
  5255. if (!isPixelSizing(table) && isPixelsForced(editor)) {
  5256. enforcePixels(table);
  5257. } else if (!isPercentSizing(table) && isPercentagesForced(editor)) {
  5258. enforcePercentage(table);
  5259. }
  5260. if (isNoneSizing(table) && startsWith(e.origin, barResizerPrefix)) {
  5261. enforcePercentage(table);
  5262. }
  5263. startW = e.width;
  5264. startRawW = isResponsiveForced(editor) ? '' : getRawWidth(editor, targetElm).getOr('');
  5265. }
  5266. });
  5267. editor.on('ObjectResized', function (e) {
  5268. var targetElm = e.target;
  5269. if (isTable(targetElm)) {
  5270. var table = SugarElement.fromDom(targetElm);
  5271. var origin_1 = e.origin;
  5272. if (startsWith(origin_1, 'corner-')) {
  5273. afterCornerResize(table, origin_1, e.width);
  5274. }
  5275. removeDataStyle(table);
  5276. fireTableModified(editor, table.dom, styleModified);
  5277. }
  5278. });
  5279. editor.on('SwitchMode', function () {
  5280. lazyResize().each(function (resize) {
  5281. if (editor.mode.isReadOnly()) {
  5282. resize.hideBars();
  5283. } else {
  5284. resize.showBars();
  5285. }
  5286. });
  5287. });
  5288. return {
  5289. lazyResize: lazyResize,
  5290. lazyWire: lazyWire,
  5291. destroy: destroy
  5292. };
  5293. };
  5294. var point = function (element, offset) {
  5295. return {
  5296. element: element,
  5297. offset: offset
  5298. };
  5299. };
  5300. var scan$1 = function (universe, element, direction) {
  5301. if (universe.property().isText(element) && universe.property().getText(element).trim().length === 0 || universe.property().isComment(element)) {
  5302. return direction(element).bind(function (elem) {
  5303. return scan$1(universe, elem, direction).orThunk(function () {
  5304. return Optional.some(elem);
  5305. });
  5306. });
  5307. } else {
  5308. return Optional.none();
  5309. }
  5310. };
  5311. var toEnd = function (universe, element) {
  5312. if (universe.property().isText(element)) {
  5313. return universe.property().getText(element).length;
  5314. }
  5315. var children = universe.property().children(element);
  5316. return children.length;
  5317. };
  5318. var freefallRtl$2 = function (universe, element) {
  5319. var candidate = scan$1(universe, element, universe.query().prevSibling).getOr(element);
  5320. if (universe.property().isText(candidate)) {
  5321. return point(candidate, toEnd(universe, candidate));
  5322. }
  5323. var children = universe.property().children(candidate);
  5324. return children.length > 0 ? freefallRtl$2(universe, children[children.length - 1]) : point(candidate, toEnd(universe, candidate));
  5325. };
  5326. var freefallRtl$1 = freefallRtl$2;
  5327. var universe$2 = DomUniverse();
  5328. var freefallRtl = function (element) {
  5329. return freefallRtl$1(universe$2, element);
  5330. };
  5331. var halve = function (main, other) {
  5332. var colspan = getSpan(main, 'colspan');
  5333. if (colspan === 1) {
  5334. var width = getGenericWidth(main);
  5335. width.each(function (w) {
  5336. var newWidth = w.value / 2;
  5337. setGenericWidth(main, newWidth, w.unit);
  5338. setGenericWidth(other, newWidth, w.unit);
  5339. });
  5340. }
  5341. };
  5342. var isHeaderCell = isTag('th');
  5343. var isHeaderCells = function (cells) {
  5344. return forall(cells, function (cell) {
  5345. return isHeaderCell(cell.element);
  5346. });
  5347. };
  5348. var getRowHeaderType = function (isHeaderRow, isHeaderCells) {
  5349. if (isHeaderRow && isHeaderCells) {
  5350. return 'sectionCells';
  5351. } else if (isHeaderRow) {
  5352. return 'section';
  5353. } else {
  5354. return 'cells';
  5355. }
  5356. };
  5357. var getRowType$1 = function (row) {
  5358. var isHeaderRow = row.section === 'thead';
  5359. var isHeaderCells = is(findCommonCellType(row.cells), 'th');
  5360. if (isHeaderRow || isHeaderCells) {
  5361. return {
  5362. type: 'header',
  5363. subType: getRowHeaderType(isHeaderRow, isHeaderCells)
  5364. };
  5365. } else if (row.section === 'tfoot') {
  5366. return { type: 'footer' };
  5367. } else {
  5368. return { type: 'body' };
  5369. }
  5370. };
  5371. var findCommonCellType = function (cells) {
  5372. var headerCells = filter$2(cells, function (cell) {
  5373. return isHeaderCell(cell.element);
  5374. });
  5375. if (headerCells.length === 0) {
  5376. return Optional.some('td');
  5377. } else if (headerCells.length === cells.length) {
  5378. return Optional.some('th');
  5379. } else {
  5380. return Optional.none();
  5381. }
  5382. };
  5383. var findCommonRowType = function (rows) {
  5384. var rowTypes = map$1(rows, function (row) {
  5385. return getRowType$1(row).type;
  5386. });
  5387. var hasHeader = contains$2(rowTypes, 'header');
  5388. var hasFooter = contains$2(rowTypes, 'footer');
  5389. if (!hasHeader && !hasFooter) {
  5390. return Optional.some('body');
  5391. } else {
  5392. var hasBody = contains$2(rowTypes, 'body');
  5393. if (hasHeader && !hasBody && !hasFooter) {
  5394. return Optional.some('header');
  5395. } else if (!hasHeader && !hasBody && hasFooter) {
  5396. return Optional.some('footer');
  5397. } else {
  5398. return Optional.none();
  5399. }
  5400. }
  5401. };
  5402. var findTableRowHeaderType = function (warehouse) {
  5403. return findMap(warehouse.all, function (row) {
  5404. var rowType = getRowType$1(row);
  5405. return rowType.type === 'header' ? Optional.from(rowType.subType) : Optional.none();
  5406. });
  5407. };
  5408. var transformCell = function (cell, comparator, substitution) {
  5409. return elementnew(substitution(cell.element, comparator), true, cell.isLocked);
  5410. };
  5411. var transformRow = function (row, section) {
  5412. return row.section !== section ? rowcells(row.element, row.cells, section, row.isNew) : row;
  5413. };
  5414. var section = function () {
  5415. return {
  5416. transformRow: transformRow,
  5417. transformCell: function (cell, comparator, substitution) {
  5418. var newCell = substitution(cell.element, comparator);
  5419. var fixedCell = name(newCell) !== 'td' ? mutate$1(newCell, 'td') : newCell;
  5420. return elementnew(fixedCell, cell.isNew, cell.isLocked);
  5421. }
  5422. };
  5423. };
  5424. var sectionCells = function () {
  5425. return {
  5426. transformRow: transformRow,
  5427. transformCell: transformCell
  5428. };
  5429. };
  5430. var cells = function () {
  5431. return {
  5432. transformRow: function (row, section) {
  5433. var newSection = section === 'thead' ? 'tbody' : section;
  5434. return transformRow(row, newSection);
  5435. },
  5436. transformCell: transformCell
  5437. };
  5438. };
  5439. var fallback = function () {
  5440. return {
  5441. transformRow: identity,
  5442. transformCell: transformCell
  5443. };
  5444. };
  5445. var getTableSectionType = function (table, fallback) {
  5446. var warehouse = Warehouse.fromTable(table);
  5447. var type = findTableRowHeaderType(warehouse).getOr(fallback);
  5448. switch (type) {
  5449. case 'section':
  5450. return section();
  5451. case 'sectionCells':
  5452. return sectionCells();
  5453. case 'cells':
  5454. return cells();
  5455. }
  5456. };
  5457. var TableSection = {
  5458. getTableSectionType: getTableSectionType,
  5459. section: section,
  5460. sectionCells: sectionCells,
  5461. cells: cells,
  5462. fallback: fallback
  5463. };
  5464. var setIfNot = function (element, property, value, ignore) {
  5465. if (value === ignore) {
  5466. remove$7(element, property);
  5467. } else {
  5468. set$2(element, property, value);
  5469. }
  5470. };
  5471. var insert$1 = function (table, selector, element) {
  5472. last$2(children$1(table, selector)).fold(function () {
  5473. return prepend(table, element);
  5474. }, function (child) {
  5475. return after$5(child, element);
  5476. });
  5477. };
  5478. var generateSection = function (table, sectionName) {
  5479. var section = child$1(table, sectionName).getOrThunk(function () {
  5480. var newSection = SugarElement.fromTag(sectionName, owner(table).dom);
  5481. if (sectionName === 'thead') {
  5482. insert$1(table, 'caption,colgroup', newSection);
  5483. } else if (sectionName === 'colgroup') {
  5484. insert$1(table, 'caption', newSection);
  5485. } else {
  5486. append$1(table, newSection);
  5487. }
  5488. return newSection;
  5489. });
  5490. empty(section);
  5491. return section;
  5492. };
  5493. var render$1 = function (table, grid) {
  5494. var newRows = [];
  5495. var newCells = [];
  5496. var syncRows = function (gridSection) {
  5497. return map$1(gridSection, function (row) {
  5498. if (row.isNew) {
  5499. newRows.push(row.element);
  5500. }
  5501. var tr = row.element;
  5502. empty(tr);
  5503. each$2(row.cells, function (cell) {
  5504. if (cell.isNew) {
  5505. newCells.push(cell.element);
  5506. }
  5507. setIfNot(cell.element, 'colspan', cell.colspan, 1);
  5508. setIfNot(cell.element, 'rowspan', cell.rowspan, 1);
  5509. append$1(tr, cell.element);
  5510. });
  5511. return tr;
  5512. });
  5513. };
  5514. var syncColGroup = function (gridSection) {
  5515. return bind$2(gridSection, function (colGroup) {
  5516. return map$1(colGroup.cells, function (col) {
  5517. setIfNot(col.element, 'span', col.colspan, 1);
  5518. return col.element;
  5519. });
  5520. });
  5521. };
  5522. var renderSection = function (gridSection, sectionName) {
  5523. var section = generateSection(table, sectionName);
  5524. var sync = sectionName === 'colgroup' ? syncColGroup : syncRows;
  5525. var sectionElems = sync(gridSection);
  5526. append(section, sectionElems);
  5527. };
  5528. var removeSection = function (sectionName) {
  5529. child$1(table, sectionName).each(remove$5);
  5530. };
  5531. var renderOrRemoveSection = function (gridSection, sectionName) {
  5532. if (gridSection.length > 0) {
  5533. renderSection(gridSection, sectionName);
  5534. } else {
  5535. removeSection(sectionName);
  5536. }
  5537. };
  5538. var headSection = [];
  5539. var bodySection = [];
  5540. var footSection = [];
  5541. var columnGroupsSection = [];
  5542. each$2(grid, function (row) {
  5543. switch (row.section) {
  5544. case 'thead':
  5545. headSection.push(row);
  5546. break;
  5547. case 'tbody':
  5548. bodySection.push(row);
  5549. break;
  5550. case 'tfoot':
  5551. footSection.push(row);
  5552. break;
  5553. case 'colgroup':
  5554. columnGroupsSection.push(row);
  5555. break;
  5556. }
  5557. });
  5558. renderOrRemoveSection(columnGroupsSection, 'colgroup');
  5559. renderOrRemoveSection(headSection, 'thead');
  5560. renderOrRemoveSection(bodySection, 'tbody');
  5561. renderOrRemoveSection(footSection, 'tfoot');
  5562. return {
  5563. newRows: newRows,
  5564. newCells: newCells
  5565. };
  5566. };
  5567. var copy = function (grid) {
  5568. return map$1(grid, function (row) {
  5569. var tr = shallow(row.element);
  5570. each$2(row.cells, function (cell) {
  5571. var clonedCell = deep(cell.element);
  5572. setIfNot(clonedCell, 'colspan', cell.colspan, 1);
  5573. setIfNot(clonedCell, 'rowspan', cell.rowspan, 1);
  5574. append$1(tr, clonedCell);
  5575. });
  5576. return tr;
  5577. });
  5578. };
  5579. var getColumn = function (grid, index) {
  5580. return map$1(grid, function (row) {
  5581. return getCell(row, index);
  5582. });
  5583. };
  5584. var getRow = function (grid, index) {
  5585. return grid[index];
  5586. };
  5587. var findDiff = function (xs, comp) {
  5588. if (xs.length === 0) {
  5589. return 0;
  5590. }
  5591. var first = xs[0];
  5592. var index = findIndex(xs, function (x) {
  5593. return !comp(first.element, x.element);
  5594. });
  5595. return index.getOr(xs.length);
  5596. };
  5597. var subgrid = function (grid, row, column, comparator) {
  5598. var gridRow = getRow(grid, row);
  5599. var isColRow = gridRow.section === 'colgroup';
  5600. var colspan = findDiff(gridRow.cells.slice(column), comparator);
  5601. var rowspan = isColRow ? 1 : findDiff(getColumn(grid.slice(row), column), comparator);
  5602. return {
  5603. colspan: colspan,
  5604. rowspan: rowspan
  5605. };
  5606. };
  5607. var toDetails = function (grid, comparator) {
  5608. var seen = map$1(grid, function (row) {
  5609. return map$1(row.cells, never);
  5610. });
  5611. var updateSeen = function (rowIndex, columnIndex, rowspan, colspan) {
  5612. for (var row = rowIndex; row < rowIndex + rowspan; row++) {
  5613. for (var column = columnIndex; column < columnIndex + colspan; column++) {
  5614. seen[row][column] = true;
  5615. }
  5616. }
  5617. };
  5618. return map$1(grid, function (row, rowIndex) {
  5619. var details = bind$2(row.cells, function (cell, columnIndex) {
  5620. if (seen[rowIndex][columnIndex] === false) {
  5621. var result = subgrid(grid, rowIndex, columnIndex, comparator);
  5622. updateSeen(rowIndex, columnIndex, result.rowspan, result.colspan);
  5623. return [detailnew(cell.element, result.rowspan, result.colspan, cell.isNew)];
  5624. } else {
  5625. return [];
  5626. }
  5627. });
  5628. return rowdetailnew(row.element, details, row.section, row.isNew);
  5629. });
  5630. };
  5631. var toGrid = function (warehouse, generators, isNew) {
  5632. var grid = [];
  5633. each$2(warehouse.colgroups, function (colgroup) {
  5634. var colgroupCols = [];
  5635. for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
  5636. var element = Warehouse.getColumnAt(warehouse, columnIndex).map(function (column) {
  5637. return elementnew(column.element, isNew, false);
  5638. }).getOrThunk(function () {
  5639. return elementnew(generators.colGap(), true, false);
  5640. });
  5641. colgroupCols.push(element);
  5642. }
  5643. grid.push(rowcells(colgroup.element, colgroupCols, 'colgroup', isNew));
  5644. });
  5645. for (var rowIndex = 0; rowIndex < warehouse.grid.rows; rowIndex++) {
  5646. var rowCells = [];
  5647. for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
  5648. var element = Warehouse.getAt(warehouse, rowIndex, columnIndex).map(function (item) {
  5649. return elementnew(item.element, isNew, item.isLocked);
  5650. }).getOrThunk(function () {
  5651. return elementnew(generators.gap(), true, false);
  5652. });
  5653. rowCells.push(element);
  5654. }
  5655. var rowDetail = warehouse.all[rowIndex];
  5656. var row = rowcells(rowDetail.element, rowCells, rowDetail.section, isNew);
  5657. grid.push(row);
  5658. }
  5659. return grid;
  5660. };
  5661. var fromWarehouse = function (warehouse, generators) {
  5662. return toGrid(warehouse, generators, false);
  5663. };
  5664. var toDetailList = function (grid) {
  5665. return toDetails(grid, eq$1);
  5666. };
  5667. var findInWarehouse = function (warehouse, element) {
  5668. return findMap(warehouse.all, function (r) {
  5669. return find$1(r.cells, function (e) {
  5670. return eq$1(element, e.element);
  5671. });
  5672. });
  5673. };
  5674. var extractCells = function (warehouse, target, predicate) {
  5675. var details = map$1(target.selection, function (cell$1) {
  5676. return cell(cell$1).bind(function (lc) {
  5677. return findInWarehouse(warehouse, lc);
  5678. }).filter(predicate);
  5679. });
  5680. var cells = cat(details);
  5681. return someIf(cells.length > 0, cells);
  5682. };
  5683. var run = function (operation, extract, adjustment, postAction, genWrappers) {
  5684. return function (wire, table, target, generators, behaviours) {
  5685. var warehouse = Warehouse.fromTable(table);
  5686. var tableSection = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.section).getOrThunk(TableSection.fallback);
  5687. var output = extract(warehouse, target).map(function (info) {
  5688. var model = fromWarehouse(warehouse, generators);
  5689. var result = operation(model, info, eq$1, genWrappers(generators), tableSection);
  5690. var lockedColumns = getLockedColumnsFromGrid(result.grid);
  5691. var grid = toDetailList(result.grid);
  5692. return {
  5693. info: info,
  5694. grid: grid,
  5695. cursor: result.cursor,
  5696. lockedColumns: lockedColumns
  5697. };
  5698. });
  5699. return output.bind(function (out) {
  5700. var newElements = render$1(table, out.grid);
  5701. var tableSizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.sizing).getOrThunk(function () {
  5702. return TableSize.getTableSize(table);
  5703. });
  5704. var resizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.resize).getOrThunk(preserveTable);
  5705. adjustment(table, out.grid, out.info, {
  5706. sizing: tableSizing,
  5707. resize: resizing,
  5708. section: tableSection
  5709. });
  5710. postAction(table);
  5711. refresh(wire, table);
  5712. remove$7(table, LOCKED_COL_ATTR);
  5713. if (out.lockedColumns.length > 0) {
  5714. set$2(table, LOCKED_COL_ATTR, out.lockedColumns.join(','));
  5715. }
  5716. return Optional.some({
  5717. cursor: out.cursor,
  5718. newRows: newElements.newRows,
  5719. newCells: newElements.newCells
  5720. });
  5721. });
  5722. };
  5723. };
  5724. var onPaste = function (warehouse, target) {
  5725. return cell(target.element).bind(function (cell) {
  5726. return findInWarehouse(warehouse, cell).map(function (details) {
  5727. var value = __assign(__assign({}, details), {
  5728. generators: target.generators,
  5729. clipboard: target.clipboard
  5730. });
  5731. return value;
  5732. });
  5733. });
  5734. };
  5735. var onPasteByEditor = function (warehouse, target) {
  5736. return extractCells(warehouse, target, always).map(function (cells) {
  5737. return {
  5738. cells: cells,
  5739. generators: target.generators,
  5740. clipboard: target.clipboard
  5741. };
  5742. });
  5743. };
  5744. var onMergable = function (_warehouse, target) {
  5745. return target.mergable;
  5746. };
  5747. var onUnmergable = function (_warehouse, target) {
  5748. return target.unmergable;
  5749. };
  5750. var onCells = function (warehouse, target) {
  5751. return extractCells(warehouse, target, always);
  5752. };
  5753. var onUnlockedCells = function (warehouse, target) {
  5754. return extractCells(warehouse, target, function (detail) {
  5755. return !detail.isLocked;
  5756. });
  5757. };
  5758. var isUnlockedTableCell = function (warehouse, cell) {
  5759. return findInWarehouse(warehouse, cell).exists(function (detail) {
  5760. return !detail.isLocked;
  5761. });
  5762. };
  5763. var allUnlocked = function (warehouse, cells) {
  5764. return forall(cells, function (cell) {
  5765. return isUnlockedTableCell(warehouse, cell);
  5766. });
  5767. };
  5768. var onUnlockedMergable = function (warehouse, target) {
  5769. return onMergable(warehouse, target).filter(function (mergeable) {
  5770. return allUnlocked(warehouse, mergeable.cells);
  5771. });
  5772. };
  5773. var onUnlockedUnmergable = function (warehouse, target) {
  5774. return onUnmergable(warehouse, target).filter(function (cells) {
  5775. return allUnlocked(warehouse, cells);
  5776. });
  5777. };
  5778. var merge$2 = function (grid, bounds, comparator, substitution) {
  5779. var rows = extractGridDetails(grid).rows;
  5780. if (rows.length === 0) {
  5781. return grid;
  5782. }
  5783. for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
  5784. for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
  5785. var row = rows[i];
  5786. var isLocked = getCell(row, j).isLocked;
  5787. mutateCell(row, j, elementnew(substitution(), false, isLocked));
  5788. }
  5789. }
  5790. return grid;
  5791. };
  5792. var unmerge = function (grid, target, comparator, substitution) {
  5793. var rows = extractGridDetails(grid).rows;
  5794. var first = true;
  5795. for (var i = 0; i < rows.length; i++) {
  5796. for (var j = 0; j < cellLength(rows[0]); j++) {
  5797. var row = rows[i];
  5798. var currentCell = getCell(row, j);
  5799. var currentCellElm = currentCell.element;
  5800. var isToReplace = comparator(currentCellElm, target);
  5801. if (isToReplace === true && first === false) {
  5802. mutateCell(row, j, elementnew(substitution(), true, currentCell.isLocked));
  5803. } else if (isToReplace === true) {
  5804. first = false;
  5805. }
  5806. }
  5807. }
  5808. return grid;
  5809. };
  5810. var uniqueCells = function (row, comparator) {
  5811. return foldl(row, function (rest, cell) {
  5812. return exists(rest, function (currentCell) {
  5813. return comparator(currentCell.element, cell.element);
  5814. }) ? rest : rest.concat([cell]);
  5815. }, []);
  5816. };
  5817. var splitCols = function (grid, index, comparator, substitution) {
  5818. if (index > 0 && index < grid[0].cells.length) {
  5819. each$2(grid, function (row) {
  5820. var prevCell = row.cells[index - 1];
  5821. var current = row.cells[index];
  5822. var isToReplace = comparator(current.element, prevCell.element);
  5823. if (isToReplace) {
  5824. mutateCell(row, index, elementnew(substitution(), true, current.isLocked));
  5825. }
  5826. });
  5827. }
  5828. return grid;
  5829. };
  5830. var splitRows = function (grid, index, comparator, substitution) {
  5831. var rows = extractGridDetails(grid).rows;
  5832. if (index > 0 && index < rows.length) {
  5833. var rowPrevCells = rows[index - 1].cells;
  5834. var cells = uniqueCells(rowPrevCells, comparator);
  5835. each$2(cells, function (cell) {
  5836. var replacement = Optional.none();
  5837. for (var i = index; i < rows.length; i++) {
  5838. var _loop_1 = function (j) {
  5839. var row = rows[i];
  5840. var current = getCell(row, j);
  5841. var isToReplace = comparator(current.element, cell.element);
  5842. if (isToReplace) {
  5843. if (replacement.isNone()) {
  5844. replacement = Optional.some(substitution());
  5845. }
  5846. replacement.each(function (sub) {
  5847. mutateCell(row, j, elementnew(sub, true, current.isLocked));
  5848. });
  5849. }
  5850. };
  5851. for (var j = 0; j < cellLength(rows[0]); j++) {
  5852. _loop_1(j);
  5853. }
  5854. }
  5855. });
  5856. }
  5857. return grid;
  5858. };
  5859. var value$1 = function (o) {
  5860. var or = function (_opt) {
  5861. return value$1(o);
  5862. };
  5863. var orThunk = function (_f) {
  5864. return value$1(o);
  5865. };
  5866. var map = function (f) {
  5867. return value$1(f(o));
  5868. };
  5869. var mapError = function (_f) {
  5870. return value$1(o);
  5871. };
  5872. var each = function (f) {
  5873. f(o);
  5874. };
  5875. var bind = function (f) {
  5876. return f(o);
  5877. };
  5878. var fold = function (_, onValue) {
  5879. return onValue(o);
  5880. };
  5881. var exists = function (f) {
  5882. return f(o);
  5883. };
  5884. var forall = function (f) {
  5885. return f(o);
  5886. };
  5887. var toOptional = function () {
  5888. return Optional.some(o);
  5889. };
  5890. return {
  5891. isValue: always,
  5892. isError: never,
  5893. getOr: constant(o),
  5894. getOrThunk: constant(o),
  5895. getOrDie: constant(o),
  5896. or: or,
  5897. orThunk: orThunk,
  5898. fold: fold,
  5899. map: map,
  5900. mapError: mapError,
  5901. each: each,
  5902. bind: bind,
  5903. exists: exists,
  5904. forall: forall,
  5905. toOptional: toOptional
  5906. };
  5907. };
  5908. var error = function (message) {
  5909. var getOrThunk = function (f) {
  5910. return f();
  5911. };
  5912. var getOrDie = function () {
  5913. return die(String(message))();
  5914. };
  5915. var or = identity;
  5916. var orThunk = function (f) {
  5917. return f();
  5918. };
  5919. var map = function (_f) {
  5920. return error(message);
  5921. };
  5922. var mapError = function (f) {
  5923. return error(f(message));
  5924. };
  5925. var bind = function (_f) {
  5926. return error(message);
  5927. };
  5928. var fold = function (onError, _) {
  5929. return onError(message);
  5930. };
  5931. return {
  5932. isValue: never,
  5933. isError: always,
  5934. getOr: identity,
  5935. getOrThunk: getOrThunk,
  5936. getOrDie: getOrDie,
  5937. or: or,
  5938. orThunk: orThunk,
  5939. fold: fold,
  5940. map: map,
  5941. mapError: mapError,
  5942. each: noop,
  5943. bind: bind,
  5944. exists: never,
  5945. forall: always,
  5946. toOptional: Optional.none
  5947. };
  5948. };
  5949. var fromOption = function (opt, err) {
  5950. return opt.fold(function () {
  5951. return error(err);
  5952. }, value$1);
  5953. };
  5954. var Result = {
  5955. value: value$1,
  5956. error: error,
  5957. fromOption: fromOption
  5958. };
  5959. var measure = function (startAddress, gridA, gridB) {
  5960. if (startAddress.row >= gridA.length || startAddress.column > cellLength(gridA[0])) {
  5961. return Result.error('invalid start address out of table bounds, row: ' + startAddress.row + ', column: ' + startAddress.column);
  5962. }
  5963. var rowRemainder = gridA.slice(startAddress.row);
  5964. var colRemainder = rowRemainder[0].cells.slice(startAddress.column);
  5965. var colRequired = cellLength(gridB[0]);
  5966. var rowRequired = gridB.length;
  5967. return Result.value({
  5968. rowDelta: rowRemainder.length - rowRequired,
  5969. colDelta: colRemainder.length - colRequired
  5970. });
  5971. };
  5972. var measureWidth = function (gridA, gridB) {
  5973. var colLengthA = cellLength(gridA[0]);
  5974. var colLengthB = cellLength(gridB[0]);
  5975. return {
  5976. rowDelta: 0,
  5977. colDelta: colLengthA - colLengthB
  5978. };
  5979. };
  5980. var measureHeight = function (gridA, gridB) {
  5981. var rowLengthA = gridA.length;
  5982. var rowLengthB = gridB.length;
  5983. return {
  5984. rowDelta: rowLengthA - rowLengthB,
  5985. colDelta: 0
  5986. };
  5987. };
  5988. var generateElements = function (amount, row, generators, isLocked) {
  5989. var generator = row.section === 'colgroup' ? generators.col : generators.cell;
  5990. return range$1(amount, function (idx) {
  5991. return elementnew(generator(), true, isLocked(idx));
  5992. });
  5993. };
  5994. var rowFill = function (grid, amount, generators, lockedColumns) {
  5995. var exampleRow = grid[grid.length - 1];
  5996. return grid.concat(range$1(amount, function () {
  5997. var generator = exampleRow.section === 'colgroup' ? generators.colgroup : generators.row;
  5998. var row = clone$1(exampleRow, generator, identity);
  5999. var elements = generateElements(row.cells.length, row, generators, function (idx) {
  6000. return has$1(lockedColumns, idx.toString());
  6001. });
  6002. return setCells(row, elements);
  6003. }));
  6004. };
  6005. var colFill = function (grid, amount, generators, startIndex) {
  6006. return map$1(grid, function (row) {
  6007. var newChildren = generateElements(amount, row, generators, never);
  6008. return addCells(row, startIndex, newChildren);
  6009. });
  6010. };
  6011. var lockedColFill = function (grid, generators, lockedColumns) {
  6012. return map$1(grid, function (row) {
  6013. return foldl(lockedColumns, function (acc, colNum) {
  6014. var newChild = generateElements(1, row, generators, always)[0];
  6015. return addCell(acc, colNum, newChild);
  6016. }, row);
  6017. });
  6018. };
  6019. var tailor = function (gridA, delta, generators) {
  6020. var fillCols = delta.colDelta < 0 ? colFill : identity;
  6021. var fillRows = delta.rowDelta < 0 ? rowFill : identity;
  6022. var lockedColumns = getLockedColumnsFromGrid(gridA);
  6023. var gridWidth = cellLength(gridA[0]);
  6024. var isLastColLocked = exists(lockedColumns, function (locked) {
  6025. return locked === gridWidth - 1;
  6026. });
  6027. var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta), generators, isLastColLocked ? gridWidth - 1 : gridWidth);
  6028. var newLockedColumns = getLockedColumnsFromGrid(modifiedCols);
  6029. return fillRows(modifiedCols, Math.abs(delta.rowDelta), generators, mapToObject(newLockedColumns, always));
  6030. };
  6031. var isSpanning = function (grid, row, col, comparator) {
  6032. var candidate = getCell(grid[row], col);
  6033. var matching = curry(comparator, candidate.element);
  6034. var currentRow = grid[row];
  6035. 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)));
  6036. };
  6037. var mergeTables = function (startAddress, gridA, gridB, generator, comparator, lockedColumns) {
  6038. var startRow = startAddress.row;
  6039. var startCol = startAddress.column;
  6040. var mergeHeight = gridB.length;
  6041. var mergeWidth = cellLength(gridB[0]);
  6042. var endRow = startRow + mergeHeight;
  6043. var endCol = startCol + mergeWidth + lockedColumns.length;
  6044. var lockedColumnObj = mapToObject(lockedColumns, always);
  6045. for (var r = startRow; r < endRow; r++) {
  6046. var skippedCol = 0;
  6047. for (var c = startCol; c < endCol; c++) {
  6048. if (lockedColumnObj[c]) {
  6049. skippedCol++;
  6050. continue;
  6051. }
  6052. if (isSpanning(gridA, r, c, comparator)) {
  6053. unmerge(gridA, getCellElement(gridA[r], c), comparator, generator.cell);
  6054. }
  6055. var gridBColIndex = c - startCol - skippedCol;
  6056. var newCell = getCell(gridB[r - startRow], gridBColIndex);
  6057. var newCellElm = newCell.element;
  6058. var replacement = generator.replace(newCellElm);
  6059. mutateCell(gridA[r], c, elementnew(replacement, true, newCell.isLocked));
  6060. }
  6061. }
  6062. return gridA;
  6063. };
  6064. var getValidStartAddress = function (currentStartAddress, grid, lockedColumns) {
  6065. var gridColLength = cellLength(grid[0]);
  6066. var adjustedRowAddress = extractGridDetails(grid).cols.length + currentStartAddress.row;
  6067. var possibleColAddresses = range$1(gridColLength - currentStartAddress.column, function (num) {
  6068. return num + currentStartAddress.column;
  6069. });
  6070. var validColAddress = find$1(possibleColAddresses, function (num) {
  6071. return forall(lockedColumns, function (col) {
  6072. return col !== num;
  6073. });
  6074. }).getOr(gridColLength - 1);
  6075. return {
  6076. row: adjustedRowAddress,
  6077. column: validColAddress
  6078. };
  6079. };
  6080. var getLockedColumnsWithinBounds = function (startAddress, grid, lockedColumns) {
  6081. return filter$2(lockedColumns, function (colNum) {
  6082. return colNum >= startAddress.column && colNum <= cellLength(grid[0]) + startAddress.column;
  6083. });
  6084. };
  6085. var merge$1 = function (startAddress, gridA, gridB, generator, comparator) {
  6086. var lockedColumns = getLockedColumnsFromGrid(gridA);
  6087. var validStartAddress = getValidStartAddress(startAddress, gridA, lockedColumns);
  6088. var gridBRows = extractGridDetails(gridB).rows;
  6089. var lockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, lockedColumns);
  6090. var result = measure(validStartAddress, gridA, gridBRows);
  6091. return result.map(function (diff) {
  6092. var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - lockedColumnsWithinBounds.length });
  6093. var fittedGrid = tailor(gridA, delta, generator);
  6094. var newLockedColumns = getLockedColumnsFromGrid(fittedGrid);
  6095. var newLockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, newLockedColumns);
  6096. return mergeTables(validStartAddress, fittedGrid, gridBRows, generator, comparator, newLockedColumnsWithinBounds);
  6097. });
  6098. };
  6099. var insertCols = function (index, gridA, gridB, generator, comparator) {
  6100. splitCols(gridA, index, comparator, generator.cell);
  6101. var delta = measureHeight(gridB, gridA);
  6102. var fittedNewGrid = tailor(gridB, delta, generator);
  6103. var secondDelta = measureHeight(gridA, fittedNewGrid);
  6104. var fittedOldGrid = tailor(gridA, secondDelta, generator);
  6105. return map$1(fittedOldGrid, function (gridRow, i) {
  6106. return addCells(gridRow, index, fittedNewGrid[i].cells);
  6107. });
  6108. };
  6109. var insertRows = function (index, gridA, gridB, generator, comparator) {
  6110. splitRows(gridA, index, comparator, generator.cell);
  6111. var locked = getLockedColumnsFromGrid(gridA);
  6112. var diff = measureWidth(gridA, gridB);
  6113. var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - locked.length });
  6114. var fittedOldGrid = tailor(gridA, delta, generator);
  6115. var _a = extractGridDetails(fittedOldGrid), oldCols = _a.cols, oldRows = _a.rows;
  6116. var newLocked = getLockedColumnsFromGrid(fittedOldGrid);
  6117. var secondDiff = measureWidth(gridB, gridA);
  6118. var secondDelta = __assign(__assign({}, secondDiff), { colDelta: secondDiff.colDelta + newLocked.length });
  6119. var fittedGridB = lockedColFill(gridB, generator, newLocked);
  6120. var fittedNewGrid = tailor(fittedGridB, secondDelta, generator);
  6121. return oldCols.concat(oldRows.slice(0, index)).concat(fittedNewGrid).concat(oldRows.slice(index, oldRows.length));
  6122. };
  6123. var cloneRow = function (row, cloneCell, comparator, substitution) {
  6124. return clone$1(row, function (elem) {
  6125. return substitution(elem, comparator);
  6126. }, cloneCell);
  6127. };
  6128. var insertRowAt = function (grid, index, example, comparator, substitution) {
  6129. var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
  6130. var before = rows.slice(0, index);
  6131. var after = rows.slice(index);
  6132. var newRow = cloneRow(rows[example], function (ex, c) {
  6133. var withinSpan = index > 0 && index < rows.length && comparator(getCellElement(rows[index - 1], c), getCellElement(rows[index], c));
  6134. var ret = withinSpan ? getCell(rows[index], c) : elementnew(substitution(ex.element, comparator), true, ex.isLocked);
  6135. return ret;
  6136. }, comparator, substitution);
  6137. return cols.concat(before).concat([newRow]).concat(after);
  6138. };
  6139. var getElementFor = function (row, column, section, withinSpan, example, comparator, substitution) {
  6140. if (section === 'colgroup' || !withinSpan) {
  6141. var cell = getCell(row, example);
  6142. return elementnew(substitution(cell.element, comparator), true, false);
  6143. } else {
  6144. return getCell(row, column);
  6145. }
  6146. };
  6147. var insertColumnAt = function (grid, index, example, comparator, substitution) {
  6148. return map$1(grid, function (row) {
  6149. var withinSpan = index > 0 && index < cellLength(row) && comparator(getCellElement(row, index - 1), getCellElement(row, index));
  6150. var sub = getElementFor(row, index, row.section, withinSpan, example, comparator, substitution);
  6151. return addCell(row, index, sub);
  6152. });
  6153. };
  6154. var deleteColumnsAt = function (grid, columns) {
  6155. return bind$2(grid, function (row) {
  6156. var existingCells = row.cells;
  6157. var cells = foldr(columns, function (acc, column) {
  6158. return column >= 0 && column < acc.length ? acc.slice(0, column).concat(acc.slice(column + 1)) : acc;
  6159. }, existingCells);
  6160. return cells.length > 0 ? [rowcells(row.element, cells, row.section, row.isNew)] : [];
  6161. });
  6162. };
  6163. var deleteRowsAt = function (grid, start, finish) {
  6164. var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
  6165. return cols.concat(rows.slice(0, start)).concat(rows.slice(finish + 1));
  6166. };
  6167. var notInStartRow = function (grid, rowIndex, colIndex, comparator) {
  6168. return getCellElement(grid[rowIndex], colIndex) !== undefined && (rowIndex > 0 && comparator(getCellElement(grid[rowIndex - 1], colIndex), getCellElement(grid[rowIndex], colIndex)));
  6169. };
  6170. var notInStartColumn = function (row, index, comparator) {
  6171. return index > 0 && comparator(getCellElement(row, index - 1), getCellElement(row, index));
  6172. };
  6173. var isDuplicatedCell = function (grid, rowIndex, colIndex, comparator) {
  6174. return notInStartRow(grid, rowIndex, colIndex, comparator) || notInStartColumn(grid[rowIndex], colIndex, comparator);
  6175. };
  6176. var rowReplacerPredicate = function (targetRow, columnHeaders) {
  6177. var entireTableIsHeader = forall(columnHeaders, identity) && isHeaderCells(targetRow.cells);
  6178. return entireTableIsHeader ? always : function (cell, _rowIndex, colIndex) {
  6179. var type = name(cell.element);
  6180. return !(type === 'th' && columnHeaders[colIndex]);
  6181. };
  6182. };
  6183. var columnReplacePredicate = function (targetColumn, rowHeaders) {
  6184. var entireTableIsHeader = forall(rowHeaders, identity) && isHeaderCells(targetColumn);
  6185. return entireTableIsHeader ? always : function (cell, rowIndex, _colIndex) {
  6186. var type = name(cell.element);
  6187. return !(type === 'th' && rowHeaders[rowIndex]);
  6188. };
  6189. };
  6190. var determineScope = function (applyScope, element, newScope, isInHeader) {
  6191. var hasSpan = function (scope) {
  6192. return scope === 'row' ? hasRowspan(element) : hasColspan(element);
  6193. };
  6194. var getScope = function (scope) {
  6195. return hasSpan(scope) ? scope + 'group' : scope;
  6196. };
  6197. if (applyScope) {
  6198. return isHeaderCell(element) ? getScope(newScope) : null;
  6199. } else if (isInHeader && isHeaderCell(element)) {
  6200. var oppositeScope = newScope === 'row' ? 'col' : 'row';
  6201. return getScope(oppositeScope);
  6202. } else {
  6203. return null;
  6204. }
  6205. };
  6206. var rowScopeGenerator = function (applyScope, columnHeaders) {
  6207. return function (cell, rowIndex, columnIndex) {
  6208. return Optional.some(determineScope(applyScope, cell.element, 'col', columnHeaders[columnIndex]));
  6209. };
  6210. };
  6211. var columnScopeGenerator = function (applyScope, rowHeaders) {
  6212. return function (cell, rowIndex) {
  6213. return Optional.some(determineScope(applyScope, cell.element, 'row', rowHeaders[rowIndex]));
  6214. };
  6215. };
  6216. var replace = function (cell, comparator, substitute) {
  6217. return elementnew(substitute(cell.element, comparator), true, cell.isLocked);
  6218. };
  6219. var replaceIn = function (grid, targets, comparator, substitute, replacer, genScope, shouldReplace) {
  6220. var isTarget = function (cell) {
  6221. return exists(targets, function (target) {
  6222. return comparator(cell.element, target.element);
  6223. });
  6224. };
  6225. return map$1(grid, function (row, rowIndex) {
  6226. return mapCells(row, function (cell, colIndex) {
  6227. if (isTarget(cell)) {
  6228. var newCell_1 = shouldReplace(cell, rowIndex, colIndex) ? replacer(cell, comparator, substitute) : cell;
  6229. genScope(newCell_1, rowIndex, colIndex).each(function (scope) {
  6230. setOptions(newCell_1.element, { scope: Optional.from(scope) });
  6231. });
  6232. return newCell_1;
  6233. } else {
  6234. return cell;
  6235. }
  6236. });
  6237. });
  6238. };
  6239. var getColumnCells = function (rows, columnIndex, comparator) {
  6240. return bind$2(rows, function (row, i) {
  6241. return isDuplicatedCell(rows, i, columnIndex, comparator) ? [] : [getCell(row, columnIndex)];
  6242. });
  6243. };
  6244. var getRowCells = function (rows, rowIndex, comparator) {
  6245. var targetRow = rows[rowIndex];
  6246. return bind$2(targetRow.cells, function (item, i) {
  6247. return isDuplicatedCell(rows, rowIndex, i, comparator) ? [] : [item];
  6248. });
  6249. };
  6250. var replaceColumns = function (grid, indexes, applyScope, comparator, substitution) {
  6251. var rows = extractGridDetails(grid).rows;
  6252. var targets = bind$2(indexes, function (index) {
  6253. return getColumnCells(rows, index, comparator);
  6254. });
  6255. var rowHeaders = map$1(grid, function (row) {
  6256. return isHeaderCells(row.cells);
  6257. });
  6258. var shouldReplaceCell = columnReplacePredicate(targets, rowHeaders);
  6259. var scopeGenerator = columnScopeGenerator(applyScope, rowHeaders);
  6260. return replaceIn(grid, targets, comparator, substitution, replace, scopeGenerator, shouldReplaceCell);
  6261. };
  6262. var replaceRows = function (grid, indexes, section, applyScope, comparator, substitution, tableSection) {
  6263. var _a = extractGridDetails(grid), cols = _a.cols, rows = _a.rows;
  6264. var targetRow = rows[indexes[0]];
  6265. var targets = bind$2(indexes, function (index) {
  6266. return getRowCells(rows, index, comparator);
  6267. });
  6268. var columnHeaders = map$1(targetRow.cells, function (_cell, index) {
  6269. return isHeaderCells(getColumnCells(rows, index, comparator));
  6270. });
  6271. var newRows = __spreadArray([], rows, true);
  6272. each$2(indexes, function (index) {
  6273. newRows[index] = tableSection.transformRow(rows[index], section);
  6274. });
  6275. var newGrid = cols.concat(newRows);
  6276. var shouldReplaceCell = rowReplacerPredicate(targetRow, columnHeaders);
  6277. var scopeGenerator = rowScopeGenerator(applyScope, columnHeaders);
  6278. return replaceIn(newGrid, targets, comparator, substitution, tableSection.transformCell, scopeGenerator, shouldReplaceCell);
  6279. };
  6280. var replaceCells = function (grid, details, comparator, substitution) {
  6281. var rows = extractGridDetails(grid).rows;
  6282. var targetCells = map$1(details, function (detail) {
  6283. return getCell(rows[detail.row], detail.column);
  6284. });
  6285. return replaceIn(grid, targetCells, comparator, substitution, replace, Optional.none, always);
  6286. };
  6287. var uniqueColumns = function (details) {
  6288. var uniqueCheck = function (rest, detail) {
  6289. var columnExists = exists(rest, function (currentDetail) {
  6290. return currentDetail.column === detail.column;
  6291. });
  6292. return columnExists ? rest : rest.concat([detail]);
  6293. };
  6294. return foldl(details, uniqueCheck, []).sort(function (detailA, detailB) {
  6295. return detailA.column - detailB.column;
  6296. });
  6297. };
  6298. var isCol = isTag('col');
  6299. var isColgroup = isTag('colgroup');
  6300. var isRow$1 = function (element) {
  6301. return name(element) === 'tr' || isColgroup(element);
  6302. };
  6303. var elementToData = function (element) {
  6304. var colspan = getAttrValue(element, 'colspan', 1);
  6305. var rowspan = getAttrValue(element, 'rowspan', 1);
  6306. return {
  6307. element: element,
  6308. colspan: colspan,
  6309. rowspan: rowspan
  6310. };
  6311. };
  6312. var modification = function (generators, toData) {
  6313. if (toData === void 0) {
  6314. toData = elementToData;
  6315. }
  6316. var nuCell = function (data) {
  6317. return isCol(data.element) ? generators.col(data) : generators.cell(data);
  6318. };
  6319. var nuRow = function (data) {
  6320. return isColgroup(data.element) ? generators.colgroup(data) : generators.row(data);
  6321. };
  6322. var add = function (element) {
  6323. if (isRow$1(element)) {
  6324. return nuRow({ element: element });
  6325. } else {
  6326. var replacement = nuCell(toData(element));
  6327. recent = Optional.some({
  6328. item: element,
  6329. replacement: replacement
  6330. });
  6331. return replacement;
  6332. }
  6333. };
  6334. var recent = Optional.none();
  6335. var getOrInit = function (element, comparator) {
  6336. return recent.fold(function () {
  6337. return add(element);
  6338. }, function (p) {
  6339. return comparator(element, p.item) ? p.replacement : add(element);
  6340. });
  6341. };
  6342. return { getOrInit: getOrInit };
  6343. };
  6344. var transform = function (tag) {
  6345. return function (generators) {
  6346. var list = [];
  6347. var find = function (element, comparator) {
  6348. return find$1(list, function (x) {
  6349. return comparator(x.item, element);
  6350. });
  6351. };
  6352. var makeNew = function (element) {
  6353. var attrs = tag === 'td' ? { scope: null } : {};
  6354. var cell = generators.replace(element, tag, attrs);
  6355. list.push({
  6356. item: element,
  6357. sub: cell
  6358. });
  6359. return cell;
  6360. };
  6361. var replaceOrInit = function (element, comparator) {
  6362. if (isRow$1(element) || isCol(element)) {
  6363. return element;
  6364. } else {
  6365. return find(element, comparator).fold(function () {
  6366. return makeNew(element);
  6367. }, function (p) {
  6368. return comparator(element, p.item) ? p.sub : makeNew(element);
  6369. });
  6370. }
  6371. };
  6372. return { replaceOrInit: replaceOrInit };
  6373. };
  6374. };
  6375. var getScopeAttribute = function (cell) {
  6376. return getOpt(cell, 'scope').map(function (attribute) {
  6377. return attribute.substr(0, 3);
  6378. });
  6379. };
  6380. var merging = function (generators) {
  6381. var unmerge = function (cell) {
  6382. var scope = getScopeAttribute(cell);
  6383. scope.each(function (attribute) {
  6384. return set$2(cell, 'scope', attribute);
  6385. });
  6386. return function () {
  6387. var raw = generators.cell({
  6388. element: cell,
  6389. colspan: 1,
  6390. rowspan: 1
  6391. });
  6392. remove$6(raw, 'width');
  6393. remove$6(cell, 'width');
  6394. scope.each(function (attribute) {
  6395. return set$2(raw, 'scope', attribute);
  6396. });
  6397. return raw;
  6398. };
  6399. };
  6400. var merge = function (cells) {
  6401. var getScopeProperty = function () {
  6402. var stringAttributes = cat(map$1(cells, getScopeAttribute));
  6403. if (stringAttributes.length === 0) {
  6404. return Optional.none();
  6405. } else {
  6406. var baseScope_1 = stringAttributes[0];
  6407. var scopes_1 = [
  6408. 'row',
  6409. 'col'
  6410. ];
  6411. var isMixed = exists(stringAttributes, function (attribute) {
  6412. return attribute !== baseScope_1 && contains$2(scopes_1, attribute);
  6413. });
  6414. return isMixed ? Optional.none() : Optional.from(baseScope_1);
  6415. }
  6416. };
  6417. remove$6(cells[0], 'width');
  6418. getScopeProperty().fold(function () {
  6419. return remove$7(cells[0], 'scope');
  6420. }, function (attribute) {
  6421. return set$2(cells[0], 'scope', attribute + 'group');
  6422. });
  6423. return constant(cells[0]);
  6424. };
  6425. return {
  6426. unmerge: unmerge,
  6427. merge: merge
  6428. };
  6429. };
  6430. var Generators = {
  6431. modification: modification,
  6432. transform: transform,
  6433. merging: merging
  6434. };
  6435. var blockList = [
  6436. 'body',
  6437. 'p',
  6438. 'div',
  6439. 'article',
  6440. 'aside',
  6441. 'figcaption',
  6442. 'figure',
  6443. 'footer',
  6444. 'header',
  6445. 'nav',
  6446. 'section',
  6447. 'ol',
  6448. 'ul',
  6449. 'table',
  6450. 'thead',
  6451. 'tfoot',
  6452. 'tbody',
  6453. 'caption',
  6454. 'tr',
  6455. 'td',
  6456. 'th',
  6457. 'h1',
  6458. 'h2',
  6459. 'h3',
  6460. 'h4',
  6461. 'h5',
  6462. 'h6',
  6463. 'blockquote',
  6464. 'pre',
  6465. 'address'
  6466. ];
  6467. var isList$1 = function (universe, item) {
  6468. var tagName = universe.property().name(item);
  6469. return contains$2([
  6470. 'ol',
  6471. 'ul'
  6472. ], tagName);
  6473. };
  6474. var isBlock$1 = function (universe, item) {
  6475. var tagName = universe.property().name(item);
  6476. return contains$2(blockList, tagName);
  6477. };
  6478. var isEmptyTag$1 = function (universe, item) {
  6479. return contains$2([
  6480. 'br',
  6481. 'img',
  6482. 'hr',
  6483. 'input'
  6484. ], universe.property().name(item));
  6485. };
  6486. var universe$1 = DomUniverse();
  6487. var isBlock = function (element) {
  6488. return isBlock$1(universe$1, element);
  6489. };
  6490. var isList = function (element) {
  6491. return isList$1(universe$1, element);
  6492. };
  6493. var isEmptyTag = function (element) {
  6494. return isEmptyTag$1(universe$1, element);
  6495. };
  6496. var merge = function (cells) {
  6497. var isBr = function (el) {
  6498. return name(el) === 'br';
  6499. };
  6500. var advancedBr = function (children) {
  6501. return forall(children, function (c) {
  6502. return isBr(c) || isText(c) && get$9(c).trim().length === 0;
  6503. });
  6504. };
  6505. var isListItem = function (el) {
  6506. return name(el) === 'li' || ancestor$2(el, isList).isSome();
  6507. };
  6508. var siblingIsBlock = function (el) {
  6509. return nextSibling(el).map(function (rightSibling) {
  6510. if (isBlock(rightSibling)) {
  6511. return true;
  6512. }
  6513. if (isEmptyTag(rightSibling)) {
  6514. return name(rightSibling) === 'img' ? false : true;
  6515. }
  6516. return false;
  6517. }).getOr(false);
  6518. };
  6519. var markCell = function (cell) {
  6520. return last$1(cell).bind(function (rightEdge) {
  6521. var rightSiblingIsBlock = siblingIsBlock(rightEdge);
  6522. return parent(rightEdge).map(function (parent) {
  6523. return rightSiblingIsBlock === true || isListItem(parent) || isBr(rightEdge) || isBlock(parent) && !eq$1(cell, parent) ? [] : [SugarElement.fromTag('br')];
  6524. });
  6525. }).getOr([]);
  6526. };
  6527. var markContent = function () {
  6528. var content = bind$2(cells, function (cell) {
  6529. var children = children$3(cell);
  6530. return advancedBr(children) ? [] : children.concat(markCell(cell));
  6531. });
  6532. return content.length === 0 ? [SugarElement.fromTag('br')] : content;
  6533. };
  6534. var contents = markContent();
  6535. empty(cells[0]);
  6536. append(cells[0], contents);
  6537. };
  6538. var isEditable = function (elem) {
  6539. return isEditable$1(elem, true);
  6540. };
  6541. var prune = function (table) {
  6542. var cells = cells$1(table);
  6543. if (cells.length === 0) {
  6544. remove$5(table);
  6545. }
  6546. };
  6547. var outcome = function (grid, cursor) {
  6548. return {
  6549. grid: grid,
  6550. cursor: cursor
  6551. };
  6552. };
  6553. var findEditableCursorPosition = function (rows) {
  6554. return findMap(rows, function (row) {
  6555. return findMap(row.cells, function (cell) {
  6556. var elem = cell.element;
  6557. return someIf(isEditable(elem), elem);
  6558. });
  6559. });
  6560. };
  6561. var elementFromGrid = function (grid, row, column) {
  6562. var _a, _b;
  6563. var rows = extractGridDetails(grid).rows;
  6564. 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 () {
  6565. return findEditableCursorPosition(rows);
  6566. });
  6567. };
  6568. var bundle = function (grid, row, column) {
  6569. var cursorElement = elementFromGrid(grid, row, column);
  6570. return outcome(grid, cursorElement);
  6571. };
  6572. var uniqueRows = function (details) {
  6573. var rowCompilation = function (rest, detail) {
  6574. var rowExists = exists(rest, function (currentDetail) {
  6575. return currentDetail.row === detail.row;
  6576. });
  6577. return rowExists ? rest : rest.concat([detail]);
  6578. };
  6579. return foldl(details, rowCompilation, []).sort(function (detailA, detailB) {
  6580. return detailA.row - detailB.row;
  6581. });
  6582. };
  6583. var opInsertRowsBefore = function (grid, details, comparator, genWrappers) {
  6584. var targetIndex = details[0].row;
  6585. var rows = uniqueRows(details);
  6586. var newGrid = foldr(rows, function (acc, row) {
  6587. var newG = insertRowAt(acc.grid, targetIndex, row.row + acc.delta, comparator, genWrappers.getOrInit);
  6588. return {
  6589. grid: newG,
  6590. delta: acc.delta + 1
  6591. };
  6592. }, {
  6593. grid: grid,
  6594. delta: 0
  6595. }).grid;
  6596. return bundle(newGrid, targetIndex, details[0].column);
  6597. };
  6598. var opInsertRowsAfter = function (grid, details, comparator, genWrappers) {
  6599. var rows = uniqueRows(details);
  6600. var target = rows[rows.length - 1];
  6601. var targetIndex = target.row + target.rowspan;
  6602. var newGrid = foldr(rows, function (newG, row) {
  6603. return insertRowAt(newG, targetIndex, row.row, comparator, genWrappers.getOrInit);
  6604. }, grid);
  6605. return bundle(newGrid, targetIndex, details[0].column);
  6606. };
  6607. var opInsertColumnsBefore = function (grid, extractDetail, comparator, genWrappers) {
  6608. var details = extractDetail.details;
  6609. var columns = uniqueColumns(details);
  6610. var targetIndex = columns[0].column;
  6611. var newGrid = foldr(columns, function (acc, col) {
  6612. var newG = insertColumnAt(acc.grid, targetIndex, col.column + acc.delta, comparator, genWrappers.getOrInit);
  6613. return {
  6614. grid: newG,
  6615. delta: acc.delta + 1
  6616. };
  6617. }, {
  6618. grid: grid,
  6619. delta: 0
  6620. }).grid;
  6621. return bundle(newGrid, details[0].row, targetIndex);
  6622. };
  6623. var opInsertColumnsAfter = function (grid, extractDetail, comparator, genWrappers) {
  6624. var details = extractDetail.details;
  6625. var target = details[details.length - 1];
  6626. var targetIndex = target.column + target.colspan;
  6627. var columns = uniqueColumns(details);
  6628. var newGrid = foldr(columns, function (newG, col) {
  6629. return insertColumnAt(newG, targetIndex, col.column, comparator, genWrappers.getOrInit);
  6630. }, grid);
  6631. return bundle(newGrid, details[0].row, targetIndex);
  6632. };
  6633. var opMakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
  6634. var columns = uniqueColumns(details);
  6635. var columnIndexes = map$1(columns, function (detail) {
  6636. return detail.column;
  6637. });
  6638. var newGrid = replaceColumns(initialGrid, columnIndexes, true, comparator, genWrappers.replaceOrInit);
  6639. return bundle(newGrid, details[0].row, details[0].column);
  6640. };
  6641. var opMakeCellsHeader = function (initialGrid, details, comparator, genWrappers) {
  6642. var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
  6643. return bundle(newGrid, details[0].row, details[0].column);
  6644. };
  6645. var opUnmakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
  6646. var columns = uniqueColumns(details);
  6647. var columnIndexes = map$1(columns, function (detail) {
  6648. return detail.column;
  6649. });
  6650. var newGrid = replaceColumns(initialGrid, columnIndexes, false, comparator, genWrappers.replaceOrInit);
  6651. return bundle(newGrid, details[0].row, details[0].column);
  6652. };
  6653. var opUnmakeCellsHeader = function (initialGrid, details, comparator, genWrappers) {
  6654. var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
  6655. return bundle(newGrid, details[0].row, details[0].column);
  6656. };
  6657. var makeRowsSection = function (section, applyScope) {
  6658. return function (initialGrid, details, comparator, genWrappers, tableSection) {
  6659. var rows = uniqueRows(details);
  6660. var rowIndexes = map$1(rows, function (detail) {
  6661. return detail.row;
  6662. });
  6663. var newGrid = replaceRows(initialGrid, rowIndexes, section, applyScope, comparator, genWrappers.replaceOrInit, tableSection);
  6664. return bundle(newGrid, details[0].row, details[0].column);
  6665. };
  6666. };
  6667. var opMakeRowsHeader = makeRowsSection('thead', true);
  6668. var opMakeRowsBody = makeRowsSection('tbody', false);
  6669. var opMakeRowsFooter = makeRowsSection('tfoot', false);
  6670. var opEraseColumns = function (grid, extractDetail, _comparator, _genWrappers) {
  6671. var columns = uniqueColumns(extractDetail.details);
  6672. var newGrid = deleteColumnsAt(grid, map$1(columns, function (column) {
  6673. return column.column;
  6674. }));
  6675. var maxColIndex = newGrid.length > 0 ? newGrid[0].cells.length - 1 : 0;
  6676. return bundle(newGrid, columns[0].row, Math.min(columns[0].column, maxColIndex));
  6677. };
  6678. var opEraseRows = function (grid, details, _comparator, _genWrappers) {
  6679. var rows = uniqueRows(details);
  6680. var newGrid = deleteRowsAt(grid, rows[0].row, rows[rows.length - 1].row);
  6681. var maxRowIndex = newGrid.length > 0 ? newGrid.length - 1 : 0;
  6682. return bundle(newGrid, Math.min(details[0].row, maxRowIndex), details[0].column);
  6683. };
  6684. var opMergeCells = function (grid, mergable, comparator, genWrappers) {
  6685. var cells = mergable.cells;
  6686. merge(cells);
  6687. var newGrid = merge$2(grid, mergable.bounds, comparator, genWrappers.merge(cells));
  6688. return outcome(newGrid, Optional.from(cells[0]));
  6689. };
  6690. var opUnmergeCells = function (grid, unmergable, comparator, genWrappers) {
  6691. var unmerge$1 = function (b, cell) {
  6692. return unmerge(b, cell, comparator, genWrappers.unmerge(cell));
  6693. };
  6694. var newGrid = foldr(unmergable, unmerge$1, grid);
  6695. return outcome(newGrid, Optional.from(unmergable[0]));
  6696. };
  6697. var opPasteCells = function (grid, pasteDetails, comparator, _genWrappers) {
  6698. var gridify = function (table, generators) {
  6699. var wh = Warehouse.fromTable(table);
  6700. return toGrid(wh, generators, true);
  6701. };
  6702. var gridB = gridify(pasteDetails.clipboard, pasteDetails.generators);
  6703. var startAddress = address(pasteDetails.row, pasteDetails.column);
  6704. var mergedGrid = merge$1(startAddress, grid, gridB, pasteDetails.generators, comparator);
  6705. return mergedGrid.fold(function () {
  6706. return outcome(grid, Optional.some(pasteDetails.element));
  6707. }, function (newGrid) {
  6708. return bundle(newGrid, pasteDetails.row, pasteDetails.column);
  6709. });
  6710. };
  6711. var gridifyRows = function (rows, generators, context) {
  6712. var pasteDetails = fromPastedRows(rows, context.section);
  6713. var wh = Warehouse.generate(pasteDetails);
  6714. return toGrid(wh, generators, true);
  6715. };
  6716. var opPasteColsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  6717. var rows = extractGridDetails(grid).rows;
  6718. var index = pasteDetails.cells[0].column;
  6719. var context = rows[pasteDetails.cells[0].row];
  6720. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6721. var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
  6722. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6723. };
  6724. var opPasteColsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  6725. var rows = extractGridDetails(grid).rows;
  6726. var index = pasteDetails.cells[pasteDetails.cells.length - 1].column + pasteDetails.cells[pasteDetails.cells.length - 1].colspan;
  6727. var context = rows[pasteDetails.cells[0].row];
  6728. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6729. var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
  6730. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6731. };
  6732. var opPasteRowsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  6733. var rows = extractGridDetails(grid).rows;
  6734. var index = pasteDetails.cells[0].row;
  6735. var context = rows[index];
  6736. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6737. var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
  6738. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6739. };
  6740. var opPasteRowsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  6741. var rows = extractGridDetails(grid).rows;
  6742. var index = pasteDetails.cells[pasteDetails.cells.length - 1].row + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan;
  6743. var context = rows[pasteDetails.cells[0].row];
  6744. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6745. var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
  6746. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6747. };
  6748. var opGetColumnsType = function (table, target) {
  6749. var house = Warehouse.fromTable(table);
  6750. var details = onCells(house, target);
  6751. return details.bind(function (selectedCells) {
  6752. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  6753. var minColRange = selectedCells[0].column;
  6754. var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
  6755. var selectedColumnCells = flatten$1(map$1(house.all, function (row) {
  6756. return filter$2(row.cells, function (cell) {
  6757. return cell.column >= minColRange && cell.column < maxColRange;
  6758. });
  6759. }));
  6760. return findCommonCellType(selectedColumnCells);
  6761. }).getOr('');
  6762. };
  6763. var opGetCellsType = function (table, target) {
  6764. var house = Warehouse.fromTable(table);
  6765. var details = onCells(house, target);
  6766. return details.bind(findCommonCellType).getOr('');
  6767. };
  6768. var opGetRowsType = function (table, target) {
  6769. var house = Warehouse.fromTable(table);
  6770. var details = onCells(house, target);
  6771. return details.bind(function (selectedCells) {
  6772. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  6773. var minRowRange = selectedCells[0].row;
  6774. var maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
  6775. var selectedRows = house.all.slice(minRowRange, maxRowRange);
  6776. return findCommonRowType(selectedRows);
  6777. }).getOr('');
  6778. };
  6779. var resize = function (table, list, details, behaviours) {
  6780. return adjustWidthTo(table, list, details, behaviours.sizing);
  6781. };
  6782. var adjustAndRedistributeWidths = function (table, list, details, behaviours) {
  6783. return adjustAndRedistributeWidths$1(table, list, details, behaviours.sizing, behaviours.resize);
  6784. };
  6785. var firstColumnIsLocked = function (_warehouse, details) {
  6786. return exists(details, function (detail) {
  6787. return detail.column === 0 && detail.isLocked;
  6788. });
  6789. };
  6790. var lastColumnIsLocked = function (warehouse, details) {
  6791. return exists(details, function (detail) {
  6792. return detail.column + detail.colspan >= warehouse.grid.columns && detail.isLocked;
  6793. });
  6794. };
  6795. var getColumnsWidth = function (warehouse, details) {
  6796. var columns$1 = columns(warehouse);
  6797. var uniqueCols = uniqueColumns(details);
  6798. return foldl(uniqueCols, function (acc, detail) {
  6799. var column = columns$1[detail.column];
  6800. var colWidth = column.map(getOuter$2).getOr(0);
  6801. return acc + colWidth;
  6802. }, 0);
  6803. };
  6804. var insertColumnsExtractor = function (before) {
  6805. return function (warehouse, target) {
  6806. return onCells(warehouse, target).filter(function (details) {
  6807. var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
  6808. return !checkLocked(warehouse, details);
  6809. }).map(function (details) {
  6810. return {
  6811. details: details,
  6812. pixelDelta: getColumnsWidth(warehouse, details)
  6813. };
  6814. });
  6815. };
  6816. };
  6817. var eraseColumnsExtractor = function (warehouse, target) {
  6818. return onUnlockedCells(warehouse, target).map(function (details) {
  6819. return {
  6820. details: details,
  6821. pixelDelta: -getColumnsWidth(warehouse, details)
  6822. };
  6823. });
  6824. };
  6825. var pasteColumnsExtractor = function (before) {
  6826. return function (warehouse, target) {
  6827. return onPasteByEditor(warehouse, target).filter(function (details) {
  6828. var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
  6829. return !checkLocked(warehouse, details.cells);
  6830. });
  6831. };
  6832. };
  6833. var headerCellGenerator = Generators.transform('th');
  6834. var bodyCellGenerator = Generators.transform('td');
  6835. var insertRowsBefore = run(opInsertRowsBefore, onCells, noop, noop, Generators.modification);
  6836. var insertRowsAfter = run(opInsertRowsAfter, onCells, noop, noop, Generators.modification);
  6837. var insertColumnsBefore = run(opInsertColumnsBefore, insertColumnsExtractor(true), adjustAndRedistributeWidths, noop, Generators.modification);
  6838. var insertColumnsAfter = run(opInsertColumnsAfter, insertColumnsExtractor(false), adjustAndRedistributeWidths, noop, Generators.modification);
  6839. var eraseColumns = run(opEraseColumns, eraseColumnsExtractor, adjustAndRedistributeWidths, prune, Generators.modification);
  6840. var eraseRows = run(opEraseRows, onCells, noop, prune, Generators.modification);
  6841. var makeColumnsHeader = run(opMakeColumnsHeader, onUnlockedCells, noop, noop, headerCellGenerator);
  6842. var unmakeColumnsHeader = run(opUnmakeColumnsHeader, onUnlockedCells, noop, noop, bodyCellGenerator);
  6843. var makeRowsHeader = run(opMakeRowsHeader, onUnlockedCells, noop, noop, headerCellGenerator);
  6844. var makeRowsBody = run(opMakeRowsBody, onUnlockedCells, noop, noop, bodyCellGenerator);
  6845. var makeRowsFooter = run(opMakeRowsFooter, onUnlockedCells, noop, noop, bodyCellGenerator);
  6846. var makeCellsHeader = run(opMakeCellsHeader, onUnlockedCells, noop, noop, headerCellGenerator);
  6847. var unmakeCellsHeader = run(opUnmakeCellsHeader, onUnlockedCells, noop, noop, bodyCellGenerator);
  6848. var mergeCells = run(opMergeCells, onUnlockedMergable, resize, noop, Generators.merging);
  6849. var unmergeCells = run(opUnmergeCells, onUnlockedUnmergable, resize, noop, Generators.merging);
  6850. var pasteCells = run(opPasteCells, onPaste, resize, noop, Generators.modification);
  6851. var pasteColsBefore = run(opPasteColsBefore, pasteColumnsExtractor(true), noop, noop, Generators.modification);
  6852. var pasteColsAfter = run(opPasteColsAfter, pasteColumnsExtractor(false), noop, noop, Generators.modification);
  6853. var pasteRowsBefore = run(opPasteRowsBefore, onPasteByEditor, noop, noop, Generators.modification);
  6854. var pasteRowsAfter = run(opPasteRowsAfter, onPasteByEditor, noop, noop, Generators.modification);
  6855. var getColumnsType = opGetColumnsType;
  6856. var getCellsType = opGetCellsType;
  6857. var getRowsType = opGetRowsType;
  6858. var TableActions = function (editor, cellSelection, lazyWire) {
  6859. var isTableBody = function (editor) {
  6860. return name(getBody(editor)) === 'table';
  6861. };
  6862. var lastRowGuard = function (table) {
  6863. return isTableBody(editor) === false || getGridSize(table).rows > 1;
  6864. };
  6865. var lastColumnGuard = function (table) {
  6866. return isTableBody(editor) === false || getGridSize(table).columns > 1;
  6867. };
  6868. var cloneFormats = getCloneElements(editor);
  6869. var colMutationOp = isResizeTableColumnResizing(editor) ? noop : halve;
  6870. var getTableSectionType = function (table) {
  6871. switch (getTableHeaderType(editor)) {
  6872. case 'section':
  6873. return TableSection.section();
  6874. case 'sectionCells':
  6875. return TableSection.sectionCells();
  6876. case 'cells':
  6877. return TableSection.cells();
  6878. default:
  6879. return TableSection.getTableSectionType(table, 'section');
  6880. }
  6881. };
  6882. var setSelectionFromAction = function (table, result) {
  6883. return result.cursor.fold(function () {
  6884. var cells = cells$1(table);
  6885. return head(cells).filter(inBody).map(function (firstCell) {
  6886. cellSelection.clear(table);
  6887. var rng = editor.dom.createRng();
  6888. rng.selectNode(firstCell.dom);
  6889. editor.selection.setRng(rng);
  6890. set$2(firstCell, 'data-mce-selected', '1');
  6891. return rng;
  6892. });
  6893. }, function (cell) {
  6894. var des = freefallRtl(cell);
  6895. var rng = editor.dom.createRng();
  6896. rng.setStart(des.element.dom, des.offset);
  6897. rng.setEnd(des.element.dom, des.offset);
  6898. editor.selection.setRng(rng);
  6899. cellSelection.clear(table);
  6900. return Optional.some(rng);
  6901. });
  6902. };
  6903. var execute = function (operation, guard, mutate, lazyWire, effect) {
  6904. return function (table, target, noEvents) {
  6905. if (noEvents === void 0) {
  6906. noEvents = false;
  6907. }
  6908. removeDataStyle(table);
  6909. var wire = lazyWire();
  6910. var doc = SugarElement.fromDom(editor.getDoc());
  6911. var generators = cellOperations(mutate, doc, cloneFormats);
  6912. var behaviours = {
  6913. sizing: get$4(editor, table),
  6914. resize: isResizeTableColumnResizing(editor) ? resizeTable() : preserveTable(),
  6915. section: getTableSectionType(table)
  6916. };
  6917. return guard(table) ? operation(wire, table, target, generators, behaviours).bind(function (result) {
  6918. each$2(result.newRows, function (row) {
  6919. fireNewRow(editor, row.dom);
  6920. });
  6921. each$2(result.newCells, function (cell) {
  6922. fireNewCell(editor, cell.dom);
  6923. });
  6924. var range = setSelectionFromAction(table, result);
  6925. if (inBody(table)) {
  6926. removeDataStyle(table);
  6927. if (!noEvents) {
  6928. fireTableModified(editor, table.dom, effect);
  6929. }
  6930. }
  6931. return range.map(function (rng) {
  6932. return {
  6933. rng: rng,
  6934. effect: effect
  6935. };
  6936. });
  6937. }) : Optional.none();
  6938. };
  6939. };
  6940. var deleteRow = execute(eraseRows, lastRowGuard, noop, lazyWire, structureModified);
  6941. var deleteColumn = execute(eraseColumns, lastColumnGuard, noop, lazyWire, structureModified);
  6942. var insertRowsBefore$1 = execute(insertRowsBefore, always, noop, lazyWire, structureModified);
  6943. var insertRowsAfter$1 = execute(insertRowsAfter, always, noop, lazyWire, structureModified);
  6944. var insertColumnsBefore$1 = execute(insertColumnsBefore, always, colMutationOp, lazyWire, structureModified);
  6945. var insertColumnsAfter$1 = execute(insertColumnsAfter, always, colMutationOp, lazyWire, structureModified);
  6946. var mergeCells$1 = execute(mergeCells, always, noop, lazyWire, structureModified);
  6947. var unmergeCells$1 = execute(unmergeCells, always, noop, lazyWire, structureModified);
  6948. var pasteColsBefore$1 = execute(pasteColsBefore, always, noop, lazyWire, structureModified);
  6949. var pasteColsAfter$1 = execute(pasteColsAfter, always, noop, lazyWire, structureModified);
  6950. var pasteRowsBefore$1 = execute(pasteRowsBefore, always, noop, lazyWire, structureModified);
  6951. var pasteRowsAfter$1 = execute(pasteRowsAfter, always, noop, lazyWire, structureModified);
  6952. var pasteCells$1 = execute(pasteCells, always, noop, lazyWire, styleAndStructureModified);
  6953. var makeCellsHeader$1 = execute(makeCellsHeader, always, noop, lazyWire, structureModified);
  6954. var unmakeCellsHeader$1 = execute(unmakeCellsHeader, always, noop, lazyWire, structureModified);
  6955. var makeColumnsHeader$1 = execute(makeColumnsHeader, always, noop, lazyWire, structureModified);
  6956. var unmakeColumnsHeader$1 = execute(unmakeColumnsHeader, always, noop, lazyWire, structureModified);
  6957. var makeRowsHeader$1 = execute(makeRowsHeader, always, noop, lazyWire, structureModified);
  6958. var makeRowsBody$1 = execute(makeRowsBody, always, noop, lazyWire, structureModified);
  6959. var makeRowsFooter$1 = execute(makeRowsFooter, always, noop, lazyWire, structureModified);
  6960. var getTableCellType = getCellsType;
  6961. var getTableColType = getColumnsType;
  6962. var getTableRowType = getRowsType;
  6963. return {
  6964. deleteRow: deleteRow,
  6965. deleteColumn: deleteColumn,
  6966. insertRowsBefore: insertRowsBefore$1,
  6967. insertRowsAfter: insertRowsAfter$1,
  6968. insertColumnsBefore: insertColumnsBefore$1,
  6969. insertColumnsAfter: insertColumnsAfter$1,
  6970. mergeCells: mergeCells$1,
  6971. unmergeCells: unmergeCells$1,
  6972. pasteColsBefore: pasteColsBefore$1,
  6973. pasteColsAfter: pasteColsAfter$1,
  6974. pasteRowsBefore: pasteRowsBefore$1,
  6975. pasteRowsAfter: pasteRowsAfter$1,
  6976. pasteCells: pasteCells$1,
  6977. makeCellsHeader: makeCellsHeader$1,
  6978. unmakeCellsHeader: unmakeCellsHeader$1,
  6979. makeColumnsHeader: makeColumnsHeader$1,
  6980. unmakeColumnsHeader: unmakeColumnsHeader$1,
  6981. makeRowsHeader: makeRowsHeader$1,
  6982. makeRowsBody: makeRowsBody$1,
  6983. makeRowsFooter: makeRowsFooter$1,
  6984. getTableRowType: getTableRowType,
  6985. getTableCellType: getTableCellType,
  6986. getTableColType: getTableColType
  6987. };
  6988. };
  6989. var DefaultRenderOptions = {
  6990. styles: {
  6991. 'border-collapse': 'collapse',
  6992. 'width': '100%'
  6993. },
  6994. attributes: { border: '1' },
  6995. colGroups: false
  6996. };
  6997. var tableHeaderCell = function () {
  6998. return SugarElement.fromTag('th');
  6999. };
  7000. var tableCell = function () {
  7001. return SugarElement.fromTag('td');
  7002. };
  7003. var tableColumn = function () {
  7004. return SugarElement.fromTag('col');
  7005. };
  7006. var createRow = function (columns, rowHeaders, columnHeaders, rowIndex) {
  7007. var tr = SugarElement.fromTag('tr');
  7008. for (var j = 0; j < columns; j++) {
  7009. var td = rowIndex < rowHeaders || j < columnHeaders ? tableHeaderCell() : tableCell();
  7010. if (j < columnHeaders) {
  7011. set$2(td, 'scope', 'row');
  7012. }
  7013. if (rowIndex < rowHeaders) {
  7014. set$2(td, 'scope', 'col');
  7015. }
  7016. append$1(td, SugarElement.fromTag('br'));
  7017. append$1(tr, td);
  7018. }
  7019. return tr;
  7020. };
  7021. var createGroupRow = function (columns) {
  7022. var columnGroup = SugarElement.fromTag('colgroup');
  7023. range$1(columns, function () {
  7024. return append$1(columnGroup, tableColumn());
  7025. });
  7026. return columnGroup;
  7027. };
  7028. var createRows = function (rows, columns, rowHeaders, columnHeaders) {
  7029. return range$1(rows, function (r) {
  7030. return createRow(columns, rowHeaders, columnHeaders, r);
  7031. });
  7032. };
  7033. var render = function (rows, columns, rowHeaders, columnHeaders, headerType, renderOpts) {
  7034. if (renderOpts === void 0) {
  7035. renderOpts = DefaultRenderOptions;
  7036. }
  7037. var table = SugarElement.fromTag('table');
  7038. var rowHeadersGoInThead = headerType !== 'cells';
  7039. setAll(table, renderOpts.styles);
  7040. setAll$1(table, renderOpts.attributes);
  7041. if (renderOpts.colGroups) {
  7042. append$1(table, createGroupRow(columns));
  7043. }
  7044. var actualRowHeaders = Math.min(rows, rowHeaders);
  7045. if (rowHeadersGoInThead && rowHeaders > 0) {
  7046. var thead = SugarElement.fromTag('thead');
  7047. append$1(table, thead);
  7048. var theadRowHeaders = headerType === 'sectionCells' ? actualRowHeaders : 0;
  7049. var theadRows = createRows(rowHeaders, columns, theadRowHeaders, columnHeaders);
  7050. append(thead, theadRows);
  7051. }
  7052. var tbody = SugarElement.fromTag('tbody');
  7053. append$1(table, tbody);
  7054. var numRows = rowHeadersGoInThead ? rows - actualRowHeaders : rows;
  7055. var numRowHeaders = rowHeadersGoInThead ? 0 : rowHeaders;
  7056. var tbodyRows = createRows(numRows, columns, numRowHeaders, columnHeaders);
  7057. append(tbody, tbodyRows);
  7058. return table;
  7059. };
  7060. var get$2 = function (element) {
  7061. return element.dom.innerHTML;
  7062. };
  7063. var getOuter = function (element) {
  7064. var container = SugarElement.fromTag('div');
  7065. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  7066. append$1(container, clone);
  7067. return get$2(container);
  7068. };
  7069. var placeCaretInCell = function (editor, cell) {
  7070. editor.selection.select(cell.dom, true);
  7071. editor.selection.collapse(true);
  7072. };
  7073. var selectFirstCellInTable = function (editor, tableElm) {
  7074. descendant(tableElm, 'td,th').each(curry(placeCaretInCell, editor));
  7075. };
  7076. var fireEvents = function (editor, table) {
  7077. each$2(descendants(table, 'tr'), function (row) {
  7078. fireNewRow(editor, row.dom);
  7079. each$2(descendants(row, 'th,td'), function (cell) {
  7080. fireNewCell(editor, cell.dom);
  7081. });
  7082. });
  7083. };
  7084. var isPercentage = function (width) {
  7085. return isString(width) && width.indexOf('%') !== -1;
  7086. };
  7087. var insert = function (editor, columns, rows, colHeaders, rowHeaders) {
  7088. var defaultStyles = getDefaultStyles(editor);
  7089. var options = {
  7090. styles: defaultStyles,
  7091. attributes: getDefaultAttributes(editor),
  7092. colGroups: useColumnGroup(editor)
  7093. };
  7094. editor.undoManager.ignore(function () {
  7095. var table = render(rows, columns, rowHeaders, colHeaders, getTableHeaderType(editor), options);
  7096. set$2(table, 'data-mce-id', '__mce');
  7097. var html = getOuter(table);
  7098. editor.insertContent(html);
  7099. editor.addVisual();
  7100. });
  7101. return descendant(getBody(editor), 'table[data-mce-id="__mce"]').map(function (table) {
  7102. if (isPixelsForced(editor)) {
  7103. enforcePixels(table);
  7104. } else if (isResponsiveForced(editor)) {
  7105. enforceNone(table);
  7106. } else if (isPercentagesForced(editor) || isPercentage(defaultStyles.width)) {
  7107. enforcePercentage(table);
  7108. }
  7109. removeDataStyle(table);
  7110. remove$7(table, 'data-mce-id');
  7111. fireEvents(editor, table);
  7112. selectFirstCellInTable(editor, table);
  7113. return table.dom;
  7114. }).getOr(null);
  7115. };
  7116. var insertTableWithDataValidation = function (editor, rows, columns, options, errorMsg) {
  7117. if (options === void 0) {
  7118. options = {};
  7119. }
  7120. var checkInput = function (val) {
  7121. return isNumber(val) && val > 0;
  7122. };
  7123. if (checkInput(rows) && checkInput(columns)) {
  7124. var headerRows = options.headerRows || 0;
  7125. var headerColumns = options.headerColumns || 0;
  7126. return insert(editor, columns, rows, headerColumns, headerRows);
  7127. } else {
  7128. console.error(errorMsg);
  7129. return null;
  7130. }
  7131. };
  7132. var getClipboardElements = function (getClipboard) {
  7133. return function () {
  7134. return getClipboard().fold(function () {
  7135. return [];
  7136. }, function (elems) {
  7137. return map$1(elems, function (e) {
  7138. return e.dom;
  7139. });
  7140. });
  7141. };
  7142. };
  7143. var setClipboardElements = function (setClipboard) {
  7144. return function (elems) {
  7145. var elmsOpt = elems.length > 0 ? Optional.some(fromDom(elems)) : Optional.none();
  7146. setClipboard(elmsOpt);
  7147. };
  7148. };
  7149. var insertTable = function (editor) {
  7150. return function (columns, rows, options) {
  7151. if (options === void 0) {
  7152. options = {};
  7153. }
  7154. var table = insertTableWithDataValidation(editor, rows, columns, options, 'Invalid values for insertTable - rows and columns values are required to insert a table.');
  7155. editor.undoManager.add();
  7156. return table;
  7157. };
  7158. };
  7159. var getApi = function (editor, clipboard, resizeHandler, selectionTargets) {
  7160. return {
  7161. insertTable: insertTable(editor),
  7162. setClipboardRows: setClipboardElements(clipboard.setRows),
  7163. getClipboardRows: getClipboardElements(clipboard.getRows),
  7164. setClipboardCols: setClipboardElements(clipboard.setColumns),
  7165. getClipboardCols: getClipboardElements(clipboard.getColumns),
  7166. resizeHandler: resizeHandler,
  7167. selectionTargets: selectionTargets
  7168. };
  7169. };
  7170. var constrainSpan = function (element, property, value) {
  7171. var currentColspan = getAttrValue(element, property, 1);
  7172. if (value === 1 || currentColspan <= 1) {
  7173. remove$7(element, property);
  7174. } else {
  7175. set$2(element, property, Math.min(value, currentColspan));
  7176. }
  7177. };
  7178. var generateColGroup = function (house, minColRange, maxColRange) {
  7179. if (Warehouse.hasColumns(house)) {
  7180. var colsToCopy = filter$2(Warehouse.justColumns(house), function (col) {
  7181. return col.column >= minColRange && col.column < maxColRange;
  7182. });
  7183. var copiedCols = map$1(colsToCopy, function (c) {
  7184. var clonedCol = deep(c.element);
  7185. constrainSpan(clonedCol, 'span', maxColRange - minColRange);
  7186. return clonedCol;
  7187. });
  7188. var fakeColgroup = SugarElement.fromTag('colgroup');
  7189. append(fakeColgroup, copiedCols);
  7190. return [fakeColgroup];
  7191. } else {
  7192. return [];
  7193. }
  7194. };
  7195. var generateRows = function (house, minColRange, maxColRange) {
  7196. return map$1(house.all, function (row) {
  7197. var cellsToCopy = filter$2(row.cells, function (cell) {
  7198. return cell.column >= minColRange && cell.column < maxColRange;
  7199. });
  7200. var copiedCells = map$1(cellsToCopy, function (cell) {
  7201. var clonedCell = deep(cell.element);
  7202. constrainSpan(clonedCell, 'colspan', maxColRange - minColRange);
  7203. return clonedCell;
  7204. });
  7205. var fakeTR = SugarElement.fromTag('tr');
  7206. append(fakeTR, copiedCells);
  7207. return fakeTR;
  7208. });
  7209. };
  7210. var copyCols = function (table, target) {
  7211. var house = Warehouse.fromTable(table);
  7212. var details = onUnlockedCells(house, target);
  7213. return details.map(function (selectedCells) {
  7214. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  7215. var minColRange = selectedCells[0].column;
  7216. var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
  7217. var fakeColGroups = generateColGroup(house, minColRange, maxColRange);
  7218. var fakeRows = generateRows(house, minColRange, maxColRange);
  7219. return __spreadArray(__spreadArray([], fakeColGroups, true), fakeRows, true);
  7220. });
  7221. };
  7222. var copyRows = function (table, target, generators) {
  7223. var warehouse = Warehouse.fromTable(table);
  7224. var details = onCells(warehouse, target);
  7225. return details.bind(function (selectedCells) {
  7226. var grid = toGrid(warehouse, generators, false);
  7227. var rows = extractGridDetails(grid).rows;
  7228. var slicedGrid = rows.slice(selectedCells[0].row, selectedCells[selectedCells.length - 1].row + selectedCells[selectedCells.length - 1].rowspan);
  7229. var filteredGrid = bind$2(slicedGrid, function (row) {
  7230. var newCells = filter$2(row.cells, function (cell) {
  7231. return !cell.isLocked;
  7232. });
  7233. return newCells.length > 0 ? [__assign(__assign({}, row), { cells: newCells })] : [];
  7234. });
  7235. var slicedDetails = toDetailList(filteredGrid);
  7236. return someIf(slicedDetails.length > 0, slicedDetails);
  7237. }).map(function (slicedDetails) {
  7238. return copy(slicedDetails);
  7239. });
  7240. };
  7241. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  7242. var getTDTHOverallStyle = function (dom, elm, name) {
  7243. var cells = dom.select('td,th', elm);
  7244. var firstChildStyle;
  7245. var checkChildren = function (firstChildStyle, elms) {
  7246. for (var i = 0; i < elms.length; i++) {
  7247. var currentStyle = dom.getStyle(elms[i], name);
  7248. if (typeof firstChildStyle === 'undefined') {
  7249. firstChildStyle = currentStyle;
  7250. }
  7251. if (firstChildStyle !== currentStyle) {
  7252. return '';
  7253. }
  7254. }
  7255. return firstChildStyle;
  7256. };
  7257. return checkChildren(firstChildStyle, cells);
  7258. };
  7259. var applyAlign = function (editor, elm, name) {
  7260. if (name) {
  7261. editor.formatter.apply('align' + name, {}, elm);
  7262. }
  7263. };
  7264. var applyVAlign = function (editor, elm, name) {
  7265. if (name) {
  7266. editor.formatter.apply('valign' + name, {}, elm);
  7267. }
  7268. };
  7269. var unApplyAlign = function (editor, elm) {
  7270. global$2.each('left center right'.split(' '), function (name) {
  7271. editor.formatter.remove('align' + name, {}, elm);
  7272. });
  7273. };
  7274. var unApplyVAlign = function (editor, elm) {
  7275. global$2.each('top middle bottom'.split(' '), function (name) {
  7276. editor.formatter.remove('valign' + name, {}, elm);
  7277. });
  7278. };
  7279. var verticalAlignValues = [
  7280. {
  7281. text: 'None',
  7282. value: ''
  7283. },
  7284. {
  7285. text: 'Top',
  7286. value: 'top'
  7287. },
  7288. {
  7289. text: 'Middle',
  7290. value: 'middle'
  7291. },
  7292. {
  7293. text: 'Bottom',
  7294. value: 'bottom'
  7295. }
  7296. ];
  7297. var hexColour = function (value) {
  7298. return { value: value };
  7299. };
  7300. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  7301. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  7302. var isHexString = function (hex) {
  7303. return shorthandRegex.test(hex) || longformRegex.test(hex);
  7304. };
  7305. var normalizeHex = function (hex) {
  7306. return removeLeading(hex, '#').toUpperCase();
  7307. };
  7308. var fromString$1 = function (hex) {
  7309. return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  7310. };
  7311. var toHex = function (component) {
  7312. var hex = component.toString(16);
  7313. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  7314. };
  7315. var fromRgba = function (rgbaColour) {
  7316. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  7317. return hexColour(value);
  7318. };
  7319. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  7320. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  7321. var rgbaColour = function (red, green, blue, alpha) {
  7322. return {
  7323. red: red,
  7324. green: green,
  7325. blue: blue,
  7326. alpha: alpha
  7327. };
  7328. };
  7329. var fromStringValues = function (red, green, blue, alpha) {
  7330. var r = parseInt(red, 10);
  7331. var g = parseInt(green, 10);
  7332. var b = parseInt(blue, 10);
  7333. var a = parseFloat(alpha);
  7334. return rgbaColour(r, g, b, a);
  7335. };
  7336. var fromString = function (rgbaString) {
  7337. if (rgbaString === 'transparent') {
  7338. return Optional.some(rgbaColour(0, 0, 0, 0));
  7339. }
  7340. var rgbMatch = rgbRegex.exec(rgbaString);
  7341. if (rgbMatch !== null) {
  7342. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  7343. }
  7344. var rgbaMatch = rgbaRegex.exec(rgbaString);
  7345. if (rgbaMatch !== null) {
  7346. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  7347. }
  7348. return Optional.none();
  7349. };
  7350. var anyToHex = function (color) {
  7351. return fromString$1(color).orThunk(function () {
  7352. return fromString(color).map(fromRgba);
  7353. }).getOrThunk(function () {
  7354. var canvas = document.createElement('canvas');
  7355. canvas.height = 1;
  7356. canvas.width = 1;
  7357. var canvasContext = canvas.getContext('2d');
  7358. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  7359. canvasContext.fillStyle = '#FFFFFF';
  7360. canvasContext.fillStyle = color;
  7361. canvasContext.fillRect(0, 0, 1, 1);
  7362. var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  7363. var r = rgba[0];
  7364. var g = rgba[1];
  7365. var b = rgba[2];
  7366. var a = rgba[3];
  7367. return fromRgba(rgbaColour(r, g, b, a));
  7368. });
  7369. };
  7370. var Cell = function (initial) {
  7371. var value = initial;
  7372. var get = function () {
  7373. return value;
  7374. };
  7375. var set = function (v) {
  7376. value = v;
  7377. };
  7378. return {
  7379. get: get,
  7380. set: set
  7381. };
  7382. };
  7383. var singleton = function (doRevoke) {
  7384. var subject = Cell(Optional.none());
  7385. var revoke = function () {
  7386. return subject.get().each(doRevoke);
  7387. };
  7388. var clear = function () {
  7389. revoke();
  7390. subject.set(Optional.none());
  7391. };
  7392. var isSet = function () {
  7393. return subject.get().isSome();
  7394. };
  7395. var get = function () {
  7396. return subject.get();
  7397. };
  7398. var set = function (s) {
  7399. revoke();
  7400. subject.set(Optional.some(s));
  7401. };
  7402. return {
  7403. clear: clear,
  7404. isSet: isSet,
  7405. get: get,
  7406. set: set
  7407. };
  7408. };
  7409. var unbindable = function () {
  7410. return singleton(function (s) {
  7411. return s.unbind();
  7412. });
  7413. };
  7414. var value = function () {
  7415. var subject = singleton(noop);
  7416. var on = function (f) {
  7417. return subject.get().each(f);
  7418. };
  7419. return __assign(__assign({}, subject), { on: on });
  7420. };
  7421. var onSetupToggle = function (editor, selections, formatName, formatValue) {
  7422. return function (api) {
  7423. var boundCallback = unbindable();
  7424. var isNone = isEmpty$1(formatValue);
  7425. var init = function () {
  7426. var selectedCells = getCellsFromSelection(selections);
  7427. var checkNode = function (cell) {
  7428. return editor.formatter.match(formatName, { value: formatValue }, cell.dom, isNone);
  7429. };
  7430. if (isNone) {
  7431. api.setActive(!exists(selectedCells, checkNode));
  7432. boundCallback.set(editor.formatter.formatChanged(formatName, function (match) {
  7433. return api.setActive(!match);
  7434. }, true));
  7435. } else {
  7436. api.setActive(forall(selectedCells, checkNode));
  7437. boundCallback.set(editor.formatter.formatChanged(formatName, api.setActive, false, { value: formatValue }));
  7438. }
  7439. };
  7440. editor.initialized ? init() : editor.on('init', init);
  7441. return boundCallback.clear;
  7442. };
  7443. };
  7444. var isListGroup = function (item) {
  7445. return hasNonNullableKey(item, 'menu');
  7446. };
  7447. var buildListItems = function (items) {
  7448. return map$1(items, function (item) {
  7449. var text = item.text || item.title;
  7450. if (isListGroup(item)) {
  7451. return {
  7452. text: text,
  7453. items: buildListItems(item.menu)
  7454. };
  7455. } else {
  7456. return {
  7457. text: text,
  7458. value: item.value
  7459. };
  7460. }
  7461. });
  7462. };
  7463. var buildMenuItems = function (editor, selections, items, format, onAction) {
  7464. return map$1(items, function (item) {
  7465. var text = item.text || item.title;
  7466. if (isListGroup(item)) {
  7467. return {
  7468. type: 'nestedmenuitem',
  7469. text: text,
  7470. getSubmenuItems: function () {
  7471. return buildMenuItems(editor, selections, item.menu, format, onAction);
  7472. }
  7473. };
  7474. } else {
  7475. return {
  7476. text: text,
  7477. type: 'togglemenuitem',
  7478. onAction: function () {
  7479. return onAction(item.value);
  7480. },
  7481. onSetup: onSetupToggle(editor, selections, format, item.value)
  7482. };
  7483. }
  7484. });
  7485. };
  7486. var applyTableCellStyle = function (editor, style) {
  7487. return function (value) {
  7488. var _a;
  7489. editor.execCommand('mceTableApplyCellStyle', false, (_a = {}, _a[style] = value, _a));
  7490. };
  7491. };
  7492. var filterNoneItem = function (list) {
  7493. return bind$2(list, function (item) {
  7494. if (isListGroup(item)) {
  7495. return [__assign(__assign({}, item), { menu: filterNoneItem(item.menu) })];
  7496. } else {
  7497. return isNotEmpty(item.value) ? [item] : [];
  7498. }
  7499. });
  7500. };
  7501. var generateMenuItemsCallback = function (editor, selections, items, format, onAction) {
  7502. return function (callback) {
  7503. return callback(buildMenuItems(editor, selections, items, format, onAction));
  7504. };
  7505. };
  7506. var buildColorMenu = function (editor, colorList, style) {
  7507. var colorMap = map$1(colorList, function (entry) {
  7508. return {
  7509. text: entry.title,
  7510. value: '#' + anyToHex(entry.value).value,
  7511. type: 'choiceitem'
  7512. };
  7513. });
  7514. return [{
  7515. type: 'fancymenuitem',
  7516. fancytype: 'colorswatch',
  7517. initData: {
  7518. colors: colorMap.length > 0 ? colorMap : undefined,
  7519. allowCustomColors: false
  7520. },
  7521. onAction: function (data) {
  7522. var _a;
  7523. var value = data.value === 'remove' ? '' : data.value;
  7524. editor.execCommand('mceTableApplyCellStyle', false, (_a = {}, _a[style] = value, _a));
  7525. }
  7526. }];
  7527. };
  7528. var changeRowHeader = function (editor) {
  7529. return function () {
  7530. var currentType = editor.queryCommandValue('mceTableRowType');
  7531. var newType = currentType === 'header' ? 'body' : 'header';
  7532. editor.execCommand('mceTableRowType', false, { type: newType });
  7533. };
  7534. };
  7535. var changeColumnHeader = function (editor) {
  7536. return function () {
  7537. var currentType = editor.queryCommandValue('mceTableColType');
  7538. var newType = currentType === 'th' ? 'td' : 'th';
  7539. editor.execCommand('mceTableColType', false, { type: newType });
  7540. };
  7541. };
  7542. var getClassList$1 = function (editor) {
  7543. var classes = buildListItems(getCellClassList(editor));
  7544. if (classes.length > 0) {
  7545. return Optional.some({
  7546. name: 'class',
  7547. type: 'listbox',
  7548. label: 'Class',
  7549. items: classes
  7550. });
  7551. }
  7552. return Optional.none();
  7553. };
  7554. var children = [
  7555. {
  7556. name: 'width',
  7557. type: 'input',
  7558. label: 'Width'
  7559. },
  7560. {
  7561. name: 'height',
  7562. type: 'input',
  7563. label: 'Height'
  7564. },
  7565. {
  7566. name: 'celltype',
  7567. type: 'listbox',
  7568. label: 'Cell type',
  7569. items: [
  7570. {
  7571. text: 'Cell',
  7572. value: 'td'
  7573. },
  7574. {
  7575. text: 'Header cell',
  7576. value: 'th'
  7577. }
  7578. ]
  7579. },
  7580. {
  7581. name: 'scope',
  7582. type: 'listbox',
  7583. label: 'Scope',
  7584. items: [
  7585. {
  7586. text: 'None',
  7587. value: ''
  7588. },
  7589. {
  7590. text: 'Row',
  7591. value: 'row'
  7592. },
  7593. {
  7594. text: 'Column',
  7595. value: 'col'
  7596. },
  7597. {
  7598. text: 'Row group',
  7599. value: 'rowgroup'
  7600. },
  7601. {
  7602. text: 'Column group',
  7603. value: 'colgroup'
  7604. }
  7605. ]
  7606. },
  7607. {
  7608. name: 'halign',
  7609. type: 'listbox',
  7610. label: 'Horizontal align',
  7611. items: [
  7612. {
  7613. text: 'None',
  7614. value: ''
  7615. },
  7616. {
  7617. text: 'Left',
  7618. value: 'left'
  7619. },
  7620. {
  7621. text: 'Center',
  7622. value: 'center'
  7623. },
  7624. {
  7625. text: 'Right',
  7626. value: 'right'
  7627. }
  7628. ]
  7629. },
  7630. {
  7631. name: 'valign',
  7632. type: 'listbox',
  7633. label: 'Vertical align',
  7634. items: verticalAlignValues
  7635. }
  7636. ];
  7637. var getItems$2 = function (editor) {
  7638. return children.concat(getClassList$1(editor).toArray());
  7639. };
  7640. var getAdvancedTab = function (editor, dialogName) {
  7641. var emptyBorderStyle = [{
  7642. text: 'Select...',
  7643. value: ''
  7644. }];
  7645. var advTabItems = [
  7646. {
  7647. name: 'borderstyle',
  7648. type: 'listbox',
  7649. label: 'Border style',
  7650. items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
  7651. },
  7652. {
  7653. name: 'bordercolor',
  7654. type: 'colorinput',
  7655. label: 'Border color'
  7656. },
  7657. {
  7658. name: 'backgroundcolor',
  7659. type: 'colorinput',
  7660. label: 'Background color'
  7661. }
  7662. ];
  7663. var borderWidth = {
  7664. name: 'borderwidth',
  7665. type: 'input',
  7666. label: 'Border width'
  7667. };
  7668. var items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
  7669. return {
  7670. title: 'Advanced',
  7671. name: 'advanced',
  7672. items: items
  7673. };
  7674. };
  7675. var modifiers = function (testTruthy) {
  7676. return function (editor, node) {
  7677. var dom = editor.dom;
  7678. var setAttrib = function (attr, value) {
  7679. if (!testTruthy || value) {
  7680. dom.setAttrib(node, attr, value);
  7681. }
  7682. };
  7683. var setStyle = function (prop, value) {
  7684. if (!testTruthy || value) {
  7685. dom.setStyle(node, prop, value);
  7686. }
  7687. };
  7688. var setFormat = function (formatName, value) {
  7689. if (!testTruthy || value) {
  7690. if (value === '') {
  7691. editor.formatter.remove(formatName, { value: null }, node, true);
  7692. } else {
  7693. editor.formatter.apply(formatName, { value: value }, node);
  7694. }
  7695. }
  7696. };
  7697. return {
  7698. setAttrib: setAttrib,
  7699. setStyle: setStyle,
  7700. setFormat: setFormat
  7701. };
  7702. };
  7703. };
  7704. var DomModifier = {
  7705. normal: modifiers(false),
  7706. ifTruthy: modifiers(true)
  7707. };
  7708. var rgbToHex = function (dom) {
  7709. return function (value) {
  7710. return startsWith(value, 'rgb') ? dom.toHex(value) : value;
  7711. };
  7712. };
  7713. var extractAdvancedStyles = function (dom, elm) {
  7714. var element = SugarElement.fromDom(elm);
  7715. return {
  7716. borderwidth: getRaw$2(element, 'border-width').getOr(''),
  7717. borderstyle: getRaw$2(element, 'border-style').getOr(''),
  7718. bordercolor: getRaw$2(element, 'border-color').map(rgbToHex(dom)).getOr(''),
  7719. backgroundcolor: getRaw$2(element, 'background-color').map(rgbToHex(dom)).getOr('')
  7720. };
  7721. };
  7722. var getSharedValues = function (data) {
  7723. var baseData = data[0];
  7724. var comparisonData = data.slice(1);
  7725. each$2(comparisonData, function (items) {
  7726. each$2(keys(baseData), function (key) {
  7727. each$1(items, function (itemValue, itemKey) {
  7728. var comparisonValue = baseData[key];
  7729. if (comparisonValue !== '' && key === itemKey) {
  7730. if (comparisonValue !== itemValue) {
  7731. baseData[key] = '';
  7732. }
  7733. }
  7734. });
  7735. });
  7736. });
  7737. return baseData;
  7738. };
  7739. var getAlignment = function (formats, formatName, editor, elm) {
  7740. return find$1(formats, function (name) {
  7741. return !isUndefined(editor.formatter.matchNode(elm, formatName + name));
  7742. }).getOr('');
  7743. };
  7744. var getHAlignment = curry(getAlignment, [
  7745. 'left',
  7746. 'center',
  7747. 'right'
  7748. ], 'align');
  7749. var getVAlignment = curry(getAlignment, [
  7750. 'top',
  7751. 'middle',
  7752. 'bottom'
  7753. ], 'valign');
  7754. var extractDataFromSettings = function (editor, hasAdvTableTab) {
  7755. var style = getDefaultStyles(editor);
  7756. var attrs = getDefaultAttributes(editor);
  7757. var extractAdvancedStyleData = function (dom) {
  7758. return {
  7759. borderstyle: get$c(style, 'border-style').getOr(''),
  7760. bordercolor: rgbToHex(dom)(get$c(style, 'border-color').getOr('')),
  7761. backgroundcolor: rgbToHex(dom)(get$c(style, 'background-color').getOr(''))
  7762. };
  7763. };
  7764. var defaultData = {
  7765. height: '',
  7766. width: '100%',
  7767. cellspacing: '',
  7768. cellpadding: '',
  7769. caption: false,
  7770. class: '',
  7771. align: '',
  7772. border: ''
  7773. };
  7774. var getBorder = function () {
  7775. var borderWidth = style['border-width'];
  7776. if (shouldStyleWithCss(editor) && borderWidth) {
  7777. return { border: borderWidth };
  7778. }
  7779. return get$c(attrs, 'border').fold(function () {
  7780. return {};
  7781. }, function (border) {
  7782. return { border: border };
  7783. });
  7784. };
  7785. var advStyle = hasAdvTableTab ? extractAdvancedStyleData(editor.dom) : {};
  7786. var getCellPaddingCellSpacing = function () {
  7787. var spacing = get$c(style, 'border-spacing').or(get$c(attrs, 'cellspacing')).fold(function () {
  7788. return {};
  7789. }, function (cellspacing) {
  7790. return { cellspacing: cellspacing };
  7791. });
  7792. var padding = get$c(style, 'border-padding').or(get$c(attrs, 'cellpadding')).fold(function () {
  7793. return {};
  7794. }, function (cellpadding) {
  7795. return { cellpadding: cellpadding };
  7796. });
  7797. return __assign(__assign({}, spacing), padding);
  7798. };
  7799. var data = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
  7800. return data;
  7801. };
  7802. var getRowType = function (elm) {
  7803. return table(SugarElement.fromDom(elm)).map(function (table) {
  7804. var target = { selection: fromDom(elm.cells) };
  7805. return getRowsType(table, target);
  7806. }).getOr('');
  7807. };
  7808. var extractDataFromTableElement = function (editor, elm, hasAdvTableTab) {
  7809. var getBorder = function (dom, elm) {
  7810. var optBorderWidth = getRaw$2(SugarElement.fromDom(elm), 'border-width');
  7811. if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
  7812. return optBorderWidth.getOr('');
  7813. }
  7814. return dom.getAttrib(elm, 'border') || getTDTHOverallStyle(editor.dom, elm, 'border-width') || getTDTHOverallStyle(editor.dom, elm, 'border');
  7815. };
  7816. var dom = editor.dom;
  7817. var cellspacing = shouldStyleWithCss(editor) ? dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing') : dom.getAttrib(elm, 'cellspacing') || dom.getStyle(elm, 'border-spacing');
  7818. var cellpadding = shouldStyleWithCss(editor) ? getTDTHOverallStyle(dom, elm, 'padding') || dom.getAttrib(elm, 'cellpadding') : dom.getAttrib(elm, 'cellpadding') || getTDTHOverallStyle(dom, elm, 'padding');
  7819. return __assign({
  7820. width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
  7821. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  7822. cellspacing: cellspacing,
  7823. cellpadding: cellpadding,
  7824. border: getBorder(dom, elm),
  7825. caption: !!dom.select('caption', elm)[0],
  7826. class: dom.getAttrib(elm, 'class', ''),
  7827. align: getHAlignment(editor, elm)
  7828. }, hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
  7829. };
  7830. var extractDataFromRowElement = function (editor, elm, hasAdvancedRowTab) {
  7831. var dom = editor.dom;
  7832. return __assign({
  7833. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  7834. class: dom.getAttrib(elm, 'class', ''),
  7835. type: getRowType(elm),
  7836. align: getHAlignment(editor, elm)
  7837. }, hasAdvancedRowTab ? extractAdvancedStyles(dom, elm) : {});
  7838. };
  7839. var extractDataFromCellElement = function (editor, cell, hasAdvancedCellTab, column) {
  7840. var dom = editor.dom;
  7841. var colElm = column.getOr(cell);
  7842. var getStyle = function (element, style) {
  7843. return dom.getStyle(element, style) || dom.getAttrib(element, style);
  7844. };
  7845. return __assign({
  7846. width: getStyle(colElm, 'width'),
  7847. height: getStyle(cell, 'height'),
  7848. scope: dom.getAttrib(cell, 'scope'),
  7849. celltype: getNodeName(cell),
  7850. class: dom.getAttrib(cell, 'class', ''),
  7851. halign: getHAlignment(editor, cell),
  7852. valign: getVAlignment(editor, cell)
  7853. }, hasAdvancedCellTab ? extractAdvancedStyles(dom, cell) : {});
  7854. };
  7855. var getSelectedCells = function (table, cells) {
  7856. var warehouse = Warehouse.fromTable(table);
  7857. var allCells = Warehouse.justCells(warehouse);
  7858. var filtered = filter$2(allCells, function (cellA) {
  7859. return exists(cells, function (cellB) {
  7860. return eq$1(cellA.element, cellB);
  7861. });
  7862. });
  7863. return map$1(filtered, function (cell) {
  7864. return {
  7865. element: cell.element.dom,
  7866. column: Warehouse.getColumnAt(warehouse, cell.column).map(function (col) {
  7867. return col.element.dom;
  7868. })
  7869. };
  7870. });
  7871. };
  7872. var updateSimpleProps$1 = function (modifier, colModifier, data) {
  7873. modifier.setAttrib('scope', data.scope);
  7874. modifier.setAttrib('class', data.class);
  7875. modifier.setStyle('height', addPxSuffix(data.height));
  7876. colModifier.setStyle('width', addPxSuffix(data.width));
  7877. };
  7878. var updateAdvancedProps$1 = function (modifier, data) {
  7879. modifier.setFormat('tablecellbackgroundcolor', data.backgroundcolor);
  7880. modifier.setFormat('tablecellbordercolor', data.bordercolor);
  7881. modifier.setFormat('tablecellborderstyle', data.borderstyle);
  7882. modifier.setFormat('tablecellborderwidth', addPxSuffix(data.borderwidth));
  7883. };
  7884. var applyStyleData$1 = function (editor, cells, data) {
  7885. var isSingleCell = cells.length === 1;
  7886. each$2(cells, function (item) {
  7887. var cellElm = item.element;
  7888. var modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
  7889. var colModifier = item.column.map(function (col) {
  7890. return isSingleCell ? DomModifier.normal(editor, col) : DomModifier.ifTruthy(editor, col);
  7891. }).getOr(modifier);
  7892. updateSimpleProps$1(modifier, colModifier, data);
  7893. if (hasAdvancedCellTab(editor)) {
  7894. updateAdvancedProps$1(modifier, data);
  7895. }
  7896. if (isSingleCell) {
  7897. unApplyAlign(editor, cellElm);
  7898. unApplyVAlign(editor, cellElm);
  7899. }
  7900. if (data.halign) {
  7901. applyAlign(editor, cellElm, data.halign);
  7902. }
  7903. if (data.valign) {
  7904. applyVAlign(editor, cellElm, data.valign);
  7905. }
  7906. });
  7907. };
  7908. var applyStructureData$1 = function (editor, data) {
  7909. editor.execCommand('mceTableCellType', false, {
  7910. type: data.celltype,
  7911. no_events: true
  7912. });
  7913. };
  7914. var applyCellData = function (editor, cells, oldData, data) {
  7915. var modifiedData = filter$1(data, function (value, key) {
  7916. return oldData[key] !== value;
  7917. });
  7918. if (size(modifiedData) > 0 && cells.length >= 1) {
  7919. table(cells[0]).each(function (table) {
  7920. var selectedCells = getSelectedCells(table, cells);
  7921. var styleModified = size(filter$1(modifiedData, function (_value, key) {
  7922. return key !== 'scope' && key !== 'celltype';
  7923. })) > 0;
  7924. var structureModified = has$1(modifiedData, 'celltype');
  7925. if (styleModified || has$1(modifiedData, 'scope')) {
  7926. applyStyleData$1(editor, selectedCells, data);
  7927. }
  7928. if (structureModified) {
  7929. applyStructureData$1(editor, data);
  7930. }
  7931. fireTableModified(editor, table.dom, {
  7932. structure: structureModified,
  7933. style: styleModified
  7934. });
  7935. });
  7936. }
  7937. };
  7938. var onSubmitCellForm = function (editor, cells, oldData, api) {
  7939. var data = api.getData();
  7940. api.close();
  7941. editor.undoManager.transact(function () {
  7942. applyCellData(editor, cells, oldData, data);
  7943. editor.focus();
  7944. });
  7945. };
  7946. var getData = function (editor, cells) {
  7947. var cellsData = table(cells[0]).map(function (table) {
  7948. return map$1(getSelectedCells(table, cells), function (item) {
  7949. return extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column);
  7950. });
  7951. });
  7952. return getSharedValues(cellsData.getOrDie());
  7953. };
  7954. var open$2 = function (editor, selections) {
  7955. var cells = getCellsFromSelection(selections);
  7956. if (cells.length === 0) {
  7957. return;
  7958. }
  7959. var data = getData(editor, cells);
  7960. var dialogTabPanel = {
  7961. type: 'tabpanel',
  7962. tabs: [
  7963. {
  7964. title: 'General',
  7965. name: 'general',
  7966. items: getItems$2(editor)
  7967. },
  7968. getAdvancedTab(editor, 'cell')
  7969. ]
  7970. };
  7971. var dialogPanel = {
  7972. type: 'panel',
  7973. items: [{
  7974. type: 'grid',
  7975. columns: 2,
  7976. items: getItems$2(editor)
  7977. }]
  7978. };
  7979. editor.windowManager.open({
  7980. title: 'Cell Properties',
  7981. size: 'normal',
  7982. body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
  7983. buttons: [
  7984. {
  7985. type: 'cancel',
  7986. name: 'cancel',
  7987. text: 'Cancel'
  7988. },
  7989. {
  7990. type: 'submit',
  7991. name: 'save',
  7992. text: 'Save',
  7993. primary: true
  7994. }
  7995. ],
  7996. initialData: data,
  7997. onSubmit: curry(onSubmitCellForm, editor, cells, data)
  7998. });
  7999. };
  8000. var getClassList = function (editor) {
  8001. var classes = buildListItems(getRowClassList(editor));
  8002. if (classes.length > 0) {
  8003. return Optional.some({
  8004. name: 'class',
  8005. type: 'listbox',
  8006. label: 'Class',
  8007. items: classes
  8008. });
  8009. }
  8010. return Optional.none();
  8011. };
  8012. var formChildren = [
  8013. {
  8014. type: 'listbox',
  8015. name: 'type',
  8016. label: 'Row type',
  8017. items: [
  8018. {
  8019. text: 'Header',
  8020. value: 'header'
  8021. },
  8022. {
  8023. text: 'Body',
  8024. value: 'body'
  8025. },
  8026. {
  8027. text: 'Footer',
  8028. value: 'footer'
  8029. }
  8030. ]
  8031. },
  8032. {
  8033. type: 'listbox',
  8034. name: 'align',
  8035. label: 'Alignment',
  8036. items: [
  8037. {
  8038. text: 'None',
  8039. value: ''
  8040. },
  8041. {
  8042. text: 'Left',
  8043. value: 'left'
  8044. },
  8045. {
  8046. text: 'Center',
  8047. value: 'center'
  8048. },
  8049. {
  8050. text: 'Right',
  8051. value: 'right'
  8052. }
  8053. ]
  8054. },
  8055. {
  8056. label: 'Height',
  8057. name: 'height',
  8058. type: 'input'
  8059. }
  8060. ];
  8061. var getItems$1 = function (editor) {
  8062. return formChildren.concat(getClassList(editor).toArray());
  8063. };
  8064. var updateSimpleProps = function (modifier, data) {
  8065. modifier.setAttrib('class', data.class);
  8066. modifier.setStyle('height', addPxSuffix(data.height));
  8067. };
  8068. var updateAdvancedProps = function (modifier, data) {
  8069. modifier.setStyle('background-color', data.backgroundcolor);
  8070. modifier.setStyle('border-color', data.bordercolor);
  8071. modifier.setStyle('border-style', data.borderstyle);
  8072. };
  8073. var applyStyleData = function (editor, rows, data, oldData) {
  8074. var isSingleRow = rows.length === 1;
  8075. each$2(rows, function (rowElm) {
  8076. var modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
  8077. updateSimpleProps(modifier, data);
  8078. if (hasAdvancedRowTab(editor)) {
  8079. updateAdvancedProps(modifier, data);
  8080. }
  8081. if (data.align !== oldData.align) {
  8082. unApplyAlign(editor, rowElm);
  8083. applyAlign(editor, rowElm, data.align);
  8084. }
  8085. });
  8086. };
  8087. var applyStructureData = function (editor, data) {
  8088. editor.execCommand('mceTableRowType', false, {
  8089. type: data.type,
  8090. no_events: true
  8091. });
  8092. };
  8093. var applyRowData = function (editor, rows, oldData, data) {
  8094. var modifiedData = filter$1(data, function (value, key) {
  8095. return oldData[key] !== value;
  8096. });
  8097. if (size(modifiedData) > 0) {
  8098. var typeModified_1 = has$1(modifiedData, 'type');
  8099. var styleModified_1 = typeModified_1 ? size(modifiedData) > 1 : true;
  8100. if (styleModified_1) {
  8101. applyStyleData(editor, rows, data, oldData);
  8102. }
  8103. if (typeModified_1) {
  8104. applyStructureData(editor, data);
  8105. }
  8106. table(SugarElement.fromDom(rows[0])).each(function (table) {
  8107. return fireTableModified(editor, table.dom, {
  8108. structure: typeModified_1,
  8109. style: styleModified_1
  8110. });
  8111. });
  8112. }
  8113. };
  8114. var onSubmitRowForm = function (editor, rows, oldData, api) {
  8115. var data = api.getData();
  8116. api.close();
  8117. editor.undoManager.transact(function () {
  8118. applyRowData(editor, rows, oldData, data);
  8119. editor.focus();
  8120. });
  8121. };
  8122. var open$1 = function (editor) {
  8123. var rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
  8124. if (rows.length === 0) {
  8125. return;
  8126. }
  8127. var rowsData = map$1(rows, function (rowElm) {
  8128. return extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor));
  8129. });
  8130. var data = getSharedValues(rowsData);
  8131. var dialogTabPanel = {
  8132. type: 'tabpanel',
  8133. tabs: [
  8134. {
  8135. title: 'General',
  8136. name: 'general',
  8137. items: getItems$1(editor)
  8138. },
  8139. getAdvancedTab(editor, 'row')
  8140. ]
  8141. };
  8142. var dialogPanel = {
  8143. type: 'panel',
  8144. items: [{
  8145. type: 'grid',
  8146. columns: 2,
  8147. items: getItems$1(editor)
  8148. }]
  8149. };
  8150. editor.windowManager.open({
  8151. title: 'Row Properties',
  8152. size: 'normal',
  8153. body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
  8154. buttons: [
  8155. {
  8156. type: 'cancel',
  8157. name: 'cancel',
  8158. text: 'Cancel'
  8159. },
  8160. {
  8161. type: 'submit',
  8162. name: 'save',
  8163. text: 'Save',
  8164. primary: true
  8165. }
  8166. ],
  8167. initialData: data,
  8168. onSubmit: curry(onSubmitRowForm, editor, map$1(rows, function (r) {
  8169. return r.dom;
  8170. }), data)
  8171. });
  8172. };
  8173. var getItems = function (editor, classes, insertNewTable) {
  8174. var rowColCountItems = !insertNewTable ? [] : [
  8175. {
  8176. type: 'input',
  8177. name: 'cols',
  8178. label: 'Cols',
  8179. inputMode: 'numeric'
  8180. },
  8181. {
  8182. type: 'input',
  8183. name: 'rows',
  8184. label: 'Rows',
  8185. inputMode: 'numeric'
  8186. }
  8187. ];
  8188. var alwaysItems = [
  8189. {
  8190. type: 'input',
  8191. name: 'width',
  8192. label: 'Width'
  8193. },
  8194. {
  8195. type: 'input',
  8196. name: 'height',
  8197. label: 'Height'
  8198. }
  8199. ];
  8200. var appearanceItems = hasAppearanceOptions(editor) ? [
  8201. {
  8202. type: 'input',
  8203. name: 'cellspacing',
  8204. label: 'Cell spacing',
  8205. inputMode: 'numeric'
  8206. },
  8207. {
  8208. type: 'input',
  8209. name: 'cellpadding',
  8210. label: 'Cell padding',
  8211. inputMode: 'numeric'
  8212. },
  8213. {
  8214. type: 'input',
  8215. name: 'border',
  8216. label: 'Border width'
  8217. },
  8218. {
  8219. type: 'label',
  8220. label: 'Caption',
  8221. items: [{
  8222. type: 'checkbox',
  8223. name: 'caption',
  8224. label: 'Show caption'
  8225. }]
  8226. }
  8227. ] : [];
  8228. var alignmentItem = [{
  8229. type: 'listbox',
  8230. name: 'align',
  8231. label: 'Alignment',
  8232. items: [
  8233. {
  8234. text: 'None',
  8235. value: ''
  8236. },
  8237. {
  8238. text: 'Left',
  8239. value: 'left'
  8240. },
  8241. {
  8242. text: 'Center',
  8243. value: 'center'
  8244. },
  8245. {
  8246. text: 'Right',
  8247. value: 'right'
  8248. }
  8249. ]
  8250. }];
  8251. var classListItem = classes.length > 0 ? [{
  8252. type: 'listbox',
  8253. name: 'class',
  8254. label: 'Class',
  8255. items: classes
  8256. }] : [];
  8257. return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
  8258. };
  8259. var styleTDTH = function (dom, elm, name, value) {
  8260. if (elm.tagName === 'TD' || elm.tagName === 'TH') {
  8261. if (isString(name)) {
  8262. dom.setStyle(elm, name, value);
  8263. } else {
  8264. dom.setStyle(elm, name);
  8265. }
  8266. } else {
  8267. if (elm.children) {
  8268. for (var i = 0; i < elm.children.length; i++) {
  8269. styleTDTH(dom, elm.children[i], name, value);
  8270. }
  8271. }
  8272. }
  8273. };
  8274. var applyDataToElement = function (editor, tableElm, data) {
  8275. var dom = editor.dom;
  8276. var attrs = {};
  8277. var styles = {};
  8278. attrs.class = data.class;
  8279. styles.height = addPxSuffix(data.height);
  8280. if (dom.getAttrib(tableElm, 'width') && !shouldStyleWithCss(editor)) {
  8281. attrs.width = removePxSuffix(data.width);
  8282. } else {
  8283. styles.width = addPxSuffix(data.width);
  8284. }
  8285. if (shouldStyleWithCss(editor)) {
  8286. styles['border-width'] = addPxSuffix(data.border);
  8287. styles['border-spacing'] = addPxSuffix(data.cellspacing);
  8288. } else {
  8289. attrs.border = data.border;
  8290. attrs.cellpadding = data.cellpadding;
  8291. attrs.cellspacing = data.cellspacing;
  8292. }
  8293. if (shouldStyleWithCss(editor) && tableElm.children) {
  8294. for (var i = 0; i < tableElm.children.length; i++) {
  8295. styleTDTH(dom, tableElm.children[i], {
  8296. 'border-width': addPxSuffix(data.border),
  8297. 'padding': addPxSuffix(data.cellpadding)
  8298. });
  8299. if (hasAdvancedTableTab(editor)) {
  8300. styleTDTH(dom, tableElm.children[i], { 'border-color': data.bordercolor });
  8301. }
  8302. }
  8303. }
  8304. if (hasAdvancedTableTab(editor)) {
  8305. styles['background-color'] = data.backgroundcolor;
  8306. styles['border-color'] = data.bordercolor;
  8307. styles['border-style'] = data.borderstyle;
  8308. }
  8309. attrs.style = dom.serializeStyle(__assign(__assign({}, getDefaultStyles(editor)), styles));
  8310. dom.setAttribs(tableElm, __assign(__assign({}, getDefaultAttributes(editor)), attrs));
  8311. };
  8312. var onSubmitTableForm = function (editor, tableElm, oldData, api) {
  8313. var dom = editor.dom;
  8314. var data = api.getData();
  8315. var modifiedData = filter$1(data, function (value, key) {
  8316. return oldData[key] !== value;
  8317. });
  8318. api.close();
  8319. if (data.class === '') {
  8320. delete data.class;
  8321. }
  8322. editor.undoManager.transact(function () {
  8323. if (!tableElm) {
  8324. var cols = parseInt(data.cols, 10) || 1;
  8325. var rows = parseInt(data.rows, 10) || 1;
  8326. tableElm = insert(editor, cols, rows, 0, 0);
  8327. }
  8328. if (size(modifiedData) > 0) {
  8329. applyDataToElement(editor, tableElm, data);
  8330. var captionElm = dom.select('caption', tableElm)[0];
  8331. if (captionElm && !data.caption || !captionElm && data.caption) {
  8332. editor.execCommand('mceTableToggleCaption');
  8333. }
  8334. if (data.align === '') {
  8335. unApplyAlign(editor, tableElm);
  8336. } else {
  8337. applyAlign(editor, tableElm, data.align);
  8338. }
  8339. }
  8340. editor.focus();
  8341. editor.addVisual();
  8342. if (size(modifiedData) > 0) {
  8343. var captionModified = has$1(modifiedData, 'caption');
  8344. var styleModified = captionModified ? size(modifiedData) > 1 : true;
  8345. fireTableModified(editor, tableElm, {
  8346. structure: captionModified,
  8347. style: styleModified
  8348. });
  8349. }
  8350. });
  8351. };
  8352. var open = function (editor, insertNewTable) {
  8353. var dom = editor.dom;
  8354. var tableElm;
  8355. var data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
  8356. if (insertNewTable === false) {
  8357. tableElm = dom.getParent(editor.selection.getStart(), 'table', editor.getBody());
  8358. if (tableElm) {
  8359. data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
  8360. } else {
  8361. if (hasAdvancedTableTab(editor)) {
  8362. data.borderstyle = '';
  8363. data.bordercolor = '';
  8364. data.backgroundcolor = '';
  8365. }
  8366. }
  8367. } else {
  8368. data.cols = '1';
  8369. data.rows = '1';
  8370. if (hasAdvancedTableTab(editor)) {
  8371. data.borderstyle = '';
  8372. data.bordercolor = '';
  8373. data.backgroundcolor = '';
  8374. }
  8375. }
  8376. var classes = buildListItems(getTableClassList(editor));
  8377. if (classes.length > 0) {
  8378. if (data.class) {
  8379. data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
  8380. }
  8381. }
  8382. var generalPanel = {
  8383. type: 'grid',
  8384. columns: 2,
  8385. items: getItems(editor, classes, insertNewTable)
  8386. };
  8387. var nonAdvancedForm = function () {
  8388. return {
  8389. type: 'panel',
  8390. items: [generalPanel]
  8391. };
  8392. };
  8393. var advancedForm = function () {
  8394. return {
  8395. type: 'tabpanel',
  8396. tabs: [
  8397. {
  8398. title: 'General',
  8399. name: 'general',
  8400. items: [generalPanel]
  8401. },
  8402. getAdvancedTab(editor, 'table')
  8403. ]
  8404. };
  8405. };
  8406. var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
  8407. editor.windowManager.open({
  8408. title: 'Table Properties',
  8409. size: 'normal',
  8410. body: dialogBody,
  8411. onSubmit: curry(onSubmitTableForm, editor, tableElm, data),
  8412. buttons: [
  8413. {
  8414. type: 'cancel',
  8415. name: 'cancel',
  8416. text: 'Cancel'
  8417. },
  8418. {
  8419. type: 'submit',
  8420. name: 'save',
  8421. text: 'Save',
  8422. primary: true
  8423. }
  8424. ],
  8425. initialData: data
  8426. });
  8427. };
  8428. var getSelectionStartCellOrCaption = function (editor) {
  8429. return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  8430. };
  8431. var getSelectionStartCell = function (editor) {
  8432. return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
  8433. };
  8434. var registerCommands = function (editor, actions, cellSelection, selections, clipboard) {
  8435. var isRoot = getIsRoot(editor);
  8436. var eraseTable = function () {
  8437. return getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8438. table(cellOrCaption, isRoot).filter(not(isRoot)).each(function (table) {
  8439. var cursor = SugarElement.fromText('');
  8440. after$5(table, cursor);
  8441. remove$5(table);
  8442. if (editor.dom.isEmpty(editor.getBody())) {
  8443. editor.setContent('');
  8444. editor.selection.setCursorLocation();
  8445. } else {
  8446. var rng = editor.dom.createRng();
  8447. rng.setStart(cursor.dom, 0);
  8448. rng.setEnd(cursor.dom, 0);
  8449. editor.selection.setRng(rng);
  8450. editor.nodeChanged();
  8451. }
  8452. });
  8453. });
  8454. };
  8455. var setSizingMode = function (sizing) {
  8456. return getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8457. var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
  8458. if (!isForcedSizing) {
  8459. table(cellOrCaption, isRoot).each(function (table) {
  8460. if (sizing === 'relative' && !isPercentSizing(table)) {
  8461. enforcePercentage(table);
  8462. } else if (sizing === 'fixed' && !isPixelSizing(table)) {
  8463. enforcePixels(table);
  8464. } else if (sizing === 'responsive' && !isNoneSizing(table)) {
  8465. enforceNone(table);
  8466. }
  8467. removeDataStyle(table);
  8468. fireTableModified(editor, table.dom, structureModified);
  8469. });
  8470. }
  8471. });
  8472. };
  8473. var getTableFromCell = function (cell) {
  8474. return table(cell, isRoot);
  8475. };
  8476. var performActionOnSelection = function (action) {
  8477. return getSelectionStartCell(editor).bind(function (cell) {
  8478. return getTableFromCell(cell).map(function (table) {
  8479. return action(table, cell);
  8480. });
  8481. });
  8482. };
  8483. var toggleTableClass = function (_ui, clazz) {
  8484. performActionOnSelection(function (table) {
  8485. editor.formatter.toggle('tableclass', { value: clazz }, table.dom);
  8486. fireTableModified(editor, table.dom, styleModified);
  8487. });
  8488. };
  8489. var toggleTableCellClass = function (_ui, clazz) {
  8490. performActionOnSelection(function (table) {
  8491. var selectedCells = getCellsFromSelection(selections);
  8492. var allHaveClass = forall(selectedCells, function (cell) {
  8493. return editor.formatter.match('tablecellclass', { value: clazz }, cell.dom);
  8494. });
  8495. var formatterAction = allHaveClass ? editor.formatter.remove : editor.formatter.apply;
  8496. each$2(selectedCells, function (cell) {
  8497. return formatterAction('tablecellclass', { value: clazz }, cell.dom);
  8498. });
  8499. fireTableModified(editor, table.dom, styleModified);
  8500. });
  8501. };
  8502. var toggleCaption = function () {
  8503. getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8504. table(cellOrCaption, isRoot).each(function (table) {
  8505. child$1(table, 'caption').fold(function () {
  8506. var caption = SugarElement.fromTag('caption');
  8507. append$1(caption, SugarElement.fromText('Caption'));
  8508. appendAt(table, caption, 0);
  8509. editor.selection.setCursorLocation(caption.dom, 0);
  8510. }, function (caption) {
  8511. if (isTag('caption')(cellOrCaption)) {
  8512. one('td', table).each(function (td) {
  8513. return editor.selection.setCursorLocation(td.dom, 0);
  8514. });
  8515. }
  8516. remove$5(caption);
  8517. });
  8518. fireTableModified(editor, table.dom, structureModified);
  8519. });
  8520. });
  8521. };
  8522. var postExecute = function (_data) {
  8523. editor.focus();
  8524. };
  8525. var actOnSelection = function (execute, noEvents) {
  8526. if (noEvents === void 0) {
  8527. noEvents = false;
  8528. }
  8529. return performActionOnSelection(function (table, startCell) {
  8530. var targets = forMenu(selections, table, startCell);
  8531. execute(table, targets, noEvents).each(postExecute);
  8532. });
  8533. };
  8534. var copyRowSelection = function () {
  8535. return performActionOnSelection(function (table, startCell) {
  8536. var targets = forMenu(selections, table, startCell);
  8537. var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), Optional.none());
  8538. return copyRows(table, targets, generators);
  8539. });
  8540. };
  8541. var copyColSelection = function () {
  8542. return performActionOnSelection(function (table, startCell) {
  8543. var targets = forMenu(selections, table, startCell);
  8544. return copyCols(table, targets);
  8545. });
  8546. };
  8547. var pasteOnSelection = function (execute, getRows) {
  8548. return getRows().each(function (rows) {
  8549. var clonedRows = map$1(rows, function (row) {
  8550. return deep(row);
  8551. });
  8552. performActionOnSelection(function (table, startCell) {
  8553. var generators = paste$1(SugarElement.fromDom(editor.getDoc()));
  8554. var targets = pasteRows(selections, startCell, clonedRows, generators);
  8555. execute(table, targets).each(postExecute);
  8556. });
  8557. });
  8558. };
  8559. var actOnType = function (getAction) {
  8560. return function (_ui, args) {
  8561. return get$c(args, 'type').each(function (type) {
  8562. actOnSelection(getAction(type), args.no_events);
  8563. });
  8564. };
  8565. };
  8566. each$1({
  8567. mceTableSplitCells: function () {
  8568. return actOnSelection(actions.unmergeCells);
  8569. },
  8570. mceTableMergeCells: function () {
  8571. return actOnSelection(actions.mergeCells);
  8572. },
  8573. mceTableInsertRowBefore: function () {
  8574. return actOnSelection(actions.insertRowsBefore);
  8575. },
  8576. mceTableInsertRowAfter: function () {
  8577. return actOnSelection(actions.insertRowsAfter);
  8578. },
  8579. mceTableInsertColBefore: function () {
  8580. return actOnSelection(actions.insertColumnsBefore);
  8581. },
  8582. mceTableInsertColAfter: function () {
  8583. return actOnSelection(actions.insertColumnsAfter);
  8584. },
  8585. mceTableDeleteCol: function () {
  8586. return actOnSelection(actions.deleteColumn);
  8587. },
  8588. mceTableDeleteRow: function () {
  8589. return actOnSelection(actions.deleteRow);
  8590. },
  8591. mceTableCutCol: function () {
  8592. return copyColSelection().each(function (selection) {
  8593. clipboard.setColumns(selection);
  8594. actOnSelection(actions.deleteColumn);
  8595. });
  8596. },
  8597. mceTableCutRow: function () {
  8598. return copyRowSelection().each(function (selection) {
  8599. clipboard.setRows(selection);
  8600. actOnSelection(actions.deleteRow);
  8601. });
  8602. },
  8603. mceTableCopyCol: function () {
  8604. return copyColSelection().each(function (selection) {
  8605. return clipboard.setColumns(selection);
  8606. });
  8607. },
  8608. mceTableCopyRow: function () {
  8609. return copyRowSelection().each(function (selection) {
  8610. return clipboard.setRows(selection);
  8611. });
  8612. },
  8613. mceTablePasteColBefore: function () {
  8614. return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
  8615. },
  8616. mceTablePasteColAfter: function () {
  8617. return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
  8618. },
  8619. mceTablePasteRowBefore: function () {
  8620. return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
  8621. },
  8622. mceTablePasteRowAfter: function () {
  8623. return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
  8624. },
  8625. mceTableDelete: eraseTable,
  8626. mceTableCellToggleClass: toggleTableCellClass,
  8627. mceTableToggleClass: toggleTableClass,
  8628. mceTableToggleCaption: toggleCaption,
  8629. mceTableSizingMode: function (_ui, sizing) {
  8630. return setSizingMode(sizing);
  8631. },
  8632. mceTableCellType: actOnType(function (type) {
  8633. return type === 'th' ? actions.makeCellsHeader : actions.unmakeCellsHeader;
  8634. }),
  8635. mceTableColType: actOnType(function (type) {
  8636. return type === 'th' ? actions.makeColumnsHeader : actions.unmakeColumnsHeader;
  8637. }),
  8638. mceTableRowType: actOnType(function (type) {
  8639. switch (type) {
  8640. case 'header':
  8641. return actions.makeRowsHeader;
  8642. case 'footer':
  8643. return actions.makeRowsFooter;
  8644. default:
  8645. return actions.makeRowsBody;
  8646. }
  8647. })
  8648. }, function (func, name) {
  8649. return editor.addCommand(name, func);
  8650. });
  8651. each$1({
  8652. mceTableProps: curry(open, editor, false),
  8653. mceTableRowProps: curry(open$1, editor),
  8654. mceTableCellProps: curry(open$2, editor, selections)
  8655. }, function (func, name) {
  8656. return editor.addCommand(name, function () {
  8657. return func();
  8658. });
  8659. });
  8660. editor.addCommand('mceInsertTable', function (_ui, args) {
  8661. if (isObject(args) && keys(args).length > 0) {
  8662. insertTableWithDataValidation(editor, args.rows, args.columns, args.options, 'Invalid values for mceInsertTable - rows and columns values are required to insert a table.');
  8663. } else {
  8664. open(editor, true);
  8665. }
  8666. });
  8667. editor.addCommand('mceTableApplyCellStyle', function (_ui, args) {
  8668. var getFormatName = function (style) {
  8669. return 'tablecell' + style.toLowerCase().replace('-', '');
  8670. };
  8671. if (!isObject(args)) {
  8672. return;
  8673. }
  8674. var cells = getCellsFromSelection(selections);
  8675. if (cells.length === 0) {
  8676. return;
  8677. }
  8678. var validArgs = filter$1(args, function (value, style) {
  8679. return editor.formatter.has(getFormatName(style)) && isString(value);
  8680. });
  8681. if (isEmpty(validArgs)) {
  8682. return;
  8683. }
  8684. each$1(validArgs, function (value, style) {
  8685. each$2(cells, function (cell) {
  8686. DomModifier.normal(editor, cell.dom).setFormat(getFormatName(style), value);
  8687. });
  8688. });
  8689. getTableFromCell(cells[0]).each(function (table) {
  8690. return fireTableModified(editor, table.dom, styleModified);
  8691. });
  8692. });
  8693. };
  8694. var registerQueryCommands = function (editor, actions, selections) {
  8695. var isRoot = getIsRoot(editor);
  8696. var lookupOnSelection = function (action) {
  8697. return getSelectionCell(getSelectionStart(editor)).bind(function (cell) {
  8698. return table(cell, isRoot).map(function (table) {
  8699. var targets = forMenu(selections, table, cell);
  8700. return action(table, targets);
  8701. });
  8702. }).getOr('');
  8703. };
  8704. each$1({
  8705. mceTableRowType: function () {
  8706. return lookupOnSelection(actions.getTableRowType);
  8707. },
  8708. mceTableCellType: function () {
  8709. return lookupOnSelection(actions.getTableCellType);
  8710. },
  8711. mceTableColType: function () {
  8712. return lookupOnSelection(actions.getTableColType);
  8713. }
  8714. }, function (func, name) {
  8715. return editor.addQueryValueHandler(name, func);
  8716. });
  8717. };
  8718. var Clipboard = function () {
  8719. var rows = value();
  8720. var cols = value();
  8721. return {
  8722. getRows: rows.get,
  8723. setRows: function (r) {
  8724. r.fold(rows.clear, rows.set);
  8725. cols.clear();
  8726. },
  8727. clearRows: rows.clear,
  8728. getColumns: cols.get,
  8729. setColumns: function (c) {
  8730. c.fold(cols.clear, cols.set);
  8731. rows.clear();
  8732. },
  8733. clearColumns: cols.clear
  8734. };
  8735. };
  8736. var genericBase = {
  8737. remove_similar: true,
  8738. inherit: false
  8739. };
  8740. var cellBase = __assign({ selector: 'td,th' }, genericBase);
  8741. var cellFormats = {
  8742. tablecellbackgroundcolor: __assign({ styles: { backgroundColor: '%value' } }, cellBase),
  8743. tablecellverticalalign: __assign({ styles: { 'vertical-align': '%value' } }, cellBase),
  8744. tablecellbordercolor: __assign({ styles: { borderColor: '%value' } }, cellBase),
  8745. tablecellclass: __assign({ classes: ['%value'] }, cellBase),
  8746. tableclass: __assign({
  8747. selector: 'table',
  8748. classes: ['%value']
  8749. }, genericBase),
  8750. tablecellborderstyle: __assign({ styles: { borderStyle: '%value' } }, cellBase),
  8751. tablecellborderwidth: __assign({ styles: { borderWidth: '%value' } }, cellBase)
  8752. };
  8753. var registerFormats = function (editor) {
  8754. editor.formatter.register(cellFormats);
  8755. };
  8756. var adt$5 = Adt.generate([
  8757. { none: ['current'] },
  8758. { first: ['current'] },
  8759. {
  8760. middle: [
  8761. 'current',
  8762. 'target'
  8763. ]
  8764. },
  8765. { last: ['current'] }
  8766. ]);
  8767. var none = function (current) {
  8768. if (current === void 0) {
  8769. current = undefined;
  8770. }
  8771. return adt$5.none(current);
  8772. };
  8773. var CellLocation = __assign(__assign({}, adt$5), { none: none });
  8774. var walk = function (all, current, index, direction, isEligible) {
  8775. if (isEligible === void 0) {
  8776. isEligible = always;
  8777. }
  8778. var forwards = direction === 1;
  8779. if (!forwards && index <= 0) {
  8780. return CellLocation.first(all[0]);
  8781. } else if (forwards && index >= all.length - 1) {
  8782. return CellLocation.last(all[all.length - 1]);
  8783. } else {
  8784. var newIndex = index + direction;
  8785. var elem = all[newIndex];
  8786. return isEligible(elem) ? CellLocation.middle(current, elem) : walk(all, current, newIndex, direction, isEligible);
  8787. }
  8788. };
  8789. var detect$1 = function (current, isRoot) {
  8790. return table(current, isRoot).bind(function (table) {
  8791. var all = cells$1(table);
  8792. var index = findIndex(all, function (x) {
  8793. return eq$1(current, x);
  8794. });
  8795. return index.map(function (index) {
  8796. return {
  8797. index: index,
  8798. all: all
  8799. };
  8800. });
  8801. });
  8802. };
  8803. var next = function (current, isEligible, isRoot) {
  8804. var detection = detect$1(current, isRoot);
  8805. return detection.fold(function () {
  8806. return CellLocation.none(current);
  8807. }, function (info) {
  8808. return walk(info.all, current, info.index, 1, isEligible);
  8809. });
  8810. };
  8811. var prev = function (current, isEligible, isRoot) {
  8812. var detection = detect$1(current, isRoot);
  8813. return detection.fold(function () {
  8814. return CellLocation.none();
  8815. }, function (info) {
  8816. return walk(info.all, current, info.index, -1, isEligible);
  8817. });
  8818. };
  8819. var create$2 = function (start, soffset, finish, foffset) {
  8820. return {
  8821. start: start,
  8822. soffset: soffset,
  8823. finish: finish,
  8824. foffset: foffset
  8825. };
  8826. };
  8827. var SimRange = { create: create$2 };
  8828. var adt$4 = Adt.generate([
  8829. { before: ['element'] },
  8830. {
  8831. on: [
  8832. 'element',
  8833. 'offset'
  8834. ]
  8835. },
  8836. { after: ['element'] }
  8837. ]);
  8838. var cata$1 = function (subject, onBefore, onOn, onAfter) {
  8839. return subject.fold(onBefore, onOn, onAfter);
  8840. };
  8841. var getStart$1 = function (situ) {
  8842. return situ.fold(identity, identity, identity);
  8843. };
  8844. var before$2 = adt$4.before;
  8845. var on = adt$4.on;
  8846. var after$3 = adt$4.after;
  8847. var Situ = {
  8848. before: before$2,
  8849. on: on,
  8850. after: after$3,
  8851. cata: cata$1,
  8852. getStart: getStart$1
  8853. };
  8854. var adt$3 = Adt.generate([
  8855. { domRange: ['rng'] },
  8856. {
  8857. relative: [
  8858. 'startSitu',
  8859. 'finishSitu'
  8860. ]
  8861. },
  8862. {
  8863. exact: [
  8864. 'start',
  8865. 'soffset',
  8866. 'finish',
  8867. 'foffset'
  8868. ]
  8869. }
  8870. ]);
  8871. var exactFromRange = function (simRange) {
  8872. return adt$3.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  8873. };
  8874. var getStart = function (selection) {
  8875. return selection.match({
  8876. domRange: function (rng) {
  8877. return SugarElement.fromDom(rng.startContainer);
  8878. },
  8879. relative: function (startSitu, _finishSitu) {
  8880. return Situ.getStart(startSitu);
  8881. },
  8882. exact: function (start, _soffset, _finish, _foffset) {
  8883. return start;
  8884. }
  8885. });
  8886. };
  8887. var domRange = adt$3.domRange;
  8888. var relative = adt$3.relative;
  8889. var exact = adt$3.exact;
  8890. var getWin = function (selection) {
  8891. var start = getStart(selection);
  8892. return defaultView(start);
  8893. };
  8894. var range = SimRange.create;
  8895. var SimSelection = {
  8896. domRange: domRange,
  8897. relative: relative,
  8898. exact: exact,
  8899. exactFromRange: exactFromRange,
  8900. getWin: getWin,
  8901. range: range
  8902. };
  8903. var selectNode = function (win, element) {
  8904. var rng = win.document.createRange();
  8905. rng.selectNode(element.dom);
  8906. return rng;
  8907. };
  8908. var selectNodeContents = function (win, element) {
  8909. var rng = win.document.createRange();
  8910. selectNodeContentsUsing(rng, element);
  8911. return rng;
  8912. };
  8913. var selectNodeContentsUsing = function (rng, element) {
  8914. return rng.selectNodeContents(element.dom);
  8915. };
  8916. var setStart = function (rng, situ) {
  8917. situ.fold(function (e) {
  8918. rng.setStartBefore(e.dom);
  8919. }, function (e, o) {
  8920. rng.setStart(e.dom, o);
  8921. }, function (e) {
  8922. rng.setStartAfter(e.dom);
  8923. });
  8924. };
  8925. var setFinish = function (rng, situ) {
  8926. situ.fold(function (e) {
  8927. rng.setEndBefore(e.dom);
  8928. }, function (e, o) {
  8929. rng.setEnd(e.dom, o);
  8930. }, function (e) {
  8931. rng.setEndAfter(e.dom);
  8932. });
  8933. };
  8934. var relativeToNative = function (win, startSitu, finishSitu) {
  8935. var range = win.document.createRange();
  8936. setStart(range, startSitu);
  8937. setFinish(range, finishSitu);
  8938. return range;
  8939. };
  8940. var exactToNative = function (win, start, soffset, finish, foffset) {
  8941. var rng = win.document.createRange();
  8942. rng.setStart(start.dom, soffset);
  8943. rng.setEnd(finish.dom, foffset);
  8944. return rng;
  8945. };
  8946. var toRect = function (rect) {
  8947. return {
  8948. left: rect.left,
  8949. top: rect.top,
  8950. right: rect.right,
  8951. bottom: rect.bottom,
  8952. width: rect.width,
  8953. height: rect.height
  8954. };
  8955. };
  8956. var getFirstRect$1 = function (rng) {
  8957. var rects = rng.getClientRects();
  8958. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  8959. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  8960. };
  8961. var adt$2 = Adt.generate([
  8962. {
  8963. ltr: [
  8964. 'start',
  8965. 'soffset',
  8966. 'finish',
  8967. 'foffset'
  8968. ]
  8969. },
  8970. {
  8971. rtl: [
  8972. 'start',
  8973. 'soffset',
  8974. 'finish',
  8975. 'foffset'
  8976. ]
  8977. }
  8978. ]);
  8979. var fromRange = function (win, type, range) {
  8980. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  8981. };
  8982. var getRanges = function (win, selection) {
  8983. return selection.match({
  8984. domRange: function (rng) {
  8985. return {
  8986. ltr: constant(rng),
  8987. rtl: Optional.none
  8988. };
  8989. },
  8990. relative: function (startSitu, finishSitu) {
  8991. return {
  8992. ltr: cached(function () {
  8993. return relativeToNative(win, startSitu, finishSitu);
  8994. }),
  8995. rtl: cached(function () {
  8996. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  8997. })
  8998. };
  8999. },
  9000. exact: function (start, soffset, finish, foffset) {
  9001. return {
  9002. ltr: cached(function () {
  9003. return exactToNative(win, start, soffset, finish, foffset);
  9004. }),
  9005. rtl: cached(function () {
  9006. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  9007. })
  9008. };
  9009. }
  9010. });
  9011. };
  9012. var doDiagnose = function (win, ranges) {
  9013. var rng = ranges.ltr();
  9014. if (rng.collapsed) {
  9015. var reversed = ranges.rtl().filter(function (rev) {
  9016. return rev.collapsed === false;
  9017. });
  9018. return reversed.map(function (rev) {
  9019. return adt$2.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  9020. }).getOrThunk(function () {
  9021. return fromRange(win, adt$2.ltr, rng);
  9022. });
  9023. } else {
  9024. return fromRange(win, adt$2.ltr, rng);
  9025. }
  9026. };
  9027. var diagnose = function (win, selection) {
  9028. var ranges = getRanges(win, selection);
  9029. return doDiagnose(win, ranges);
  9030. };
  9031. var asLtrRange = function (win, selection) {
  9032. var diagnosis = diagnose(win, selection);
  9033. return diagnosis.match({
  9034. ltr: function (start, soffset, finish, foffset) {
  9035. var rng = win.document.createRange();
  9036. rng.setStart(start.dom, soffset);
  9037. rng.setEnd(finish.dom, foffset);
  9038. return rng;
  9039. },
  9040. rtl: function (start, soffset, finish, foffset) {
  9041. var rng = win.document.createRange();
  9042. rng.setStart(finish.dom, foffset);
  9043. rng.setEnd(start.dom, soffset);
  9044. return rng;
  9045. }
  9046. });
  9047. };
  9048. adt$2.ltr;
  9049. adt$2.rtl;
  9050. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  9051. if (length === 0) {
  9052. return 0;
  9053. } else if (x === maxX) {
  9054. return length - 1;
  9055. }
  9056. var xDelta = maxX;
  9057. for (var i = 1; i < length; i++) {
  9058. var rect = rectForOffset(i);
  9059. var curDeltaX = Math.abs(x - rect.left);
  9060. if (y <= rect.bottom) {
  9061. if (y < rect.top || curDeltaX > xDelta) {
  9062. return i - 1;
  9063. } else {
  9064. xDelta = curDeltaX;
  9065. }
  9066. }
  9067. }
  9068. return 0;
  9069. };
  9070. var inRect = function (rect, x, y) {
  9071. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  9072. };
  9073. var locateOffset = function (doc, textnode, x, y, rect) {
  9074. var rangeForOffset = function (o) {
  9075. var r = doc.dom.createRange();
  9076. r.setStart(textnode.dom, o);
  9077. r.collapse(true);
  9078. return r;
  9079. };
  9080. var rectForOffset = function (o) {
  9081. var r = rangeForOffset(o);
  9082. return r.getBoundingClientRect();
  9083. };
  9084. var length = get$9(textnode).length;
  9085. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  9086. return rangeForOffset(offset);
  9087. };
  9088. var locate$1 = function (doc, node, x, y) {
  9089. var r = doc.dom.createRange();
  9090. r.selectNode(node.dom);
  9091. var rects = r.getClientRects();
  9092. var foundRect = findMap(rects, function (rect) {
  9093. return inRect(rect, x, y) ? Optional.some(rect) : Optional.none();
  9094. });
  9095. return foundRect.map(function (rect) {
  9096. return locateOffset(doc, node, x, y, rect);
  9097. });
  9098. };
  9099. var searchInChildren = function (doc, node, x, y) {
  9100. var r = doc.dom.createRange();
  9101. var nodes = children$3(node);
  9102. return findMap(nodes, function (n) {
  9103. r.selectNode(n.dom);
  9104. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Optional.none();
  9105. });
  9106. };
  9107. var locateNode = function (doc, node, x, y) {
  9108. return isText(node) ? locate$1(doc, node, x, y) : searchInChildren(doc, node, x, y);
  9109. };
  9110. var locate = function (doc, node, x, y) {
  9111. var r = doc.dom.createRange();
  9112. r.selectNode(node.dom);
  9113. var rect = r.getBoundingClientRect();
  9114. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  9115. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  9116. return locateNode(doc, node, boundedX, boundedY);
  9117. };
  9118. var COLLAPSE_TO_LEFT = true;
  9119. var COLLAPSE_TO_RIGHT = false;
  9120. var getCollapseDirection = function (rect, x) {
  9121. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  9122. };
  9123. var createCollapsedNode = function (doc, target, collapseDirection) {
  9124. var r = doc.dom.createRange();
  9125. r.selectNode(target.dom);
  9126. r.collapse(collapseDirection);
  9127. return r;
  9128. };
  9129. var locateInElement = function (doc, node, x) {
  9130. var cursorRange = doc.dom.createRange();
  9131. cursorRange.selectNode(node.dom);
  9132. var rect = cursorRange.getBoundingClientRect();
  9133. var collapseDirection = getCollapseDirection(rect, x);
  9134. var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
  9135. return f(node).map(function (target) {
  9136. return createCollapsedNode(doc, target, collapseDirection);
  9137. });
  9138. };
  9139. var locateInEmpty = function (doc, node, x) {
  9140. var rect = node.dom.getBoundingClientRect();
  9141. var collapseDirection = getCollapseDirection(rect, x);
  9142. return Optional.some(createCollapsedNode(doc, node, collapseDirection));
  9143. };
  9144. var search = function (doc, node, x) {
  9145. var f = children$3(node).length === 0 ? locateInEmpty : locateInElement;
  9146. return f(doc, node, x);
  9147. };
  9148. var caretPositionFromPoint = function (doc, x, y) {
  9149. var _a, _b;
  9150. return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y)).bind(function (pos) {
  9151. if (pos.offsetNode === null) {
  9152. return Optional.none();
  9153. }
  9154. var r = doc.dom.createRange();
  9155. r.setStart(pos.offsetNode, pos.offset);
  9156. r.collapse();
  9157. return Optional.some(r);
  9158. });
  9159. };
  9160. var caretRangeFromPoint = function (doc, x, y) {
  9161. var _a, _b;
  9162. return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y));
  9163. };
  9164. var searchTextNodes = function (doc, node, x, y) {
  9165. var r = doc.dom.createRange();
  9166. r.selectNode(node.dom);
  9167. var rect = r.getBoundingClientRect();
  9168. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  9169. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  9170. return locate(doc, node, boundedX, boundedY);
  9171. };
  9172. var searchFromPoint = function (doc, x, y) {
  9173. return SugarElement.fromPoint(doc, x, y).bind(function (elem) {
  9174. var fallback = function () {
  9175. return search(doc, elem, x);
  9176. };
  9177. return children$3(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  9178. });
  9179. };
  9180. var availableSearch = function () {
  9181. if (document.caretPositionFromPoint) {
  9182. return caretPositionFromPoint;
  9183. } else if (document.caretRangeFromPoint) {
  9184. return caretRangeFromPoint;
  9185. } else {
  9186. return searchFromPoint;
  9187. }
  9188. }();
  9189. var fromPoint = function (win, x, y) {
  9190. var doc = SugarElement.fromDom(win.document);
  9191. return availableSearch(doc, x, y).map(function (rng) {
  9192. return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
  9193. });
  9194. };
  9195. var beforeSpecial = function (element, offset) {
  9196. var name$1 = name(element);
  9197. if ('input' === name$1) {
  9198. return Situ.after(element);
  9199. } else if (!contains$2([
  9200. 'br',
  9201. 'img'
  9202. ], name$1)) {
  9203. return Situ.on(element, offset);
  9204. } else {
  9205. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9206. }
  9207. };
  9208. var preprocessRelative = function (startSitu, finishSitu) {
  9209. var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9210. var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9211. return SimSelection.relative(start, finish);
  9212. };
  9213. var preprocessExact = function (start, soffset, finish, foffset) {
  9214. var startSitu = beforeSpecial(start, soffset);
  9215. var finishSitu = beforeSpecial(finish, foffset);
  9216. return SimSelection.relative(startSitu, finishSitu);
  9217. };
  9218. var preprocess = function (selection) {
  9219. return selection.match({
  9220. domRange: function (rng) {
  9221. var start = SugarElement.fromDom(rng.startContainer);
  9222. var finish = SugarElement.fromDom(rng.endContainer);
  9223. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  9224. },
  9225. relative: preprocessRelative,
  9226. exact: preprocessExact
  9227. });
  9228. };
  9229. var makeRange = function (start, soffset, finish, foffset) {
  9230. var doc = owner(start);
  9231. var rng = doc.dom.createRange();
  9232. rng.setStart(start.dom, soffset);
  9233. rng.setEnd(finish.dom, foffset);
  9234. return rng;
  9235. };
  9236. var after$2 = function (start, soffset, finish, foffset) {
  9237. var r = makeRange(start, soffset, finish, foffset);
  9238. var same = eq$1(start, finish) && soffset === foffset;
  9239. return r.collapsed && !same;
  9240. };
  9241. var getNativeSelection = function (win) {
  9242. return Optional.from(win.getSelection());
  9243. };
  9244. var doSetNativeRange = function (win, rng) {
  9245. getNativeSelection(win).each(function (selection) {
  9246. selection.removeAllRanges();
  9247. selection.addRange(rng);
  9248. });
  9249. };
  9250. var doSetRange = function (win, start, soffset, finish, foffset) {
  9251. var rng = exactToNative(win, start, soffset, finish, foffset);
  9252. doSetNativeRange(win, rng);
  9253. };
  9254. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9255. selection.collapse(start.dom, soffset);
  9256. selection.extend(finish.dom, foffset);
  9257. };
  9258. var setRangeFromRelative = function (win, relative) {
  9259. return diagnose(win, relative).match({
  9260. ltr: function (start, soffset, finish, foffset) {
  9261. doSetRange(win, start, soffset, finish, foffset);
  9262. },
  9263. rtl: function (start, soffset, finish, foffset) {
  9264. getNativeSelection(win).each(function (selection) {
  9265. if (selection.setBaseAndExtent) {
  9266. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9267. } else if (selection.extend) {
  9268. try {
  9269. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9270. } catch (e) {
  9271. doSetRange(win, finish, foffset, start, soffset);
  9272. }
  9273. } else {
  9274. doSetRange(win, finish, foffset, start, soffset);
  9275. }
  9276. });
  9277. }
  9278. });
  9279. };
  9280. var setExact = function (win, start, soffset, finish, foffset) {
  9281. var relative = preprocessExact(start, soffset, finish, foffset);
  9282. setRangeFromRelative(win, relative);
  9283. };
  9284. var setRelative = function (win, startSitu, finishSitu) {
  9285. var relative = preprocessRelative(startSitu, finishSitu);
  9286. setRangeFromRelative(win, relative);
  9287. };
  9288. var toNative = function (selection) {
  9289. var win = SimSelection.getWin(selection).dom;
  9290. var getDomRange = function (start, soffset, finish, foffset) {
  9291. return exactToNative(win, start, soffset, finish, foffset);
  9292. };
  9293. var filtered = preprocess(selection);
  9294. return diagnose(win, filtered).match({
  9295. ltr: getDomRange,
  9296. rtl: getDomRange
  9297. });
  9298. };
  9299. var readRange = function (selection) {
  9300. if (selection.rangeCount > 0) {
  9301. var firstRng = selection.getRangeAt(0);
  9302. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9303. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9304. } else {
  9305. return Optional.none();
  9306. }
  9307. };
  9308. var doGetExact = function (selection) {
  9309. if (selection.anchorNode === null || selection.focusNode === null) {
  9310. return readRange(selection);
  9311. } else {
  9312. var anchor = SugarElement.fromDom(selection.anchorNode);
  9313. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9314. return after$2(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9315. }
  9316. };
  9317. var setToElement = function (win, element, selectNodeContents$1) {
  9318. if (selectNodeContents$1 === void 0) {
  9319. selectNodeContents$1 = true;
  9320. }
  9321. var rngGetter = selectNodeContents$1 ? selectNodeContents : selectNode;
  9322. var rng = rngGetter(win, element);
  9323. doSetNativeRange(win, rng);
  9324. };
  9325. var getExact = function (win) {
  9326. return getNativeSelection(win).filter(function (sel) {
  9327. return sel.rangeCount > 0;
  9328. }).bind(doGetExact);
  9329. };
  9330. var get$1 = function (win) {
  9331. return getExact(win).map(function (range) {
  9332. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9333. });
  9334. };
  9335. var getFirstRect = function (win, selection) {
  9336. var rng = asLtrRange(win, selection);
  9337. return getFirstRect$1(rng);
  9338. };
  9339. var getAtPoint = function (win, x, y) {
  9340. return fromPoint(win, x, y);
  9341. };
  9342. var clear = function (win) {
  9343. getNativeSelection(win).each(function (selection) {
  9344. return selection.removeAllRanges();
  9345. });
  9346. };
  9347. var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');
  9348. var forward = function (editor, isRoot, cell) {
  9349. return go$1(editor, isRoot, next(cell, isEditable$1));
  9350. };
  9351. var backward = function (editor, isRoot, cell) {
  9352. return go$1(editor, isRoot, prev(cell, isEditable$1));
  9353. };
  9354. var getCellFirstCursorPosition = function (editor, cell) {
  9355. var selection = SimSelection.exact(cell, 0, cell, 0);
  9356. return toNative(selection);
  9357. };
  9358. var go$1 = function (editor, isRoot, cell) {
  9359. return cell.fold(Optional.none, Optional.none, function (current, next) {
  9360. return first(next).map(function (cell) {
  9361. return getCellFirstCursorPosition(editor, cell);
  9362. });
  9363. }, function (current) {
  9364. editor.execCommand('mceTableInsertRowAfter');
  9365. return forward(editor, isRoot, current);
  9366. });
  9367. };
  9368. var rootElements = [
  9369. 'table',
  9370. 'li',
  9371. 'dl'
  9372. ];
  9373. var handle$1 = function (event, editor, cellSelection) {
  9374. if (event.keyCode === global$1.TAB) {
  9375. var body_1 = getBody(editor);
  9376. var isRoot_1 = function (element) {
  9377. var name$1 = name(element);
  9378. return eq$1(element, body_1) || contains$2(rootElements, name$1);
  9379. };
  9380. var rng = editor.selection.getRng();
  9381. var container = SugarElement.fromDom(event.shiftKey ? rng.startContainer : rng.endContainer);
  9382. cell(container, isRoot_1).each(function (cell) {
  9383. event.preventDefault();
  9384. table(cell, isRoot_1).each(cellSelection.clear);
  9385. editor.selection.collapse(event.shiftKey);
  9386. var navigation = event.shiftKey ? backward : forward;
  9387. var rng = navigation(editor, isRoot_1, cell);
  9388. rng.each(function (range) {
  9389. editor.selection.setRng(range);
  9390. });
  9391. });
  9392. }
  9393. };
  9394. var create$1 = function (selection, kill) {
  9395. return {
  9396. selection: selection,
  9397. kill: kill
  9398. };
  9399. };
  9400. var Response = { create: create$1 };
  9401. var create = function (start, soffset, finish, foffset) {
  9402. return {
  9403. start: Situ.on(start, soffset),
  9404. finish: Situ.on(finish, foffset)
  9405. };
  9406. };
  9407. var Situs = { create: create };
  9408. var convertToRange = function (win, selection) {
  9409. var rng = asLtrRange(win, selection);
  9410. return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
  9411. };
  9412. var makeSitus = Situs.create;
  9413. var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
  9414. if (!(eq$1(start, finish) && soffset === foffset)) {
  9415. return closest$1(start, 'td,th', isRoot).bind(function (s) {
  9416. return closest$1(finish, 'td,th', isRoot).bind(function (f) {
  9417. return detect(container, isRoot, s, f, selectRange);
  9418. });
  9419. });
  9420. } else {
  9421. return Optional.none();
  9422. }
  9423. };
  9424. var detect = function (container, isRoot, start, finish, selectRange) {
  9425. if (!eq$1(start, finish)) {
  9426. return identify(start, finish, isRoot).bind(function (cellSel) {
  9427. var boxes = cellSel.boxes.getOr([]);
  9428. if (boxes.length > 1) {
  9429. selectRange(container, boxes, cellSel.start, cellSel.finish);
  9430. return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
  9431. } else {
  9432. return Optional.none();
  9433. }
  9434. });
  9435. } else {
  9436. return Optional.none();
  9437. }
  9438. };
  9439. var update = function (rows, columns, container, selected, annotations) {
  9440. var updateSelection = function (newSels) {
  9441. annotations.clearBeforeUpdate(container);
  9442. annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
  9443. return newSels.boxes;
  9444. };
  9445. return shiftSelection(selected, rows, columns, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
  9446. };
  9447. var traverse = function (item, mode) {
  9448. return {
  9449. item: item,
  9450. mode: mode
  9451. };
  9452. };
  9453. var backtrack = function (universe, item, _direction, transition) {
  9454. if (transition === void 0) {
  9455. transition = sidestep;
  9456. }
  9457. return universe.property().parent(item).map(function (p) {
  9458. return traverse(p, transition);
  9459. });
  9460. };
  9461. var sidestep = function (universe, item, direction, transition) {
  9462. if (transition === void 0) {
  9463. transition = advance;
  9464. }
  9465. return direction.sibling(universe, item).map(function (p) {
  9466. return traverse(p, transition);
  9467. });
  9468. };
  9469. var advance = function (universe, item, direction, transition) {
  9470. if (transition === void 0) {
  9471. transition = advance;
  9472. }
  9473. var children = universe.property().children(item);
  9474. var result = direction.first(children);
  9475. return result.map(function (r) {
  9476. return traverse(r, transition);
  9477. });
  9478. };
  9479. var successors = [
  9480. {
  9481. current: backtrack,
  9482. next: sidestep,
  9483. fallback: Optional.none()
  9484. },
  9485. {
  9486. current: sidestep,
  9487. next: advance,
  9488. fallback: Optional.some(backtrack)
  9489. },
  9490. {
  9491. current: advance,
  9492. next: advance,
  9493. fallback: Optional.some(sidestep)
  9494. }
  9495. ];
  9496. var go = function (universe, item, mode, direction, rules) {
  9497. if (rules === void 0) {
  9498. rules = successors;
  9499. }
  9500. var ruleOpt = find$1(rules, function (succ) {
  9501. return succ.current === mode;
  9502. });
  9503. return ruleOpt.bind(function (rule) {
  9504. return rule.current(universe, item, direction, rule.next).orThunk(function () {
  9505. return rule.fallback.bind(function (fb) {
  9506. return go(universe, item, fb, direction);
  9507. });
  9508. });
  9509. });
  9510. };
  9511. var left$1 = function () {
  9512. var sibling = function (universe, item) {
  9513. return universe.query().prevSibling(item);
  9514. };
  9515. var first = function (children) {
  9516. return children.length > 0 ? Optional.some(children[children.length - 1]) : Optional.none();
  9517. };
  9518. return {
  9519. sibling: sibling,
  9520. first: first
  9521. };
  9522. };
  9523. var right$1 = function () {
  9524. var sibling = function (universe, item) {
  9525. return universe.query().nextSibling(item);
  9526. };
  9527. var first = function (children) {
  9528. return children.length > 0 ? Optional.some(children[0]) : Optional.none();
  9529. };
  9530. return {
  9531. sibling: sibling,
  9532. first: first
  9533. };
  9534. };
  9535. var Walkers = {
  9536. left: left$1,
  9537. right: right$1
  9538. };
  9539. var hone = function (universe, item, predicate, mode, direction, isRoot) {
  9540. var next = go(universe, item, mode, direction);
  9541. return next.bind(function (n) {
  9542. if (isRoot(n.item)) {
  9543. return Optional.none();
  9544. } else {
  9545. return predicate(n.item) ? Optional.some(n.item) : hone(universe, n.item, predicate, n.mode, direction, isRoot);
  9546. }
  9547. });
  9548. };
  9549. var left = function (universe, item, predicate, isRoot) {
  9550. return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
  9551. };
  9552. var right = function (universe, item, predicate, isRoot) {
  9553. return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
  9554. };
  9555. var isLeaf = function (universe) {
  9556. return function (element) {
  9557. return universe.property().children(element).length === 0;
  9558. };
  9559. };
  9560. var before$1 = function (universe, item, isRoot) {
  9561. return seekLeft$1(universe, item, isLeaf(universe), isRoot);
  9562. };
  9563. var after$1 = function (universe, item, isRoot) {
  9564. return seekRight$1(universe, item, isLeaf(universe), isRoot);
  9565. };
  9566. var seekLeft$1 = left;
  9567. var seekRight$1 = right;
  9568. var universe = DomUniverse();
  9569. var before = function (element, isRoot) {
  9570. return before$1(universe, element, isRoot);
  9571. };
  9572. var after = function (element, isRoot) {
  9573. return after$1(universe, element, isRoot);
  9574. };
  9575. var seekLeft = function (element, predicate, isRoot) {
  9576. return seekLeft$1(universe, element, predicate, isRoot);
  9577. };
  9578. var seekRight = function (element, predicate, isRoot) {
  9579. return seekRight$1(universe, element, predicate, isRoot);
  9580. };
  9581. var ancestor = function (scope, predicate, isRoot) {
  9582. return ancestor$2(scope, predicate, isRoot).isSome();
  9583. };
  9584. var adt$1 = Adt.generate([
  9585. { none: ['message'] },
  9586. { success: [] },
  9587. { failedUp: ['cell'] },
  9588. { failedDown: ['cell'] }
  9589. ]);
  9590. var isOverlapping = function (bridge, before, after) {
  9591. var beforeBounds = bridge.getRect(before);
  9592. var afterBounds = bridge.getRect(after);
  9593. return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
  9594. };
  9595. var isRow = function (elem) {
  9596. return closest$1(elem, 'tr');
  9597. };
  9598. var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
  9599. return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
  9600. return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
  9601. if (!eq$1(afterCell, beforeCell)) {
  9602. return sharedOne(isRow, [
  9603. afterCell,
  9604. beforeCell
  9605. ]).fold(function () {
  9606. return isOverlapping(bridge, beforeCell, afterCell) ? adt$1.success() : failure(beforeCell);
  9607. }, function (_sharedRow) {
  9608. return failure(beforeCell);
  9609. });
  9610. } else {
  9611. return eq$1(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$1.none('in same cell');
  9612. }
  9613. });
  9614. }).getOr(adt$1.none('default'));
  9615. };
  9616. var cata = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
  9617. return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
  9618. };
  9619. var BeforeAfter = __assign(__assign({}, adt$1), {
  9620. verify: verify,
  9621. cata: cata
  9622. });
  9623. var inParent = function (parent, children, element, index) {
  9624. return {
  9625. parent: parent,
  9626. children: children,
  9627. element: element,
  9628. index: index
  9629. };
  9630. };
  9631. var indexInParent = function (element) {
  9632. return parent(element).bind(function (parent) {
  9633. var children = children$3(parent);
  9634. return indexOf(children, element).map(function (index) {
  9635. return inParent(parent, children, element, index);
  9636. });
  9637. });
  9638. };
  9639. var indexOf = function (elements, element) {
  9640. return findIndex(elements, curry(eq$1, element));
  9641. };
  9642. var isBr = function (elem) {
  9643. return name(elem) === 'br';
  9644. };
  9645. var gatherer = function (cand, gather, isRoot) {
  9646. return gather(cand, isRoot).bind(function (target) {
  9647. return isText(target) && get$9(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
  9648. });
  9649. };
  9650. var handleBr = function (isRoot, element, direction) {
  9651. return direction.traverse(element).orThunk(function () {
  9652. return gatherer(element, direction.gather, isRoot);
  9653. }).map(direction.relative);
  9654. };
  9655. var findBr = function (element, offset) {
  9656. return child$3(element, offset).filter(isBr).orThunk(function () {
  9657. return child$3(element, offset - 1).filter(isBr);
  9658. });
  9659. };
  9660. var handleParent = function (isRoot, element, offset, direction) {
  9661. return findBr(element, offset).bind(function (br) {
  9662. return direction.traverse(br).fold(function () {
  9663. return gatherer(br, direction.gather, isRoot).map(direction.relative);
  9664. }, function (adjacent) {
  9665. return indexInParent(adjacent).map(function (info) {
  9666. return Situ.on(info.parent, info.index);
  9667. });
  9668. });
  9669. });
  9670. };
  9671. var tryBr = function (isRoot, element, offset, direction) {
  9672. var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
  9673. return target.map(function (tgt) {
  9674. return {
  9675. start: tgt,
  9676. finish: tgt
  9677. };
  9678. });
  9679. };
  9680. var process = function (analysis) {
  9681. return BeforeAfter.cata(analysis, function (_message) {
  9682. return Optional.none();
  9683. }, function () {
  9684. return Optional.none();
  9685. }, function (cell) {
  9686. return Optional.some(point(cell, 0));
  9687. }, function (cell) {
  9688. return Optional.some(point(cell, getEnd(cell)));
  9689. });
  9690. };
  9691. var moveDown = function (caret, amount) {
  9692. return {
  9693. left: caret.left,
  9694. top: caret.top + amount,
  9695. right: caret.right,
  9696. bottom: caret.bottom + amount
  9697. };
  9698. };
  9699. var moveUp = function (caret, amount) {
  9700. return {
  9701. left: caret.left,
  9702. top: caret.top - amount,
  9703. right: caret.right,
  9704. bottom: caret.bottom - amount
  9705. };
  9706. };
  9707. var translate = function (caret, xDelta, yDelta) {
  9708. return {
  9709. left: caret.left + xDelta,
  9710. top: caret.top + yDelta,
  9711. right: caret.right + xDelta,
  9712. bottom: caret.bottom + yDelta
  9713. };
  9714. };
  9715. var getTop = function (caret) {
  9716. return caret.top;
  9717. };
  9718. var getBottom = function (caret) {
  9719. return caret.bottom;
  9720. };
  9721. var getPartialBox = function (bridge, element, offset) {
  9722. if (offset >= 0 && offset < getEnd(element)) {
  9723. return bridge.getRangedRect(element, offset, element, offset + 1);
  9724. } else if (offset > 0) {
  9725. return bridge.getRangedRect(element, offset - 1, element, offset);
  9726. }
  9727. return Optional.none();
  9728. };
  9729. var toCaret = function (rect) {
  9730. return {
  9731. left: rect.left,
  9732. top: rect.top,
  9733. right: rect.right,
  9734. bottom: rect.bottom
  9735. };
  9736. };
  9737. var getElemBox = function (bridge, element) {
  9738. return Optional.some(bridge.getRect(element));
  9739. };
  9740. var getBoxAt = function (bridge, element, offset) {
  9741. if (isElement(element)) {
  9742. return getElemBox(bridge, element).map(toCaret);
  9743. } else if (isText(element)) {
  9744. return getPartialBox(bridge, element, offset).map(toCaret);
  9745. } else {
  9746. return Optional.none();
  9747. }
  9748. };
  9749. var getEntireBox = function (bridge, element) {
  9750. if (isElement(element)) {
  9751. return getElemBox(bridge, element).map(toCaret);
  9752. } else if (isText(element)) {
  9753. return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
  9754. } else {
  9755. return Optional.none();
  9756. }
  9757. };
  9758. var JUMP_SIZE = 5;
  9759. var NUM_RETRIES = 100;
  9760. var adt = Adt.generate([
  9761. { none: [] },
  9762. { retry: ['caret'] }
  9763. ]);
  9764. var isOutside = function (caret, box) {
  9765. return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
  9766. };
  9767. var inOutsideBlock = function (bridge, element, caret) {
  9768. return closest$2(element, isBlock).fold(never, function (cell) {
  9769. return getEntireBox(bridge, cell).exists(function (box) {
  9770. return isOutside(caret, box);
  9771. });
  9772. });
  9773. };
  9774. var adjustDown = function (bridge, element, guessBox, original, caret) {
  9775. var lowerCaret = moveDown(caret, JUMP_SIZE);
  9776. if (Math.abs(guessBox.bottom - original.bottom) < 1) {
  9777. return adt.retry(lowerCaret);
  9778. } else if (guessBox.top > caret.bottom) {
  9779. return adt.retry(lowerCaret);
  9780. } else if (guessBox.top === caret.bottom) {
  9781. return adt.retry(moveDown(caret, 1));
  9782. } else {
  9783. return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt.none();
  9784. }
  9785. };
  9786. var adjustUp = function (bridge, element, guessBox, original, caret) {
  9787. var higherCaret = moveUp(caret, JUMP_SIZE);
  9788. if (Math.abs(guessBox.top - original.top) < 1) {
  9789. return adt.retry(higherCaret);
  9790. } else if (guessBox.bottom < caret.top) {
  9791. return adt.retry(higherCaret);
  9792. } else if (guessBox.bottom === caret.top) {
  9793. return adt.retry(moveUp(caret, 1));
  9794. } else {
  9795. return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt.none();
  9796. }
  9797. };
  9798. var upMovement = {
  9799. point: getTop,
  9800. adjuster: adjustUp,
  9801. move: moveUp,
  9802. gather: before
  9803. };
  9804. var downMovement = {
  9805. point: getBottom,
  9806. adjuster: adjustDown,
  9807. move: moveDown,
  9808. gather: after
  9809. };
  9810. var isAtTable = function (bridge, x, y) {
  9811. return bridge.elementFromPoint(x, y).filter(function (elm) {
  9812. return name(elm) === 'table';
  9813. }).isSome();
  9814. };
  9815. var adjustForTable = function (bridge, movement, original, caret, numRetries) {
  9816. return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
  9817. };
  9818. var adjustTil = function (bridge, movement, original, caret, numRetries) {
  9819. if (numRetries === 0) {
  9820. return Optional.some(caret);
  9821. }
  9822. if (isAtTable(bridge, caret.left, movement.point(caret))) {
  9823. return adjustForTable(bridge, movement, original, caret, numRetries - 1);
  9824. }
  9825. return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function (guess) {
  9826. return guess.start.fold(Optional.none, function (element) {
  9827. return getEntireBox(bridge, element).bind(function (guessBox) {
  9828. return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function (newCaret) {
  9829. return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
  9830. });
  9831. }).orThunk(function () {
  9832. return Optional.some(caret);
  9833. });
  9834. }, Optional.none);
  9835. });
  9836. };
  9837. var ieTryDown = function (bridge, caret) {
  9838. return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
  9839. };
  9840. var ieTryUp = function (bridge, caret) {
  9841. return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
  9842. };
  9843. var checkScroll = function (movement, adjusted, bridge) {
  9844. if (movement.point(adjusted) > bridge.getInnerHeight()) {
  9845. return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
  9846. } else if (movement.point(adjusted) < 0) {
  9847. return Optional.some(-movement.point(adjusted));
  9848. } else {
  9849. return Optional.none();
  9850. }
  9851. };
  9852. var retry = function (movement, bridge, caret) {
  9853. var moved = movement.move(caret, JUMP_SIZE);
  9854. var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
  9855. return checkScroll(movement, adjusted, bridge).fold(function () {
  9856. return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
  9857. }, function (delta) {
  9858. bridge.scrollBy(0, delta);
  9859. return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
  9860. });
  9861. };
  9862. var Retries = {
  9863. tryUp: curry(retry, upMovement),
  9864. tryDown: curry(retry, downMovement),
  9865. ieTryUp: ieTryUp,
  9866. ieTryDown: ieTryDown,
  9867. getJumpSize: constant(JUMP_SIZE)
  9868. };
  9869. var MAX_RETRIES = 20;
  9870. var findSpot = function (bridge, isRoot, direction) {
  9871. return bridge.getSelection().bind(function (sel) {
  9872. return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function () {
  9873. return Optional.some(point(sel.finish, sel.foffset));
  9874. }, function (brNeighbour) {
  9875. var range = bridge.fromSitus(brNeighbour);
  9876. var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range.finish, range.foffset, direction.failure, isRoot);
  9877. return process(analysis);
  9878. });
  9879. });
  9880. };
  9881. var scan = function (bridge, isRoot, element, offset, direction, numRetries) {
  9882. if (numRetries === 0) {
  9883. return Optional.none();
  9884. }
  9885. return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
  9886. var range = bridge.fromSitus(situs);
  9887. var analysis = BeforeAfter.verify(bridge, element, offset, range.finish, range.foffset, direction.failure, isRoot);
  9888. return BeforeAfter.cata(analysis, function () {
  9889. return Optional.none();
  9890. }, function () {
  9891. return Optional.some(situs);
  9892. }, function (cell) {
  9893. if (eq$1(element, cell) && offset === 0) {
  9894. return tryAgain(bridge, element, offset, moveUp, direction);
  9895. } else {
  9896. return scan(bridge, isRoot, cell, 0, direction, numRetries - 1);
  9897. }
  9898. }, function (cell) {
  9899. if (eq$1(element, cell) && offset === getEnd(cell)) {
  9900. return tryAgain(bridge, element, offset, moveDown, direction);
  9901. } else {
  9902. return scan(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
  9903. }
  9904. });
  9905. });
  9906. };
  9907. var tryAgain = function (bridge, element, offset, move, direction) {
  9908. return getBoxAt(bridge, element, offset).bind(function (box) {
  9909. return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
  9910. });
  9911. };
  9912. var tryAt = function (bridge, direction, box) {
  9913. var browser = detect$3().browser;
  9914. if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
  9915. return direction.otherRetry(bridge, box);
  9916. } else if (browser.isIE()) {
  9917. return direction.ieRetry(bridge, box);
  9918. } else {
  9919. return Optional.none();
  9920. }
  9921. };
  9922. var tryCursor = function (bridge, isRoot, element, offset, direction) {
  9923. return getBoxAt(bridge, element, offset).bind(function (box) {
  9924. return tryAt(bridge, direction, box);
  9925. });
  9926. };
  9927. var handle = function (bridge, isRoot, direction) {
  9928. return findSpot(bridge, isRoot, direction).bind(function (spot) {
  9929. return scan(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
  9930. });
  9931. };
  9932. var inSameTable = function (elem, table) {
  9933. return ancestor(elem, function (e) {
  9934. return parent(e).exists(function (p) {
  9935. return eq$1(p, table);
  9936. });
  9937. });
  9938. };
  9939. var simulate = function (bridge, isRoot, direction, initial, anchor) {
  9940. return closest$1(initial, 'td,th', isRoot).bind(function (start) {
  9941. return closest$1(start, 'table', isRoot).bind(function (table) {
  9942. if (!inSameTable(anchor, table)) {
  9943. return Optional.none();
  9944. }
  9945. return handle(bridge, isRoot, direction).bind(function (range) {
  9946. return closest$1(range.finish, 'td,th', isRoot).map(function (finish) {
  9947. return {
  9948. start: start,
  9949. finish: finish,
  9950. range: range
  9951. };
  9952. });
  9953. });
  9954. });
  9955. });
  9956. };
  9957. var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
  9958. if (detect$3().browser.isIE()) {
  9959. return Optional.none();
  9960. } else {
  9961. return precheck(initial, isRoot).orThunk(function () {
  9962. return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
  9963. var range = info.range;
  9964. return Response.create(Optional.some(makeSitus(range.start, range.soffset, range.finish, range.foffset)), true);
  9965. });
  9966. });
  9967. }
  9968. };
  9969. var firstUpCheck = function (initial, isRoot) {
  9970. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  9971. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  9972. var rows = descendants(table, 'tr');
  9973. if (eq$1(startRow, rows[0])) {
  9974. return seekLeft(table, function (element) {
  9975. return last$1(element).isSome();
  9976. }, isRoot).map(function (last) {
  9977. var lastOffset = getEnd(last);
  9978. return Response.create(Optional.some(makeSitus(last, lastOffset, last, lastOffset)), true);
  9979. });
  9980. } else {
  9981. return Optional.none();
  9982. }
  9983. });
  9984. });
  9985. };
  9986. var lastDownCheck = function (initial, isRoot) {
  9987. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  9988. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  9989. var rows = descendants(table, 'tr');
  9990. if (eq$1(startRow, rows[rows.length - 1])) {
  9991. return seekRight(table, function (element) {
  9992. return first(element).isSome();
  9993. }, isRoot).map(function (first) {
  9994. return Response.create(Optional.some(makeSitus(first, 0, first, 0)), true);
  9995. });
  9996. } else {
  9997. return Optional.none();
  9998. }
  9999. });
  10000. });
  10001. };
  10002. var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
  10003. return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
  10004. return detect(container, isRoot, info.start, info.finish, selectRange);
  10005. });
  10006. };
  10007. var findCell = function (target, isRoot) {
  10008. return closest$1(target, 'td,th', isRoot);
  10009. };
  10010. var MouseSelection = function (bridge, container, isRoot, annotations) {
  10011. var cursor = value();
  10012. var clearstate = cursor.clear;
  10013. var applySelection = function (event) {
  10014. cursor.on(function (start) {
  10015. annotations.clearBeforeUpdate(container);
  10016. findCell(event.target, isRoot).each(function (finish) {
  10017. identify(start, finish, isRoot).each(function (cellSel) {
  10018. var boxes = cellSel.boxes.getOr([]);
  10019. if (boxes.length === 1) {
  10020. var singleCell = boxes[0];
  10021. var isNonEditableCell = getRaw(singleCell) === 'false';
  10022. var isCellClosestContentEditable = is(closest(event.target), singleCell, eq$1);
  10023. if (isNonEditableCell && isCellClosestContentEditable) {
  10024. annotations.selectRange(container, boxes, singleCell, singleCell);
  10025. bridge.selectContents(singleCell);
  10026. }
  10027. } else if (boxes.length > 1) {
  10028. annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
  10029. bridge.selectContents(finish);
  10030. }
  10031. });
  10032. });
  10033. });
  10034. };
  10035. var mousedown = function (event) {
  10036. annotations.clear(container);
  10037. findCell(event.target, isRoot).each(cursor.set);
  10038. };
  10039. var mouseover = function (event) {
  10040. applySelection(event);
  10041. };
  10042. var mouseup = function (event) {
  10043. applySelection(event);
  10044. clearstate();
  10045. };
  10046. return {
  10047. clearstate: clearstate,
  10048. mousedown: mousedown,
  10049. mouseover: mouseover,
  10050. mouseup: mouseup
  10051. };
  10052. };
  10053. var down = {
  10054. traverse: nextSibling,
  10055. gather: after,
  10056. relative: Situ.before,
  10057. otherRetry: Retries.tryDown,
  10058. ieRetry: Retries.ieTryDown,
  10059. failure: BeforeAfter.failedDown
  10060. };
  10061. var up = {
  10062. traverse: prevSibling,
  10063. gather: before,
  10064. relative: Situ.before,
  10065. otherRetry: Retries.tryUp,
  10066. ieRetry: Retries.ieTryUp,
  10067. failure: BeforeAfter.failedUp
  10068. };
  10069. var isKey = function (key) {
  10070. return function (keycode) {
  10071. return keycode === key;
  10072. };
  10073. };
  10074. var isUp = isKey(38);
  10075. var isDown = isKey(40);
  10076. var isNavigation = function (keycode) {
  10077. return keycode >= 37 && keycode <= 40;
  10078. };
  10079. var ltr = {
  10080. isBackward: isKey(37),
  10081. isForward: isKey(39)
  10082. };
  10083. var rtl = {
  10084. isBackward: isKey(39),
  10085. isForward: isKey(37)
  10086. };
  10087. var get = function (_DOC) {
  10088. var doc = _DOC !== undefined ? _DOC.dom : document;
  10089. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  10090. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  10091. return SugarPosition(x, y);
  10092. };
  10093. var by = function (x, y, _DOC) {
  10094. var doc = _DOC !== undefined ? _DOC.dom : document;
  10095. var win = doc.defaultView;
  10096. if (win) {
  10097. win.scrollBy(x, y);
  10098. }
  10099. };
  10100. var WindowBridge = function (win) {
  10101. var elementFromPoint = function (x, y) {
  10102. return SugarElement.fromPoint(SugarElement.fromDom(win.document), x, y);
  10103. };
  10104. var getRect = function (element) {
  10105. return element.dom.getBoundingClientRect();
  10106. };
  10107. var getRangedRect = function (start, soffset, finish, foffset) {
  10108. var sel = SimSelection.exact(start, soffset, finish, foffset);
  10109. return getFirstRect(win, sel);
  10110. };
  10111. var getSelection = function () {
  10112. return get$1(win).map(function (exactAdt) {
  10113. return convertToRange(win, exactAdt);
  10114. });
  10115. };
  10116. var fromSitus = function (situs) {
  10117. var relative = SimSelection.relative(situs.start, situs.finish);
  10118. return convertToRange(win, relative);
  10119. };
  10120. var situsFromPoint = function (x, y) {
  10121. return getAtPoint(win, x, y).map(function (exact) {
  10122. return Situs.create(exact.start, exact.soffset, exact.finish, exact.foffset);
  10123. });
  10124. };
  10125. var clearSelection = function () {
  10126. clear(win);
  10127. };
  10128. var collapseSelection = function (toStart) {
  10129. if (toStart === void 0) {
  10130. toStart = false;
  10131. }
  10132. get$1(win).each(function (sel) {
  10133. return sel.fold(function (rng) {
  10134. return rng.collapse(toStart);
  10135. }, function (startSitu, finishSitu) {
  10136. var situ = toStart ? startSitu : finishSitu;
  10137. setRelative(win, situ, situ);
  10138. }, function (start, soffset, finish, foffset) {
  10139. var node = toStart ? start : finish;
  10140. var offset = toStart ? soffset : foffset;
  10141. setExact(win, node, offset, node, offset);
  10142. });
  10143. });
  10144. };
  10145. var selectNode = function (element) {
  10146. setToElement(win, element, false);
  10147. };
  10148. var selectContents = function (element) {
  10149. setToElement(win, element);
  10150. };
  10151. var setSelection = function (sel) {
  10152. setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
  10153. };
  10154. var setRelativeSelection = function (start, finish) {
  10155. setRelative(win, start, finish);
  10156. };
  10157. var getInnerHeight = function () {
  10158. return win.innerHeight;
  10159. };
  10160. var getScrollY = function () {
  10161. var pos = get(SugarElement.fromDom(win.document));
  10162. return pos.top;
  10163. };
  10164. var scrollBy = function (x, y) {
  10165. by(x, y, SugarElement.fromDom(win.document));
  10166. };
  10167. return {
  10168. elementFromPoint: elementFromPoint,
  10169. getRect: getRect,
  10170. getRangedRect: getRangedRect,
  10171. getSelection: getSelection,
  10172. fromSitus: fromSitus,
  10173. situsFromPoint: situsFromPoint,
  10174. clearSelection: clearSelection,
  10175. collapseSelection: collapseSelection,
  10176. setSelection: setSelection,
  10177. setRelativeSelection: setRelativeSelection,
  10178. selectNode: selectNode,
  10179. selectContents: selectContents,
  10180. getInnerHeight: getInnerHeight,
  10181. getScrollY: getScrollY,
  10182. scrollBy: scrollBy
  10183. };
  10184. };
  10185. var rc = function (rows, cols) {
  10186. return {
  10187. rows: rows,
  10188. cols: cols
  10189. };
  10190. };
  10191. var mouse = function (win, container, isRoot, annotations) {
  10192. var bridge = WindowBridge(win);
  10193. var handlers = MouseSelection(bridge, container, isRoot, annotations);
  10194. return {
  10195. clearstate: handlers.clearstate,
  10196. mousedown: handlers.mousedown,
  10197. mouseover: handlers.mouseover,
  10198. mouseup: handlers.mouseup
  10199. };
  10200. };
  10201. var keyboard = function (win, container, isRoot, annotations) {
  10202. var bridge = WindowBridge(win);
  10203. var clearToNavigate = function () {
  10204. annotations.clear(container);
  10205. return Optional.none();
  10206. };
  10207. var keydown = function (event, start, soffset, finish, foffset, direction) {
  10208. var realEvent = event.raw;
  10209. var keycode = realEvent.which;
  10210. var shiftKey = realEvent.shiftKey === true;
  10211. var handler = retrieve$1(container, annotations.selectedSelector).fold(function () {
  10212. if (isNavigation(keycode) && !shiftKey) {
  10213. annotations.clearBeforeUpdate(container);
  10214. }
  10215. if (isDown(keycode) && shiftKey) {
  10216. return curry(select, bridge, container, isRoot, down, finish, start, annotations.selectRange);
  10217. } else if (isUp(keycode) && shiftKey) {
  10218. return curry(select, bridge, container, isRoot, up, finish, start, annotations.selectRange);
  10219. } else if (isDown(keycode)) {
  10220. return curry(navigate, bridge, isRoot, down, finish, start, lastDownCheck);
  10221. } else if (isUp(keycode)) {
  10222. return curry(navigate, bridge, isRoot, up, finish, start, firstUpCheck);
  10223. } else {
  10224. return Optional.none;
  10225. }
  10226. }, function (selected) {
  10227. var update$1 = function (attempts) {
  10228. return function () {
  10229. var navigation = findMap(attempts, function (delta) {
  10230. return update(delta.rows, delta.cols, container, selected, annotations);
  10231. });
  10232. return navigation.fold(function () {
  10233. return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function (edges) {
  10234. var relative = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
  10235. bridge.setRelativeSelection(Situ.on(edges.first, 0), relative(edges.table));
  10236. annotations.clear(container);
  10237. return Response.create(Optional.none(), true);
  10238. });
  10239. }, function (_) {
  10240. return Optional.some(Response.create(Optional.none(), true));
  10241. });
  10242. };
  10243. };
  10244. if (isDown(keycode) && shiftKey) {
  10245. return update$1([rc(+1, 0)]);
  10246. } else if (isUp(keycode) && shiftKey) {
  10247. return update$1([rc(-1, 0)]);
  10248. } else if (direction.isBackward(keycode) && shiftKey) {
  10249. return update$1([
  10250. rc(0, -1),
  10251. rc(-1, 0)
  10252. ]);
  10253. } else if (direction.isForward(keycode) && shiftKey) {
  10254. return update$1([
  10255. rc(0, +1),
  10256. rc(+1, 0)
  10257. ]);
  10258. } else if (isNavigation(keycode) && !shiftKey) {
  10259. return clearToNavigate;
  10260. } else {
  10261. return Optional.none;
  10262. }
  10263. });
  10264. return handler();
  10265. };
  10266. var keyup = function (event, start, soffset, finish, foffset) {
  10267. return retrieve$1(container, annotations.selectedSelector).fold(function () {
  10268. var realEvent = event.raw;
  10269. var keycode = realEvent.which;
  10270. var shiftKey = realEvent.shiftKey === true;
  10271. if (!shiftKey) {
  10272. return Optional.none();
  10273. }
  10274. if (isNavigation(keycode)) {
  10275. return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
  10276. } else {
  10277. return Optional.none();
  10278. }
  10279. }, Optional.none);
  10280. };
  10281. return {
  10282. keydown: keydown,
  10283. keyup: keyup
  10284. };
  10285. };
  10286. var external = function (win, container, isRoot, annotations) {
  10287. var bridge = WindowBridge(win);
  10288. return function (start, finish) {
  10289. annotations.clearBeforeUpdate(container);
  10290. identify(start, finish, isRoot).each(function (cellSel) {
  10291. var boxes = cellSel.boxes.getOr([]);
  10292. annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
  10293. bridge.selectContents(finish);
  10294. bridge.collapseSelection();
  10295. });
  10296. };
  10297. };
  10298. var remove = function (element, classes) {
  10299. each$2(classes, function (x) {
  10300. remove$2(element, x);
  10301. });
  10302. };
  10303. var addClass = function (clazz) {
  10304. return function (element) {
  10305. add(element, clazz);
  10306. };
  10307. };
  10308. var removeClasses = function (classes) {
  10309. return function (element) {
  10310. remove(element, classes);
  10311. };
  10312. };
  10313. var byClass = function (ephemera) {
  10314. var addSelectionClass = addClass(ephemera.selected);
  10315. var removeSelectionClasses = removeClasses([
  10316. ephemera.selected,
  10317. ephemera.lastSelected,
  10318. ephemera.firstSelected
  10319. ]);
  10320. var clear = function (container) {
  10321. var sels = descendants(container, ephemera.selectedSelector);
  10322. each$2(sels, removeSelectionClasses);
  10323. };
  10324. var selectRange = function (container, cells, start, finish) {
  10325. clear(container);
  10326. each$2(cells, addSelectionClass);
  10327. add(start, ephemera.firstSelected);
  10328. add(finish, ephemera.lastSelected);
  10329. };
  10330. return {
  10331. clearBeforeUpdate: clear,
  10332. clear: clear,
  10333. selectRange: selectRange,
  10334. selectedSelector: ephemera.selectedSelector,
  10335. firstSelectedSelector: ephemera.firstSelectedSelector,
  10336. lastSelectedSelector: ephemera.lastSelectedSelector
  10337. };
  10338. };
  10339. var byAttr = function (ephemera, onSelection, onClear) {
  10340. var removeSelectionAttributes = function (element) {
  10341. remove$7(element, ephemera.selected);
  10342. remove$7(element, ephemera.firstSelected);
  10343. remove$7(element, ephemera.lastSelected);
  10344. };
  10345. var addSelectionAttribute = function (element) {
  10346. set$2(element, ephemera.selected, '1');
  10347. };
  10348. var clear = function (container) {
  10349. clearBeforeUpdate(container);
  10350. onClear();
  10351. };
  10352. var clearBeforeUpdate = function (container) {
  10353. var sels = descendants(container, ephemera.selectedSelector + ',' + ephemera.firstSelectedSelector + ',' + ephemera.lastSelectedSelector);
  10354. each$2(sels, removeSelectionAttributes);
  10355. };
  10356. var selectRange = function (container, cells, start, finish) {
  10357. clear(container);
  10358. each$2(cells, addSelectionAttribute);
  10359. set$2(start, ephemera.firstSelected, '1');
  10360. set$2(finish, ephemera.lastSelected, '1');
  10361. onSelection(cells, start, finish);
  10362. };
  10363. return {
  10364. clearBeforeUpdate: clearBeforeUpdate,
  10365. clear: clear,
  10366. selectRange: selectRange,
  10367. selectedSelector: ephemera.selectedSelector,
  10368. firstSelectedSelector: ephemera.firstSelectedSelector,
  10369. lastSelectedSelector: ephemera.lastSelectedSelector
  10370. };
  10371. };
  10372. var SelectionAnnotation = {
  10373. byClass: byClass,
  10374. byAttr: byAttr
  10375. };
  10376. var getUpOrLeftCells = function (grid, selectedCells) {
  10377. var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row + 1);
  10378. var upDetails = toDetailList(upGrid);
  10379. return bind$2(upDetails, function (detail) {
  10380. var slicedCells = detail.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
  10381. return map$1(slicedCells, function (cell) {
  10382. return cell.element;
  10383. });
  10384. });
  10385. };
  10386. var getDownOrRightCells = function (grid, selectedCells) {
  10387. var downGrid = grid.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid.length);
  10388. var downDetails = toDetailList(downGrid);
  10389. return bind$2(downDetails, function (detail) {
  10390. var slicedCells = detail.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail.cells.length);
  10391. return map$1(slicedCells, function (cell) {
  10392. return cell.element;
  10393. });
  10394. });
  10395. };
  10396. var getOtherCells = function (table, target, generators) {
  10397. var warehouse = Warehouse.fromTable(table);
  10398. var details = onCells(warehouse, target);
  10399. return details.map(function (selectedCells) {
  10400. var grid = toGrid(warehouse, generators, false);
  10401. var upOrLeftCells = getUpOrLeftCells(grid, selectedCells);
  10402. var downOrRightCells = getDownOrRightCells(grid, selectedCells);
  10403. return {
  10404. upOrLeftCells: upOrLeftCells,
  10405. downOrRightCells: downOrRightCells
  10406. };
  10407. });
  10408. };
  10409. var global = tinymce.util.Tools.resolve('tinymce.Env');
  10410. var hasInternalTarget = function (e) {
  10411. return has(SugarElement.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
  10412. };
  10413. function CellSelection (editor, lazyResize, selectionTargets) {
  10414. var onSelection = function (cells, start, finish) {
  10415. selectionTargets.targets().each(function (targets) {
  10416. var tableOpt = table(start);
  10417. tableOpt.each(function (table) {
  10418. var cloneFormats = getCloneElements(editor);
  10419. var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), cloneFormats);
  10420. var otherCells = getOtherCells(table, targets, generators);
  10421. fireTableSelectionChange(editor, cells, start, finish, otherCells);
  10422. });
  10423. });
  10424. };
  10425. var onClear = function () {
  10426. return fireTableSelectionClear(editor);
  10427. };
  10428. var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
  10429. editor.on('init', function (_e) {
  10430. var win = editor.getWin();
  10431. var body = getBody(editor);
  10432. var isRoot = getIsRoot(editor);
  10433. var syncSelection = function () {
  10434. var sel = editor.selection;
  10435. var start = SugarElement.fromDom(sel.getStart());
  10436. var end = SugarElement.fromDom(sel.getEnd());
  10437. var shared = sharedOne(table, [
  10438. start,
  10439. end
  10440. ]);
  10441. shared.fold(function () {
  10442. return annotations.clear(body);
  10443. }, noop);
  10444. };
  10445. var mouseHandlers = mouse(win, body, isRoot, annotations);
  10446. var keyHandlers = keyboard(win, body, isRoot, annotations);
  10447. var external$1 = external(win, body, isRoot, annotations);
  10448. var hasShiftKey = function (event) {
  10449. return event.raw.shiftKey === true;
  10450. };
  10451. editor.on('TableSelectorChange', function (e) {
  10452. return external$1(e.start, e.finish);
  10453. });
  10454. var handleResponse = function (event, response) {
  10455. if (!hasShiftKey(event)) {
  10456. return;
  10457. }
  10458. if (response.kill) {
  10459. event.kill();
  10460. }
  10461. response.selection.each(function (ns) {
  10462. var relative = SimSelection.relative(ns.start, ns.finish);
  10463. var rng = asLtrRange(win, relative);
  10464. editor.selection.setRng(rng);
  10465. });
  10466. };
  10467. var keyup = function (event) {
  10468. var wrappedEvent = fromRawEvent(event);
  10469. if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
  10470. var rng = editor.selection.getRng();
  10471. var start = SugarElement.fromDom(rng.startContainer);
  10472. var end = SugarElement.fromDom(rng.endContainer);
  10473. keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
  10474. handleResponse(wrappedEvent, response);
  10475. });
  10476. }
  10477. };
  10478. var keydown = function (event) {
  10479. var wrappedEvent = fromRawEvent(event);
  10480. lazyResize().each(function (resize) {
  10481. return resize.hideBars();
  10482. });
  10483. var rng = editor.selection.getRng();
  10484. var start = SugarElement.fromDom(rng.startContainer);
  10485. var end = SugarElement.fromDom(rng.endContainer);
  10486. var direction = onDirection(ltr, rtl)(SugarElement.fromDom(editor.selection.getStart()));
  10487. keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
  10488. handleResponse(wrappedEvent, response);
  10489. });
  10490. lazyResize().each(function (resize) {
  10491. return resize.showBars();
  10492. });
  10493. };
  10494. var isLeftMouse = function (raw) {
  10495. return raw.button === 0;
  10496. };
  10497. var isLeftButtonPressed = function (raw) {
  10498. if (raw.buttons === undefined) {
  10499. return true;
  10500. }
  10501. if (global.browser.isEdge() && raw.buttons === 0) {
  10502. return true;
  10503. }
  10504. return (raw.buttons & 1) !== 0;
  10505. };
  10506. var dragStart = function (_e) {
  10507. mouseHandlers.clearstate();
  10508. };
  10509. var mouseDown = function (e) {
  10510. if (isLeftMouse(e) && hasInternalTarget(e)) {
  10511. mouseHandlers.mousedown(fromRawEvent(e));
  10512. }
  10513. };
  10514. var mouseOver = function (e) {
  10515. if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
  10516. mouseHandlers.mouseover(fromRawEvent(e));
  10517. }
  10518. };
  10519. var mouseUp = function (e) {
  10520. if (isLeftMouse(e) && hasInternalTarget(e)) {
  10521. mouseHandlers.mouseup(fromRawEvent(e));
  10522. }
  10523. };
  10524. var getDoubleTap = function () {
  10525. var lastTarget = Cell(SugarElement.fromDom(body));
  10526. var lastTimeStamp = Cell(0);
  10527. var touchEnd = function (t) {
  10528. var target = SugarElement.fromDom(t.target);
  10529. if (name(target) === 'td' || name(target) === 'th') {
  10530. var lT = lastTarget.get();
  10531. var lTS = lastTimeStamp.get();
  10532. if (eq$1(lT, target) && t.timeStamp - lTS < 300) {
  10533. t.preventDefault();
  10534. external$1(target, target);
  10535. }
  10536. }
  10537. lastTarget.set(target);
  10538. lastTimeStamp.set(t.timeStamp);
  10539. };
  10540. return { touchEnd: touchEnd };
  10541. };
  10542. var doubleTap = getDoubleTap();
  10543. editor.on('dragstart', dragStart);
  10544. editor.on('mousedown', mouseDown);
  10545. editor.on('mouseover', mouseOver);
  10546. editor.on('mouseup', mouseUp);
  10547. editor.on('touchend', doubleTap.touchEnd);
  10548. editor.on('keyup', keyup);
  10549. editor.on('keydown', keydown);
  10550. editor.on('NodeChange', syncSelection);
  10551. });
  10552. return { clear: annotations.clear };
  10553. }
  10554. var child = function (scope, selector) {
  10555. return child$1(scope, selector).isSome();
  10556. };
  10557. var getSelectionTargets = function (editor, selections) {
  10558. var targets = Cell(Optional.none());
  10559. var changeHandlers = Cell([]);
  10560. var selectionDetails = Optional.none();
  10561. var isCaption = isTag('caption');
  10562. var isDisabledForSelection = function (key) {
  10563. return selectionDetails.forall(function (details) {
  10564. return !details[key];
  10565. });
  10566. };
  10567. var getStart = function () {
  10568. return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  10569. };
  10570. var getEnd = function () {
  10571. return getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
  10572. };
  10573. var findTargets = function () {
  10574. return getStart().bind(function (startCellOrCaption) {
  10575. return flatten(lift2(table(startCellOrCaption), getEnd().bind(table), function (startTable, endTable) {
  10576. if (eq$1(startTable, endTable)) {
  10577. if (isCaption(startCellOrCaption)) {
  10578. return Optional.some(noMenu(startCellOrCaption));
  10579. } else {
  10580. return Optional.some(forMenu(selections, startTable, startCellOrCaption));
  10581. }
  10582. }
  10583. return Optional.none();
  10584. }));
  10585. });
  10586. };
  10587. var getExtractedDetails = function (targets) {
  10588. var tableOpt = table(targets.element);
  10589. return tableOpt.map(function (table) {
  10590. var warehouse = Warehouse.fromTable(table);
  10591. var selectedCells = onCells(warehouse, targets).getOr([]);
  10592. var locked = foldl(selectedCells, function (acc, cell) {
  10593. if (cell.isLocked) {
  10594. acc.onAny = true;
  10595. if (cell.column === 0) {
  10596. acc.onFirst = true;
  10597. } else if (cell.column + cell.colspan >= warehouse.grid.columns) {
  10598. acc.onLast = true;
  10599. }
  10600. }
  10601. return acc;
  10602. }, {
  10603. onAny: false,
  10604. onFirst: false,
  10605. onLast: false
  10606. });
  10607. return {
  10608. mergeable: onUnlockedMergable(warehouse, targets).isSome(),
  10609. unmergeable: onUnlockedUnmergable(warehouse, targets).isSome(),
  10610. locked: locked
  10611. };
  10612. });
  10613. };
  10614. var resetTargets = function () {
  10615. targets.set(cached(findTargets)());
  10616. selectionDetails = targets.get().bind(getExtractedDetails);
  10617. each$2(changeHandlers.get(), function (handler) {
  10618. return handler();
  10619. });
  10620. };
  10621. var setupHandler = function (handler) {
  10622. handler();
  10623. changeHandlers.set(changeHandlers.get().concat([handler]));
  10624. return function () {
  10625. changeHandlers.set(filter$2(changeHandlers.get(), function (h) {
  10626. return h !== handler;
  10627. }));
  10628. };
  10629. };
  10630. var onSetup = function (api, isDisabled) {
  10631. return setupHandler(function () {
  10632. return targets.get().fold(function () {
  10633. api.setDisabled(true);
  10634. }, function (targets) {
  10635. api.setDisabled(isDisabled(targets));
  10636. });
  10637. });
  10638. };
  10639. var onSetupWithToggle = function (api, isDisabled, isActive) {
  10640. return setupHandler(function () {
  10641. return targets.get().fold(function () {
  10642. api.setDisabled(true);
  10643. api.setActive(false);
  10644. }, function (targets) {
  10645. api.setDisabled(isDisabled(targets));
  10646. api.setActive(isActive(targets));
  10647. });
  10648. });
  10649. };
  10650. var isDisabledFromLocked = function (lockedDisable) {
  10651. return selectionDetails.exists(function (details) {
  10652. return details.locked[lockedDisable];
  10653. });
  10654. };
  10655. var onSetupTable = function (api) {
  10656. return onSetup(api, function (_) {
  10657. return false;
  10658. });
  10659. };
  10660. var onSetupCellOrRow = function (api) {
  10661. return onSetup(api, function (targets) {
  10662. return isCaption(targets.element);
  10663. });
  10664. };
  10665. var onSetupColumn = function (lockedDisable) {
  10666. return function (api) {
  10667. return onSetup(api, function (targets) {
  10668. return isCaption(targets.element) || isDisabledFromLocked(lockedDisable);
  10669. });
  10670. };
  10671. };
  10672. var onSetupPasteable = function (getClipboardData) {
  10673. return function (api) {
  10674. return onSetup(api, function (targets) {
  10675. return isCaption(targets.element) || getClipboardData().isNone();
  10676. });
  10677. };
  10678. };
  10679. var onSetupPasteableColumn = function (getClipboardData, lockedDisable) {
  10680. return function (api) {
  10681. return onSetup(api, function (targets) {
  10682. return isCaption(targets.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable);
  10683. });
  10684. };
  10685. };
  10686. var onSetupMergeable = function (api) {
  10687. return onSetup(api, function (_targets) {
  10688. return isDisabledForSelection('mergeable');
  10689. });
  10690. };
  10691. var onSetupUnmergeable = function (api) {
  10692. return onSetup(api, function (_targets) {
  10693. return isDisabledForSelection('unmergeable');
  10694. });
  10695. };
  10696. var onSetupTableWithCaption = function (api) {
  10697. return onSetupWithToggle(api, never, function (targets) {
  10698. var tableOpt = table(targets.element, getIsRoot(editor));
  10699. return tableOpt.exists(function (table) {
  10700. return child(table, 'caption');
  10701. });
  10702. });
  10703. };
  10704. var onSetupTableHeaders = function (command, headerType) {
  10705. return function (api) {
  10706. return onSetupWithToggle(api, function (targets) {
  10707. return isCaption(targets.element);
  10708. }, function () {
  10709. return editor.queryCommandValue(command) === headerType;
  10710. });
  10711. };
  10712. };
  10713. var onSetupTableRowHeaders = onSetupTableHeaders('mceTableRowType', 'header');
  10714. var onSetupTableColumnHeaders = onSetupTableHeaders('mceTableColType', 'th');
  10715. editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
  10716. return {
  10717. onSetupTable: onSetupTable,
  10718. onSetupCellOrRow: onSetupCellOrRow,
  10719. onSetupColumn: onSetupColumn,
  10720. onSetupPasteable: onSetupPasteable,
  10721. onSetupPasteableColumn: onSetupPasteableColumn,
  10722. onSetupMergeable: onSetupMergeable,
  10723. onSetupUnmergeable: onSetupUnmergeable,
  10724. resetTargets: resetTargets,
  10725. onSetupTableWithCaption: onSetupTableWithCaption,
  10726. onSetupTableRowHeaders: onSetupTableRowHeaders,
  10727. onSetupTableColumnHeaders: onSetupTableColumnHeaders,
  10728. targets: targets.get
  10729. };
  10730. };
  10731. var addButtons = function (editor, selections, selectionTargets, clipboard) {
  10732. editor.ui.registry.addMenuButton('table', {
  10733. tooltip: 'Table',
  10734. icon: 'table',
  10735. fetch: function (callback) {
  10736. return callback('inserttable | cell row column | advtablesort | tableprops deletetable');
  10737. }
  10738. });
  10739. var cmd = function (command) {
  10740. return function () {
  10741. return editor.execCommand(command);
  10742. };
  10743. };
  10744. editor.ui.registry.addButton('tableprops', {
  10745. tooltip: 'Table properties',
  10746. onAction: cmd('mceTableProps'),
  10747. icon: 'table',
  10748. onSetup: selectionTargets.onSetupTable
  10749. });
  10750. editor.ui.registry.addButton('tabledelete', {
  10751. tooltip: 'Delete table',
  10752. onAction: cmd('mceTableDelete'),
  10753. icon: 'table-delete-table',
  10754. onSetup: selectionTargets.onSetupTable
  10755. });
  10756. editor.ui.registry.addButton('tablecellprops', {
  10757. tooltip: 'Cell properties',
  10758. onAction: cmd('mceTableCellProps'),
  10759. icon: 'table-cell-properties',
  10760. onSetup: selectionTargets.onSetupCellOrRow
  10761. });
  10762. editor.ui.registry.addButton('tablemergecells', {
  10763. tooltip: 'Merge cells',
  10764. onAction: cmd('mceTableMergeCells'),
  10765. icon: 'table-merge-cells',
  10766. onSetup: selectionTargets.onSetupMergeable
  10767. });
  10768. editor.ui.registry.addButton('tablesplitcells', {
  10769. tooltip: 'Split cell',
  10770. onAction: cmd('mceTableSplitCells'),
  10771. icon: 'table-split-cells',
  10772. onSetup: selectionTargets.onSetupUnmergeable
  10773. });
  10774. editor.ui.registry.addButton('tableinsertrowbefore', {
  10775. tooltip: 'Insert row before',
  10776. onAction: cmd('mceTableInsertRowBefore'),
  10777. icon: 'table-insert-row-above',
  10778. onSetup: selectionTargets.onSetupCellOrRow
  10779. });
  10780. editor.ui.registry.addButton('tableinsertrowafter', {
  10781. tooltip: 'Insert row after',
  10782. onAction: cmd('mceTableInsertRowAfter'),
  10783. icon: 'table-insert-row-after',
  10784. onSetup: selectionTargets.onSetupCellOrRow
  10785. });
  10786. editor.ui.registry.addButton('tabledeleterow', {
  10787. tooltip: 'Delete row',
  10788. onAction: cmd('mceTableDeleteRow'),
  10789. icon: 'table-delete-row',
  10790. onSetup: selectionTargets.onSetupCellOrRow
  10791. });
  10792. editor.ui.registry.addButton('tablerowprops', {
  10793. tooltip: 'Row properties',
  10794. onAction: cmd('mceTableRowProps'),
  10795. icon: 'table-row-properties',
  10796. onSetup: selectionTargets.onSetupCellOrRow
  10797. });
  10798. editor.ui.registry.addButton('tableinsertcolbefore', {
  10799. tooltip: 'Insert column before',
  10800. onAction: cmd('mceTableInsertColBefore'),
  10801. icon: 'table-insert-column-before',
  10802. onSetup: selectionTargets.onSetupColumn('onFirst')
  10803. });
  10804. editor.ui.registry.addButton('tableinsertcolafter', {
  10805. tooltip: 'Insert column after',
  10806. onAction: cmd('mceTableInsertColAfter'),
  10807. icon: 'table-insert-column-after',
  10808. onSetup: selectionTargets.onSetupColumn('onLast')
  10809. });
  10810. editor.ui.registry.addButton('tabledeletecol', {
  10811. tooltip: 'Delete column',
  10812. onAction: cmd('mceTableDeleteCol'),
  10813. icon: 'table-delete-column',
  10814. onSetup: selectionTargets.onSetupColumn('onAny')
  10815. });
  10816. editor.ui.registry.addButton('tablecutrow', {
  10817. tooltip: 'Cut row',
  10818. icon: 'cut-row',
  10819. onAction: cmd('mceTableCutRow'),
  10820. onSetup: selectionTargets.onSetupCellOrRow
  10821. });
  10822. editor.ui.registry.addButton('tablecopyrow', {
  10823. tooltip: 'Copy row',
  10824. icon: 'duplicate-row',
  10825. onAction: cmd('mceTableCopyRow'),
  10826. onSetup: selectionTargets.onSetupCellOrRow
  10827. });
  10828. editor.ui.registry.addButton('tablepasterowbefore', {
  10829. tooltip: 'Paste row before',
  10830. icon: 'paste-row-before',
  10831. onAction: cmd('mceTablePasteRowBefore'),
  10832. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10833. });
  10834. editor.ui.registry.addButton('tablepasterowafter', {
  10835. tooltip: 'Paste row after',
  10836. icon: 'paste-row-after',
  10837. onAction: cmd('mceTablePasteRowAfter'),
  10838. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10839. });
  10840. editor.ui.registry.addButton('tablecutcol', {
  10841. tooltip: 'Cut column',
  10842. icon: 'cut-column',
  10843. onAction: cmd('mceTableCutCol'),
  10844. onSetup: selectionTargets.onSetupColumn('onAny')
  10845. });
  10846. editor.ui.registry.addButton('tablecopycol', {
  10847. tooltip: 'Copy column',
  10848. icon: 'duplicate-column',
  10849. onAction: cmd('mceTableCopyCol'),
  10850. onSetup: selectionTargets.onSetupColumn('onAny')
  10851. });
  10852. editor.ui.registry.addButton('tablepastecolbefore', {
  10853. tooltip: 'Paste column before',
  10854. icon: 'paste-column-before',
  10855. onAction: cmd('mceTablePasteColBefore'),
  10856. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
  10857. });
  10858. editor.ui.registry.addButton('tablepastecolafter', {
  10859. tooltip: 'Paste column after',
  10860. icon: 'paste-column-after',
  10861. onAction: cmd('mceTablePasteColAfter'),
  10862. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
  10863. });
  10864. editor.ui.registry.addButton('tableinsertdialog', {
  10865. tooltip: 'Insert table',
  10866. onAction: cmd('mceInsertTable'),
  10867. icon: 'table'
  10868. });
  10869. var tableClassList = filterNoneItem(getTableClassList(editor));
  10870. if (tableClassList.length !== 0) {
  10871. editor.ui.registry.addMenuButton('tableclass', {
  10872. icon: 'table-classes',
  10873. tooltip: 'Table styles',
  10874. fetch: generateMenuItemsCallback(editor, selections, tableClassList, 'tableclass', function (value) {
  10875. return editor.execCommand('mceTableToggleClass', false, value);
  10876. }),
  10877. onSetup: selectionTargets.onSetupTable
  10878. });
  10879. }
  10880. var tableCellClassList = filterNoneItem(getCellClassList(editor));
  10881. if (tableCellClassList.length !== 0) {
  10882. editor.ui.registry.addMenuButton('tablecellclass', {
  10883. icon: 'table-cell-classes',
  10884. tooltip: 'Cell styles',
  10885. fetch: generateMenuItemsCallback(editor, selections, tableCellClassList, 'tablecellclass', function (value) {
  10886. return editor.execCommand('mceTableCellToggleClass', false, value);
  10887. }),
  10888. onSetup: selectionTargets.onSetupCellOrRow
  10889. });
  10890. }
  10891. editor.ui.registry.addMenuButton('tablecellvalign', {
  10892. icon: 'vertical-align',
  10893. tooltip: 'Vertical align',
  10894. fetch: generateMenuItemsCallback(editor, selections, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
  10895. onSetup: selectionTargets.onSetupCellOrRow
  10896. });
  10897. editor.ui.registry.addMenuButton('tablecellborderwidth', {
  10898. icon: 'border-width',
  10899. tooltip: 'Border width',
  10900. fetch: generateMenuItemsCallback(editor, selections, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
  10901. onSetup: selectionTargets.onSetupCellOrRow
  10902. });
  10903. editor.ui.registry.addMenuButton('tablecellborderstyle', {
  10904. icon: 'border-style',
  10905. tooltip: 'Border style',
  10906. fetch: generateMenuItemsCallback(editor, selections, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
  10907. onSetup: selectionTargets.onSetupCellOrRow
  10908. });
  10909. editor.ui.registry.addToggleButton('tablecaption', {
  10910. tooltip: 'Table caption',
  10911. onAction: cmd('mceTableToggleCaption'),
  10912. icon: 'table-caption',
  10913. onSetup: selectionTargets.onSetupTableWithCaption
  10914. });
  10915. editor.ui.registry.addMenuButton('tablecellbackgroundcolor', {
  10916. icon: 'cell-background-color',
  10917. tooltip: 'Background color',
  10918. fetch: function (callback) {
  10919. return callback(buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color'));
  10920. },
  10921. onSetup: selectionTargets.onSetupCellOrRow
  10922. });
  10923. editor.ui.registry.addMenuButton('tablecellbordercolor', {
  10924. icon: 'cell-border-color',
  10925. tooltip: 'Border color',
  10926. fetch: function (callback) {
  10927. return callback(buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color'));
  10928. },
  10929. onSetup: selectionTargets.onSetupCellOrRow
  10930. });
  10931. editor.ui.registry.addToggleButton('tablerowheader', {
  10932. tooltip: 'Row header',
  10933. icon: 'table-top-header',
  10934. onAction: changeRowHeader(editor),
  10935. onSetup: selectionTargets.onSetupTableRowHeaders
  10936. });
  10937. editor.ui.registry.addToggleButton('tablecolheader', {
  10938. tooltip: 'Column header',
  10939. icon: 'table-left-header',
  10940. onAction: changeColumnHeader(editor),
  10941. onSetup: selectionTargets.onSetupTableColumnHeaders
  10942. });
  10943. };
  10944. var addToolbars = function (editor) {
  10945. var isTable = function (table) {
  10946. return editor.dom.is(table, 'table') && editor.getBody().contains(table);
  10947. };
  10948. var toolbar = getToolbar(editor);
  10949. if (toolbar.length > 0) {
  10950. editor.ui.registry.addContextToolbar('table', {
  10951. predicate: isTable,
  10952. items: toolbar,
  10953. scope: 'node',
  10954. position: 'node'
  10955. });
  10956. }
  10957. };
  10958. var addMenuItems = function (editor, selections, selectionTargets, clipboard) {
  10959. var cmd = function (command) {
  10960. return function () {
  10961. return editor.execCommand(command);
  10962. };
  10963. };
  10964. var insertTableAction = function (data) {
  10965. editor.execCommand('mceInsertTable', false, {
  10966. rows: data.numRows,
  10967. columns: data.numColumns
  10968. });
  10969. };
  10970. var tableProperties = {
  10971. text: 'Table properties',
  10972. onSetup: selectionTargets.onSetupTable,
  10973. onAction: cmd('mceTableProps')
  10974. };
  10975. var deleteTable = {
  10976. text: 'Delete table',
  10977. icon: 'table-delete-table',
  10978. onSetup: selectionTargets.onSetupTable,
  10979. onAction: cmd('mceTableDelete')
  10980. };
  10981. editor.ui.registry.addMenuItem('tableinsertrowbefore', {
  10982. text: 'Insert row before',
  10983. icon: 'table-insert-row-above',
  10984. onAction: cmd('mceTableInsertRowBefore'),
  10985. onSetup: selectionTargets.onSetupCellOrRow
  10986. });
  10987. editor.ui.registry.addMenuItem('tableinsertrowafter', {
  10988. text: 'Insert row after',
  10989. icon: 'table-insert-row-after',
  10990. onAction: cmd('mceTableInsertRowAfter'),
  10991. onSetup: selectionTargets.onSetupCellOrRow
  10992. });
  10993. editor.ui.registry.addMenuItem('tabledeleterow', {
  10994. text: 'Delete row',
  10995. icon: 'table-delete-row',
  10996. onAction: cmd('mceTableDeleteRow'),
  10997. onSetup: selectionTargets.onSetupCellOrRow
  10998. });
  10999. editor.ui.registry.addMenuItem('tablerowprops', {
  11000. text: 'Row properties',
  11001. icon: 'table-row-properties',
  11002. onAction: cmd('mceTableRowProps'),
  11003. onSetup: selectionTargets.onSetupCellOrRow
  11004. });
  11005. editor.ui.registry.addMenuItem('tablecutrow', {
  11006. text: 'Cut row',
  11007. icon: 'cut-row',
  11008. onAction: cmd('mceTableCutRow'),
  11009. onSetup: selectionTargets.onSetupCellOrRow
  11010. });
  11011. editor.ui.registry.addMenuItem('tablecopyrow', {
  11012. text: 'Copy row',
  11013. icon: 'duplicate-row',
  11014. onAction: cmd('mceTableCopyRow'),
  11015. onSetup: selectionTargets.onSetupCellOrRow
  11016. });
  11017. editor.ui.registry.addMenuItem('tablepasterowbefore', {
  11018. text: 'Paste row before',
  11019. icon: 'paste-row-before',
  11020. onAction: cmd('mceTablePasteRowBefore'),
  11021. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  11022. });
  11023. editor.ui.registry.addMenuItem('tablepasterowafter', {
  11024. text: 'Paste row after',
  11025. icon: 'paste-row-after',
  11026. onAction: cmd('mceTablePasteRowAfter'),
  11027. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  11028. });
  11029. var row = {
  11030. type: 'nestedmenuitem',
  11031. text: 'Row',
  11032. getSubmenuItems: constant('tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter')
  11033. };
  11034. editor.ui.registry.addMenuItem('tableinsertcolumnbefore', {
  11035. text: 'Insert column before',
  11036. icon: 'table-insert-column-before',
  11037. onAction: cmd('mceTableInsertColBefore'),
  11038. onSetup: selectionTargets.onSetupColumn('onFirst')
  11039. });
  11040. editor.ui.registry.addMenuItem('tableinsertcolumnafter', {
  11041. text: 'Insert column after',
  11042. icon: 'table-insert-column-after',
  11043. onAction: cmd('mceTableInsertColAfter'),
  11044. onSetup: selectionTargets.onSetupColumn('onLast')
  11045. });
  11046. editor.ui.registry.addMenuItem('tabledeletecolumn', {
  11047. text: 'Delete column',
  11048. icon: 'table-delete-column',
  11049. onAction: cmd('mceTableDeleteCol'),
  11050. onSetup: selectionTargets.onSetupColumn('onAny')
  11051. });
  11052. editor.ui.registry.addMenuItem('tablecutcolumn', {
  11053. text: 'Cut column',
  11054. icon: 'cut-column',
  11055. onAction: cmd('mceTableCutCol'),
  11056. onSetup: selectionTargets.onSetupColumn('onAny')
  11057. });
  11058. editor.ui.registry.addMenuItem('tablecopycolumn', {
  11059. text: 'Copy column',
  11060. icon: 'duplicate-column',
  11061. onAction: cmd('mceTableCopyCol'),
  11062. onSetup: selectionTargets.onSetupColumn('onAny')
  11063. });
  11064. editor.ui.registry.addMenuItem('tablepastecolumnbefore', {
  11065. text: 'Paste column before',
  11066. icon: 'paste-column-before',
  11067. onAction: cmd('mceTablePasteColBefore'),
  11068. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
  11069. });
  11070. editor.ui.registry.addMenuItem('tablepastecolumnafter', {
  11071. text: 'Paste column after',
  11072. icon: 'paste-column-after',
  11073. onAction: cmd('mceTablePasteColAfter'),
  11074. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
  11075. });
  11076. var column = {
  11077. type: 'nestedmenuitem',
  11078. text: 'Column',
  11079. getSubmenuItems: constant('tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter')
  11080. };
  11081. editor.ui.registry.addMenuItem('tablecellprops', {
  11082. text: 'Cell properties',
  11083. icon: 'table-cell-properties',
  11084. onAction: cmd('mceTableCellProps'),
  11085. onSetup: selectionTargets.onSetupCellOrRow
  11086. });
  11087. editor.ui.registry.addMenuItem('tablemergecells', {
  11088. text: 'Merge cells',
  11089. icon: 'table-merge-cells',
  11090. onAction: cmd('mceTableMergeCells'),
  11091. onSetup: selectionTargets.onSetupMergeable
  11092. });
  11093. editor.ui.registry.addMenuItem('tablesplitcells', {
  11094. text: 'Split cell',
  11095. icon: 'table-split-cells',
  11096. onAction: cmd('mceTableSplitCells'),
  11097. onSetup: selectionTargets.onSetupUnmergeable
  11098. });
  11099. var cell = {
  11100. type: 'nestedmenuitem',
  11101. text: 'Cell',
  11102. getSubmenuItems: constant('tablecellprops tablemergecells tablesplitcells')
  11103. };
  11104. if (hasTableGrid(editor) === false) {
  11105. editor.ui.registry.addMenuItem('inserttable', {
  11106. text: 'Table',
  11107. icon: 'table',
  11108. onAction: cmd('mceInsertTable')
  11109. });
  11110. } else {
  11111. editor.ui.registry.addNestedMenuItem('inserttable', {
  11112. text: 'Table',
  11113. icon: 'table',
  11114. getSubmenuItems: function () {
  11115. return [{
  11116. type: 'fancymenuitem',
  11117. fancytype: 'inserttable',
  11118. onAction: insertTableAction
  11119. }];
  11120. }
  11121. });
  11122. }
  11123. editor.ui.registry.addMenuItem('inserttabledialog', {
  11124. text: 'Insert table',
  11125. icon: 'table',
  11126. onAction: cmd('mceInsertTable')
  11127. });
  11128. editor.ui.registry.addMenuItem('tableprops', tableProperties);
  11129. editor.ui.registry.addMenuItem('deletetable', deleteTable);
  11130. editor.ui.registry.addNestedMenuItem('row', row);
  11131. editor.ui.registry.addNestedMenuItem('column', column);
  11132. editor.ui.registry.addNestedMenuItem('cell', cell);
  11133. editor.ui.registry.addContextMenu('table', {
  11134. update: function () {
  11135. selectionTargets.resetTargets();
  11136. return selectionTargets.targets().fold(constant(''), function (targets) {
  11137. if (name(targets.element) === 'caption') {
  11138. return 'tableprops deletetable';
  11139. } else {
  11140. return 'cell row column | advtablesort | tableprops deletetable';
  11141. }
  11142. });
  11143. }
  11144. });
  11145. var tableClassList = filterNoneItem(getTableClassList(editor));
  11146. if (tableClassList.length !== 0) {
  11147. editor.ui.registry.addNestedMenuItem('tableclass', {
  11148. icon: 'table-classes',
  11149. text: 'Table styles',
  11150. getSubmenuItems: function () {
  11151. return buildMenuItems(editor, selections, tableClassList, 'tableclass', function (value) {
  11152. return editor.execCommand('mceTableToggleClass', false, value);
  11153. });
  11154. },
  11155. onSetup: selectionTargets.onSetupTable
  11156. });
  11157. }
  11158. var tableCellClassList = filterNoneItem(getCellClassList(editor));
  11159. if (tableCellClassList.length !== 0) {
  11160. editor.ui.registry.addNestedMenuItem('tablecellclass', {
  11161. icon: 'table-cell-classes',
  11162. text: 'Cell styles',
  11163. getSubmenuItems: function () {
  11164. return buildMenuItems(editor, selections, tableCellClassList, 'tablecellclass', function (value) {
  11165. return editor.execCommand('mceTableCellToggleClass', false, value);
  11166. });
  11167. },
  11168. onSetup: selectionTargets.onSetupCellOrRow
  11169. });
  11170. }
  11171. editor.ui.registry.addNestedMenuItem('tablecellvalign', {
  11172. icon: 'vertical-align',
  11173. text: 'Vertical align',
  11174. getSubmenuItems: function () {
  11175. return buildMenuItems(editor, selections, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align'));
  11176. },
  11177. onSetup: selectionTargets.onSetupCellOrRow
  11178. });
  11179. editor.ui.registry.addNestedMenuItem('tablecellborderwidth', {
  11180. icon: 'border-width',
  11181. text: 'Border width',
  11182. getSubmenuItems: function () {
  11183. return buildMenuItems(editor, selections, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width'));
  11184. },
  11185. onSetup: selectionTargets.onSetupCellOrRow
  11186. });
  11187. editor.ui.registry.addNestedMenuItem('tablecellborderstyle', {
  11188. icon: 'border-style',
  11189. text: 'Border style',
  11190. getSubmenuItems: function () {
  11191. return buildMenuItems(editor, selections, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style'));
  11192. },
  11193. onSetup: selectionTargets.onSetupCellOrRow
  11194. });
  11195. editor.ui.registry.addToggleMenuItem('tablecaption', {
  11196. icon: 'table-caption',
  11197. text: 'Table caption',
  11198. onAction: cmd('mceTableToggleCaption'),
  11199. onSetup: selectionTargets.onSetupTableWithCaption
  11200. });
  11201. editor.ui.registry.addNestedMenuItem('tablecellbackgroundcolor', {
  11202. icon: 'cell-background-color',
  11203. text: 'Background color',
  11204. getSubmenuItems: function () {
  11205. return buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color');
  11206. },
  11207. onSetup: selectionTargets.onSetupCellOrRow
  11208. });
  11209. editor.ui.registry.addNestedMenuItem('tablecellbordercolor', {
  11210. icon: 'cell-border-color',
  11211. text: 'Border color',
  11212. getSubmenuItems: function () {
  11213. return buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color');
  11214. },
  11215. onSetup: selectionTargets.onSetupCellOrRow
  11216. });
  11217. editor.ui.registry.addToggleMenuItem('tablerowheader', {
  11218. text: 'Row header',
  11219. icon: 'table-top-header',
  11220. onAction: changeRowHeader(editor),
  11221. onSetup: selectionTargets.onSetupTableRowHeaders
  11222. });
  11223. editor.ui.registry.addToggleMenuItem('tablecolheader', {
  11224. text: 'Column header',
  11225. icon: 'table-left-header',
  11226. onAction: changeColumnHeader(editor),
  11227. onSetup: selectionTargets.onSetupTableColumnHeaders
  11228. });
  11229. };
  11230. var Plugin = function (editor) {
  11231. var selections = Selections(function () {
  11232. return getBody(editor);
  11233. }, function () {
  11234. return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
  11235. }, ephemera.selectedSelector);
  11236. var selectionTargets = getSelectionTargets(editor, selections);
  11237. var resizeHandler = getResizeHandler(editor);
  11238. var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
  11239. var actions = TableActions(editor, cellSelection, resizeHandler.lazyWire);
  11240. var clipboard = Clipboard();
  11241. registerCommands(editor, actions, cellSelection, selections, clipboard);
  11242. registerQueryCommands(editor, actions, selections);
  11243. registerEvents(editor, selections, actions);
  11244. addMenuItems(editor, selections, selectionTargets, clipboard);
  11245. addButtons(editor, selections, selectionTargets, clipboard);
  11246. addToolbars(editor);
  11247. editor.on('PreInit', function () {
  11248. editor.serializer.addTempAttr(ephemera.firstSelected);
  11249. editor.serializer.addTempAttr(ephemera.lastSelected);
  11250. registerFormats(editor);
  11251. });
  11252. if (hasTabNavigation(editor)) {
  11253. editor.on('keydown', function (e) {
  11254. handle$1(e, editor, cellSelection);
  11255. });
  11256. }
  11257. editor.on('remove', function () {
  11258. resizeHandler.destroy();
  11259. });
  11260. return getApi(editor, clipboard, resizeHandler, selectionTargets);
  11261. };
  11262. function Plugin$1 () {
  11263. global$3.add('table', Plugin);
  11264. }
  11265. Plugin$1();
  11266. }());