plugin.js 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009
  1. /**
  2. * TinyMCE version 8.0.2 (2025-08-14)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  7. /* eslint-disable @typescript-eslint/no-wrapper-object-types */
  8. const hasProto = (v, constructor, predicate) => {
  9. var _a;
  10. if (predicate(v, constructor.prototype)) {
  11. return true;
  12. }
  13. else {
  14. // String-based fallback time
  15. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  16. }
  17. };
  18. const typeOf = (x) => {
  19. const t = typeof x;
  20. if (x === null) {
  21. return 'null';
  22. }
  23. else if (t === 'object' && Array.isArray(x)) {
  24. return 'array';
  25. }
  26. else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  27. return 'string';
  28. }
  29. else {
  30. return t;
  31. }
  32. };
  33. const isType$1 = (type) => (value) => typeOf(value) === type;
  34. const isSimpleType = (type) => (value) => typeof value === type;
  35. const eq$1 = (t) => (a) => t === a;
  36. const isString = isType$1('string');
  37. const isArray = isType$1('array');
  38. const isBoolean = isSimpleType('boolean');
  39. const isUndefined = eq$1(undefined);
  40. const isNullable = (a) => a === null || a === undefined;
  41. const isNonNullable = (a) => !isNullable(a);
  42. const isFunction = isSimpleType('function');
  43. const isNumber = isSimpleType('number');
  44. const noop = () => { };
  45. /** Compose two unary functions. Similar to compose, but avoids using Function.prototype.apply. */
  46. const compose1 = (fbc, fab) => (a) => fbc(fab(a));
  47. const constant = (value) => {
  48. return () => {
  49. return value;
  50. };
  51. };
  52. const identity = (x) => {
  53. return x;
  54. };
  55. const tripleEquals = (a, b) => {
  56. return a === b;
  57. };
  58. function curry(fn, ...initialArgs) {
  59. return (...restArgs) => {
  60. const all = initialArgs.concat(restArgs);
  61. return fn.apply(null, all);
  62. };
  63. }
  64. const call = (f) => {
  65. f();
  66. };
  67. const never = constant(false);
  68. const always = constant(true);
  69. /**
  70. * The `Optional` type represents a value (of any type) that potentially does
  71. * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the
  72. * value does exist) or a `None` (in which case the value does not exist). This
  73. * module defines a whole lot of FP-inspired utility functions for dealing with
  74. * `Optional` objects.
  75. *
  76. * Comparison with null or undefined:
  77. * - We don't get fancy null coalescing operators with `Optional`
  78. * - We do get fancy helper functions with `Optional`
  79. * - `Optional` support nesting, and allow for the type to still be nullable (or
  80. * another `Optional`)
  81. * - There is no option to turn off strict-optional-checks like there is for
  82. * strict-null-checks
  83. */
  84. class Optional {
  85. // The internal representation has a `tag` and a `value`, but both are
  86. // private: able to be console.logged, but not able to be accessed by code
  87. constructor(tag, value) {
  88. this.tag = tag;
  89. this.value = value;
  90. }
  91. // --- Identities ---
  92. /**
  93. * Creates a new `Optional<T>` that **does** contain a value.
  94. */
  95. static some(value) {
  96. return new Optional(true, value);
  97. }
  98. /**
  99. * Create a new `Optional<T>` that **does not** contain a value. `T` can be
  100. * any type because we don't actually have a `T`.
  101. */
  102. static none() {
  103. return Optional.singletonNone;
  104. }
  105. /**
  106. * Perform a transform on an `Optional` type. Regardless of whether this
  107. * `Optional` contains a value or not, `fold` will return a value of type `U`.
  108. * If this `Optional` does not contain a value, the `U` will be created by
  109. * calling `onNone`. If this `Optional` does contain a value, the `U` will be
  110. * created by calling `onSome`.
  111. *
  112. * For the FP enthusiasts in the room, this function:
  113. * 1. Could be used to implement all of the functions below
  114. * 2. Forms a catamorphism
  115. */
  116. fold(onNone, onSome) {
  117. if (this.tag) {
  118. return onSome(this.value);
  119. }
  120. else {
  121. return onNone();
  122. }
  123. }
  124. /**
  125. * Determine if this `Optional` object contains a value.
  126. */
  127. isSome() {
  128. return this.tag;
  129. }
  130. /**
  131. * Determine if this `Optional` object **does not** contain a value.
  132. */
  133. isNone() {
  134. return !this.tag;
  135. }
  136. // --- Functor (name stolen from Haskell / maths) ---
  137. /**
  138. * Perform a transform on an `Optional` object, **if** there is a value. If
  139. * you provide a function to turn a T into a U, this is the function you use
  140. * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain
  141. * a value then the output will also contain a value (that value being the
  142. * output of `mapper(this.value)`), and if this **does not** contain a value
  143. * then neither will the output.
  144. */
  145. map(mapper) {
  146. if (this.tag) {
  147. return Optional.some(mapper(this.value));
  148. }
  149. else {
  150. return Optional.none();
  151. }
  152. }
  153. // --- Monad (name stolen from Haskell / maths) ---
  154. /**
  155. * Perform a transform on an `Optional` object, **if** there is a value.
  156. * Unlike `map`, here the transform itself also returns an `Optional`.
  157. */
  158. bind(binder) {
  159. if (this.tag) {
  160. return binder(this.value);
  161. }
  162. else {
  163. return Optional.none();
  164. }
  165. }
  166. // --- Traversable (name stolen from Haskell / maths) ---
  167. /**
  168. * For a given predicate, this function finds out if there **exists** a value
  169. * inside this `Optional` object that meets the predicate. In practice, this
  170. * means that for `Optional`s that do not contain a value it returns false (as
  171. * no predicate-meeting value exists).
  172. */
  173. exists(predicate) {
  174. return this.tag && predicate(this.value);
  175. }
  176. /**
  177. * For a given predicate, this function finds out if **all** the values inside
  178. * this `Optional` object meet the predicate. In practice, this means that
  179. * for `Optional`s that do not contain a value it returns true (as all 0
  180. * objects do meet the predicate).
  181. */
  182. forall(predicate) {
  183. return !this.tag || predicate(this.value);
  184. }
  185. filter(predicate) {
  186. if (!this.tag || predicate(this.value)) {
  187. return this;
  188. }
  189. else {
  190. return Optional.none();
  191. }
  192. }
  193. // --- Getters ---
  194. /**
  195. * Get the value out of the inside of the `Optional` object, using a default
  196. * `replacement` value if the provided `Optional` object does not contain a
  197. * value.
  198. */
  199. getOr(replacement) {
  200. return this.tag ? this.value : replacement;
  201. }
  202. /**
  203. * Get the value out of the inside of the `Optional` object, using a default
  204. * `replacement` value if the provided `Optional` object does not contain a
  205. * value. Unlike `getOr`, in this method the `replacement` object is also
  206. * `Optional` - meaning that this method will always return an `Optional`.
  207. */
  208. or(replacement) {
  209. return this.tag ? this : replacement;
  210. }
  211. /**
  212. * Get the value out of the inside of the `Optional` object, using a default
  213. * `replacement` value if the provided `Optional` object does not contain a
  214. * value. Unlike `getOr`, in this method the `replacement` value is
  215. * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you
  216. * pass a function which (if called) will **return** the `value` you want to
  217. * use.
  218. */
  219. getOrThunk(thunk) {
  220. return this.tag ? this.value : thunk();
  221. }
  222. /**
  223. * Get the value out of the inside of the `Optional` object, using a default
  224. * `replacement` value if the provided Optional object does not contain a
  225. * value.
  226. *
  227. * Unlike `or`, in this method the `replacement` value is "thunked" - that is
  228. * to say that you don't pass a value to `orThunk`, you pass a function which
  229. * (if called) will **return** the `value` you want to use.
  230. *
  231. * Unlike `getOrThunk`, in this method the `replacement` value is also
  232. * `Optional`, meaning that this method will always return an `Optional`.
  233. */
  234. orThunk(thunk) {
  235. return this.tag ? this : thunk();
  236. }
  237. /**
  238. * Get the value out of the inside of the `Optional` object, throwing an
  239. * exception if the provided `Optional` object does not contain a value.
  240. *
  241. * WARNING:
  242. * You should only be using this function if you know that the `Optional`
  243. * object **is not** empty (otherwise you're throwing exceptions in production
  244. * code, which is bad).
  245. *
  246. * In tests this is more acceptable.
  247. *
  248. * Prefer other methods to this, such as `.each`.
  249. */
  250. getOrDie(message) {
  251. if (!this.tag) {
  252. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  253. }
  254. else {
  255. return this.value;
  256. }
  257. }
  258. // --- Interop with null and undefined ---
  259. /**
  260. * Creates an `Optional` value from a nullable (or undefined-able) input.
  261. * Null, or undefined, is converted to `None`, and anything else is converted
  262. * to `Some`.
  263. */
  264. static from(value) {
  265. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  266. }
  267. /**
  268. * Converts an `Optional` to a nullable type, by getting the value if it
  269. * exists, or returning `null` if it does not.
  270. */
  271. getOrNull() {
  272. return this.tag ? this.value : null;
  273. }
  274. /**
  275. * Converts an `Optional` to an undefined-able type, by getting the value if
  276. * it exists, or returning `undefined` if it does not.
  277. */
  278. getOrUndefined() {
  279. return this.value;
  280. }
  281. // --- Utilities ---
  282. /**
  283. * If the `Optional` contains a value, perform an action on that value.
  284. * Unlike the rest of the methods on this type, `.each` has side-effects. If
  285. * you want to transform an `Optional<T>` **into** something, then this is not
  286. * the method for you. If you want to use an `Optional<T>` to **do**
  287. * something, then this is the method for you - provided you're okay with not
  288. * doing anything in the case where the `Optional` doesn't have a value inside
  289. * it. If you're not sure whether your use-case fits into transforming
  290. * **into** something or **doing** something, check whether it has a return
  291. * value. If it does, you should be performing a transform.
  292. */
  293. each(worker) {
  294. if (this.tag) {
  295. worker(this.value);
  296. }
  297. }
  298. /**
  299. * Turn the `Optional` object into an array that contains all of the values
  300. * stored inside the `Optional`. In practice, this means the output will have
  301. * either 0 or 1 elements.
  302. */
  303. toArray() {
  304. return this.tag ? [this.value] : [];
  305. }
  306. /**
  307. * Turn the `Optional` object into a string for debugging or printing. Not
  308. * recommended for production code, but good for debugging. Also note that
  309. * these days an `Optional` object can be logged to the console directly, and
  310. * its inner value (if it exists) will be visible.
  311. */
  312. toString() {
  313. return this.tag ? `some(${this.value})` : 'none()';
  314. }
  315. }
  316. // Sneaky optimisation: every instance of Optional.none is identical, so just
  317. // reuse the same object
  318. Optional.singletonNone = new Optional(false);
  319. const nativeSlice = Array.prototype.slice;
  320. const nativeIndexOf = Array.prototype.indexOf;
  321. const nativePush = Array.prototype.push;
  322. const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t);
  323. const contains = (xs, x) => rawIndexOf(xs, x) > -1;
  324. const exists = (xs, pred) => {
  325. for (let i = 0, len = xs.length; i < len; i++) {
  326. const x = xs[i];
  327. if (pred(x, i)) {
  328. return true;
  329. }
  330. }
  331. return false;
  332. };
  333. const range = (num, f) => {
  334. const r = [];
  335. for (let i = 0; i < num; i++) {
  336. r.push(f(i));
  337. }
  338. return r;
  339. };
  340. const map = (xs, f) => {
  341. // pre-allocating array size when it's guaranteed to be known
  342. // http://jsperf.com/push-allocated-vs-dynamic/22
  343. const len = xs.length;
  344. const r = new Array(len);
  345. for (let i = 0; i < len; i++) {
  346. const x = xs[i];
  347. r[i] = f(x, i);
  348. }
  349. return r;
  350. };
  351. // Unwound implementing other functions in terms of each.
  352. // The code size is roughly the same, and it should allow for better optimisation.
  353. // const each = function<T, U>(xs: T[], f: (x: T, i?: number, xs?: T[]) => void): void {
  354. const each$1 = (xs, f) => {
  355. for (let i = 0, len = xs.length; i < len; i++) {
  356. const x = xs[i];
  357. f(x, i);
  358. }
  359. };
  360. const eachr = (xs, f) => {
  361. for (let i = xs.length - 1; i >= 0; i--) {
  362. const x = xs[i];
  363. f(x, i);
  364. }
  365. };
  366. const partition = (xs, pred) => {
  367. const pass = [];
  368. const fail = [];
  369. for (let i = 0, len = xs.length; i < len; i++) {
  370. const x = xs[i];
  371. const arr = pred(x, i) ? pass : fail;
  372. arr.push(x);
  373. }
  374. return { pass, fail };
  375. };
  376. const filter$1 = (xs, pred) => {
  377. const r = [];
  378. for (let i = 0, len = xs.length; i < len; i++) {
  379. const x = xs[i];
  380. if (pred(x, i)) {
  381. r.push(x);
  382. }
  383. }
  384. return r;
  385. };
  386. const foldr = (xs, f, acc) => {
  387. eachr(xs, (x, i) => {
  388. acc = f(acc, x, i);
  389. });
  390. return acc;
  391. };
  392. const foldl = (xs, f, acc) => {
  393. each$1(xs, (x, i) => {
  394. acc = f(acc, x, i);
  395. });
  396. return acc;
  397. };
  398. const findUntil = (xs, pred, until) => {
  399. for (let i = 0, len = xs.length; i < len; i++) {
  400. const x = xs[i];
  401. if (pred(x, i)) {
  402. return Optional.some(x);
  403. }
  404. else if (until(x, i)) {
  405. break;
  406. }
  407. }
  408. return Optional.none();
  409. };
  410. const find = (xs, pred) => {
  411. return findUntil(xs, pred, never);
  412. };
  413. const findIndex = (xs, pred) => {
  414. for (let i = 0, len = xs.length; i < len; i++) {
  415. const x = xs[i];
  416. if (pred(x, i)) {
  417. return Optional.some(i);
  418. }
  419. }
  420. return Optional.none();
  421. };
  422. const flatten$1 = (xs) => {
  423. // Note, this is possible because push supports multiple arguments:
  424. // http://jsperf.com/concat-push/6
  425. // Note that in the past, concat() would silently work (very slowly) for array-like objects.
  426. // With this change it will throw an error.
  427. const r = [];
  428. for (let i = 0, len = xs.length; i < len; ++i) {
  429. // Ensure that each value is an array itself
  430. if (!isArray(xs[i])) {
  431. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  432. }
  433. nativePush.apply(r, xs[i]);
  434. }
  435. return r;
  436. };
  437. const bind = (xs, f) => flatten$1(map(xs, f));
  438. const forall = (xs, pred) => {
  439. for (let i = 0, len = xs.length; i < len; ++i) {
  440. const x = xs[i];
  441. if (pred(x, i) !== true) {
  442. return false;
  443. }
  444. }
  445. return true;
  446. };
  447. const mapToObject = (xs, f) => {
  448. const r = {};
  449. for (let i = 0, len = xs.length; i < len; i++) {
  450. const x = xs[i];
  451. r[String(x)] = f(x, i);
  452. }
  453. return r;
  454. };
  455. const get$4 = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  456. const head = (xs) => get$4(xs, 0);
  457. const last = (xs) => get$4(xs, xs.length - 1);
  458. isFunction(Array.from) ? Array.from : (x) => nativeSlice.call(x);
  459. const findMap = (arr, f) => {
  460. for (let i = 0; i < arr.length; i++) {
  461. const r = f(arr[i], i);
  462. if (r.isSome()) {
  463. return r;
  464. }
  465. }
  466. return Optional.none();
  467. };
  468. // There are many variations of Object iteration that are faster than the 'for-in' style:
  469. // http://jsperf.com/object-keys-iteration/107
  470. //
  471. // Use the native keys if it is available (IE9+), otherwise fall back to manually filtering
  472. const keys = Object.keys;
  473. const hasOwnProperty = Object.hasOwnProperty;
  474. const each = (obj, f) => {
  475. const props = keys(obj);
  476. for (let k = 0, len = props.length; k < len; k++) {
  477. const i = props[k];
  478. const x = obj[i];
  479. f(x, i);
  480. }
  481. };
  482. const objAcc = (r) => (x, i) => {
  483. r[i] = x;
  484. };
  485. const internalFilter = (obj, pred, onTrue, onFalse) => {
  486. each(obj, (x, i) => {
  487. (pred(x, i) ? onTrue : onFalse)(x, i);
  488. });
  489. };
  490. const filter = (obj, pred) => {
  491. const t = {};
  492. internalFilter(obj, pred, objAcc(t), noop);
  493. return t;
  494. };
  495. const mapToArray = (obj, f) => {
  496. const r = [];
  497. each(obj, (value, name) => {
  498. r.push(f(value, name));
  499. });
  500. return r;
  501. };
  502. const values = (obj) => {
  503. return mapToArray(obj, identity);
  504. };
  505. const size = (obj) => {
  506. return keys(obj).length;
  507. };
  508. const get$3 = (obj, key) => {
  509. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  510. };
  511. const has = (obj, key) => hasOwnProperty.call(obj, key);
  512. const hasNonNullableKey = (obj, key) => has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  513. const isEmpty$1 = (r) => {
  514. for (const x in r) {
  515. if (hasOwnProperty.call(r, x)) {
  516. return false;
  517. }
  518. }
  519. return true;
  520. };
  521. const Cell = (initial) => {
  522. let value = initial;
  523. const get = () => {
  524. return value;
  525. };
  526. const set = (v) => {
  527. value = v;
  528. };
  529. return {
  530. get,
  531. set
  532. };
  533. };
  534. /**
  535. * **Is** the value stored inside this Optional object equal to `rhs`?
  536. */
  537. const is$2 = (lhs, rhs, comparator = tripleEquals) => lhs.exists((left) => comparator(left, rhs));
  538. const cat = (arr) => {
  539. const r = [];
  540. const push = (x) => {
  541. r.push(x);
  542. };
  543. for (let i = 0; i < arr.length; i++) {
  544. arr[i].each(push);
  545. }
  546. return r;
  547. };
  548. /*
  549. Notes on the lift functions:
  550. - We used to have a generic liftN, but we were concerned about its type-safety, and the below variants were faster in microbenchmarks.
  551. - The getOrDie calls are partial functions, but are checked beforehand. This is faster and more convenient (but less safe) than folds.
  552. - && is used instead of a loop for simplicity and performance.
  553. */
  554. const lift2 = (oa, ob, f) => oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  555. const flatten = (oot) => oot.bind(identity);
  556. // This can help with type inference, by specifying the type param on the none case, so the caller doesn't have to.
  557. const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
  558. const singleton = (doRevoke) => {
  559. const subject = Cell(Optional.none());
  560. const revoke = () => subject.get().each(doRevoke);
  561. const clear = () => {
  562. revoke();
  563. subject.set(Optional.none());
  564. };
  565. const isSet = () => subject.get().isSome();
  566. const get = () => subject.get();
  567. const set = (s) => {
  568. revoke();
  569. subject.set(Optional.some(s));
  570. };
  571. return {
  572. clear,
  573. isSet,
  574. get,
  575. set
  576. };
  577. };
  578. const unbindable = () => singleton((s) => s.unbind());
  579. const removeFromStart = (str, numChars) => {
  580. return str.substring(numChars);
  581. };
  582. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  583. const removeLeading = (str, prefix) => {
  584. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  585. };
  586. /** Does 'str' start with 'prefix'?
  587. * Note: all strings start with the empty string.
  588. * More formally, for all strings x, startsWith(x, "").
  589. * This is so that for all strings x and y, startsWith(y + x, y)
  590. */
  591. const startsWith = (str, prefix) => {
  592. return checkRange(str, prefix, 0);
  593. };
  594. const blank = (r) => (s) => s.replace(r, '');
  595. /** removes all leading and trailing spaces */
  596. const trim = blank(/^\s+|\s+$/g);
  597. const isNotEmpty = (s) => s.length > 0;
  598. const isEmpty = (s) => !isNotEmpty(s);
  599. const toInt = (value, radix = 10) => {
  600. const num = parseInt(value, radix);
  601. return isNaN(num) ? Optional.none() : Optional.some(num);
  602. };
  603. const toFloat = (value) => {
  604. const num = parseFloat(value);
  605. return isNaN(num) ? Optional.none() : Optional.some(num);
  606. };
  607. const cached = (f) => {
  608. let called = false;
  609. let r;
  610. return (...args) => {
  611. if (!called) {
  612. called = true;
  613. r = f.apply(null, args);
  614. }
  615. return r;
  616. };
  617. };
  618. const fromHtml = (html, scope) => {
  619. const doc = scope || document;
  620. const div = doc.createElement('div');
  621. div.innerHTML = html;
  622. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  623. const message = 'HTML does not have a single root node';
  624. // eslint-disable-next-line no-console
  625. console.error(message, html);
  626. throw new Error(message);
  627. }
  628. return fromDom$1(div.childNodes[0]);
  629. };
  630. const fromTag = (tag, scope) => {
  631. const doc = scope || document;
  632. const node = doc.createElement(tag);
  633. return fromDom$1(node);
  634. };
  635. const fromText = (text, scope) => {
  636. const doc = scope || document;
  637. const node = doc.createTextNode(text);
  638. return fromDom$1(node);
  639. };
  640. const fromDom$1 = (node) => {
  641. // TODO: Consider removing this check, but left atm for safety
  642. if (node === null || node === undefined) {
  643. throw new Error('Node cannot be null or undefined');
  644. }
  645. return {
  646. dom: node
  647. };
  648. };
  649. const fromPoint = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$1);
  650. // tslint:disable-next-line:variable-name
  651. const SugarElement = {
  652. fromHtml,
  653. fromTag,
  654. fromText,
  655. fromDom: fromDom$1,
  656. fromPoint
  657. };
  658. const COMMENT = 8;
  659. const DOCUMENT = 9;
  660. const DOCUMENT_FRAGMENT = 11;
  661. const ELEMENT = 1;
  662. const TEXT = 3;
  663. const is$1 = (element, selector) => {
  664. const dom = element.dom;
  665. if (dom.nodeType !== ELEMENT) {
  666. return false;
  667. }
  668. else {
  669. const elem = dom;
  670. if (elem.matches !== undefined) {
  671. return elem.matches(selector);
  672. }
  673. else if (elem.msMatchesSelector !== undefined) {
  674. return elem.msMatchesSelector(selector);
  675. }
  676. else if (elem.webkitMatchesSelector !== undefined) {
  677. return elem.webkitMatchesSelector(selector);
  678. }
  679. else if (elem.mozMatchesSelector !== undefined) {
  680. // cast to any as mozMatchesSelector doesn't exist in TS DOM lib
  681. return elem.mozMatchesSelector(selector);
  682. }
  683. else {
  684. throw new Error('Browser lacks native selectors');
  685. } // unfortunately we can't throw this on startup :(
  686. }
  687. };
  688. const bypassSelector = (dom) =>
  689. // Only elements, documents and shadow roots support querySelector
  690. // shadow root element type is DOCUMENT_FRAGMENT
  691. dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT ||
  692. // IE fix for complex queries on empty nodes: http://jsfiddle.net/spyder/fv9ptr5L/
  693. dom.childElementCount === 0;
  694. const all$1 = (selector, scope) => {
  695. const base = scope === undefined ? document : scope.dom;
  696. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
  697. };
  698. const one = (selector, scope) => {
  699. const base = scope === undefined ? document : scope.dom;
  700. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  701. };
  702. const eq = (e1, e2) => e1.dom === e2.dom;
  703. const is = is$1;
  704. const name = (element) => {
  705. const r = element.dom.nodeName;
  706. return r.toLowerCase();
  707. };
  708. const type = (element) => element.dom.nodeType;
  709. const isType = (t) => (element) => type(element) === t;
  710. const isComment = (element) => type(element) === COMMENT || name(element) === '#comment';
  711. const isElement = isType(ELEMENT);
  712. const isText = isType(TEXT);
  713. const isDocument = isType(DOCUMENT);
  714. const isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  715. const isTag = (tag) => (e) => isElement(e) && name(e) === tag;
  716. /**
  717. * The document associated with the current element
  718. * NOTE: this will throw if the owner is null.
  719. */
  720. const owner = (element) => SugarElement.fromDom(element.dom.ownerDocument);
  721. /**
  722. * If the element is a document, return it. Otherwise, return its ownerDocument.
  723. * @param dos
  724. */
  725. const documentOrOwner = (dos) => isDocument(dos) ? dos : owner(dos);
  726. const parent = (element) => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  727. const parents = (element, isRoot) => {
  728. const stop = isFunction(isRoot) ? isRoot : never;
  729. // This is used a *lot* so it needs to be performant, not recursive
  730. let dom = element.dom;
  731. const ret = [];
  732. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  733. const rawParent = dom.parentNode;
  734. const p = SugarElement.fromDom(rawParent);
  735. ret.push(p);
  736. if (stop(p) === true) {
  737. break;
  738. }
  739. else {
  740. dom = rawParent;
  741. }
  742. }
  743. return ret;
  744. };
  745. const prevSibling = (element) => Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  746. const nextSibling = (element) => Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  747. const children$3 = (element) => map(element.dom.childNodes, SugarElement.fromDom);
  748. const child$3 = (element, index) => {
  749. const cs = element.dom.childNodes;
  750. return Optional.from(cs[index]).map(SugarElement.fromDom);
  751. };
  752. const firstChild = (element) => child$3(element, 0);
  753. /**
  754. * Is the element a ShadowRoot?
  755. *
  756. * Note: this is insufficient to test if any element is a shadow root, but it is sufficient to differentiate between
  757. * a Document and a ShadowRoot.
  758. */
  759. const isShadowRoot = (dos) => isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  760. const getRootNode = (e) => SugarElement.fromDom(e.dom.getRootNode());
  761. /** If this element is in a ShadowRoot, return it. */
  762. const getShadowRoot = (e) => {
  763. const r = getRootNode(e);
  764. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  765. };
  766. /** Return the host of a ShadowRoot.
  767. *
  768. * This function will throw if Shadow DOM is unsupported in the browser, or if the host is null.
  769. * If you actually have a ShadowRoot, this shouldn't happen.
  770. */
  771. const getShadowHost = (e) => SugarElement.fromDom(e.dom.host);
  772. const before = (marker, element) => {
  773. const parent$1 = parent(marker);
  774. parent$1.each((v) => {
  775. v.dom.insertBefore(element.dom, marker.dom);
  776. });
  777. };
  778. const after$1 = (marker, element) => {
  779. const sibling = nextSibling(marker);
  780. sibling.fold(() => {
  781. const parent$1 = parent(marker);
  782. parent$1.each((v) => {
  783. append$1(v, element);
  784. });
  785. }, (v) => {
  786. before(v, element);
  787. });
  788. };
  789. const prepend = (parent, element) => {
  790. const firstChild$1 = firstChild(parent);
  791. firstChild$1.fold(() => {
  792. append$1(parent, element);
  793. }, (v) => {
  794. parent.dom.insertBefore(element.dom, v.dom);
  795. });
  796. };
  797. const append$1 = (parent, element) => {
  798. parent.dom.appendChild(element.dom);
  799. };
  800. const wrap = (element, wrapper) => {
  801. before(element, wrapper);
  802. append$1(wrapper, element);
  803. };
  804. const after = (marker, elements) => {
  805. each$1(elements, (x, i) => {
  806. const e = i === 0 ? marker : elements[i - 1];
  807. after$1(e, x);
  808. });
  809. };
  810. const append = (parent, elements) => {
  811. each$1(elements, (x) => {
  812. append$1(parent, x);
  813. });
  814. };
  815. const rawSet = (dom, key, value) => {
  816. /*
  817. * JQuery coerced everything to a string, and silently did nothing on text node/null/undefined.
  818. *
  819. * We fail on those invalid cases, only allowing numbers and booleans.
  820. */
  821. if (isString(value) || isBoolean(value) || isNumber(value)) {
  822. dom.setAttribute(key, value + '');
  823. }
  824. else {
  825. // eslint-disable-next-line no-console
  826. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  827. throw new Error('Attribute value was not simple');
  828. }
  829. };
  830. const set$2 = (element, key, value) => {
  831. rawSet(element.dom, key, value);
  832. };
  833. const setAll = (element, attrs) => {
  834. const dom = element.dom;
  835. each(attrs, (v, k) => {
  836. rawSet(dom, k, v);
  837. });
  838. };
  839. const get$2 = (element, key) => {
  840. const v = element.dom.getAttribute(key);
  841. // undefined is the more appropriate value for JS, and this matches JQuery
  842. return v === null ? undefined : v;
  843. };
  844. const getOpt = (element, key) => Optional.from(get$2(element, key));
  845. const remove$2 = (element, key) => {
  846. element.dom.removeAttribute(key);
  847. };
  848. const clone = (element) => foldl(element.dom.attributes, (acc, attr) => {
  849. acc[attr.name] = attr.value;
  850. return acc;
  851. }, {});
  852. const remove$1 = (element) => {
  853. const dom = element.dom;
  854. if (dom.parentNode !== null) {
  855. dom.parentNode.removeChild(dom);
  856. }
  857. };
  858. const unwrap = (wrapper) => {
  859. const children = children$3(wrapper);
  860. if (children.length > 0) {
  861. after(wrapper, children);
  862. }
  863. remove$1(wrapper);
  864. };
  865. const fromDom = (nodes) => map(nodes, SugarElement.fromDom);
  866. // some elements, such as mathml, don't have style attributes
  867. // others, such as angular elements, have style attributes that aren't a CSSStyleDeclaration
  868. const isSupported = (dom) => dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  869. // Node.contains() is very, very, very good performance
  870. // http://jsperf.com/closest-vs-contains/5
  871. const inBody = (element) => {
  872. // Technically this is only required on IE, where contains() returns false for text nodes.
  873. // But it's cheap enough to run everywhere and Sugar doesn't have platform detection (yet).
  874. const dom = isText(element) ? element.dom.parentNode : element.dom;
  875. // use ownerDocument.body to ensure this works inside iframes.
  876. // Normally contains is bad because an element "contains" itself, but here we want that.
  877. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  878. return false;
  879. }
  880. const doc = dom.ownerDocument;
  881. return getShadowRoot(SugarElement.fromDom(dom)).fold(() => doc.body.contains(dom), compose1(inBody, getShadowHost));
  882. };
  883. const internalSet = (dom, property, value) => {
  884. // This is going to hurt. Apologies.
  885. // JQuery coerces numbers to pixels for certain property names, and other times lets numbers through.
  886. // we're going to be explicit; strings only.
  887. if (!isString(value)) {
  888. // eslint-disable-next-line no-console
  889. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  890. throw new Error('CSS value must be a string: ' + value);
  891. }
  892. // removed: support for dom().style[property] where prop is camel case instead of normal property name
  893. if (isSupported(dom)) {
  894. dom.style.setProperty(property, value);
  895. }
  896. };
  897. const internalRemove = (dom, property) => {
  898. /*
  899. * IE9 and above - MDN doesn't have details, but here's a couple of random internet claims
  900. *
  901. * http://help.dottoro.com/ljopsjck.php
  902. * http://stackoverflow.com/a/7901886/7546
  903. */
  904. if (isSupported(dom)) {
  905. dom.style.removeProperty(property);
  906. }
  907. };
  908. const set$1 = (element, property, value) => {
  909. const dom = element.dom;
  910. internalSet(dom, property, value);
  911. };
  912. /*
  913. * NOTE: For certain properties, this returns the "used value" which is subtly different to the "computed value" (despite calling getComputedStyle).
  914. * Blame CSS 2.0.
  915. *
  916. * https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  917. */
  918. const get$1 = (element, property) => {
  919. const dom = element.dom;
  920. /*
  921. * IE9 and above per
  922. * https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle
  923. *
  924. * Not in numerosity, because it doesn't memoize and looking this up dynamically in performance critical code would be horrendous.
  925. *
  926. * JQuery has some magic here for IE popups, but we don't really need that.
  927. * It also uses element.ownerDocument.defaultView to handle iframes but that hasn't been required since FF 3.6.
  928. */
  929. const styles = window.getComputedStyle(dom);
  930. const r = styles.getPropertyValue(property);
  931. // jquery-ism: If r is an empty string, check that the element is not in a document. If it isn't, return the raw value.
  932. // Turns out we do this a lot.
  933. return (r === '' && !inBody(element)) ? getUnsafeProperty(dom, property) : r;
  934. };
  935. // removed: support for dom().style[property] where prop is camel case instead of normal property name
  936. // empty string is what the browsers (IE11 and Chrome) return when the propertyValue doesn't exists.
  937. const getUnsafeProperty = (dom, property) => isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  938. /*
  939. * Gets the raw value from the style attribute. Useful for retrieving "used values" from the DOM:
  940. * https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  941. *
  942. * Returns NONE if the property isn't set, or the value is an empty string.
  943. */
  944. const getRaw$1 = (element, property) => {
  945. const dom = element.dom;
  946. const raw = getUnsafeProperty(dom, property);
  947. return Optional.from(raw).filter((r) => r.length > 0);
  948. };
  949. const remove = (element, property) => {
  950. const dom = element.dom;
  951. internalRemove(dom, property);
  952. if (is$2(getOpt(element, 'style').map(trim), '')) {
  953. // No more styles left, remove the style attribute as well
  954. remove$2(element, 'style');
  955. }
  956. };
  957. const Dimension = (name, getOffset) => {
  958. const set = (element, h) => {
  959. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  960. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  961. }
  962. const dom = element.dom;
  963. if (isSupported(dom)) {
  964. dom.style[name] = h + 'px';
  965. }
  966. };
  967. /*
  968. * jQuery supports querying width and height on the document and window objects.
  969. *
  970. * TBIO doesn't do this, so the code is removed to save space, but left here just in case.
  971. */
  972. /*
  973. var getDocumentWidth = (element) => {
  974. var dom = element.dom;
  975. if (Node.isDocument(element)) {
  976. var body = dom.body;
  977. var doc = dom.documentElement;
  978. return Math.max(
  979. body.scrollHeight,
  980. doc.scrollHeight,
  981. body.offsetHeight,
  982. doc.offsetHeight,
  983. doc.clientHeight
  984. );
  985. }
  986. };
  987. var getWindowWidth = (element) => {
  988. var dom = element.dom;
  989. if (dom.window === dom) {
  990. // There is no offsetHeight on a window, so use the clientHeight of the document
  991. return dom.document.documentElement.clientHeight;
  992. }
  993. };
  994. */
  995. const get = (element) => {
  996. const r = getOffset(element);
  997. // zero or null means non-standard or disconnected, fall back to CSS
  998. if (r <= 0 || r === null) {
  999. const css = get$1(element, name);
  1000. // ugh this feels dirty, but it saves cycles
  1001. return parseFloat(css) || 0;
  1002. }
  1003. return r;
  1004. };
  1005. // in jQuery, getOuter replicates (or uses) box-sizing: border-box calculations
  1006. // although these calculations only seem relevant for quirks mode, and edge cases TBIO doesn't rely on
  1007. const getOuter = get;
  1008. const aggregate = (element, properties) => foldl(properties, (acc, property) => {
  1009. const val = get$1(element, property);
  1010. const value = val === undefined ? 0 : parseInt(val, 10);
  1011. return isNaN(value) ? acc : acc + value;
  1012. }, 0);
  1013. const max = (element, value, properties) => {
  1014. const cumulativeInclusions = aggregate(element, properties);
  1015. // if max-height is 100px and your cumulativeInclusions is 150px, there is no way max-height can be 100px, so we return 0.
  1016. const absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  1017. return absoluteMax;
  1018. };
  1019. return {
  1020. set,
  1021. get,
  1022. getOuter,
  1023. aggregate,
  1024. max
  1025. };
  1026. };
  1027. const toNumber = (px, fallback) => toFloat(px).getOr(fallback);
  1028. const getProp = (element, name, fallback) => toNumber(get$1(element, name), fallback);
  1029. const calcContentBoxSize = (element, size, upper, lower) => {
  1030. const paddingUpper = getProp(element, `padding-${upper}`, 0);
  1031. const paddingLower = getProp(element, `padding-${lower}`, 0);
  1032. const borderUpper = getProp(element, `border-${upper}-width`, 0);
  1033. const borderLower = getProp(element, `border-${lower}-width`, 0);
  1034. return size - paddingUpper - paddingLower - borderUpper - borderLower;
  1035. };
  1036. const getCalculatedWidth = (element, boxSizing) => {
  1037. const dom = element.dom;
  1038. const width = dom.getBoundingClientRect().width || dom.offsetWidth;
  1039. return boxSizing === 'border-box' ? width : calcContentBoxSize(element, width, 'left', 'right');
  1040. };
  1041. const getInnerWidth = (element) => getCalculatedWidth(element, 'content-box');
  1042. Dimension('width', (element) => {
  1043. const dom = element.dom;
  1044. return inBody(element) ? dom.getBoundingClientRect().width : dom.offsetWidth;
  1045. });
  1046. const getInner = getInnerWidth;
  1047. const NodeValue = (is, name) => {
  1048. const get = (element) => {
  1049. if (!is(element)) {
  1050. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  1051. }
  1052. return getOption(element).getOr('');
  1053. };
  1054. const getOption = (element) => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  1055. const set = (element, value) => {
  1056. if (!is(element)) {
  1057. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  1058. }
  1059. element.dom.nodeValue = value;
  1060. };
  1061. return {
  1062. get,
  1063. getOption,
  1064. set
  1065. };
  1066. };
  1067. const api = NodeValue(isText, 'text');
  1068. const get = (element) => api.get(element);
  1069. const set = (element, value) => api.set(element, value);
  1070. var ClosestOrAncestor = (is, ancestor, scope, a, isRoot) => {
  1071. if (is(scope, a)) {
  1072. return Optional.some(scope);
  1073. }
  1074. else if (isFunction(isRoot) && isRoot(scope)) {
  1075. return Optional.none();
  1076. }
  1077. else {
  1078. return ancestor(scope, a, isRoot);
  1079. }
  1080. };
  1081. const ancestor$1 = (scope, predicate, isRoot) => {
  1082. let element = scope.dom;
  1083. const stop = isFunction(isRoot) ? isRoot : never;
  1084. while (element.parentNode) {
  1085. element = element.parentNode;
  1086. const el = SugarElement.fromDom(element);
  1087. if (predicate(el)) {
  1088. return Optional.some(el);
  1089. }
  1090. else if (stop(el)) {
  1091. break;
  1092. }
  1093. }
  1094. return Optional.none();
  1095. };
  1096. const closest$2 = (scope, predicate, isRoot) => {
  1097. // This is required to avoid ClosestOrAncestor passing the predicate to itself
  1098. const is = (s, test) => test(s);
  1099. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  1100. };
  1101. const child$2 = (scope, predicate) => {
  1102. const pred = (node) => predicate(SugarElement.fromDom(node));
  1103. const result = find(scope.dom.childNodes, pred);
  1104. return result.map(SugarElement.fromDom);
  1105. };
  1106. const ancestor = (scope, selector, isRoot) => ancestor$1(scope, (e) => is$1(e, selector), isRoot);
  1107. const child$1 = (scope, selector) => child$2(scope, (e) => is$1(e, selector));
  1108. const descendant = (scope, selector) => one(selector, scope);
  1109. // Returns Some(closest ancestor element (sugared)) matching 'selector' up to isRoot, or None() otherwise
  1110. const closest$1 = (scope, selector, isRoot) => {
  1111. const is = (element, selector) => is$1(element, selector);
  1112. return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
  1113. };
  1114. const closest = (target) => closest$1(target, '[contenteditable]');
  1115. const isEditable = (element, assumeEditable = false) => {
  1116. if (inBody(element)) {
  1117. return element.dom.isContentEditable;
  1118. }
  1119. else {
  1120. // Find the closest contenteditable element and check if it's editable
  1121. return closest(element).fold(constant(assumeEditable), (editable) => getRaw(editable) === 'true');
  1122. }
  1123. };
  1124. const getRaw = (element) => element.dom.contentEditable;
  1125. const children$2 = (scope, predicate) => filter$1(children$3(scope), predicate);
  1126. const descendants$1 = (scope, predicate) => {
  1127. let result = [];
  1128. // Recurse.toArray() might help here
  1129. each$1(children$3(scope), (x) => {
  1130. if (predicate(x)) {
  1131. result = result.concat([x]);
  1132. }
  1133. result = result.concat(descendants$1(x, predicate));
  1134. });
  1135. return result;
  1136. };
  1137. const children$1 = (scope, selector) =>
  1138. // It may surprise you to learn this is exactly what JQuery does
  1139. // TODO: Avoid all the wrapping and unwrapping
  1140. children$2(scope, (e) => is$1(e, selector));
  1141. const descendants = (scope, selector) => all$1(selector, scope);
  1142. const child = (scope, selector) => child$1(scope, selector).isSome();
  1143. /*
  1144. NOTE: This file is partially duplicated in the following locations:
  1145. - models/dom/table/core/TableUtils.ts
  1146. - advtable
  1147. Make sure that if making changes to this file, the other files are updated as well
  1148. */
  1149. const getNodeName = (elm) => elm.nodeName.toLowerCase();
  1150. const getBody = (editor) => SugarElement.fromDom(editor.getBody());
  1151. const getIsRoot = (editor) => (element) => eq(element, getBody(editor));
  1152. const removePxSuffix = (size) => size ? size.replace(/px$/, '') : '';
  1153. const addPxSuffix = (size) => /^\d+(\.\d+)?$/.test(size) ? size + 'px' : size;
  1154. const getSelectionStart = (editor) => SugarElement.fromDom(editor.selection.getStart());
  1155. const getSelectionEnd = (editor) => SugarElement.fromDom(editor.selection.getEnd());
  1156. const isInEditableContext = (cell) => closest$2(cell, isTag('table')).forall(isEditable);
  1157. const validSectionList = ['tfoot', 'thead', 'tbody', 'colgroup'];
  1158. const isValidSection = (parentName) => contains(validSectionList, parentName);
  1159. const grid = (rows, columns) => ({
  1160. rows,
  1161. columns
  1162. });
  1163. const detail = (element, rowspan, colspan) => ({
  1164. element,
  1165. rowspan,
  1166. colspan
  1167. });
  1168. const extended = (element, rowspan, colspan, row, column, isLocked) => ({
  1169. element,
  1170. rowspan,
  1171. colspan,
  1172. row,
  1173. column,
  1174. isLocked
  1175. });
  1176. const rowdetail = (element, cells, section) => ({
  1177. element,
  1178. cells,
  1179. section
  1180. });
  1181. const bounds = (startRow, startCol, finishRow, finishCol) => ({
  1182. startRow,
  1183. startCol,
  1184. finishRow,
  1185. finishCol
  1186. });
  1187. const columnext = (element, colspan, column) => ({
  1188. element,
  1189. colspan,
  1190. column
  1191. });
  1192. const colgroup = (element, columns) => ({
  1193. element,
  1194. columns
  1195. });
  1196. const getAttrValue = (cell, name, fallback = 0) => getOpt(cell, name).map((value) => parseInt(value, 10)).getOr(fallback);
  1197. const firstLayer = (scope, selector) => {
  1198. return filterFirstLayer(scope, selector, always);
  1199. };
  1200. const filterFirstLayer = (scope, selector, predicate) => {
  1201. return bind(children$3(scope), (x) => {
  1202. if (is$1(x, selector)) {
  1203. return predicate(x) ? [x] : [];
  1204. }
  1205. else {
  1206. return filterFirstLayer(x, selector, predicate);
  1207. }
  1208. });
  1209. };
  1210. // lookup inside this table
  1211. const lookup = (tags, element, isRoot = never) => {
  1212. // If the element we're inspecting is the root, we definitely don't want it.
  1213. if (isRoot(element)) {
  1214. return Optional.none();
  1215. }
  1216. // This looks a lot like SelectorFind.closest, with one big exception - the isRoot check.
  1217. // The code here will look for parents if passed a table, SelectorFind.closest with that specific isRoot check won't.
  1218. if (contains(tags, name(element))) {
  1219. return Optional.some(element);
  1220. }
  1221. const isRootOrUpperTable = (elm) => is$1(elm, 'table') || isRoot(elm);
  1222. return ancestor(element, tags.join(','), isRootOrUpperTable);
  1223. };
  1224. /*
  1225. * Identify the optional cell that element represents.
  1226. */
  1227. const cell = (element, isRoot) => lookup(['td', 'th'], element, isRoot);
  1228. const cells = (ancestor) => firstLayer(ancestor, 'th,td');
  1229. const columns = (ancestor) => {
  1230. if (is$1(ancestor, 'colgroup')) {
  1231. return children$1(ancestor, 'col');
  1232. }
  1233. else {
  1234. return bind(columnGroups(ancestor), (columnGroup) => children$1(columnGroup, 'col'));
  1235. }
  1236. };
  1237. const table = (element, isRoot) => closest$1(element, 'table', isRoot);
  1238. const rows = (ancestor) => firstLayer(ancestor, 'tr');
  1239. const columnGroups = (ancestor) => table(ancestor).fold(constant([]), (table) => children$1(table, 'colgroup'));
  1240. const isHeaderCell = isTag('th');
  1241. const getRowHeaderType = (isHeaderRow, isHeaderCells) => {
  1242. if (isHeaderRow && isHeaderCells) {
  1243. return 'sectionCells';
  1244. }
  1245. else if (isHeaderRow) {
  1246. return 'section';
  1247. }
  1248. else {
  1249. return 'cells';
  1250. }
  1251. };
  1252. const getRowType$1 = (row) => {
  1253. // Header rows can use a combination of theads and ths - want to detect the different combinations
  1254. const isHeaderRow = row.section === 'thead';
  1255. const isHeaderCells = is$2(findCommonCellType(row.cells), 'th');
  1256. if (row.section === 'tfoot') {
  1257. return { type: 'footer' };
  1258. }
  1259. else if (isHeaderRow || isHeaderCells) {
  1260. return { type: 'header', subType: getRowHeaderType(isHeaderRow, isHeaderCells) };
  1261. }
  1262. else {
  1263. return { type: 'body' };
  1264. }
  1265. };
  1266. const findCommonCellType = (cells) => {
  1267. const headerCells = filter$1(cells, (cell) => isHeaderCell(cell.element));
  1268. if (headerCells.length === 0) {
  1269. return Optional.some('td');
  1270. }
  1271. else if (headerCells.length === cells.length) {
  1272. return Optional.some('th');
  1273. }
  1274. else {
  1275. return Optional.none();
  1276. }
  1277. };
  1278. const findCommonRowType = (rows) => {
  1279. const rowTypes = map(rows, (row) => getRowType$1(row).type);
  1280. const hasHeader = contains(rowTypes, 'header');
  1281. const hasFooter = contains(rowTypes, 'footer');
  1282. if (!hasHeader && !hasFooter) {
  1283. return Optional.some('body');
  1284. }
  1285. else {
  1286. const hasBody = contains(rowTypes, 'body');
  1287. if (hasHeader && !hasBody && !hasFooter) {
  1288. return Optional.some('header');
  1289. }
  1290. else if (!hasHeader && !hasBody && hasFooter) {
  1291. return Optional.some('footer');
  1292. }
  1293. else {
  1294. return Optional.none();
  1295. }
  1296. }
  1297. };
  1298. const fromRowsOrColGroups = (elems, getSection) => map(elems, (row) => {
  1299. if (name(row) === 'colgroup') {
  1300. const cells = map(columns(row), (column) => {
  1301. const colspan = getAttrValue(column, 'span', 1);
  1302. return detail(column, 1, colspan);
  1303. });
  1304. return rowdetail(row, cells, 'colgroup');
  1305. }
  1306. else {
  1307. const cells$1 = map(cells(row), (cell) => {
  1308. const rowspan = getAttrValue(cell, 'rowspan', 1);
  1309. const colspan = getAttrValue(cell, 'colspan', 1);
  1310. return detail(cell, rowspan, colspan);
  1311. });
  1312. return rowdetail(row, cells$1, getSection(row));
  1313. }
  1314. });
  1315. const getParentSection = (group) => parent(group).map((parent) => {
  1316. const parentName = name(parent);
  1317. return isValidSection(parentName) ? parentName : 'tbody';
  1318. }).getOr('tbody');
  1319. /*
  1320. * Takes a DOM table and returns a list of list of:
  1321. element: row element
  1322. cells: (id, rowspan, colspan) structs
  1323. */
  1324. const fromTable$1 = (table) => {
  1325. const rows$1 = rows(table);
  1326. const columnGroups$1 = columnGroups(table);
  1327. const elems = [...columnGroups$1, ...rows$1];
  1328. return fromRowsOrColGroups(elems, getParentSection);
  1329. };
  1330. const LOCKED_COL_ATTR = 'data-snooker-locked-cols';
  1331. const getLockedColumnsFromTable = (table) => getOpt(table, LOCKED_COL_ATTR)
  1332. .bind((lockedColStr) => Optional.from(lockedColStr.match(/\d+/g)))
  1333. .map((lockedCols) => mapToObject(lockedCols, always));
  1334. const key = (row, column) => {
  1335. return row + ',' + column;
  1336. };
  1337. const getAt = (warehouse, row, column) => Optional.from(warehouse.access[key(row, column)]);
  1338. const findItem = (warehouse, item, comparator) => {
  1339. const filtered = filterItems(warehouse, (detail) => {
  1340. return comparator(item, detail.element);
  1341. });
  1342. return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
  1343. };
  1344. const filterItems = (warehouse, predicate) => {
  1345. const all = bind(warehouse.all, (r) => {
  1346. return r.cells;
  1347. });
  1348. return filter$1(all, predicate);
  1349. };
  1350. const generateColumns = (rowData) => {
  1351. const columnsGroup = {};
  1352. let index = 0;
  1353. each$1(rowData.cells, (column) => {
  1354. const colspan = column.colspan;
  1355. range(colspan, (columnIndex) => {
  1356. const colIndex = index + columnIndex;
  1357. columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
  1358. });
  1359. index += colspan;
  1360. });
  1361. return columnsGroup;
  1362. };
  1363. /*
  1364. * From a list of list of Detail, generate three pieces of information:
  1365. * 1. the grid size
  1366. * 2. a data structure which can efficiently identify which cell is in which row,column position
  1367. * 3. a list of all cells in order left-to-right, top-to-bottom
  1368. */
  1369. const generate = (list) => {
  1370. // list is an array of objects, made by cells and elements
  1371. // elements: is the TR
  1372. // cells: is an array of objects representing the cells in the row.
  1373. // It is made of:
  1374. // colspan (merge cell)
  1375. // element
  1376. // rowspan (merge cols)
  1377. const access = {};
  1378. const cells = [];
  1379. const tableOpt = head(list).map((rowData) => rowData.element).bind(table);
  1380. const lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
  1381. let maxRows = 0;
  1382. let maxColumns = 0;
  1383. let rowCount = 0;
  1384. const { pass: colgroupRows, fail: rows } = partition(list, (rowData) => rowData.section === 'colgroup');
  1385. // Handle rows first
  1386. each$1(rows, (rowData) => {
  1387. const currentRow = [];
  1388. each$1(rowData.cells, (rowCell) => {
  1389. let start = 0;
  1390. // If this spot has been taken by a previous rowspan, skip it.
  1391. while (access[key(rowCount, start)] !== undefined) {
  1392. start++;
  1393. }
  1394. const isLocked = hasNonNullableKey(lockedColumns, start.toString());
  1395. const current = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start, isLocked);
  1396. // Occupy all the (row, column) positions that this cell spans for.
  1397. for (let occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
  1398. for (let occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
  1399. const rowPosition = rowCount + occupiedRowPosition;
  1400. const columnPosition = start + occupiedColumnPosition;
  1401. const newpos = key(rowPosition, columnPosition);
  1402. access[newpos] = current;
  1403. maxColumns = Math.max(maxColumns, columnPosition + 1);
  1404. }
  1405. }
  1406. currentRow.push(current);
  1407. });
  1408. maxRows++;
  1409. cells.push(rowdetail(rowData.element, currentRow, rowData.section));
  1410. rowCount++;
  1411. });
  1412. // Handle colgroups
  1413. // Note: Currently only a single colgroup is supported so just use the last one
  1414. const { columns, colgroups } = last(colgroupRows).map((rowData) => {
  1415. const columns = generateColumns(rowData);
  1416. const colgroup$1 = colgroup(rowData.element, values(columns));
  1417. return {
  1418. colgroups: [colgroup$1],
  1419. columns
  1420. };
  1421. }).getOrThunk(() => ({
  1422. colgroups: [],
  1423. columns: {}
  1424. }));
  1425. const grid$1 = grid(maxRows, maxColumns);
  1426. return {
  1427. grid: grid$1,
  1428. access,
  1429. all: cells,
  1430. columns,
  1431. colgroups
  1432. };
  1433. };
  1434. const fromTable = (table) => {
  1435. const list = fromTable$1(table);
  1436. return generate(list);
  1437. };
  1438. const justCells = (warehouse) => bind(warehouse.all, (w) => w.cells);
  1439. const justColumns = (warehouse) => values(warehouse.columns);
  1440. const hasColumns = (warehouse) => keys(warehouse.columns).length > 0;
  1441. const getColumnAt = (warehouse, columnIndex) => Optional.from(warehouse.columns[columnIndex]);
  1442. const Warehouse = {
  1443. fromTable,
  1444. generate,
  1445. getAt,
  1446. findItem,
  1447. filterItems,
  1448. justCells,
  1449. justColumns,
  1450. hasColumns,
  1451. getColumnAt
  1452. };
  1453. const findInWarehouse = (warehouse, element) => findMap(warehouse.all, (r) => find(r.cells, (e) => eq(element, e.element)));
  1454. const extractCells = (warehouse, target, predicate) => {
  1455. const details = map(target.selection, (cell$1) => {
  1456. return cell(cell$1)
  1457. .bind((lc) => findInWarehouse(warehouse, lc))
  1458. .filter(predicate);
  1459. });
  1460. const cells = cat(details);
  1461. return someIf(cells.length > 0, cells);
  1462. };
  1463. const onMergable = (_warehouse, target) => target.mergable;
  1464. const onUnmergable = (_warehouse, target) => target.unmergable;
  1465. const onCells = (warehouse, target) => extractCells(warehouse, target, always);
  1466. const isUnlockedTableCell = (warehouse, cell) => findInWarehouse(warehouse, cell).exists((detail) => !detail.isLocked);
  1467. const allUnlocked = (warehouse, cells) => forall(cells, (cell) => isUnlockedTableCell(warehouse, cell));
  1468. // If any locked columns are present in the selection, then don't want to be able to merge
  1469. const onUnlockedMergable = (warehouse, target) => onMergable(warehouse, target).filter((mergeable) => allUnlocked(warehouse, mergeable.cells));
  1470. // If any locked columns are present in the selection, then don't want to be able to unmerge
  1471. const onUnlockedUnmergable = (warehouse, target) => onUnmergable(warehouse, target).filter((cells) => allUnlocked(warehouse, cells));
  1472. const isCol = isTag('col');
  1473. const isColgroup = isTag('colgroup');
  1474. const isRow = (element) => name(element) === 'tr' || isColgroup(element);
  1475. const elementToData = (element) => {
  1476. const colspan = getAttrValue(element, 'colspan', 1);
  1477. const rowspan = getAttrValue(element, 'rowspan', 1);
  1478. return {
  1479. element,
  1480. colspan,
  1481. rowspan
  1482. };
  1483. };
  1484. // note that `toData` seems to be only for testing
  1485. const modification = (generators, toData = elementToData) => {
  1486. const nuCell = (data) => isCol(data.element) ? generators.col(data) : generators.cell(data);
  1487. const nuRow = (data) => isColgroup(data.element) ? generators.colgroup(data) : generators.row(data);
  1488. const add = (element) => {
  1489. if (isRow(element)) {
  1490. return nuRow({ element });
  1491. }
  1492. else {
  1493. const cell = element;
  1494. const replacement = nuCell(toData(cell));
  1495. recent = Optional.some({ item: cell, replacement });
  1496. return replacement;
  1497. }
  1498. };
  1499. let recent = Optional.none();
  1500. const getOrInit = (element, comparator) => {
  1501. return recent.fold(() => {
  1502. return add(element);
  1503. }, (p) => {
  1504. return comparator(element, p.item) ? p.replacement : add(element);
  1505. });
  1506. };
  1507. return {
  1508. getOrInit
  1509. };
  1510. };
  1511. const transform = (tag) => {
  1512. return (generators) => {
  1513. const list = [];
  1514. const find$1 = (element, comparator) => {
  1515. return find(list, (x) => {
  1516. return comparator(x.item, element);
  1517. });
  1518. };
  1519. const makeNew = (element) => {
  1520. // Ensure scope is never set on a td element as it's a deprecated attribute
  1521. const attrs = tag === 'td' ? { scope: null } : {};
  1522. const cell = generators.replace(element, tag, attrs);
  1523. list.push({
  1524. item: element,
  1525. sub: cell
  1526. });
  1527. return cell;
  1528. };
  1529. const replaceOrInit = (element, comparator) => {
  1530. if (isRow(element) || isCol(element)) {
  1531. return element;
  1532. }
  1533. else {
  1534. const cell = element;
  1535. return find$1(cell, comparator).fold(() => {
  1536. return makeNew(cell);
  1537. }, (p) => {
  1538. return comparator(element, p.item) ? p.sub : makeNew(cell);
  1539. });
  1540. }
  1541. };
  1542. return {
  1543. replaceOrInit
  1544. };
  1545. };
  1546. };
  1547. const getScopeAttribute = (cell) => getOpt(cell, 'scope').map(
  1548. // Attribute can be col, colgroup, row, and rowgroup.
  1549. // As col and colgroup are to be treated as if they are the same, lob off everything after the first three characters and there is no difference.
  1550. (attribute) => attribute.substr(0, 3));
  1551. const merging = (generators) => {
  1552. const unmerge = (cell) => {
  1553. const scope = getScopeAttribute(cell);
  1554. scope.each((attribute) => set$2(cell, 'scope', attribute));
  1555. return () => {
  1556. const raw = generators.cell({
  1557. element: cell,
  1558. colspan: 1,
  1559. rowspan: 1
  1560. });
  1561. // Remove any width calculations because they are no longer relevant.
  1562. remove(raw, 'width');
  1563. remove(cell, 'width');
  1564. scope.each((attribute) => set$2(raw, 'scope', attribute));
  1565. return raw;
  1566. };
  1567. };
  1568. const merge = (cells) => {
  1569. const getScopeProperty = () => {
  1570. const stringAttributes = cat(map(cells, getScopeAttribute));
  1571. if (stringAttributes.length === 0) {
  1572. return Optional.none();
  1573. }
  1574. else {
  1575. const baseScope = stringAttributes[0];
  1576. const scopes = ['row', 'col'];
  1577. const isMixed = exists(stringAttributes, (attribute) => {
  1578. return attribute !== baseScope && contains(scopes, attribute);
  1579. });
  1580. return isMixed ? Optional.none() : Optional.from(baseScope);
  1581. }
  1582. };
  1583. remove(cells[0], 'width');
  1584. getScopeProperty().fold(() => remove$2(cells[0], 'scope'), (attribute) => set$2(cells[0], 'scope', attribute + 'group'));
  1585. return constant(cells[0]);
  1586. };
  1587. return {
  1588. unmerge,
  1589. merge
  1590. };
  1591. };
  1592. const Generators = {
  1593. modification,
  1594. transform,
  1595. merging
  1596. };
  1597. var TagBoundaries = [
  1598. 'body',
  1599. 'p',
  1600. 'div',
  1601. 'article',
  1602. 'aside',
  1603. 'figcaption',
  1604. 'figure',
  1605. 'footer',
  1606. 'header',
  1607. 'nav',
  1608. 'section',
  1609. 'ol',
  1610. 'ul',
  1611. 'li',
  1612. 'table',
  1613. 'thead',
  1614. 'tbody',
  1615. 'tfoot',
  1616. 'caption',
  1617. 'tr',
  1618. 'td',
  1619. 'th',
  1620. 'h1',
  1621. 'h2',
  1622. 'h3',
  1623. 'h4',
  1624. 'h5',
  1625. 'h6',
  1626. 'blockquote',
  1627. 'pre',
  1628. 'address'
  1629. ];
  1630. var DomUniverse = () => {
  1631. const clone$1 = (element) => {
  1632. return SugarElement.fromDom(element.dom.cloneNode(false));
  1633. };
  1634. const document = (element) => documentOrOwner(element).dom;
  1635. const isBoundary = (element) => {
  1636. if (!isElement(element)) {
  1637. return false;
  1638. }
  1639. if (name(element) === 'body') {
  1640. return true;
  1641. }
  1642. return contains(TagBoundaries, name(element));
  1643. };
  1644. const isEmptyTag = (element) => {
  1645. if (!isElement(element)) {
  1646. return false;
  1647. }
  1648. return contains(['br', 'img', 'hr', 'input'], name(element));
  1649. };
  1650. const isNonEditable = (element) => isElement(element) && get$2(element, 'contenteditable') === 'false';
  1651. const comparePosition = (element, other) => {
  1652. return element.dom.compareDocumentPosition(other.dom);
  1653. };
  1654. const copyAttributesTo = (source, destination) => {
  1655. const as = clone(source);
  1656. setAll(destination, as);
  1657. };
  1658. const isSpecial = (element) => {
  1659. const tag = name(element);
  1660. return contains([
  1661. 'script', 'noscript', 'iframe', 'noframes', 'noembed', 'title', 'style', 'textarea', 'xmp'
  1662. ], tag);
  1663. };
  1664. const getLanguage = (element) => isElement(element) ? getOpt(element, 'lang') : Optional.none();
  1665. return {
  1666. up: constant({
  1667. selector: ancestor,
  1668. closest: closest$1,
  1669. predicate: ancestor$1,
  1670. all: parents
  1671. }),
  1672. down: constant({
  1673. selector: descendants,
  1674. predicate: descendants$1
  1675. }),
  1676. styles: constant({
  1677. get: get$1,
  1678. getRaw: getRaw$1,
  1679. set: set$1,
  1680. remove: remove
  1681. }),
  1682. attrs: constant({
  1683. get: get$2,
  1684. set: set$2,
  1685. remove: remove$2,
  1686. copyTo: copyAttributesTo
  1687. }),
  1688. insert: constant({
  1689. before: before,
  1690. after: after$1,
  1691. afterAll: after,
  1692. append: append$1,
  1693. appendAll: append,
  1694. prepend: prepend,
  1695. wrap: wrap
  1696. }),
  1697. remove: constant({
  1698. unwrap: unwrap,
  1699. remove: remove$1
  1700. }),
  1701. create: constant({
  1702. nu: SugarElement.fromTag,
  1703. clone: clone$1,
  1704. text: SugarElement.fromText
  1705. }),
  1706. query: constant({
  1707. comparePosition,
  1708. prevSibling: prevSibling,
  1709. nextSibling: nextSibling
  1710. }),
  1711. property: constant({
  1712. children: children$3,
  1713. name: name,
  1714. parent: parent,
  1715. document,
  1716. isText: isText,
  1717. isComment: isComment,
  1718. isElement: isElement,
  1719. isSpecial,
  1720. getLanguage,
  1721. getText: get,
  1722. setText: set,
  1723. isBoundary,
  1724. isEmptyTag,
  1725. isNonEditable
  1726. }),
  1727. eq: eq,
  1728. is: is
  1729. };
  1730. };
  1731. const leftRight = (left, right) => ({
  1732. left,
  1733. right
  1734. });
  1735. const brokenPath = (first, second, splits) => ({
  1736. first,
  1737. second,
  1738. splits
  1739. });
  1740. const bisect = (universe, parent, child) => {
  1741. const children = universe.property().children(parent);
  1742. const index = findIndex(children, curry(universe.eq, child));
  1743. return index.map((ind) => {
  1744. return {
  1745. before: children.slice(0, ind),
  1746. after: children.slice(ind + 1)
  1747. };
  1748. });
  1749. };
  1750. /**
  1751. * Clone parent to the RIGHT and move everything after child in the parent element into
  1752. * a clone of the parent (placed after parent).
  1753. */
  1754. const breakToRight = (universe, parent, child) => {
  1755. return bisect(universe, parent, child).map((parts) => {
  1756. const second = universe.create().clone(parent);
  1757. universe.insert().appendAll(second, parts.after);
  1758. universe.insert().after(parent, second);
  1759. return leftRight(parent, second);
  1760. });
  1761. };
  1762. /**
  1763. * Clone parent to the LEFT and move everything before and including child into
  1764. * the a clone of the parent (placed before parent)
  1765. */
  1766. const breakToLeft = (universe, parent, child) => {
  1767. return bisect(universe, parent, child).map((parts) => {
  1768. const prior = universe.create().clone(parent);
  1769. universe.insert().appendAll(prior, parts.before.concat([child]));
  1770. universe.insert().appendAll(parent, parts.after);
  1771. universe.insert().before(parent, prior);
  1772. return leftRight(prior, parent);
  1773. });
  1774. };
  1775. /*
  1776. * Using the breaker, break from the child up to the top element defined by the predicate.
  1777. * It returns three values:
  1778. * first: the top level element that completed the break
  1779. * second: the optional element representing second part of the top-level split if the breaking completed successfully to the top
  1780. * splits: a list of (Element, Element) pairs that represent the splits that have occurred on the way to the top.
  1781. */
  1782. const breakPath = (universe, item, isTop, breaker) => {
  1783. const next = (child, group, splits) => {
  1784. const fallback = brokenPath(child, Optional.none(), splits);
  1785. // Found the top, so stop.
  1786. if (isTop(child)) {
  1787. return brokenPath(child, group, splits);
  1788. }
  1789. else {
  1790. // Split the child at parent, and keep going
  1791. return universe.property().parent(child).bind((parent) => {
  1792. return breaker(universe, parent, child).map((breakage) => {
  1793. const extra = [{ first: breakage.left, second: breakage.right }];
  1794. // Our isTop is based on the left-side parent, so keep it regardless of split.
  1795. const nextChild = isTop(parent) ? parent : breakage.left;
  1796. return next(nextChild, Optional.some(breakage.right), splits.concat(extra));
  1797. });
  1798. }).getOr(fallback);
  1799. }
  1800. };
  1801. return next(item, Optional.none(), []);
  1802. };
  1803. const all = (universe, look, elements, f) => {
  1804. const head = elements[0];
  1805. const tail = elements.slice(1);
  1806. return f(universe, look, head, tail);
  1807. };
  1808. /**
  1809. * Check if look returns the same element for all elements, and return it if it exists.
  1810. */
  1811. const oneAll = (universe, look, elements) => {
  1812. return elements.length > 0 ?
  1813. all(universe, look, elements, unsafeOne) :
  1814. Optional.none();
  1815. };
  1816. const unsafeOne = (universe, look, head, tail) => {
  1817. const start = look(universe, head);
  1818. return foldr(tail, (b, a) => {
  1819. const current = look(universe, a);
  1820. return commonElement(universe, b, current);
  1821. }, start);
  1822. };
  1823. const commonElement = (universe, start, end) => {
  1824. return start.bind((s) => {
  1825. return end.filter(curry(universe.eq, s));
  1826. });
  1827. };
  1828. const sharedOne$1 = oneAll;
  1829. breakToLeft;
  1830. breakToRight;
  1831. breakPath;
  1832. const universe = DomUniverse();
  1833. const sharedOne = (look, elements) => {
  1834. return sharedOne$1(universe, (_universe, element) => {
  1835. return look(element);
  1836. }, elements);
  1837. };
  1838. const opGetRowsType = (table, target) => {
  1839. const house = Warehouse.fromTable(table);
  1840. const details = onCells(house, target);
  1841. return details.bind((selectedCells) => {
  1842. const lastSelectedCell = selectedCells[selectedCells.length - 1];
  1843. const minRowRange = selectedCells[0].row;
  1844. const maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
  1845. const selectedRows = house.all.slice(minRowRange, maxRowRange);
  1846. return findCommonRowType(selectedRows);
  1847. }).getOr('');
  1848. };
  1849. Generators.transform('th');
  1850. Generators.transform('td');
  1851. const getRowsType = opGetRowsType;
  1852. // Note, something is *within* if it is completely contained within the bounds.
  1853. const isWithin = (bounds, detail) => {
  1854. return (detail.column >= bounds.startCol &&
  1855. (detail.column + detail.colspan - 1) <= bounds.finishCol &&
  1856. detail.row >= bounds.startRow &&
  1857. (detail.row + detail.rowspan - 1) <= bounds.finishRow);
  1858. };
  1859. const isRectangular = (warehouse, bounds) => {
  1860. let isRect = true;
  1861. const detailIsWithin = curry(isWithin, bounds);
  1862. for (let i = bounds.startRow; i <= bounds.finishRow; i++) {
  1863. for (let j = bounds.startCol; j <= bounds.finishCol; j++) {
  1864. isRect = isRect && Warehouse.getAt(warehouse, i, j).exists(detailIsWithin);
  1865. }
  1866. }
  1867. return isRect ? Optional.some(bounds) : Optional.none();
  1868. };
  1869. const getBounds = (detailA, detailB) => {
  1870. 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));
  1871. };
  1872. const getAnyBox = (warehouse, startCell, finishCell) => {
  1873. const startCoords = Warehouse.findItem(warehouse, startCell, eq);
  1874. const finishCoords = Warehouse.findItem(warehouse, finishCell, eq);
  1875. return startCoords.bind((sc) => {
  1876. return finishCoords.map((fc) => {
  1877. return getBounds(sc, fc);
  1878. });
  1879. });
  1880. };
  1881. const getBox$1 = (warehouse, startCell, finishCell) => {
  1882. return getAnyBox(warehouse, startCell, finishCell).bind((bounds) => {
  1883. return isRectangular(warehouse, bounds);
  1884. });
  1885. };
  1886. const getBox = (table, first, last) => {
  1887. const warehouse = getWarehouse(table);
  1888. return getBox$1(warehouse, first, last);
  1889. };
  1890. // Private method ... keep warehouse in snooker, please.
  1891. const getWarehouse = Warehouse.fromTable;
  1892. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  1893. const getTDTHOverallStyle = (dom, elm, name) => {
  1894. const cells = dom.select('td,th', elm);
  1895. let firstChildStyle;
  1896. for (let i = 0; i < cells.length; i++) {
  1897. const currentStyle = dom.getStyle(cells[i], name);
  1898. if (isUndefined(firstChildStyle)) {
  1899. firstChildStyle = currentStyle;
  1900. }
  1901. if (firstChildStyle !== currentStyle) {
  1902. return '';
  1903. }
  1904. }
  1905. return firstChildStyle;
  1906. };
  1907. const setAlign = (editor, elm, name) => {
  1908. // Alignment formats may not use the same styles so ensure to remove any existing horizontal alignment format first
  1909. global$2.each('left center right'.split(' '), (align) => {
  1910. if (align !== name) {
  1911. editor.formatter.remove('align' + align, {}, elm);
  1912. }
  1913. });
  1914. if (name) {
  1915. editor.formatter.apply('align' + name, {}, elm);
  1916. }
  1917. };
  1918. const setVAlign = (editor, elm, name) => {
  1919. // Alignment formats may not use the same styles so ensure to remove any existing vertical alignment format first
  1920. global$2.each('top middle bottom'.split(' '), (align) => {
  1921. if (align !== name) {
  1922. editor.formatter.remove('valign' + align, {}, elm);
  1923. }
  1924. });
  1925. if (name) {
  1926. editor.formatter.apply('valign' + name, {}, elm);
  1927. }
  1928. };
  1929. /*
  1930. NOTE: This file is duplicated in the following locations:
  1931. - core/api/TableEvents.ts
  1932. - models/dom/table/api/Events.ts
  1933. - advtable
  1934. Make sure that if making changes to this file, the other files are updated as well
  1935. */
  1936. const fireTableModified = (editor, table, data) => {
  1937. editor.dispatch('TableModified', { ...data, table });
  1938. };
  1939. var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
  1940. const defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
  1941. const defaultCellBorderWidths = range(5, (i) => {
  1942. const size = `${i + 1}px`;
  1943. return { title: size, value: size };
  1944. });
  1945. const defaultCellBorderStyles = map(['Solid', 'Dotted', 'Dashed', 'Double', 'Groove', 'Ridge', 'Inset', 'Outset', 'None', 'Hidden'], (type) => {
  1946. return { title: type, value: type.toLowerCase() };
  1947. });
  1948. // Note: This is also contained in the core Options.ts file
  1949. const defaultWidth = '100%';
  1950. const getPixelForcedWidth = (editor) => {
  1951. var _a;
  1952. // Determine the inner size of the parent block element where the table will be inserted
  1953. const dom = editor.dom;
  1954. const parentBlock = (_a = dom.getParent(editor.selection.getStart(), dom.isBlock)) !== null && _a !== void 0 ? _a : editor.getBody();
  1955. return getInner(SugarElement.fromDom(parentBlock)) + 'px';
  1956. };
  1957. // Note: This is also contained in the core Options.ts file
  1958. const determineDefaultStyles = (editor, defaultStyles) => {
  1959. if (isResponsiveForced(editor) || !shouldStyleWithCss(editor)) {
  1960. return defaultStyles;
  1961. }
  1962. else if (isPixelsForced(editor)) {
  1963. return { ...defaultStyles, width: getPixelForcedWidth(editor) };
  1964. }
  1965. else {
  1966. return { ...defaultStyles, width: defaultWidth };
  1967. }
  1968. };
  1969. // Note: This is also contained in the core Options.ts file
  1970. const determineDefaultAttributes = (editor, defaultAttributes) => {
  1971. if (isResponsiveForced(editor) || shouldStyleWithCss(editor)) {
  1972. return defaultAttributes;
  1973. }
  1974. else if (isPixelsForced(editor)) {
  1975. return { ...defaultAttributes, width: getPixelForcedWidth(editor) };
  1976. }
  1977. else {
  1978. return { ...defaultAttributes, width: defaultWidth };
  1979. }
  1980. };
  1981. const option = (name) => (editor) => editor.options.get(name);
  1982. const register = (editor) => {
  1983. const registerOption = editor.options.register;
  1984. registerOption('table_border_widths', {
  1985. processor: 'object[]',
  1986. default: defaultCellBorderWidths
  1987. });
  1988. registerOption('table_border_styles', {
  1989. processor: 'object[]',
  1990. default: defaultCellBorderStyles
  1991. });
  1992. registerOption('table_cell_advtab', {
  1993. processor: 'boolean',
  1994. default: true
  1995. });
  1996. registerOption('table_row_advtab', {
  1997. processor: 'boolean',
  1998. default: true
  1999. });
  2000. registerOption('table_advtab', {
  2001. processor: 'boolean',
  2002. default: true
  2003. });
  2004. registerOption('table_appearance_options', {
  2005. processor: 'boolean',
  2006. default: true
  2007. });
  2008. registerOption('table_grid', {
  2009. processor: 'boolean',
  2010. // Table grid relies on hover, which isn't available on touch devices so use the dialog instead
  2011. default: !global$1.deviceType.isTouch()
  2012. });
  2013. registerOption('table_cell_class_list', {
  2014. processor: 'object[]',
  2015. default: []
  2016. });
  2017. registerOption('table_row_class_list', {
  2018. processor: 'object[]',
  2019. default: []
  2020. });
  2021. registerOption('table_class_list', {
  2022. processor: 'object[]',
  2023. default: []
  2024. });
  2025. registerOption('table_toolbar', {
  2026. processor: 'string',
  2027. default: defaultTableToolbar
  2028. });
  2029. registerOption('table_background_color_map', {
  2030. processor: 'object[]',
  2031. default: []
  2032. });
  2033. registerOption('table_border_color_map', {
  2034. processor: 'object[]',
  2035. default: []
  2036. });
  2037. };
  2038. const getTableSizingMode = option('table_sizing_mode');
  2039. const getTableBorderWidths = option('table_border_widths');
  2040. const getTableBorderStyles = option('table_border_styles');
  2041. const hasAdvancedCellTab = option('table_cell_advtab');
  2042. const hasAdvancedRowTab = option('table_row_advtab');
  2043. const hasAdvancedTableTab = option('table_advtab');
  2044. const hasAppearanceOptions = option('table_appearance_options');
  2045. const hasTableGrid = option('table_grid');
  2046. const shouldStyleWithCss = option('table_style_by_css');
  2047. const getCellClassList = option('table_cell_class_list');
  2048. const getRowClassList = option('table_row_class_list');
  2049. const getTableClassList = option('table_class_list');
  2050. const getToolbar = option('table_toolbar');
  2051. const getTableBackgroundColorMap = option('table_background_color_map');
  2052. const getTableBorderColorMap = option('table_border_color_map');
  2053. const isPixelsForced = (editor) => getTableSizingMode(editor) === 'fixed';
  2054. const isResponsiveForced = (editor) => getTableSizingMode(editor) === 'responsive';
  2055. const getDefaultStyles = (editor) => {
  2056. // Note: The we don't rely on the default here as we need to dynamically lookup the widths based on the current editor state
  2057. const options = editor.options;
  2058. const defaultStyles = options.get('table_default_styles');
  2059. return options.isSet('table_default_styles') ? defaultStyles : determineDefaultStyles(editor, defaultStyles);
  2060. };
  2061. const getDefaultAttributes = (editor) => {
  2062. // Note: The we don't rely on the default here as we need to dynamically lookup the widths based on the current editor state
  2063. const options = editor.options;
  2064. const defaultAttributes = options.get('table_default_attributes');
  2065. return options.isSet('table_default_attributes') ? defaultAttributes : determineDefaultAttributes(editor, defaultAttributes);
  2066. };
  2067. const lookupTable = (container) => {
  2068. return ancestor(container, 'table');
  2069. };
  2070. const retrieve$1 = (container, selector) => {
  2071. const sels = descendants(container, selector);
  2072. return sels.length > 0 ? Optional.some(sels) : Optional.none();
  2073. };
  2074. const getEdges = (container, firstSelectedSelector, lastSelectedSelector) => {
  2075. return descendant(container, firstSelectedSelector).bind((first) => {
  2076. return descendant(container, lastSelectedSelector).bind((last) => {
  2077. return sharedOne(lookupTable, [first, last]).map((table) => {
  2078. return {
  2079. first,
  2080. last,
  2081. table
  2082. };
  2083. });
  2084. });
  2085. });
  2086. };
  2087. // Explicitly calling CellSelection.retrieve so that we can see the API signature.
  2088. const retrieve = (container, selector) => {
  2089. return retrieve$1(container, selector);
  2090. };
  2091. const retrieveBox = (container, firstSelectedSelector, lastSelectedSelector) => {
  2092. return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind((edges) => {
  2093. const isRoot = (ancestor) => {
  2094. return eq(container, ancestor);
  2095. };
  2096. const sectionSelector = 'thead,tfoot,tbody,table';
  2097. const firstAncestor = ancestor(edges.first, sectionSelector, isRoot);
  2098. const lastAncestor = ancestor(edges.last, sectionSelector, isRoot);
  2099. return firstAncestor.bind((fA) => {
  2100. return lastAncestor.bind((lA) => {
  2101. return eq(fA, lA) ? getBox(edges.table, edges.first, edges.last) : Optional.none();
  2102. });
  2103. });
  2104. });
  2105. };
  2106. const selection = identity;
  2107. const unmergable = (selectedCells) => {
  2108. const hasSpan = (elem, type) => getOpt(elem, type).exists((span) => parseInt(span, 10) > 1);
  2109. const hasRowOrColSpan = (elem) => hasSpan(elem, 'rowspan') || hasSpan(elem, 'colspan');
  2110. return selectedCells.length > 0 && forall(selectedCells, hasRowOrColSpan) ? Optional.some(selectedCells) : Optional.none();
  2111. };
  2112. const mergable = (table, selectedCells, ephemera) => {
  2113. if (selectedCells.length <= 1) {
  2114. return Optional.none();
  2115. }
  2116. else {
  2117. return retrieveBox(table, ephemera.firstSelectedSelector, ephemera.lastSelectedSelector)
  2118. .map((bounds) => ({ bounds, cells: selectedCells }));
  2119. }
  2120. };
  2121. /*
  2122. NOTE: This file is duplicated in the following locations:
  2123. - models/dom/table/selection/Ephemera.ts
  2124. - advtable
  2125. Make sure that if making changes to this file, the other files are updated as well
  2126. */
  2127. const strSelected = 'data-mce-selected';
  2128. const strSelectedSelector = 'td[' + strSelected + '],th[' + strSelected + ']';
  2129. const strFirstSelected = 'data-mce-first-selected';
  2130. const strFirstSelectedSelector = 'td[' + strFirstSelected + '],th[' + strFirstSelected + ']';
  2131. const strLastSelected = 'data-mce-last-selected';
  2132. const strLastSelectedSelector = 'td[' + strLastSelected + '],th[' + strLastSelected + ']';
  2133. const ephemera = {
  2134. selected: strSelected,
  2135. selectedSelector: strSelectedSelector,
  2136. firstSelected: strFirstSelected,
  2137. firstSelectedSelector: strFirstSelectedSelector,
  2138. lastSelected: strLastSelected,
  2139. lastSelectedSelector: strLastSelectedSelector
  2140. };
  2141. /*
  2142. NOTE: This file is partially duplicated in the following locations:
  2143. - models/dom/table/selection/TableSelection.ts
  2144. - advtable
  2145. Make sure that if making changes to this file, the other files are updated as well
  2146. */
  2147. const getSelectionCellFallback = (element) => table(element).bind((table) => retrieve(table, ephemera.firstSelectedSelector)).fold(constant(element), (cells) => cells[0]);
  2148. const getSelectionFromSelector = (selector) => (initCell, isRoot) => {
  2149. const cellName = name(initCell);
  2150. const cell = cellName === 'col' || cellName === 'colgroup' ? getSelectionCellFallback(initCell) : initCell;
  2151. return closest$1(cell, selector, isRoot);
  2152. };
  2153. const getSelectionCellOrCaption = getSelectionFromSelector('th,td,caption');
  2154. const getSelectionCell = getSelectionFromSelector('th,td');
  2155. const getCellsFromSelection = (editor) => fromDom(editor.model.table.getSelectedCells());
  2156. const getRowsFromSelection = (selected, selector) => {
  2157. const cellOpt = getSelectionCell(selected);
  2158. const rowsOpt = cellOpt.bind((cell) => table(cell))
  2159. .map((table) => rows(table));
  2160. return lift2(cellOpt, rowsOpt, (cell, rows) => filter$1(rows, (row) => exists(fromDom(row.dom.cells), (rowCell) => get$2(rowCell, selector) === '1' || eq(rowCell, cell)))).getOr([]);
  2161. };
  2162. const verticalAlignValues = [
  2163. {
  2164. text: 'None',
  2165. value: ''
  2166. },
  2167. {
  2168. text: 'Top',
  2169. value: 'top'
  2170. },
  2171. {
  2172. text: 'Middle',
  2173. value: 'middle'
  2174. },
  2175. {
  2176. text: 'Bottom',
  2177. value: 'bottom'
  2178. }
  2179. ];
  2180. const hexColour = (value) => ({
  2181. value: normalizeHex(value)
  2182. });
  2183. const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  2184. const longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  2185. const isHexString = (hex) => shorthandRegex.test(hex) || longformRegex.test(hex);
  2186. const normalizeHex = (hex) => removeLeading(hex, '#').toUpperCase();
  2187. const fromString$1 = (hex) => isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  2188. const toHex = (component) => {
  2189. const hex = component.toString(16);
  2190. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  2191. };
  2192. const fromRgba = (rgbaColour) => {
  2193. const value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  2194. return hexColour(value);
  2195. };
  2196. const rgbRegex = /^\s*rgb\s*\(\s*(\d+)\s*[,\s]\s*(\d+)\s*[,\s]\s*(\d+)\s*\)\s*$/i;
  2197. // This regex will match rgba(0, 0, 0, 0.5) or rgba(0, 0, 0, 50%) , or without commas
  2198. const rgbaRegex = /^\s*rgba\s*\(\s*(\d+)\s*[,\s]\s*(\d+)\s*[,\s]\s*(\d+)\s*[,\s]\s*((?:\d?\.\d+|\d+)%?)\s*\)\s*$/i;
  2199. const rgbaColour = (red, green, blue, alpha) => ({
  2200. red,
  2201. green,
  2202. blue,
  2203. alpha
  2204. });
  2205. const fromStringValues = (red, green, blue, alpha) => {
  2206. const r = parseInt(red, 10);
  2207. const g = parseInt(green, 10);
  2208. const b = parseInt(blue, 10);
  2209. const a = parseFloat(alpha);
  2210. return rgbaColour(r, g, b, a);
  2211. };
  2212. const fromString = (rgbaString) => {
  2213. const rgbMatch = rgbRegex.exec(rgbaString);
  2214. if (rgbMatch !== null) {
  2215. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  2216. }
  2217. const rgbaMatch = rgbaRegex.exec(rgbaString);
  2218. if (rgbaMatch !== null) {
  2219. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  2220. }
  2221. return Optional.none();
  2222. };
  2223. const anyToHex = (color) => fromString$1(color)
  2224. .orThunk(() => fromString(color).map(fromRgba))
  2225. .getOrThunk(() => {
  2226. // Not dealing with Hex or RGBA so use a canvas to parse the color
  2227. const canvas = document.createElement('canvas');
  2228. canvas.height = 1;
  2229. canvas.width = 1;
  2230. const canvasContext = canvas.getContext('2d');
  2231. // all valid colors after this point
  2232. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  2233. // invalid colors will be shown as white - the first assignment will pass and the second may be ignored
  2234. canvasContext.fillStyle = '#FFFFFF';
  2235. canvasContext.fillStyle = color;
  2236. canvasContext.fillRect(0, 0, 1, 1);
  2237. const rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  2238. const r = rgba[0];
  2239. const g = rgba[1];
  2240. const b = rgba[2];
  2241. const a = rgba[3];
  2242. return fromRgba(rgbaColour(r, g, b, a));
  2243. });
  2244. const rgbaToHexString = (color) => fromString(color)
  2245. .map(fromRgba)
  2246. .map((h) => '#' + h.value)
  2247. .getOr(color);
  2248. const onSetupToggle = (editor, formatName, formatValue) => {
  2249. return (api) => {
  2250. const boundCallback = unbindable();
  2251. const isNone = isEmpty(formatValue);
  2252. const init = () => {
  2253. const selectedCells = getCellsFromSelection(editor);
  2254. const checkNode = (cell) => editor.formatter.match(formatName, { value: formatValue }, cell.dom, isNone);
  2255. // If value is empty (A None-entry in the list), check if the format is not set at all. Otherwise, check if the format is set to the correct value.
  2256. if (isNone) {
  2257. api.setActive(!exists(selectedCells, checkNode));
  2258. boundCallback.set(editor.formatter.formatChanged(formatName, (match) => api.setActive(!match), true));
  2259. }
  2260. else {
  2261. api.setActive(forall(selectedCells, checkNode));
  2262. boundCallback.set(editor.formatter.formatChanged(formatName, api.setActive, false, { value: formatValue }));
  2263. }
  2264. };
  2265. // The editor may or may not have been setup yet, so check for that
  2266. editor.initialized ? init() : editor.on('init', init);
  2267. return boundCallback.clear;
  2268. };
  2269. };
  2270. const isListGroup = (item) => hasNonNullableKey(item, 'menu');
  2271. const buildListItems = (items) => map(items, (item) => {
  2272. // item.text is not documented - maybe deprecated option we can delete??
  2273. const text = item.text || item.title || '';
  2274. if (isListGroup(item)) {
  2275. return {
  2276. text,
  2277. items: buildListItems(item.menu)
  2278. };
  2279. }
  2280. else {
  2281. return {
  2282. text,
  2283. value: item.value
  2284. };
  2285. }
  2286. });
  2287. const buildClassList = (classList) => {
  2288. if (!classList.length) {
  2289. return Optional.none();
  2290. }
  2291. return Optional.some(buildListItems([{ text: 'Select...', value: 'mce-no-match' }, ...classList]));
  2292. };
  2293. const buildMenuItems = (editor, items, format, onAction) => map(items, (item) => {
  2294. // item.text is not documented - maybe deprecated option we can delete??
  2295. const text = item.text || item.title;
  2296. if (isListGroup(item)) {
  2297. return {
  2298. type: 'nestedmenuitem',
  2299. text,
  2300. getSubmenuItems: () => buildMenuItems(editor, item.menu, format, onAction)
  2301. };
  2302. }
  2303. else {
  2304. return {
  2305. text,
  2306. type: 'togglemenuitem',
  2307. onAction: () => onAction(item.value),
  2308. onSetup: onSetupToggle(editor, format, item.value)
  2309. };
  2310. }
  2311. });
  2312. const applyTableCellStyle = (editor, style) => (value) => {
  2313. editor.execCommand('mceTableApplyCellStyle', false, { [style]: value });
  2314. };
  2315. const filterNoneItem = (list) => bind(list, (item) => {
  2316. if (isListGroup(item)) {
  2317. return [{ ...item, menu: filterNoneItem(item.menu) }];
  2318. }
  2319. else {
  2320. return isNotEmpty(item.value) ? [item] : [];
  2321. }
  2322. });
  2323. const generateMenuItemsCallback = (editor, items, format, onAction) => (callback) => callback(buildMenuItems(editor, items, format, onAction));
  2324. const buildColorMenu = (editor, colorList, style) => {
  2325. const colorMap = map(colorList, (entry) => ({
  2326. text: entry.title,
  2327. value: '#' + anyToHex(entry.value).value,
  2328. type: 'choiceitem'
  2329. }));
  2330. return [{
  2331. type: 'fancymenuitem',
  2332. fancytype: 'colorswatch',
  2333. initData: {
  2334. colors: colorMap.length > 0 ? colorMap : undefined,
  2335. allowCustomColors: false
  2336. },
  2337. onAction: (data) => {
  2338. const value = data.value === 'remove' ? '' : data.value;
  2339. editor.execCommand('mceTableApplyCellStyle', false, { [style]: value });
  2340. }
  2341. }];
  2342. };
  2343. const changeRowHeader = (editor) => () => {
  2344. const currentType = editor.queryCommandValue('mceTableRowType');
  2345. const newType = currentType === 'header' ? 'body' : 'header';
  2346. editor.execCommand('mceTableRowType', false, { type: newType });
  2347. };
  2348. const changeColumnHeader = (editor) => () => {
  2349. const currentType = editor.queryCommandValue('mceTableColType');
  2350. const newType = currentType === 'th' ? 'td' : 'th';
  2351. editor.execCommand('mceTableColType', false, { type: newType });
  2352. };
  2353. const getClassList$1 = (editor) => buildClassList(getCellClassList(editor))
  2354. .map((items) => ({
  2355. name: 'class',
  2356. type: 'listbox',
  2357. label: 'Class',
  2358. items
  2359. }));
  2360. const children = [
  2361. {
  2362. name: 'width',
  2363. type: 'input',
  2364. label: 'Width'
  2365. },
  2366. {
  2367. name: 'celltype',
  2368. type: 'listbox',
  2369. label: 'Cell type',
  2370. items: [
  2371. { text: 'Cell', value: 'td' },
  2372. { text: 'Header cell', value: 'th' }
  2373. ]
  2374. },
  2375. {
  2376. name: 'scope',
  2377. type: 'listbox',
  2378. label: 'Scope',
  2379. items: [
  2380. { text: 'None', value: '' },
  2381. { text: 'Row', value: 'row' },
  2382. { text: 'Column', value: 'col' },
  2383. { text: 'Row group', value: 'rowgroup' },
  2384. { text: 'Column group', value: 'colgroup' }
  2385. ]
  2386. },
  2387. {
  2388. name: 'halign',
  2389. type: 'listbox',
  2390. label: 'Horizontal align',
  2391. items: [
  2392. { text: 'None', value: '' },
  2393. { text: 'Left', value: 'left' },
  2394. { text: 'Center', value: 'center' },
  2395. { text: 'Right', value: 'right' }
  2396. ]
  2397. },
  2398. {
  2399. name: 'valign',
  2400. type: 'listbox',
  2401. label: 'Vertical align',
  2402. items: verticalAlignValues
  2403. }
  2404. ];
  2405. const getItems$2 = (editor) => children.concat(getClassList$1(editor).toArray());
  2406. const getAdvancedTab = (editor, dialogName) => {
  2407. const emptyBorderStyle = [{ text: 'Select...', value: '' }];
  2408. const advTabItems = [
  2409. {
  2410. name: 'borderstyle',
  2411. type: 'listbox',
  2412. label: 'Border style',
  2413. items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
  2414. },
  2415. {
  2416. name: 'bordercolor',
  2417. type: 'colorinput',
  2418. label: 'Border color'
  2419. },
  2420. {
  2421. name: 'backgroundcolor',
  2422. type: 'colorinput',
  2423. label: 'Background color'
  2424. }
  2425. ];
  2426. const borderWidth = {
  2427. name: 'borderwidth',
  2428. type: 'input',
  2429. label: 'Border width'
  2430. };
  2431. const items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
  2432. return {
  2433. title: 'Advanced',
  2434. name: 'advanced',
  2435. items
  2436. };
  2437. };
  2438. // The get node is required here because it can be transformed
  2439. // when switching between tags (e.g. th and td)
  2440. const normal = (editor, element) => {
  2441. const dom = editor.dom;
  2442. const setAttrib = (attr, value) => {
  2443. dom.setAttrib(element, attr, value);
  2444. };
  2445. const setStyle = (prop, value) => {
  2446. dom.setStyle(element, prop, value);
  2447. };
  2448. const setFormat = (formatName, value) => {
  2449. // Remove format if given an empty string
  2450. if (value === '') {
  2451. editor.formatter.remove(formatName, { value: null }, element, true);
  2452. }
  2453. else {
  2454. editor.formatter.apply(formatName, { value }, element);
  2455. }
  2456. };
  2457. return {
  2458. setAttrib,
  2459. setStyle,
  2460. setFormat
  2461. };
  2462. };
  2463. const DomModifier = {
  2464. normal
  2465. };
  2466. const rgbToHex = (value) => startsWith(value, 'rgb') ? rgbaToHexString(value) : value;
  2467. const extractAdvancedStyles = (elm) => {
  2468. const element = SugarElement.fromDom(elm);
  2469. return {
  2470. borderwidth: getRaw$1(element, 'border-width').getOr(''),
  2471. borderstyle: getRaw$1(element, 'border-style').getOr(''),
  2472. bordercolor: getRaw$1(element, 'border-color').map(rgbToHex).getOr(''),
  2473. backgroundcolor: getRaw$1(element, 'background-color').map(rgbToHex).getOr('')
  2474. };
  2475. };
  2476. const getSharedValues = (data) => {
  2477. // TODO surely there's a better way to do this??
  2478. // Mutates baseData to return an object that contains only the values
  2479. // that were the same across all objects in data
  2480. const baseData = data[0];
  2481. const comparisonData = data.slice(1);
  2482. each$1(comparisonData, (items) => {
  2483. each$1(keys(baseData), (key) => {
  2484. each(items, (itemValue, itemKey) => {
  2485. const comparisonValue = baseData[key];
  2486. if (comparisonValue !== '' && key === itemKey) {
  2487. if (comparisonValue !== itemValue) {
  2488. baseData[key] = key === 'class' ? 'mce-no-match' : '';
  2489. }
  2490. }
  2491. });
  2492. });
  2493. });
  2494. return baseData;
  2495. };
  2496. // The extractDataFrom... functions are in this file partly for code reuse and partly so we can test them,
  2497. // because some of these are crazy complicated
  2498. const getAlignment = (formats, formatName, editor, elm) => find(formats, (name) => !isUndefined(editor.formatter.matchNode(elm, formatName + name))).getOr('');
  2499. const getHAlignment = curry(getAlignment, ['left', 'center', 'right'], 'align');
  2500. const getVAlignment = curry(getAlignment, ['top', 'middle', 'bottom'], 'valign');
  2501. const extractDataFromSettings = (editor, hasAdvTableTab) => {
  2502. const style = getDefaultStyles(editor);
  2503. const attrs = getDefaultAttributes(editor);
  2504. const extractAdvancedStyleData = () => ({
  2505. borderstyle: get$3(style, 'border-style').getOr(''),
  2506. bordercolor: rgbToHex(get$3(style, 'border-color').getOr('')),
  2507. backgroundcolor: rgbToHex(get$3(style, 'background-color').getOr(''))
  2508. });
  2509. const defaultData = {
  2510. height: '',
  2511. width: '100%',
  2512. cellspacing: '',
  2513. cellpadding: '',
  2514. caption: false,
  2515. class: '',
  2516. align: '',
  2517. border: ''
  2518. };
  2519. const getBorder = () => {
  2520. const borderWidth = style['border-width'];
  2521. if (shouldStyleWithCss(editor) && borderWidth) {
  2522. return { border: borderWidth };
  2523. }
  2524. return get$3(attrs, 'border').fold(() => ({}), (border) => ({ border }));
  2525. };
  2526. const advStyle = (hasAdvTableTab ? extractAdvancedStyleData() : {});
  2527. const getCellPaddingCellSpacing = () => {
  2528. const spacing = get$3(style, 'border-spacing').or(get$3(attrs, 'cellspacing')).fold(() => ({}), (cellspacing) => ({ cellspacing }));
  2529. const padding = get$3(style, 'border-padding').or(get$3(attrs, 'cellpadding')).fold(() => ({}), (cellpadding) => ({ cellpadding }));
  2530. return {
  2531. ...spacing,
  2532. ...padding
  2533. };
  2534. };
  2535. const data = {
  2536. ...defaultData,
  2537. ...style,
  2538. ...attrs,
  2539. ...advStyle,
  2540. ...getBorder(),
  2541. ...getCellPaddingCellSpacing()
  2542. };
  2543. return data;
  2544. };
  2545. const getRowType = (elm) => table(SugarElement.fromDom(elm)).map((table) => {
  2546. const target = { selection: fromDom(elm.cells) };
  2547. return getRowsType(table, target);
  2548. }).getOr('');
  2549. const extractDataFromTableElement = (editor, elm, hasAdvTableTab) => {
  2550. const getBorder = (dom, elm) => {
  2551. // Cases (in order to check):
  2552. // 1. shouldStyleWithCss - extract border-width style if it exists
  2553. // 2. !shouldStyleWithCss && border attribute - set border attribute as value
  2554. // 3. !shouldStyleWithCss && nothing on the table - grab styles from the first th or td
  2555. const optBorderWidth = getRaw$1(SugarElement.fromDom(elm), 'border-width');
  2556. if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
  2557. return optBorderWidth.getOr('');
  2558. }
  2559. return dom.getAttrib(elm, 'border') || getTDTHOverallStyle(editor.dom, elm, 'border-width')
  2560. || getTDTHOverallStyle(editor.dom, elm, 'border') || '';
  2561. };
  2562. const dom = editor.dom;
  2563. const cellspacing = shouldStyleWithCss(editor) ?
  2564. dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing') :
  2565. dom.getAttrib(elm, 'cellspacing') || dom.getStyle(elm, 'border-spacing');
  2566. const cellpadding = shouldStyleWithCss(editor) ?
  2567. getTDTHOverallStyle(dom, elm, 'padding') || dom.getAttrib(elm, 'cellpadding') :
  2568. dom.getAttrib(elm, 'cellpadding') || getTDTHOverallStyle(dom, elm, 'padding');
  2569. return {
  2570. width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
  2571. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  2572. cellspacing: cellspacing !== null && cellspacing !== void 0 ? cellspacing : '',
  2573. cellpadding: cellpadding !== null && cellpadding !== void 0 ? cellpadding : '',
  2574. border: getBorder(dom, elm),
  2575. caption: !!dom.select('caption', elm)[0],
  2576. class: dom.getAttrib(elm, 'class', ''),
  2577. align: getHAlignment(editor, elm),
  2578. ...(hasAdvTableTab ? extractAdvancedStyles(elm) : {})
  2579. };
  2580. };
  2581. const extractDataFromRowElement = (editor, elm, hasAdvancedRowTab) => {
  2582. const dom = editor.dom;
  2583. return {
  2584. height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
  2585. class: dom.getAttrib(elm, 'class', ''),
  2586. type: getRowType(elm),
  2587. align: getHAlignment(editor, elm),
  2588. ...(hasAdvancedRowTab ? extractAdvancedStyles(elm) : {})
  2589. };
  2590. };
  2591. const extractDataFromCellElement = (editor, cell, hasAdvancedCellTab, column) => {
  2592. const dom = editor.dom;
  2593. const colElm = column.getOr(cell);
  2594. const getStyle = (element, style) => dom.getStyle(element, style) || dom.getAttrib(element, style);
  2595. return {
  2596. width: getStyle(colElm, 'width'),
  2597. scope: dom.getAttrib(cell, 'scope'),
  2598. celltype: getNodeName(cell),
  2599. class: dom.getAttrib(cell, 'class', ''),
  2600. halign: getHAlignment(editor, cell),
  2601. valign: getVAlignment(editor, cell),
  2602. ...(hasAdvancedCellTab ? extractAdvancedStyles(cell) : {})
  2603. };
  2604. };
  2605. const getSelectedCells = (table, cells) => {
  2606. const warehouse = Warehouse.fromTable(table);
  2607. const allCells = Warehouse.justCells(warehouse);
  2608. const filtered = filter$1(allCells, (cellA) => exists(cells, (cellB) => eq(cellA.element, cellB)));
  2609. return map(filtered, (cell) => ({
  2610. element: cell.element.dom,
  2611. column: Warehouse.getColumnAt(warehouse, cell.column).map((col) => col.element.dom)
  2612. }));
  2613. };
  2614. const updateSimpleProps$1 = (modifier, colModifier, data, shouldUpdate) => {
  2615. if (shouldUpdate('scope')) {
  2616. modifier.setAttrib('scope', data.scope);
  2617. }
  2618. if (shouldUpdate('class') && data.class !== 'mce-no-match') {
  2619. modifier.setAttrib('class', data.class);
  2620. }
  2621. if (shouldUpdate('width')) {
  2622. colModifier.setStyle('width', addPxSuffix(data.width));
  2623. }
  2624. };
  2625. const updateAdvancedProps$1 = (modifier, data, shouldUpdate) => {
  2626. if (shouldUpdate('backgroundcolor')) {
  2627. modifier.setFormat('tablecellbackgroundcolor', data.backgroundcolor);
  2628. }
  2629. if (shouldUpdate('bordercolor')) {
  2630. modifier.setFormat('tablecellbordercolor', data.bordercolor);
  2631. }
  2632. if (shouldUpdate('borderstyle')) {
  2633. modifier.setFormat('tablecellborderstyle', data.borderstyle);
  2634. }
  2635. if (shouldUpdate('borderwidth')) {
  2636. modifier.setFormat('tablecellborderwidth', addPxSuffix(data.borderwidth));
  2637. }
  2638. };
  2639. const applyStyleData$1 = (editor, cells, data, wasChanged) => {
  2640. const isSingleCell = cells.length === 1;
  2641. each$1(cells, (item) => {
  2642. const cellElm = item.element;
  2643. const shouldOverrideCurrentValue = isSingleCell ? always : wasChanged;
  2644. const modifier = DomModifier.normal(editor, cellElm);
  2645. const colModifier = item.column.map((col) => DomModifier.normal(editor, col)).getOr(modifier);
  2646. updateSimpleProps$1(modifier, colModifier, data, shouldOverrideCurrentValue);
  2647. if (hasAdvancedCellTab(editor)) {
  2648. updateAdvancedProps$1(modifier, data, shouldOverrideCurrentValue);
  2649. }
  2650. // Apply alignment
  2651. if (wasChanged('halign')) {
  2652. setAlign(editor, cellElm, data.halign);
  2653. }
  2654. // Apply vertical alignment
  2655. if (wasChanged('valign')) {
  2656. setVAlign(editor, cellElm, data.valign);
  2657. }
  2658. });
  2659. };
  2660. const applyStructureData$1 = (editor, data) => {
  2661. // Switch cell type if applicable. Note that we specifically tell the command to not fire events
  2662. // as we'll batch the events and fire a `TableModified` event at the end of the updates.
  2663. editor.execCommand('mceTableCellType', false, { type: data.celltype, no_events: true });
  2664. };
  2665. const applyCellData = (editor, cells, oldData, data) => {
  2666. const modifiedData = filter(data, (value, key) => oldData[key] !== value);
  2667. if (size(modifiedData) > 0 && cells.length >= 1) {
  2668. // Retrieve the table before the cells are modified as there is a case where cells
  2669. // are replaced and the reference will be lost when trying to fire events.
  2670. table(cells[0]).each((table) => {
  2671. const selectedCells = getSelectedCells(table, cells);
  2672. // style modified if there's at least one other change apart from 'celltype' and 'scope'
  2673. const styleModified = size(filter(modifiedData, (_value, key) => key !== 'scope' && key !== 'celltype')) > 0;
  2674. const structureModified = has(modifiedData, 'celltype');
  2675. // Update the cells styling using the dialog data
  2676. if (styleModified || has(modifiedData, 'scope')) {
  2677. applyStyleData$1(editor, selectedCells, data, curry(has, modifiedData));
  2678. }
  2679. // Update the cells structure using the dialog data
  2680. if (structureModified) {
  2681. applyStructureData$1(editor, data);
  2682. }
  2683. fireTableModified(editor, table.dom, {
  2684. structure: structureModified,
  2685. style: styleModified,
  2686. });
  2687. });
  2688. }
  2689. };
  2690. const onSubmitCellForm = (editor, cells, oldData, api) => {
  2691. const data = api.getData();
  2692. api.close();
  2693. editor.undoManager.transact(() => {
  2694. applyCellData(editor, cells, oldData, data);
  2695. editor.focus();
  2696. });
  2697. };
  2698. const getData$1 = (editor, cells) => {
  2699. const cellsData = table(cells[0]).map((table) => map(getSelectedCells(table, cells), (item) => extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column)));
  2700. return getSharedValues(cellsData.getOrDie());
  2701. };
  2702. const open$2 = (editor) => {
  2703. const cells = getCellsFromSelection(editor);
  2704. // Check if there are any cells to operate on
  2705. if (cells.length === 0) {
  2706. return;
  2707. }
  2708. const data = getData$1(editor, cells);
  2709. const dialogTabPanel = {
  2710. type: 'tabpanel',
  2711. tabs: [
  2712. {
  2713. title: 'General',
  2714. name: 'general',
  2715. items: getItems$2(editor)
  2716. },
  2717. getAdvancedTab(editor, 'cell')
  2718. ]
  2719. };
  2720. const dialogPanel = {
  2721. type: 'panel',
  2722. items: [
  2723. {
  2724. type: 'grid',
  2725. columns: 2,
  2726. items: getItems$2(editor)
  2727. }
  2728. ]
  2729. };
  2730. editor.windowManager.open({
  2731. title: 'Cell Properties',
  2732. size: 'normal',
  2733. body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
  2734. buttons: [
  2735. {
  2736. type: 'cancel',
  2737. name: 'cancel',
  2738. text: 'Cancel'
  2739. },
  2740. {
  2741. type: 'submit',
  2742. name: 'save',
  2743. text: 'Save',
  2744. primary: true
  2745. }
  2746. ],
  2747. initialData: data,
  2748. onSubmit: curry(onSubmitCellForm, editor, cells, data)
  2749. });
  2750. };
  2751. const getClassList = (editor) => buildClassList(getRowClassList(editor))
  2752. .map((items) => ({
  2753. name: 'class',
  2754. type: 'listbox',
  2755. label: 'Class',
  2756. items
  2757. }));
  2758. const formChildren = [
  2759. {
  2760. type: 'listbox',
  2761. name: 'type',
  2762. label: 'Row type',
  2763. items: [
  2764. { text: 'Header', value: 'header' },
  2765. { text: 'Body', value: 'body' },
  2766. { text: 'Footer', value: 'footer' }
  2767. ]
  2768. },
  2769. {
  2770. type: 'listbox',
  2771. name: 'align',
  2772. label: 'Alignment',
  2773. items: [
  2774. { text: 'None', value: '' },
  2775. { text: 'Left', value: 'left' },
  2776. { text: 'Center', value: 'center' },
  2777. { text: 'Right', value: 'right' }
  2778. ]
  2779. },
  2780. {
  2781. label: 'Height',
  2782. name: 'height',
  2783. type: 'input'
  2784. }
  2785. ];
  2786. const getItems$1 = (editor) => formChildren.concat(getClassList(editor).toArray());
  2787. const updateSimpleProps = (modifier, data, shouldUpdate) => {
  2788. if (shouldUpdate('class') && data.class !== 'mce-no-match') {
  2789. modifier.setAttrib('class', data.class);
  2790. }
  2791. if (shouldUpdate('height')) {
  2792. modifier.setStyle('height', addPxSuffix(data.height));
  2793. }
  2794. };
  2795. const updateAdvancedProps = (modifier, data, shouldUpdate) => {
  2796. if (shouldUpdate('backgroundcolor')) {
  2797. modifier.setStyle('background-color', data.backgroundcolor);
  2798. }
  2799. if (shouldUpdate('bordercolor')) {
  2800. modifier.setStyle('border-color', data.bordercolor);
  2801. }
  2802. if (shouldUpdate('borderstyle')) {
  2803. modifier.setStyle('border-style', data.borderstyle);
  2804. }
  2805. };
  2806. const applyStyleData = (editor, rows, data, wasChanged) => {
  2807. const isSingleRow = rows.length === 1;
  2808. const shouldOverrideCurrentValue = isSingleRow ? always : wasChanged;
  2809. each$1(rows, (rowElm) => {
  2810. const rowCells = children$1(SugarElement.fromDom(rowElm), 'td,th');
  2811. const modifier = DomModifier.normal(editor, rowElm);
  2812. updateSimpleProps(modifier, data, shouldOverrideCurrentValue);
  2813. if (hasAdvancedRowTab(editor)) {
  2814. updateAdvancedProps(modifier, data, shouldOverrideCurrentValue);
  2815. }
  2816. // TINY-10617: Simplify number of height styles when applying height on tr
  2817. if (wasChanged('height')) {
  2818. each$1(rowCells, (cell) => {
  2819. editor.dom.setStyle(cell.dom, 'height', null);
  2820. });
  2821. }
  2822. if (wasChanged('align')) {
  2823. setAlign(editor, rowElm, data.align);
  2824. }
  2825. });
  2826. };
  2827. const applyStructureData = (editor, data) => {
  2828. // Switch cell type if applicable. Note that we specifically tell the command to not fire events
  2829. // as we'll batch the events and fire a `TableModified` event at the end of the updates.
  2830. editor.execCommand('mceTableRowType', false, { type: data.type, no_events: true });
  2831. };
  2832. const applyRowData = (editor, rows, oldData, data) => {
  2833. const modifiedData = filter(data, (value, key) => oldData[key] !== value);
  2834. if (size(modifiedData) > 0) {
  2835. const typeModified = has(modifiedData, 'type');
  2836. // style modified if there's at least one other change apart from 'type'
  2837. const styleModified = typeModified ? size(modifiedData) > 1 : true;
  2838. // Update the rows styling using the dialog data
  2839. if (styleModified) {
  2840. applyStyleData(editor, rows, data, curry(has, modifiedData));
  2841. }
  2842. // Update the rows structure using the dialog data
  2843. if (typeModified) {
  2844. applyStructureData(editor, data);
  2845. }
  2846. table(SugarElement.fromDom(rows[0])).each((table) => fireTableModified(editor, table.dom, {
  2847. structure: typeModified,
  2848. style: styleModified
  2849. }));
  2850. }
  2851. };
  2852. const onSubmitRowForm = (editor, rows, oldData, api) => {
  2853. const data = api.getData();
  2854. api.close();
  2855. editor.undoManager.transact(() => {
  2856. applyRowData(editor, rows, oldData, data);
  2857. editor.focus();
  2858. });
  2859. };
  2860. const open$1 = (editor) => {
  2861. const rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
  2862. // Check if there are any rows to operate on
  2863. if (rows.length === 0) {
  2864. return;
  2865. }
  2866. // Get current data and find shared values between rows
  2867. const rowsData = map(rows, (rowElm) => extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor)));
  2868. const data = getSharedValues(rowsData);
  2869. const dialogTabPanel = {
  2870. type: 'tabpanel',
  2871. tabs: [
  2872. {
  2873. title: 'General',
  2874. name: 'general',
  2875. items: getItems$1(editor)
  2876. },
  2877. getAdvancedTab(editor, 'row')
  2878. ]
  2879. };
  2880. const dialogPanel = {
  2881. type: 'panel',
  2882. items: [
  2883. {
  2884. type: 'grid',
  2885. columns: 2,
  2886. items: getItems$1(editor)
  2887. }
  2888. ]
  2889. };
  2890. editor.windowManager.open({
  2891. title: 'Row Properties',
  2892. size: 'normal',
  2893. body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
  2894. buttons: [
  2895. {
  2896. type: 'cancel',
  2897. name: 'cancel',
  2898. text: 'Cancel'
  2899. },
  2900. {
  2901. type: 'submit',
  2902. name: 'save',
  2903. text: 'Save',
  2904. primary: true
  2905. }
  2906. ],
  2907. initialData: data,
  2908. onSubmit: curry(onSubmitRowForm, editor, map(rows, (r) => r.dom), data)
  2909. });
  2910. };
  2911. const getItems = (editor, classes, insertNewTable) => {
  2912. const rowColCountItems = !insertNewTable ? [] : [
  2913. {
  2914. type: 'input',
  2915. name: 'cols',
  2916. label: 'Cols',
  2917. inputMode: 'numeric'
  2918. },
  2919. {
  2920. type: 'input',
  2921. name: 'rows',
  2922. label: 'Rows',
  2923. inputMode: 'numeric'
  2924. }
  2925. ];
  2926. const alwaysItems = [
  2927. {
  2928. type: 'input',
  2929. name: 'width',
  2930. label: 'Width'
  2931. },
  2932. {
  2933. type: 'input',
  2934. name: 'height',
  2935. label: 'Height'
  2936. }
  2937. ];
  2938. const appearanceItems = hasAppearanceOptions(editor) ? [
  2939. {
  2940. type: 'input',
  2941. name: 'cellspacing',
  2942. label: 'Cell spacing',
  2943. inputMode: 'numeric'
  2944. },
  2945. {
  2946. type: 'input',
  2947. name: 'cellpadding',
  2948. label: 'Cell padding',
  2949. inputMode: 'numeric'
  2950. },
  2951. {
  2952. type: 'input',
  2953. name: 'border',
  2954. label: 'Border width'
  2955. },
  2956. {
  2957. type: 'label',
  2958. label: 'Caption',
  2959. items: [
  2960. {
  2961. type: 'checkbox',
  2962. name: 'caption',
  2963. label: 'Show caption'
  2964. }
  2965. ]
  2966. }
  2967. ] : [];
  2968. const alignmentItem = [
  2969. {
  2970. type: 'listbox',
  2971. name: 'align',
  2972. label: 'Alignment',
  2973. items: [
  2974. { text: 'None', value: '' },
  2975. { text: 'Left', value: 'left' },
  2976. { text: 'Center', value: 'center' },
  2977. { text: 'Right', value: 'right' }
  2978. ]
  2979. }
  2980. ];
  2981. const classListItem = classes.length > 0 ? [
  2982. {
  2983. name: 'class',
  2984. type: 'listbox',
  2985. label: 'Class',
  2986. items: classes
  2987. }
  2988. ] : [];
  2989. return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
  2990. };
  2991. // Explore the layers of the table till we find the first layer of tds or ths
  2992. const styleTDTH = (dom, elm, name, value) => {
  2993. if (elm.tagName === 'TD' || elm.tagName === 'TH') {
  2994. if (isString(name) && isNonNullable(value)) {
  2995. dom.setStyle(elm, name, value);
  2996. }
  2997. else {
  2998. dom.setStyles(elm, name);
  2999. }
  3000. }
  3001. else {
  3002. if (elm.children) {
  3003. for (let i = 0; i < elm.children.length; i++) {
  3004. styleTDTH(dom, elm.children[i], name, value);
  3005. }
  3006. }
  3007. }
  3008. };
  3009. const applyDataToElement = (editor, tableElm, data, shouldApplyOnCell) => {
  3010. const dom = editor.dom;
  3011. const attrs = {};
  3012. const styles = {};
  3013. const shouldStyleWithCss$1 = shouldStyleWithCss(editor);
  3014. const hasAdvancedTableTab$1 = hasAdvancedTableTab(editor);
  3015. const borderIsZero = parseFloat(data.border) === 0;
  3016. if (!isUndefined(data.class) && data.class !== 'mce-no-match') {
  3017. attrs.class = data.class;
  3018. }
  3019. styles.height = addPxSuffix(data.height);
  3020. if (shouldStyleWithCss$1) {
  3021. styles.width = addPxSuffix(data.width);
  3022. }
  3023. else if (dom.getAttrib(tableElm, 'width')) {
  3024. attrs.width = removePxSuffix(data.width);
  3025. }
  3026. if (shouldStyleWithCss$1) {
  3027. if (borderIsZero) {
  3028. attrs.border = 0;
  3029. styles['border-width'] = '';
  3030. }
  3031. else {
  3032. styles['border-width'] = addPxSuffix(data.border);
  3033. attrs.border = 1;
  3034. }
  3035. styles['border-spacing'] = addPxSuffix(data.cellspacing);
  3036. }
  3037. else {
  3038. attrs.border = borderIsZero ? 0 : data.border;
  3039. attrs.cellpadding = data.cellpadding;
  3040. attrs.cellspacing = data.cellspacing;
  3041. }
  3042. // TINY-9837: Relevant data are applied on child TD/THs only if they have been modified since the previous dialog submission
  3043. if (shouldStyleWithCss$1 && tableElm.children) {
  3044. const cellStyles = {};
  3045. if (borderIsZero) {
  3046. cellStyles['border-width'] = '';
  3047. }
  3048. else if (shouldApplyOnCell.border) {
  3049. cellStyles['border-width'] = addPxSuffix(data.border);
  3050. }
  3051. if (shouldApplyOnCell.cellpadding) {
  3052. cellStyles.padding = addPxSuffix(data.cellpadding);
  3053. }
  3054. if (hasAdvancedTableTab$1 && shouldApplyOnCell.bordercolor) {
  3055. cellStyles['border-color'] = data.bordercolor;
  3056. }
  3057. if (!isEmpty$1(cellStyles)) {
  3058. for (let i = 0; i < tableElm.children.length; i++) {
  3059. styleTDTH(dom, tableElm.children[i], cellStyles);
  3060. }
  3061. }
  3062. }
  3063. if (hasAdvancedTableTab$1) {
  3064. const advData = data;
  3065. styles['background-color'] = advData.backgroundcolor;
  3066. styles['border-color'] = advData.bordercolor;
  3067. styles['border-style'] = advData.borderstyle;
  3068. }
  3069. dom.setStyles(tableElm, { ...getDefaultStyles(editor), ...styles });
  3070. dom.setAttribs(tableElm, { ...getDefaultAttributes(editor), ...attrs });
  3071. };
  3072. const onSubmitTableForm = (editor, tableElm, oldData, api) => {
  3073. const dom = editor.dom;
  3074. const data = api.getData();
  3075. const modifiedData = filter(data, (value, key) => oldData[key] !== value);
  3076. api.close();
  3077. editor.undoManager.transact(() => {
  3078. if (!tableElm) {
  3079. const cols = toInt(data.cols).getOr(1);
  3080. const rows = toInt(data.rows).getOr(1);
  3081. // Cases 1 & 3 - inserting a table
  3082. editor.execCommand('mceInsertTable', false, { rows, columns: cols });
  3083. tableElm = getSelectionCell(getSelectionStart(editor), getIsRoot(editor))
  3084. .bind((cell) => table(cell, getIsRoot(editor)))
  3085. .map((table) => table.dom)
  3086. .getOrDie();
  3087. }
  3088. if (size(modifiedData) > 0) {
  3089. const applicableCellProperties = {
  3090. border: has(modifiedData, 'border'),
  3091. bordercolor: has(modifiedData, 'bordercolor'),
  3092. cellpadding: has(modifiedData, 'cellpadding')
  3093. };
  3094. applyDataToElement(editor, tableElm, data, applicableCellProperties);
  3095. // Toggle caption on/off
  3096. const captionElm = dom.select('caption', tableElm)[0];
  3097. if (captionElm && !data.caption || !captionElm && data.caption) {
  3098. editor.execCommand('mceTableToggleCaption');
  3099. }
  3100. setAlign(editor, tableElm, data.align);
  3101. }
  3102. editor.focus();
  3103. editor.addVisual();
  3104. if (size(modifiedData) > 0) {
  3105. const captionModified = has(modifiedData, 'caption');
  3106. // style modified if there's at least one other change apart from 'caption'
  3107. const styleModified = captionModified ? size(modifiedData) > 1 : true;
  3108. fireTableModified(editor, tableElm, { structure: captionModified, style: styleModified });
  3109. }
  3110. });
  3111. };
  3112. const open = (editor, insertNewTable) => {
  3113. const dom = editor.dom;
  3114. let tableElm;
  3115. let data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
  3116. // Cases for creation/update of tables:
  3117. // 1. isNew == true - called by mceInsertTable - we are inserting a new table so we don't care what the selection's parent is,
  3118. // and we need to add cols and rows input fields to the dialog
  3119. // 2. isNew == false && selection parent is a table - update the table
  3120. // 3. isNew == false && selection parent isn't a table - open dialog with default values and insert a table
  3121. if (insertNewTable) {
  3122. // Case 1 - isNew == true. We're inserting a new table so use defaults and add cols and rows + adv properties.
  3123. data.cols = '1';
  3124. data.rows = '1';
  3125. if (hasAdvancedTableTab(editor)) {
  3126. data.borderstyle = '';
  3127. data.bordercolor = '';
  3128. data.backgroundcolor = '';
  3129. }
  3130. }
  3131. else {
  3132. tableElm = dom.getParent(editor.selection.getStart(), 'table', editor.getBody());
  3133. if (tableElm) {
  3134. // Case 2 - isNew == false && table parent
  3135. data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
  3136. }
  3137. else {
  3138. // Case 3 - isNew == false && non-table parent. data is set to basic defaults so just add the adv properties if needed
  3139. if (hasAdvancedTableTab(editor)) {
  3140. data.borderstyle = '';
  3141. data.bordercolor = '';
  3142. data.backgroundcolor = '';
  3143. }
  3144. }
  3145. }
  3146. const classes = buildClassList(getTableClassList(editor));
  3147. if (classes.isSome()) {
  3148. if (data.class) {
  3149. data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
  3150. }
  3151. }
  3152. const generalPanel = {
  3153. type: 'grid',
  3154. columns: 2,
  3155. items: getItems(editor, classes.getOr([]), insertNewTable)
  3156. };
  3157. const nonAdvancedForm = () => ({
  3158. type: 'panel',
  3159. items: [generalPanel]
  3160. });
  3161. const advancedForm = () => ({
  3162. type: 'tabpanel',
  3163. tabs: [
  3164. {
  3165. title: 'General',
  3166. name: 'general',
  3167. items: [generalPanel]
  3168. },
  3169. getAdvancedTab(editor, 'table')
  3170. ]
  3171. });
  3172. const dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
  3173. editor.windowManager.open({
  3174. title: 'Table Properties',
  3175. size: 'normal',
  3176. body: dialogBody,
  3177. onSubmit: curry(onSubmitTableForm, editor, tableElm, data),
  3178. buttons: [
  3179. {
  3180. type: 'cancel',
  3181. name: 'cancel',
  3182. text: 'Cancel'
  3183. },
  3184. {
  3185. type: 'submit',
  3186. name: 'save',
  3187. text: 'Save',
  3188. primary: true
  3189. }
  3190. ],
  3191. initialData: data
  3192. });
  3193. };
  3194. const registerCommands = (editor) => {
  3195. const runAction = (f) => {
  3196. if (isInEditableContext(getSelectionStart(editor))) {
  3197. f();
  3198. }
  3199. };
  3200. // Register dialog commands
  3201. each({
  3202. // AP-101 TableDialog.open renders a slightly different dialog if isNew is true
  3203. mceTableProps: curry(open, editor, false),
  3204. mceTableRowProps: curry(open$1, editor),
  3205. mceTableCellProps: curry(open$2, editor),
  3206. mceInsertTableDialog: curry(open, editor, true),
  3207. }, (func, name) => editor.addCommand(name, () => runAction(func)));
  3208. };
  3209. /*
  3210. NOTE: This file is partially duplicated in the following locations:
  3211. - models/dom/table/queries/TableTargets.ts
  3212. - advtable
  3213. Make sure that if making changes to this file, the other files are updated as well
  3214. */
  3215. const noMenu = (cell) => ({
  3216. element: cell,
  3217. mergable: Optional.none(),
  3218. unmergable: Optional.none(),
  3219. selection: [cell]
  3220. });
  3221. const forMenu = (selectedCells, table, cell) => ({
  3222. element: cell,
  3223. mergable: mergable(table, selectedCells, ephemera),
  3224. unmergable: unmergable(selectedCells),
  3225. selection: selection(selectedCells)
  3226. });
  3227. const getSelectionTargets = (editor) => {
  3228. const targets = Cell(Optional.none());
  3229. const changeHandlers = Cell([]);
  3230. let selectionDetails = Optional.none();
  3231. const isCaption = isTag('caption');
  3232. const isDisabledForSelection = (key) => selectionDetails.forall((details) => !details[key]);
  3233. const getStart = () => getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
  3234. const getEnd = () => getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
  3235. const findTargets = () => getStart().bind((startCellOrCaption) => flatten(lift2(table(startCellOrCaption), getEnd().bind(table), (startTable, endTable) => {
  3236. if (eq(startTable, endTable)) {
  3237. if (isCaption(startCellOrCaption)) {
  3238. return Optional.some(noMenu(startCellOrCaption));
  3239. }
  3240. else {
  3241. return Optional.some(forMenu(getCellsFromSelection(editor), startTable, startCellOrCaption));
  3242. }
  3243. }
  3244. return Optional.none();
  3245. })));
  3246. const getExtractedDetails = (targets) => {
  3247. const tableOpt = table(targets.element);
  3248. return tableOpt.map((table) => {
  3249. const warehouse = Warehouse.fromTable(table);
  3250. const selectedCells = onCells(warehouse, targets).getOr([]);
  3251. const locked = foldl(selectedCells, (acc, cell) => {
  3252. if (cell.isLocked) {
  3253. acc.onAny = true;
  3254. if (cell.column === 0) {
  3255. acc.onFirst = true;
  3256. }
  3257. else if (cell.column + cell.colspan >= warehouse.grid.columns) {
  3258. acc.onLast = true;
  3259. }
  3260. }
  3261. return acc;
  3262. }, { onAny: false, onFirst: false, onLast: false });
  3263. return {
  3264. mergeable: onUnlockedMergable(warehouse, targets).isSome(),
  3265. unmergeable: onUnlockedUnmergable(warehouse, targets).isSome(),
  3266. locked
  3267. };
  3268. });
  3269. };
  3270. const resetTargets = () => {
  3271. // Reset the targets
  3272. targets.set(cached(findTargets)());
  3273. // Reset the selection details
  3274. selectionDetails = targets.get().bind(getExtractedDetails);
  3275. // Trigger change handlers
  3276. each$1(changeHandlers.get(), call);
  3277. };
  3278. const setupHandler = (handler) => {
  3279. // Execute the handler to set the initial state
  3280. handler();
  3281. // Register the handler so we can update the state when resetting targets
  3282. changeHandlers.set(changeHandlers.get().concat([handler]));
  3283. return () => {
  3284. changeHandlers.set(filter$1(changeHandlers.get(), (h) => h !== handler));
  3285. };
  3286. };
  3287. const onSetup = (api, isDisabled) => setupHandler(() => targets.get().fold(() => {
  3288. api.setEnabled(false);
  3289. }, (targets) => {
  3290. api.setEnabled(!isDisabled(targets) && editor.selection.isEditable());
  3291. }));
  3292. const onSetupWithToggle = (api, isDisabled, isActive) => setupHandler(() => targets.get().fold(() => {
  3293. api.setEnabled(false);
  3294. api.setActive(false);
  3295. }, (targets) => {
  3296. api.setEnabled(!isDisabled(targets) && editor.selection.isEditable());
  3297. api.setActive(isActive(targets));
  3298. }));
  3299. const isDisabledFromLocked = (lockedDisable) => selectionDetails.exists((details) => details.locked[lockedDisable]);
  3300. const onSetupTable = (api) => onSetup(api, (_) => false);
  3301. const onSetupCellOrRow = (api) => onSetup(api, (targets) => isCaption(targets.element));
  3302. const onSetupColumn = (lockedDisable) => (api) => onSetup(api, (targets) => isCaption(targets.element) || isDisabledFromLocked(lockedDisable));
  3303. const onSetupPasteable = (getClipboardData) => (api) => onSetup(api, (targets) => isCaption(targets.element) || getClipboardData().isNone());
  3304. const onSetupPasteableColumn = (getClipboardData, lockedDisable) => (api) => onSetup(api, (targets) => isCaption(targets.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable));
  3305. const onSetupMergeable = (api) => onSetup(api, (_targets) => isDisabledForSelection('mergeable'));
  3306. const onSetupUnmergeable = (api) => onSetup(api, (_targets) => isDisabledForSelection('unmergeable'));
  3307. const onSetupTableWithCaption = (api) => {
  3308. return onSetupWithToggle(api, never, (targets) => {
  3309. const tableOpt = table(targets.element, getIsRoot(editor));
  3310. return tableOpt.exists((table) => child(table, 'caption'));
  3311. });
  3312. };
  3313. const onSetupTableHeaders = (command, headerType) => (api) => {
  3314. return onSetupWithToggle(api, (targets) => isCaption(targets.element), () => editor.queryCommandValue(command) === headerType);
  3315. };
  3316. const onSetupTableRowHeaders = onSetupTableHeaders('mceTableRowType', 'header');
  3317. const onSetupTableColumnHeaders = onSetupTableHeaders('mceTableColType', 'th');
  3318. editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
  3319. return {
  3320. onSetupTable,
  3321. onSetupCellOrRow,
  3322. onSetupColumn,
  3323. onSetupPasteable,
  3324. onSetupPasteableColumn,
  3325. onSetupMergeable,
  3326. onSetupUnmergeable,
  3327. resetTargets,
  3328. onSetupTableWithCaption,
  3329. onSetupTableRowHeaders,
  3330. onSetupTableColumnHeaders,
  3331. targets: targets.get
  3332. };
  3333. };
  3334. var global = tinymce.util.Tools.resolve('tinymce.FakeClipboard');
  3335. /*
  3336. NOTE: This file is duplicated in the following locations:
  3337. - models/dom/table/api/Clipboard.ts
  3338. Make sure that if making changes to this file, the other files are updated as well
  3339. */
  3340. const tableTypeBase = 'x-tinymce/dom-table-';
  3341. const tableTypeRow = tableTypeBase + 'rows';
  3342. const tableTypeColumn = tableTypeBase + 'columns';
  3343. const getData = (type) => {
  3344. var _a;
  3345. const items = (_a = global.read()) !== null && _a !== void 0 ? _a : [];
  3346. return findMap(items, (item) => Optional.from(item.getType(type)));
  3347. };
  3348. const getRows = () => getData(tableTypeRow);
  3349. const getColumns = () => getData(tableTypeColumn);
  3350. const onSetupEditable$1 = (editor) => (api) => {
  3351. const nodeChanged = () => {
  3352. api.setEnabled(editor.selection.isEditable());
  3353. };
  3354. editor.on('NodeChange', nodeChanged);
  3355. nodeChanged();
  3356. return () => {
  3357. editor.off('NodeChange', nodeChanged);
  3358. };
  3359. };
  3360. const addButtons = (editor, selectionTargets) => {
  3361. editor.ui.registry.addMenuButton('table', {
  3362. tooltip: 'Table',
  3363. icon: 'table',
  3364. onSetup: onSetupEditable$1(editor),
  3365. fetch: (callback) => callback('inserttable | cell row column | advtablesort | tableprops deletetable')
  3366. });
  3367. const cmd = (command) => () => editor.execCommand(command);
  3368. // TODO: TINY-8172 Unwind this when an alternative solution is found
  3369. const addButtonIfRegistered = (name, spec) => {
  3370. if (editor.queryCommandSupported(spec.command)) {
  3371. editor.ui.registry.addButton(name, {
  3372. ...spec,
  3373. onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
  3374. });
  3375. }
  3376. };
  3377. // TODO: TINY-8172 Unwind this when an alternative solution is found
  3378. const addToggleButtonIfRegistered = (name, spec) => {
  3379. if (editor.queryCommandSupported(spec.command)) {
  3380. editor.ui.registry.addToggleButton(name, {
  3381. ...spec,
  3382. onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
  3383. });
  3384. }
  3385. };
  3386. addButtonIfRegistered('tableprops', {
  3387. tooltip: 'Table properties',
  3388. command: 'mceTableProps',
  3389. icon: 'table',
  3390. onSetup: selectionTargets.onSetupTable
  3391. });
  3392. addButtonIfRegistered('tabledelete', {
  3393. tooltip: 'Delete table',
  3394. command: 'mceTableDelete',
  3395. icon: 'table-delete-table',
  3396. onSetup: selectionTargets.onSetupTable
  3397. });
  3398. addButtonIfRegistered('tablecellprops', {
  3399. tooltip: 'Cell properties',
  3400. command: 'mceTableCellProps',
  3401. icon: 'table-cell-properties',
  3402. onSetup: selectionTargets.onSetupCellOrRow
  3403. });
  3404. addButtonIfRegistered('tablemergecells', {
  3405. tooltip: 'Merge cells',
  3406. command: 'mceTableMergeCells',
  3407. icon: 'table-merge-cells',
  3408. onSetup: selectionTargets.onSetupMergeable
  3409. });
  3410. addButtonIfRegistered('tablesplitcells', {
  3411. tooltip: 'Split cell',
  3412. command: 'mceTableSplitCells',
  3413. icon: 'table-split-cells',
  3414. onSetup: selectionTargets.onSetupUnmergeable
  3415. });
  3416. addButtonIfRegistered('tableinsertrowbefore', {
  3417. tooltip: 'Insert row before',
  3418. command: 'mceTableInsertRowBefore',
  3419. icon: 'table-insert-row-above',
  3420. onSetup: selectionTargets.onSetupCellOrRow
  3421. });
  3422. addButtonIfRegistered('tableinsertrowafter', {
  3423. tooltip: 'Insert row after',
  3424. command: 'mceTableInsertRowAfter',
  3425. icon: 'table-insert-row-after',
  3426. onSetup: selectionTargets.onSetupCellOrRow
  3427. });
  3428. addButtonIfRegistered('tabledeleterow', {
  3429. tooltip: 'Delete row',
  3430. command: 'mceTableDeleteRow',
  3431. icon: 'table-delete-row',
  3432. onSetup: selectionTargets.onSetupCellOrRow
  3433. });
  3434. addButtonIfRegistered('tablerowprops', {
  3435. tooltip: 'Row properties',
  3436. command: 'mceTableRowProps',
  3437. icon: 'table-row-properties',
  3438. onSetup: selectionTargets.onSetupCellOrRow
  3439. });
  3440. addButtonIfRegistered('tableinsertcolbefore', {
  3441. tooltip: 'Insert column before',
  3442. command: 'mceTableInsertColBefore',
  3443. icon: 'table-insert-column-before',
  3444. onSetup: selectionTargets.onSetupColumn("onFirst" /* LockedDisable.onFirst */)
  3445. });
  3446. addButtonIfRegistered('tableinsertcolafter', {
  3447. tooltip: 'Insert column after',
  3448. command: 'mceTableInsertColAfter',
  3449. icon: 'table-insert-column-after',
  3450. onSetup: selectionTargets.onSetupColumn("onLast" /* LockedDisable.onLast */)
  3451. });
  3452. addButtonIfRegistered('tabledeletecol', {
  3453. tooltip: 'Delete column',
  3454. command: 'mceTableDeleteCol',
  3455. icon: 'table-delete-column',
  3456. onSetup: selectionTargets.onSetupColumn("onAny" /* LockedDisable.onAny */)
  3457. });
  3458. addButtonIfRegistered('tablecutrow', {
  3459. tooltip: 'Cut row',
  3460. command: 'mceTableCutRow',
  3461. icon: 'cut-row',
  3462. onSetup: selectionTargets.onSetupCellOrRow
  3463. });
  3464. addButtonIfRegistered('tablecopyrow', {
  3465. tooltip: 'Copy row',
  3466. command: 'mceTableCopyRow',
  3467. icon: 'duplicate-row',
  3468. onSetup: selectionTargets.onSetupCellOrRow
  3469. });
  3470. addButtonIfRegistered('tablepasterowbefore', {
  3471. tooltip: 'Paste row before',
  3472. command: 'mceTablePasteRowBefore',
  3473. icon: 'paste-row-before',
  3474. onSetup: selectionTargets.onSetupPasteable(getRows)
  3475. });
  3476. addButtonIfRegistered('tablepasterowafter', {
  3477. tooltip: 'Paste row after',
  3478. command: 'mceTablePasteRowAfter',
  3479. icon: 'paste-row-after',
  3480. onSetup: selectionTargets.onSetupPasteable(getRows)
  3481. });
  3482. addButtonIfRegistered('tablecutcol', {
  3483. tooltip: 'Cut column',
  3484. command: 'mceTableCutCol',
  3485. icon: 'cut-column',
  3486. onSetup: selectionTargets.onSetupColumn("onAny" /* LockedDisable.onAny */)
  3487. });
  3488. addButtonIfRegistered('tablecopycol', {
  3489. tooltip: 'Copy column',
  3490. command: 'mceTableCopyCol',
  3491. icon: 'duplicate-column',
  3492. onSetup: selectionTargets.onSetupColumn("onAny" /* LockedDisable.onAny */)
  3493. });
  3494. addButtonIfRegistered('tablepastecolbefore', {
  3495. tooltip: 'Paste column before',
  3496. command: 'mceTablePasteColBefore',
  3497. icon: 'paste-column-before',
  3498. onSetup: selectionTargets.onSetupPasteableColumn(getColumns, "onFirst" /* LockedDisable.onFirst */)
  3499. });
  3500. addButtonIfRegistered('tablepastecolafter', {
  3501. tooltip: 'Paste column after',
  3502. command: 'mceTablePasteColAfter',
  3503. icon: 'paste-column-after',
  3504. onSetup: selectionTargets.onSetupPasteableColumn(getColumns, "onLast" /* LockedDisable.onLast */)
  3505. });
  3506. addButtonIfRegistered('tableinsertdialog', {
  3507. tooltip: 'Insert table',
  3508. command: 'mceInsertTableDialog',
  3509. icon: 'table',
  3510. onSetup: onSetupEditable$1(editor)
  3511. });
  3512. const tableClassList = filterNoneItem(getTableClassList(editor));
  3513. if (tableClassList.length !== 0 && editor.queryCommandSupported('mceTableToggleClass')) {
  3514. editor.ui.registry.addMenuButton('tableclass', {
  3515. icon: 'table-classes',
  3516. tooltip: 'Table styles',
  3517. fetch: generateMenuItemsCallback(editor, tableClassList, 'tableclass', (value) => editor.execCommand('mceTableToggleClass', false, value)),
  3518. onSetup: selectionTargets.onSetupTable
  3519. });
  3520. }
  3521. const tableCellClassList = filterNoneItem(getCellClassList(editor));
  3522. if (tableCellClassList.length !== 0 && editor.queryCommandSupported('mceTableCellToggleClass')) {
  3523. editor.ui.registry.addMenuButton('tablecellclass', {
  3524. icon: 'table-cell-classes',
  3525. tooltip: 'Cell styles',
  3526. fetch: generateMenuItemsCallback(editor, tableCellClassList, 'tablecellclass', (value) => editor.execCommand('mceTableCellToggleClass', false, value)),
  3527. onSetup: selectionTargets.onSetupCellOrRow
  3528. });
  3529. }
  3530. // TODO: TINY-8172 Unwind this when an alternative solution is found
  3531. if (editor.queryCommandSupported('mceTableApplyCellStyle')) {
  3532. editor.ui.registry.addMenuButton('tablecellvalign', {
  3533. icon: 'vertical-align',
  3534. tooltip: 'Vertical align',
  3535. fetch: generateMenuItemsCallback(editor, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
  3536. onSetup: selectionTargets.onSetupCellOrRow
  3537. });
  3538. editor.ui.registry.addMenuButton('tablecellborderwidth', {
  3539. icon: 'border-width',
  3540. tooltip: 'Border width',
  3541. fetch: generateMenuItemsCallback(editor, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
  3542. onSetup: selectionTargets.onSetupCellOrRow
  3543. });
  3544. editor.ui.registry.addMenuButton('tablecellborderstyle', {
  3545. icon: 'border-style',
  3546. tooltip: 'Border style',
  3547. fetch: generateMenuItemsCallback(editor, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
  3548. onSetup: selectionTargets.onSetupCellOrRow
  3549. });
  3550. editor.ui.registry.addMenuButton('tablecellbackgroundcolor', {
  3551. icon: 'cell-background-color',
  3552. tooltip: 'Background color',
  3553. fetch: (callback) => callback(buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color')),
  3554. onSetup: selectionTargets.onSetupCellOrRow
  3555. });
  3556. editor.ui.registry.addMenuButton('tablecellbordercolor', {
  3557. icon: 'cell-border-color',
  3558. tooltip: 'Border color',
  3559. fetch: (callback) => callback(buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color')),
  3560. onSetup: selectionTargets.onSetupCellOrRow
  3561. });
  3562. }
  3563. addToggleButtonIfRegistered('tablecaption', {
  3564. tooltip: 'Table caption',
  3565. icon: 'table-caption',
  3566. command: 'mceTableToggleCaption',
  3567. onSetup: selectionTargets.onSetupTableWithCaption
  3568. });
  3569. addToggleButtonIfRegistered('tablerowheader', {
  3570. tooltip: 'Row header',
  3571. icon: 'table-top-header',
  3572. command: 'mceTableRowType',
  3573. onAction: changeRowHeader(editor),
  3574. onSetup: selectionTargets.onSetupTableRowHeaders
  3575. });
  3576. addToggleButtonIfRegistered('tablecolheader', {
  3577. tooltip: 'Column header',
  3578. icon: 'table-left-header',
  3579. command: 'mceTableColType',
  3580. onAction: changeColumnHeader(editor),
  3581. onSetup: selectionTargets.onSetupTableColumnHeaders
  3582. });
  3583. };
  3584. const addToolbars = (editor) => {
  3585. const isEditableTable = (table) => editor.dom.is(table, 'table') && editor.getBody().contains(table) && editor.dom.isEditable(table.parentNode);
  3586. const toolbar = getToolbar(editor);
  3587. if (toolbar.length > 0) {
  3588. editor.ui.registry.addContextToolbar('table', {
  3589. predicate: isEditableTable,
  3590. items: toolbar,
  3591. scope: 'node',
  3592. position: 'node'
  3593. });
  3594. }
  3595. };
  3596. const onSetupEditable = (editor) => (api) => {
  3597. const nodeChanged = () => {
  3598. api.setEnabled(editor.selection.isEditable());
  3599. };
  3600. editor.on('NodeChange', nodeChanged);
  3601. nodeChanged();
  3602. return () => {
  3603. editor.off('NodeChange', nodeChanged);
  3604. };
  3605. };
  3606. const addMenuItems = (editor, selectionTargets) => {
  3607. const cmd = (command) => () => editor.execCommand(command);
  3608. // TODO: TINY-8172 Unwind this when an alternative solution is found
  3609. const addMenuIfRegistered = (name, spec) => {
  3610. if (editor.queryCommandSupported(spec.command)) {
  3611. editor.ui.registry.addMenuItem(name, {
  3612. ...spec,
  3613. onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
  3614. });
  3615. return true;
  3616. }
  3617. else {
  3618. return false;
  3619. }
  3620. };
  3621. // TODO: TINY-8172 Unwind this when an alternative solution is found
  3622. const addToggleMenuIfRegistered = (name, spec) => {
  3623. if (editor.queryCommandSupported(spec.command)) {
  3624. editor.ui.registry.addToggleMenuItem(name, {
  3625. ...spec,
  3626. onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
  3627. });
  3628. }
  3629. };
  3630. const insertTableAction = (data) => {
  3631. editor.execCommand('mceInsertTable', false, {
  3632. rows: data.numRows,
  3633. columns: data.numColumns
  3634. });
  3635. };
  3636. const hasRowMenuItems = [
  3637. addMenuIfRegistered('tableinsertrowbefore', {
  3638. text: 'Insert row before',
  3639. icon: 'table-insert-row-above',
  3640. command: 'mceTableInsertRowBefore',
  3641. onSetup: selectionTargets.onSetupCellOrRow
  3642. }),
  3643. addMenuIfRegistered('tableinsertrowafter', {
  3644. text: 'Insert row after',
  3645. icon: 'table-insert-row-after',
  3646. command: 'mceTableInsertRowAfter',
  3647. onSetup: selectionTargets.onSetupCellOrRow
  3648. }),
  3649. addMenuIfRegistered('tabledeleterow', {
  3650. text: 'Delete row',
  3651. icon: 'table-delete-row',
  3652. command: 'mceTableDeleteRow',
  3653. onSetup: selectionTargets.onSetupCellOrRow
  3654. }),
  3655. addMenuIfRegistered('tablerowprops', {
  3656. text: 'Row properties',
  3657. icon: 'table-row-properties',
  3658. command: 'mceTableRowProps',
  3659. onSetup: selectionTargets.onSetupCellOrRow
  3660. }),
  3661. addMenuIfRegistered('tablecutrow', {
  3662. text: 'Cut row',
  3663. icon: 'cut-row',
  3664. command: 'mceTableCutRow',
  3665. onSetup: selectionTargets.onSetupCellOrRow
  3666. }),
  3667. addMenuIfRegistered('tablecopyrow', {
  3668. text: 'Copy row',
  3669. icon: 'duplicate-row',
  3670. command: 'mceTableCopyRow',
  3671. onSetup: selectionTargets.onSetupCellOrRow
  3672. }),
  3673. addMenuIfRegistered('tablepasterowbefore', {
  3674. text: 'Paste row before',
  3675. icon: 'paste-row-before',
  3676. command: 'mceTablePasteRowBefore',
  3677. onSetup: selectionTargets.onSetupPasteable(getRows)
  3678. }),
  3679. addMenuIfRegistered('tablepasterowafter', {
  3680. text: 'Paste row after',
  3681. icon: 'paste-row-after',
  3682. command: 'mceTablePasteRowAfter',
  3683. onSetup: selectionTargets.onSetupPasteable(getRows)
  3684. }),
  3685. ];
  3686. const hasColumnMenuItems = [
  3687. addMenuIfRegistered('tableinsertcolumnbefore', {
  3688. text: 'Insert column before',
  3689. icon: 'table-insert-column-before',
  3690. command: 'mceTableInsertColBefore',
  3691. onSetup: selectionTargets.onSetupColumn("onFirst" /* LockedDisable.onFirst */)
  3692. }),
  3693. addMenuIfRegistered('tableinsertcolumnafter', {
  3694. text: 'Insert column after',
  3695. icon: 'table-insert-column-after',
  3696. command: 'mceTableInsertColAfter',
  3697. onSetup: selectionTargets.onSetupColumn("onLast" /* LockedDisable.onLast */)
  3698. }),
  3699. addMenuIfRegistered('tabledeletecolumn', {
  3700. text: 'Delete column',
  3701. icon: 'table-delete-column',
  3702. command: 'mceTableDeleteCol',
  3703. onSetup: selectionTargets.onSetupColumn("onAny" /* LockedDisable.onAny */)
  3704. }),
  3705. addMenuIfRegistered('tablecutcolumn', {
  3706. text: 'Cut column',
  3707. icon: 'cut-column',
  3708. command: 'mceTableCutCol',
  3709. onSetup: selectionTargets.onSetupColumn("onAny" /* LockedDisable.onAny */)
  3710. }),
  3711. addMenuIfRegistered('tablecopycolumn', {
  3712. text: 'Copy column',
  3713. icon: 'duplicate-column',
  3714. command: 'mceTableCopyCol',
  3715. onSetup: selectionTargets.onSetupColumn("onAny" /* LockedDisable.onAny */)
  3716. }),
  3717. addMenuIfRegistered('tablepastecolumnbefore', {
  3718. text: 'Paste column before',
  3719. icon: 'paste-column-before',
  3720. command: 'mceTablePasteColBefore',
  3721. onSetup: selectionTargets.onSetupPasteableColumn(getColumns, "onFirst" /* LockedDisable.onFirst */)
  3722. }),
  3723. addMenuIfRegistered('tablepastecolumnafter', {
  3724. text: 'Paste column after',
  3725. icon: 'paste-column-after',
  3726. command: 'mceTablePasteColAfter',
  3727. onSetup: selectionTargets.onSetupPasteableColumn(getColumns, "onLast" /* LockedDisable.onLast */)
  3728. }),
  3729. ];
  3730. const hasCellMenuItems = [
  3731. addMenuIfRegistered('tablecellprops', {
  3732. text: 'Cell properties',
  3733. icon: 'table-cell-properties',
  3734. command: 'mceTableCellProps',
  3735. onSetup: selectionTargets.onSetupCellOrRow
  3736. }),
  3737. addMenuIfRegistered('tablemergecells', {
  3738. text: 'Merge cells',
  3739. icon: 'table-merge-cells',
  3740. command: 'mceTableMergeCells',
  3741. onSetup: selectionTargets.onSetupMergeable
  3742. }),
  3743. addMenuIfRegistered('tablesplitcells', {
  3744. text: 'Split cell',
  3745. icon: 'table-split-cells',
  3746. command: 'mceTableSplitCells',
  3747. onSetup: selectionTargets.onSetupUnmergeable
  3748. }),
  3749. ];
  3750. if (!hasTableGrid(editor)) {
  3751. editor.ui.registry.addMenuItem('inserttable', {
  3752. text: 'Table',
  3753. icon: 'table',
  3754. onAction: cmd('mceInsertTableDialog'),
  3755. onSetup: onSetupEditable(editor)
  3756. });
  3757. }
  3758. else {
  3759. editor.ui.registry.addNestedMenuItem('inserttable', {
  3760. text: 'Table',
  3761. icon: 'table',
  3762. getSubmenuItems: () => [{ type: 'fancymenuitem', fancytype: 'inserttable', onAction: insertTableAction }],
  3763. onSetup: onSetupEditable(editor)
  3764. });
  3765. }
  3766. // TINY-3636: We want a way to use the dialog even when tablegrid true.
  3767. // If tablegrid false then inserttable and inserttabledialog are the same,
  3768. // but that's preferrable to breaking things at this point.
  3769. editor.ui.registry.addMenuItem('inserttabledialog', {
  3770. text: 'Insert table',
  3771. icon: 'table',
  3772. onAction: cmd('mceInsertTableDialog'),
  3773. onSetup: onSetupEditable(editor)
  3774. });
  3775. addMenuIfRegistered('tableprops', {
  3776. text: 'Table properties',
  3777. onSetup: selectionTargets.onSetupTable,
  3778. command: 'mceTableProps'
  3779. });
  3780. addMenuIfRegistered('deletetable', {
  3781. text: 'Delete table',
  3782. icon: 'table-delete-table',
  3783. onSetup: selectionTargets.onSetupTable,
  3784. command: 'mceTableDelete'
  3785. });
  3786. // if any of the row menu items returned true
  3787. if (contains(hasRowMenuItems, true)) {
  3788. editor.ui.registry.addNestedMenuItem('row', {
  3789. type: 'nestedmenuitem',
  3790. text: 'Row',
  3791. getSubmenuItems: constant('tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter')
  3792. });
  3793. }
  3794. if (contains(hasColumnMenuItems, true)) {
  3795. editor.ui.registry.addNestedMenuItem('column', {
  3796. type: 'nestedmenuitem',
  3797. text: 'Column',
  3798. getSubmenuItems: constant('tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter')
  3799. });
  3800. }
  3801. if (contains(hasCellMenuItems, true)) {
  3802. editor.ui.registry.addNestedMenuItem('cell', {
  3803. type: 'nestedmenuitem',
  3804. text: 'Cell',
  3805. getSubmenuItems: constant('tablecellprops tablemergecells tablesplitcells')
  3806. });
  3807. }
  3808. editor.ui.registry.addContextMenu('table', {
  3809. update: () => {
  3810. // context menu fires before node change, so check the selection here first
  3811. selectionTargets.resetTargets();
  3812. // ignoring element since it's monitored elsewhere
  3813. return selectionTargets.targets().fold(constant(''), (targets) => {
  3814. // If clicking in a caption, then we shouldn't show the cell/row/column options
  3815. if (name(targets.element) === 'caption') {
  3816. return 'tableprops deletetable';
  3817. }
  3818. else {
  3819. return 'cell row column | advtablesort | tableprops deletetable';
  3820. }
  3821. });
  3822. }
  3823. });
  3824. const tableClassList = filterNoneItem(getTableClassList(editor));
  3825. if (tableClassList.length !== 0 && editor.queryCommandSupported('mceTableToggleClass')) {
  3826. editor.ui.registry.addNestedMenuItem('tableclass', {
  3827. icon: 'table-classes',
  3828. text: 'Table styles',
  3829. getSubmenuItems: () => buildMenuItems(editor, tableClassList, 'tableclass', (value) => editor.execCommand('mceTableToggleClass', false, value)),
  3830. onSetup: selectionTargets.onSetupTable
  3831. });
  3832. }
  3833. const tableCellClassList = filterNoneItem(getCellClassList(editor));
  3834. if (tableCellClassList.length !== 0 && editor.queryCommandSupported('mceTableCellToggleClass')) {
  3835. editor.ui.registry.addNestedMenuItem('tablecellclass', {
  3836. icon: 'table-cell-classes',
  3837. text: 'Cell styles',
  3838. getSubmenuItems: () => buildMenuItems(editor, tableCellClassList, 'tablecellclass', (value) => editor.execCommand('mceTableCellToggleClass', false, value)),
  3839. onSetup: selectionTargets.onSetupCellOrRow
  3840. });
  3841. }
  3842. // TODO: TINY-8172 Unwind this when an alternative solution is found
  3843. if (editor.queryCommandSupported('mceTableApplyCellStyle')) {
  3844. editor.ui.registry.addNestedMenuItem('tablecellvalign', {
  3845. icon: 'vertical-align',
  3846. text: 'Vertical align',
  3847. getSubmenuItems: () => buildMenuItems(editor, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
  3848. onSetup: selectionTargets.onSetupCellOrRow
  3849. });
  3850. editor.ui.registry.addNestedMenuItem('tablecellborderwidth', {
  3851. icon: 'border-width',
  3852. text: 'Border width',
  3853. getSubmenuItems: () => buildMenuItems(editor, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
  3854. onSetup: selectionTargets.onSetupCellOrRow
  3855. });
  3856. editor.ui.registry.addNestedMenuItem('tablecellborderstyle', {
  3857. icon: 'border-style',
  3858. text: 'Border style',
  3859. getSubmenuItems: () => buildMenuItems(editor, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
  3860. onSetup: selectionTargets.onSetupCellOrRow
  3861. });
  3862. editor.ui.registry.addNestedMenuItem('tablecellbackgroundcolor', {
  3863. icon: 'cell-background-color',
  3864. text: 'Background color',
  3865. getSubmenuItems: () => buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color'),
  3866. onSetup: selectionTargets.onSetupCellOrRow
  3867. });
  3868. editor.ui.registry.addNestedMenuItem('tablecellbordercolor', {
  3869. icon: 'cell-border-color',
  3870. text: 'Border color',
  3871. getSubmenuItems: () => buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color'),
  3872. onSetup: selectionTargets.onSetupCellOrRow
  3873. });
  3874. }
  3875. addToggleMenuIfRegistered('tablecaption', {
  3876. icon: 'table-caption',
  3877. text: 'Table caption',
  3878. command: 'mceTableToggleCaption',
  3879. onSetup: selectionTargets.onSetupTableWithCaption
  3880. });
  3881. addToggleMenuIfRegistered('tablerowheader', {
  3882. text: 'Row header',
  3883. icon: 'table-top-header',
  3884. command: 'mceTableRowType',
  3885. onAction: changeRowHeader(editor),
  3886. onSetup: selectionTargets.onSetupTableRowHeaders
  3887. });
  3888. addToggleMenuIfRegistered('tablecolheader', {
  3889. text: 'Column header',
  3890. icon: 'table-left-header',
  3891. command: 'mceTableColType',
  3892. onAction: changeColumnHeader(editor),
  3893. onSetup: selectionTargets.onSetupTableRowHeaders
  3894. });
  3895. };
  3896. const Plugin = (editor) => {
  3897. const selectionTargets = getSelectionTargets(editor);
  3898. register(editor);
  3899. registerCommands(editor);
  3900. addMenuItems(editor, selectionTargets);
  3901. addButtons(editor, selectionTargets);
  3902. addToolbars(editor);
  3903. };
  3904. var Plugin$1 = () => {
  3905. global$3.add('table', Plugin);
  3906. };
  3907. Plugin$1();
  3908. /** *****
  3909. * DO NOT EXPORT ANYTHING
  3910. *
  3911. * IF YOU DO ROLLUP WILL LEAVE A GLOBAL ON THE PAGE
  3912. *******/
  3913. })();