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.0 (2021-10-11)
  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. };
  3372. var getRawWidth = function (editor, elm) {
  3373. var raw = editor.dom.getStyle(elm, 'width') || editor.dom.getAttrib(elm, 'width');
  3374. return Optional.from(raw).filter(isNotEmpty);
  3375. };
  3376. var isPercentage$1 = function (value) {
  3377. return /^(\d+(\.\d+)?)%$/.test(value);
  3378. };
  3379. var isPixel = function (value) {
  3380. return /^(\d+(\.\d+)?)px$/.test(value);
  3381. };
  3382. var getSelectionStart = function (editor) {
  3383. return SugarElement.fromDom(editor.selection.getStart());
  3384. };
  3385. var getSelectionEnd = function (editor) {
  3386. return SugarElement.fromDom(editor.selection.getEnd());
  3387. };
  3388. var selection = function (selections) {
  3389. return cata$2(selections.get(), constant([]), identity, pure);
  3390. };
  3391. var unmergable = function (selections) {
  3392. var hasSpan = function (elem, type) {
  3393. return getOpt(elem, type).exists(function (span) {
  3394. return parseInt(span, 10) > 1;
  3395. });
  3396. };
  3397. var hasRowOrColSpan = function (elem) {
  3398. return hasSpan(elem, 'rowspan') || hasSpan(elem, 'colspan');
  3399. };
  3400. var candidates = selection(selections);
  3401. return candidates.length > 0 && forall(candidates, hasRowOrColSpan) ? Optional.some(candidates) : Optional.none();
  3402. };
  3403. var mergable = function (table, selections, ephemera) {
  3404. return cata$2(selections.get(), Optional.none, function (cells) {
  3405. if (cells.length <= 1) {
  3406. return Optional.none();
  3407. } else {
  3408. return retrieveBox(table, ephemera.firstSelectedSelector, ephemera.lastSelectedSelector).map(function (bounds) {
  3409. return {
  3410. bounds: bounds,
  3411. cells: cells
  3412. };
  3413. });
  3414. }
  3415. }, Optional.none);
  3416. };
  3417. var strSelected = 'data-mce-selected';
  3418. var strSelectedSelector = 'td[' + strSelected + '],th[' + strSelected + ']';
  3419. var strAttributeSelector = '[' + strSelected + ']';
  3420. var strFirstSelected = 'data-mce-first-selected';
  3421. var strFirstSelectedSelector = 'td[' + strFirstSelected + '],th[' + strFirstSelected + ']';
  3422. var strLastSelected = 'data-mce-last-selected';
  3423. var strLastSelectedSelector = 'td[' + strLastSelected + '],th[' + strLastSelected + ']';
  3424. var attributeSelector = strAttributeSelector;
  3425. var ephemera = {
  3426. selected: strSelected,
  3427. selectedSelector: strSelectedSelector,
  3428. firstSelected: strFirstSelected,
  3429. firstSelectedSelector: strFirstSelectedSelector,
  3430. lastSelected: strLastSelected,
  3431. lastSelectedSelector: strLastSelectedSelector
  3432. };
  3433. var noMenu = function (cell) {
  3434. return {
  3435. element: cell,
  3436. mergable: Optional.none(),
  3437. unmergable: Optional.none(),
  3438. selection: [cell]
  3439. };
  3440. };
  3441. var forMenu = function (selections, table, cell) {
  3442. return {
  3443. element: cell,
  3444. mergable: mergable(table, selections, ephemera),
  3445. unmergable: unmergable(selections),
  3446. selection: selection(selections)
  3447. };
  3448. };
  3449. var paste = function (element, clipboard, generators) {
  3450. return {
  3451. element: element,
  3452. clipboard: clipboard,
  3453. generators: generators
  3454. };
  3455. };
  3456. var pasteRows = function (selections, cell, clipboard, generators) {
  3457. return {
  3458. selection: selection(selections),
  3459. clipboard: clipboard,
  3460. generators: generators
  3461. };
  3462. };
  3463. var getSelectionCellFallback = function (element) {
  3464. return table(element).bind(function (table) {
  3465. return retrieve(table, ephemera.firstSelectedSelector);
  3466. }).fold(constant(element), function (cells) {
  3467. return cells[0];
  3468. });
  3469. };
  3470. var getSelectionFromSelector = function (selector) {
  3471. return function (initCell, isRoot) {
  3472. var cellName = name(initCell);
  3473. var cell = cellName === 'col' || cellName === 'colgroup' ? getSelectionCellFallback(initCell) : initCell;
  3474. return closest$1(cell, selector, isRoot);
  3475. };
  3476. };
  3477. var getSelectionCellOrCaption = getSelectionFromSelector('th,td,caption');
  3478. var getSelectionCell = getSelectionFromSelector('th,td');
  3479. var getCellsFromSelection = function (selections) {
  3480. return selection(selections);
  3481. };
  3482. var getRowsFromSelection = function (selected, selector) {
  3483. var cellOpt = getSelectionCell(selected);
  3484. var rowsOpt = cellOpt.bind(function (cell) {
  3485. return table(cell);
  3486. }).map(function (table) {
  3487. return rows$1(table);
  3488. });
  3489. return lift2(cellOpt, rowsOpt, function (cell, rows) {
  3490. return filter$2(rows, function (row) {
  3491. return exists(fromDom(row.dom.cells), function (rowCell) {
  3492. return get$b(rowCell, selector) === '1' || eq$1(rowCell, cell);
  3493. });
  3494. });
  3495. }).getOr([]);
  3496. };
  3497. var extractSelected = function (cells) {
  3498. return table(cells[0]).map(function (table) {
  3499. var replica = extract$1(table, attributeSelector);
  3500. removeDataStyle(replica);
  3501. return [replica];
  3502. });
  3503. };
  3504. var serializeElements = function (editor, elements) {
  3505. return map$1(elements, function (elm) {
  3506. return editor.selection.serializer.serialize(elm.dom, {});
  3507. }).join('');
  3508. };
  3509. var getTextContent = function (elements) {
  3510. return map$1(elements, function (element) {
  3511. return element.dom.innerText;
  3512. }).join('');
  3513. };
  3514. var registerEvents = function (editor, selections, actions) {
  3515. editor.on('BeforeGetContent', function (e) {
  3516. var multiCellContext = function (cells) {
  3517. e.preventDefault();
  3518. extractSelected(cells).each(function (elements) {
  3519. e.content = e.format === 'text' ? getTextContent(elements) : serializeElements(editor, elements);
  3520. });
  3521. };
  3522. if (e.selection === true) {
  3523. cata$2(selections.get(), noop, multiCellContext, noop);
  3524. }
  3525. });
  3526. editor.on('BeforeSetContent', function (e) {
  3527. if (e.selection === true && e.paste === true) {
  3528. var selectedCells = getCellsFromSelection(selections);
  3529. head(selectedCells).each(function (cell) {
  3530. table(cell).each(function (table) {
  3531. var elements = filter$2(fromHtml(e.content), function (content) {
  3532. return name(content) !== 'meta';
  3533. });
  3534. var isTable = isTag('table');
  3535. if (elements.length === 1 && isTable(elements[0])) {
  3536. e.preventDefault();
  3537. var doc = SugarElement.fromDom(editor.getDoc());
  3538. var generators = paste$1(doc);
  3539. var targets = paste(cell, elements[0], generators);
  3540. actions.pasteCells(table, targets).each(function () {
  3541. editor.focus();
  3542. });
  3543. }
  3544. });
  3545. });
  3546. }
  3547. });
  3548. };
  3549. var adt$7 = Adt.generate([
  3550. { none: [] },
  3551. { only: ['index'] },
  3552. {
  3553. left: [
  3554. 'index',
  3555. 'next'
  3556. ]
  3557. },
  3558. {
  3559. middle: [
  3560. 'prev',
  3561. 'index',
  3562. 'next'
  3563. ]
  3564. },
  3565. {
  3566. right: [
  3567. 'prev',
  3568. 'index'
  3569. ]
  3570. }
  3571. ]);
  3572. var ColumnContext = __assign({}, adt$7);
  3573. var neighbours = function (input, index) {
  3574. if (input.length === 0) {
  3575. return ColumnContext.none();
  3576. }
  3577. if (input.length === 1) {
  3578. return ColumnContext.only(0);
  3579. }
  3580. if (index === 0) {
  3581. return ColumnContext.left(0, 1);
  3582. }
  3583. if (index === input.length - 1) {
  3584. return ColumnContext.right(index - 1, index);
  3585. }
  3586. if (index > 0 && index < input.length - 1) {
  3587. return ColumnContext.middle(index - 1, index, index + 1);
  3588. }
  3589. return ColumnContext.none();
  3590. };
  3591. var determine = function (input, column, step, tableSize, resize) {
  3592. var result = input.slice(0);
  3593. var context = neighbours(input, column);
  3594. var onNone = constant(map$1(result, constant(0)));
  3595. var onOnly = function (index) {
  3596. return tableSize.singleColumnWidth(result[index], step);
  3597. };
  3598. var onLeft = function (index, next) {
  3599. return resize.calcLeftEdgeDeltas(result, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
  3600. };
  3601. var onMiddle = function (prev, index, next) {
  3602. return resize.calcMiddleDeltas(result, prev, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
  3603. };
  3604. var onRight = function (prev, index) {
  3605. return resize.calcRightEdgeDeltas(result, prev, index, step, tableSize.minCellWidth(), tableSize.isRelative);
  3606. };
  3607. return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
  3608. };
  3609. var total = function (start, end, measures) {
  3610. var r = 0;
  3611. for (var i = start; i < end; i++) {
  3612. r += measures[i] !== undefined ? measures[i] : 0;
  3613. }
  3614. return r;
  3615. };
  3616. var recalculateWidthForCells = function (warehouse, widths) {
  3617. var all = Warehouse.justCells(warehouse);
  3618. return map$1(all, function (cell) {
  3619. var width = total(cell.column, cell.column + cell.colspan, widths);
  3620. return {
  3621. element: cell.element,
  3622. width: width,
  3623. colspan: cell.colspan
  3624. };
  3625. });
  3626. };
  3627. var recalculateWidthForColumns = function (warehouse, widths) {
  3628. var groups = Warehouse.justColumns(warehouse);
  3629. return map$1(groups, function (column, index) {
  3630. return {
  3631. element: column.element,
  3632. width: widths[index],
  3633. colspan: column.colspan
  3634. };
  3635. });
  3636. };
  3637. var recalculateHeightForCells = function (warehouse, heights) {
  3638. var all = Warehouse.justCells(warehouse);
  3639. return map$1(all, function (cell) {
  3640. var height = total(cell.row, cell.row + cell.rowspan, heights);
  3641. return {
  3642. element: cell.element,
  3643. height: height,
  3644. rowspan: cell.rowspan
  3645. };
  3646. });
  3647. };
  3648. var matchRowHeight = function (warehouse, heights) {
  3649. return map$1(warehouse.all, function (row, i) {
  3650. return {
  3651. element: row.element,
  3652. height: heights[i]
  3653. };
  3654. });
  3655. };
  3656. var sumUp = function (newSize) {
  3657. return foldr(newSize, function (b, a) {
  3658. return b + a;
  3659. }, 0);
  3660. };
  3661. var recalculate = function (warehouse, widths) {
  3662. if (Warehouse.hasColumns(warehouse)) {
  3663. return recalculateWidthForColumns(warehouse, widths);
  3664. } else {
  3665. return recalculateWidthForCells(warehouse, widths);
  3666. }
  3667. };
  3668. var recalculateAndApply = function (warehouse, widths, tableSize) {
  3669. var newSizes = recalculate(warehouse, widths);
  3670. each$2(newSizes, function (cell) {
  3671. tableSize.setElementWidth(cell.element, cell.width);
  3672. });
  3673. };
  3674. var adjustWidth = function (table, delta, index, resizing, tableSize) {
  3675. var warehouse = Warehouse.fromTable(table);
  3676. var step = tableSize.getCellDelta(delta);
  3677. var widths = tableSize.getWidths(warehouse, tableSize);
  3678. var isLastColumn = index === warehouse.grid.columns - 1;
  3679. var clampedStep = resizing.clampTableDelta(widths, index, step, tableSize.minCellWidth(), isLastColumn);
  3680. var deltas = determine(widths, index, clampedStep, tableSize, resizing);
  3681. var newWidths = map$1(deltas, function (dx, i) {
  3682. return dx + widths[i];
  3683. });
  3684. recalculateAndApply(warehouse, newWidths, tableSize);
  3685. resizing.resizeTable(tableSize.adjustTableWidth, clampedStep, isLastColumn);
  3686. };
  3687. var adjustHeight = function (table, delta, index, direction) {
  3688. var warehouse = Warehouse.fromTable(table);
  3689. var heights = getPixelHeights(warehouse, table, direction);
  3690. var newHeights = map$1(heights, function (dy, i) {
  3691. return index === i ? Math.max(delta + dy, minHeight()) : dy;
  3692. });
  3693. var newCellSizes = recalculateHeightForCells(warehouse, newHeights);
  3694. var newRowSizes = matchRowHeight(warehouse, newHeights);
  3695. each$2(newRowSizes, function (row) {
  3696. setHeight(row.element, row.height);
  3697. });
  3698. each$2(newCellSizes, function (cell) {
  3699. setHeight(cell.element, cell.height);
  3700. });
  3701. var total = sumUp(newHeights);
  3702. setHeight(table, total);
  3703. };
  3704. var adjustAndRedistributeWidths$1 = function (_table, list, details, tableSize, resizeBehaviour) {
  3705. var warehouse = Warehouse.generate(list);
  3706. var sizes = tableSize.getWidths(warehouse, tableSize);
  3707. var tablePixelWidth = tableSize.pixelWidth();
  3708. var _a = resizeBehaviour.calcRedestributedWidths(sizes, tablePixelWidth, details.pixelDelta, tableSize.isRelative), newSizes = _a.newSizes, delta = _a.delta;
  3709. recalculateAndApply(warehouse, newSizes, tableSize);
  3710. tableSize.adjustTableWidth(delta);
  3711. };
  3712. var adjustWidthTo = function (_table, list, _info, tableSize) {
  3713. var warehouse = Warehouse.generate(list);
  3714. var widths = tableSize.getWidths(warehouse, tableSize);
  3715. recalculateAndApply(warehouse, widths, tableSize);
  3716. };
  3717. var zero = function (array) {
  3718. return map$1(array, constant(0));
  3719. };
  3720. var surround = function (sizes, startIndex, endIndex, results, f) {
  3721. return f(sizes.slice(0, startIndex)).concat(results).concat(f(sizes.slice(endIndex)));
  3722. };
  3723. var clampDeltaHelper = function (predicate) {
  3724. return function (sizes, index, delta, minCellSize) {
  3725. if (!predicate(delta)) {
  3726. return delta;
  3727. } else {
  3728. var newSize = Math.max(minCellSize, sizes[index] - Math.abs(delta));
  3729. var diff = Math.abs(newSize - sizes[index]);
  3730. return delta >= 0 ? diff : -diff;
  3731. }
  3732. };
  3733. };
  3734. var clampNegativeDelta = clampDeltaHelper(function (delta) {
  3735. return delta < 0;
  3736. });
  3737. var clampDelta = clampDeltaHelper(always);
  3738. var resizeTable = function () {
  3739. var calcFixedDeltas = function (sizes, index, next, delta, minCellSize) {
  3740. var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
  3741. return surround(sizes, index, next + 1, [
  3742. clampedDelta,
  3743. 0
  3744. ], zero);
  3745. };
  3746. var calcRelativeDeltas = function (sizes, index, delta, minCellSize) {
  3747. var ratio = (100 + delta) / 100;
  3748. var newThis = Math.max(minCellSize, (sizes[index] + delta) / ratio);
  3749. return map$1(sizes, function (size, idx) {
  3750. var newSize = idx === index ? newThis : size / ratio;
  3751. return newSize - size;
  3752. });
  3753. };
  3754. var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize, isRelative) {
  3755. if (isRelative) {
  3756. return calcRelativeDeltas(sizes, index, delta, minCellSize);
  3757. } else {
  3758. return calcFixedDeltas(sizes, index, next, delta, minCellSize);
  3759. }
  3760. };
  3761. var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize, isRelative) {
  3762. return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize, isRelative);
  3763. };
  3764. var resizeTable = function (resizer, delta) {
  3765. return resizer(delta);
  3766. };
  3767. var calcRightEdgeDeltas = function (sizes, _prev, index, delta, minCellSize, isRelative) {
  3768. if (isRelative) {
  3769. return calcRelativeDeltas(sizes, index, delta, minCellSize);
  3770. } else {
  3771. var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
  3772. return zero(sizes.slice(0, index)).concat([clampedDelta]);
  3773. }
  3774. };
  3775. var calcRedestributedWidths = function (sizes, totalWidth, pixelDelta, isRelative) {
  3776. if (isRelative) {
  3777. var tableWidth = totalWidth + pixelDelta;
  3778. var ratio_1 = tableWidth / totalWidth;
  3779. var newSizes = map$1(sizes, function (size) {
  3780. return size / ratio_1;
  3781. });
  3782. return {
  3783. delta: ratio_1 * 100 - 100,
  3784. newSizes: newSizes
  3785. };
  3786. } else {
  3787. return {
  3788. delta: pixelDelta,
  3789. newSizes: sizes
  3790. };
  3791. }
  3792. };
  3793. return {
  3794. resizeTable: resizeTable,
  3795. clampTableDelta: clampNegativeDelta,
  3796. calcLeftEdgeDeltas: calcLeftEdgeDeltas,
  3797. calcMiddleDeltas: calcMiddleDeltas,
  3798. calcRightEdgeDeltas: calcRightEdgeDeltas,
  3799. calcRedestributedWidths: calcRedestributedWidths
  3800. };
  3801. };
  3802. var preserveTable = function () {
  3803. var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize) {
  3804. var idx = delta >= 0 ? next : index;
  3805. var clampedDelta = clampDelta(sizes, idx, delta, minCellSize);
  3806. return surround(sizes, index, next + 1, [
  3807. clampedDelta,
  3808. -clampedDelta
  3809. ], zero);
  3810. };
  3811. var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize) {
  3812. return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize);
  3813. };
  3814. var resizeTable = function (resizer, delta, isLastColumn) {
  3815. if (isLastColumn) {
  3816. resizer(delta);
  3817. }
  3818. };
  3819. var calcRightEdgeDeltas = function (sizes, _prev, _index, delta, _minCellSize, isRelative) {
  3820. if (isRelative) {
  3821. return zero(sizes);
  3822. } else {
  3823. var diff = delta / sizes.length;
  3824. return map$1(sizes, constant(diff));
  3825. }
  3826. };
  3827. var clampTableDelta = function (sizes, index, delta, minCellSize, isLastColumn) {
  3828. if (isLastColumn) {
  3829. if (delta >= 0) {
  3830. return delta;
  3831. } else {
  3832. var maxDelta = foldl(sizes, function (a, b) {
  3833. return a + b - minCellSize;
  3834. }, 0);
  3835. return Math.max(-maxDelta, delta);
  3836. }
  3837. } else {
  3838. return clampNegativeDelta(sizes, index, delta, minCellSize);
  3839. }
  3840. };
  3841. var calcRedestributedWidths = function (sizes, _totalWidth, _pixelDelta, _isRelative) {
  3842. return {
  3843. delta: 0,
  3844. newSizes: sizes
  3845. };
  3846. };
  3847. return {
  3848. resizeTable: resizeTable,
  3849. clampTableDelta: clampTableDelta,
  3850. calcLeftEdgeDeltas: calcLeftEdgeDeltas,
  3851. calcMiddleDeltas: calcMiddleDeltas,
  3852. calcRightEdgeDeltas: calcRightEdgeDeltas,
  3853. calcRedestributedWidths: calcRedestributedWidths
  3854. };
  3855. };
  3856. var only = function (element, isResizable) {
  3857. var parent = Optional.from(element.dom.documentElement).map(SugarElement.fromDom).getOr(element);
  3858. return {
  3859. parent: constant(parent),
  3860. view: constant(element),
  3861. origin: constant(SugarPosition(0, 0)),
  3862. isResizable: isResizable
  3863. };
  3864. };
  3865. var detached = function (editable, chrome, isResizable) {
  3866. var origin = function () {
  3867. return absolute(chrome);
  3868. };
  3869. return {
  3870. parent: constant(chrome),
  3871. view: constant(editable),
  3872. origin: origin,
  3873. isResizable: isResizable
  3874. };
  3875. };
  3876. var body = function (editable, chrome, isResizable) {
  3877. return {
  3878. parent: constant(chrome),
  3879. view: constant(editable),
  3880. origin: constant(SugarPosition(0, 0)),
  3881. isResizable: isResizable
  3882. };
  3883. };
  3884. var ResizeWire = {
  3885. only: only,
  3886. detached: detached,
  3887. body: body
  3888. };
  3889. var adt$6 = Adt.generate([
  3890. { invalid: ['raw'] },
  3891. { pixels: ['value'] },
  3892. { percent: ['value'] }
  3893. ]);
  3894. var validateFor = function (suffix, type, value) {
  3895. var rawAmount = value.substring(0, value.length - suffix.length);
  3896. var amount = parseFloat(rawAmount);
  3897. return rawAmount === amount.toString() ? type(amount) : adt$6.invalid(value);
  3898. };
  3899. var from = function (value) {
  3900. if (endsWith(value, '%')) {
  3901. return validateFor('%', adt$6.percent, value);
  3902. }
  3903. if (endsWith(value, 'px')) {
  3904. return validateFor('px', adt$6.pixels, value);
  3905. }
  3906. return adt$6.invalid(value);
  3907. };
  3908. var Size = __assign(__assign({}, adt$6), { from: from });
  3909. var redistributeToPercent = function (widths, totalWidth) {
  3910. return map$1(widths, function (w) {
  3911. var colType = Size.from(w);
  3912. return colType.fold(function () {
  3913. return w;
  3914. }, function (px) {
  3915. var ratio = px / totalWidth * 100;
  3916. return ratio + '%';
  3917. }, function (pc) {
  3918. return pc + '%';
  3919. });
  3920. });
  3921. };
  3922. var redistributeToPx = function (widths, totalWidth, newTotalWidth) {
  3923. var scale = newTotalWidth / totalWidth;
  3924. return map$1(widths, function (w) {
  3925. var colType = Size.from(w);
  3926. return colType.fold(function () {
  3927. return w;
  3928. }, function (px) {
  3929. return px * scale + 'px';
  3930. }, function (pc) {
  3931. return pc / 100 * newTotalWidth + 'px';
  3932. });
  3933. });
  3934. };
  3935. var redistributeEmpty = function (newWidthType, columns) {
  3936. var f = newWidthType.fold(function () {
  3937. return constant('');
  3938. }, function (pixels) {
  3939. var num = pixels / columns;
  3940. return constant(num + 'px');
  3941. }, function () {
  3942. var num = 100 / columns;
  3943. return constant(num + '%');
  3944. });
  3945. return range$1(columns, f);
  3946. };
  3947. var redistributeValues = function (newWidthType, widths, totalWidth) {
  3948. return newWidthType.fold(function () {
  3949. return widths;
  3950. }, function (px) {
  3951. return redistributeToPx(widths, totalWidth, px);
  3952. }, function (_pc) {
  3953. return redistributeToPercent(widths, totalWidth);
  3954. });
  3955. };
  3956. var redistribute$1 = function (widths, totalWidth, newWidth) {
  3957. var newType = Size.from(newWidth);
  3958. var floats = forall(widths, function (s) {
  3959. return s === '0px';
  3960. }) ? redistributeEmpty(newType, widths.length) : redistributeValues(newType, widths, totalWidth);
  3961. return normalize(floats);
  3962. };
  3963. var sum = function (values, fallback) {
  3964. if (values.length === 0) {
  3965. return fallback;
  3966. }
  3967. return foldr(values, function (rest, v) {
  3968. return Size.from(v).fold(constant(0), identity, identity) + rest;
  3969. }, 0);
  3970. };
  3971. var roundDown = function (num, unit) {
  3972. var floored = Math.floor(num);
  3973. return {
  3974. value: floored + unit,
  3975. remainder: num - floored
  3976. };
  3977. };
  3978. var add$3 = function (value, amount) {
  3979. return Size.from(value).fold(constant(value), function (px) {
  3980. return px + amount + 'px';
  3981. }, function (pc) {
  3982. return pc + amount + '%';
  3983. });
  3984. };
  3985. var normalize = function (values) {
  3986. if (values.length === 0) {
  3987. return values;
  3988. }
  3989. var scan = foldr(values, function (rest, value) {
  3990. var info = Size.from(value).fold(function () {
  3991. return {
  3992. value: value,
  3993. remainder: 0
  3994. };
  3995. }, function (num) {
  3996. return roundDown(num, 'px');
  3997. }, function (num) {
  3998. return {
  3999. value: num + '%',
  4000. remainder: 0
  4001. };
  4002. });
  4003. return {
  4004. output: [info.value].concat(rest.output),
  4005. remainder: rest.remainder + info.remainder
  4006. };
  4007. }, {
  4008. output: [],
  4009. remainder: 0
  4010. });
  4011. var r = scan.output;
  4012. return r.slice(0, r.length - 1).concat([add$3(r[r.length - 1], Math.round(scan.remainder))]);
  4013. };
  4014. var validate = Size.from;
  4015. var redistributeToW = function (newWidths, cells, unit) {
  4016. each$2(cells, function (cell) {
  4017. var widths = newWidths.slice(cell.column, cell.colspan + cell.column);
  4018. var w = sum(widths, minWidth());
  4019. set$1(cell.element, 'width', w + unit);
  4020. });
  4021. };
  4022. var redistributeToColumns = function (newWidths, columns, unit) {
  4023. each$2(columns, function (column, index) {
  4024. var width = sum([newWidths[index]], minWidth());
  4025. set$1(column.element, 'width', width + unit);
  4026. });
  4027. };
  4028. var redistributeToH = function (newHeights, rows, cells, unit) {
  4029. each$2(cells, function (cell) {
  4030. var heights = newHeights.slice(cell.row, cell.rowspan + cell.row);
  4031. var h = sum(heights, minHeight());
  4032. set$1(cell.element, 'height', h + unit);
  4033. });
  4034. each$2(rows, function (row, i) {
  4035. set$1(row.element, 'height', newHeights[i]);
  4036. });
  4037. };
  4038. var getUnit = function (newSize) {
  4039. return validate(newSize).fold(constant('px'), constant('px'), constant('%'));
  4040. };
  4041. var redistribute = function (table, optWidth, optHeight) {
  4042. var warehouse = Warehouse.fromTable(table);
  4043. var rows = warehouse.all;
  4044. var cells = Warehouse.justCells(warehouse);
  4045. var columns = Warehouse.justColumns(warehouse);
  4046. optWidth.each(function (newWidth) {
  4047. var widthUnit = getUnit(newWidth);
  4048. var totalWidth = get$8(table);
  4049. var oldWidths = getRawWidths(warehouse, table);
  4050. var nuWidths = redistribute$1(oldWidths, totalWidth, newWidth);
  4051. if (Warehouse.hasColumns(warehouse)) {
  4052. redistributeToColumns(nuWidths, columns, widthUnit);
  4053. } else {
  4054. redistributeToW(nuWidths, cells, widthUnit);
  4055. }
  4056. set$1(table, 'width', newWidth);
  4057. });
  4058. optHeight.each(function (newHeight) {
  4059. var hUnit = getUnit(newHeight);
  4060. var totalHeight = get$7(table);
  4061. var oldHeights = getRawHeights(warehouse, table, height);
  4062. var nuHeights = redistribute$1(oldHeights, totalHeight, newHeight);
  4063. redistributeToH(nuHeights, rows, cells, hUnit);
  4064. set$1(table, 'height', newHeight);
  4065. });
  4066. };
  4067. var isPercentSizing = isPercentSizing$1;
  4068. var isPixelSizing = isPixelSizing$1;
  4069. var isNoneSizing = isNoneSizing$1;
  4070. var getGridSize = function (table) {
  4071. var warehouse = Warehouse.fromTable(table);
  4072. return warehouse.grid;
  4073. };
  4074. var Event = function (fields) {
  4075. var handlers = [];
  4076. var bind = function (handler) {
  4077. if (handler === undefined) {
  4078. throw new Error('Event bind error: undefined handler');
  4079. }
  4080. handlers.push(handler);
  4081. };
  4082. var unbind = function (handler) {
  4083. handlers = filter$2(handlers, function (h) {
  4084. return h !== handler;
  4085. });
  4086. };
  4087. var trigger = function () {
  4088. var args = [];
  4089. for (var _i = 0; _i < arguments.length; _i++) {
  4090. args[_i] = arguments[_i];
  4091. }
  4092. var event = {};
  4093. each$2(fields, function (name, i) {
  4094. event[name] = args[i];
  4095. });
  4096. each$2(handlers, function (handler) {
  4097. handler(event);
  4098. });
  4099. };
  4100. return {
  4101. bind: bind,
  4102. unbind: unbind,
  4103. trigger: trigger
  4104. };
  4105. };
  4106. var create$4 = function (typeDefs) {
  4107. var registry = map(typeDefs, function (event) {
  4108. return {
  4109. bind: event.bind,
  4110. unbind: event.unbind
  4111. };
  4112. });
  4113. var trigger = map(typeDefs, function (event) {
  4114. return event.trigger;
  4115. });
  4116. return {
  4117. registry: registry,
  4118. trigger: trigger
  4119. };
  4120. };
  4121. var last = function (fn, rate) {
  4122. var timer = null;
  4123. var cancel = function () {
  4124. if (!isNull(timer)) {
  4125. clearTimeout(timer);
  4126. timer = null;
  4127. }
  4128. };
  4129. var throttle = function () {
  4130. var args = [];
  4131. for (var _i = 0; _i < arguments.length; _i++) {
  4132. args[_i] = arguments[_i];
  4133. }
  4134. cancel();
  4135. timer = setTimeout(function () {
  4136. timer = null;
  4137. fn.apply(null, args);
  4138. }, rate);
  4139. };
  4140. return {
  4141. cancel: cancel,
  4142. throttle: throttle
  4143. };
  4144. };
  4145. var sort = function (arr) {
  4146. return arr.slice(0).sort();
  4147. };
  4148. var reqMessage = function (required, keys) {
  4149. throw new Error('All required keys (' + sort(required).join(', ') + ') were not specified. Specified keys were: ' + sort(keys).join(', ') + '.');
  4150. };
  4151. var unsuppMessage = function (unsupported) {
  4152. throw new Error('Unsupported keys for object: ' + sort(unsupported).join(', '));
  4153. };
  4154. var validateStrArr = function (label, array) {
  4155. if (!isArray(array)) {
  4156. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  4157. }
  4158. each$2(array, function (a) {
  4159. if (!isString(a)) {
  4160. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  4161. }
  4162. });
  4163. };
  4164. var invalidTypeMessage = function (incorrect, type) {
  4165. throw new Error('All values need to be of type: ' + type + '. Keys (' + sort(incorrect).join(', ') + ') were not.');
  4166. };
  4167. var checkDupes = function (everything) {
  4168. var sorted = sort(everything);
  4169. var dupe = find$1(sorted, function (s, i) {
  4170. return i < sorted.length - 1 && s === sorted[i + 1];
  4171. });
  4172. dupe.each(function (d) {
  4173. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  4174. });
  4175. };
  4176. var base = function (handleUnsupported, required) {
  4177. return baseWith(handleUnsupported, required, {
  4178. validate: isFunction,
  4179. label: 'function'
  4180. });
  4181. };
  4182. var baseWith = function (handleUnsupported, required, pred) {
  4183. if (required.length === 0) {
  4184. throw new Error('You must specify at least one required field.');
  4185. }
  4186. validateStrArr('required', required);
  4187. checkDupes(required);
  4188. return function (obj) {
  4189. var keys$1 = keys(obj);
  4190. var allReqd = forall(required, function (req) {
  4191. return contains$2(keys$1, req);
  4192. });
  4193. if (!allReqd) {
  4194. reqMessage(required, keys$1);
  4195. }
  4196. handleUnsupported(required, keys$1);
  4197. var invalidKeys = filter$2(required, function (key) {
  4198. return !pred.validate(obj[key], key);
  4199. });
  4200. if (invalidKeys.length > 0) {
  4201. invalidTypeMessage(invalidKeys, pred.label);
  4202. }
  4203. return obj;
  4204. };
  4205. };
  4206. var handleExact = function (required, keys) {
  4207. var unsupported = filter$2(keys, function (key) {
  4208. return !contains$2(required, key);
  4209. });
  4210. if (unsupported.length > 0) {
  4211. unsuppMessage(unsupported);
  4212. }
  4213. };
  4214. var exactly = function (required) {
  4215. return base(handleExact, required);
  4216. };
  4217. var DragMode = exactly([
  4218. 'compare',
  4219. 'extract',
  4220. 'mutate',
  4221. 'sink'
  4222. ]);
  4223. var DragSink = exactly([
  4224. 'element',
  4225. 'start',
  4226. 'stop',
  4227. 'destroy'
  4228. ]);
  4229. var DragApi = exactly([
  4230. 'forceDrop',
  4231. 'drop',
  4232. 'move',
  4233. 'delayDrop'
  4234. ]);
  4235. var InDrag = function () {
  4236. var previous = Optional.none();
  4237. var reset = function () {
  4238. previous = Optional.none();
  4239. };
  4240. var update = function (mode, nu) {
  4241. var result = previous.map(function (old) {
  4242. return mode.compare(old, nu);
  4243. });
  4244. previous = Optional.some(nu);
  4245. return result;
  4246. };
  4247. var onEvent = function (event, mode) {
  4248. var dataOption = mode.extract(event);
  4249. dataOption.each(function (data) {
  4250. var offset = update(mode, data);
  4251. offset.each(function (d) {
  4252. events.trigger.move(d);
  4253. });
  4254. });
  4255. };
  4256. var events = create$4({ move: Event(['info']) });
  4257. return {
  4258. onEvent: onEvent,
  4259. reset: reset,
  4260. events: events.registry
  4261. };
  4262. };
  4263. var NoDrag = function () {
  4264. var events = create$4({ move: Event(['info']) });
  4265. return {
  4266. onEvent: noop,
  4267. reset: noop,
  4268. events: events.registry
  4269. };
  4270. };
  4271. var Movement = function () {
  4272. var noDragState = NoDrag();
  4273. var inDragState = InDrag();
  4274. var dragState = noDragState;
  4275. var on = function () {
  4276. dragState.reset();
  4277. dragState = inDragState;
  4278. };
  4279. var off = function () {
  4280. dragState.reset();
  4281. dragState = noDragState;
  4282. };
  4283. var onEvent = function (event, mode) {
  4284. dragState.onEvent(event, mode);
  4285. };
  4286. var isOn = function () {
  4287. return dragState === inDragState;
  4288. };
  4289. return {
  4290. on: on,
  4291. off: off,
  4292. isOn: isOn,
  4293. onEvent: onEvent,
  4294. events: inDragState.events
  4295. };
  4296. };
  4297. var setup = function (mutation, mode, settings) {
  4298. var active = false;
  4299. var events = create$4({
  4300. start: Event([]),
  4301. stop: Event([])
  4302. });
  4303. var movement = Movement();
  4304. var drop = function () {
  4305. sink.stop();
  4306. if (movement.isOn()) {
  4307. movement.off();
  4308. events.trigger.stop();
  4309. }
  4310. };
  4311. var throttledDrop = last(drop, 200);
  4312. var go = function (parent) {
  4313. sink.start(parent);
  4314. movement.on();
  4315. events.trigger.start();
  4316. };
  4317. var mousemove = function (event) {
  4318. throttledDrop.cancel();
  4319. movement.onEvent(event, mode);
  4320. };
  4321. movement.events.move.bind(function (event) {
  4322. mode.mutate(mutation, event.info);
  4323. });
  4324. var on = function () {
  4325. active = true;
  4326. };
  4327. var off = function () {
  4328. active = false;
  4329. };
  4330. var runIfActive = function (f) {
  4331. return function () {
  4332. var args = [];
  4333. for (var _i = 0; _i < arguments.length; _i++) {
  4334. args[_i] = arguments[_i];
  4335. }
  4336. if (active) {
  4337. f.apply(null, args);
  4338. }
  4339. };
  4340. };
  4341. var sink = mode.sink(DragApi({
  4342. forceDrop: drop,
  4343. drop: runIfActive(drop),
  4344. move: runIfActive(mousemove),
  4345. delayDrop: runIfActive(throttledDrop.throttle)
  4346. }), settings);
  4347. var destroy = function () {
  4348. sink.destroy();
  4349. };
  4350. return {
  4351. element: sink.element,
  4352. go: go,
  4353. on: on,
  4354. off: off,
  4355. destroy: destroy,
  4356. events: events.registry
  4357. };
  4358. };
  4359. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  4360. return {
  4361. target: target,
  4362. x: x,
  4363. y: y,
  4364. stop: stop,
  4365. prevent: prevent,
  4366. kill: kill,
  4367. raw: raw
  4368. };
  4369. };
  4370. var fromRawEvent$1 = function (rawEvent) {
  4371. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  4372. var stop = function () {
  4373. return rawEvent.stopPropagation();
  4374. };
  4375. var prevent = function () {
  4376. return rawEvent.preventDefault();
  4377. };
  4378. var kill = compose(prevent, stop);
  4379. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  4380. };
  4381. var handle$2 = function (filter, handler) {
  4382. return function (rawEvent) {
  4383. if (filter(rawEvent)) {
  4384. handler(fromRawEvent$1(rawEvent));
  4385. }
  4386. };
  4387. };
  4388. var binder = function (element, event, filter, handler, useCapture) {
  4389. var wrapped = handle$2(filter, handler);
  4390. element.dom.addEventListener(event, wrapped, useCapture);
  4391. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  4392. };
  4393. var bind$1 = function (element, event, filter, handler) {
  4394. return binder(element, event, filter, handler, false);
  4395. };
  4396. var unbind = function (element, event, handler, useCapture) {
  4397. element.dom.removeEventListener(event, handler, useCapture);
  4398. };
  4399. var filter = always;
  4400. var bind = function (element, event, handler) {
  4401. return bind$1(element, event, filter, handler);
  4402. };
  4403. var fromRawEvent = fromRawEvent$1;
  4404. var read = function (element, attr) {
  4405. var value = get$b(element, attr);
  4406. return value === undefined || value === '' ? [] : value.split(' ');
  4407. };
  4408. var add$2 = function (element, attr, id) {
  4409. var old = read(element, attr);
  4410. var nu = old.concat([id]);
  4411. set$2(element, attr, nu.join(' '));
  4412. return true;
  4413. };
  4414. var remove$4 = function (element, attr, id) {
  4415. var nu = filter$2(read(element, attr), function (v) {
  4416. return v !== id;
  4417. });
  4418. if (nu.length > 0) {
  4419. set$2(element, attr, nu.join(' '));
  4420. } else {
  4421. remove$7(element, attr);
  4422. }
  4423. return false;
  4424. };
  4425. var supports = function (element) {
  4426. return element.dom.classList !== undefined;
  4427. };
  4428. var get$5 = function (element) {
  4429. return read(element, 'class');
  4430. };
  4431. var add$1 = function (element, clazz) {
  4432. return add$2(element, 'class', clazz);
  4433. };
  4434. var remove$3 = function (element, clazz) {
  4435. return remove$4(element, 'class', clazz);
  4436. };
  4437. var add = function (element, clazz) {
  4438. if (supports(element)) {
  4439. element.dom.classList.add(clazz);
  4440. } else {
  4441. add$1(element, clazz);
  4442. }
  4443. };
  4444. var cleanClass = function (element) {
  4445. var classList = supports(element) ? element.dom.classList : get$5(element);
  4446. if (classList.length === 0) {
  4447. remove$7(element, 'class');
  4448. }
  4449. };
  4450. var remove$2 = function (element, clazz) {
  4451. if (supports(element)) {
  4452. var classList = element.dom.classList;
  4453. classList.remove(clazz);
  4454. } else {
  4455. remove$3(element, clazz);
  4456. }
  4457. cleanClass(element);
  4458. };
  4459. var has = function (element, clazz) {
  4460. return supports(element) && element.dom.classList.contains(clazz);
  4461. };
  4462. var css = function (namespace) {
  4463. var dashNamespace = namespace.replace(/\./g, '-');
  4464. var resolve = function (str) {
  4465. return dashNamespace + '-' + str;
  4466. };
  4467. return { resolve: resolve };
  4468. };
  4469. var styles$1 = css('ephox-dragster');
  4470. var resolve$1 = styles$1.resolve;
  4471. var Blocker = function (options) {
  4472. var settings = __assign({ layerClass: resolve$1('blocker') }, options);
  4473. var div = SugarElement.fromTag('div');
  4474. set$2(div, 'role', 'presentation');
  4475. setAll(div, {
  4476. position: 'fixed',
  4477. left: '0px',
  4478. top: '0px',
  4479. width: '100%',
  4480. height: '100%'
  4481. });
  4482. add(div, resolve$1('blocker'));
  4483. add(div, settings.layerClass);
  4484. var element = constant(div);
  4485. var destroy = function () {
  4486. remove$5(div);
  4487. };
  4488. return {
  4489. element: element,
  4490. destroy: destroy
  4491. };
  4492. };
  4493. var compare = function (old, nu) {
  4494. return SugarPosition(nu.left - old.left, nu.top - old.top);
  4495. };
  4496. var extract = function (event) {
  4497. return Optional.some(SugarPosition(event.x, event.y));
  4498. };
  4499. var mutate = function (mutation, info) {
  4500. mutation.mutate(info.left, info.top);
  4501. };
  4502. var sink = function (dragApi, settings) {
  4503. var blocker = Blocker(settings);
  4504. var mdown = bind(blocker.element(), 'mousedown', dragApi.forceDrop);
  4505. var mup = bind(blocker.element(), 'mouseup', dragApi.drop);
  4506. var mmove = bind(blocker.element(), 'mousemove', dragApi.move);
  4507. var mout = bind(blocker.element(), 'mouseout', dragApi.delayDrop);
  4508. var destroy = function () {
  4509. blocker.destroy();
  4510. mup.unbind();
  4511. mmove.unbind();
  4512. mout.unbind();
  4513. mdown.unbind();
  4514. };
  4515. var start = function (parent) {
  4516. append$1(parent, blocker.element());
  4517. };
  4518. var stop = function () {
  4519. remove$5(blocker.element());
  4520. };
  4521. return DragSink({
  4522. element: blocker.element,
  4523. start: start,
  4524. stop: stop,
  4525. destroy: destroy
  4526. });
  4527. };
  4528. var MouseDrag = DragMode({
  4529. compare: compare,
  4530. extract: extract,
  4531. sink: sink,
  4532. mutate: mutate
  4533. });
  4534. var transform$1 = function (mutation, settings) {
  4535. if (settings === void 0) {
  4536. settings = {};
  4537. }
  4538. var mode = settings.mode !== undefined ? settings.mode : MouseDrag;
  4539. return setup(mutation, mode, settings);
  4540. };
  4541. var closest = function (target) {
  4542. return closest$1(target, '[contenteditable]');
  4543. };
  4544. var isEditable$1 = function (element, assumeEditable) {
  4545. if (assumeEditable === void 0) {
  4546. assumeEditable = false;
  4547. }
  4548. if (!detect$3().browser.isIE() && inBody(element)) {
  4549. return element.dom.isContentEditable;
  4550. } else {
  4551. return closest(element).fold(constant(assumeEditable), function (editable) {
  4552. return getRaw(editable) === 'true';
  4553. });
  4554. }
  4555. };
  4556. var getRaw = function (element) {
  4557. return element.dom.contentEditable;
  4558. };
  4559. var styles = css('ephox-snooker');
  4560. var resolve = styles.resolve;
  4561. var Mutation = function () {
  4562. var events = create$4({
  4563. drag: Event([
  4564. 'xDelta',
  4565. 'yDelta'
  4566. ])
  4567. });
  4568. var mutate = function (x, y) {
  4569. events.trigger.drag(x, y);
  4570. };
  4571. return {
  4572. mutate: mutate,
  4573. events: events.registry
  4574. };
  4575. };
  4576. var BarMutation = function () {
  4577. var events = create$4({
  4578. drag: Event([
  4579. 'xDelta',
  4580. 'yDelta',
  4581. 'target'
  4582. ])
  4583. });
  4584. var target = Optional.none();
  4585. var delegate = Mutation();
  4586. delegate.events.drag.bind(function (event) {
  4587. target.each(function (t) {
  4588. events.trigger.drag(event.xDelta, event.yDelta, t);
  4589. });
  4590. });
  4591. var assign = function (t) {
  4592. target = Optional.some(t);
  4593. };
  4594. var get = function () {
  4595. return target;
  4596. };
  4597. return {
  4598. assign: assign,
  4599. get: get,
  4600. mutate: delegate.mutate,
  4601. events: events.registry
  4602. };
  4603. };
  4604. var col = function (column, x, y, w, h) {
  4605. var bar = SugarElement.fromTag('div');
  4606. setAll(bar, {
  4607. position: 'absolute',
  4608. left: x - w / 2 + 'px',
  4609. top: y + 'px',
  4610. height: h + 'px',
  4611. width: w + 'px'
  4612. });
  4613. setAll$1(bar, {
  4614. 'data-column': column,
  4615. 'role': 'presentation'
  4616. });
  4617. return bar;
  4618. };
  4619. var row = function (r, x, y, w, h) {
  4620. var bar = SugarElement.fromTag('div');
  4621. setAll(bar, {
  4622. position: 'absolute',
  4623. left: x + 'px',
  4624. top: y - h / 2 + 'px',
  4625. height: h + 'px',
  4626. width: w + 'px'
  4627. });
  4628. setAll$1(bar, {
  4629. 'data-row': r,
  4630. 'role': 'presentation'
  4631. });
  4632. return bar;
  4633. };
  4634. var resizeBar = resolve('resizer-bar');
  4635. var resizeRowBar = resolve('resizer-rows');
  4636. var resizeColBar = resolve('resizer-cols');
  4637. var BAR_THICKNESS = 7;
  4638. var resizableRows = function (warehouse, isResizable) {
  4639. return bind$2(warehouse.all, function (row, i) {
  4640. return isResizable(row.element) ? [i] : [];
  4641. });
  4642. };
  4643. var resizableColumns = function (warehouse, isResizable) {
  4644. var resizableCols = [];
  4645. range$1(warehouse.grid.columns, function (index) {
  4646. var colElmOpt = Warehouse.getColumnAt(warehouse, index).map(function (col) {
  4647. return col.element;
  4648. });
  4649. if (colElmOpt.forall(isResizable)) {
  4650. resizableCols.push(index);
  4651. }
  4652. });
  4653. return filter$2(resizableCols, function (colIndex) {
  4654. var columnCells = Warehouse.filterItems(warehouse, function (cell) {
  4655. return cell.column === colIndex;
  4656. });
  4657. return forall(columnCells, function (cell) {
  4658. return isResizable(cell.element);
  4659. });
  4660. });
  4661. };
  4662. var destroy = function (wire) {
  4663. var previous = descendants(wire.parent(), '.' + resizeBar);
  4664. each$2(previous, remove$5);
  4665. };
  4666. var drawBar = function (wire, positions, create) {
  4667. var origin = wire.origin();
  4668. each$2(positions, function (cpOption) {
  4669. cpOption.each(function (cp) {
  4670. var bar = create(origin, cp);
  4671. add(bar, resizeBar);
  4672. append$1(wire.parent(), bar);
  4673. });
  4674. });
  4675. };
  4676. var refreshCol = function (wire, colPositions, position, tableHeight) {
  4677. drawBar(wire, colPositions, function (origin, cp) {
  4678. var colBar = col(cp.col, cp.x - origin.left, position.top - origin.top, BAR_THICKNESS, tableHeight);
  4679. add(colBar, resizeColBar);
  4680. return colBar;
  4681. });
  4682. };
  4683. var refreshRow = function (wire, rowPositions, position, tableWidth) {
  4684. drawBar(wire, rowPositions, function (origin, cp) {
  4685. var rowBar = row(cp.row, position.left - origin.left, cp.y - origin.top, tableWidth, BAR_THICKNESS);
  4686. add(rowBar, resizeRowBar);
  4687. return rowBar;
  4688. });
  4689. };
  4690. var refreshGrid = function (warhouse, wire, table, rows, cols) {
  4691. var position = absolute(table);
  4692. var isResizable = wire.isResizable;
  4693. var rowPositions = rows.length > 0 ? height.positions(rows, table) : [];
  4694. var resizableRowBars = rowPositions.length > 0 ? resizableRows(warhouse, isResizable) : [];
  4695. var resizableRowPositions = filter$2(rowPositions, function (_pos, i) {
  4696. return exists(resizableRowBars, function (barIndex) {
  4697. return i === barIndex;
  4698. });
  4699. });
  4700. refreshRow(wire, resizableRowPositions, position, getOuter$2(table));
  4701. var colPositions = cols.length > 0 ? width.positions(cols, table) : [];
  4702. var resizableColBars = colPositions.length > 0 ? resizableColumns(warhouse, isResizable) : [];
  4703. var resizableColPositions = filter$2(colPositions, function (_pos, i) {
  4704. return exists(resizableColBars, function (barIndex) {
  4705. return i === barIndex;
  4706. });
  4707. });
  4708. refreshCol(wire, resizableColPositions, position, getOuter$1(table));
  4709. };
  4710. var refresh = function (wire, table) {
  4711. destroy(wire);
  4712. if (wire.isResizable(table)) {
  4713. var warehouse = Warehouse.fromTable(table);
  4714. var rows$1 = rows(warehouse);
  4715. var cols = columns(warehouse);
  4716. refreshGrid(warehouse, wire, table, rows$1, cols);
  4717. }
  4718. };
  4719. var each = function (wire, f) {
  4720. var bars = descendants(wire.parent(), '.' + resizeBar);
  4721. each$2(bars, f);
  4722. };
  4723. var hide = function (wire) {
  4724. each(wire, function (bar) {
  4725. set$1(bar, 'display', 'none');
  4726. });
  4727. };
  4728. var show = function (wire) {
  4729. each(wire, function (bar) {
  4730. set$1(bar, 'display', 'block');
  4731. });
  4732. };
  4733. var isRowBar = function (element) {
  4734. return has(element, resizeRowBar);
  4735. };
  4736. var isColBar = function (element) {
  4737. return has(element, resizeColBar);
  4738. };
  4739. var resizeBarDragging = resolve('resizer-bar-dragging');
  4740. var BarManager = function (wire) {
  4741. var mutation = BarMutation();
  4742. var resizing = transform$1(mutation, {});
  4743. var hoverTable = Optional.none();
  4744. var getResizer = function (element, type) {
  4745. return Optional.from(get$b(element, type));
  4746. };
  4747. mutation.events.drag.bind(function (event) {
  4748. getResizer(event.target, 'data-row').each(function (_dataRow) {
  4749. var currentRow = getCssValue(event.target, 'top');
  4750. set$1(event.target, 'top', currentRow + event.yDelta + 'px');
  4751. });
  4752. getResizer(event.target, 'data-column').each(function (_dataCol) {
  4753. var currentCol = getCssValue(event.target, 'left');
  4754. set$1(event.target, 'left', currentCol + event.xDelta + 'px');
  4755. });
  4756. });
  4757. var getDelta = function (target, dir) {
  4758. var newX = getCssValue(target, dir);
  4759. var oldX = getAttrValue(target, 'data-initial-' + dir, 0);
  4760. return newX - oldX;
  4761. };
  4762. resizing.events.stop.bind(function () {
  4763. mutation.get().each(function (target) {
  4764. hoverTable.each(function (table) {
  4765. getResizer(target, 'data-row').each(function (row) {
  4766. var delta = getDelta(target, 'top');
  4767. remove$7(target, 'data-initial-top');
  4768. events.trigger.adjustHeight(table, delta, parseInt(row, 10));
  4769. });
  4770. getResizer(target, 'data-column').each(function (column) {
  4771. var delta = getDelta(target, 'left');
  4772. remove$7(target, 'data-initial-left');
  4773. events.trigger.adjustWidth(table, delta, parseInt(column, 10));
  4774. });
  4775. refresh(wire, table);
  4776. });
  4777. });
  4778. });
  4779. var handler = function (target, dir) {
  4780. events.trigger.startAdjust();
  4781. mutation.assign(target);
  4782. set$2(target, 'data-initial-' + dir, getCssValue(target, dir));
  4783. add(target, resizeBarDragging);
  4784. set$1(target, 'opacity', '0.2');
  4785. resizing.go(wire.parent());
  4786. };
  4787. var mousedown = bind(wire.parent(), 'mousedown', function (event) {
  4788. if (isRowBar(event.target)) {
  4789. handler(event.target, 'top');
  4790. }
  4791. if (isColBar(event.target)) {
  4792. handler(event.target, 'left');
  4793. }
  4794. });
  4795. var isRoot = function (e) {
  4796. return eq$1(e, wire.view());
  4797. };
  4798. var findClosestEditableTable = function (target) {
  4799. return closest$1(target, 'table', isRoot).filter(isEditable$1);
  4800. };
  4801. var mouseover = bind(wire.view(), 'mouseover', function (event) {
  4802. findClosestEditableTable(event.target).fold(function () {
  4803. if (inBody(event.target)) {
  4804. destroy(wire);
  4805. }
  4806. }, function (table) {
  4807. hoverTable = Optional.some(table);
  4808. refresh(wire, table);
  4809. });
  4810. });
  4811. var destroy$1 = function () {
  4812. mousedown.unbind();
  4813. mouseover.unbind();
  4814. resizing.destroy();
  4815. destroy(wire);
  4816. };
  4817. var refresh$1 = function (tbl) {
  4818. refresh(wire, tbl);
  4819. };
  4820. var events = create$4({
  4821. adjustHeight: Event([
  4822. 'table',
  4823. 'delta',
  4824. 'row'
  4825. ]),
  4826. adjustWidth: Event([
  4827. 'table',
  4828. 'delta',
  4829. 'column'
  4830. ]),
  4831. startAdjust: Event([])
  4832. });
  4833. return {
  4834. destroy: destroy$1,
  4835. refresh: refresh$1,
  4836. on: resizing.on,
  4837. off: resizing.off,
  4838. hideBars: curry(hide, wire),
  4839. showBars: curry(show, wire),
  4840. events: events.registry
  4841. };
  4842. };
  4843. var create$3 = function (wire, resizing, lazySizing) {
  4844. var hdirection = height;
  4845. var vdirection = width;
  4846. var manager = BarManager(wire);
  4847. var events = create$4({
  4848. beforeResize: Event([
  4849. 'table',
  4850. 'type'
  4851. ]),
  4852. afterResize: Event([
  4853. 'table',
  4854. 'type'
  4855. ]),
  4856. startDrag: Event([])
  4857. });
  4858. manager.events.adjustHeight.bind(function (event) {
  4859. var table = event.table;
  4860. events.trigger.beforeResize(table, 'row');
  4861. var delta = hdirection.delta(event.delta, table);
  4862. adjustHeight(table, delta, event.row, hdirection);
  4863. events.trigger.afterResize(table, 'row');
  4864. });
  4865. manager.events.startAdjust.bind(function (_event) {
  4866. events.trigger.startDrag();
  4867. });
  4868. manager.events.adjustWidth.bind(function (event) {
  4869. var table = event.table;
  4870. events.trigger.beforeResize(table, 'col');
  4871. var delta = vdirection.delta(event.delta, table);
  4872. var tableSize = lazySizing(table);
  4873. adjustWidth(table, delta, event.column, resizing, tableSize);
  4874. events.trigger.afterResize(table, 'col');
  4875. });
  4876. return {
  4877. on: manager.on,
  4878. off: manager.off,
  4879. hideBars: manager.hideBars,
  4880. showBars: manager.showBars,
  4881. destroy: manager.destroy,
  4882. events: events.registry
  4883. };
  4884. };
  4885. var TableResize = { create: create$3 };
  4886. var fireNewRow = function (editor, row) {
  4887. return editor.fire('newrow', { node: row });
  4888. };
  4889. var fireNewCell = function (editor, cell) {
  4890. return editor.fire('newcell', { node: cell });
  4891. };
  4892. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  4893. editor.fire('ObjectResizeStart', {
  4894. target: target,
  4895. width: width,
  4896. height: height,
  4897. origin: origin
  4898. });
  4899. };
  4900. var fireObjectResized = function (editor, target, width, height, origin) {
  4901. editor.fire('ObjectResized', {
  4902. target: target,
  4903. width: width,
  4904. height: height,
  4905. origin: origin
  4906. });
  4907. };
  4908. var fireTableSelectionChange = function (editor, cells, start, finish, otherCells) {
  4909. editor.fire('TableSelectionChange', {
  4910. cells: cells,
  4911. start: start,
  4912. finish: finish,
  4913. otherCells: otherCells
  4914. });
  4915. };
  4916. var fireTableSelectionClear = function (editor) {
  4917. editor.fire('TableSelectionClear');
  4918. };
  4919. var fireTableModified = function (editor, table, data) {
  4920. editor.fire('TableModified', __assign(__assign({}, data), { table: table }));
  4921. };
  4922. var styleModified = {
  4923. structure: false,
  4924. style: true
  4925. };
  4926. var structureModified = {
  4927. structure: true,
  4928. style: false
  4929. };
  4930. var styleAndStructureModified = {
  4931. structure: true,
  4932. style: true
  4933. };
  4934. var defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
  4935. var defaultStyles = {
  4936. 'border-collapse': 'collapse',
  4937. 'width': '100%'
  4938. };
  4939. var defaultCellBorderWidths = range$1(5, function (i) {
  4940. var size = i + 1 + 'px';
  4941. return {
  4942. title: size,
  4943. value: size
  4944. };
  4945. });
  4946. var defaultCellBorderStyles = map$1([
  4947. 'Solid',
  4948. 'Dotted',
  4949. 'Dashed',
  4950. 'Double',
  4951. 'Groove',
  4952. 'Ridge',
  4953. 'Inset',
  4954. 'Outset',
  4955. 'None',
  4956. 'Hidden'
  4957. ], function (type) {
  4958. return {
  4959. title: type,
  4960. value: type.toLowerCase()
  4961. };
  4962. });
  4963. var determineDefaultStyles = function (editor) {
  4964. var _a;
  4965. if (isPixelsForced(editor)) {
  4966. var dom = editor.dom;
  4967. var parentBlock = (_a = dom.getParent(editor.selection.getStart(), dom.isBlock)) !== null && _a !== void 0 ? _a : editor.getBody();
  4968. var contentWidth = getInner(SugarElement.fromDom(parentBlock));
  4969. return __assign(__assign({}, defaultStyles), { width: contentWidth + 'px' });
  4970. } else if (isResponsiveForced(editor)) {
  4971. return filter$1(defaultStyles, function (_value, key) {
  4972. return key !== 'width';
  4973. });
  4974. } else {
  4975. return defaultStyles;
  4976. }
  4977. };
  4978. var defaultAttributes = { border: '1' };
  4979. var defaultColumnResizingBehaviour = 'preservetable';
  4980. var getTableSizingMode = function (editor) {
  4981. return editor.getParam('table_sizing_mode', 'auto');
  4982. };
  4983. var getTableResponseWidth = function (editor) {
  4984. return editor.getParam('table_responsive_width');
  4985. };
  4986. var getTableBorderWidths = function (editor) {
  4987. return editor.getParam('table_border_widths', defaultCellBorderWidths, 'array');
  4988. };
  4989. var getTableBorderStyles = function (editor) {
  4990. return editor.getParam('table_border_styles', defaultCellBorderStyles, 'array');
  4991. };
  4992. var getDefaultAttributes = function (editor) {
  4993. return editor.getParam('table_default_attributes', defaultAttributes, 'object');
  4994. };
  4995. var getDefaultStyles = function (editor) {
  4996. return editor.getParam('table_default_styles', determineDefaultStyles(editor), 'object');
  4997. };
  4998. var hasTableResizeBars = function (editor) {
  4999. return editor.getParam('table_resize_bars', true, 'boolean');
  5000. };
  5001. var hasTabNavigation = function (editor) {
  5002. return editor.getParam('table_tab_navigation', true, 'boolean');
  5003. };
  5004. var hasAdvancedCellTab = function (editor) {
  5005. return editor.getParam('table_cell_advtab', true, 'boolean');
  5006. };
  5007. var hasAdvancedRowTab = function (editor) {
  5008. return editor.getParam('table_row_advtab', true, 'boolean');
  5009. };
  5010. var hasAdvancedTableTab = function (editor) {
  5011. return editor.getParam('table_advtab', true, 'boolean');
  5012. };
  5013. var hasAppearanceOptions = function (editor) {
  5014. return editor.getParam('table_appearance_options', true, 'boolean');
  5015. };
  5016. var hasTableGrid = function (editor) {
  5017. return editor.getParam('table_grid', true, 'boolean');
  5018. };
  5019. var shouldStyleWithCss = function (editor) {
  5020. return editor.getParam('table_style_by_css', false, 'boolean');
  5021. };
  5022. var getCellClassList = function (editor) {
  5023. return editor.getParam('table_cell_class_list', [], 'array');
  5024. };
  5025. var getRowClassList = function (editor) {
  5026. return editor.getParam('table_row_class_list', [], 'array');
  5027. };
  5028. var getTableClassList = function (editor) {
  5029. return editor.getParam('table_class_list', [], 'array');
  5030. };
  5031. var isPercentagesForced = function (editor) {
  5032. return getTableSizingMode(editor) === 'relative' || getTableResponseWidth(editor) === true;
  5033. };
  5034. var isPixelsForced = function (editor) {
  5035. return getTableSizingMode(editor) === 'fixed' || getTableResponseWidth(editor) === false;
  5036. };
  5037. var isResponsiveForced = function (editor) {
  5038. return getTableSizingMode(editor) === 'responsive';
  5039. };
  5040. var getToolbar = function (editor) {
  5041. return editor.getParam('table_toolbar', defaultTableToolbar);
  5042. };
  5043. var useColumnGroup = function (editor) {
  5044. return editor.getParam('table_use_colgroups', false, 'boolean');
  5045. };
  5046. var getTableHeaderType = function (editor) {
  5047. var defaultValue = 'section';
  5048. var value = editor.getParam('table_header_type', defaultValue, 'string');
  5049. var validValues = [
  5050. 'section',
  5051. 'cells',
  5052. 'sectionCells',
  5053. 'auto'
  5054. ];
  5055. if (!contains$2(validValues, value)) {
  5056. return defaultValue;
  5057. } else {
  5058. return value;
  5059. }
  5060. };
  5061. var getColumnResizingBehaviour = function (editor) {
  5062. var validModes = [
  5063. 'preservetable',
  5064. 'resizetable'
  5065. ];
  5066. var givenMode = editor.getParam('table_column_resizing', defaultColumnResizingBehaviour, 'string');
  5067. return find$1(validModes, function (mode) {
  5068. return mode === givenMode;
  5069. }).getOr(defaultColumnResizingBehaviour);
  5070. };
  5071. var isPreserveTableColumnResizing = function (editor) {
  5072. return getColumnResizingBehaviour(editor) === 'preservetable';
  5073. };
  5074. var isResizeTableColumnResizing = function (editor) {
  5075. return getColumnResizingBehaviour(editor) === 'resizetable';
  5076. };
  5077. var getCloneElements = function (editor) {
  5078. var cloneElements = editor.getParam('table_clone_elements');
  5079. if (isString(cloneElements)) {
  5080. return Optional.some(cloneElements.split(/[ ,]/));
  5081. } else if (Array.isArray(cloneElements)) {
  5082. return Optional.some(cloneElements);
  5083. } else {
  5084. return Optional.none();
  5085. }
  5086. };
  5087. var hasObjectResizing = function (editor) {
  5088. var objectResizing = editor.getParam('object_resizing', true);
  5089. return isString(objectResizing) ? objectResizing === 'table' : objectResizing;
  5090. };
  5091. var getTableBackgroundColorMap = function (editor) {
  5092. return editor.getParam('table_background_color_map', [], 'array');
  5093. };
  5094. var getTableBorderColorMap = function (editor) {
  5095. return editor.getParam('table_border_color_map', [], 'array');
  5096. };
  5097. var get$4 = function (editor, table) {
  5098. if (isPercentagesForced(editor)) {
  5099. return TableSize.percentageSize(table);
  5100. } else if (isPixelsForced(editor)) {
  5101. return TableSize.pixelSize(table);
  5102. } else {
  5103. return TableSize.getTableSize(table);
  5104. }
  5105. };
  5106. var cleanupLegacyAttributes = function (element) {
  5107. remove$7(element, 'width');
  5108. };
  5109. var convertToPercentSize = function (table) {
  5110. var newWidth = getPercentTableWidth(table);
  5111. redistribute(table, Optional.some(newWidth), Optional.none());
  5112. cleanupLegacyAttributes(table);
  5113. };
  5114. var convertToPixelSize = function (table) {
  5115. var newWidth = getPixelTableWidth(table);
  5116. redistribute(table, Optional.some(newWidth), Optional.none());
  5117. cleanupLegacyAttributes(table);
  5118. };
  5119. var convertToNoneSize = function (table) {
  5120. remove$6(table, 'width');
  5121. var columns = columns$1(table);
  5122. var rowElements = columns.length > 0 ? columns : cells$1(table);
  5123. each$2(rowElements, function (cell) {
  5124. remove$6(cell, 'width');
  5125. cleanupLegacyAttributes(cell);
  5126. });
  5127. cleanupLegacyAttributes(table);
  5128. };
  5129. var enforcePercentage = convertToPercentSize;
  5130. var enforcePixels = convertToPixelSize;
  5131. var enforceNone = convertToNoneSize;
  5132. var syncPixels = function (table) {
  5133. var warehouse = Warehouse.fromTable(table);
  5134. if (!Warehouse.hasColumns(warehouse)) {
  5135. each$2(cells$1(table), function (cell) {
  5136. var computedWidth = get$a(cell, 'width');
  5137. set$1(cell, 'width', computedWidth);
  5138. remove$7(cell, 'width');
  5139. });
  5140. }
  5141. };
  5142. var createContainer = function () {
  5143. var container = SugarElement.fromTag('div');
  5144. setAll(container, {
  5145. position: 'static',
  5146. height: '0',
  5147. width: '0',
  5148. padding: '0',
  5149. margin: '0',
  5150. border: '0'
  5151. });
  5152. append$1(body$1(), container);
  5153. return container;
  5154. };
  5155. var get$3 = function (editor, isResizable) {
  5156. return editor.inline ? ResizeWire.body(getBody(editor), createContainer(), isResizable) : ResizeWire.only(SugarElement.fromDom(editor.getDoc()), isResizable);
  5157. };
  5158. var remove$1 = function (editor, wire) {
  5159. if (editor.inline) {
  5160. remove$5(wire.parent());
  5161. }
  5162. };
  5163. var barResizerPrefix = 'bar-';
  5164. var isResizable = function (elm) {
  5165. return get$b(elm, 'data-mce-resize') !== 'false';
  5166. };
  5167. var getResizeHandler = function (editor) {
  5168. var selectionRng = Optional.none();
  5169. var resize = Optional.none();
  5170. var wire = Optional.none();
  5171. var startW;
  5172. var startRawW;
  5173. var isTable = function (elm) {
  5174. return elm.nodeName === 'TABLE';
  5175. };
  5176. var lazyResize = function () {
  5177. return resize;
  5178. };
  5179. var lazyWire = function () {
  5180. return wire.getOr(ResizeWire.only(SugarElement.fromDom(editor.getBody()), isResizable));
  5181. };
  5182. var lazySizing = function (table) {
  5183. return get$4(editor, table);
  5184. };
  5185. var lazyResizingBehaviour = function () {
  5186. return isPreserveTableColumnResizing(editor) ? preserveTable() : resizeTable();
  5187. };
  5188. var getNumColumns = function (table) {
  5189. return getGridSize(table).columns;
  5190. };
  5191. var afterCornerResize = function (table, origin, width) {
  5192. var isRightEdgeResize = endsWith(origin, 'e');
  5193. if (startRawW === '') {
  5194. enforcePercentage(table);
  5195. }
  5196. if (width !== startW && startRawW !== '') {
  5197. set$1(table, 'width', startRawW);
  5198. var resizing = lazyResizingBehaviour();
  5199. var tableSize = lazySizing(table);
  5200. var col = isPreserveTableColumnResizing(editor) || isRightEdgeResize ? getNumColumns(table) - 1 : 0;
  5201. adjustWidth(table, width - startW, col, resizing, tableSize);
  5202. } else if (isPercentage$1(startRawW)) {
  5203. var percentW = parseFloat(startRawW.replace('%', ''));
  5204. var targetPercentW = width * percentW / startW;
  5205. set$1(table, 'width', targetPercentW + '%');
  5206. }
  5207. if (isPixel(startRawW)) {
  5208. syncPixels(table);
  5209. }
  5210. };
  5211. var destroy = function () {
  5212. resize.each(function (sz) {
  5213. sz.destroy();
  5214. });
  5215. wire.each(function (w) {
  5216. remove$1(editor, w);
  5217. });
  5218. };
  5219. editor.on('init', function () {
  5220. var rawWire = get$3(editor, isResizable);
  5221. wire = Optional.some(rawWire);
  5222. if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
  5223. var resizing = lazyResizingBehaviour();
  5224. var sz = TableResize.create(rawWire, resizing, lazySizing);
  5225. sz.on();
  5226. sz.events.startDrag.bind(function (_event) {
  5227. selectionRng = Optional.some(editor.selection.getRng());
  5228. });
  5229. sz.events.beforeResize.bind(function (event) {
  5230. var rawTable = event.table.dom;
  5231. fireObjectResizeStart(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
  5232. });
  5233. sz.events.afterResize.bind(function (event) {
  5234. var table = event.table;
  5235. var rawTable = table.dom;
  5236. removeDataStyle(table);
  5237. selectionRng.each(function (rng) {
  5238. editor.selection.setRng(rng);
  5239. editor.focus();
  5240. });
  5241. fireObjectResized(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
  5242. editor.undoManager.add();
  5243. });
  5244. resize = Optional.some(sz);
  5245. }
  5246. });
  5247. editor.on('ObjectResizeStart', function (e) {
  5248. var targetElm = e.target;
  5249. if (isTable(targetElm)) {
  5250. var table = SugarElement.fromDom(targetElm);
  5251. each$2(editor.dom.select('.mce-clonedresizable'), function (clone) {
  5252. editor.dom.addClass(clone, 'mce-' + getColumnResizingBehaviour(editor) + '-columns');
  5253. });
  5254. if (!isPixelSizing(table) && isPixelsForced(editor)) {
  5255. enforcePixels(table);
  5256. } else if (!isPercentSizing(table) && isPercentagesForced(editor)) {
  5257. enforcePercentage(table);
  5258. }
  5259. if (isNoneSizing(table) && startsWith(e.origin, barResizerPrefix)) {
  5260. enforcePercentage(table);
  5261. }
  5262. startW = e.width;
  5263. startRawW = isResponsiveForced(editor) ? '' : getRawWidth(editor, targetElm).getOr('');
  5264. }
  5265. });
  5266. editor.on('ObjectResized', function (e) {
  5267. var targetElm = e.target;
  5268. if (isTable(targetElm)) {
  5269. var table = SugarElement.fromDom(targetElm);
  5270. var origin_1 = e.origin;
  5271. if (startsWith(origin_1, 'corner-')) {
  5272. afterCornerResize(table, origin_1, e.width);
  5273. }
  5274. removeDataStyle(table);
  5275. fireTableModified(editor, table.dom, styleModified);
  5276. }
  5277. });
  5278. editor.on('SwitchMode', function () {
  5279. lazyResize().each(function (resize) {
  5280. if (editor.mode.isReadOnly()) {
  5281. resize.hideBars();
  5282. } else {
  5283. resize.showBars();
  5284. }
  5285. });
  5286. });
  5287. return {
  5288. lazyResize: lazyResize,
  5289. lazyWire: lazyWire,
  5290. destroy: destroy
  5291. };
  5292. };
  5293. var point = function (element, offset) {
  5294. return {
  5295. element: element,
  5296. offset: offset
  5297. };
  5298. };
  5299. var scan$1 = function (universe, element, direction) {
  5300. if (universe.property().isText(element) && universe.property().getText(element).trim().length === 0 || universe.property().isComment(element)) {
  5301. return direction(element).bind(function (elem) {
  5302. return scan$1(universe, elem, direction).orThunk(function () {
  5303. return Optional.some(elem);
  5304. });
  5305. });
  5306. } else {
  5307. return Optional.none();
  5308. }
  5309. };
  5310. var toEnd = function (universe, element) {
  5311. if (universe.property().isText(element)) {
  5312. return universe.property().getText(element).length;
  5313. }
  5314. var children = universe.property().children(element);
  5315. return children.length;
  5316. };
  5317. var freefallRtl$2 = function (universe, element) {
  5318. var candidate = scan$1(universe, element, universe.query().prevSibling).getOr(element);
  5319. if (universe.property().isText(candidate)) {
  5320. return point(candidate, toEnd(universe, candidate));
  5321. }
  5322. var children = universe.property().children(candidate);
  5323. return children.length > 0 ? freefallRtl$2(universe, children[children.length - 1]) : point(candidate, toEnd(universe, candidate));
  5324. };
  5325. var freefallRtl$1 = freefallRtl$2;
  5326. var universe$2 = DomUniverse();
  5327. var freefallRtl = function (element) {
  5328. return freefallRtl$1(universe$2, element);
  5329. };
  5330. var halve = function (main, other) {
  5331. var colspan = getSpan(main, 'colspan');
  5332. if (colspan === 1) {
  5333. var width = getGenericWidth(main);
  5334. width.each(function (w) {
  5335. var newWidth = w.value / 2;
  5336. setGenericWidth(main, newWidth, w.unit);
  5337. setGenericWidth(other, newWidth, w.unit);
  5338. });
  5339. }
  5340. };
  5341. var isHeaderCell = isTag('th');
  5342. var isHeaderCells = function (cells) {
  5343. return forall(cells, function (cell) {
  5344. return isHeaderCell(cell.element);
  5345. });
  5346. };
  5347. var getRowHeaderType = function (isHeaderRow, isHeaderCells) {
  5348. if (isHeaderRow && isHeaderCells) {
  5349. return 'sectionCells';
  5350. } else if (isHeaderRow) {
  5351. return 'section';
  5352. } else {
  5353. return 'cells';
  5354. }
  5355. };
  5356. var getRowType$1 = function (row) {
  5357. var isHeaderRow = row.section === 'thead';
  5358. var isHeaderCells = is(findCommonCellType(row.cells), 'th');
  5359. if (isHeaderRow || isHeaderCells) {
  5360. return {
  5361. type: 'header',
  5362. subType: getRowHeaderType(isHeaderRow, isHeaderCells)
  5363. };
  5364. } else if (row.section === 'tfoot') {
  5365. return { type: 'footer' };
  5366. } else {
  5367. return { type: 'body' };
  5368. }
  5369. };
  5370. var findCommonCellType = function (cells) {
  5371. var headerCells = filter$2(cells, function (cell) {
  5372. return isHeaderCell(cell.element);
  5373. });
  5374. if (headerCells.length === 0) {
  5375. return Optional.some('td');
  5376. } else if (headerCells.length === cells.length) {
  5377. return Optional.some('th');
  5378. } else {
  5379. return Optional.none();
  5380. }
  5381. };
  5382. var findCommonRowType = function (rows) {
  5383. var rowTypes = map$1(rows, function (row) {
  5384. return getRowType$1(row).type;
  5385. });
  5386. var hasHeader = contains$2(rowTypes, 'header');
  5387. var hasFooter = contains$2(rowTypes, 'footer');
  5388. if (!hasHeader && !hasFooter) {
  5389. return Optional.some('body');
  5390. } else {
  5391. var hasBody = contains$2(rowTypes, 'body');
  5392. if (hasHeader && !hasBody && !hasFooter) {
  5393. return Optional.some('header');
  5394. } else if (!hasHeader && !hasBody && hasFooter) {
  5395. return Optional.some('footer');
  5396. } else {
  5397. return Optional.none();
  5398. }
  5399. }
  5400. };
  5401. var findTableRowHeaderType = function (warehouse) {
  5402. return findMap(warehouse.all, function (row) {
  5403. var rowType = getRowType$1(row);
  5404. return rowType.type === 'header' ? Optional.from(rowType.subType) : Optional.none();
  5405. });
  5406. };
  5407. var transformCell = function (cell, comparator, substitution) {
  5408. return elementnew(substitution(cell.element, comparator), true, cell.isLocked);
  5409. };
  5410. var transformRow = function (row, section) {
  5411. return row.section !== section ? rowcells(row.element, row.cells, section, row.isNew) : row;
  5412. };
  5413. var section = function () {
  5414. return {
  5415. transformRow: transformRow,
  5416. transformCell: function (cell, comparator, substitution) {
  5417. var newCell = substitution(cell.element, comparator);
  5418. var fixedCell = name(newCell) !== 'td' ? mutate$1(newCell, 'td') : newCell;
  5419. return elementnew(fixedCell, cell.isNew, cell.isLocked);
  5420. }
  5421. };
  5422. };
  5423. var sectionCells = function () {
  5424. return {
  5425. transformRow: transformRow,
  5426. transformCell: transformCell
  5427. };
  5428. };
  5429. var cells = function () {
  5430. return {
  5431. transformRow: function (row, section) {
  5432. var newSection = section === 'thead' ? 'tbody' : section;
  5433. return transformRow(row, newSection);
  5434. },
  5435. transformCell: transformCell
  5436. };
  5437. };
  5438. var fallback = function () {
  5439. return {
  5440. transformRow: identity,
  5441. transformCell: transformCell
  5442. };
  5443. };
  5444. var getTableSectionType = function (table, fallback) {
  5445. var warehouse = Warehouse.fromTable(table);
  5446. var type = findTableRowHeaderType(warehouse).getOr(fallback);
  5447. switch (type) {
  5448. case 'section':
  5449. return section();
  5450. case 'sectionCells':
  5451. return sectionCells();
  5452. case 'cells':
  5453. return cells();
  5454. }
  5455. };
  5456. var TableSection = {
  5457. getTableSectionType: getTableSectionType,
  5458. section: section,
  5459. sectionCells: sectionCells,
  5460. cells: cells,
  5461. fallback: fallback
  5462. };
  5463. var setIfNot = function (element, property, value, ignore) {
  5464. if (value === ignore) {
  5465. remove$7(element, property);
  5466. } else {
  5467. set$2(element, property, value);
  5468. }
  5469. };
  5470. var insert$1 = function (table, selector, element) {
  5471. last$2(children$1(table, selector)).fold(function () {
  5472. return prepend(table, element);
  5473. }, function (child) {
  5474. return after$5(child, element);
  5475. });
  5476. };
  5477. var generateSection = function (table, sectionName) {
  5478. var section = child$1(table, sectionName).getOrThunk(function () {
  5479. var newSection = SugarElement.fromTag(sectionName, owner(table).dom);
  5480. if (sectionName === 'thead') {
  5481. insert$1(table, 'caption,colgroup', newSection);
  5482. } else if (sectionName === 'colgroup') {
  5483. insert$1(table, 'caption', newSection);
  5484. } else {
  5485. append$1(table, newSection);
  5486. }
  5487. return newSection;
  5488. });
  5489. empty(section);
  5490. return section;
  5491. };
  5492. var render$1 = function (table, grid) {
  5493. var newRows = [];
  5494. var newCells = [];
  5495. var syncRows = function (gridSection) {
  5496. return map$1(gridSection, function (row) {
  5497. if (row.isNew) {
  5498. newRows.push(row.element);
  5499. }
  5500. var tr = row.element;
  5501. empty(tr);
  5502. each$2(row.cells, function (cell) {
  5503. if (cell.isNew) {
  5504. newCells.push(cell.element);
  5505. }
  5506. setIfNot(cell.element, 'colspan', cell.colspan, 1);
  5507. setIfNot(cell.element, 'rowspan', cell.rowspan, 1);
  5508. append$1(tr, cell.element);
  5509. });
  5510. return tr;
  5511. });
  5512. };
  5513. var syncColGroup = function (gridSection) {
  5514. return bind$2(gridSection, function (colGroup) {
  5515. return map$1(colGroup.cells, function (col) {
  5516. setIfNot(col.element, 'span', col.colspan, 1);
  5517. return col.element;
  5518. });
  5519. });
  5520. };
  5521. var renderSection = function (gridSection, sectionName) {
  5522. var section = generateSection(table, sectionName);
  5523. var sync = sectionName === 'colgroup' ? syncColGroup : syncRows;
  5524. var sectionElems = sync(gridSection);
  5525. append(section, sectionElems);
  5526. };
  5527. var removeSection = function (sectionName) {
  5528. child$1(table, sectionName).each(remove$5);
  5529. };
  5530. var renderOrRemoveSection = function (gridSection, sectionName) {
  5531. if (gridSection.length > 0) {
  5532. renderSection(gridSection, sectionName);
  5533. } else {
  5534. removeSection(sectionName);
  5535. }
  5536. };
  5537. var headSection = [];
  5538. var bodySection = [];
  5539. var footSection = [];
  5540. var columnGroupsSection = [];
  5541. each$2(grid, function (row) {
  5542. switch (row.section) {
  5543. case 'thead':
  5544. headSection.push(row);
  5545. break;
  5546. case 'tbody':
  5547. bodySection.push(row);
  5548. break;
  5549. case 'tfoot':
  5550. footSection.push(row);
  5551. break;
  5552. case 'colgroup':
  5553. columnGroupsSection.push(row);
  5554. break;
  5555. }
  5556. });
  5557. renderOrRemoveSection(columnGroupsSection, 'colgroup');
  5558. renderOrRemoveSection(headSection, 'thead');
  5559. renderOrRemoveSection(bodySection, 'tbody');
  5560. renderOrRemoveSection(footSection, 'tfoot');
  5561. return {
  5562. newRows: newRows,
  5563. newCells: newCells
  5564. };
  5565. };
  5566. var copy = function (grid) {
  5567. return map$1(grid, function (row) {
  5568. var tr = shallow(row.element);
  5569. each$2(row.cells, function (cell) {
  5570. var clonedCell = deep(cell.element);
  5571. setIfNot(clonedCell, 'colspan', cell.colspan, 1);
  5572. setIfNot(clonedCell, 'rowspan', cell.rowspan, 1);
  5573. append$1(tr, clonedCell);
  5574. });
  5575. return tr;
  5576. });
  5577. };
  5578. var getColumn = function (grid, index) {
  5579. return map$1(grid, function (row) {
  5580. return getCell(row, index);
  5581. });
  5582. };
  5583. var getRow = function (grid, index) {
  5584. return grid[index];
  5585. };
  5586. var findDiff = function (xs, comp) {
  5587. if (xs.length === 0) {
  5588. return 0;
  5589. }
  5590. var first = xs[0];
  5591. var index = findIndex(xs, function (x) {
  5592. return !comp(first.element, x.element);
  5593. });
  5594. return index.getOr(xs.length);
  5595. };
  5596. var subgrid = function (grid, row, column, comparator) {
  5597. var gridRow = getRow(grid, row);
  5598. var isColRow = gridRow.section === 'colgroup';
  5599. var colspan = findDiff(gridRow.cells.slice(column), comparator);
  5600. var rowspan = isColRow ? 1 : findDiff(getColumn(grid.slice(row), column), comparator);
  5601. return {
  5602. colspan: colspan,
  5603. rowspan: rowspan
  5604. };
  5605. };
  5606. var toDetails = function (grid, comparator) {
  5607. var seen = map$1(grid, function (row) {
  5608. return map$1(row.cells, never);
  5609. });
  5610. var updateSeen = function (rowIndex, columnIndex, rowspan, colspan) {
  5611. for (var row = rowIndex; row < rowIndex + rowspan; row++) {
  5612. for (var column = columnIndex; column < columnIndex + colspan; column++) {
  5613. seen[row][column] = true;
  5614. }
  5615. }
  5616. };
  5617. return map$1(grid, function (row, rowIndex) {
  5618. var details = bind$2(row.cells, function (cell, columnIndex) {
  5619. if (seen[rowIndex][columnIndex] === false) {
  5620. var result = subgrid(grid, rowIndex, columnIndex, comparator);
  5621. updateSeen(rowIndex, columnIndex, result.rowspan, result.colspan);
  5622. return [detailnew(cell.element, result.rowspan, result.colspan, cell.isNew)];
  5623. } else {
  5624. return [];
  5625. }
  5626. });
  5627. return rowdetailnew(row.element, details, row.section, row.isNew);
  5628. });
  5629. };
  5630. var toGrid = function (warehouse, generators, isNew) {
  5631. var grid = [];
  5632. each$2(warehouse.colgroups, function (colgroup) {
  5633. var colgroupCols = [];
  5634. for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
  5635. var element = Warehouse.getColumnAt(warehouse, columnIndex).map(function (column) {
  5636. return elementnew(column.element, isNew, false);
  5637. }).getOrThunk(function () {
  5638. return elementnew(generators.colGap(), true, false);
  5639. });
  5640. colgroupCols.push(element);
  5641. }
  5642. grid.push(rowcells(colgroup.element, colgroupCols, 'colgroup', isNew));
  5643. });
  5644. for (var rowIndex = 0; rowIndex < warehouse.grid.rows; rowIndex++) {
  5645. var rowCells = [];
  5646. for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
  5647. var element = Warehouse.getAt(warehouse, rowIndex, columnIndex).map(function (item) {
  5648. return elementnew(item.element, isNew, item.isLocked);
  5649. }).getOrThunk(function () {
  5650. return elementnew(generators.gap(), true, false);
  5651. });
  5652. rowCells.push(element);
  5653. }
  5654. var rowDetail = warehouse.all[rowIndex];
  5655. var row = rowcells(rowDetail.element, rowCells, rowDetail.section, isNew);
  5656. grid.push(row);
  5657. }
  5658. return grid;
  5659. };
  5660. var fromWarehouse = function (warehouse, generators) {
  5661. return toGrid(warehouse, generators, false);
  5662. };
  5663. var toDetailList = function (grid) {
  5664. return toDetails(grid, eq$1);
  5665. };
  5666. var findInWarehouse = function (warehouse, element) {
  5667. return findMap(warehouse.all, function (r) {
  5668. return find$1(r.cells, function (e) {
  5669. return eq$1(element, e.element);
  5670. });
  5671. });
  5672. };
  5673. var extractCells = function (warehouse, target, predicate) {
  5674. var details = map$1(target.selection, function (cell$1) {
  5675. return cell(cell$1).bind(function (lc) {
  5676. return findInWarehouse(warehouse, lc);
  5677. }).filter(predicate);
  5678. });
  5679. var cells = cat(details);
  5680. return someIf(cells.length > 0, cells);
  5681. };
  5682. var run = function (operation, extract, adjustment, postAction, genWrappers) {
  5683. return function (wire, table, target, generators, behaviours) {
  5684. var warehouse = Warehouse.fromTable(table);
  5685. var tableSection = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.section).getOrThunk(TableSection.fallback);
  5686. var output = extract(warehouse, target).map(function (info) {
  5687. var model = fromWarehouse(warehouse, generators);
  5688. var result = operation(model, info, eq$1, genWrappers(generators), tableSection);
  5689. var lockedColumns = getLockedColumnsFromGrid(result.grid);
  5690. var grid = toDetailList(result.grid);
  5691. return {
  5692. info: info,
  5693. grid: grid,
  5694. cursor: result.cursor,
  5695. lockedColumns: lockedColumns
  5696. };
  5697. });
  5698. return output.bind(function (out) {
  5699. var newElements = render$1(table, out.grid);
  5700. var tableSizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.sizing).getOrThunk(function () {
  5701. return TableSize.getTableSize(table);
  5702. });
  5703. var resizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.resize).getOrThunk(preserveTable);
  5704. adjustment(table, out.grid, out.info, {
  5705. sizing: tableSizing,
  5706. resize: resizing,
  5707. section: tableSection
  5708. });
  5709. postAction(table);
  5710. refresh(wire, table);
  5711. remove$7(table, LOCKED_COL_ATTR);
  5712. if (out.lockedColumns.length > 0) {
  5713. set$2(table, LOCKED_COL_ATTR, out.lockedColumns.join(','));
  5714. }
  5715. return Optional.some({
  5716. cursor: out.cursor,
  5717. newRows: newElements.newRows,
  5718. newCells: newElements.newCells
  5719. });
  5720. });
  5721. };
  5722. };
  5723. var onPaste = function (warehouse, target) {
  5724. return cell(target.element).bind(function (cell) {
  5725. return findInWarehouse(warehouse, cell).map(function (details) {
  5726. var value = __assign(__assign({}, details), {
  5727. generators: target.generators,
  5728. clipboard: target.clipboard
  5729. });
  5730. return value;
  5731. });
  5732. });
  5733. };
  5734. var onPasteByEditor = function (warehouse, target) {
  5735. return extractCells(warehouse, target, always).map(function (cells) {
  5736. return {
  5737. cells: cells,
  5738. generators: target.generators,
  5739. clipboard: target.clipboard
  5740. };
  5741. });
  5742. };
  5743. var onMergable = function (_warehouse, target) {
  5744. return target.mergable;
  5745. };
  5746. var onUnmergable = function (_warehouse, target) {
  5747. return target.unmergable;
  5748. };
  5749. var onCells = function (warehouse, target) {
  5750. return extractCells(warehouse, target, always);
  5751. };
  5752. var onUnlockedCells = function (warehouse, target) {
  5753. return extractCells(warehouse, target, function (detail) {
  5754. return !detail.isLocked;
  5755. });
  5756. };
  5757. var isUnlockedTableCell = function (warehouse, cell) {
  5758. return findInWarehouse(warehouse, cell).exists(function (detail) {
  5759. return !detail.isLocked;
  5760. });
  5761. };
  5762. var allUnlocked = function (warehouse, cells) {
  5763. return forall(cells, function (cell) {
  5764. return isUnlockedTableCell(warehouse, cell);
  5765. });
  5766. };
  5767. var onUnlockedMergable = function (warehouse, target) {
  5768. return onMergable(warehouse, target).filter(function (mergeable) {
  5769. return allUnlocked(warehouse, mergeable.cells);
  5770. });
  5771. };
  5772. var onUnlockedUnmergable = function (warehouse, target) {
  5773. return onUnmergable(warehouse, target).filter(function (cells) {
  5774. return allUnlocked(warehouse, cells);
  5775. });
  5776. };
  5777. var merge$2 = function (grid, bounds, comparator, substitution) {
  5778. var rows = extractGridDetails(grid).rows;
  5779. if (rows.length === 0) {
  5780. return grid;
  5781. }
  5782. for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
  5783. for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
  5784. var row = rows[i];
  5785. var isLocked = getCell(row, j).isLocked;
  5786. mutateCell(row, j, elementnew(substitution(), false, isLocked));
  5787. }
  5788. }
  5789. return grid;
  5790. };
  5791. var unmerge = function (grid, target, comparator, substitution) {
  5792. var rows = extractGridDetails(grid).rows;
  5793. var first = true;
  5794. for (var i = 0; i < rows.length; i++) {
  5795. for (var j = 0; j < cellLength(rows[0]); j++) {
  5796. var row = rows[i];
  5797. var currentCell = getCell(row, j);
  5798. var currentCellElm = currentCell.element;
  5799. var isToReplace = comparator(currentCellElm, target);
  5800. if (isToReplace === true && first === false) {
  5801. mutateCell(row, j, elementnew(substitution(), true, currentCell.isLocked));
  5802. } else if (isToReplace === true) {
  5803. first = false;
  5804. }
  5805. }
  5806. }
  5807. return grid;
  5808. };
  5809. var uniqueCells = function (row, comparator) {
  5810. return foldl(row, function (rest, cell) {
  5811. return exists(rest, function (currentCell) {
  5812. return comparator(currentCell.element, cell.element);
  5813. }) ? rest : rest.concat([cell]);
  5814. }, []);
  5815. };
  5816. var splitCols = function (grid, index, comparator, substitution) {
  5817. if (index > 0 && index < grid[0].cells.length) {
  5818. each$2(grid, function (row) {
  5819. var prevCell = row.cells[index - 1];
  5820. var current = row.cells[index];
  5821. var isToReplace = comparator(current.element, prevCell.element);
  5822. if (isToReplace) {
  5823. mutateCell(row, index, elementnew(substitution(), true, current.isLocked));
  5824. }
  5825. });
  5826. }
  5827. return grid;
  5828. };
  5829. var splitRows = function (grid, index, comparator, substitution) {
  5830. var rows = extractGridDetails(grid).rows;
  5831. if (index > 0 && index < rows.length) {
  5832. var rowPrevCells = rows[index - 1].cells;
  5833. var cells = uniqueCells(rowPrevCells, comparator);
  5834. each$2(cells, function (cell) {
  5835. var replacement = Optional.none();
  5836. for (var i = index; i < rows.length; i++) {
  5837. var _loop_1 = function (j) {
  5838. var row = rows[i];
  5839. var current = getCell(row, j);
  5840. var isToReplace = comparator(current.element, cell.element);
  5841. if (isToReplace) {
  5842. if (replacement.isNone()) {
  5843. replacement = Optional.some(substitution());
  5844. }
  5845. replacement.each(function (sub) {
  5846. mutateCell(row, j, elementnew(sub, true, current.isLocked));
  5847. });
  5848. }
  5849. };
  5850. for (var j = 0; j < cellLength(rows[0]); j++) {
  5851. _loop_1(j);
  5852. }
  5853. }
  5854. });
  5855. }
  5856. return grid;
  5857. };
  5858. var value$1 = function (o) {
  5859. var or = function (_opt) {
  5860. return value$1(o);
  5861. };
  5862. var orThunk = function (_f) {
  5863. return value$1(o);
  5864. };
  5865. var map = function (f) {
  5866. return value$1(f(o));
  5867. };
  5868. var mapError = function (_f) {
  5869. return value$1(o);
  5870. };
  5871. var each = function (f) {
  5872. f(o);
  5873. };
  5874. var bind = function (f) {
  5875. return f(o);
  5876. };
  5877. var fold = function (_, onValue) {
  5878. return onValue(o);
  5879. };
  5880. var exists = function (f) {
  5881. return f(o);
  5882. };
  5883. var forall = function (f) {
  5884. return f(o);
  5885. };
  5886. var toOptional = function () {
  5887. return Optional.some(o);
  5888. };
  5889. return {
  5890. isValue: always,
  5891. isError: never,
  5892. getOr: constant(o),
  5893. getOrThunk: constant(o),
  5894. getOrDie: constant(o),
  5895. or: or,
  5896. orThunk: orThunk,
  5897. fold: fold,
  5898. map: map,
  5899. mapError: mapError,
  5900. each: each,
  5901. bind: bind,
  5902. exists: exists,
  5903. forall: forall,
  5904. toOptional: toOptional
  5905. };
  5906. };
  5907. var error = function (message) {
  5908. var getOrThunk = function (f) {
  5909. return f();
  5910. };
  5911. var getOrDie = function () {
  5912. return die(String(message))();
  5913. };
  5914. var or = identity;
  5915. var orThunk = function (f) {
  5916. return f();
  5917. };
  5918. var map = function (_f) {
  5919. return error(message);
  5920. };
  5921. var mapError = function (f) {
  5922. return error(f(message));
  5923. };
  5924. var bind = function (_f) {
  5925. return error(message);
  5926. };
  5927. var fold = function (onError, _) {
  5928. return onError(message);
  5929. };
  5930. return {
  5931. isValue: never,
  5932. isError: always,
  5933. getOr: identity,
  5934. getOrThunk: getOrThunk,
  5935. getOrDie: getOrDie,
  5936. or: or,
  5937. orThunk: orThunk,
  5938. fold: fold,
  5939. map: map,
  5940. mapError: mapError,
  5941. each: noop,
  5942. bind: bind,
  5943. exists: never,
  5944. forall: always,
  5945. toOptional: Optional.none
  5946. };
  5947. };
  5948. var fromOption = function (opt, err) {
  5949. return opt.fold(function () {
  5950. return error(err);
  5951. }, value$1);
  5952. };
  5953. var Result = {
  5954. value: value$1,
  5955. error: error,
  5956. fromOption: fromOption
  5957. };
  5958. var measure = function (startAddress, gridA, gridB) {
  5959. if (startAddress.row >= gridA.length || startAddress.column > cellLength(gridA[0])) {
  5960. return Result.error('invalid start address out of table bounds, row: ' + startAddress.row + ', column: ' + startAddress.column);
  5961. }
  5962. var rowRemainder = gridA.slice(startAddress.row);
  5963. var colRemainder = rowRemainder[0].cells.slice(startAddress.column);
  5964. var colRequired = cellLength(gridB[0]);
  5965. var rowRequired = gridB.length;
  5966. return Result.value({
  5967. rowDelta: rowRemainder.length - rowRequired,
  5968. colDelta: colRemainder.length - colRequired
  5969. });
  5970. };
  5971. var measureWidth = function (gridA, gridB) {
  5972. var colLengthA = cellLength(gridA[0]);
  5973. var colLengthB = cellLength(gridB[0]);
  5974. return {
  5975. rowDelta: 0,
  5976. colDelta: colLengthA - colLengthB
  5977. };
  5978. };
  5979. var measureHeight = function (gridA, gridB) {
  5980. var rowLengthA = gridA.length;
  5981. var rowLengthB = gridB.length;
  5982. return {
  5983. rowDelta: rowLengthA - rowLengthB,
  5984. colDelta: 0
  5985. };
  5986. };
  5987. var generateElements = function (amount, row, generators, isLocked) {
  5988. var generator = row.section === 'colgroup' ? generators.col : generators.cell;
  5989. return range$1(amount, function (idx) {
  5990. return elementnew(generator(), true, isLocked(idx));
  5991. });
  5992. };
  5993. var rowFill = function (grid, amount, generators, lockedColumns) {
  5994. var exampleRow = grid[grid.length - 1];
  5995. return grid.concat(range$1(amount, function () {
  5996. var generator = exampleRow.section === 'colgroup' ? generators.colgroup : generators.row;
  5997. var row = clone$1(exampleRow, generator, identity);
  5998. var elements = generateElements(row.cells.length, row, generators, function (idx) {
  5999. return has$1(lockedColumns, idx.toString());
  6000. });
  6001. return setCells(row, elements);
  6002. }));
  6003. };
  6004. var colFill = function (grid, amount, generators, startIndex) {
  6005. return map$1(grid, function (row) {
  6006. var newChildren = generateElements(amount, row, generators, never);
  6007. return addCells(row, startIndex, newChildren);
  6008. });
  6009. };
  6010. var lockedColFill = function (grid, generators, lockedColumns) {
  6011. return map$1(grid, function (row) {
  6012. return foldl(lockedColumns, function (acc, colNum) {
  6013. var newChild = generateElements(1, row, generators, always)[0];
  6014. return addCell(acc, colNum, newChild);
  6015. }, row);
  6016. });
  6017. };
  6018. var tailor = function (gridA, delta, generators) {
  6019. var fillCols = delta.colDelta < 0 ? colFill : identity;
  6020. var fillRows = delta.rowDelta < 0 ? rowFill : identity;
  6021. var lockedColumns = getLockedColumnsFromGrid(gridA);
  6022. var gridWidth = cellLength(gridA[0]);
  6023. var isLastColLocked = exists(lockedColumns, function (locked) {
  6024. return locked === gridWidth - 1;
  6025. });
  6026. var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta), generators, isLastColLocked ? gridWidth - 1 : gridWidth);
  6027. var newLockedColumns = getLockedColumnsFromGrid(modifiedCols);
  6028. return fillRows(modifiedCols, Math.abs(delta.rowDelta), generators, mapToObject(newLockedColumns, always));
  6029. };
  6030. var isSpanning = function (grid, row, col, comparator) {
  6031. var candidate = getCell(grid[row], col);
  6032. var matching = curry(comparator, candidate.element);
  6033. var currentRow = grid[row];
  6034. 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)));
  6035. };
  6036. var mergeTables = function (startAddress, gridA, gridB, generator, comparator, lockedColumns) {
  6037. var startRow = startAddress.row;
  6038. var startCol = startAddress.column;
  6039. var mergeHeight = gridB.length;
  6040. var mergeWidth = cellLength(gridB[0]);
  6041. var endRow = startRow + mergeHeight;
  6042. var endCol = startCol + mergeWidth + lockedColumns.length;
  6043. var lockedColumnObj = mapToObject(lockedColumns, always);
  6044. for (var r = startRow; r < endRow; r++) {
  6045. var skippedCol = 0;
  6046. for (var c = startCol; c < endCol; c++) {
  6047. if (lockedColumnObj[c]) {
  6048. skippedCol++;
  6049. continue;
  6050. }
  6051. if (isSpanning(gridA, r, c, comparator)) {
  6052. unmerge(gridA, getCellElement(gridA[r], c), comparator, generator.cell);
  6053. }
  6054. var gridBColIndex = c - startCol - skippedCol;
  6055. var newCell = getCell(gridB[r - startRow], gridBColIndex);
  6056. var newCellElm = newCell.element;
  6057. var replacement = generator.replace(newCellElm);
  6058. mutateCell(gridA[r], c, elementnew(replacement, true, newCell.isLocked));
  6059. }
  6060. }
  6061. return gridA;
  6062. };
  6063. var getValidStartAddress = function (currentStartAddress, grid, lockedColumns) {
  6064. var gridColLength = cellLength(grid[0]);
  6065. var adjustedRowAddress = extractGridDetails(grid).cols.length + currentStartAddress.row;
  6066. var possibleColAddresses = range$1(gridColLength - currentStartAddress.column, function (num) {
  6067. return num + currentStartAddress.column;
  6068. });
  6069. var validColAddress = find$1(possibleColAddresses, function (num) {
  6070. return forall(lockedColumns, function (col) {
  6071. return col !== num;
  6072. });
  6073. }).getOr(gridColLength - 1);
  6074. return {
  6075. row: adjustedRowAddress,
  6076. column: validColAddress
  6077. };
  6078. };
  6079. var getLockedColumnsWithinBounds = function (startAddress, grid, lockedColumns) {
  6080. return filter$2(lockedColumns, function (colNum) {
  6081. return colNum >= startAddress.column && colNum <= cellLength(grid[0]) + startAddress.column;
  6082. });
  6083. };
  6084. var merge$1 = function (startAddress, gridA, gridB, generator, comparator) {
  6085. var lockedColumns = getLockedColumnsFromGrid(gridA);
  6086. var validStartAddress = getValidStartAddress(startAddress, gridA, lockedColumns);
  6087. var gridBRows = extractGridDetails(gridB).rows;
  6088. var lockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, lockedColumns);
  6089. var result = measure(validStartAddress, gridA, gridBRows);
  6090. return result.map(function (diff) {
  6091. var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - lockedColumnsWithinBounds.length });
  6092. var fittedGrid = tailor(gridA, delta, generator);
  6093. var newLockedColumns = getLockedColumnsFromGrid(fittedGrid);
  6094. var newLockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, newLockedColumns);
  6095. return mergeTables(validStartAddress, fittedGrid, gridBRows, generator, comparator, newLockedColumnsWithinBounds);
  6096. });
  6097. };
  6098. var insertCols = function (index, gridA, gridB, generator, comparator) {
  6099. splitCols(gridA, index, comparator, generator.cell);
  6100. var delta = measureHeight(gridB, gridA);
  6101. var fittedNewGrid = tailor(gridB, delta, generator);
  6102. var secondDelta = measureHeight(gridA, fittedNewGrid);
  6103. var fittedOldGrid = tailor(gridA, secondDelta, generator);
  6104. return map$1(fittedOldGrid, function (gridRow, i) {
  6105. return addCells(gridRow, index, fittedNewGrid[i].cells);
  6106. });
  6107. };
  6108. var insertRows = function (index, gridA, gridB, generator, comparator) {
  6109. splitRows(gridA, index, comparator, generator.cell);
  6110. var locked = getLockedColumnsFromGrid(gridA);
  6111. var diff = measureWidth(gridA, gridB);
  6112. var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - locked.length });
  6113. var fittedOldGrid = tailor(gridA, delta, generator);
  6114. var _a = extractGridDetails(fittedOldGrid), oldCols = _a.cols, oldRows = _a.rows;
  6115. var newLocked = getLockedColumnsFromGrid(fittedOldGrid);
  6116. var secondDiff = measureWidth(gridB, gridA);
  6117. var secondDelta = __assign(__assign({}, secondDiff), { colDelta: secondDiff.colDelta + newLocked.length });
  6118. var fittedGridB = lockedColFill(gridB, generator, newLocked);
  6119. var fittedNewGrid = tailor(fittedGridB, secondDelta, generator);
  6120. return oldCols.concat(oldRows.slice(0, index)).concat(fittedNewGrid).concat(oldRows.slice(index, oldRows.length));
  6121. };
  6122. var cloneRow = function (row, cloneCell, comparator, substitution) {
  6123. return clone$1(row, function (elem) {
  6124. return substitution(elem, comparator);
  6125. }, cloneCell);
  6126. };
  6127. var insertRowAt = function (grid, index, example, comparator, substitution) {
  6128. var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
  6129. var before = rows.slice(0, index);
  6130. var after = rows.slice(index);
  6131. var newRow = cloneRow(rows[example], function (ex, c) {
  6132. var withinSpan = index > 0 && index < rows.length && comparator(getCellElement(rows[index - 1], c), getCellElement(rows[index], c));
  6133. var ret = withinSpan ? getCell(rows[index], c) : elementnew(substitution(ex.element, comparator), true, ex.isLocked);
  6134. return ret;
  6135. }, comparator, substitution);
  6136. return cols.concat(before).concat([newRow]).concat(after);
  6137. };
  6138. var getElementFor = function (row, column, section, withinSpan, example, comparator, substitution) {
  6139. if (section === 'colgroup' || !withinSpan) {
  6140. var cell = getCell(row, example);
  6141. return elementnew(substitution(cell.element, comparator), true, false);
  6142. } else {
  6143. return getCell(row, column);
  6144. }
  6145. };
  6146. var insertColumnAt = function (grid, index, example, comparator, substitution) {
  6147. return map$1(grid, function (row) {
  6148. var withinSpan = index > 0 && index < cellLength(row) && comparator(getCellElement(row, index - 1), getCellElement(row, index));
  6149. var sub = getElementFor(row, index, row.section, withinSpan, example, comparator, substitution);
  6150. return addCell(row, index, sub);
  6151. });
  6152. };
  6153. var deleteColumnsAt = function (grid, columns) {
  6154. return bind$2(grid, function (row) {
  6155. var existingCells = row.cells;
  6156. var cells = foldr(columns, function (acc, column) {
  6157. return column >= 0 && column < acc.length ? acc.slice(0, column).concat(acc.slice(column + 1)) : acc;
  6158. }, existingCells);
  6159. return cells.length > 0 ? [rowcells(row.element, cells, row.section, row.isNew)] : [];
  6160. });
  6161. };
  6162. var deleteRowsAt = function (grid, start, finish) {
  6163. var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
  6164. return cols.concat(rows.slice(0, start)).concat(rows.slice(finish + 1));
  6165. };
  6166. var notInStartRow = function (grid, rowIndex, colIndex, comparator) {
  6167. return getCellElement(grid[rowIndex], colIndex) !== undefined && (rowIndex > 0 && comparator(getCellElement(grid[rowIndex - 1], colIndex), getCellElement(grid[rowIndex], colIndex)));
  6168. };
  6169. var notInStartColumn = function (row, index, comparator) {
  6170. return index > 0 && comparator(getCellElement(row, index - 1), getCellElement(row, index));
  6171. };
  6172. var isDuplicatedCell = function (grid, rowIndex, colIndex, comparator) {
  6173. return notInStartRow(grid, rowIndex, colIndex, comparator) || notInStartColumn(grid[rowIndex], colIndex, comparator);
  6174. };
  6175. var rowReplacerPredicate = function (targetRow, columnHeaders) {
  6176. var entireTableIsHeader = forall(columnHeaders, identity) && isHeaderCells(targetRow.cells);
  6177. return entireTableIsHeader ? always : function (cell, _rowIndex, colIndex) {
  6178. var type = name(cell.element);
  6179. return !(type === 'th' && columnHeaders[colIndex]);
  6180. };
  6181. };
  6182. var columnReplacePredicate = function (targetColumn, rowHeaders) {
  6183. var entireTableIsHeader = forall(rowHeaders, identity) && isHeaderCells(targetColumn);
  6184. return entireTableIsHeader ? always : function (cell, rowIndex, _colIndex) {
  6185. var type = name(cell.element);
  6186. return !(type === 'th' && rowHeaders[rowIndex]);
  6187. };
  6188. };
  6189. var determineScope = function (applyScope, element, newScope, isInHeader) {
  6190. var hasSpan = function (scope) {
  6191. return scope === 'row' ? hasRowspan(element) : hasColspan(element);
  6192. };
  6193. var getScope = function (scope) {
  6194. return hasSpan(scope) ? scope + 'group' : scope;
  6195. };
  6196. if (applyScope) {
  6197. return isHeaderCell(element) ? getScope(newScope) : null;
  6198. } else if (isInHeader && isHeaderCell(element)) {
  6199. var oppositeScope = newScope === 'row' ? 'col' : 'row';
  6200. return getScope(oppositeScope);
  6201. } else {
  6202. return null;
  6203. }
  6204. };
  6205. var rowScopeGenerator = function (applyScope, columnHeaders) {
  6206. return function (cell, rowIndex, columnIndex) {
  6207. return Optional.some(determineScope(applyScope, cell.element, 'col', columnHeaders[columnIndex]));
  6208. };
  6209. };
  6210. var columnScopeGenerator = function (applyScope, rowHeaders) {
  6211. return function (cell, rowIndex) {
  6212. return Optional.some(determineScope(applyScope, cell.element, 'row', rowHeaders[rowIndex]));
  6213. };
  6214. };
  6215. var replace = function (cell, comparator, substitute) {
  6216. return elementnew(substitute(cell.element, comparator), true, cell.isLocked);
  6217. };
  6218. var replaceIn = function (grid, targets, comparator, substitute, replacer, genScope, shouldReplace) {
  6219. var isTarget = function (cell) {
  6220. return exists(targets, function (target) {
  6221. return comparator(cell.element, target.element);
  6222. });
  6223. };
  6224. return map$1(grid, function (row, rowIndex) {
  6225. return mapCells(row, function (cell, colIndex) {
  6226. if (isTarget(cell)) {
  6227. var newCell_1 = shouldReplace(cell, rowIndex, colIndex) ? replacer(cell, comparator, substitute) : cell;
  6228. genScope(newCell_1, rowIndex, colIndex).each(function (scope) {
  6229. setOptions(newCell_1.element, { scope: Optional.from(scope) });
  6230. });
  6231. return newCell_1;
  6232. } else {
  6233. return cell;
  6234. }
  6235. });
  6236. });
  6237. };
  6238. var getColumnCells = function (rows, columnIndex, comparator) {
  6239. return bind$2(rows, function (row, i) {
  6240. return isDuplicatedCell(rows, i, columnIndex, comparator) ? [] : [getCell(row, columnIndex)];
  6241. });
  6242. };
  6243. var getRowCells = function (rows, rowIndex, comparator) {
  6244. var targetRow = rows[rowIndex];
  6245. return bind$2(targetRow.cells, function (item, i) {
  6246. return isDuplicatedCell(rows, rowIndex, i, comparator) ? [] : [item];
  6247. });
  6248. };
  6249. var replaceColumns = function (grid, indexes, applyScope, comparator, substitution) {
  6250. var rows = extractGridDetails(grid).rows;
  6251. var targets = bind$2(indexes, function (index) {
  6252. return getColumnCells(rows, index, comparator);
  6253. });
  6254. var rowHeaders = map$1(grid, function (row) {
  6255. return isHeaderCells(row.cells);
  6256. });
  6257. var shouldReplaceCell = columnReplacePredicate(targets, rowHeaders);
  6258. var scopeGenerator = columnScopeGenerator(applyScope, rowHeaders);
  6259. return replaceIn(grid, targets, comparator, substitution, replace, scopeGenerator, shouldReplaceCell);
  6260. };
  6261. var replaceRows = function (grid, indexes, section, applyScope, comparator, substitution, tableSection) {
  6262. var _a = extractGridDetails(grid), cols = _a.cols, rows = _a.rows;
  6263. var targetRow = rows[indexes[0]];
  6264. var targets = bind$2(indexes, function (index) {
  6265. return getRowCells(rows, index, comparator);
  6266. });
  6267. var columnHeaders = map$1(targetRow.cells, function (_cell, index) {
  6268. return isHeaderCells(getColumnCells(rows, index, comparator));
  6269. });
  6270. var newRows = __spreadArray([], rows, true);
  6271. each$2(indexes, function (index) {
  6272. newRows[index] = tableSection.transformRow(rows[index], section);
  6273. });
  6274. var newGrid = cols.concat(newRows);
  6275. var shouldReplaceCell = rowReplacerPredicate(targetRow, columnHeaders);
  6276. var scopeGenerator = rowScopeGenerator(applyScope, columnHeaders);
  6277. return replaceIn(newGrid, targets, comparator, substitution, tableSection.transformCell, scopeGenerator, shouldReplaceCell);
  6278. };
  6279. var replaceCells = function (grid, details, comparator, substitution) {
  6280. var rows = extractGridDetails(grid).rows;
  6281. var targetCells = map$1(details, function (detail) {
  6282. return getCell(rows[detail.row], detail.column);
  6283. });
  6284. return replaceIn(grid, targetCells, comparator, substitution, replace, Optional.none, always);
  6285. };
  6286. var uniqueColumns = function (details) {
  6287. var uniqueCheck = function (rest, detail) {
  6288. var columnExists = exists(rest, function (currentDetail) {
  6289. return currentDetail.column === detail.column;
  6290. });
  6291. return columnExists ? rest : rest.concat([detail]);
  6292. };
  6293. return foldl(details, uniqueCheck, []).sort(function (detailA, detailB) {
  6294. return detailA.column - detailB.column;
  6295. });
  6296. };
  6297. var isCol = isTag('col');
  6298. var isColgroup = isTag('colgroup');
  6299. var isRow$1 = function (element) {
  6300. return name(element) === 'tr' || isColgroup(element);
  6301. };
  6302. var elementToData = function (element) {
  6303. var colspan = getAttrValue(element, 'colspan', 1);
  6304. var rowspan = getAttrValue(element, 'rowspan', 1);
  6305. return {
  6306. element: element,
  6307. colspan: colspan,
  6308. rowspan: rowspan
  6309. };
  6310. };
  6311. var modification = function (generators, toData) {
  6312. if (toData === void 0) {
  6313. toData = elementToData;
  6314. }
  6315. var nuCell = function (data) {
  6316. return isCol(data.element) ? generators.col(data) : generators.cell(data);
  6317. };
  6318. var nuRow = function (data) {
  6319. return isColgroup(data.element) ? generators.colgroup(data) : generators.row(data);
  6320. };
  6321. var add = function (element) {
  6322. if (isRow$1(element)) {
  6323. return nuRow({ element: element });
  6324. } else {
  6325. var replacement = nuCell(toData(element));
  6326. recent = Optional.some({
  6327. item: element,
  6328. replacement: replacement
  6329. });
  6330. return replacement;
  6331. }
  6332. };
  6333. var recent = Optional.none();
  6334. var getOrInit = function (element, comparator) {
  6335. return recent.fold(function () {
  6336. return add(element);
  6337. }, function (p) {
  6338. return comparator(element, p.item) ? p.replacement : add(element);
  6339. });
  6340. };
  6341. return { getOrInit: getOrInit };
  6342. };
  6343. var transform = function (tag) {
  6344. return function (generators) {
  6345. var list = [];
  6346. var find = function (element, comparator) {
  6347. return find$1(list, function (x) {
  6348. return comparator(x.item, element);
  6349. });
  6350. };
  6351. var makeNew = function (element) {
  6352. var attrs = tag === 'td' ? { scope: null } : {};
  6353. var cell = generators.replace(element, tag, attrs);
  6354. list.push({
  6355. item: element,
  6356. sub: cell
  6357. });
  6358. return cell;
  6359. };
  6360. var replaceOrInit = function (element, comparator) {
  6361. if (isRow$1(element) || isCol(element)) {
  6362. return element;
  6363. } else {
  6364. return find(element, comparator).fold(function () {
  6365. return makeNew(element);
  6366. }, function (p) {
  6367. return comparator(element, p.item) ? p.sub : makeNew(element);
  6368. });
  6369. }
  6370. };
  6371. return { replaceOrInit: replaceOrInit };
  6372. };
  6373. };
  6374. var getScopeAttribute = function (cell) {
  6375. return getOpt(cell, 'scope').map(function (attribute) {
  6376. return attribute.substr(0, 3);
  6377. });
  6378. };
  6379. var merging = function (generators) {
  6380. var unmerge = function (cell) {
  6381. var scope = getScopeAttribute(cell);
  6382. scope.each(function (attribute) {
  6383. return set$2(cell, 'scope', attribute);
  6384. });
  6385. return function () {
  6386. var raw = generators.cell({
  6387. element: cell,
  6388. colspan: 1,
  6389. rowspan: 1
  6390. });
  6391. remove$6(raw, 'width');
  6392. remove$6(cell, 'width');
  6393. scope.each(function (attribute) {
  6394. return set$2(raw, 'scope', attribute);
  6395. });
  6396. return raw;
  6397. };
  6398. };
  6399. var merge = function (cells) {
  6400. var getScopeProperty = function () {
  6401. var stringAttributes = cat(map$1(cells, getScopeAttribute));
  6402. if (stringAttributes.length === 0) {
  6403. return Optional.none();
  6404. } else {
  6405. var baseScope_1 = stringAttributes[0];
  6406. var scopes_1 = [
  6407. 'row',
  6408. 'col'
  6409. ];
  6410. var isMixed = exists(stringAttributes, function (attribute) {
  6411. return attribute !== baseScope_1 && contains$2(scopes_1, attribute);
  6412. });
  6413. return isMixed ? Optional.none() : Optional.from(baseScope_1);
  6414. }
  6415. };
  6416. remove$6(cells[0], 'width');
  6417. getScopeProperty().fold(function () {
  6418. return remove$7(cells[0], 'scope');
  6419. }, function (attribute) {
  6420. return set$2(cells[0], 'scope', attribute + 'group');
  6421. });
  6422. return constant(cells[0]);
  6423. };
  6424. return {
  6425. unmerge: unmerge,
  6426. merge: merge
  6427. };
  6428. };
  6429. var Generators = {
  6430. modification: modification,
  6431. transform: transform,
  6432. merging: merging
  6433. };
  6434. var blockList = [
  6435. 'body',
  6436. 'p',
  6437. 'div',
  6438. 'article',
  6439. 'aside',
  6440. 'figcaption',
  6441. 'figure',
  6442. 'footer',
  6443. 'header',
  6444. 'nav',
  6445. 'section',
  6446. 'ol',
  6447. 'ul',
  6448. 'table',
  6449. 'thead',
  6450. 'tfoot',
  6451. 'tbody',
  6452. 'caption',
  6453. 'tr',
  6454. 'td',
  6455. 'th',
  6456. 'h1',
  6457. 'h2',
  6458. 'h3',
  6459. 'h4',
  6460. 'h5',
  6461. 'h6',
  6462. 'blockquote',
  6463. 'pre',
  6464. 'address'
  6465. ];
  6466. var isList$1 = function (universe, item) {
  6467. var tagName = universe.property().name(item);
  6468. return contains$2([
  6469. 'ol',
  6470. 'ul'
  6471. ], tagName);
  6472. };
  6473. var isBlock$1 = function (universe, item) {
  6474. var tagName = universe.property().name(item);
  6475. return contains$2(blockList, tagName);
  6476. };
  6477. var isEmptyTag$1 = function (universe, item) {
  6478. return contains$2([
  6479. 'br',
  6480. 'img',
  6481. 'hr',
  6482. 'input'
  6483. ], universe.property().name(item));
  6484. };
  6485. var universe$1 = DomUniverse();
  6486. var isBlock = function (element) {
  6487. return isBlock$1(universe$1, element);
  6488. };
  6489. var isList = function (element) {
  6490. return isList$1(universe$1, element);
  6491. };
  6492. var isEmptyTag = function (element) {
  6493. return isEmptyTag$1(universe$1, element);
  6494. };
  6495. var merge = function (cells) {
  6496. var isBr = function (el) {
  6497. return name(el) === 'br';
  6498. };
  6499. var advancedBr = function (children) {
  6500. return forall(children, function (c) {
  6501. return isBr(c) || isText(c) && get$9(c).trim().length === 0;
  6502. });
  6503. };
  6504. var isListItem = function (el) {
  6505. return name(el) === 'li' || ancestor$2(el, isList).isSome();
  6506. };
  6507. var siblingIsBlock = function (el) {
  6508. return nextSibling(el).map(function (rightSibling) {
  6509. if (isBlock(rightSibling)) {
  6510. return true;
  6511. }
  6512. if (isEmptyTag(rightSibling)) {
  6513. return name(rightSibling) === 'img' ? false : true;
  6514. }
  6515. return false;
  6516. }).getOr(false);
  6517. };
  6518. var markCell = function (cell) {
  6519. return last$1(cell).bind(function (rightEdge) {
  6520. var rightSiblingIsBlock = siblingIsBlock(rightEdge);
  6521. return parent(rightEdge).map(function (parent) {
  6522. return rightSiblingIsBlock === true || isListItem(parent) || isBr(rightEdge) || isBlock(parent) && !eq$1(cell, parent) ? [] : [SugarElement.fromTag('br')];
  6523. });
  6524. }).getOr([]);
  6525. };
  6526. var markContent = function () {
  6527. var content = bind$2(cells, function (cell) {
  6528. var children = children$3(cell);
  6529. return advancedBr(children) ? [] : children.concat(markCell(cell));
  6530. });
  6531. return content.length === 0 ? [SugarElement.fromTag('br')] : content;
  6532. };
  6533. var contents = markContent();
  6534. empty(cells[0]);
  6535. append(cells[0], contents);
  6536. };
  6537. var isEditable = function (elem) {
  6538. return isEditable$1(elem, true);
  6539. };
  6540. var prune = function (table) {
  6541. var cells = cells$1(table);
  6542. if (cells.length === 0) {
  6543. remove$5(table);
  6544. }
  6545. };
  6546. var outcome = function (grid, cursor) {
  6547. return {
  6548. grid: grid,
  6549. cursor: cursor
  6550. };
  6551. };
  6552. var findEditableCursorPosition = function (rows) {
  6553. return findMap(rows, function (row) {
  6554. return findMap(row.cells, function (cell) {
  6555. var elem = cell.element;
  6556. return someIf(isEditable(elem), elem);
  6557. });
  6558. });
  6559. };
  6560. var elementFromGrid = function (grid, row, column) {
  6561. var _a, _b;
  6562. var rows = extractGridDetails(grid).rows;
  6563. 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 () {
  6564. return findEditableCursorPosition(rows);
  6565. });
  6566. };
  6567. var bundle = function (grid, row, column) {
  6568. var cursorElement = elementFromGrid(grid, row, column);
  6569. return outcome(grid, cursorElement);
  6570. };
  6571. var uniqueRows = function (details) {
  6572. var rowCompilation = function (rest, detail) {
  6573. var rowExists = exists(rest, function (currentDetail) {
  6574. return currentDetail.row === detail.row;
  6575. });
  6576. return rowExists ? rest : rest.concat([detail]);
  6577. };
  6578. return foldl(details, rowCompilation, []).sort(function (detailA, detailB) {
  6579. return detailA.row - detailB.row;
  6580. });
  6581. };
  6582. var opInsertRowsBefore = function (grid, details, comparator, genWrappers) {
  6583. var targetIndex = details[0].row;
  6584. var rows = uniqueRows(details);
  6585. var newGrid = foldr(rows, function (acc, row) {
  6586. var newG = insertRowAt(acc.grid, targetIndex, row.row + acc.delta, comparator, genWrappers.getOrInit);
  6587. return {
  6588. grid: newG,
  6589. delta: acc.delta + 1
  6590. };
  6591. }, {
  6592. grid: grid,
  6593. delta: 0
  6594. }).grid;
  6595. return bundle(newGrid, targetIndex, details[0].column);
  6596. };
  6597. var opInsertRowsAfter = function (grid, details, comparator, genWrappers) {
  6598. var rows = uniqueRows(details);
  6599. var target = rows[rows.length - 1];
  6600. var targetIndex = target.row + target.rowspan;
  6601. var newGrid = foldr(rows, function (newG, row) {
  6602. return insertRowAt(newG, targetIndex, row.row, comparator, genWrappers.getOrInit);
  6603. }, grid);
  6604. return bundle(newGrid, targetIndex, details[0].column);
  6605. };
  6606. var opInsertColumnsBefore = function (grid, extractDetail, comparator, genWrappers) {
  6607. var details = extractDetail.details;
  6608. var columns = uniqueColumns(details);
  6609. var targetIndex = columns[0].column;
  6610. var newGrid = foldr(columns, function (acc, col) {
  6611. var newG = insertColumnAt(acc.grid, targetIndex, col.column + acc.delta, comparator, genWrappers.getOrInit);
  6612. return {
  6613. grid: newG,
  6614. delta: acc.delta + 1
  6615. };
  6616. }, {
  6617. grid: grid,
  6618. delta: 0
  6619. }).grid;
  6620. return bundle(newGrid, details[0].row, targetIndex);
  6621. };
  6622. var opInsertColumnsAfter = function (grid, extractDetail, comparator, genWrappers) {
  6623. var details = extractDetail.details;
  6624. var target = details[details.length - 1];
  6625. var targetIndex = target.column + target.colspan;
  6626. var columns = uniqueColumns(details);
  6627. var newGrid = foldr(columns, function (newG, col) {
  6628. return insertColumnAt(newG, targetIndex, col.column, comparator, genWrappers.getOrInit);
  6629. }, grid);
  6630. return bundle(newGrid, details[0].row, targetIndex);
  6631. };
  6632. var opMakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
  6633. var columns = uniqueColumns(details);
  6634. var columnIndexes = map$1(columns, function (detail) {
  6635. return detail.column;
  6636. });
  6637. var newGrid = replaceColumns(initialGrid, columnIndexes, true, comparator, genWrappers.replaceOrInit);
  6638. return bundle(newGrid, details[0].row, details[0].column);
  6639. };
  6640. var opMakeCellsHeader = function (initialGrid, details, comparator, genWrappers) {
  6641. var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
  6642. return bundle(newGrid, details[0].row, details[0].column);
  6643. };
  6644. var opUnmakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
  6645. var columns = uniqueColumns(details);
  6646. var columnIndexes = map$1(columns, function (detail) {
  6647. return detail.column;
  6648. });
  6649. var newGrid = replaceColumns(initialGrid, columnIndexes, false, comparator, genWrappers.replaceOrInit);
  6650. return bundle(newGrid, details[0].row, details[0].column);
  6651. };
  6652. var opUnmakeCellsHeader = function (initialGrid, details, comparator, genWrappers) {
  6653. var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
  6654. return bundle(newGrid, details[0].row, details[0].column);
  6655. };
  6656. var makeRowsSection = function (section, applyScope) {
  6657. return function (initialGrid, details, comparator, genWrappers, tableSection) {
  6658. var rows = uniqueRows(details);
  6659. var rowIndexes = map$1(rows, function (detail) {
  6660. return detail.row;
  6661. });
  6662. var newGrid = replaceRows(initialGrid, rowIndexes, section, applyScope, comparator, genWrappers.replaceOrInit, tableSection);
  6663. return bundle(newGrid, details[0].row, details[0].column);
  6664. };
  6665. };
  6666. var opMakeRowsHeader = makeRowsSection('thead', true);
  6667. var opMakeRowsBody = makeRowsSection('tbody', false);
  6668. var opMakeRowsFooter = makeRowsSection('tfoot', false);
  6669. var opEraseColumns = function (grid, extractDetail, _comparator, _genWrappers) {
  6670. var columns = uniqueColumns(extractDetail.details);
  6671. var newGrid = deleteColumnsAt(grid, map$1(columns, function (column) {
  6672. return column.column;
  6673. }));
  6674. var maxColIndex = newGrid.length > 0 ? newGrid[0].cells.length - 1 : 0;
  6675. return bundle(newGrid, columns[0].row, Math.min(columns[0].column, maxColIndex));
  6676. };
  6677. var opEraseRows = function (grid, details, _comparator, _genWrappers) {
  6678. var rows = uniqueRows(details);
  6679. var newGrid = deleteRowsAt(grid, rows[0].row, rows[rows.length - 1].row);
  6680. var maxRowIndex = newGrid.length > 0 ? newGrid.length - 1 : 0;
  6681. return bundle(newGrid, Math.min(details[0].row, maxRowIndex), details[0].column);
  6682. };
  6683. var opMergeCells = function (grid, mergable, comparator, genWrappers) {
  6684. var cells = mergable.cells;
  6685. merge(cells);
  6686. var newGrid = merge$2(grid, mergable.bounds, comparator, genWrappers.merge(cells));
  6687. return outcome(newGrid, Optional.from(cells[0]));
  6688. };
  6689. var opUnmergeCells = function (grid, unmergable, comparator, genWrappers) {
  6690. var unmerge$1 = function (b, cell) {
  6691. return unmerge(b, cell, comparator, genWrappers.unmerge(cell));
  6692. };
  6693. var newGrid = foldr(unmergable, unmerge$1, grid);
  6694. return outcome(newGrid, Optional.from(unmergable[0]));
  6695. };
  6696. var opPasteCells = function (grid, pasteDetails, comparator, _genWrappers) {
  6697. var gridify = function (table, generators) {
  6698. var wh = Warehouse.fromTable(table);
  6699. return toGrid(wh, generators, true);
  6700. };
  6701. var gridB = gridify(pasteDetails.clipboard, pasteDetails.generators);
  6702. var startAddress = address(pasteDetails.row, pasteDetails.column);
  6703. var mergedGrid = merge$1(startAddress, grid, gridB, pasteDetails.generators, comparator);
  6704. return mergedGrid.fold(function () {
  6705. return outcome(grid, Optional.some(pasteDetails.element));
  6706. }, function (newGrid) {
  6707. return bundle(newGrid, pasteDetails.row, pasteDetails.column);
  6708. });
  6709. };
  6710. var gridifyRows = function (rows, generators, context) {
  6711. var pasteDetails = fromPastedRows(rows, context.section);
  6712. var wh = Warehouse.generate(pasteDetails);
  6713. return toGrid(wh, generators, true);
  6714. };
  6715. var opPasteColsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  6716. var rows = extractGridDetails(grid).rows;
  6717. var index = pasteDetails.cells[0].column;
  6718. var context = rows[pasteDetails.cells[0].row];
  6719. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6720. var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
  6721. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6722. };
  6723. var opPasteColsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  6724. var rows = extractGridDetails(grid).rows;
  6725. var index = pasteDetails.cells[pasteDetails.cells.length - 1].column + pasteDetails.cells[pasteDetails.cells.length - 1].colspan;
  6726. var context = rows[pasteDetails.cells[0].row];
  6727. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6728. var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
  6729. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6730. };
  6731. var opPasteRowsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
  6732. var rows = extractGridDetails(grid).rows;
  6733. var index = pasteDetails.cells[0].row;
  6734. var context = rows[index];
  6735. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6736. var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
  6737. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6738. };
  6739. var opPasteRowsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
  6740. var rows = extractGridDetails(grid).rows;
  6741. var index = pasteDetails.cells[pasteDetails.cells.length - 1].row + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan;
  6742. var context = rows[pasteDetails.cells[0].row];
  6743. var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
  6744. var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
  6745. return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
  6746. };
  6747. var opGetColumnsType = function (table, target) {
  6748. var house = Warehouse.fromTable(table);
  6749. var details = onCells(house, target);
  6750. return details.bind(function (selectedCells) {
  6751. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  6752. var minColRange = selectedCells[0].column;
  6753. var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
  6754. var selectedColumnCells = flatten$1(map$1(house.all, function (row) {
  6755. return filter$2(row.cells, function (cell) {
  6756. return cell.column >= minColRange && cell.column < maxColRange;
  6757. });
  6758. }));
  6759. return findCommonCellType(selectedColumnCells);
  6760. }).getOr('');
  6761. };
  6762. var opGetCellsType = function (table, target) {
  6763. var house = Warehouse.fromTable(table);
  6764. var details = onCells(house, target);
  6765. return details.bind(findCommonCellType).getOr('');
  6766. };
  6767. var opGetRowsType = function (table, target) {
  6768. var house = Warehouse.fromTable(table);
  6769. var details = onCells(house, target);
  6770. return details.bind(function (selectedCells) {
  6771. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  6772. var minRowRange = selectedCells[0].row;
  6773. var maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
  6774. var selectedRows = house.all.slice(minRowRange, maxRowRange);
  6775. return findCommonRowType(selectedRows);
  6776. }).getOr('');
  6777. };
  6778. var resize = function (table, list, details, behaviours) {
  6779. return adjustWidthTo(table, list, details, behaviours.sizing);
  6780. };
  6781. var adjustAndRedistributeWidths = function (table, list, details, behaviours) {
  6782. return adjustAndRedistributeWidths$1(table, list, details, behaviours.sizing, behaviours.resize);
  6783. };
  6784. var firstColumnIsLocked = function (_warehouse, details) {
  6785. return exists(details, function (detail) {
  6786. return detail.column === 0 && detail.isLocked;
  6787. });
  6788. };
  6789. var lastColumnIsLocked = function (warehouse, details) {
  6790. return exists(details, function (detail) {
  6791. return detail.column + detail.colspan >= warehouse.grid.columns && detail.isLocked;
  6792. });
  6793. };
  6794. var getColumnsWidth = function (warehouse, details) {
  6795. var columns$1 = columns(warehouse);
  6796. var uniqueCols = uniqueColumns(details);
  6797. return foldl(uniqueCols, function (acc, detail) {
  6798. var column = columns$1[detail.column];
  6799. var colWidth = column.map(getOuter$2).getOr(0);
  6800. return acc + colWidth;
  6801. }, 0);
  6802. };
  6803. var insertColumnsExtractor = function (before) {
  6804. return function (warehouse, target) {
  6805. return onCells(warehouse, target).filter(function (details) {
  6806. var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
  6807. return !checkLocked(warehouse, details);
  6808. }).map(function (details) {
  6809. return {
  6810. details: details,
  6811. pixelDelta: getColumnsWidth(warehouse, details)
  6812. };
  6813. });
  6814. };
  6815. };
  6816. var eraseColumnsExtractor = function (warehouse, target) {
  6817. return onUnlockedCells(warehouse, target).map(function (details) {
  6818. return {
  6819. details: details,
  6820. pixelDelta: -getColumnsWidth(warehouse, details)
  6821. };
  6822. });
  6823. };
  6824. var pasteColumnsExtractor = function (before) {
  6825. return function (warehouse, target) {
  6826. return onPasteByEditor(warehouse, target).filter(function (details) {
  6827. var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
  6828. return !checkLocked(warehouse, details.cells);
  6829. });
  6830. };
  6831. };
  6832. var headerCellGenerator = Generators.transform('th');
  6833. var bodyCellGenerator = Generators.transform('td');
  6834. var insertRowsBefore = run(opInsertRowsBefore, onCells, noop, noop, Generators.modification);
  6835. var insertRowsAfter = run(opInsertRowsAfter, onCells, noop, noop, Generators.modification);
  6836. var insertColumnsBefore = run(opInsertColumnsBefore, insertColumnsExtractor(true), adjustAndRedistributeWidths, noop, Generators.modification);
  6837. var insertColumnsAfter = run(opInsertColumnsAfter, insertColumnsExtractor(false), adjustAndRedistributeWidths, noop, Generators.modification);
  6838. var eraseColumns = run(opEraseColumns, eraseColumnsExtractor, adjustAndRedistributeWidths, prune, Generators.modification);
  6839. var eraseRows = run(opEraseRows, onCells, noop, prune, Generators.modification);
  6840. var makeColumnsHeader = run(opMakeColumnsHeader, onUnlockedCells, noop, noop, headerCellGenerator);
  6841. var unmakeColumnsHeader = run(opUnmakeColumnsHeader, onUnlockedCells, noop, noop, bodyCellGenerator);
  6842. var makeRowsHeader = run(opMakeRowsHeader, onUnlockedCells, noop, noop, headerCellGenerator);
  6843. var makeRowsBody = run(opMakeRowsBody, onUnlockedCells, noop, noop, bodyCellGenerator);
  6844. var makeRowsFooter = run(opMakeRowsFooter, onUnlockedCells, noop, noop, bodyCellGenerator);
  6845. var makeCellsHeader = run(opMakeCellsHeader, onUnlockedCells, noop, noop, headerCellGenerator);
  6846. var unmakeCellsHeader = run(opUnmakeCellsHeader, onUnlockedCells, noop, noop, bodyCellGenerator);
  6847. var mergeCells = run(opMergeCells, onUnlockedMergable, resize, noop, Generators.merging);
  6848. var unmergeCells = run(opUnmergeCells, onUnlockedUnmergable, resize, noop, Generators.merging);
  6849. var pasteCells = run(opPasteCells, onPaste, resize, noop, Generators.modification);
  6850. var pasteColsBefore = run(opPasteColsBefore, pasteColumnsExtractor(true), noop, noop, Generators.modification);
  6851. var pasteColsAfter = run(opPasteColsAfter, pasteColumnsExtractor(false), noop, noop, Generators.modification);
  6852. var pasteRowsBefore = run(opPasteRowsBefore, onPasteByEditor, noop, noop, Generators.modification);
  6853. var pasteRowsAfter = run(opPasteRowsAfter, onPasteByEditor, noop, noop, Generators.modification);
  6854. var getColumnsType = opGetColumnsType;
  6855. var getCellsType = opGetCellsType;
  6856. var getRowsType = opGetRowsType;
  6857. var TableActions = function (editor, cellSelection, lazyWire) {
  6858. var isTableBody = function (editor) {
  6859. return name(getBody(editor)) === 'table';
  6860. };
  6861. var lastRowGuard = function (table) {
  6862. return isTableBody(editor) === false || getGridSize(table).rows > 1;
  6863. };
  6864. var lastColumnGuard = function (table) {
  6865. return isTableBody(editor) === false || getGridSize(table).columns > 1;
  6866. };
  6867. var cloneFormats = getCloneElements(editor);
  6868. var colMutationOp = isResizeTableColumnResizing(editor) ? noop : halve;
  6869. var getTableSectionType = function (table) {
  6870. switch (getTableHeaderType(editor)) {
  6871. case 'section':
  6872. return TableSection.section();
  6873. case 'sectionCells':
  6874. return TableSection.sectionCells();
  6875. case 'cells':
  6876. return TableSection.cells();
  6877. default:
  6878. return TableSection.getTableSectionType(table, 'section');
  6879. }
  6880. };
  6881. var setSelectionFromAction = function (table, result) {
  6882. return result.cursor.fold(function () {
  6883. var cells = cells$1(table);
  6884. return head(cells).filter(inBody).map(function (firstCell) {
  6885. cellSelection.clear(table);
  6886. var rng = editor.dom.createRng();
  6887. rng.selectNode(firstCell.dom);
  6888. editor.selection.setRng(rng);
  6889. set$2(firstCell, 'data-mce-selected', '1');
  6890. return rng;
  6891. });
  6892. }, function (cell) {
  6893. var des = freefallRtl(cell);
  6894. var rng = editor.dom.createRng();
  6895. rng.setStart(des.element.dom, des.offset);
  6896. rng.setEnd(des.element.dom, des.offset);
  6897. editor.selection.setRng(rng);
  6898. cellSelection.clear(table);
  6899. return Optional.some(rng);
  6900. });
  6901. };
  6902. var execute = function (operation, guard, mutate, lazyWire, effect) {
  6903. return function (table, target, noEvents) {
  6904. if (noEvents === void 0) {
  6905. noEvents = false;
  6906. }
  6907. removeDataStyle(table);
  6908. var wire = lazyWire();
  6909. var doc = SugarElement.fromDom(editor.getDoc());
  6910. var generators = cellOperations(mutate, doc, cloneFormats);
  6911. var behaviours = {
  6912. sizing: get$4(editor, table),
  6913. resize: isResizeTableColumnResizing(editor) ? resizeTable() : preserveTable(),
  6914. section: getTableSectionType(table)
  6915. };
  6916. return guard(table) ? operation(wire, table, target, generators, behaviours).bind(function (result) {
  6917. each$2(result.newRows, function (row) {
  6918. fireNewRow(editor, row.dom);
  6919. });
  6920. each$2(result.newCells, function (cell) {
  6921. fireNewCell(editor, cell.dom);
  6922. });
  6923. var range = setSelectionFromAction(table, result);
  6924. if (inBody(table)) {
  6925. removeDataStyle(table);
  6926. if (!noEvents) {
  6927. fireTableModified(editor, table.dom, effect);
  6928. }
  6929. }
  6930. return range.map(function (rng) {
  6931. return {
  6932. rng: rng,
  6933. effect: effect
  6934. };
  6935. });
  6936. }) : Optional.none();
  6937. };
  6938. };
  6939. var deleteRow = execute(eraseRows, lastRowGuard, noop, lazyWire, structureModified);
  6940. var deleteColumn = execute(eraseColumns, lastColumnGuard, noop, lazyWire, structureModified);
  6941. var insertRowsBefore$1 = execute(insertRowsBefore, always, noop, lazyWire, structureModified);
  6942. var insertRowsAfter$1 = execute(insertRowsAfter, always, noop, lazyWire, structureModified);
  6943. var insertColumnsBefore$1 = execute(insertColumnsBefore, always, colMutationOp, lazyWire, structureModified);
  6944. var insertColumnsAfter$1 = execute(insertColumnsAfter, always, colMutationOp, lazyWire, structureModified);
  6945. var mergeCells$1 = execute(mergeCells, always, noop, lazyWire, structureModified);
  6946. var unmergeCells$1 = execute(unmergeCells, always, noop, lazyWire, structureModified);
  6947. var pasteColsBefore$1 = execute(pasteColsBefore, always, noop, lazyWire, structureModified);
  6948. var pasteColsAfter$1 = execute(pasteColsAfter, always, noop, lazyWire, structureModified);
  6949. var pasteRowsBefore$1 = execute(pasteRowsBefore, always, noop, lazyWire, structureModified);
  6950. var pasteRowsAfter$1 = execute(pasteRowsAfter, always, noop, lazyWire, structureModified);
  6951. var pasteCells$1 = execute(pasteCells, always, noop, lazyWire, styleAndStructureModified);
  6952. var makeCellsHeader$1 = execute(makeCellsHeader, always, noop, lazyWire, structureModified);
  6953. var unmakeCellsHeader$1 = execute(unmakeCellsHeader, always, noop, lazyWire, structureModified);
  6954. var makeColumnsHeader$1 = execute(makeColumnsHeader, always, noop, lazyWire, structureModified);
  6955. var unmakeColumnsHeader$1 = execute(unmakeColumnsHeader, always, noop, lazyWire, structureModified);
  6956. var makeRowsHeader$1 = execute(makeRowsHeader, always, noop, lazyWire, structureModified);
  6957. var makeRowsBody$1 = execute(makeRowsBody, always, noop, lazyWire, structureModified);
  6958. var makeRowsFooter$1 = execute(makeRowsFooter, always, noop, lazyWire, structureModified);
  6959. var getTableCellType = getCellsType;
  6960. var getTableColType = getColumnsType;
  6961. var getTableRowType = getRowsType;
  6962. return {
  6963. deleteRow: deleteRow,
  6964. deleteColumn: deleteColumn,
  6965. insertRowsBefore: insertRowsBefore$1,
  6966. insertRowsAfter: insertRowsAfter$1,
  6967. insertColumnsBefore: insertColumnsBefore$1,
  6968. insertColumnsAfter: insertColumnsAfter$1,
  6969. mergeCells: mergeCells$1,
  6970. unmergeCells: unmergeCells$1,
  6971. pasteColsBefore: pasteColsBefore$1,
  6972. pasteColsAfter: pasteColsAfter$1,
  6973. pasteRowsBefore: pasteRowsBefore$1,
  6974. pasteRowsAfter: pasteRowsAfter$1,
  6975. pasteCells: pasteCells$1,
  6976. makeCellsHeader: makeCellsHeader$1,
  6977. unmakeCellsHeader: unmakeCellsHeader$1,
  6978. makeColumnsHeader: makeColumnsHeader$1,
  6979. unmakeColumnsHeader: unmakeColumnsHeader$1,
  6980. makeRowsHeader: makeRowsHeader$1,
  6981. makeRowsBody: makeRowsBody$1,
  6982. makeRowsFooter: makeRowsFooter$1,
  6983. getTableRowType: getTableRowType,
  6984. getTableCellType: getTableCellType,
  6985. getTableColType: getTableColType
  6986. };
  6987. };
  6988. var DefaultRenderOptions = {
  6989. styles: {
  6990. 'border-collapse': 'collapse',
  6991. 'width': '100%'
  6992. },
  6993. attributes: { border: '1' },
  6994. colGroups: false
  6995. };
  6996. var tableHeaderCell = function () {
  6997. return SugarElement.fromTag('th');
  6998. };
  6999. var tableCell = function () {
  7000. return SugarElement.fromTag('td');
  7001. };
  7002. var tableColumn = function () {
  7003. return SugarElement.fromTag('col');
  7004. };
  7005. var createRow = function (columns, rowHeaders, columnHeaders, rowIndex) {
  7006. var tr = SugarElement.fromTag('tr');
  7007. for (var j = 0; j < columns; j++) {
  7008. var td = rowIndex < rowHeaders || j < columnHeaders ? tableHeaderCell() : tableCell();
  7009. if (j < columnHeaders) {
  7010. set$2(td, 'scope', 'row');
  7011. }
  7012. if (rowIndex < rowHeaders) {
  7013. set$2(td, 'scope', 'col');
  7014. }
  7015. append$1(td, SugarElement.fromTag('br'));
  7016. append$1(tr, td);
  7017. }
  7018. return tr;
  7019. };
  7020. var createGroupRow = function (columns) {
  7021. var columnGroup = SugarElement.fromTag('colgroup');
  7022. range$1(columns, function () {
  7023. return append$1(columnGroup, tableColumn());
  7024. });
  7025. return columnGroup;
  7026. };
  7027. var createRows = function (rows, columns, rowHeaders, columnHeaders) {
  7028. return range$1(rows, function (r) {
  7029. return createRow(columns, rowHeaders, columnHeaders, r);
  7030. });
  7031. };
  7032. var render = function (rows, columns, rowHeaders, columnHeaders, headerType, renderOpts) {
  7033. if (renderOpts === void 0) {
  7034. renderOpts = DefaultRenderOptions;
  7035. }
  7036. var table = SugarElement.fromTag('table');
  7037. var rowHeadersGoInThead = headerType !== 'cells';
  7038. setAll(table, renderOpts.styles);
  7039. setAll$1(table, renderOpts.attributes);
  7040. if (renderOpts.colGroups) {
  7041. append$1(table, createGroupRow(columns));
  7042. }
  7043. var actualRowHeaders = Math.min(rows, rowHeaders);
  7044. if (rowHeadersGoInThead && rowHeaders > 0) {
  7045. var thead = SugarElement.fromTag('thead');
  7046. append$1(table, thead);
  7047. var theadRowHeaders = headerType === 'sectionCells' ? actualRowHeaders : 0;
  7048. var theadRows = createRows(rowHeaders, columns, theadRowHeaders, columnHeaders);
  7049. append(thead, theadRows);
  7050. }
  7051. var tbody = SugarElement.fromTag('tbody');
  7052. append$1(table, tbody);
  7053. var numRows = rowHeadersGoInThead ? rows - actualRowHeaders : rows;
  7054. var numRowHeaders = rowHeadersGoInThead ? 0 : rowHeaders;
  7055. var tbodyRows = createRows(numRows, columns, numRowHeaders, columnHeaders);
  7056. append(tbody, tbodyRows);
  7057. return table;
  7058. };
  7059. var get$2 = function (element) {
  7060. return element.dom.innerHTML;
  7061. };
  7062. var getOuter = function (element) {
  7063. var container = SugarElement.fromTag('div');
  7064. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  7065. append$1(container, clone);
  7066. return get$2(container);
  7067. };
  7068. var placeCaretInCell = function (editor, cell) {
  7069. editor.selection.select(cell.dom, true);
  7070. editor.selection.collapse(true);
  7071. };
  7072. var selectFirstCellInTable = function (editor, tableElm) {
  7073. descendant(tableElm, 'td,th').each(curry(placeCaretInCell, editor));
  7074. };
  7075. var fireEvents = function (editor, table) {
  7076. each$2(descendants(table, 'tr'), function (row) {
  7077. fireNewRow(editor, row.dom);
  7078. each$2(descendants(row, 'th,td'), function (cell) {
  7079. fireNewCell(editor, cell.dom);
  7080. });
  7081. });
  7082. };
  7083. var isPercentage = function (width) {
  7084. return isString(width) && width.indexOf('%') !== -1;
  7085. };
  7086. var insert = function (editor, columns, rows, colHeaders, rowHeaders) {
  7087. var defaultStyles = getDefaultStyles(editor);
  7088. var options = {
  7089. styles: defaultStyles,
  7090. attributes: getDefaultAttributes(editor),
  7091. colGroups: useColumnGroup(editor)
  7092. };
  7093. editor.undoManager.ignore(function () {
  7094. var table = render(rows, columns, rowHeaders, colHeaders, getTableHeaderType(editor), options);
  7095. set$2(table, 'data-mce-id', '__mce');
  7096. var html = getOuter(table);
  7097. editor.insertContent(html);
  7098. editor.addVisual();
  7099. });
  7100. return descendant(getBody(editor), 'table[data-mce-id="__mce"]').map(function (table) {
  7101. if (isPixelsForced(editor)) {
  7102. enforcePixels(table);
  7103. } else if (isResponsiveForced(editor)) {
  7104. enforceNone(table);
  7105. } else if (isPercentagesForced(editor) || isPercentage(defaultStyles.width)) {
  7106. enforcePercentage(table);
  7107. }
  7108. removeDataStyle(table);
  7109. remove$7(table, 'data-mce-id');
  7110. fireEvents(editor, table);
  7111. selectFirstCellInTable(editor, table);
  7112. return table.dom;
  7113. }).getOr(null);
  7114. };
  7115. var insertTableWithDataValidation = function (editor, rows, columns, options, errorMsg) {
  7116. if (options === void 0) {
  7117. options = {};
  7118. }
  7119. var checkInput = function (val) {
  7120. return isNumber(val) && val > 0;
  7121. };
  7122. if (checkInput(rows) && checkInput(columns)) {
  7123. var headerRows = options.headerRows || 0;
  7124. var headerColumns = options.headerColumns || 0;
  7125. return insert(editor, columns, rows, headerColumns, headerRows);
  7126. } else {
  7127. console.error(errorMsg);
  7128. return null;
  7129. }
  7130. };
  7131. var getClipboardElements = function (getClipboard) {
  7132. return function () {
  7133. return getClipboard().fold(function () {
  7134. return [];
  7135. }, function (elems) {
  7136. return map$1(elems, function (e) {
  7137. return e.dom;
  7138. });
  7139. });
  7140. };
  7141. };
  7142. var setClipboardElements = function (setClipboard) {
  7143. return function (elems) {
  7144. var elmsOpt = elems.length > 0 ? Optional.some(fromDom(elems)) : Optional.none();
  7145. setClipboard(elmsOpt);
  7146. };
  7147. };
  7148. var insertTable = function (editor) {
  7149. return function (columns, rows, options) {
  7150. if (options === void 0) {
  7151. options = {};
  7152. }
  7153. var table = insertTableWithDataValidation(editor, rows, columns, options, 'Invalid values for insertTable - rows and columns values are required to insert a table.');
  7154. editor.undoManager.add();
  7155. return table;
  7156. };
  7157. };
  7158. var getApi = function (editor, clipboard, resizeHandler, selectionTargets) {
  7159. return {
  7160. insertTable: insertTable(editor),
  7161. setClipboardRows: setClipboardElements(clipboard.setRows),
  7162. getClipboardRows: getClipboardElements(clipboard.getRows),
  7163. setClipboardCols: setClipboardElements(clipboard.setColumns),
  7164. getClipboardCols: getClipboardElements(clipboard.getColumns),
  7165. resizeHandler: resizeHandler,
  7166. selectionTargets: selectionTargets
  7167. };
  7168. };
  7169. var constrainSpan = function (element, property, value) {
  7170. var currentColspan = getAttrValue(element, property, 1);
  7171. if (value === 1 || currentColspan <= 1) {
  7172. remove$7(element, property);
  7173. } else {
  7174. set$2(element, property, Math.min(value, currentColspan));
  7175. }
  7176. };
  7177. var generateColGroup = function (house, minColRange, maxColRange) {
  7178. if (Warehouse.hasColumns(house)) {
  7179. var colsToCopy = filter$2(Warehouse.justColumns(house), function (col) {
  7180. return col.column >= minColRange && col.column < maxColRange;
  7181. });
  7182. var copiedCols = map$1(colsToCopy, function (c) {
  7183. var clonedCol = deep(c.element);
  7184. constrainSpan(clonedCol, 'span', maxColRange - minColRange);
  7185. return clonedCol;
  7186. });
  7187. var fakeColgroup = SugarElement.fromTag('colgroup');
  7188. append(fakeColgroup, copiedCols);
  7189. return [fakeColgroup];
  7190. } else {
  7191. return [];
  7192. }
  7193. };
  7194. var generateRows = function (house, minColRange, maxColRange) {
  7195. return map$1(house.all, function (row) {
  7196. var cellsToCopy = filter$2(row.cells, function (cell) {
  7197. return cell.column >= minColRange && cell.column < maxColRange;
  7198. });
  7199. var copiedCells = map$1(cellsToCopy, function (cell) {
  7200. var clonedCell = deep(cell.element);
  7201. constrainSpan(clonedCell, 'colspan', maxColRange - minColRange);
  7202. return clonedCell;
  7203. });
  7204. var fakeTR = SugarElement.fromTag('tr');
  7205. append(fakeTR, copiedCells);
  7206. return fakeTR;
  7207. });
  7208. };
  7209. var copyCols = function (table, target) {
  7210. var house = Warehouse.fromTable(table);
  7211. var details = onUnlockedCells(house, target);
  7212. return details.map(function (selectedCells) {
  7213. var lastSelectedCell = selectedCells[selectedCells.length - 1];
  7214. var minColRange = selectedCells[0].column;
  7215. var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
  7216. var fakeColGroups = generateColGroup(house, minColRange, maxColRange);
  7217. var fakeRows = generateRows(house, minColRange, maxColRange);
  7218. return __spreadArray(__spreadArray([], fakeColGroups, true), fakeRows, true);
  7219. });
  7220. };
  7221. var copyRows = function (table, target, generators) {
  7222. var warehouse = Warehouse.fromTable(table);
  7223. var details = onCells(warehouse, target);
  7224. return details.bind(function (selectedCells) {
  7225. var grid = toGrid(warehouse, generators, false);
  7226. var rows = extractGridDetails(grid).rows;
  7227. var slicedGrid = rows.slice(selectedCells[0].row, selectedCells[selectedCells.length - 1].row + selectedCells[selectedCells.length - 1].rowspan);
  7228. var filteredGrid = bind$2(slicedGrid, function (row) {
  7229. var newCells = filter$2(row.cells, function (cell) {
  7230. return !cell.isLocked;
  7231. });
  7232. return newCells.length > 0 ? [__assign(__assign({}, row), { cells: newCells })] : [];
  7233. });
  7234. var slicedDetails = toDetailList(filteredGrid);
  7235. return someIf(slicedDetails.length > 0, slicedDetails);
  7236. }).map(function (slicedDetails) {
  7237. return copy(slicedDetails);
  7238. });
  7239. };
  7240. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  7241. var getTDTHOverallStyle = function (dom, elm, name) {
  7242. var cells = dom.select('td,th', elm);
  7243. var firstChildStyle;
  7244. var checkChildren = function (firstChildStyle, elms) {
  7245. for (var i = 0; i < elms.length; i++) {
  7246. var currentStyle = dom.getStyle(elms[i], name);
  7247. if (typeof firstChildStyle === 'undefined') {
  7248. firstChildStyle = currentStyle;
  7249. }
  7250. if (firstChildStyle !== currentStyle) {
  7251. return '';
  7252. }
  7253. }
  7254. return firstChildStyle;
  7255. };
  7256. return checkChildren(firstChildStyle, cells);
  7257. };
  7258. var applyAlign = function (editor, elm, name) {
  7259. if (name) {
  7260. editor.formatter.apply('align' + name, {}, elm);
  7261. }
  7262. };
  7263. var applyVAlign = function (editor, elm, name) {
  7264. if (name) {
  7265. editor.formatter.apply('valign' + name, {}, elm);
  7266. }
  7267. };
  7268. var unApplyAlign = function (editor, elm) {
  7269. global$2.each('left center right'.split(' '), function (name) {
  7270. editor.formatter.remove('align' + name, {}, elm);
  7271. });
  7272. };
  7273. var unApplyVAlign = function (editor, elm) {
  7274. global$2.each('top middle bottom'.split(' '), function (name) {
  7275. editor.formatter.remove('valign' + name, {}, elm);
  7276. });
  7277. };
  7278. var verticalAlignValues = [
  7279. {
  7280. text: 'None',
  7281. value: ''
  7282. },
  7283. {
  7284. text: 'Top',
  7285. value: 'top'
  7286. },
  7287. {
  7288. text: 'Middle',
  7289. value: 'middle'
  7290. },
  7291. {
  7292. text: 'Bottom',
  7293. value: 'bottom'
  7294. }
  7295. ];
  7296. var hexColour = function (value) {
  7297. return { value: value };
  7298. };
  7299. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  7300. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  7301. var isHexString = function (hex) {
  7302. return shorthandRegex.test(hex) || longformRegex.test(hex);
  7303. };
  7304. var normalizeHex = function (hex) {
  7305. return removeLeading(hex, '#').toUpperCase();
  7306. };
  7307. var fromString$1 = function (hex) {
  7308. return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  7309. };
  7310. var toHex = function (component) {
  7311. var hex = component.toString(16);
  7312. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  7313. };
  7314. var fromRgba = function (rgbaColour) {
  7315. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  7316. return hexColour(value);
  7317. };
  7318. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  7319. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  7320. var rgbaColour = function (red, green, blue, alpha) {
  7321. return {
  7322. red: red,
  7323. green: green,
  7324. blue: blue,
  7325. alpha: alpha
  7326. };
  7327. };
  7328. var fromStringValues = function (red, green, blue, alpha) {
  7329. var r = parseInt(red, 10);
  7330. var g = parseInt(green, 10);
  7331. var b = parseInt(blue, 10);
  7332. var a = parseFloat(alpha);
  7333. return rgbaColour(r, g, b, a);
  7334. };
  7335. var fromString = function (rgbaString) {
  7336. if (rgbaString === 'transparent') {
  7337. return Optional.some(rgbaColour(0, 0, 0, 0));
  7338. }
  7339. var rgbMatch = rgbRegex.exec(rgbaString);
  7340. if (rgbMatch !== null) {
  7341. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  7342. }
  7343. var rgbaMatch = rgbaRegex.exec(rgbaString);
  7344. if (rgbaMatch !== null) {
  7345. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  7346. }
  7347. return Optional.none();
  7348. };
  7349. var anyToHex = function (color) {
  7350. return fromString$1(color).orThunk(function () {
  7351. return fromString(color).map(fromRgba);
  7352. }).getOrThunk(function () {
  7353. var canvas = document.createElement('canvas');
  7354. canvas.height = 1;
  7355. canvas.width = 1;
  7356. var canvasContext = canvas.getContext('2d');
  7357. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  7358. canvasContext.fillStyle = '#FFFFFF';
  7359. canvasContext.fillStyle = color;
  7360. canvasContext.fillRect(0, 0, 1, 1);
  7361. var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  7362. var r = rgba[0];
  7363. var g = rgba[1];
  7364. var b = rgba[2];
  7365. var a = rgba[3];
  7366. return fromRgba(rgbaColour(r, g, b, a));
  7367. });
  7368. };
  7369. var Cell = function (initial) {
  7370. var value = initial;
  7371. var get = function () {
  7372. return value;
  7373. };
  7374. var set = function (v) {
  7375. value = v;
  7376. };
  7377. return {
  7378. get: get,
  7379. set: set
  7380. };
  7381. };
  7382. var singleton = function (doRevoke) {
  7383. var subject = Cell(Optional.none());
  7384. var revoke = function () {
  7385. return subject.get().each(doRevoke);
  7386. };
  7387. var clear = function () {
  7388. revoke();
  7389. subject.set(Optional.none());
  7390. };
  7391. var isSet = function () {
  7392. return subject.get().isSome();
  7393. };
  7394. var get = function () {
  7395. return subject.get();
  7396. };
  7397. var set = function (s) {
  7398. revoke();
  7399. subject.set(Optional.some(s));
  7400. };
  7401. return {
  7402. clear: clear,
  7403. isSet: isSet,
  7404. get: get,
  7405. set: set
  7406. };
  7407. };
  7408. var unbindable = function () {
  7409. return singleton(function (s) {
  7410. return s.unbind();
  7411. });
  7412. };
  7413. var value = function () {
  7414. var subject = singleton(noop);
  7415. var on = function (f) {
  7416. return subject.get().each(f);
  7417. };
  7418. return __assign(__assign({}, subject), { on: on });
  7419. };
  7420. var onSetupToggle = function (editor, selections, formatName, formatValue) {
  7421. return function (api) {
  7422. var boundCallback = unbindable();
  7423. var isNone = isEmpty$1(formatValue);
  7424. var init = function () {
  7425. var selectedCells = getCellsFromSelection(selections);
  7426. var checkNode = function (cell) {
  7427. return editor.formatter.match(formatName, { value: formatValue }, cell.dom, isNone);
  7428. };
  7429. if (isNone) {
  7430. api.setActive(!exists(selectedCells, checkNode));
  7431. boundCallback.set(editor.formatter.formatChanged(formatName, function (match) {
  7432. return api.setActive(!match);
  7433. }, true));
  7434. } else {
  7435. api.setActive(forall(selectedCells, checkNode));
  7436. boundCallback.set(editor.formatter.formatChanged(formatName, api.setActive, false, { value: formatValue }));
  7437. }
  7438. };
  7439. editor.initialized ? init() : editor.on('init', init);
  7440. return boundCallback.clear;
  7441. };
  7442. };
  7443. var isListGroup = function (item) {
  7444. return hasNonNullableKey(item, 'menu');
  7445. };
  7446. var buildListItems = function (items) {
  7447. return map$1(items, function (item) {
  7448. var text = item.text || item.title;
  7449. if (isListGroup(item)) {
  7450. return {
  7451. text: text,
  7452. items: buildListItems(item.menu)
  7453. };
  7454. } else {
  7455. return {
  7456. text: text,
  7457. value: item.value
  7458. };
  7459. }
  7460. });
  7461. };
  7462. var buildMenuItems = function (editor, selections, items, format, onAction) {
  7463. return map$1(items, function (item) {
  7464. var text = item.text || item.title;
  7465. if (isListGroup(item)) {
  7466. return {
  7467. type: 'nestedmenuitem',
  7468. text: text,
  7469. getSubmenuItems: function () {
  7470. return buildMenuItems(editor, selections, item.menu, format, onAction);
  7471. }
  7472. };
  7473. } else {
  7474. return {
  7475. text: text,
  7476. type: 'togglemenuitem',
  7477. onAction: function () {
  7478. return onAction(item.value);
  7479. },
  7480. onSetup: onSetupToggle(editor, selections, format, item.value)
  7481. };
  7482. }
  7483. });
  7484. };
  7485. var applyTableCellStyle = function (editor, style) {
  7486. return function (value) {
  7487. var _a;
  7488. editor.execCommand('mceTableApplyCellStyle', false, (_a = {}, _a[style] = value, _a));
  7489. };
  7490. };
  7491. var filterNoneItem = function (list) {
  7492. return bind$2(list, function (item) {
  7493. if (isListGroup(item)) {
  7494. return [__assign(__assign({}, item), { menu: filterNoneItem(item.menu) })];
  7495. } else {
  7496. return isNotEmpty(item.value) ? [item] : [];
  7497. }
  7498. });
  7499. };
  7500. var generateMenuItemsCallback = function (editor, selections, items, format, onAction) {
  7501. return function (callback) {
  7502. return callback(buildMenuItems(editor, selections, items, format, onAction));
  7503. };
  7504. };
  7505. var buildColorMenu = function (editor, colorList, style) {
  7506. var colorMap = map$1(colorList, function (entry) {
  7507. return {
  7508. text: entry.title,
  7509. value: '#' + anyToHex(entry.value).value,
  7510. type: 'choiceitem'
  7511. };
  7512. });
  7513. return [{
  7514. type: 'fancymenuitem',
  7515. fancytype: 'colorswatch',
  7516. initData: {
  7517. colors: colorMap.length > 0 ? colorMap : undefined,
  7518. allowCustomColors: false
  7519. },
  7520. onAction: function (data) {
  7521. var _a;
  7522. var value = data.value === 'remove' ? '' : data.value;
  7523. editor.execCommand('mceTableApplyCellStyle', false, (_a = {}, _a[style] = value, _a));
  7524. }
  7525. }];
  7526. };
  7527. var changeRowHeader = function (editor) {
  7528. return function () {
  7529. var currentType = editor.queryCommandValue('mceTableRowType');
  7530. var newType = currentType === 'header' ? 'body' : 'header';
  7531. editor.execCommand('mceTableRowType', false, { type: newType });
  7532. };
  7533. };
  7534. var changeColumnHeader = function (editor) {
  7535. return function () {
  7536. var currentType = editor.queryCommandValue('mceTableColType');
  7537. var newType = currentType === 'th' ? 'td' : 'th';
  7538. editor.execCommand('mceTableColType', false, { type: newType });
  7539. };
  7540. };
  7541. var getClassList$1 = function (editor) {
  7542. var classes = buildListItems(getCellClassList(editor));
  7543. if (classes.length > 0) {
  7544. return Optional.some({
  7545. name: 'class',
  7546. type: 'listbox',
  7547. label: 'Class',
  7548. items: classes
  7549. });
  7550. }
  7551. return Optional.none();
  7552. };
  7553. var children = [
  7554. {
  7555. name: 'width',
  7556. type: 'input',
  7557. label: 'Width'
  7558. },
  7559. {
  7560. name: 'height',
  7561. type: 'input',
  7562. label: 'Height'
  7563. },
  7564. {
  7565. name: 'celltype',
  7566. type: 'listbox',
  7567. label: 'Cell type',
  7568. items: [
  7569. {
  7570. text: 'Cell',
  7571. value: 'td'
  7572. },
  7573. {
  7574. text: 'Header cell',
  7575. value: 'th'
  7576. }
  7577. ]
  7578. },
  7579. {
  7580. name: 'scope',
  7581. type: 'listbox',
  7582. label: 'Scope',
  7583. items: [
  7584. {
  7585. text: 'None',
  7586. value: ''
  7587. },
  7588. {
  7589. text: 'Row',
  7590. value: 'row'
  7591. },
  7592. {
  7593. text: 'Column',
  7594. value: 'col'
  7595. },
  7596. {
  7597. text: 'Row group',
  7598. value: 'rowgroup'
  7599. },
  7600. {
  7601. text: 'Column group',
  7602. value: 'colgroup'
  7603. }
  7604. ]
  7605. },
  7606. {
  7607. name: 'halign',
  7608. type: 'listbox',
  7609. label: 'Horizontal align',
  7610. items: [
  7611. {
  7612. text: 'None',
  7613. value: ''
  7614. },
  7615. {
  7616. text: 'Left',
  7617. value: 'left'
  7618. },
  7619. {
  7620. text: 'Center',
  7621. value: 'center'
  7622. },
  7623. {
  7624. text: 'Right',
  7625. value: 'right'
  7626. }
  7627. ]
  7628. },
  7629. {
  7630. name: 'valign',
  7631. type: 'listbox',
  7632. label: 'Vertical align',
  7633. items: verticalAlignValues
  7634. }
  7635. ];
  7636. var getItems$2 = function (editor) {
  7637. return children.concat(getClassList$1(editor).toArray());
  7638. };
  7639. var getAdvancedTab = function (editor, dialogName) {
  7640. var emptyBorderStyle = [{
  7641. text: 'Select...',
  7642. value: ''
  7643. }];
  7644. var advTabItems = [
  7645. {
  7646. name: 'borderstyle',
  7647. type: 'listbox',
  7648. label: 'Border style',
  7649. items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
  7650. },
  7651. {
  7652. name: 'bordercolor',
  7653. type: 'colorinput',
  7654. label: 'Border color'
  7655. },
  7656. {
  7657. name: 'backgroundcolor',
  7658. type: 'colorinput',
  7659. label: 'Background color'
  7660. }
  7661. ];
  7662. var borderWidth = {
  7663. name: 'borderwidth',
  7664. type: 'input',
  7665. label: 'Border width'
  7666. };
  7667. var items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
  7668. return {
  7669. title: 'Advanced',
  7670. name: 'advanced',
  7671. items: items
  7672. };
  7673. };
  7674. var modifiers = function (testTruthy) {
  7675. return function (editor, node) {
  7676. var dom = editor.dom;
  7677. var setAttrib = function (attr, value) {
  7678. if (!testTruthy || value) {
  7679. dom.setAttrib(node, attr, value);
  7680. }
  7681. };
  7682. var setStyle = function (prop, value) {
  7683. if (!testTruthy || value) {
  7684. dom.setStyle(node, prop, value);
  7685. }
  7686. };
  7687. var setFormat = function (formatName, value) {
  7688. if (!testTruthy || value) {
  7689. if (value === '') {
  7690. editor.formatter.remove(formatName, { value: null }, node, true);
  7691. } else {
  7692. editor.formatter.apply(formatName, { value: value }, node);
  7693. }
  7694. }
  7695. };
  7696. return {
  7697. setAttrib: setAttrib,
  7698. setStyle: setStyle,
  7699. setFormat: setFormat
  7700. };
  7701. };
  7702. };
  7703. var DomModifier = {
  7704. normal: modifiers(false),
  7705. ifTruthy: modifiers(true)
  7706. };
  7707. var rgbToHex = function (dom) {
  7708. return function (value) {
  7709. return startsWith(value, 'rgb') ? dom.toHex(value) : value;
  7710. };
  7711. };
  7712. var extractAdvancedStyles = function (dom, elm) {
  7713. var element = SugarElement.fromDom(elm);
  7714. return {
  7715. borderwidth: getRaw$2(element, 'border-width').getOr(''),
  7716. borderstyle: getRaw$2(element, 'border-style').getOr(''),
  7717. bordercolor: getRaw$2(element, 'border-color').map(rgbToHex(dom)).getOr(''),
  7718. backgroundcolor: getRaw$2(element, 'background-color').map(rgbToHex(dom)).getOr('')
  7719. };
  7720. };
  7721. var getSharedValues = function (data) {
  7722. var baseData = data[0];
  7723. var comparisonData = data.slice(1);
  7724. each$2(comparisonData, function (items) {
  7725. each$2(keys(baseData), function (key) {
  7726. each$1(items, function (itemValue, itemKey) {
  7727. var comparisonValue = baseData[key];
  7728. if (comparisonValue !== '' && key === itemKey) {
  7729. if (comparisonValue !== itemValue) {
  7730. baseData[key] = '';
  7731. }
  7732. }
  7733. });
  7734. });
  7735. });
  7736. return baseData;
  7737. };
  7738. var getAlignment = function (formats, formatName, editor, elm) {
  7739. return find$1(formats, function (name) {
  7740. return !isUndefined(editor.formatter.matchNode(elm, formatName + name));
  7741. }).getOr('');
  7742. };
  7743. var getHAlignment = curry(getAlignment, [
  7744. 'left',
  7745. 'center',
  7746. 'right'
  7747. ], 'align');
  7748. var getVAlignment = curry(getAlignment, [
  7749. 'top',
  7750. 'middle',
  7751. 'bottom'
  7752. ], 'valign');
  7753. var extractDataFromSettings = function (editor, hasAdvTableTab) {
  7754. var style = getDefaultStyles(editor);
  7755. var attrs = getDefaultAttributes(editor);
  7756. var extractAdvancedStyleData = function (dom) {
  7757. return {
  7758. borderstyle: get$c(style, 'border-style').getOr(''),
  7759. bordercolor: rgbToHex(dom)(get$c(style, 'border-color').getOr('')),
  7760. backgroundcolor: rgbToHex(dom)(get$c(style, 'background-color').getOr(''))
  7761. };
  7762. };
  7763. var defaultData = {
  7764. height: '',
  7765. width: '100%',
  7766. cellspacing: '',
  7767. cellpadding: '',
  7768. caption: false,
  7769. class: '',
  7770. align: '',
  7771. border: ''
  7772. };
  7773. var getBorder = function () {
  7774. var borderWidth = style['border-width'];
  7775. if (shouldStyleWithCss(editor) && borderWidth) {
  7776. return { border: borderWidth };
  7777. }
  7778. return get$c(attrs, 'border').fold(function () {
  7779. return {};
  7780. }, function (border) {
  7781. return { border: border };
  7782. });
  7783. };
  7784. var advStyle = hasAdvTableTab ? extractAdvancedStyleData(editor.dom) : {};
  7785. var getCellPaddingCellSpacing = function () {
  7786. var spacing = get$c(style, 'border-spacing').or(get$c(attrs, 'cellspacing')).fold(function () {
  7787. return {};
  7788. }, function (cellspacing) {
  7789. return { cellspacing: cellspacing };
  7790. });
  7791. var padding = get$c(style, 'border-padding').or(get$c(attrs, 'cellpadding')).fold(function () {
  7792. return {};
  7793. }, function (cellpadding) {
  7794. return { cellpadding: cellpadding };
  7795. });
  7796. return __assign(__assign({}, spacing), padding);
  7797. };
  7798. var data = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
  7799. return data;
  7800. };
  7801. var getRowType = function (elm) {
  7802. return table(SugarElement.fromDom(elm)).map(function (table) {
  7803. var target = { selection: fromDom(elm.cells) };
  7804. return getRowsType(table, target);
  7805. }).getOr('');
  7806. };
  7807. var extractDataFromTableElement = function (editor, elm, hasAdvTableTab) {
  7808. var getBorder = function (dom, elm) {
  7809. var optBorderWidth = getRaw$2(SugarElement.fromDom(elm), 'border-width');
  7810. if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
  7811. return optBorderWidth.getOr('');
  7812. }
  7813. return dom.getAttrib(elm, 'border') || getTDTHOverallStyle(editor.dom, elm, 'border-width') || getTDTHOverallStyle(editor.dom, elm, 'border');
  7814. };
  7815. var dom = editor.dom;
  7816. var cellspacing = shouldStyleWithCss(editor) ? dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing') : dom.getAttrib(elm, 'cellspacing') || dom.getStyle(elm, 'border-spacing');
  7817. var cellpadding = shouldStyleWithCss(editor) ? getTDTHOverallStyle(dom, elm, 'padding') || dom.getAttrib(elm, 'cellpadding') : dom.getAttrib(elm, 'cellpadding') || getTDTHOverallStyle(dom, elm, 'padding');
  7818. return __assign({
  7819. width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
  7820. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  7821. cellspacing: cellspacing,
  7822. cellpadding: cellpadding,
  7823. border: getBorder(dom, elm),
  7824. caption: !!dom.select('caption', elm)[0],
  7825. class: dom.getAttrib(elm, 'class', ''),
  7826. align: getHAlignment(editor, elm)
  7827. }, hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
  7828. };
  7829. var extractDataFromRowElement = function (editor, elm, hasAdvancedRowTab) {
  7830. var dom = editor.dom;
  7831. return __assign({
  7832. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  7833. class: dom.getAttrib(elm, 'class', ''),
  7834. type: getRowType(elm),
  7835. align: getHAlignment(editor, elm)
  7836. }, hasAdvancedRowTab ? extractAdvancedStyles(dom, elm) : {});
  7837. };
  7838. var extractDataFromCellElement = function (editor, cell, hasAdvancedCellTab, column) {
  7839. var dom = editor.dom;
  7840. var colElm = column.getOr(cell);
  7841. var getStyle = function (element, style) {
  7842. return dom.getStyle(element, style) || dom.getAttrib(element, style);
  7843. };
  7844. return __assign({
  7845. width: getStyle(colElm, 'width'),
  7846. height: getStyle(cell, 'height'),
  7847. scope: dom.getAttrib(cell, 'scope'),
  7848. celltype: getNodeName(cell),
  7849. class: dom.getAttrib(cell, 'class', ''),
  7850. halign: getHAlignment(editor, cell),
  7851. valign: getVAlignment(editor, cell)
  7852. }, hasAdvancedCellTab ? extractAdvancedStyles(dom, cell) : {});
  7853. };
  7854. var getSelectedCells = function (table, cells) {
  7855. var warehouse = Warehouse.fromTable(table);
  7856. var allCells = Warehouse.justCells(warehouse);
  7857. var filtered = filter$2(allCells, function (cellA) {
  7858. return exists(cells, function (cellB) {
  7859. return eq$1(cellA.element, cellB);
  7860. });
  7861. });
  7862. return map$1(filtered, function (cell) {
  7863. return {
  7864. element: cell.element.dom,
  7865. column: Warehouse.getColumnAt(warehouse, cell.column).map(function (col) {
  7866. return col.element.dom;
  7867. })
  7868. };
  7869. });
  7870. };
  7871. var updateSimpleProps$1 = function (modifier, colModifier, data) {
  7872. modifier.setAttrib('scope', data.scope);
  7873. modifier.setAttrib('class', data.class);
  7874. modifier.setStyle('height', addPxSuffix(data.height));
  7875. colModifier.setStyle('width', addPxSuffix(data.width));
  7876. };
  7877. var updateAdvancedProps$1 = function (modifier, data) {
  7878. modifier.setFormat('tablecellbackgroundcolor', data.backgroundcolor);
  7879. modifier.setFormat('tablecellbordercolor', data.bordercolor);
  7880. modifier.setFormat('tablecellborderstyle', data.borderstyle);
  7881. modifier.setFormat('tablecellborderwidth', addPxSuffix(data.borderwidth));
  7882. };
  7883. var applyStyleData$1 = function (editor, cells, data) {
  7884. var isSingleCell = cells.length === 1;
  7885. each$2(cells, function (item) {
  7886. var cellElm = item.element;
  7887. var modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
  7888. var colModifier = item.column.map(function (col) {
  7889. return isSingleCell ? DomModifier.normal(editor, col) : DomModifier.ifTruthy(editor, col);
  7890. }).getOr(modifier);
  7891. updateSimpleProps$1(modifier, colModifier, data);
  7892. if (hasAdvancedCellTab(editor)) {
  7893. updateAdvancedProps$1(modifier, data);
  7894. }
  7895. if (isSingleCell) {
  7896. unApplyAlign(editor, cellElm);
  7897. unApplyVAlign(editor, cellElm);
  7898. }
  7899. if (data.halign) {
  7900. applyAlign(editor, cellElm, data.halign);
  7901. }
  7902. if (data.valign) {
  7903. applyVAlign(editor, cellElm, data.valign);
  7904. }
  7905. });
  7906. };
  7907. var applyStructureData$1 = function (editor, data) {
  7908. editor.execCommand('mceTableCellType', false, {
  7909. type: data.celltype,
  7910. no_events: true
  7911. });
  7912. };
  7913. var applyCellData = function (editor, cells, oldData, data) {
  7914. var modifiedData = filter$1(data, function (value, key) {
  7915. return oldData[key] !== value;
  7916. });
  7917. if (size(modifiedData) > 0 && cells.length >= 1) {
  7918. table(cells[0]).each(function (table) {
  7919. var selectedCells = getSelectedCells(table, cells);
  7920. var styleModified = size(filter$1(modifiedData, function (_value, key) {
  7921. return key !== 'scope' && key !== 'celltype';
  7922. })) > 0;
  7923. var structureModified = has$1(modifiedData, 'celltype');
  7924. if (styleModified || has$1(modifiedData, 'scope')) {
  7925. applyStyleData$1(editor, selectedCells, data);
  7926. }
  7927. if (structureModified) {
  7928. applyStructureData$1(editor, data);
  7929. }
  7930. fireTableModified(editor, table.dom, {
  7931. structure: structureModified,
  7932. style: styleModified
  7933. });
  7934. });
  7935. }
  7936. };
  7937. var onSubmitCellForm = function (editor, cells, oldData, api) {
  7938. var data = api.getData();
  7939. api.close();
  7940. editor.undoManager.transact(function () {
  7941. applyCellData(editor, cells, oldData, data);
  7942. editor.focus();
  7943. });
  7944. };
  7945. var getData = function (editor, cells) {
  7946. var cellsData = table(cells[0]).map(function (table) {
  7947. return map$1(getSelectedCells(table, cells), function (item) {
  7948. return extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column);
  7949. });
  7950. });
  7951. return getSharedValues(cellsData.getOrDie());
  7952. };
  7953. var open$2 = function (editor, selections) {
  7954. var cells = getCellsFromSelection(selections);
  7955. if (cells.length === 0) {
  7956. return;
  7957. }
  7958. var data = getData(editor, cells);
  7959. var dialogTabPanel = {
  7960. type: 'tabpanel',
  7961. tabs: [
  7962. {
  7963. title: 'General',
  7964. name: 'general',
  7965. items: getItems$2(editor)
  7966. },
  7967. getAdvancedTab(editor, 'cell')
  7968. ]
  7969. };
  7970. var dialogPanel = {
  7971. type: 'panel',
  7972. items: [{
  7973. type: 'grid',
  7974. columns: 2,
  7975. items: getItems$2(editor)
  7976. }]
  7977. };
  7978. editor.windowManager.open({
  7979. title: 'Cell Properties',
  7980. size: 'normal',
  7981. body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
  7982. buttons: [
  7983. {
  7984. type: 'cancel',
  7985. name: 'cancel',
  7986. text: 'Cancel'
  7987. },
  7988. {
  7989. type: 'submit',
  7990. name: 'save',
  7991. text: 'Save',
  7992. primary: true
  7993. }
  7994. ],
  7995. initialData: data,
  7996. onSubmit: curry(onSubmitCellForm, editor, cells, data)
  7997. });
  7998. };
  7999. var getClassList = function (editor) {
  8000. var classes = buildListItems(getRowClassList(editor));
  8001. if (classes.length > 0) {
  8002. return Optional.some({
  8003. name: 'class',
  8004. type: 'listbox',
  8005. label: 'Class',
  8006. items: classes
  8007. });
  8008. }
  8009. return Optional.none();
  8010. };
  8011. var formChildren = [
  8012. {
  8013. type: 'listbox',
  8014. name: 'type',
  8015. label: 'Row type',
  8016. items: [
  8017. {
  8018. text: 'Header',
  8019. value: 'header'
  8020. },
  8021. {
  8022. text: 'Body',
  8023. value: 'body'
  8024. },
  8025. {
  8026. text: 'Footer',
  8027. value: 'footer'
  8028. }
  8029. ]
  8030. },
  8031. {
  8032. type: 'listbox',
  8033. name: 'align',
  8034. label: 'Alignment',
  8035. items: [
  8036. {
  8037. text: 'None',
  8038. value: ''
  8039. },
  8040. {
  8041. text: 'Left',
  8042. value: 'left'
  8043. },
  8044. {
  8045. text: 'Center',
  8046. value: 'center'
  8047. },
  8048. {
  8049. text: 'Right',
  8050. value: 'right'
  8051. }
  8052. ]
  8053. },
  8054. {
  8055. label: 'Height',
  8056. name: 'height',
  8057. type: 'input'
  8058. }
  8059. ];
  8060. var getItems$1 = function (editor) {
  8061. return formChildren.concat(getClassList(editor).toArray());
  8062. };
  8063. var updateSimpleProps = function (modifier, data) {
  8064. modifier.setAttrib('class', data.class);
  8065. modifier.setStyle('height', addPxSuffix(data.height));
  8066. };
  8067. var updateAdvancedProps = function (modifier, data) {
  8068. modifier.setStyle('background-color', data.backgroundcolor);
  8069. modifier.setStyle('border-color', data.bordercolor);
  8070. modifier.setStyle('border-style', data.borderstyle);
  8071. };
  8072. var applyStyleData = function (editor, rows, data, oldData) {
  8073. var isSingleRow = rows.length === 1;
  8074. each$2(rows, function (rowElm) {
  8075. var modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
  8076. updateSimpleProps(modifier, data);
  8077. if (hasAdvancedRowTab(editor)) {
  8078. updateAdvancedProps(modifier, data);
  8079. }
  8080. if (data.align !== oldData.align) {
  8081. unApplyAlign(editor, rowElm);
  8082. applyAlign(editor, rowElm, data.align);
  8083. }
  8084. });
  8085. };
  8086. var applyStructureData = function (editor, data) {
  8087. editor.execCommand('mceTableRowType', false, {
  8088. type: data.type,
  8089. no_events: true
  8090. });
  8091. };
  8092. var applyRowData = function (editor, rows, oldData, data) {
  8093. var modifiedData = filter$1(data, function (value, key) {
  8094. return oldData[key] !== value;
  8095. });
  8096. if (size(modifiedData) > 0) {
  8097. var typeModified_1 = has$1(modifiedData, 'type');
  8098. var styleModified_1 = typeModified_1 ? size(modifiedData) > 1 : true;
  8099. if (styleModified_1) {
  8100. applyStyleData(editor, rows, data, oldData);
  8101. }
  8102. if (typeModified_1) {
  8103. applyStructureData(editor, data);
  8104. }
  8105. table(SugarElement.fromDom(rows[0])).each(function (table) {
  8106. return fireTableModified(editor, table.dom, {
  8107. structure: typeModified_1,
  8108. style: styleModified_1
  8109. });
  8110. });
  8111. }
  8112. };
  8113. var onSubmitRowForm = function (editor, rows, oldData, api) {
  8114. var data = api.getData();
  8115. api.close();
  8116. editor.undoManager.transact(function () {
  8117. applyRowData(editor, rows, oldData, data);
  8118. editor.focus();
  8119. });
  8120. };
  8121. var open$1 = function (editor) {
  8122. var rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
  8123. if (rows.length === 0) {
  8124. return;
  8125. }
  8126. var rowsData = map$1(rows, function (rowElm) {
  8127. return extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor));
  8128. });
  8129. var data = getSharedValues(rowsData);
  8130. var dialogTabPanel = {
  8131. type: 'tabpanel',
  8132. tabs: [
  8133. {
  8134. title: 'General',
  8135. name: 'general',
  8136. items: getItems$1(editor)
  8137. },
  8138. getAdvancedTab(editor, 'row')
  8139. ]
  8140. };
  8141. var dialogPanel = {
  8142. type: 'panel',
  8143. items: [{
  8144. type: 'grid',
  8145. columns: 2,
  8146. items: getItems$1(editor)
  8147. }]
  8148. };
  8149. editor.windowManager.open({
  8150. title: 'Row Properties',
  8151. size: 'normal',
  8152. body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
  8153. buttons: [
  8154. {
  8155. type: 'cancel',
  8156. name: 'cancel',
  8157. text: 'Cancel'
  8158. },
  8159. {
  8160. type: 'submit',
  8161. name: 'save',
  8162. text: 'Save',
  8163. primary: true
  8164. }
  8165. ],
  8166. initialData: data,
  8167. onSubmit: curry(onSubmitRowForm, editor, map$1(rows, function (r) {
  8168. return r.dom;
  8169. }), data)
  8170. });
  8171. };
  8172. var getItems = function (editor, classes, insertNewTable) {
  8173. var rowColCountItems = !insertNewTable ? [] : [
  8174. {
  8175. type: 'input',
  8176. name: 'cols',
  8177. label: 'Cols',
  8178. inputMode: 'numeric'
  8179. },
  8180. {
  8181. type: 'input',
  8182. name: 'rows',
  8183. label: 'Rows',
  8184. inputMode: 'numeric'
  8185. }
  8186. ];
  8187. var alwaysItems = [
  8188. {
  8189. type: 'input',
  8190. name: 'width',
  8191. label: 'Width'
  8192. },
  8193. {
  8194. type: 'input',
  8195. name: 'height',
  8196. label: 'Height'
  8197. }
  8198. ];
  8199. var appearanceItems = hasAppearanceOptions(editor) ? [
  8200. {
  8201. type: 'input',
  8202. name: 'cellspacing',
  8203. label: 'Cell spacing',
  8204. inputMode: 'numeric'
  8205. },
  8206. {
  8207. type: 'input',
  8208. name: 'cellpadding',
  8209. label: 'Cell padding',
  8210. inputMode: 'numeric'
  8211. },
  8212. {
  8213. type: 'input',
  8214. name: 'border',
  8215. label: 'Border width'
  8216. },
  8217. {
  8218. type: 'label',
  8219. label: 'Caption',
  8220. items: [{
  8221. type: 'checkbox',
  8222. name: 'caption',
  8223. label: 'Show caption'
  8224. }]
  8225. }
  8226. ] : [];
  8227. var alignmentItem = [{
  8228. type: 'listbox',
  8229. name: 'align',
  8230. label: 'Alignment',
  8231. items: [
  8232. {
  8233. text: 'None',
  8234. value: ''
  8235. },
  8236. {
  8237. text: 'Left',
  8238. value: 'left'
  8239. },
  8240. {
  8241. text: 'Center',
  8242. value: 'center'
  8243. },
  8244. {
  8245. text: 'Right',
  8246. value: 'right'
  8247. }
  8248. ]
  8249. }];
  8250. var classListItem = classes.length > 0 ? [{
  8251. type: 'listbox',
  8252. name: 'class',
  8253. label: 'Class',
  8254. items: classes
  8255. }] : [];
  8256. return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
  8257. };
  8258. var styleTDTH = function (dom, elm, name, value) {
  8259. if (elm.tagName === 'TD' || elm.tagName === 'TH') {
  8260. if (isString(name)) {
  8261. dom.setStyle(elm, name, value);
  8262. } else {
  8263. dom.setStyle(elm, name);
  8264. }
  8265. } else {
  8266. if (elm.children) {
  8267. for (var i = 0; i < elm.children.length; i++) {
  8268. styleTDTH(dom, elm.children[i], name, value);
  8269. }
  8270. }
  8271. }
  8272. };
  8273. var applyDataToElement = function (editor, tableElm, data) {
  8274. var dom = editor.dom;
  8275. var attrs = {};
  8276. var styles = {};
  8277. attrs.class = data.class;
  8278. styles.height = addPxSuffix(data.height);
  8279. if (dom.getAttrib(tableElm, 'width') && !shouldStyleWithCss(editor)) {
  8280. attrs.width = removePxSuffix(data.width);
  8281. } else {
  8282. styles.width = addPxSuffix(data.width);
  8283. }
  8284. if (shouldStyleWithCss(editor)) {
  8285. styles['border-width'] = addPxSuffix(data.border);
  8286. styles['border-spacing'] = addPxSuffix(data.cellspacing);
  8287. } else {
  8288. attrs.border = data.border;
  8289. attrs.cellpadding = data.cellpadding;
  8290. attrs.cellspacing = data.cellspacing;
  8291. }
  8292. if (shouldStyleWithCss(editor) && tableElm.children) {
  8293. for (var i = 0; i < tableElm.children.length; i++) {
  8294. styleTDTH(dom, tableElm.children[i], {
  8295. 'border-width': addPxSuffix(data.border),
  8296. 'padding': addPxSuffix(data.cellpadding)
  8297. });
  8298. if (hasAdvancedTableTab(editor)) {
  8299. styleTDTH(dom, tableElm.children[i], { 'border-color': data.bordercolor });
  8300. }
  8301. }
  8302. }
  8303. if (hasAdvancedTableTab(editor)) {
  8304. styles['background-color'] = data.backgroundcolor;
  8305. styles['border-color'] = data.bordercolor;
  8306. styles['border-style'] = data.borderstyle;
  8307. }
  8308. attrs.style = dom.serializeStyle(__assign(__assign({}, getDefaultStyles(editor)), styles));
  8309. dom.setAttribs(tableElm, __assign(__assign({}, getDefaultAttributes(editor)), attrs));
  8310. };
  8311. var onSubmitTableForm = function (editor, tableElm, oldData, api) {
  8312. var dom = editor.dom;
  8313. var data = api.getData();
  8314. var modifiedData = filter$1(data, function (value, key) {
  8315. return oldData[key] !== value;
  8316. });
  8317. api.close();
  8318. if (data.class === '') {
  8319. delete data.class;
  8320. }
  8321. editor.undoManager.transact(function () {
  8322. if (!tableElm) {
  8323. var cols = parseInt(data.cols, 10) || 1;
  8324. var rows = parseInt(data.rows, 10) || 1;
  8325. tableElm = insert(editor, cols, rows, 0, 0);
  8326. }
  8327. if (size(modifiedData) > 0) {
  8328. applyDataToElement(editor, tableElm, data);
  8329. var captionElm = dom.select('caption', tableElm)[0];
  8330. if (captionElm && !data.caption || !captionElm && data.caption) {
  8331. editor.execCommand('mceTableToggleCaption');
  8332. }
  8333. if (data.align === '') {
  8334. unApplyAlign(editor, tableElm);
  8335. } else {
  8336. applyAlign(editor, tableElm, data.align);
  8337. }
  8338. }
  8339. editor.focus();
  8340. editor.addVisual();
  8341. if (size(modifiedData) > 0) {
  8342. var captionModified = has$1(modifiedData, 'caption');
  8343. var styleModified = captionModified ? size(modifiedData) > 1 : true;
  8344. fireTableModified(editor, tableElm, {
  8345. structure: captionModified,
  8346. style: styleModified
  8347. });
  8348. }
  8349. });
  8350. };
  8351. var open = function (editor, insertNewTable) {
  8352. var dom = editor.dom;
  8353. var tableElm;
  8354. var data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
  8355. if (insertNewTable === false) {
  8356. tableElm = dom.getParent(editor.selection.getStart(), 'table', editor.getBody());
  8357. if (tableElm) {
  8358. data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
  8359. } else {
  8360. if (hasAdvancedTableTab(editor)) {
  8361. data.borderstyle = '';
  8362. data.bordercolor = '';
  8363. data.backgroundcolor = '';
  8364. }
  8365. }
  8366. } else {
  8367. data.cols = '1';
  8368. data.rows = '1';
  8369. if (hasAdvancedTableTab(editor)) {
  8370. data.borderstyle = '';
  8371. data.bordercolor = '';
  8372. data.backgroundcolor = '';
  8373. }
  8374. }
  8375. var classes = buildListItems(getTableClassList(editor));
  8376. if (classes.length > 0) {
  8377. if (data.class) {
  8378. data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
  8379. }
  8380. }
  8381. var generalPanel = {
  8382. type: 'grid',
  8383. columns: 2,
  8384. items: getItems(editor, classes, insertNewTable)
  8385. };
  8386. var nonAdvancedForm = function () {
  8387. return {
  8388. type: 'panel',
  8389. items: [generalPanel]
  8390. };
  8391. };
  8392. var advancedForm = function () {
  8393. return {
  8394. type: 'tabpanel',
  8395. tabs: [
  8396. {
  8397. title: 'General',
  8398. name: 'general',
  8399. items: [generalPanel]
  8400. },
  8401. getAdvancedTab(editor, 'table')
  8402. ]
  8403. };
  8404. };
  8405. var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
  8406. editor.windowManager.open({
  8407. title: 'Table Properties',
  8408. size: 'normal',
  8409. body: dialogBody,
  8410. onSubmit: curry(onSubmitTableForm, editor, tableElm, data),
  8411. buttons: [
  8412. {
  8413. type: 'cancel',
  8414. name: 'cancel',
  8415. text: 'Cancel'
  8416. },
  8417. {
  8418. type: 'submit',
  8419. name: 'save',
  8420. text: 'Save',
  8421. primary: true
  8422. }
  8423. ],
  8424. initialData: data
  8425. });
  8426. };
  8427. var getSelectionStartCellOrCaption = function (editor) {
  8428. return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  8429. };
  8430. var getSelectionStartCell = function (editor) {
  8431. return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
  8432. };
  8433. var registerCommands = function (editor, actions, cellSelection, selections, clipboard) {
  8434. var isRoot = getIsRoot(editor);
  8435. var eraseTable = function () {
  8436. return getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8437. table(cellOrCaption, isRoot).filter(not(isRoot)).each(function (table) {
  8438. var cursor = SugarElement.fromText('');
  8439. after$5(table, cursor);
  8440. remove$5(table);
  8441. if (editor.dom.isEmpty(editor.getBody())) {
  8442. editor.setContent('');
  8443. editor.selection.setCursorLocation();
  8444. } else {
  8445. var rng = editor.dom.createRng();
  8446. rng.setStart(cursor.dom, 0);
  8447. rng.setEnd(cursor.dom, 0);
  8448. editor.selection.setRng(rng);
  8449. editor.nodeChanged();
  8450. }
  8451. });
  8452. });
  8453. };
  8454. var setSizingMode = function (sizing) {
  8455. return getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8456. var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
  8457. if (!isForcedSizing) {
  8458. table(cellOrCaption, isRoot).each(function (table) {
  8459. if (sizing === 'relative' && !isPercentSizing(table)) {
  8460. enforcePercentage(table);
  8461. } else if (sizing === 'fixed' && !isPixelSizing(table)) {
  8462. enforcePixels(table);
  8463. } else if (sizing === 'responsive' && !isNoneSizing(table)) {
  8464. enforceNone(table);
  8465. }
  8466. removeDataStyle(table);
  8467. fireTableModified(editor, table.dom, structureModified);
  8468. });
  8469. }
  8470. });
  8471. };
  8472. var getTableFromCell = function (cell) {
  8473. return table(cell, isRoot);
  8474. };
  8475. var performActionOnSelection = function (action) {
  8476. return getSelectionStartCell(editor).bind(function (cell) {
  8477. return getTableFromCell(cell).map(function (table) {
  8478. return action(table, cell);
  8479. });
  8480. });
  8481. };
  8482. var toggleTableClass = function (_ui, clazz) {
  8483. performActionOnSelection(function (table) {
  8484. editor.formatter.toggle('tableclass', { value: clazz }, table.dom);
  8485. fireTableModified(editor, table.dom, styleModified);
  8486. });
  8487. };
  8488. var toggleTableCellClass = function (_ui, clazz) {
  8489. performActionOnSelection(function (table) {
  8490. var selectedCells = getCellsFromSelection(selections);
  8491. var allHaveClass = forall(selectedCells, function (cell) {
  8492. return editor.formatter.match('tablecellclass', { value: clazz }, cell.dom);
  8493. });
  8494. var formatterAction = allHaveClass ? editor.formatter.remove : editor.formatter.apply;
  8495. each$2(selectedCells, function (cell) {
  8496. return formatterAction('tablecellclass', { value: clazz }, cell.dom);
  8497. });
  8498. fireTableModified(editor, table.dom, styleModified);
  8499. });
  8500. };
  8501. var toggleCaption = function () {
  8502. getSelectionStartCellOrCaption(editor).each(function (cellOrCaption) {
  8503. table(cellOrCaption, isRoot).each(function (table) {
  8504. child$1(table, 'caption').fold(function () {
  8505. var caption = SugarElement.fromTag('caption');
  8506. append$1(caption, SugarElement.fromText('Caption'));
  8507. appendAt(table, caption, 0);
  8508. editor.selection.setCursorLocation(caption.dom, 0);
  8509. }, function (caption) {
  8510. if (isTag('caption')(cellOrCaption)) {
  8511. one('td', table).each(function (td) {
  8512. return editor.selection.setCursorLocation(td.dom, 0);
  8513. });
  8514. }
  8515. remove$5(caption);
  8516. });
  8517. fireTableModified(editor, table.dom, structureModified);
  8518. });
  8519. });
  8520. };
  8521. var postExecute = function (_data) {
  8522. editor.focus();
  8523. };
  8524. var actOnSelection = function (execute, noEvents) {
  8525. if (noEvents === void 0) {
  8526. noEvents = false;
  8527. }
  8528. return performActionOnSelection(function (table, startCell) {
  8529. var targets = forMenu(selections, table, startCell);
  8530. execute(table, targets, noEvents).each(postExecute);
  8531. });
  8532. };
  8533. var copyRowSelection = function () {
  8534. return performActionOnSelection(function (table, startCell) {
  8535. var targets = forMenu(selections, table, startCell);
  8536. var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), Optional.none());
  8537. return copyRows(table, targets, generators);
  8538. });
  8539. };
  8540. var copyColSelection = function () {
  8541. return performActionOnSelection(function (table, startCell) {
  8542. var targets = forMenu(selections, table, startCell);
  8543. return copyCols(table, targets);
  8544. });
  8545. };
  8546. var pasteOnSelection = function (execute, getRows) {
  8547. return getRows().each(function (rows) {
  8548. var clonedRows = map$1(rows, function (row) {
  8549. return deep(row);
  8550. });
  8551. performActionOnSelection(function (table, startCell) {
  8552. var generators = paste$1(SugarElement.fromDom(editor.getDoc()));
  8553. var targets = pasteRows(selections, startCell, clonedRows, generators);
  8554. execute(table, targets).each(postExecute);
  8555. });
  8556. });
  8557. };
  8558. var actOnType = function (getAction) {
  8559. return function (_ui, args) {
  8560. return get$c(args, 'type').each(function (type) {
  8561. actOnSelection(getAction(type), args.no_events);
  8562. });
  8563. };
  8564. };
  8565. each$1({
  8566. mceTableSplitCells: function () {
  8567. return actOnSelection(actions.unmergeCells);
  8568. },
  8569. mceTableMergeCells: function () {
  8570. return actOnSelection(actions.mergeCells);
  8571. },
  8572. mceTableInsertRowBefore: function () {
  8573. return actOnSelection(actions.insertRowsBefore);
  8574. },
  8575. mceTableInsertRowAfter: function () {
  8576. return actOnSelection(actions.insertRowsAfter);
  8577. },
  8578. mceTableInsertColBefore: function () {
  8579. return actOnSelection(actions.insertColumnsBefore);
  8580. },
  8581. mceTableInsertColAfter: function () {
  8582. return actOnSelection(actions.insertColumnsAfter);
  8583. },
  8584. mceTableDeleteCol: function () {
  8585. return actOnSelection(actions.deleteColumn);
  8586. },
  8587. mceTableDeleteRow: function () {
  8588. return actOnSelection(actions.deleteRow);
  8589. },
  8590. mceTableCutCol: function () {
  8591. return copyColSelection().each(function (selection) {
  8592. clipboard.setColumns(selection);
  8593. actOnSelection(actions.deleteColumn);
  8594. });
  8595. },
  8596. mceTableCutRow: function () {
  8597. return copyRowSelection().each(function (selection) {
  8598. clipboard.setRows(selection);
  8599. actOnSelection(actions.deleteRow);
  8600. });
  8601. },
  8602. mceTableCopyCol: function () {
  8603. return copyColSelection().each(function (selection) {
  8604. return clipboard.setColumns(selection);
  8605. });
  8606. },
  8607. mceTableCopyRow: function () {
  8608. return copyRowSelection().each(function (selection) {
  8609. return clipboard.setRows(selection);
  8610. });
  8611. },
  8612. mceTablePasteColBefore: function () {
  8613. return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
  8614. },
  8615. mceTablePasteColAfter: function () {
  8616. return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
  8617. },
  8618. mceTablePasteRowBefore: function () {
  8619. return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
  8620. },
  8621. mceTablePasteRowAfter: function () {
  8622. return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
  8623. },
  8624. mceTableDelete: eraseTable,
  8625. mceTableCellToggleClass: toggleTableCellClass,
  8626. mceTableToggleClass: toggleTableClass,
  8627. mceTableToggleCaption: toggleCaption,
  8628. mceTableSizingMode: function (_ui, sizing) {
  8629. return setSizingMode(sizing);
  8630. },
  8631. mceTableCellType: actOnType(function (type) {
  8632. return type === 'th' ? actions.makeCellsHeader : actions.unmakeCellsHeader;
  8633. }),
  8634. mceTableColType: actOnType(function (type) {
  8635. return type === 'th' ? actions.makeColumnsHeader : actions.unmakeColumnsHeader;
  8636. }),
  8637. mceTableRowType: actOnType(function (type) {
  8638. switch (type) {
  8639. case 'header':
  8640. return actions.makeRowsHeader;
  8641. case 'footer':
  8642. return actions.makeRowsFooter;
  8643. default:
  8644. return actions.makeRowsBody;
  8645. }
  8646. })
  8647. }, function (func, name) {
  8648. return editor.addCommand(name, func);
  8649. });
  8650. each$1({
  8651. mceTableProps: curry(open, editor, false),
  8652. mceTableRowProps: curry(open$1, editor),
  8653. mceTableCellProps: curry(open$2, editor, selections)
  8654. }, function (func, name) {
  8655. return editor.addCommand(name, function () {
  8656. return func();
  8657. });
  8658. });
  8659. editor.addCommand('mceInsertTable', function (_ui, args) {
  8660. if (isObject(args) && keys(args).length > 0) {
  8661. insertTableWithDataValidation(editor, args.rows, args.columns, args.options, 'Invalid values for mceInsertTable - rows and columns values are required to insert a table.');
  8662. } else {
  8663. open(editor, true);
  8664. }
  8665. });
  8666. editor.addCommand('mceTableApplyCellStyle', function (_ui, args) {
  8667. var getFormatName = function (style) {
  8668. return 'tablecell' + style.toLowerCase().replace('-', '');
  8669. };
  8670. if (!isObject(args)) {
  8671. return;
  8672. }
  8673. var cells = getCellsFromSelection(selections);
  8674. if (cells.length === 0) {
  8675. return;
  8676. }
  8677. var validArgs = filter$1(args, function (value, style) {
  8678. return editor.formatter.has(getFormatName(style)) && isString(value);
  8679. });
  8680. if (isEmpty(validArgs)) {
  8681. return;
  8682. }
  8683. each$1(validArgs, function (value, style) {
  8684. each$2(cells, function (cell) {
  8685. DomModifier.normal(editor, cell.dom).setFormat(getFormatName(style), value);
  8686. });
  8687. });
  8688. getTableFromCell(cells[0]).each(function (table) {
  8689. return fireTableModified(editor, table.dom, styleModified);
  8690. });
  8691. });
  8692. };
  8693. var registerQueryCommands = function (editor, actions, selections) {
  8694. var isRoot = getIsRoot(editor);
  8695. var lookupOnSelection = function (action) {
  8696. return getSelectionCell(getSelectionStart(editor)).bind(function (cell) {
  8697. return table(cell, isRoot).map(function (table) {
  8698. var targets = forMenu(selections, table, cell);
  8699. return action(table, targets);
  8700. });
  8701. }).getOr('');
  8702. };
  8703. each$1({
  8704. mceTableRowType: function () {
  8705. return lookupOnSelection(actions.getTableRowType);
  8706. },
  8707. mceTableCellType: function () {
  8708. return lookupOnSelection(actions.getTableCellType);
  8709. },
  8710. mceTableColType: function () {
  8711. return lookupOnSelection(actions.getTableColType);
  8712. }
  8713. }, function (func, name) {
  8714. return editor.addQueryValueHandler(name, func);
  8715. });
  8716. };
  8717. var Clipboard = function () {
  8718. var rows = value();
  8719. var cols = value();
  8720. return {
  8721. getRows: rows.get,
  8722. setRows: function (r) {
  8723. r.fold(rows.clear, rows.set);
  8724. cols.clear();
  8725. },
  8726. clearRows: rows.clear,
  8727. getColumns: cols.get,
  8728. setColumns: function (c) {
  8729. c.fold(cols.clear, cols.set);
  8730. rows.clear();
  8731. },
  8732. clearColumns: cols.clear
  8733. };
  8734. };
  8735. var genericBase = {
  8736. remove_similar: true,
  8737. inherit: false
  8738. };
  8739. var cellBase = __assign({ selector: 'td,th' }, genericBase);
  8740. var cellFormats = {
  8741. tablecellbackgroundcolor: __assign({ styles: { backgroundColor: '%value' } }, cellBase),
  8742. tablecellverticalalign: __assign({ styles: { 'vertical-align': '%value' } }, cellBase),
  8743. tablecellbordercolor: __assign({ styles: { borderColor: '%value' } }, cellBase),
  8744. tablecellclass: __assign({ classes: ['%value'] }, cellBase),
  8745. tableclass: __assign({
  8746. selector: 'table',
  8747. classes: ['%value']
  8748. }, genericBase),
  8749. tablecellborderstyle: __assign({ styles: { borderStyle: '%value' } }, cellBase),
  8750. tablecellborderwidth: __assign({ styles: { borderWidth: '%value' } }, cellBase)
  8751. };
  8752. var registerFormats = function (editor) {
  8753. editor.formatter.register(cellFormats);
  8754. };
  8755. var adt$5 = Adt.generate([
  8756. { none: ['current'] },
  8757. { first: ['current'] },
  8758. {
  8759. middle: [
  8760. 'current',
  8761. 'target'
  8762. ]
  8763. },
  8764. { last: ['current'] }
  8765. ]);
  8766. var none = function (current) {
  8767. if (current === void 0) {
  8768. current = undefined;
  8769. }
  8770. return adt$5.none(current);
  8771. };
  8772. var CellLocation = __assign(__assign({}, adt$5), { none: none });
  8773. var walk = function (all, current, index, direction, isEligible) {
  8774. if (isEligible === void 0) {
  8775. isEligible = always;
  8776. }
  8777. var forwards = direction === 1;
  8778. if (!forwards && index <= 0) {
  8779. return CellLocation.first(all[0]);
  8780. } else if (forwards && index >= all.length - 1) {
  8781. return CellLocation.last(all[all.length - 1]);
  8782. } else {
  8783. var newIndex = index + direction;
  8784. var elem = all[newIndex];
  8785. return isEligible(elem) ? CellLocation.middle(current, elem) : walk(all, current, newIndex, direction, isEligible);
  8786. }
  8787. };
  8788. var detect$1 = function (current, isRoot) {
  8789. return table(current, isRoot).bind(function (table) {
  8790. var all = cells$1(table);
  8791. var index = findIndex(all, function (x) {
  8792. return eq$1(current, x);
  8793. });
  8794. return index.map(function (index) {
  8795. return {
  8796. index: index,
  8797. all: all
  8798. };
  8799. });
  8800. });
  8801. };
  8802. var next = function (current, isEligible, isRoot) {
  8803. var detection = detect$1(current, isRoot);
  8804. return detection.fold(function () {
  8805. return CellLocation.none(current);
  8806. }, function (info) {
  8807. return walk(info.all, current, info.index, 1, isEligible);
  8808. });
  8809. };
  8810. var prev = function (current, isEligible, isRoot) {
  8811. var detection = detect$1(current, isRoot);
  8812. return detection.fold(function () {
  8813. return CellLocation.none();
  8814. }, function (info) {
  8815. return walk(info.all, current, info.index, -1, isEligible);
  8816. });
  8817. };
  8818. var create$2 = function (start, soffset, finish, foffset) {
  8819. return {
  8820. start: start,
  8821. soffset: soffset,
  8822. finish: finish,
  8823. foffset: foffset
  8824. };
  8825. };
  8826. var SimRange = { create: create$2 };
  8827. var adt$4 = Adt.generate([
  8828. { before: ['element'] },
  8829. {
  8830. on: [
  8831. 'element',
  8832. 'offset'
  8833. ]
  8834. },
  8835. { after: ['element'] }
  8836. ]);
  8837. var cata$1 = function (subject, onBefore, onOn, onAfter) {
  8838. return subject.fold(onBefore, onOn, onAfter);
  8839. };
  8840. var getStart$1 = function (situ) {
  8841. return situ.fold(identity, identity, identity);
  8842. };
  8843. var before$2 = adt$4.before;
  8844. var on = adt$4.on;
  8845. var after$3 = adt$4.after;
  8846. var Situ = {
  8847. before: before$2,
  8848. on: on,
  8849. after: after$3,
  8850. cata: cata$1,
  8851. getStart: getStart$1
  8852. };
  8853. var adt$3 = Adt.generate([
  8854. { domRange: ['rng'] },
  8855. {
  8856. relative: [
  8857. 'startSitu',
  8858. 'finishSitu'
  8859. ]
  8860. },
  8861. {
  8862. exact: [
  8863. 'start',
  8864. 'soffset',
  8865. 'finish',
  8866. 'foffset'
  8867. ]
  8868. }
  8869. ]);
  8870. var exactFromRange = function (simRange) {
  8871. return adt$3.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  8872. };
  8873. var getStart = function (selection) {
  8874. return selection.match({
  8875. domRange: function (rng) {
  8876. return SugarElement.fromDom(rng.startContainer);
  8877. },
  8878. relative: function (startSitu, _finishSitu) {
  8879. return Situ.getStart(startSitu);
  8880. },
  8881. exact: function (start, _soffset, _finish, _foffset) {
  8882. return start;
  8883. }
  8884. });
  8885. };
  8886. var domRange = adt$3.domRange;
  8887. var relative = adt$3.relative;
  8888. var exact = adt$3.exact;
  8889. var getWin = function (selection) {
  8890. var start = getStart(selection);
  8891. return defaultView(start);
  8892. };
  8893. var range = SimRange.create;
  8894. var SimSelection = {
  8895. domRange: domRange,
  8896. relative: relative,
  8897. exact: exact,
  8898. exactFromRange: exactFromRange,
  8899. getWin: getWin,
  8900. range: range
  8901. };
  8902. var selectNode = function (win, element) {
  8903. var rng = win.document.createRange();
  8904. rng.selectNode(element.dom);
  8905. return rng;
  8906. };
  8907. var selectNodeContents = function (win, element) {
  8908. var rng = win.document.createRange();
  8909. selectNodeContentsUsing(rng, element);
  8910. return rng;
  8911. };
  8912. var selectNodeContentsUsing = function (rng, element) {
  8913. return rng.selectNodeContents(element.dom);
  8914. };
  8915. var setStart = function (rng, situ) {
  8916. situ.fold(function (e) {
  8917. rng.setStartBefore(e.dom);
  8918. }, function (e, o) {
  8919. rng.setStart(e.dom, o);
  8920. }, function (e) {
  8921. rng.setStartAfter(e.dom);
  8922. });
  8923. };
  8924. var setFinish = function (rng, situ) {
  8925. situ.fold(function (e) {
  8926. rng.setEndBefore(e.dom);
  8927. }, function (e, o) {
  8928. rng.setEnd(e.dom, o);
  8929. }, function (e) {
  8930. rng.setEndAfter(e.dom);
  8931. });
  8932. };
  8933. var relativeToNative = function (win, startSitu, finishSitu) {
  8934. var range = win.document.createRange();
  8935. setStart(range, startSitu);
  8936. setFinish(range, finishSitu);
  8937. return range;
  8938. };
  8939. var exactToNative = function (win, start, soffset, finish, foffset) {
  8940. var rng = win.document.createRange();
  8941. rng.setStart(start.dom, soffset);
  8942. rng.setEnd(finish.dom, foffset);
  8943. return rng;
  8944. };
  8945. var toRect = function (rect) {
  8946. return {
  8947. left: rect.left,
  8948. top: rect.top,
  8949. right: rect.right,
  8950. bottom: rect.bottom,
  8951. width: rect.width,
  8952. height: rect.height
  8953. };
  8954. };
  8955. var getFirstRect$1 = function (rng) {
  8956. var rects = rng.getClientRects();
  8957. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  8958. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  8959. };
  8960. var adt$2 = Adt.generate([
  8961. {
  8962. ltr: [
  8963. 'start',
  8964. 'soffset',
  8965. 'finish',
  8966. 'foffset'
  8967. ]
  8968. },
  8969. {
  8970. rtl: [
  8971. 'start',
  8972. 'soffset',
  8973. 'finish',
  8974. 'foffset'
  8975. ]
  8976. }
  8977. ]);
  8978. var fromRange = function (win, type, range) {
  8979. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  8980. };
  8981. var getRanges = function (win, selection) {
  8982. return selection.match({
  8983. domRange: function (rng) {
  8984. return {
  8985. ltr: constant(rng),
  8986. rtl: Optional.none
  8987. };
  8988. },
  8989. relative: function (startSitu, finishSitu) {
  8990. return {
  8991. ltr: cached(function () {
  8992. return relativeToNative(win, startSitu, finishSitu);
  8993. }),
  8994. rtl: cached(function () {
  8995. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  8996. })
  8997. };
  8998. },
  8999. exact: function (start, soffset, finish, foffset) {
  9000. return {
  9001. ltr: cached(function () {
  9002. return exactToNative(win, start, soffset, finish, foffset);
  9003. }),
  9004. rtl: cached(function () {
  9005. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  9006. })
  9007. };
  9008. }
  9009. });
  9010. };
  9011. var doDiagnose = function (win, ranges) {
  9012. var rng = ranges.ltr();
  9013. if (rng.collapsed) {
  9014. var reversed = ranges.rtl().filter(function (rev) {
  9015. return rev.collapsed === false;
  9016. });
  9017. return reversed.map(function (rev) {
  9018. return adt$2.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  9019. }).getOrThunk(function () {
  9020. return fromRange(win, adt$2.ltr, rng);
  9021. });
  9022. } else {
  9023. return fromRange(win, adt$2.ltr, rng);
  9024. }
  9025. };
  9026. var diagnose = function (win, selection) {
  9027. var ranges = getRanges(win, selection);
  9028. return doDiagnose(win, ranges);
  9029. };
  9030. var asLtrRange = function (win, selection) {
  9031. var diagnosis = diagnose(win, selection);
  9032. return diagnosis.match({
  9033. ltr: function (start, soffset, finish, foffset) {
  9034. var rng = win.document.createRange();
  9035. rng.setStart(start.dom, soffset);
  9036. rng.setEnd(finish.dom, foffset);
  9037. return rng;
  9038. },
  9039. rtl: function (start, soffset, finish, foffset) {
  9040. var rng = win.document.createRange();
  9041. rng.setStart(finish.dom, foffset);
  9042. rng.setEnd(start.dom, soffset);
  9043. return rng;
  9044. }
  9045. });
  9046. };
  9047. adt$2.ltr;
  9048. adt$2.rtl;
  9049. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  9050. if (length === 0) {
  9051. return 0;
  9052. } else if (x === maxX) {
  9053. return length - 1;
  9054. }
  9055. var xDelta = maxX;
  9056. for (var i = 1; i < length; i++) {
  9057. var rect = rectForOffset(i);
  9058. var curDeltaX = Math.abs(x - rect.left);
  9059. if (y <= rect.bottom) {
  9060. if (y < rect.top || curDeltaX > xDelta) {
  9061. return i - 1;
  9062. } else {
  9063. xDelta = curDeltaX;
  9064. }
  9065. }
  9066. }
  9067. return 0;
  9068. };
  9069. var inRect = function (rect, x, y) {
  9070. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  9071. };
  9072. var locateOffset = function (doc, textnode, x, y, rect) {
  9073. var rangeForOffset = function (o) {
  9074. var r = doc.dom.createRange();
  9075. r.setStart(textnode.dom, o);
  9076. r.collapse(true);
  9077. return r;
  9078. };
  9079. var rectForOffset = function (o) {
  9080. var r = rangeForOffset(o);
  9081. return r.getBoundingClientRect();
  9082. };
  9083. var length = get$9(textnode).length;
  9084. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  9085. return rangeForOffset(offset);
  9086. };
  9087. var locate$1 = function (doc, node, x, y) {
  9088. var r = doc.dom.createRange();
  9089. r.selectNode(node.dom);
  9090. var rects = r.getClientRects();
  9091. var foundRect = findMap(rects, function (rect) {
  9092. return inRect(rect, x, y) ? Optional.some(rect) : Optional.none();
  9093. });
  9094. return foundRect.map(function (rect) {
  9095. return locateOffset(doc, node, x, y, rect);
  9096. });
  9097. };
  9098. var searchInChildren = function (doc, node, x, y) {
  9099. var r = doc.dom.createRange();
  9100. var nodes = children$3(node);
  9101. return findMap(nodes, function (n) {
  9102. r.selectNode(n.dom);
  9103. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Optional.none();
  9104. });
  9105. };
  9106. var locateNode = function (doc, node, x, y) {
  9107. return isText(node) ? locate$1(doc, node, x, y) : searchInChildren(doc, node, x, y);
  9108. };
  9109. var locate = function (doc, node, x, y) {
  9110. var r = doc.dom.createRange();
  9111. r.selectNode(node.dom);
  9112. var rect = r.getBoundingClientRect();
  9113. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  9114. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  9115. return locateNode(doc, node, boundedX, boundedY);
  9116. };
  9117. var COLLAPSE_TO_LEFT = true;
  9118. var COLLAPSE_TO_RIGHT = false;
  9119. var getCollapseDirection = function (rect, x) {
  9120. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  9121. };
  9122. var createCollapsedNode = function (doc, target, collapseDirection) {
  9123. var r = doc.dom.createRange();
  9124. r.selectNode(target.dom);
  9125. r.collapse(collapseDirection);
  9126. return r;
  9127. };
  9128. var locateInElement = function (doc, node, x) {
  9129. var cursorRange = doc.dom.createRange();
  9130. cursorRange.selectNode(node.dom);
  9131. var rect = cursorRange.getBoundingClientRect();
  9132. var collapseDirection = getCollapseDirection(rect, x);
  9133. var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
  9134. return f(node).map(function (target) {
  9135. return createCollapsedNode(doc, target, collapseDirection);
  9136. });
  9137. };
  9138. var locateInEmpty = function (doc, node, x) {
  9139. var rect = node.dom.getBoundingClientRect();
  9140. var collapseDirection = getCollapseDirection(rect, x);
  9141. return Optional.some(createCollapsedNode(doc, node, collapseDirection));
  9142. };
  9143. var search = function (doc, node, x) {
  9144. var f = children$3(node).length === 0 ? locateInEmpty : locateInElement;
  9145. return f(doc, node, x);
  9146. };
  9147. var caretPositionFromPoint = function (doc, x, y) {
  9148. var _a, _b;
  9149. return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y)).bind(function (pos) {
  9150. if (pos.offsetNode === null) {
  9151. return Optional.none();
  9152. }
  9153. var r = doc.dom.createRange();
  9154. r.setStart(pos.offsetNode, pos.offset);
  9155. r.collapse();
  9156. return Optional.some(r);
  9157. });
  9158. };
  9159. var caretRangeFromPoint = function (doc, x, y) {
  9160. var _a, _b;
  9161. return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y));
  9162. };
  9163. var searchTextNodes = function (doc, node, x, y) {
  9164. var r = doc.dom.createRange();
  9165. r.selectNode(node.dom);
  9166. var rect = r.getBoundingClientRect();
  9167. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  9168. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  9169. return locate(doc, node, boundedX, boundedY);
  9170. };
  9171. var searchFromPoint = function (doc, x, y) {
  9172. return SugarElement.fromPoint(doc, x, y).bind(function (elem) {
  9173. var fallback = function () {
  9174. return search(doc, elem, x);
  9175. };
  9176. return children$3(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  9177. });
  9178. };
  9179. var availableSearch = function () {
  9180. if (document.caretPositionFromPoint) {
  9181. return caretPositionFromPoint;
  9182. } else if (document.caretRangeFromPoint) {
  9183. return caretRangeFromPoint;
  9184. } else {
  9185. return searchFromPoint;
  9186. }
  9187. }();
  9188. var fromPoint = function (win, x, y) {
  9189. var doc = SugarElement.fromDom(win.document);
  9190. return availableSearch(doc, x, y).map(function (rng) {
  9191. return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
  9192. });
  9193. };
  9194. var beforeSpecial = function (element, offset) {
  9195. var name$1 = name(element);
  9196. if ('input' === name$1) {
  9197. return Situ.after(element);
  9198. } else if (!contains$2([
  9199. 'br',
  9200. 'img'
  9201. ], name$1)) {
  9202. return Situ.on(element, offset);
  9203. } else {
  9204. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9205. }
  9206. };
  9207. var preprocessRelative = function (startSitu, finishSitu) {
  9208. var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9209. var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9210. return SimSelection.relative(start, finish);
  9211. };
  9212. var preprocessExact = function (start, soffset, finish, foffset) {
  9213. var startSitu = beforeSpecial(start, soffset);
  9214. var finishSitu = beforeSpecial(finish, foffset);
  9215. return SimSelection.relative(startSitu, finishSitu);
  9216. };
  9217. var preprocess = function (selection) {
  9218. return selection.match({
  9219. domRange: function (rng) {
  9220. var start = SugarElement.fromDom(rng.startContainer);
  9221. var finish = SugarElement.fromDom(rng.endContainer);
  9222. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  9223. },
  9224. relative: preprocessRelative,
  9225. exact: preprocessExact
  9226. });
  9227. };
  9228. var makeRange = function (start, soffset, finish, foffset) {
  9229. var doc = owner(start);
  9230. var rng = doc.dom.createRange();
  9231. rng.setStart(start.dom, soffset);
  9232. rng.setEnd(finish.dom, foffset);
  9233. return rng;
  9234. };
  9235. var after$2 = function (start, soffset, finish, foffset) {
  9236. var r = makeRange(start, soffset, finish, foffset);
  9237. var same = eq$1(start, finish) && soffset === foffset;
  9238. return r.collapsed && !same;
  9239. };
  9240. var getNativeSelection = function (win) {
  9241. return Optional.from(win.getSelection());
  9242. };
  9243. var doSetNativeRange = function (win, rng) {
  9244. getNativeSelection(win).each(function (selection) {
  9245. selection.removeAllRanges();
  9246. selection.addRange(rng);
  9247. });
  9248. };
  9249. var doSetRange = function (win, start, soffset, finish, foffset) {
  9250. var rng = exactToNative(win, start, soffset, finish, foffset);
  9251. doSetNativeRange(win, rng);
  9252. };
  9253. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9254. selection.collapse(start.dom, soffset);
  9255. selection.extend(finish.dom, foffset);
  9256. };
  9257. var setRangeFromRelative = function (win, relative) {
  9258. return diagnose(win, relative).match({
  9259. ltr: function (start, soffset, finish, foffset) {
  9260. doSetRange(win, start, soffset, finish, foffset);
  9261. },
  9262. rtl: function (start, soffset, finish, foffset) {
  9263. getNativeSelection(win).each(function (selection) {
  9264. if (selection.setBaseAndExtent) {
  9265. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9266. } else if (selection.extend) {
  9267. try {
  9268. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9269. } catch (e) {
  9270. doSetRange(win, finish, foffset, start, soffset);
  9271. }
  9272. } else {
  9273. doSetRange(win, finish, foffset, start, soffset);
  9274. }
  9275. });
  9276. }
  9277. });
  9278. };
  9279. var setExact = function (win, start, soffset, finish, foffset) {
  9280. var relative = preprocessExact(start, soffset, finish, foffset);
  9281. setRangeFromRelative(win, relative);
  9282. };
  9283. var setRelative = function (win, startSitu, finishSitu) {
  9284. var relative = preprocessRelative(startSitu, finishSitu);
  9285. setRangeFromRelative(win, relative);
  9286. };
  9287. var toNative = function (selection) {
  9288. var win = SimSelection.getWin(selection).dom;
  9289. var getDomRange = function (start, soffset, finish, foffset) {
  9290. return exactToNative(win, start, soffset, finish, foffset);
  9291. };
  9292. var filtered = preprocess(selection);
  9293. return diagnose(win, filtered).match({
  9294. ltr: getDomRange,
  9295. rtl: getDomRange
  9296. });
  9297. };
  9298. var readRange = function (selection) {
  9299. if (selection.rangeCount > 0) {
  9300. var firstRng = selection.getRangeAt(0);
  9301. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9302. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9303. } else {
  9304. return Optional.none();
  9305. }
  9306. };
  9307. var doGetExact = function (selection) {
  9308. if (selection.anchorNode === null || selection.focusNode === null) {
  9309. return readRange(selection);
  9310. } else {
  9311. var anchor = SugarElement.fromDom(selection.anchorNode);
  9312. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9313. return after$2(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9314. }
  9315. };
  9316. var setToElement = function (win, element, selectNodeContents$1) {
  9317. if (selectNodeContents$1 === void 0) {
  9318. selectNodeContents$1 = true;
  9319. }
  9320. var rngGetter = selectNodeContents$1 ? selectNodeContents : selectNode;
  9321. var rng = rngGetter(win, element);
  9322. doSetNativeRange(win, rng);
  9323. };
  9324. var getExact = function (win) {
  9325. return getNativeSelection(win).filter(function (sel) {
  9326. return sel.rangeCount > 0;
  9327. }).bind(doGetExact);
  9328. };
  9329. var get$1 = function (win) {
  9330. return getExact(win).map(function (range) {
  9331. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9332. });
  9333. };
  9334. var getFirstRect = function (win, selection) {
  9335. var rng = asLtrRange(win, selection);
  9336. return getFirstRect$1(rng);
  9337. };
  9338. var getAtPoint = function (win, x, y) {
  9339. return fromPoint(win, x, y);
  9340. };
  9341. var clear = function (win) {
  9342. getNativeSelection(win).each(function (selection) {
  9343. return selection.removeAllRanges();
  9344. });
  9345. };
  9346. var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');
  9347. var forward = function (editor, isRoot, cell) {
  9348. return go$1(editor, isRoot, next(cell, isEditable$1));
  9349. };
  9350. var backward = function (editor, isRoot, cell) {
  9351. return go$1(editor, isRoot, prev(cell, isEditable$1));
  9352. };
  9353. var getCellFirstCursorPosition = function (editor, cell) {
  9354. var selection = SimSelection.exact(cell, 0, cell, 0);
  9355. return toNative(selection);
  9356. };
  9357. var go$1 = function (editor, isRoot, cell) {
  9358. return cell.fold(Optional.none, Optional.none, function (current, next) {
  9359. return first(next).map(function (cell) {
  9360. return getCellFirstCursorPosition(editor, cell);
  9361. });
  9362. }, function (current) {
  9363. editor.execCommand('mceTableInsertRowAfter');
  9364. return forward(editor, isRoot, current);
  9365. });
  9366. };
  9367. var rootElements = [
  9368. 'table',
  9369. 'li',
  9370. 'dl'
  9371. ];
  9372. var handle$1 = function (event, editor, cellSelection) {
  9373. if (event.keyCode === global$1.TAB) {
  9374. var body_1 = getBody(editor);
  9375. var isRoot_1 = function (element) {
  9376. var name$1 = name(element);
  9377. return eq$1(element, body_1) || contains$2(rootElements, name$1);
  9378. };
  9379. var rng = editor.selection.getRng();
  9380. var container = SugarElement.fromDom(event.shiftKey ? rng.startContainer : rng.endContainer);
  9381. cell(container, isRoot_1).each(function (cell) {
  9382. event.preventDefault();
  9383. table(cell, isRoot_1).each(cellSelection.clear);
  9384. editor.selection.collapse(event.shiftKey);
  9385. var navigation = event.shiftKey ? backward : forward;
  9386. var rng = navigation(editor, isRoot_1, cell);
  9387. rng.each(function (range) {
  9388. editor.selection.setRng(range);
  9389. });
  9390. });
  9391. }
  9392. };
  9393. var create$1 = function (selection, kill) {
  9394. return {
  9395. selection: selection,
  9396. kill: kill
  9397. };
  9398. };
  9399. var Response = { create: create$1 };
  9400. var create = function (start, soffset, finish, foffset) {
  9401. return {
  9402. start: Situ.on(start, soffset),
  9403. finish: Situ.on(finish, foffset)
  9404. };
  9405. };
  9406. var Situs = { create: create };
  9407. var convertToRange = function (win, selection) {
  9408. var rng = asLtrRange(win, selection);
  9409. return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
  9410. };
  9411. var makeSitus = Situs.create;
  9412. var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
  9413. if (!(eq$1(start, finish) && soffset === foffset)) {
  9414. return closest$1(start, 'td,th', isRoot).bind(function (s) {
  9415. return closest$1(finish, 'td,th', isRoot).bind(function (f) {
  9416. return detect(container, isRoot, s, f, selectRange);
  9417. });
  9418. });
  9419. } else {
  9420. return Optional.none();
  9421. }
  9422. };
  9423. var detect = function (container, isRoot, start, finish, selectRange) {
  9424. if (!eq$1(start, finish)) {
  9425. return identify(start, finish, isRoot).bind(function (cellSel) {
  9426. var boxes = cellSel.boxes.getOr([]);
  9427. if (boxes.length > 1) {
  9428. selectRange(container, boxes, cellSel.start, cellSel.finish);
  9429. return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
  9430. } else {
  9431. return Optional.none();
  9432. }
  9433. });
  9434. } else {
  9435. return Optional.none();
  9436. }
  9437. };
  9438. var update = function (rows, columns, container, selected, annotations) {
  9439. var updateSelection = function (newSels) {
  9440. annotations.clearBeforeUpdate(container);
  9441. annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
  9442. return newSels.boxes;
  9443. };
  9444. return shiftSelection(selected, rows, columns, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
  9445. };
  9446. var traverse = function (item, mode) {
  9447. return {
  9448. item: item,
  9449. mode: mode
  9450. };
  9451. };
  9452. var backtrack = function (universe, item, _direction, transition) {
  9453. if (transition === void 0) {
  9454. transition = sidestep;
  9455. }
  9456. return universe.property().parent(item).map(function (p) {
  9457. return traverse(p, transition);
  9458. });
  9459. };
  9460. var sidestep = function (universe, item, direction, transition) {
  9461. if (transition === void 0) {
  9462. transition = advance;
  9463. }
  9464. return direction.sibling(universe, item).map(function (p) {
  9465. return traverse(p, transition);
  9466. });
  9467. };
  9468. var advance = function (universe, item, direction, transition) {
  9469. if (transition === void 0) {
  9470. transition = advance;
  9471. }
  9472. var children = universe.property().children(item);
  9473. var result = direction.first(children);
  9474. return result.map(function (r) {
  9475. return traverse(r, transition);
  9476. });
  9477. };
  9478. var successors = [
  9479. {
  9480. current: backtrack,
  9481. next: sidestep,
  9482. fallback: Optional.none()
  9483. },
  9484. {
  9485. current: sidestep,
  9486. next: advance,
  9487. fallback: Optional.some(backtrack)
  9488. },
  9489. {
  9490. current: advance,
  9491. next: advance,
  9492. fallback: Optional.some(sidestep)
  9493. }
  9494. ];
  9495. var go = function (universe, item, mode, direction, rules) {
  9496. if (rules === void 0) {
  9497. rules = successors;
  9498. }
  9499. var ruleOpt = find$1(rules, function (succ) {
  9500. return succ.current === mode;
  9501. });
  9502. return ruleOpt.bind(function (rule) {
  9503. return rule.current(universe, item, direction, rule.next).orThunk(function () {
  9504. return rule.fallback.bind(function (fb) {
  9505. return go(universe, item, fb, direction);
  9506. });
  9507. });
  9508. });
  9509. };
  9510. var left$1 = function () {
  9511. var sibling = function (universe, item) {
  9512. return universe.query().prevSibling(item);
  9513. };
  9514. var first = function (children) {
  9515. return children.length > 0 ? Optional.some(children[children.length - 1]) : Optional.none();
  9516. };
  9517. return {
  9518. sibling: sibling,
  9519. first: first
  9520. };
  9521. };
  9522. var right$1 = function () {
  9523. var sibling = function (universe, item) {
  9524. return universe.query().nextSibling(item);
  9525. };
  9526. var first = function (children) {
  9527. return children.length > 0 ? Optional.some(children[0]) : Optional.none();
  9528. };
  9529. return {
  9530. sibling: sibling,
  9531. first: first
  9532. };
  9533. };
  9534. var Walkers = {
  9535. left: left$1,
  9536. right: right$1
  9537. };
  9538. var hone = function (universe, item, predicate, mode, direction, isRoot) {
  9539. var next = go(universe, item, mode, direction);
  9540. return next.bind(function (n) {
  9541. if (isRoot(n.item)) {
  9542. return Optional.none();
  9543. } else {
  9544. return predicate(n.item) ? Optional.some(n.item) : hone(universe, n.item, predicate, n.mode, direction, isRoot);
  9545. }
  9546. });
  9547. };
  9548. var left = function (universe, item, predicate, isRoot) {
  9549. return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
  9550. };
  9551. var right = function (universe, item, predicate, isRoot) {
  9552. return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
  9553. };
  9554. var isLeaf = function (universe) {
  9555. return function (element) {
  9556. return universe.property().children(element).length === 0;
  9557. };
  9558. };
  9559. var before$1 = function (universe, item, isRoot) {
  9560. return seekLeft$1(universe, item, isLeaf(universe), isRoot);
  9561. };
  9562. var after$1 = function (universe, item, isRoot) {
  9563. return seekRight$1(universe, item, isLeaf(universe), isRoot);
  9564. };
  9565. var seekLeft$1 = left;
  9566. var seekRight$1 = right;
  9567. var universe = DomUniverse();
  9568. var before = function (element, isRoot) {
  9569. return before$1(universe, element, isRoot);
  9570. };
  9571. var after = function (element, isRoot) {
  9572. return after$1(universe, element, isRoot);
  9573. };
  9574. var seekLeft = function (element, predicate, isRoot) {
  9575. return seekLeft$1(universe, element, predicate, isRoot);
  9576. };
  9577. var seekRight = function (element, predicate, isRoot) {
  9578. return seekRight$1(universe, element, predicate, isRoot);
  9579. };
  9580. var ancestor = function (scope, predicate, isRoot) {
  9581. return ancestor$2(scope, predicate, isRoot).isSome();
  9582. };
  9583. var adt$1 = Adt.generate([
  9584. { none: ['message'] },
  9585. { success: [] },
  9586. { failedUp: ['cell'] },
  9587. { failedDown: ['cell'] }
  9588. ]);
  9589. var isOverlapping = function (bridge, before, after) {
  9590. var beforeBounds = bridge.getRect(before);
  9591. var afterBounds = bridge.getRect(after);
  9592. return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
  9593. };
  9594. var isRow = function (elem) {
  9595. return closest$1(elem, 'tr');
  9596. };
  9597. var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
  9598. return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
  9599. return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
  9600. if (!eq$1(afterCell, beforeCell)) {
  9601. return sharedOne(isRow, [
  9602. afterCell,
  9603. beforeCell
  9604. ]).fold(function () {
  9605. return isOverlapping(bridge, beforeCell, afterCell) ? adt$1.success() : failure(beforeCell);
  9606. }, function (_sharedRow) {
  9607. return failure(beforeCell);
  9608. });
  9609. } else {
  9610. return eq$1(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$1.none('in same cell');
  9611. }
  9612. });
  9613. }).getOr(adt$1.none('default'));
  9614. };
  9615. var cata = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
  9616. return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
  9617. };
  9618. var BeforeAfter = __assign(__assign({}, adt$1), {
  9619. verify: verify,
  9620. cata: cata
  9621. });
  9622. var inParent = function (parent, children, element, index) {
  9623. return {
  9624. parent: parent,
  9625. children: children,
  9626. element: element,
  9627. index: index
  9628. };
  9629. };
  9630. var indexInParent = function (element) {
  9631. return parent(element).bind(function (parent) {
  9632. var children = children$3(parent);
  9633. return indexOf(children, element).map(function (index) {
  9634. return inParent(parent, children, element, index);
  9635. });
  9636. });
  9637. };
  9638. var indexOf = function (elements, element) {
  9639. return findIndex(elements, curry(eq$1, element));
  9640. };
  9641. var isBr = function (elem) {
  9642. return name(elem) === 'br';
  9643. };
  9644. var gatherer = function (cand, gather, isRoot) {
  9645. return gather(cand, isRoot).bind(function (target) {
  9646. return isText(target) && get$9(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
  9647. });
  9648. };
  9649. var handleBr = function (isRoot, element, direction) {
  9650. return direction.traverse(element).orThunk(function () {
  9651. return gatherer(element, direction.gather, isRoot);
  9652. }).map(direction.relative);
  9653. };
  9654. var findBr = function (element, offset) {
  9655. return child$3(element, offset).filter(isBr).orThunk(function () {
  9656. return child$3(element, offset - 1).filter(isBr);
  9657. });
  9658. };
  9659. var handleParent = function (isRoot, element, offset, direction) {
  9660. return findBr(element, offset).bind(function (br) {
  9661. return direction.traverse(br).fold(function () {
  9662. return gatherer(br, direction.gather, isRoot).map(direction.relative);
  9663. }, function (adjacent) {
  9664. return indexInParent(adjacent).map(function (info) {
  9665. return Situ.on(info.parent, info.index);
  9666. });
  9667. });
  9668. });
  9669. };
  9670. var tryBr = function (isRoot, element, offset, direction) {
  9671. var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
  9672. return target.map(function (tgt) {
  9673. return {
  9674. start: tgt,
  9675. finish: tgt
  9676. };
  9677. });
  9678. };
  9679. var process = function (analysis) {
  9680. return BeforeAfter.cata(analysis, function (_message) {
  9681. return Optional.none();
  9682. }, function () {
  9683. return Optional.none();
  9684. }, function (cell) {
  9685. return Optional.some(point(cell, 0));
  9686. }, function (cell) {
  9687. return Optional.some(point(cell, getEnd(cell)));
  9688. });
  9689. };
  9690. var moveDown = function (caret, amount) {
  9691. return {
  9692. left: caret.left,
  9693. top: caret.top + amount,
  9694. right: caret.right,
  9695. bottom: caret.bottom + amount
  9696. };
  9697. };
  9698. var moveUp = function (caret, amount) {
  9699. return {
  9700. left: caret.left,
  9701. top: caret.top - amount,
  9702. right: caret.right,
  9703. bottom: caret.bottom - amount
  9704. };
  9705. };
  9706. var translate = function (caret, xDelta, yDelta) {
  9707. return {
  9708. left: caret.left + xDelta,
  9709. top: caret.top + yDelta,
  9710. right: caret.right + xDelta,
  9711. bottom: caret.bottom + yDelta
  9712. };
  9713. };
  9714. var getTop = function (caret) {
  9715. return caret.top;
  9716. };
  9717. var getBottom = function (caret) {
  9718. return caret.bottom;
  9719. };
  9720. var getPartialBox = function (bridge, element, offset) {
  9721. if (offset >= 0 && offset < getEnd(element)) {
  9722. return bridge.getRangedRect(element, offset, element, offset + 1);
  9723. } else if (offset > 0) {
  9724. return bridge.getRangedRect(element, offset - 1, element, offset);
  9725. }
  9726. return Optional.none();
  9727. };
  9728. var toCaret = function (rect) {
  9729. return {
  9730. left: rect.left,
  9731. top: rect.top,
  9732. right: rect.right,
  9733. bottom: rect.bottom
  9734. };
  9735. };
  9736. var getElemBox = function (bridge, element) {
  9737. return Optional.some(bridge.getRect(element));
  9738. };
  9739. var getBoxAt = function (bridge, element, offset) {
  9740. if (isElement(element)) {
  9741. return getElemBox(bridge, element).map(toCaret);
  9742. } else if (isText(element)) {
  9743. return getPartialBox(bridge, element, offset).map(toCaret);
  9744. } else {
  9745. return Optional.none();
  9746. }
  9747. };
  9748. var getEntireBox = function (bridge, element) {
  9749. if (isElement(element)) {
  9750. return getElemBox(bridge, element).map(toCaret);
  9751. } else if (isText(element)) {
  9752. return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
  9753. } else {
  9754. return Optional.none();
  9755. }
  9756. };
  9757. var JUMP_SIZE = 5;
  9758. var NUM_RETRIES = 100;
  9759. var adt = Adt.generate([
  9760. { none: [] },
  9761. { retry: ['caret'] }
  9762. ]);
  9763. var isOutside = function (caret, box) {
  9764. return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
  9765. };
  9766. var inOutsideBlock = function (bridge, element, caret) {
  9767. return closest$2(element, isBlock).fold(never, function (cell) {
  9768. return getEntireBox(bridge, cell).exists(function (box) {
  9769. return isOutside(caret, box);
  9770. });
  9771. });
  9772. };
  9773. var adjustDown = function (bridge, element, guessBox, original, caret) {
  9774. var lowerCaret = moveDown(caret, JUMP_SIZE);
  9775. if (Math.abs(guessBox.bottom - original.bottom) < 1) {
  9776. return adt.retry(lowerCaret);
  9777. } else if (guessBox.top > caret.bottom) {
  9778. return adt.retry(lowerCaret);
  9779. } else if (guessBox.top === caret.bottom) {
  9780. return adt.retry(moveDown(caret, 1));
  9781. } else {
  9782. return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt.none();
  9783. }
  9784. };
  9785. var adjustUp = function (bridge, element, guessBox, original, caret) {
  9786. var higherCaret = moveUp(caret, JUMP_SIZE);
  9787. if (Math.abs(guessBox.top - original.top) < 1) {
  9788. return adt.retry(higherCaret);
  9789. } else if (guessBox.bottom < caret.top) {
  9790. return adt.retry(higherCaret);
  9791. } else if (guessBox.bottom === caret.top) {
  9792. return adt.retry(moveUp(caret, 1));
  9793. } else {
  9794. return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt.none();
  9795. }
  9796. };
  9797. var upMovement = {
  9798. point: getTop,
  9799. adjuster: adjustUp,
  9800. move: moveUp,
  9801. gather: before
  9802. };
  9803. var downMovement = {
  9804. point: getBottom,
  9805. adjuster: adjustDown,
  9806. move: moveDown,
  9807. gather: after
  9808. };
  9809. var isAtTable = function (bridge, x, y) {
  9810. return bridge.elementFromPoint(x, y).filter(function (elm) {
  9811. return name(elm) === 'table';
  9812. }).isSome();
  9813. };
  9814. var adjustForTable = function (bridge, movement, original, caret, numRetries) {
  9815. return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
  9816. };
  9817. var adjustTil = function (bridge, movement, original, caret, numRetries) {
  9818. if (numRetries === 0) {
  9819. return Optional.some(caret);
  9820. }
  9821. if (isAtTable(bridge, caret.left, movement.point(caret))) {
  9822. return adjustForTable(bridge, movement, original, caret, numRetries - 1);
  9823. }
  9824. return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function (guess) {
  9825. return guess.start.fold(Optional.none, function (element) {
  9826. return getEntireBox(bridge, element).bind(function (guessBox) {
  9827. return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function (newCaret) {
  9828. return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
  9829. });
  9830. }).orThunk(function () {
  9831. return Optional.some(caret);
  9832. });
  9833. }, Optional.none);
  9834. });
  9835. };
  9836. var ieTryDown = function (bridge, caret) {
  9837. return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
  9838. };
  9839. var ieTryUp = function (bridge, caret) {
  9840. return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
  9841. };
  9842. var checkScroll = function (movement, adjusted, bridge) {
  9843. if (movement.point(adjusted) > bridge.getInnerHeight()) {
  9844. return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
  9845. } else if (movement.point(adjusted) < 0) {
  9846. return Optional.some(-movement.point(adjusted));
  9847. } else {
  9848. return Optional.none();
  9849. }
  9850. };
  9851. var retry = function (movement, bridge, caret) {
  9852. var moved = movement.move(caret, JUMP_SIZE);
  9853. var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
  9854. return checkScroll(movement, adjusted, bridge).fold(function () {
  9855. return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
  9856. }, function (delta) {
  9857. bridge.scrollBy(0, delta);
  9858. return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
  9859. });
  9860. };
  9861. var Retries = {
  9862. tryUp: curry(retry, upMovement),
  9863. tryDown: curry(retry, downMovement),
  9864. ieTryUp: ieTryUp,
  9865. ieTryDown: ieTryDown,
  9866. getJumpSize: constant(JUMP_SIZE)
  9867. };
  9868. var MAX_RETRIES = 20;
  9869. var findSpot = function (bridge, isRoot, direction) {
  9870. return bridge.getSelection().bind(function (sel) {
  9871. return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function () {
  9872. return Optional.some(point(sel.finish, sel.foffset));
  9873. }, function (brNeighbour) {
  9874. var range = bridge.fromSitus(brNeighbour);
  9875. var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range.finish, range.foffset, direction.failure, isRoot);
  9876. return process(analysis);
  9877. });
  9878. });
  9879. };
  9880. var scan = function (bridge, isRoot, element, offset, direction, numRetries) {
  9881. if (numRetries === 0) {
  9882. return Optional.none();
  9883. }
  9884. return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
  9885. var range = bridge.fromSitus(situs);
  9886. var analysis = BeforeAfter.verify(bridge, element, offset, range.finish, range.foffset, direction.failure, isRoot);
  9887. return BeforeAfter.cata(analysis, function () {
  9888. return Optional.none();
  9889. }, function () {
  9890. return Optional.some(situs);
  9891. }, function (cell) {
  9892. if (eq$1(element, cell) && offset === 0) {
  9893. return tryAgain(bridge, element, offset, moveUp, direction);
  9894. } else {
  9895. return scan(bridge, isRoot, cell, 0, direction, numRetries - 1);
  9896. }
  9897. }, function (cell) {
  9898. if (eq$1(element, cell) && offset === getEnd(cell)) {
  9899. return tryAgain(bridge, element, offset, moveDown, direction);
  9900. } else {
  9901. return scan(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
  9902. }
  9903. });
  9904. });
  9905. };
  9906. var tryAgain = function (bridge, element, offset, move, direction) {
  9907. return getBoxAt(bridge, element, offset).bind(function (box) {
  9908. return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
  9909. });
  9910. };
  9911. var tryAt = function (bridge, direction, box) {
  9912. var browser = detect$3().browser;
  9913. if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
  9914. return direction.otherRetry(bridge, box);
  9915. } else if (browser.isIE()) {
  9916. return direction.ieRetry(bridge, box);
  9917. } else {
  9918. return Optional.none();
  9919. }
  9920. };
  9921. var tryCursor = function (bridge, isRoot, element, offset, direction) {
  9922. return getBoxAt(bridge, element, offset).bind(function (box) {
  9923. return tryAt(bridge, direction, box);
  9924. });
  9925. };
  9926. var handle = function (bridge, isRoot, direction) {
  9927. return findSpot(bridge, isRoot, direction).bind(function (spot) {
  9928. return scan(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
  9929. });
  9930. };
  9931. var inSameTable = function (elem, table) {
  9932. return ancestor(elem, function (e) {
  9933. return parent(e).exists(function (p) {
  9934. return eq$1(p, table);
  9935. });
  9936. });
  9937. };
  9938. var simulate = function (bridge, isRoot, direction, initial, anchor) {
  9939. return closest$1(initial, 'td,th', isRoot).bind(function (start) {
  9940. return closest$1(start, 'table', isRoot).bind(function (table) {
  9941. if (!inSameTable(anchor, table)) {
  9942. return Optional.none();
  9943. }
  9944. return handle(bridge, isRoot, direction).bind(function (range) {
  9945. return closest$1(range.finish, 'td,th', isRoot).map(function (finish) {
  9946. return {
  9947. start: start,
  9948. finish: finish,
  9949. range: range
  9950. };
  9951. });
  9952. });
  9953. });
  9954. });
  9955. };
  9956. var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
  9957. if (detect$3().browser.isIE()) {
  9958. return Optional.none();
  9959. } else {
  9960. return precheck(initial, isRoot).orThunk(function () {
  9961. return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
  9962. var range = info.range;
  9963. return Response.create(Optional.some(makeSitus(range.start, range.soffset, range.finish, range.foffset)), true);
  9964. });
  9965. });
  9966. }
  9967. };
  9968. var firstUpCheck = function (initial, isRoot) {
  9969. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  9970. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  9971. var rows = descendants(table, 'tr');
  9972. if (eq$1(startRow, rows[0])) {
  9973. return seekLeft(table, function (element) {
  9974. return last$1(element).isSome();
  9975. }, isRoot).map(function (last) {
  9976. var lastOffset = getEnd(last);
  9977. return Response.create(Optional.some(makeSitus(last, lastOffset, last, lastOffset)), true);
  9978. });
  9979. } else {
  9980. return Optional.none();
  9981. }
  9982. });
  9983. });
  9984. };
  9985. var lastDownCheck = function (initial, isRoot) {
  9986. return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
  9987. return closest$1(startRow, 'table', isRoot).bind(function (table) {
  9988. var rows = descendants(table, 'tr');
  9989. if (eq$1(startRow, rows[rows.length - 1])) {
  9990. return seekRight(table, function (element) {
  9991. return first(element).isSome();
  9992. }, isRoot).map(function (first) {
  9993. return Response.create(Optional.some(makeSitus(first, 0, first, 0)), true);
  9994. });
  9995. } else {
  9996. return Optional.none();
  9997. }
  9998. });
  9999. });
  10000. };
  10001. var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
  10002. return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
  10003. return detect(container, isRoot, info.start, info.finish, selectRange);
  10004. });
  10005. };
  10006. var findCell = function (target, isRoot) {
  10007. return closest$1(target, 'td,th', isRoot);
  10008. };
  10009. var MouseSelection = function (bridge, container, isRoot, annotations) {
  10010. var cursor = value();
  10011. var clearstate = cursor.clear;
  10012. var applySelection = function (event) {
  10013. cursor.on(function (start) {
  10014. annotations.clearBeforeUpdate(container);
  10015. findCell(event.target, isRoot).each(function (finish) {
  10016. identify(start, finish, isRoot).each(function (cellSel) {
  10017. var boxes = cellSel.boxes.getOr([]);
  10018. if (boxes.length === 1) {
  10019. var singleCell = boxes[0];
  10020. var isNonEditableCell = getRaw(singleCell) === 'false';
  10021. var isCellClosestContentEditable = is(closest(event.target), singleCell, eq$1);
  10022. if (isNonEditableCell && isCellClosestContentEditable) {
  10023. annotations.selectRange(container, boxes, singleCell, singleCell);
  10024. bridge.selectContents(singleCell);
  10025. }
  10026. } else if (boxes.length > 1) {
  10027. annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
  10028. bridge.selectContents(finish);
  10029. }
  10030. });
  10031. });
  10032. });
  10033. };
  10034. var mousedown = function (event) {
  10035. annotations.clear(container);
  10036. findCell(event.target, isRoot).each(cursor.set);
  10037. };
  10038. var mouseover = function (event) {
  10039. applySelection(event);
  10040. };
  10041. var mouseup = function (event) {
  10042. applySelection(event);
  10043. clearstate();
  10044. };
  10045. return {
  10046. clearstate: clearstate,
  10047. mousedown: mousedown,
  10048. mouseover: mouseover,
  10049. mouseup: mouseup
  10050. };
  10051. };
  10052. var down = {
  10053. traverse: nextSibling,
  10054. gather: after,
  10055. relative: Situ.before,
  10056. otherRetry: Retries.tryDown,
  10057. ieRetry: Retries.ieTryDown,
  10058. failure: BeforeAfter.failedDown
  10059. };
  10060. var up = {
  10061. traverse: prevSibling,
  10062. gather: before,
  10063. relative: Situ.before,
  10064. otherRetry: Retries.tryUp,
  10065. ieRetry: Retries.ieTryUp,
  10066. failure: BeforeAfter.failedUp
  10067. };
  10068. var isKey = function (key) {
  10069. return function (keycode) {
  10070. return keycode === key;
  10071. };
  10072. };
  10073. var isUp = isKey(38);
  10074. var isDown = isKey(40);
  10075. var isNavigation = function (keycode) {
  10076. return keycode >= 37 && keycode <= 40;
  10077. };
  10078. var ltr = {
  10079. isBackward: isKey(37),
  10080. isForward: isKey(39)
  10081. };
  10082. var rtl = {
  10083. isBackward: isKey(39),
  10084. isForward: isKey(37)
  10085. };
  10086. var get = function (_DOC) {
  10087. var doc = _DOC !== undefined ? _DOC.dom : document;
  10088. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  10089. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  10090. return SugarPosition(x, y);
  10091. };
  10092. var by = function (x, y, _DOC) {
  10093. var doc = _DOC !== undefined ? _DOC.dom : document;
  10094. var win = doc.defaultView;
  10095. if (win) {
  10096. win.scrollBy(x, y);
  10097. }
  10098. };
  10099. var WindowBridge = function (win) {
  10100. var elementFromPoint = function (x, y) {
  10101. return SugarElement.fromPoint(SugarElement.fromDom(win.document), x, y);
  10102. };
  10103. var getRect = function (element) {
  10104. return element.dom.getBoundingClientRect();
  10105. };
  10106. var getRangedRect = function (start, soffset, finish, foffset) {
  10107. var sel = SimSelection.exact(start, soffset, finish, foffset);
  10108. return getFirstRect(win, sel);
  10109. };
  10110. var getSelection = function () {
  10111. return get$1(win).map(function (exactAdt) {
  10112. return convertToRange(win, exactAdt);
  10113. });
  10114. };
  10115. var fromSitus = function (situs) {
  10116. var relative = SimSelection.relative(situs.start, situs.finish);
  10117. return convertToRange(win, relative);
  10118. };
  10119. var situsFromPoint = function (x, y) {
  10120. return getAtPoint(win, x, y).map(function (exact) {
  10121. return Situs.create(exact.start, exact.soffset, exact.finish, exact.foffset);
  10122. });
  10123. };
  10124. var clearSelection = function () {
  10125. clear(win);
  10126. };
  10127. var collapseSelection = function (toStart) {
  10128. if (toStart === void 0) {
  10129. toStart = false;
  10130. }
  10131. get$1(win).each(function (sel) {
  10132. return sel.fold(function (rng) {
  10133. return rng.collapse(toStart);
  10134. }, function (startSitu, finishSitu) {
  10135. var situ = toStart ? startSitu : finishSitu;
  10136. setRelative(win, situ, situ);
  10137. }, function (start, soffset, finish, foffset) {
  10138. var node = toStart ? start : finish;
  10139. var offset = toStart ? soffset : foffset;
  10140. setExact(win, node, offset, node, offset);
  10141. });
  10142. });
  10143. };
  10144. var selectNode = function (element) {
  10145. setToElement(win, element, false);
  10146. };
  10147. var selectContents = function (element) {
  10148. setToElement(win, element);
  10149. };
  10150. var setSelection = function (sel) {
  10151. setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
  10152. };
  10153. var setRelativeSelection = function (start, finish) {
  10154. setRelative(win, start, finish);
  10155. };
  10156. var getInnerHeight = function () {
  10157. return win.innerHeight;
  10158. };
  10159. var getScrollY = function () {
  10160. var pos = get(SugarElement.fromDom(win.document));
  10161. return pos.top;
  10162. };
  10163. var scrollBy = function (x, y) {
  10164. by(x, y, SugarElement.fromDom(win.document));
  10165. };
  10166. return {
  10167. elementFromPoint: elementFromPoint,
  10168. getRect: getRect,
  10169. getRangedRect: getRangedRect,
  10170. getSelection: getSelection,
  10171. fromSitus: fromSitus,
  10172. situsFromPoint: situsFromPoint,
  10173. clearSelection: clearSelection,
  10174. collapseSelection: collapseSelection,
  10175. setSelection: setSelection,
  10176. setRelativeSelection: setRelativeSelection,
  10177. selectNode: selectNode,
  10178. selectContents: selectContents,
  10179. getInnerHeight: getInnerHeight,
  10180. getScrollY: getScrollY,
  10181. scrollBy: scrollBy
  10182. };
  10183. };
  10184. var rc = function (rows, cols) {
  10185. return {
  10186. rows: rows,
  10187. cols: cols
  10188. };
  10189. };
  10190. var mouse = function (win, container, isRoot, annotations) {
  10191. var bridge = WindowBridge(win);
  10192. var handlers = MouseSelection(bridge, container, isRoot, annotations);
  10193. return {
  10194. clearstate: handlers.clearstate,
  10195. mousedown: handlers.mousedown,
  10196. mouseover: handlers.mouseover,
  10197. mouseup: handlers.mouseup
  10198. };
  10199. };
  10200. var keyboard = function (win, container, isRoot, annotations) {
  10201. var bridge = WindowBridge(win);
  10202. var clearToNavigate = function () {
  10203. annotations.clear(container);
  10204. return Optional.none();
  10205. };
  10206. var keydown = function (event, start, soffset, finish, foffset, direction) {
  10207. var realEvent = event.raw;
  10208. var keycode = realEvent.which;
  10209. var shiftKey = realEvent.shiftKey === true;
  10210. var handler = retrieve$1(container, annotations.selectedSelector).fold(function () {
  10211. if (isNavigation(keycode) && !shiftKey) {
  10212. annotations.clearBeforeUpdate(container);
  10213. }
  10214. if (isDown(keycode) && shiftKey) {
  10215. return curry(select, bridge, container, isRoot, down, finish, start, annotations.selectRange);
  10216. } else if (isUp(keycode) && shiftKey) {
  10217. return curry(select, bridge, container, isRoot, up, finish, start, annotations.selectRange);
  10218. } else if (isDown(keycode)) {
  10219. return curry(navigate, bridge, isRoot, down, finish, start, lastDownCheck);
  10220. } else if (isUp(keycode)) {
  10221. return curry(navigate, bridge, isRoot, up, finish, start, firstUpCheck);
  10222. } else {
  10223. return Optional.none;
  10224. }
  10225. }, function (selected) {
  10226. var update$1 = function (attempts) {
  10227. return function () {
  10228. var navigation = findMap(attempts, function (delta) {
  10229. return update(delta.rows, delta.cols, container, selected, annotations);
  10230. });
  10231. return navigation.fold(function () {
  10232. return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function (edges) {
  10233. var relative = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
  10234. bridge.setRelativeSelection(Situ.on(edges.first, 0), relative(edges.table));
  10235. annotations.clear(container);
  10236. return Response.create(Optional.none(), true);
  10237. });
  10238. }, function (_) {
  10239. return Optional.some(Response.create(Optional.none(), true));
  10240. });
  10241. };
  10242. };
  10243. if (isDown(keycode) && shiftKey) {
  10244. return update$1([rc(+1, 0)]);
  10245. } else if (isUp(keycode) && shiftKey) {
  10246. return update$1([rc(-1, 0)]);
  10247. } else if (direction.isBackward(keycode) && shiftKey) {
  10248. return update$1([
  10249. rc(0, -1),
  10250. rc(-1, 0)
  10251. ]);
  10252. } else if (direction.isForward(keycode) && shiftKey) {
  10253. return update$1([
  10254. rc(0, +1),
  10255. rc(+1, 0)
  10256. ]);
  10257. } else if (isNavigation(keycode) && !shiftKey) {
  10258. return clearToNavigate;
  10259. } else {
  10260. return Optional.none;
  10261. }
  10262. });
  10263. return handler();
  10264. };
  10265. var keyup = function (event, start, soffset, finish, foffset) {
  10266. return retrieve$1(container, annotations.selectedSelector).fold(function () {
  10267. var realEvent = event.raw;
  10268. var keycode = realEvent.which;
  10269. var shiftKey = realEvent.shiftKey === true;
  10270. if (!shiftKey) {
  10271. return Optional.none();
  10272. }
  10273. if (isNavigation(keycode)) {
  10274. return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
  10275. } else {
  10276. return Optional.none();
  10277. }
  10278. }, Optional.none);
  10279. };
  10280. return {
  10281. keydown: keydown,
  10282. keyup: keyup
  10283. };
  10284. };
  10285. var external = function (win, container, isRoot, annotations) {
  10286. var bridge = WindowBridge(win);
  10287. return function (start, finish) {
  10288. annotations.clearBeforeUpdate(container);
  10289. identify(start, finish, isRoot).each(function (cellSel) {
  10290. var boxes = cellSel.boxes.getOr([]);
  10291. annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
  10292. bridge.selectContents(finish);
  10293. bridge.collapseSelection();
  10294. });
  10295. };
  10296. };
  10297. var remove = function (element, classes) {
  10298. each$2(classes, function (x) {
  10299. remove$2(element, x);
  10300. });
  10301. };
  10302. var addClass = function (clazz) {
  10303. return function (element) {
  10304. add(element, clazz);
  10305. };
  10306. };
  10307. var removeClasses = function (classes) {
  10308. return function (element) {
  10309. remove(element, classes);
  10310. };
  10311. };
  10312. var byClass = function (ephemera) {
  10313. var addSelectionClass = addClass(ephemera.selected);
  10314. var removeSelectionClasses = removeClasses([
  10315. ephemera.selected,
  10316. ephemera.lastSelected,
  10317. ephemera.firstSelected
  10318. ]);
  10319. var clear = function (container) {
  10320. var sels = descendants(container, ephemera.selectedSelector);
  10321. each$2(sels, removeSelectionClasses);
  10322. };
  10323. var selectRange = function (container, cells, start, finish) {
  10324. clear(container);
  10325. each$2(cells, addSelectionClass);
  10326. add(start, ephemera.firstSelected);
  10327. add(finish, ephemera.lastSelected);
  10328. };
  10329. return {
  10330. clearBeforeUpdate: clear,
  10331. clear: clear,
  10332. selectRange: selectRange,
  10333. selectedSelector: ephemera.selectedSelector,
  10334. firstSelectedSelector: ephemera.firstSelectedSelector,
  10335. lastSelectedSelector: ephemera.lastSelectedSelector
  10336. };
  10337. };
  10338. var byAttr = function (ephemera, onSelection, onClear) {
  10339. var removeSelectionAttributes = function (element) {
  10340. remove$7(element, ephemera.selected);
  10341. remove$7(element, ephemera.firstSelected);
  10342. remove$7(element, ephemera.lastSelected);
  10343. };
  10344. var addSelectionAttribute = function (element) {
  10345. set$2(element, ephemera.selected, '1');
  10346. };
  10347. var clear = function (container) {
  10348. clearBeforeUpdate(container);
  10349. onClear();
  10350. };
  10351. var clearBeforeUpdate = function (container) {
  10352. var sels = descendants(container, ephemera.selectedSelector + ',' + ephemera.firstSelectedSelector + ',' + ephemera.lastSelectedSelector);
  10353. each$2(sels, removeSelectionAttributes);
  10354. };
  10355. var selectRange = function (container, cells, start, finish) {
  10356. clear(container);
  10357. each$2(cells, addSelectionAttribute);
  10358. set$2(start, ephemera.firstSelected, '1');
  10359. set$2(finish, ephemera.lastSelected, '1');
  10360. onSelection(cells, start, finish);
  10361. };
  10362. return {
  10363. clearBeforeUpdate: clearBeforeUpdate,
  10364. clear: clear,
  10365. selectRange: selectRange,
  10366. selectedSelector: ephemera.selectedSelector,
  10367. firstSelectedSelector: ephemera.firstSelectedSelector,
  10368. lastSelectedSelector: ephemera.lastSelectedSelector
  10369. };
  10370. };
  10371. var SelectionAnnotation = {
  10372. byClass: byClass,
  10373. byAttr: byAttr
  10374. };
  10375. var getUpOrLeftCells = function (grid, selectedCells) {
  10376. var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row + 1);
  10377. var upDetails = toDetailList(upGrid);
  10378. return bind$2(upDetails, function (detail) {
  10379. var slicedCells = detail.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
  10380. return map$1(slicedCells, function (cell) {
  10381. return cell.element;
  10382. });
  10383. });
  10384. };
  10385. var getDownOrRightCells = function (grid, selectedCells) {
  10386. var downGrid = grid.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid.length);
  10387. var downDetails = toDetailList(downGrid);
  10388. return bind$2(downDetails, function (detail) {
  10389. var slicedCells = detail.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail.cells.length);
  10390. return map$1(slicedCells, function (cell) {
  10391. return cell.element;
  10392. });
  10393. });
  10394. };
  10395. var getOtherCells = function (table, target, generators) {
  10396. var warehouse = Warehouse.fromTable(table);
  10397. var details = onCells(warehouse, target);
  10398. return details.map(function (selectedCells) {
  10399. var grid = toGrid(warehouse, generators, false);
  10400. var upOrLeftCells = getUpOrLeftCells(grid, selectedCells);
  10401. var downOrRightCells = getDownOrRightCells(grid, selectedCells);
  10402. return {
  10403. upOrLeftCells: upOrLeftCells,
  10404. downOrRightCells: downOrRightCells
  10405. };
  10406. });
  10407. };
  10408. var global = tinymce.util.Tools.resolve('tinymce.Env');
  10409. var hasInternalTarget = function (e) {
  10410. return has(SugarElement.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
  10411. };
  10412. function CellSelection (editor, lazyResize, selectionTargets) {
  10413. var onSelection = function (cells, start, finish) {
  10414. selectionTargets.targets().each(function (targets) {
  10415. var tableOpt = table(start);
  10416. tableOpt.each(function (table) {
  10417. var cloneFormats = getCloneElements(editor);
  10418. var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), cloneFormats);
  10419. var otherCells = getOtherCells(table, targets, generators);
  10420. fireTableSelectionChange(editor, cells, start, finish, otherCells);
  10421. });
  10422. });
  10423. };
  10424. var onClear = function () {
  10425. return fireTableSelectionClear(editor);
  10426. };
  10427. var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
  10428. editor.on('init', function (_e) {
  10429. var win = editor.getWin();
  10430. var body = getBody(editor);
  10431. var isRoot = getIsRoot(editor);
  10432. var syncSelection = function () {
  10433. var sel = editor.selection;
  10434. var start = SugarElement.fromDom(sel.getStart());
  10435. var end = SugarElement.fromDom(sel.getEnd());
  10436. var shared = sharedOne(table, [
  10437. start,
  10438. end
  10439. ]);
  10440. shared.fold(function () {
  10441. return annotations.clear(body);
  10442. }, noop);
  10443. };
  10444. var mouseHandlers = mouse(win, body, isRoot, annotations);
  10445. var keyHandlers = keyboard(win, body, isRoot, annotations);
  10446. var external$1 = external(win, body, isRoot, annotations);
  10447. var hasShiftKey = function (event) {
  10448. return event.raw.shiftKey === true;
  10449. };
  10450. editor.on('TableSelectorChange', function (e) {
  10451. return external$1(e.start, e.finish);
  10452. });
  10453. var handleResponse = function (event, response) {
  10454. if (!hasShiftKey(event)) {
  10455. return;
  10456. }
  10457. if (response.kill) {
  10458. event.kill();
  10459. }
  10460. response.selection.each(function (ns) {
  10461. var relative = SimSelection.relative(ns.start, ns.finish);
  10462. var rng = asLtrRange(win, relative);
  10463. editor.selection.setRng(rng);
  10464. });
  10465. };
  10466. var keyup = function (event) {
  10467. var wrappedEvent = fromRawEvent(event);
  10468. if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
  10469. var rng = editor.selection.getRng();
  10470. var start = SugarElement.fromDom(rng.startContainer);
  10471. var end = SugarElement.fromDom(rng.endContainer);
  10472. keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
  10473. handleResponse(wrappedEvent, response);
  10474. });
  10475. }
  10476. };
  10477. var keydown = function (event) {
  10478. var wrappedEvent = fromRawEvent(event);
  10479. lazyResize().each(function (resize) {
  10480. return resize.hideBars();
  10481. });
  10482. var rng = editor.selection.getRng();
  10483. var start = SugarElement.fromDom(rng.startContainer);
  10484. var end = SugarElement.fromDom(rng.endContainer);
  10485. var direction = onDirection(ltr, rtl)(SugarElement.fromDom(editor.selection.getStart()));
  10486. keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
  10487. handleResponse(wrappedEvent, response);
  10488. });
  10489. lazyResize().each(function (resize) {
  10490. return resize.showBars();
  10491. });
  10492. };
  10493. var isLeftMouse = function (raw) {
  10494. return raw.button === 0;
  10495. };
  10496. var isLeftButtonPressed = function (raw) {
  10497. if (raw.buttons === undefined) {
  10498. return true;
  10499. }
  10500. if (global.browser.isEdge() && raw.buttons === 0) {
  10501. return true;
  10502. }
  10503. return (raw.buttons & 1) !== 0;
  10504. };
  10505. var dragStart = function (_e) {
  10506. mouseHandlers.clearstate();
  10507. };
  10508. var mouseDown = function (e) {
  10509. if (isLeftMouse(e) && hasInternalTarget(e)) {
  10510. mouseHandlers.mousedown(fromRawEvent(e));
  10511. }
  10512. };
  10513. var mouseOver = function (e) {
  10514. if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
  10515. mouseHandlers.mouseover(fromRawEvent(e));
  10516. }
  10517. };
  10518. var mouseUp = function (e) {
  10519. if (isLeftMouse(e) && hasInternalTarget(e)) {
  10520. mouseHandlers.mouseup(fromRawEvent(e));
  10521. }
  10522. };
  10523. var getDoubleTap = function () {
  10524. var lastTarget = Cell(SugarElement.fromDom(body));
  10525. var lastTimeStamp = Cell(0);
  10526. var touchEnd = function (t) {
  10527. var target = SugarElement.fromDom(t.target);
  10528. if (name(target) === 'td' || name(target) === 'th') {
  10529. var lT = lastTarget.get();
  10530. var lTS = lastTimeStamp.get();
  10531. if (eq$1(lT, target) && t.timeStamp - lTS < 300) {
  10532. t.preventDefault();
  10533. external$1(target, target);
  10534. }
  10535. }
  10536. lastTarget.set(target);
  10537. lastTimeStamp.set(t.timeStamp);
  10538. };
  10539. return { touchEnd: touchEnd };
  10540. };
  10541. var doubleTap = getDoubleTap();
  10542. editor.on('dragstart', dragStart);
  10543. editor.on('mousedown', mouseDown);
  10544. editor.on('mouseover', mouseOver);
  10545. editor.on('mouseup', mouseUp);
  10546. editor.on('touchend', doubleTap.touchEnd);
  10547. editor.on('keyup', keyup);
  10548. editor.on('keydown', keydown);
  10549. editor.on('NodeChange', syncSelection);
  10550. });
  10551. return { clear: annotations.clear };
  10552. }
  10553. var child = function (scope, selector) {
  10554. return child$1(scope, selector).isSome();
  10555. };
  10556. var getSelectionTargets = function (editor, selections) {
  10557. var targets = Cell(Optional.none());
  10558. var changeHandlers = Cell([]);
  10559. var selectionDetails = Optional.none();
  10560. var isCaption = isTag('caption');
  10561. var isDisabledForSelection = function (key) {
  10562. return selectionDetails.forall(function (details) {
  10563. return !details[key];
  10564. });
  10565. };
  10566. var getStart = function () {
  10567. return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  10568. };
  10569. var getEnd = function () {
  10570. return getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
  10571. };
  10572. var findTargets = function () {
  10573. return getStart().bind(function (startCellOrCaption) {
  10574. return flatten(lift2(table(startCellOrCaption), getEnd().bind(table), function (startTable, endTable) {
  10575. if (eq$1(startTable, endTable)) {
  10576. if (isCaption(startCellOrCaption)) {
  10577. return Optional.some(noMenu(startCellOrCaption));
  10578. } else {
  10579. return Optional.some(forMenu(selections, startTable, startCellOrCaption));
  10580. }
  10581. }
  10582. return Optional.none();
  10583. }));
  10584. });
  10585. };
  10586. var getExtractedDetails = function (targets) {
  10587. var tableOpt = table(targets.element);
  10588. return tableOpt.map(function (table) {
  10589. var warehouse = Warehouse.fromTable(table);
  10590. var selectedCells = onCells(warehouse, targets).getOr([]);
  10591. var locked = foldl(selectedCells, function (acc, cell) {
  10592. if (cell.isLocked) {
  10593. acc.onAny = true;
  10594. if (cell.column === 0) {
  10595. acc.onFirst = true;
  10596. } else if (cell.column + cell.colspan >= warehouse.grid.columns) {
  10597. acc.onLast = true;
  10598. }
  10599. }
  10600. return acc;
  10601. }, {
  10602. onAny: false,
  10603. onFirst: false,
  10604. onLast: false
  10605. });
  10606. return {
  10607. mergeable: onUnlockedMergable(warehouse, targets).isSome(),
  10608. unmergeable: onUnlockedUnmergable(warehouse, targets).isSome(),
  10609. locked: locked
  10610. };
  10611. });
  10612. };
  10613. var resetTargets = function () {
  10614. targets.set(cached(findTargets)());
  10615. selectionDetails = targets.get().bind(getExtractedDetails);
  10616. each$2(changeHandlers.get(), function (handler) {
  10617. return handler();
  10618. });
  10619. };
  10620. var setupHandler = function (handler) {
  10621. handler();
  10622. changeHandlers.set(changeHandlers.get().concat([handler]));
  10623. return function () {
  10624. changeHandlers.set(filter$2(changeHandlers.get(), function (h) {
  10625. return h !== handler;
  10626. }));
  10627. };
  10628. };
  10629. var onSetup = function (api, isDisabled) {
  10630. return setupHandler(function () {
  10631. return targets.get().fold(function () {
  10632. api.setDisabled(true);
  10633. }, function (targets) {
  10634. api.setDisabled(isDisabled(targets));
  10635. });
  10636. });
  10637. };
  10638. var onSetupWithToggle = function (api, isDisabled, isActive) {
  10639. return setupHandler(function () {
  10640. return targets.get().fold(function () {
  10641. api.setDisabled(true);
  10642. api.setActive(false);
  10643. }, function (targets) {
  10644. api.setDisabled(isDisabled(targets));
  10645. api.setActive(isActive(targets));
  10646. });
  10647. });
  10648. };
  10649. var isDisabledFromLocked = function (lockedDisable) {
  10650. return selectionDetails.exists(function (details) {
  10651. return details.locked[lockedDisable];
  10652. });
  10653. };
  10654. var onSetupTable = function (api) {
  10655. return onSetup(api, function (_) {
  10656. return false;
  10657. });
  10658. };
  10659. var onSetupCellOrRow = function (api) {
  10660. return onSetup(api, function (targets) {
  10661. return isCaption(targets.element);
  10662. });
  10663. };
  10664. var onSetupColumn = function (lockedDisable) {
  10665. return function (api) {
  10666. return onSetup(api, function (targets) {
  10667. return isCaption(targets.element) || isDisabledFromLocked(lockedDisable);
  10668. });
  10669. };
  10670. };
  10671. var onSetupPasteable = function (getClipboardData) {
  10672. return function (api) {
  10673. return onSetup(api, function (targets) {
  10674. return isCaption(targets.element) || getClipboardData().isNone();
  10675. });
  10676. };
  10677. };
  10678. var onSetupPasteableColumn = function (getClipboardData, lockedDisable) {
  10679. return function (api) {
  10680. return onSetup(api, function (targets) {
  10681. return isCaption(targets.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable);
  10682. });
  10683. };
  10684. };
  10685. var onSetupMergeable = function (api) {
  10686. return onSetup(api, function (_targets) {
  10687. return isDisabledForSelection('mergeable');
  10688. });
  10689. };
  10690. var onSetupUnmergeable = function (api) {
  10691. return onSetup(api, function (_targets) {
  10692. return isDisabledForSelection('unmergeable');
  10693. });
  10694. };
  10695. var onSetupTableWithCaption = function (api) {
  10696. return onSetupWithToggle(api, never, function (targets) {
  10697. var tableOpt = table(targets.element, getIsRoot(editor));
  10698. return tableOpt.exists(function (table) {
  10699. return child(table, 'caption');
  10700. });
  10701. });
  10702. };
  10703. var onSetupTableHeaders = function (command, headerType) {
  10704. return function (api) {
  10705. return onSetupWithToggle(api, function (targets) {
  10706. return isCaption(targets.element);
  10707. }, function () {
  10708. return editor.queryCommandValue(command) === headerType;
  10709. });
  10710. };
  10711. };
  10712. var onSetupTableRowHeaders = onSetupTableHeaders('mceTableRowType', 'header');
  10713. var onSetupTableColumnHeaders = onSetupTableHeaders('mceTableColType', 'th');
  10714. editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
  10715. return {
  10716. onSetupTable: onSetupTable,
  10717. onSetupCellOrRow: onSetupCellOrRow,
  10718. onSetupColumn: onSetupColumn,
  10719. onSetupPasteable: onSetupPasteable,
  10720. onSetupPasteableColumn: onSetupPasteableColumn,
  10721. onSetupMergeable: onSetupMergeable,
  10722. onSetupUnmergeable: onSetupUnmergeable,
  10723. resetTargets: resetTargets,
  10724. onSetupTableWithCaption: onSetupTableWithCaption,
  10725. onSetupTableRowHeaders: onSetupTableRowHeaders,
  10726. onSetupTableColumnHeaders: onSetupTableColumnHeaders,
  10727. targets: targets.get
  10728. };
  10729. };
  10730. var addButtons = function (editor, selections, selectionTargets, clipboard) {
  10731. editor.ui.registry.addMenuButton('table', {
  10732. tooltip: 'Table',
  10733. icon: 'table',
  10734. fetch: function (callback) {
  10735. return callback('inserttable | cell row column | advtablesort | tableprops deletetable');
  10736. }
  10737. });
  10738. var cmd = function (command) {
  10739. return function () {
  10740. return editor.execCommand(command);
  10741. };
  10742. };
  10743. editor.ui.registry.addButton('tableprops', {
  10744. tooltip: 'Table properties',
  10745. onAction: cmd('mceTableProps'),
  10746. icon: 'table',
  10747. onSetup: selectionTargets.onSetupTable
  10748. });
  10749. editor.ui.registry.addButton('tabledelete', {
  10750. tooltip: 'Delete table',
  10751. onAction: cmd('mceTableDelete'),
  10752. icon: 'table-delete-table',
  10753. onSetup: selectionTargets.onSetupTable
  10754. });
  10755. editor.ui.registry.addButton('tablecellprops', {
  10756. tooltip: 'Cell properties',
  10757. onAction: cmd('mceTableCellProps'),
  10758. icon: 'table-cell-properties',
  10759. onSetup: selectionTargets.onSetupCellOrRow
  10760. });
  10761. editor.ui.registry.addButton('tablemergecells', {
  10762. tooltip: 'Merge cells',
  10763. onAction: cmd('mceTableMergeCells'),
  10764. icon: 'table-merge-cells',
  10765. onSetup: selectionTargets.onSetupMergeable
  10766. });
  10767. editor.ui.registry.addButton('tablesplitcells', {
  10768. tooltip: 'Split cell',
  10769. onAction: cmd('mceTableSplitCells'),
  10770. icon: 'table-split-cells',
  10771. onSetup: selectionTargets.onSetupUnmergeable
  10772. });
  10773. editor.ui.registry.addButton('tableinsertrowbefore', {
  10774. tooltip: 'Insert row before',
  10775. onAction: cmd('mceTableInsertRowBefore'),
  10776. icon: 'table-insert-row-above',
  10777. onSetup: selectionTargets.onSetupCellOrRow
  10778. });
  10779. editor.ui.registry.addButton('tableinsertrowafter', {
  10780. tooltip: 'Insert row after',
  10781. onAction: cmd('mceTableInsertRowAfter'),
  10782. icon: 'table-insert-row-after',
  10783. onSetup: selectionTargets.onSetupCellOrRow
  10784. });
  10785. editor.ui.registry.addButton('tabledeleterow', {
  10786. tooltip: 'Delete row',
  10787. onAction: cmd('mceTableDeleteRow'),
  10788. icon: 'table-delete-row',
  10789. onSetup: selectionTargets.onSetupCellOrRow
  10790. });
  10791. editor.ui.registry.addButton('tablerowprops', {
  10792. tooltip: 'Row properties',
  10793. onAction: cmd('mceTableRowProps'),
  10794. icon: 'table-row-properties',
  10795. onSetup: selectionTargets.onSetupCellOrRow
  10796. });
  10797. editor.ui.registry.addButton('tableinsertcolbefore', {
  10798. tooltip: 'Insert column before',
  10799. onAction: cmd('mceTableInsertColBefore'),
  10800. icon: 'table-insert-column-before',
  10801. onSetup: selectionTargets.onSetupColumn('onFirst')
  10802. });
  10803. editor.ui.registry.addButton('tableinsertcolafter', {
  10804. tooltip: 'Insert column after',
  10805. onAction: cmd('mceTableInsertColAfter'),
  10806. icon: 'table-insert-column-after',
  10807. onSetup: selectionTargets.onSetupColumn('onLast')
  10808. });
  10809. editor.ui.registry.addButton('tabledeletecol', {
  10810. tooltip: 'Delete column',
  10811. onAction: cmd('mceTableDeleteCol'),
  10812. icon: 'table-delete-column',
  10813. onSetup: selectionTargets.onSetupColumn('onAny')
  10814. });
  10815. editor.ui.registry.addButton('tablecutrow', {
  10816. tooltip: 'Cut row',
  10817. icon: 'cut-row',
  10818. onAction: cmd('mceTableCutRow'),
  10819. onSetup: selectionTargets.onSetupCellOrRow
  10820. });
  10821. editor.ui.registry.addButton('tablecopyrow', {
  10822. tooltip: 'Copy row',
  10823. icon: 'duplicate-row',
  10824. onAction: cmd('mceTableCopyRow'),
  10825. onSetup: selectionTargets.onSetupCellOrRow
  10826. });
  10827. editor.ui.registry.addButton('tablepasterowbefore', {
  10828. tooltip: 'Paste row before',
  10829. icon: 'paste-row-before',
  10830. onAction: cmd('mceTablePasteRowBefore'),
  10831. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10832. });
  10833. editor.ui.registry.addButton('tablepasterowafter', {
  10834. tooltip: 'Paste row after',
  10835. icon: 'paste-row-after',
  10836. onAction: cmd('mceTablePasteRowAfter'),
  10837. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  10838. });
  10839. editor.ui.registry.addButton('tablecutcol', {
  10840. tooltip: 'Cut column',
  10841. icon: 'cut-column',
  10842. onAction: cmd('mceTableCutCol'),
  10843. onSetup: selectionTargets.onSetupColumn('onAny')
  10844. });
  10845. editor.ui.registry.addButton('tablecopycol', {
  10846. tooltip: 'Copy column',
  10847. icon: 'duplicate-column',
  10848. onAction: cmd('mceTableCopyCol'),
  10849. onSetup: selectionTargets.onSetupColumn('onAny')
  10850. });
  10851. editor.ui.registry.addButton('tablepastecolbefore', {
  10852. tooltip: 'Paste column before',
  10853. icon: 'paste-column-before',
  10854. onAction: cmd('mceTablePasteColBefore'),
  10855. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
  10856. });
  10857. editor.ui.registry.addButton('tablepastecolafter', {
  10858. tooltip: 'Paste column after',
  10859. icon: 'paste-column-after',
  10860. onAction: cmd('mceTablePasteColAfter'),
  10861. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
  10862. });
  10863. editor.ui.registry.addButton('tableinsertdialog', {
  10864. tooltip: 'Insert table',
  10865. onAction: cmd('mceInsertTable'),
  10866. icon: 'table'
  10867. });
  10868. var tableClassList = filterNoneItem(getTableClassList(editor));
  10869. if (tableClassList.length !== 0) {
  10870. editor.ui.registry.addMenuButton('tableclass', {
  10871. icon: 'table-classes',
  10872. tooltip: 'Table styles',
  10873. fetch: generateMenuItemsCallback(editor, selections, tableClassList, 'tableclass', function (value) {
  10874. return editor.execCommand('mceTableToggleClass', false, value);
  10875. }),
  10876. onSetup: selectionTargets.onSetupTable
  10877. });
  10878. }
  10879. var tableCellClassList = filterNoneItem(getCellClassList(editor));
  10880. if (tableCellClassList.length !== 0) {
  10881. editor.ui.registry.addMenuButton('tablecellclass', {
  10882. icon: 'table-cell-classes',
  10883. tooltip: 'Cell styles',
  10884. fetch: generateMenuItemsCallback(editor, selections, tableCellClassList, 'tablecellclass', function (value) {
  10885. return editor.execCommand('mceTableCellToggleClass', false, value);
  10886. }),
  10887. onSetup: selectionTargets.onSetupCellOrRow
  10888. });
  10889. }
  10890. editor.ui.registry.addMenuButton('tablecellvalign', {
  10891. icon: 'vertical-align',
  10892. tooltip: 'Vertical align',
  10893. fetch: generateMenuItemsCallback(editor, selections, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
  10894. onSetup: selectionTargets.onSetupCellOrRow
  10895. });
  10896. editor.ui.registry.addMenuButton('tablecellborderwidth', {
  10897. icon: 'border-width',
  10898. tooltip: 'Border width',
  10899. fetch: generateMenuItemsCallback(editor, selections, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
  10900. onSetup: selectionTargets.onSetupCellOrRow
  10901. });
  10902. editor.ui.registry.addMenuButton('tablecellborderstyle', {
  10903. icon: 'border-style',
  10904. tooltip: 'Border style',
  10905. fetch: generateMenuItemsCallback(editor, selections, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
  10906. onSetup: selectionTargets.onSetupCellOrRow
  10907. });
  10908. editor.ui.registry.addToggleButton('tablecaption', {
  10909. tooltip: 'Table caption',
  10910. onAction: cmd('mceTableToggleCaption'),
  10911. icon: 'table-caption',
  10912. onSetup: selectionTargets.onSetupTableWithCaption
  10913. });
  10914. editor.ui.registry.addMenuButton('tablecellbackgroundcolor', {
  10915. icon: 'cell-background-color',
  10916. tooltip: 'Background color',
  10917. fetch: function (callback) {
  10918. return callback(buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color'));
  10919. },
  10920. onSetup: selectionTargets.onSetupCellOrRow
  10921. });
  10922. editor.ui.registry.addMenuButton('tablecellbordercolor', {
  10923. icon: 'cell-border-color',
  10924. tooltip: 'Border color',
  10925. fetch: function (callback) {
  10926. return callback(buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color'));
  10927. },
  10928. onSetup: selectionTargets.onSetupCellOrRow
  10929. });
  10930. editor.ui.registry.addToggleButton('tablerowheader', {
  10931. tooltip: 'Row header',
  10932. icon: 'table-top-header',
  10933. onAction: changeRowHeader(editor),
  10934. onSetup: selectionTargets.onSetupTableRowHeaders
  10935. });
  10936. editor.ui.registry.addToggleButton('tablecolheader', {
  10937. tooltip: 'Column header',
  10938. icon: 'table-left-header',
  10939. onAction: changeColumnHeader(editor),
  10940. onSetup: selectionTargets.onSetupTableColumnHeaders
  10941. });
  10942. };
  10943. var addToolbars = function (editor) {
  10944. var isTable = function (table) {
  10945. return editor.dom.is(table, 'table') && editor.getBody().contains(table);
  10946. };
  10947. var toolbar = getToolbar(editor);
  10948. if (toolbar.length > 0) {
  10949. editor.ui.registry.addContextToolbar('table', {
  10950. predicate: isTable,
  10951. items: toolbar,
  10952. scope: 'node',
  10953. position: 'node'
  10954. });
  10955. }
  10956. };
  10957. var addMenuItems = function (editor, selections, selectionTargets, clipboard) {
  10958. var cmd = function (command) {
  10959. return function () {
  10960. return editor.execCommand(command);
  10961. };
  10962. };
  10963. var insertTableAction = function (data) {
  10964. editor.execCommand('mceInsertTable', false, {
  10965. rows: data.numRows,
  10966. columns: data.numColumns
  10967. });
  10968. };
  10969. var tableProperties = {
  10970. text: 'Table properties',
  10971. onSetup: selectionTargets.onSetupTable,
  10972. onAction: cmd('mceTableProps')
  10973. };
  10974. var deleteTable = {
  10975. text: 'Delete table',
  10976. icon: 'table-delete-table',
  10977. onSetup: selectionTargets.onSetupTable,
  10978. onAction: cmd('mceTableDelete')
  10979. };
  10980. editor.ui.registry.addMenuItem('tableinsertrowbefore', {
  10981. text: 'Insert row before',
  10982. icon: 'table-insert-row-above',
  10983. onAction: cmd('mceTableInsertRowBefore'),
  10984. onSetup: selectionTargets.onSetupCellOrRow
  10985. });
  10986. editor.ui.registry.addMenuItem('tableinsertrowafter', {
  10987. text: 'Insert row after',
  10988. icon: 'table-insert-row-after',
  10989. onAction: cmd('mceTableInsertRowAfter'),
  10990. onSetup: selectionTargets.onSetupCellOrRow
  10991. });
  10992. editor.ui.registry.addMenuItem('tabledeleterow', {
  10993. text: 'Delete row',
  10994. icon: 'table-delete-row',
  10995. onAction: cmd('mceTableDeleteRow'),
  10996. onSetup: selectionTargets.onSetupCellOrRow
  10997. });
  10998. editor.ui.registry.addMenuItem('tablerowprops', {
  10999. text: 'Row properties',
  11000. icon: 'table-row-properties',
  11001. onAction: cmd('mceTableRowProps'),
  11002. onSetup: selectionTargets.onSetupCellOrRow
  11003. });
  11004. editor.ui.registry.addMenuItem('tablecutrow', {
  11005. text: 'Cut row',
  11006. icon: 'cut-row',
  11007. onAction: cmd('mceTableCutRow'),
  11008. onSetup: selectionTargets.onSetupCellOrRow
  11009. });
  11010. editor.ui.registry.addMenuItem('tablecopyrow', {
  11011. text: 'Copy row',
  11012. icon: 'duplicate-row',
  11013. onAction: cmd('mceTableCopyRow'),
  11014. onSetup: selectionTargets.onSetupCellOrRow
  11015. });
  11016. editor.ui.registry.addMenuItem('tablepasterowbefore', {
  11017. text: 'Paste row before',
  11018. icon: 'paste-row-before',
  11019. onAction: cmd('mceTablePasteRowBefore'),
  11020. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  11021. });
  11022. editor.ui.registry.addMenuItem('tablepasterowafter', {
  11023. text: 'Paste row after',
  11024. icon: 'paste-row-after',
  11025. onAction: cmd('mceTablePasteRowAfter'),
  11026. onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
  11027. });
  11028. var row = {
  11029. type: 'nestedmenuitem',
  11030. text: 'Row',
  11031. getSubmenuItems: constant('tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter')
  11032. };
  11033. editor.ui.registry.addMenuItem('tableinsertcolumnbefore', {
  11034. text: 'Insert column before',
  11035. icon: 'table-insert-column-before',
  11036. onAction: cmd('mceTableInsertColBefore'),
  11037. onSetup: selectionTargets.onSetupColumn('onFirst')
  11038. });
  11039. editor.ui.registry.addMenuItem('tableinsertcolumnafter', {
  11040. text: 'Insert column after',
  11041. icon: 'table-insert-column-after',
  11042. onAction: cmd('mceTableInsertColAfter'),
  11043. onSetup: selectionTargets.onSetupColumn('onLast')
  11044. });
  11045. editor.ui.registry.addMenuItem('tabledeletecolumn', {
  11046. text: 'Delete column',
  11047. icon: 'table-delete-column',
  11048. onAction: cmd('mceTableDeleteCol'),
  11049. onSetup: selectionTargets.onSetupColumn('onAny')
  11050. });
  11051. editor.ui.registry.addMenuItem('tablecutcolumn', {
  11052. text: 'Cut column',
  11053. icon: 'cut-column',
  11054. onAction: cmd('mceTableCutCol'),
  11055. onSetup: selectionTargets.onSetupColumn('onAny')
  11056. });
  11057. editor.ui.registry.addMenuItem('tablecopycolumn', {
  11058. text: 'Copy column',
  11059. icon: 'duplicate-column',
  11060. onAction: cmd('mceTableCopyCol'),
  11061. onSetup: selectionTargets.onSetupColumn('onAny')
  11062. });
  11063. editor.ui.registry.addMenuItem('tablepastecolumnbefore', {
  11064. text: 'Paste column before',
  11065. icon: 'paste-column-before',
  11066. onAction: cmd('mceTablePasteColBefore'),
  11067. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
  11068. });
  11069. editor.ui.registry.addMenuItem('tablepastecolumnafter', {
  11070. text: 'Paste column after',
  11071. icon: 'paste-column-after',
  11072. onAction: cmd('mceTablePasteColAfter'),
  11073. onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
  11074. });
  11075. var column = {
  11076. type: 'nestedmenuitem',
  11077. text: 'Column',
  11078. getSubmenuItems: constant('tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter')
  11079. };
  11080. editor.ui.registry.addMenuItem('tablecellprops', {
  11081. text: 'Cell properties',
  11082. icon: 'table-cell-properties',
  11083. onAction: cmd('mceTableCellProps'),
  11084. onSetup: selectionTargets.onSetupCellOrRow
  11085. });
  11086. editor.ui.registry.addMenuItem('tablemergecells', {
  11087. text: 'Merge cells',
  11088. icon: 'table-merge-cells',
  11089. onAction: cmd('mceTableMergeCells'),
  11090. onSetup: selectionTargets.onSetupMergeable
  11091. });
  11092. editor.ui.registry.addMenuItem('tablesplitcells', {
  11093. text: 'Split cell',
  11094. icon: 'table-split-cells',
  11095. onAction: cmd('mceTableSplitCells'),
  11096. onSetup: selectionTargets.onSetupUnmergeable
  11097. });
  11098. var cell = {
  11099. type: 'nestedmenuitem',
  11100. text: 'Cell',
  11101. getSubmenuItems: constant('tablecellprops tablemergecells tablesplitcells')
  11102. };
  11103. if (hasTableGrid(editor) === false) {
  11104. editor.ui.registry.addMenuItem('inserttable', {
  11105. text: 'Table',
  11106. icon: 'table',
  11107. onAction: cmd('mceInsertTable')
  11108. });
  11109. } else {
  11110. editor.ui.registry.addNestedMenuItem('inserttable', {
  11111. text: 'Table',
  11112. icon: 'table',
  11113. getSubmenuItems: function () {
  11114. return [{
  11115. type: 'fancymenuitem',
  11116. fancytype: 'inserttable',
  11117. onAction: insertTableAction
  11118. }];
  11119. }
  11120. });
  11121. }
  11122. editor.ui.registry.addMenuItem('inserttabledialog', {
  11123. text: 'Insert table',
  11124. icon: 'table',
  11125. onAction: cmd('mceInsertTable')
  11126. });
  11127. editor.ui.registry.addMenuItem('tableprops', tableProperties);
  11128. editor.ui.registry.addMenuItem('deletetable', deleteTable);
  11129. editor.ui.registry.addNestedMenuItem('row', row);
  11130. editor.ui.registry.addNestedMenuItem('column', column);
  11131. editor.ui.registry.addNestedMenuItem('cell', cell);
  11132. editor.ui.registry.addContextMenu('table', {
  11133. update: function () {
  11134. selectionTargets.resetTargets();
  11135. return selectionTargets.targets().fold(constant(''), function (targets) {
  11136. if (name(targets.element) === 'caption') {
  11137. return 'tableprops deletetable';
  11138. } else {
  11139. return 'cell row column | advtablesort | tableprops deletetable';
  11140. }
  11141. });
  11142. }
  11143. });
  11144. var tableClassList = filterNoneItem(getTableClassList(editor));
  11145. if (tableClassList.length !== 0) {
  11146. editor.ui.registry.addNestedMenuItem('tableclass', {
  11147. icon: 'table-classes',
  11148. text: 'Table styles',
  11149. getSubmenuItems: function () {
  11150. return buildMenuItems(editor, selections, tableClassList, 'tableclass', function (value) {
  11151. return editor.execCommand('mceTableToggleClass', false, value);
  11152. });
  11153. },
  11154. onSetup: selectionTargets.onSetupTable
  11155. });
  11156. }
  11157. var tableCellClassList = filterNoneItem(getCellClassList(editor));
  11158. if (tableCellClassList.length !== 0) {
  11159. editor.ui.registry.addNestedMenuItem('tablecellclass', {
  11160. icon: 'table-cell-classes',
  11161. text: 'Cell styles',
  11162. getSubmenuItems: function () {
  11163. return buildMenuItems(editor, selections, tableCellClassList, 'tablecellclass', function (value) {
  11164. return editor.execCommand('mceTableCellToggleClass', false, value);
  11165. });
  11166. },
  11167. onSetup: selectionTargets.onSetupCellOrRow
  11168. });
  11169. }
  11170. editor.ui.registry.addNestedMenuItem('tablecellvalign', {
  11171. icon: 'vertical-align',
  11172. text: 'Vertical align',
  11173. getSubmenuItems: function () {
  11174. return buildMenuItems(editor, selections, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align'));
  11175. },
  11176. onSetup: selectionTargets.onSetupCellOrRow
  11177. });
  11178. editor.ui.registry.addNestedMenuItem('tablecellborderwidth', {
  11179. icon: 'border-width',
  11180. text: 'Border width',
  11181. getSubmenuItems: function () {
  11182. return buildMenuItems(editor, selections, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width'));
  11183. },
  11184. onSetup: selectionTargets.onSetupCellOrRow
  11185. });
  11186. editor.ui.registry.addNestedMenuItem('tablecellborderstyle', {
  11187. icon: 'border-style',
  11188. text: 'Border style',
  11189. getSubmenuItems: function () {
  11190. return buildMenuItems(editor, selections, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style'));
  11191. },
  11192. onSetup: selectionTargets.onSetupCellOrRow
  11193. });
  11194. editor.ui.registry.addToggleMenuItem('tablecaption', {
  11195. icon: 'table-caption',
  11196. text: 'Table caption',
  11197. onAction: cmd('mceTableToggleCaption'),
  11198. onSetup: selectionTargets.onSetupTableWithCaption
  11199. });
  11200. editor.ui.registry.addNestedMenuItem('tablecellbackgroundcolor', {
  11201. icon: 'cell-background-color',
  11202. text: 'Background color',
  11203. getSubmenuItems: function () {
  11204. return buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color');
  11205. },
  11206. onSetup: selectionTargets.onSetupCellOrRow
  11207. });
  11208. editor.ui.registry.addNestedMenuItem('tablecellbordercolor', {
  11209. icon: 'cell-border-color',
  11210. text: 'Border color',
  11211. getSubmenuItems: function () {
  11212. return buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color');
  11213. },
  11214. onSetup: selectionTargets.onSetupCellOrRow
  11215. });
  11216. editor.ui.registry.addToggleMenuItem('tablerowheader', {
  11217. text: 'Row header',
  11218. icon: 'table-top-header',
  11219. onAction: changeRowHeader(editor),
  11220. onSetup: selectionTargets.onSetupTableRowHeaders
  11221. });
  11222. editor.ui.registry.addToggleMenuItem('tablecolheader', {
  11223. text: 'Column header',
  11224. icon: 'table-left-header',
  11225. onAction: changeColumnHeader(editor),
  11226. onSetup: selectionTargets.onSetupTableColumnHeaders
  11227. });
  11228. };
  11229. var Plugin = function (editor) {
  11230. var selections = Selections(function () {
  11231. return getBody(editor);
  11232. }, function () {
  11233. return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
  11234. }, ephemera.selectedSelector);
  11235. var selectionTargets = getSelectionTargets(editor, selections);
  11236. var resizeHandler = getResizeHandler(editor);
  11237. var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
  11238. var actions = TableActions(editor, cellSelection, resizeHandler.lazyWire);
  11239. var clipboard = Clipboard();
  11240. registerCommands(editor, actions, cellSelection, selections, clipboard);
  11241. registerQueryCommands(editor, actions, selections);
  11242. registerEvents(editor, selections, actions);
  11243. addMenuItems(editor, selections, selectionTargets, clipboard);
  11244. addButtons(editor, selections, selectionTargets, clipboard);
  11245. addToolbars(editor);
  11246. editor.on('PreInit', function () {
  11247. editor.serializer.addTempAttr(ephemera.firstSelected);
  11248. editor.serializer.addTempAttr(ephemera.lastSelected);
  11249. registerFormats(editor);
  11250. });
  11251. if (hasTabNavigation(editor)) {
  11252. editor.on('keydown', function (e) {
  11253. handle$1(e, editor, cellSelection);
  11254. });
  11255. }
  11256. editor.on('remove', function () {
  11257. resizeHandler.destroy();
  11258. });
  11259. return getApi(editor, clipboard, resizeHandler, selectionTargets);
  11260. };
  11261. function Plugin$1 () {
  11262. global$3.add('table', Plugin);
  11263. }
  11264. Plugin$1();
  11265. }());