plugin.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  1. /**
  2. * TinyMCE version 8.0.2 (2025-08-14)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global$4 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  7. /* eslint-disable @typescript-eslint/no-wrapper-object-types */
  8. const getPrototypeOf = Object.getPrototypeOf;
  9. const hasProto = (v, constructor, predicate) => {
  10. var _a;
  11. if (predicate(v, constructor.prototype)) {
  12. return true;
  13. }
  14. else {
  15. // String-based fallback time
  16. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  17. }
  18. };
  19. const typeOf = (x) => {
  20. const t = typeof x;
  21. if (x === null) {
  22. return 'null';
  23. }
  24. else if (t === 'object' && Array.isArray(x)) {
  25. return 'array';
  26. }
  27. else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  28. return 'string';
  29. }
  30. else {
  31. return t;
  32. }
  33. };
  34. const isType = (type) => (value) => typeOf(value) === type;
  35. const isSimpleType = (type) => (value) => typeof value === type;
  36. const eq = (t) => (a) => t === a;
  37. const is = (value, constructor) => isObject(value) && hasProto(value, constructor, (o, proto) => getPrototypeOf(o) === proto);
  38. const isString = isType('string');
  39. const isObject = isType('object');
  40. const isPlainObject = (value) => is(value, Object);
  41. const isArray = isType('array');
  42. const isNull = eq(null);
  43. const isBoolean = isSimpleType('boolean');
  44. const isNullable = (a) => a === null || a === undefined;
  45. const isNonNullable = (a) => !isNullable(a);
  46. const isFunction = isSimpleType('function');
  47. const isNumber = isSimpleType('number');
  48. const isArrayOf = (value, pred) => {
  49. if (isArray(value)) {
  50. for (let i = 0, len = value.length; i < len; ++i) {
  51. if (!(pred(value[i]))) {
  52. return false;
  53. }
  54. }
  55. return true;
  56. }
  57. return false;
  58. };
  59. const noop = () => { };
  60. /**
  61. * The `Optional` type represents a value (of any type) that potentially does
  62. * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the
  63. * value does exist) or a `None` (in which case the value does not exist). This
  64. * module defines a whole lot of FP-inspired utility functions for dealing with
  65. * `Optional` objects.
  66. *
  67. * Comparison with null or undefined:
  68. * - We don't get fancy null coalescing operators with `Optional`
  69. * - We do get fancy helper functions with `Optional`
  70. * - `Optional` support nesting, and allow for the type to still be nullable (or
  71. * another `Optional`)
  72. * - There is no option to turn off strict-optional-checks like there is for
  73. * strict-null-checks
  74. */
  75. class Optional {
  76. // The internal representation has a `tag` and a `value`, but both are
  77. // private: able to be console.logged, but not able to be accessed by code
  78. constructor(tag, value) {
  79. this.tag = tag;
  80. this.value = value;
  81. }
  82. // --- Identities ---
  83. /**
  84. * Creates a new `Optional<T>` that **does** contain a value.
  85. */
  86. static some(value) {
  87. return new Optional(true, value);
  88. }
  89. /**
  90. * Create a new `Optional<T>` that **does not** contain a value. `T` can be
  91. * any type because we don't actually have a `T`.
  92. */
  93. static none() {
  94. return Optional.singletonNone;
  95. }
  96. /**
  97. * Perform a transform on an `Optional` type. Regardless of whether this
  98. * `Optional` contains a value or not, `fold` will return a value of type `U`.
  99. * If this `Optional` does not contain a value, the `U` will be created by
  100. * calling `onNone`. If this `Optional` does contain a value, the `U` will be
  101. * created by calling `onSome`.
  102. *
  103. * For the FP enthusiasts in the room, this function:
  104. * 1. Could be used to implement all of the functions below
  105. * 2. Forms a catamorphism
  106. */
  107. fold(onNone, onSome) {
  108. if (this.tag) {
  109. return onSome(this.value);
  110. }
  111. else {
  112. return onNone();
  113. }
  114. }
  115. /**
  116. * Determine if this `Optional` object contains a value.
  117. */
  118. isSome() {
  119. return this.tag;
  120. }
  121. /**
  122. * Determine if this `Optional` object **does not** contain a value.
  123. */
  124. isNone() {
  125. return !this.tag;
  126. }
  127. // --- Functor (name stolen from Haskell / maths) ---
  128. /**
  129. * Perform a transform on an `Optional` object, **if** there is a value. If
  130. * you provide a function to turn a T into a U, this is the function you use
  131. * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain
  132. * a value then the output will also contain a value (that value being the
  133. * output of `mapper(this.value)`), and if this **does not** contain a value
  134. * then neither will the output.
  135. */
  136. map(mapper) {
  137. if (this.tag) {
  138. return Optional.some(mapper(this.value));
  139. }
  140. else {
  141. return Optional.none();
  142. }
  143. }
  144. // --- Monad (name stolen from Haskell / maths) ---
  145. /**
  146. * Perform a transform on an `Optional` object, **if** there is a value.
  147. * Unlike `map`, here the transform itself also returns an `Optional`.
  148. */
  149. bind(binder) {
  150. if (this.tag) {
  151. return binder(this.value);
  152. }
  153. else {
  154. return Optional.none();
  155. }
  156. }
  157. // --- Traversable (name stolen from Haskell / maths) ---
  158. /**
  159. * For a given predicate, this function finds out if there **exists** a value
  160. * inside this `Optional` object that meets the predicate. In practice, this
  161. * means that for `Optional`s that do not contain a value it returns false (as
  162. * no predicate-meeting value exists).
  163. */
  164. exists(predicate) {
  165. return this.tag && predicate(this.value);
  166. }
  167. /**
  168. * For a given predicate, this function finds out if **all** the values inside
  169. * this `Optional` object meet the predicate. In practice, this means that
  170. * for `Optional`s that do not contain a value it returns true (as all 0
  171. * objects do meet the predicate).
  172. */
  173. forall(predicate) {
  174. return !this.tag || predicate(this.value);
  175. }
  176. filter(predicate) {
  177. if (!this.tag || predicate(this.value)) {
  178. return this;
  179. }
  180. else {
  181. return Optional.none();
  182. }
  183. }
  184. // --- Getters ---
  185. /**
  186. * Get the value out of the inside of the `Optional` object, using a default
  187. * `replacement` value if the provided `Optional` object does not contain a
  188. * value.
  189. */
  190. getOr(replacement) {
  191. return this.tag ? this.value : replacement;
  192. }
  193. /**
  194. * Get the value out of the inside of the `Optional` object, using a default
  195. * `replacement` value if the provided `Optional` object does not contain a
  196. * value. Unlike `getOr`, in this method the `replacement` object is also
  197. * `Optional` - meaning that this method will always return an `Optional`.
  198. */
  199. or(replacement) {
  200. return this.tag ? this : 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` value is
  206. * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you
  207. * pass a function which (if called) will **return** the `value` you want to
  208. * use.
  209. */
  210. getOrThunk(thunk) {
  211. return this.tag ? this.value : thunk();
  212. }
  213. /**
  214. * Get the value out of the inside of the `Optional` object, using a default
  215. * `replacement` value if the provided Optional object does not contain a
  216. * value.
  217. *
  218. * Unlike `or`, in this method the `replacement` value is "thunked" - that is
  219. * to say that you don't pass a value to `orThunk`, you pass a function which
  220. * (if called) will **return** the `value` you want to use.
  221. *
  222. * Unlike `getOrThunk`, in this method the `replacement` value is also
  223. * `Optional`, meaning that this method will always return an `Optional`.
  224. */
  225. orThunk(thunk) {
  226. return this.tag ? this : thunk();
  227. }
  228. /**
  229. * Get the value out of the inside of the `Optional` object, throwing an
  230. * exception if the provided `Optional` object does not contain a value.
  231. *
  232. * WARNING:
  233. * You should only be using this function if you know that the `Optional`
  234. * object **is not** empty (otherwise you're throwing exceptions in production
  235. * code, which is bad).
  236. *
  237. * In tests this is more acceptable.
  238. *
  239. * Prefer other methods to this, such as `.each`.
  240. */
  241. getOrDie(message) {
  242. if (!this.tag) {
  243. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  244. }
  245. else {
  246. return this.value;
  247. }
  248. }
  249. // --- Interop with null and undefined ---
  250. /**
  251. * Creates an `Optional` value from a nullable (or undefined-able) input.
  252. * Null, or undefined, is converted to `None`, and anything else is converted
  253. * to `Some`.
  254. */
  255. static from(value) {
  256. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  257. }
  258. /**
  259. * Converts an `Optional` to a nullable type, by getting the value if it
  260. * exists, or returning `null` if it does not.
  261. */
  262. getOrNull() {
  263. return this.tag ? this.value : null;
  264. }
  265. /**
  266. * Converts an `Optional` to an undefined-able type, by getting the value if
  267. * it exists, or returning `undefined` if it does not.
  268. */
  269. getOrUndefined() {
  270. return this.value;
  271. }
  272. // --- Utilities ---
  273. /**
  274. * If the `Optional` contains a value, perform an action on that value.
  275. * Unlike the rest of the methods on this type, `.each` has side-effects. If
  276. * you want to transform an `Optional<T>` **into** something, then this is not
  277. * the method for you. If you want to use an `Optional<T>` to **do**
  278. * something, then this is the method for you - provided you're okay with not
  279. * doing anything in the case where the `Optional` doesn't have a value inside
  280. * it. If you're not sure whether your use-case fits into transforming
  281. * **into** something or **doing** something, check whether it has a return
  282. * value. If it does, you should be performing a transform.
  283. */
  284. each(worker) {
  285. if (this.tag) {
  286. worker(this.value);
  287. }
  288. }
  289. /**
  290. * Turn the `Optional` object into an array that contains all of the values
  291. * stored inside the `Optional`. In practice, this means the output will have
  292. * either 0 or 1 elements.
  293. */
  294. toArray() {
  295. return this.tag ? [this.value] : [];
  296. }
  297. /**
  298. * Turn the `Optional` object into a string for debugging or printing. Not
  299. * recommended for production code, but good for debugging. Also note that
  300. * these days an `Optional` object can be logged to the console directly, and
  301. * its inner value (if it exists) will be visible.
  302. */
  303. toString() {
  304. return this.tag ? `some(${this.value})` : 'none()';
  305. }
  306. }
  307. // Sneaky optimisation: every instance of Optional.none is identical, so just
  308. // reuse the same object
  309. Optional.singletonNone = new Optional(false);
  310. const nativeSlice = Array.prototype.slice;
  311. const nativePush = Array.prototype.push;
  312. const flatten = (xs) => {
  313. // Note, this is possible because push supports multiple arguments:
  314. // http://jsperf.com/concat-push/6
  315. // Note that in the past, concat() would silently work (very slowly) for array-like objects.
  316. // With this change it will throw an error.
  317. const r = [];
  318. for (let i = 0, len = xs.length; i < len; ++i) {
  319. // Ensure that each value is an array itself
  320. if (!isArray(xs[i])) {
  321. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  322. }
  323. nativePush.apply(r, xs[i]);
  324. }
  325. return r;
  326. };
  327. const get = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  328. const head = (xs) => get(xs, 0);
  329. isFunction(Array.from) ? Array.from : (x) => nativeSlice.call(x);
  330. const findMap = (arr, f) => {
  331. for (let i = 0; i < arr.length; i++) {
  332. const r = f(arr[i], i);
  333. if (r.isSome()) {
  334. return r;
  335. }
  336. }
  337. return Optional.none();
  338. };
  339. // There are many variations of Object iteration that are faster than the 'for-in' style:
  340. // http://jsperf.com/object-keys-iteration/107
  341. //
  342. // Use the native keys if it is available (IE9+), otherwise fall back to manually filtering
  343. const keys = Object.keys;
  344. const hasOwnProperty = Object.hasOwnProperty;
  345. const each = (obj, f) => {
  346. const props = keys(obj);
  347. for (let k = 0, len = props.length; k < len; k++) {
  348. const i = props[k];
  349. const x = obj[i];
  350. f(x, i);
  351. }
  352. };
  353. const objAcc = (r) => (x, i) => {
  354. r[i] = x;
  355. };
  356. const internalFilter = (obj, pred, onTrue, onFalse) => {
  357. each(obj, (x, i) => {
  358. (pred(x, i) ? onTrue : onFalse)(x, i);
  359. });
  360. };
  361. const filter = (obj, pred) => {
  362. const t = {};
  363. internalFilter(obj, pred, objAcc(t), noop);
  364. return t;
  365. };
  366. const has = (obj, key) => hasOwnProperty.call(obj, key);
  367. const hasNonNullableKey = (obj, key) => has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  368. const deep = (old, nu) => {
  369. const bothObjects = isPlainObject(old) && isPlainObject(nu);
  370. return bothObjects ? deepMerge(old, nu) : nu;
  371. };
  372. const baseMerge = (merger) => {
  373. return (...objects) => {
  374. if (objects.length === 0) {
  375. throw new Error(`Can't merge zero objects`);
  376. }
  377. const ret = {};
  378. for (let j = 0; j < objects.length; j++) {
  379. const curObject = objects[j];
  380. for (const key in curObject) {
  381. if (has(curObject, key)) {
  382. ret[key] = merger(ret[key], curObject[key]);
  383. }
  384. }
  385. }
  386. return ret;
  387. };
  388. };
  389. const deepMerge = baseMerge(deep);
  390. const isNotEmpty = (s) => s.length > 0;
  391. const fromHtml = (html, scope) => {
  392. const doc = scope || document;
  393. const div = doc.createElement('div');
  394. div.innerHTML = html;
  395. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  396. const message = 'HTML does not have a single root node';
  397. // eslint-disable-next-line no-console
  398. console.error(message, html);
  399. throw new Error(message);
  400. }
  401. return fromDom(div.childNodes[0]);
  402. };
  403. const fromTag = (tag, scope) => {
  404. const doc = scope || document;
  405. const node = doc.createElement(tag);
  406. return fromDom(node);
  407. };
  408. const fromText = (text, scope) => {
  409. const doc = scope || document;
  410. const node = doc.createTextNode(text);
  411. return fromDom(node);
  412. };
  413. const fromDom = (node) => {
  414. // TODO: Consider removing this check, but left atm for safety
  415. if (node === null || node === undefined) {
  416. throw new Error('Node cannot be null or undefined');
  417. }
  418. return {
  419. dom: node
  420. };
  421. };
  422. const fromPoint = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  423. // tslint:disable-next-line:variable-name
  424. const SugarElement = {
  425. fromHtml,
  426. fromTag,
  427. fromText,
  428. fromDom,
  429. fromPoint
  430. };
  431. const rawSet = (dom, key, value) => {
  432. /*
  433. * JQuery coerced everything to a string, and silently did nothing on text node/null/undefined.
  434. *
  435. * We fail on those invalid cases, only allowing numbers and booleans.
  436. */
  437. if (isString(value) || isBoolean(value) || isNumber(value)) {
  438. dom.setAttribute(key, value + '');
  439. }
  440. else {
  441. // eslint-disable-next-line no-console
  442. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  443. throw new Error('Attribute value was not simple');
  444. }
  445. };
  446. const set = (element, key, value) => {
  447. rawSet(element.dom, key, value);
  448. };
  449. const remove = (element, key) => {
  450. element.dom.removeAttribute(key);
  451. };
  452. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  453. var global$2 = tinymce.util.Tools.resolve('tinymce.util.URI');
  454. const option = (name) => (editor) => editor.options.get(name);
  455. const register$2 = (editor) => {
  456. const registerOption = editor.options.register;
  457. registerOption('image_dimensions', {
  458. processor: 'boolean',
  459. default: true
  460. });
  461. registerOption('image_advtab', {
  462. processor: 'boolean',
  463. default: false
  464. });
  465. registerOption('image_uploadtab', {
  466. processor: 'boolean',
  467. default: true
  468. });
  469. registerOption('image_prepend_url', {
  470. processor: 'string',
  471. default: ''
  472. });
  473. registerOption('image_class_list', {
  474. processor: 'object[]'
  475. });
  476. registerOption('image_description', {
  477. processor: 'boolean',
  478. default: true
  479. });
  480. registerOption('image_title', {
  481. processor: 'boolean',
  482. default: false
  483. });
  484. registerOption('image_caption', {
  485. processor: 'boolean',
  486. default: false
  487. });
  488. registerOption('image_list', {
  489. processor: (value) => {
  490. const valid = value === false || isString(value) || isArrayOf(value, isObject) || isFunction(value);
  491. return valid ? { value, valid } : { valid: false, message: 'Must be false, a string, an array or a function.' };
  492. },
  493. default: false
  494. });
  495. };
  496. const hasDimensions = option('image_dimensions');
  497. const hasAdvTab = option('image_advtab');
  498. const hasUploadTab = option('image_uploadtab');
  499. const getPrependUrl = option('image_prepend_url');
  500. const getClassList = option('image_class_list');
  501. const hasDescription = option('image_description');
  502. const hasImageTitle = option('image_title');
  503. const hasImageCaption = option('image_caption');
  504. const getImageList = option('image_list');
  505. const showAccessibilityOptions = option('a11y_advanced_options');
  506. const isAutomaticUploadsEnabled = option('automatic_uploads');
  507. const hasUploadUrl = (editor) => isNotEmpty(editor.options.get('images_upload_url'));
  508. const hasUploadHandler = (editor) => isNonNullable(editor.options.get('images_upload_handler'));
  509. // TODO: Figure out if these would ever be something other than numbers. This was added in: #TINY-1350
  510. const parseIntAndGetMax = (val1, val2) => Math.max(parseInt(val1, 10), parseInt(val2, 10));
  511. const getImageSize = (url) => new Promise((callback) => {
  512. const img = document.createElement('img');
  513. const done = (dimensions) => {
  514. if (img.parentNode) {
  515. img.parentNode.removeChild(img);
  516. }
  517. callback(dimensions);
  518. };
  519. img.addEventListener('load', () => {
  520. const width = parseIntAndGetMax(img.width, img.clientWidth);
  521. const height = parseIntAndGetMax(img.height, img.clientHeight);
  522. const dimensions = { width, height };
  523. done(Promise.resolve(dimensions));
  524. });
  525. img.addEventListener('error', () => {
  526. done(Promise.reject(`Failed to get image dimensions for: ${url}`));
  527. });
  528. const style = img.style;
  529. style.visibility = 'hidden';
  530. style.position = 'fixed';
  531. style.bottom = style.left = '0px';
  532. style.width = style.height = 'auto';
  533. document.body.appendChild(img);
  534. img.src = url;
  535. });
  536. const removePixelSuffix = (value) => {
  537. if (value) {
  538. value = value.replace(/px$/, '');
  539. }
  540. return value;
  541. };
  542. const addPixelSuffix = (value) => {
  543. if (value.length > 0 && /^[0-9]+$/.test(value)) {
  544. value += 'px';
  545. }
  546. return value;
  547. };
  548. const mergeMargins = (css) => {
  549. if (css.margin) {
  550. const splitMargin = String(css.margin).split(' ');
  551. switch (splitMargin.length) {
  552. case 1: // margin: toprightbottomleft;
  553. css['margin-top'] = css['margin-top'] || splitMargin[0];
  554. css['margin-right'] = css['margin-right'] || splitMargin[0];
  555. css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
  556. css['margin-left'] = css['margin-left'] || splitMargin[0];
  557. break;
  558. case 2: // margin: topbottom rightleft;
  559. css['margin-top'] = css['margin-top'] || splitMargin[0];
  560. css['margin-right'] = css['margin-right'] || splitMargin[1];
  561. css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
  562. css['margin-left'] = css['margin-left'] || splitMargin[1];
  563. break;
  564. case 3: // margin: top rightleft bottom;
  565. css['margin-top'] = css['margin-top'] || splitMargin[0];
  566. css['margin-right'] = css['margin-right'] || splitMargin[1];
  567. css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
  568. css['margin-left'] = css['margin-left'] || splitMargin[1];
  569. break;
  570. case 4: // margin: top right bottom left;
  571. css['margin-top'] = css['margin-top'] || splitMargin[0];
  572. css['margin-right'] = css['margin-right'] || splitMargin[1];
  573. css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
  574. css['margin-left'] = css['margin-left'] || splitMargin[3];
  575. }
  576. delete css.margin;
  577. }
  578. return css;
  579. };
  580. // TODO: Input on this callback should really be validated
  581. const createImageList = (editor, callback) => {
  582. const imageList = getImageList(editor);
  583. if (isString(imageList)) {
  584. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  585. fetch(imageList)
  586. .then((res) => {
  587. if (res.ok) {
  588. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  589. res.json().then(callback);
  590. }
  591. });
  592. }
  593. else if (isFunction(imageList)) {
  594. imageList(callback);
  595. }
  596. else {
  597. callback(imageList);
  598. }
  599. };
  600. const waitLoadImage = (editor, data, imgElm) => {
  601. const selectImage = () => {
  602. imgElm.onload = imgElm.onerror = null;
  603. if (editor.selection) {
  604. editor.selection.select(imgElm);
  605. editor.nodeChanged();
  606. }
  607. };
  608. imgElm.onload = () => {
  609. if (!data.width && !data.height && hasDimensions(editor)) {
  610. editor.dom.setAttribs(imgElm, {
  611. width: String(imgElm.clientWidth),
  612. height: String(imgElm.clientHeight)
  613. });
  614. }
  615. selectImage();
  616. };
  617. imgElm.onerror = selectImage;
  618. };
  619. const blobToDataUri = (blob) => new Promise((resolve, reject) => {
  620. const reader = new FileReader();
  621. reader.onload = () => {
  622. resolve(reader.result);
  623. };
  624. reader.onerror = () => {
  625. var _a;
  626. reject((_a = reader.error) === null || _a === void 0 ? void 0 : _a.message);
  627. };
  628. reader.readAsDataURL(blob);
  629. });
  630. const isPlaceholderImage = (imgElm) => imgElm.nodeName === 'IMG' && (imgElm.hasAttribute('data-mce-object') || imgElm.hasAttribute('data-mce-placeholder'));
  631. const isSafeImageUrl = (editor, src) => {
  632. const getOption = editor.options.get;
  633. return global$2.isDomSafe(src, 'img', {
  634. allow_html_data_urls: getOption('allow_html_data_urls'),
  635. allow_script_urls: getOption('allow_script_urls'),
  636. allow_svg_data_urls: getOption('allow_svg_data_urls')
  637. });
  638. };
  639. const DOM = global$3.DOM;
  640. const getHspace = (image) => {
  641. if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) {
  642. return removePixelSuffix(image.style.marginLeft);
  643. }
  644. else {
  645. return '';
  646. }
  647. };
  648. const getVspace = (image) => {
  649. if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) {
  650. return removePixelSuffix(image.style.marginTop);
  651. }
  652. else {
  653. return '';
  654. }
  655. };
  656. const getBorder = (image) => {
  657. if (image.style.borderWidth) {
  658. return removePixelSuffix(image.style.borderWidth);
  659. }
  660. else {
  661. return '';
  662. }
  663. };
  664. const getAttrib = (image, name) => {
  665. var _a;
  666. if (image.hasAttribute(name)) {
  667. return (_a = image.getAttribute(name)) !== null && _a !== void 0 ? _a : '';
  668. }
  669. else {
  670. return '';
  671. }
  672. };
  673. const hasCaption = (image) => image.parentNode !== null && image.parentNode.nodeName === 'FIGURE';
  674. const updateAttrib = (image, name, value) => {
  675. if (value === '' || value === null) {
  676. image.removeAttribute(name);
  677. }
  678. else {
  679. image.setAttribute(name, value);
  680. }
  681. };
  682. const wrapInFigure = (image) => {
  683. const figureElm = DOM.create('figure', { class: 'image' });
  684. DOM.insertAfter(figureElm, image);
  685. figureElm.appendChild(image);
  686. figureElm.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption'));
  687. figureElm.contentEditable = 'false';
  688. };
  689. const removeFigure = (image) => {
  690. const figureElm = image.parentNode;
  691. if (isNonNullable(figureElm)) {
  692. DOM.insertAfter(image, figureElm);
  693. DOM.remove(figureElm);
  694. }
  695. };
  696. const toggleCaption = (image) => {
  697. if (hasCaption(image)) {
  698. removeFigure(image);
  699. }
  700. else {
  701. wrapInFigure(image);
  702. }
  703. };
  704. const normalizeStyle = (image, normalizeCss) => {
  705. const attrValue = image.getAttribute('style');
  706. const value = normalizeCss(attrValue !== null ? attrValue : '');
  707. if (value.length > 0) {
  708. image.setAttribute('style', value);
  709. image.setAttribute('data-mce-style', value);
  710. }
  711. else {
  712. image.removeAttribute('style');
  713. }
  714. };
  715. const setSize = (name, normalizeCss) => (image, name, value) => {
  716. const styles = image.style;
  717. if (styles[name]) {
  718. styles[name] = addPixelSuffix(value);
  719. normalizeStyle(image, normalizeCss);
  720. }
  721. else {
  722. updateAttrib(image, name, value);
  723. }
  724. };
  725. const getSize = (image, name) => {
  726. if (image.style[name]) {
  727. return removePixelSuffix(image.style[name]);
  728. }
  729. else {
  730. return getAttrib(image, name);
  731. }
  732. };
  733. const setHspace = (image, value) => {
  734. const pxValue = addPixelSuffix(value);
  735. image.style.marginLeft = pxValue;
  736. image.style.marginRight = pxValue;
  737. };
  738. const setVspace = (image, value) => {
  739. const pxValue = addPixelSuffix(value);
  740. image.style.marginTop = pxValue;
  741. image.style.marginBottom = pxValue;
  742. };
  743. const setBorder = (image, value) => {
  744. const pxValue = addPixelSuffix(value);
  745. image.style.borderWidth = pxValue;
  746. };
  747. const setBorderStyle = (image, value) => {
  748. image.style.borderStyle = value;
  749. };
  750. const getBorderStyle = (image) => { var _a; return (_a = image.style.borderStyle) !== null && _a !== void 0 ? _a : ''; };
  751. const isFigure = (elm) => isNonNullable(elm) && elm.nodeName === 'FIGURE';
  752. const isImage = (elm) => elm.nodeName === 'IMG';
  753. const getIsDecorative = (image) => {
  754. const alt = DOM.getAttrib(image, 'alt');
  755. const role = DOM.getAttrib(image, 'role');
  756. // WCAG Technique H67: Using null alt text and no title attribute on img elements for images that AT should ignore
  757. // Source: https://www.w3.org/TR/WCAG20-TECHS/H67.html
  758. // Key point: Decorative images should have alt="" and either no title or empty title (title="")
  759. // ARIA 1.2 Specification: Defines role="presentation" and role="none" as synonymous roles
  760. // Source: https://www.w3.org/TR/wai-aria-1.2/
  761. // Key point: These roles remove semantic meaning and prohibit aria-label and aria-labelledby
  762. const hasAlt = image.hasAttribute('alt');
  763. return (hasAlt && alt.length === 0) || (role === 'presentation') || (role === 'none');
  764. };
  765. const getAlt = (image) => {
  766. if (getIsDecorative(image)) {
  767. return '';
  768. }
  769. else {
  770. return getAttrib(image, 'alt');
  771. }
  772. };
  773. const defaultData = () => ({
  774. src: '',
  775. alt: '',
  776. title: '',
  777. width: '',
  778. height: '',
  779. class: '',
  780. style: '',
  781. caption: false,
  782. hspace: '',
  783. vspace: '',
  784. border: '',
  785. borderStyle: '',
  786. isDecorative: false
  787. });
  788. const getStyleValue = (normalizeCss, data) => {
  789. var _a;
  790. const image = document.createElement('img');
  791. updateAttrib(image, 'style', data.style);
  792. if (getHspace(image) || data.hspace !== '') {
  793. setHspace(image, data.hspace);
  794. }
  795. if (getVspace(image) || data.vspace !== '') {
  796. setVspace(image, data.vspace);
  797. }
  798. if (getBorder(image) || data.border !== '') {
  799. setBorder(image, data.border);
  800. }
  801. if (getBorderStyle(image) || data.borderStyle !== '') {
  802. setBorderStyle(image, data.borderStyle);
  803. }
  804. return normalizeCss((_a = image.getAttribute('style')) !== null && _a !== void 0 ? _a : '');
  805. };
  806. const create = (normalizeCss, data) => {
  807. const image = document.createElement('img');
  808. write(normalizeCss, { ...data, caption: false }, image);
  809. // Always set alt even if data.alt is an empty string
  810. setAlt(image, data.alt, data.isDecorative);
  811. if (data.caption) {
  812. const figure = DOM.create('figure', { class: 'image' });
  813. figure.appendChild(image);
  814. figure.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption'));
  815. figure.contentEditable = 'false';
  816. return figure;
  817. }
  818. else {
  819. return image;
  820. }
  821. };
  822. const read = (normalizeCss, image) => ({
  823. src: getAttrib(image, 'src'),
  824. alt: getAlt(image),
  825. title: getAttrib(image, 'title'),
  826. width: getSize(image, 'width'),
  827. height: getSize(image, 'height'),
  828. class: getAttrib(image, 'class'),
  829. style: normalizeCss(getAttrib(image, 'style')),
  830. caption: hasCaption(image),
  831. hspace: getHspace(image),
  832. vspace: getVspace(image),
  833. border: getBorder(image),
  834. borderStyle: getBorderStyle(image),
  835. isDecorative: getIsDecorative(image)
  836. });
  837. const updateProp = (image, oldData, newData, name, set) => {
  838. if (newData[name] !== oldData[name]) {
  839. set(image, name, String(newData[name]));
  840. }
  841. };
  842. const setAlt = (image, alt, isDecorative) => {
  843. if (isDecorative) {
  844. DOM.setAttrib(image, 'role', 'presentation');
  845. // unfortunately can't set "" attr value with domutils
  846. const sugarImage = SugarElement.fromDom(image);
  847. set(sugarImage, 'alt', '');
  848. }
  849. else {
  850. if (isNull(alt)) {
  851. const sugarImage = SugarElement.fromDom(image);
  852. remove(sugarImage, 'alt');
  853. }
  854. else {
  855. // unfortunately can't set "" attr value with domutils
  856. const sugarImage = SugarElement.fromDom(image);
  857. set(sugarImage, 'alt', alt);
  858. }
  859. if (DOM.getAttrib(image, 'role') === 'presentation') {
  860. DOM.setAttrib(image, 'role', '');
  861. }
  862. }
  863. };
  864. const updateAlt = (image, oldData, newData) => {
  865. if (newData.alt !== oldData.alt || newData.isDecorative !== oldData.isDecorative) {
  866. setAlt(image, newData.alt, newData.isDecorative);
  867. }
  868. };
  869. const normalized = (set, normalizeCss) => (image, name, value) => {
  870. set(image, value);
  871. normalizeStyle(image, normalizeCss);
  872. };
  873. const write = (normalizeCss, newData, image) => {
  874. const oldData = read(normalizeCss, image);
  875. updateProp(image, oldData, newData, 'caption', (image, _name, _value) => toggleCaption(image));
  876. updateProp(image, oldData, newData, 'src', updateAttrib);
  877. updateProp(image, oldData, newData, 'title', updateAttrib);
  878. updateProp(image, oldData, newData, 'width', setSize('width', normalizeCss));
  879. updateProp(image, oldData, newData, 'height', setSize('height', normalizeCss));
  880. updateProp(image, oldData, newData, 'class', updateAttrib);
  881. updateProp(image, oldData, newData, 'style', normalized((image, value) => updateAttrib(image, 'style', value), normalizeCss));
  882. updateProp(image, oldData, newData, 'hspace', normalized(setHspace, normalizeCss));
  883. updateProp(image, oldData, newData, 'vspace', normalized(setVspace, normalizeCss));
  884. updateProp(image, oldData, newData, 'border', normalized(setBorder, normalizeCss));
  885. updateProp(image, oldData, newData, 'borderStyle', normalized(setBorderStyle, normalizeCss));
  886. updateAlt(image, oldData, newData);
  887. };
  888. const normalizeCss$1 = (editor, cssText) => {
  889. const css = editor.dom.styles.parse(cssText);
  890. const mergedCss = mergeMargins(css);
  891. const compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss));
  892. return editor.dom.styles.serialize(compressed);
  893. };
  894. const getSelectedImage = (editor) => {
  895. const imgElm = editor.selection.getNode();
  896. const figureElm = editor.dom.getParent(imgElm, 'figure.image');
  897. if (figureElm) {
  898. return editor.dom.select('img', figureElm)[0];
  899. }
  900. if (imgElm && (imgElm.nodeName !== 'IMG' || isPlaceholderImage(imgElm))) {
  901. return null;
  902. }
  903. return imgElm;
  904. };
  905. const splitTextBlock = (editor, figure) => {
  906. var _a;
  907. const dom = editor.dom;
  908. const textBlockElements = filter(editor.schema.getTextBlockElements(), (_, parentElm) => !editor.schema.isValidChild(parentElm, 'figure'));
  909. const textBlock = dom.getParent(figure.parentNode, (node) => hasNonNullableKey(textBlockElements, node.nodeName), editor.getBody());
  910. if (textBlock) {
  911. return (_a = dom.split(textBlock, figure)) !== null && _a !== void 0 ? _a : figure;
  912. }
  913. else {
  914. return figure;
  915. }
  916. };
  917. const readImageDataFromSelection = (editor) => {
  918. const image = getSelectedImage(editor);
  919. return image ? read((css) => normalizeCss$1(editor, css), image) : defaultData();
  920. };
  921. const insertImageAtCaret = (editor, data) => {
  922. const elm = create((css) => normalizeCss$1(editor, css), data);
  923. editor.dom.setAttrib(elm, 'data-mce-id', '__mcenew');
  924. editor.focus();
  925. editor.insertContent(elm.outerHTML);
  926. const insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0];
  927. editor.dom.setAttrib(insertedElm, 'data-mce-id', null);
  928. if (isFigure(insertedElm)) {
  929. const figure = splitTextBlock(editor, insertedElm);
  930. editor.selection.select(figure);
  931. }
  932. else {
  933. editor.selection.select(insertedElm);
  934. }
  935. };
  936. const syncSrcAttr = (editor, image) => {
  937. editor.dom.setAttrib(image, 'src', image.getAttribute('src'));
  938. };
  939. const deleteImage = (editor, image) => {
  940. if (image) {
  941. const elm = editor.dom.is(image.parentNode, 'figure.image') ? image.parentNode : image;
  942. editor.dom.remove(elm);
  943. editor.focus();
  944. editor.nodeChanged();
  945. if (editor.dom.isEmpty(editor.getBody())) {
  946. editor.setContent('');
  947. editor.selection.setCursorLocation();
  948. }
  949. }
  950. };
  951. const writeImageDataToSelection = (editor, data) => {
  952. const image = getSelectedImage(editor);
  953. if (image) {
  954. write((css) => normalizeCss$1(editor, css), data, image);
  955. syncSrcAttr(editor, image);
  956. if (isFigure(image.parentNode)) {
  957. editor.dom.setStyle(image, 'float', '');
  958. const figure = image.parentNode;
  959. splitTextBlock(editor, figure);
  960. editor.selection.select(image.parentNode);
  961. }
  962. else {
  963. editor.selection.select(image);
  964. waitLoadImage(editor, data, image);
  965. }
  966. }
  967. };
  968. const sanitizeImageData = (editor, data) => {
  969. // Sanitize the URL
  970. const src = data.src;
  971. return {
  972. ...data,
  973. src: isSafeImageUrl(editor, src) ? src : ''
  974. };
  975. };
  976. const insertOrUpdateImage = (editor, partialData) => {
  977. const image = getSelectedImage(editor);
  978. if (image) {
  979. const selectedImageData = read((css) => normalizeCss$1(editor, css), image);
  980. const data = { ...selectedImageData, ...partialData };
  981. const sanitizedData = sanitizeImageData(editor, data);
  982. if (data.src) {
  983. writeImageDataToSelection(editor, sanitizedData);
  984. }
  985. else {
  986. deleteImage(editor, image);
  987. }
  988. }
  989. else if (partialData.src) {
  990. insertImageAtCaret(editor, { ...defaultData(), ...partialData });
  991. }
  992. };
  993. var global$1 = tinymce.util.Tools.resolve('tinymce.util.ImageUploader');
  994. var global = tinymce.util.Tools.resolve('tinymce.util.Tools');
  995. const getValue = (item) => isString(item.value) ? item.value : '';
  996. const getText = (item) => {
  997. if (isString(item.text)) {
  998. return item.text;
  999. }
  1000. else if (isString(item.title)) {
  1001. return item.title;
  1002. }
  1003. else {
  1004. return '';
  1005. }
  1006. };
  1007. const sanitizeList = (list, extractValue) => {
  1008. const out = [];
  1009. global.each(list, (item) => {
  1010. const text = getText(item);
  1011. if (item.menu !== undefined) {
  1012. const items = sanitizeList(item.menu, extractValue);
  1013. out.push({ text, items }); // list group
  1014. }
  1015. else {
  1016. const value = extractValue(item);
  1017. out.push({ text, value }); // list value
  1018. }
  1019. });
  1020. return out;
  1021. };
  1022. const sanitizer = (extractor = getValue) => (list) => {
  1023. if (list) {
  1024. return Optional.from(list).map((list) => sanitizeList(list, extractor));
  1025. }
  1026. else {
  1027. return Optional.none();
  1028. }
  1029. };
  1030. const sanitize = (list) => sanitizer(getValue)(list);
  1031. const isGroup = (item) => has(item, 'items');
  1032. const findEntryDelegate = (list, value) => findMap(list, (item) => {
  1033. if (isGroup(item)) {
  1034. return findEntryDelegate(item.items, value);
  1035. }
  1036. else if (item.value === value) {
  1037. return Optional.some(item);
  1038. }
  1039. else {
  1040. return Optional.none();
  1041. }
  1042. });
  1043. const findEntry = (optList, value) => optList.bind((list) => findEntryDelegate(list, value));
  1044. const ListUtils = {
  1045. sanitizer,
  1046. sanitize,
  1047. findEntry
  1048. };
  1049. const makeTab$2 = (_info) => ({
  1050. title: 'Advanced',
  1051. name: 'advanced',
  1052. items: [
  1053. {
  1054. type: 'grid',
  1055. columns: 2,
  1056. items: [
  1057. {
  1058. type: 'input',
  1059. label: 'Vertical space',
  1060. name: 'vspace',
  1061. inputMode: 'numeric'
  1062. },
  1063. {
  1064. type: 'input',
  1065. label: 'Horizontal space',
  1066. name: 'hspace',
  1067. inputMode: 'numeric'
  1068. },
  1069. {
  1070. type: 'input',
  1071. label: 'Border width',
  1072. name: 'border',
  1073. inputMode: 'numeric'
  1074. },
  1075. {
  1076. type: 'listbox',
  1077. name: 'borderstyle',
  1078. label: 'Border style',
  1079. items: [
  1080. { text: 'Select...', value: '' },
  1081. { text: 'Solid', value: 'solid' },
  1082. { text: 'Dotted', value: 'dotted' },
  1083. { text: 'Dashed', value: 'dashed' },
  1084. { text: 'Double', value: 'double' },
  1085. { text: 'Groove', value: 'groove' },
  1086. { text: 'Ridge', value: 'ridge' },
  1087. { text: 'Inset', value: 'inset' },
  1088. { text: 'Outset', value: 'outset' },
  1089. { text: 'None', value: 'none' },
  1090. { text: 'Hidden', value: 'hidden' }
  1091. ]
  1092. }
  1093. ]
  1094. }
  1095. ]
  1096. });
  1097. const AdvTab = {
  1098. makeTab: makeTab$2
  1099. };
  1100. const collect = (editor) => {
  1101. const urlListSanitizer = ListUtils.sanitizer((item) => editor.convertURL(item.value || item.url || '', 'src'));
  1102. const futureImageList = new Promise((completer) => {
  1103. createImageList(editor, (imageList) => {
  1104. completer(urlListSanitizer(imageList).map((items) => flatten([
  1105. [{ text: 'None', value: '' }],
  1106. items
  1107. ])));
  1108. });
  1109. });
  1110. const classList = ListUtils.sanitize(getClassList(editor));
  1111. const hasAdvTab$1 = hasAdvTab(editor);
  1112. const hasUploadTab$1 = hasUploadTab(editor);
  1113. const hasUploadUrl$1 = hasUploadUrl(editor);
  1114. const hasUploadHandler$1 = hasUploadHandler(editor);
  1115. const image = readImageDataFromSelection(editor);
  1116. const hasDescription$1 = hasDescription(editor);
  1117. const hasImageTitle$1 = hasImageTitle(editor);
  1118. const hasDimensions$1 = hasDimensions(editor);
  1119. const hasImageCaption$1 = hasImageCaption(editor);
  1120. const hasAccessibilityOptions = showAccessibilityOptions(editor);
  1121. const automaticUploads = isAutomaticUploadsEnabled(editor);
  1122. const prependURL = Optional.some(getPrependUrl(editor)).filter((preUrl) => isString(preUrl) && preUrl.length > 0);
  1123. return futureImageList.then((imageList) => ({
  1124. image,
  1125. imageList,
  1126. classList,
  1127. hasAdvTab: hasAdvTab$1,
  1128. hasUploadTab: hasUploadTab$1,
  1129. hasUploadUrl: hasUploadUrl$1,
  1130. hasUploadHandler: hasUploadHandler$1,
  1131. hasDescription: hasDescription$1,
  1132. hasImageTitle: hasImageTitle$1,
  1133. hasDimensions: hasDimensions$1,
  1134. hasImageCaption: hasImageCaption$1,
  1135. prependURL,
  1136. hasAccessibilityOptions,
  1137. automaticUploads
  1138. }));
  1139. };
  1140. const makeItems = (info) => {
  1141. const imageUrl = {
  1142. name: 'src',
  1143. type: 'urlinput',
  1144. filetype: 'image',
  1145. label: 'Source',
  1146. picker_text: 'Browse files'
  1147. };
  1148. const imageList = info.imageList.map((items) => ({
  1149. name: 'images',
  1150. type: 'listbox',
  1151. label: 'Image list',
  1152. items
  1153. }));
  1154. const imageDescription = {
  1155. name: 'alt',
  1156. type: 'input',
  1157. label: 'Alternative description',
  1158. enabled: !(info.hasAccessibilityOptions && info.image.isDecorative)
  1159. };
  1160. const imageTitle = {
  1161. name: 'title',
  1162. type: 'input',
  1163. label: 'Image title'
  1164. };
  1165. const imageDimensions = {
  1166. name: 'dimensions',
  1167. type: 'sizeinput'
  1168. };
  1169. const isDecorative = {
  1170. type: 'label',
  1171. label: 'Accessibility',
  1172. items: [{
  1173. name: 'isDecorative',
  1174. type: 'checkbox',
  1175. label: 'Image is decorative'
  1176. }]
  1177. };
  1178. // TODO: the original listbox supported styled items but bridge does not seem to support this
  1179. const classList = info.classList.map((items) => ({
  1180. name: 'classes',
  1181. type: 'listbox',
  1182. label: 'Class',
  1183. items
  1184. }));
  1185. const caption = {
  1186. type: 'label',
  1187. label: 'Caption',
  1188. items: [
  1189. {
  1190. type: 'checkbox',
  1191. name: 'caption',
  1192. label: 'Show caption'
  1193. }
  1194. ]
  1195. };
  1196. const getDialogContainerType = (useColumns) => useColumns ? { type: 'grid', columns: 2 } : { type: 'panel' };
  1197. return flatten([
  1198. [imageUrl],
  1199. imageList.toArray(),
  1200. info.hasAccessibilityOptions && info.hasDescription ? [isDecorative] : [],
  1201. info.hasDescription ? [imageDescription] : [],
  1202. info.hasImageTitle ? [imageTitle] : [],
  1203. info.hasDimensions ? [imageDimensions] : [],
  1204. [{
  1205. ...getDialogContainerType(info.classList.isSome() && info.hasImageCaption),
  1206. items: flatten([
  1207. classList.toArray(),
  1208. info.hasImageCaption ? [caption] : []
  1209. ])
  1210. }]
  1211. ]);
  1212. };
  1213. const makeTab$1 = (info) => ({
  1214. title: 'General',
  1215. name: 'general',
  1216. items: makeItems(info)
  1217. });
  1218. const MainTab = {
  1219. makeTab: makeTab$1,
  1220. makeItems
  1221. };
  1222. const makeTab = (_info) => {
  1223. const items = [
  1224. {
  1225. type: 'dropzone',
  1226. name: 'fileinput'
  1227. }
  1228. ];
  1229. return {
  1230. title: 'Upload',
  1231. name: 'upload',
  1232. items
  1233. };
  1234. };
  1235. const UploadTab = {
  1236. makeTab
  1237. };
  1238. const createState = (info) => ({
  1239. prevImage: ListUtils.findEntry(info.imageList, info.image.src),
  1240. prevAlt: info.image.alt,
  1241. open: true
  1242. });
  1243. const fromImageData = (image) => ({
  1244. src: {
  1245. value: image.src,
  1246. meta: {}
  1247. },
  1248. images: image.src,
  1249. alt: image.alt,
  1250. title: image.title,
  1251. dimensions: {
  1252. width: image.width,
  1253. height: image.height
  1254. },
  1255. classes: image.class,
  1256. caption: image.caption,
  1257. style: image.style,
  1258. vspace: image.vspace,
  1259. border: image.border,
  1260. hspace: image.hspace,
  1261. borderstyle: image.borderStyle,
  1262. fileinput: [],
  1263. isDecorative: image.isDecorative
  1264. });
  1265. const toImageData = (data, removeEmptyAlt) => ({
  1266. src: data.src.value,
  1267. alt: (data.alt === null || data.alt.length === 0) && removeEmptyAlt ? null : data.alt,
  1268. title: data.title,
  1269. width: data.dimensions.width,
  1270. height: data.dimensions.height,
  1271. class: data.classes,
  1272. style: data.style,
  1273. caption: data.caption,
  1274. hspace: data.hspace,
  1275. vspace: data.vspace,
  1276. border: data.border,
  1277. borderStyle: data.borderstyle,
  1278. isDecorative: data.isDecorative
  1279. });
  1280. const addPrependUrl2 = (info, srcURL) => {
  1281. // Add the prependURL
  1282. if (!/^(?:[a-zA-Z]+:)?\/\//.test(srcURL)) {
  1283. return info.prependURL.bind((prependUrl) => {
  1284. if (srcURL.substring(0, prependUrl.length) !== prependUrl) {
  1285. return Optional.some(prependUrl + srcURL);
  1286. }
  1287. return Optional.none();
  1288. });
  1289. }
  1290. return Optional.none();
  1291. };
  1292. const addPrependUrl = (info, api) => {
  1293. const data = api.getData();
  1294. addPrependUrl2(info, data.src.value).each((srcURL) => {
  1295. api.setData({ src: { value: srcURL, meta: data.src.meta } });
  1296. });
  1297. };
  1298. const formFillFromMeta2 = (info, data, meta) => {
  1299. if (info.hasDescription && isString(meta.alt)) {
  1300. data.alt = meta.alt;
  1301. }
  1302. if (info.hasAccessibilityOptions) {
  1303. data.isDecorative = meta.isDecorative || data.isDecorative || false;
  1304. }
  1305. if (info.hasImageTitle && isString(meta.title)) {
  1306. data.title = meta.title;
  1307. }
  1308. if (info.hasDimensions) {
  1309. if (isString(meta.width)) {
  1310. data.dimensions.width = meta.width;
  1311. }
  1312. if (isString(meta.height)) {
  1313. data.dimensions.height = meta.height;
  1314. }
  1315. }
  1316. if (isString(meta.class)) {
  1317. ListUtils.findEntry(info.classList, meta.class).each((entry) => {
  1318. data.classes = entry.value;
  1319. });
  1320. }
  1321. if (info.hasImageCaption) {
  1322. if (isBoolean(meta.caption)) {
  1323. data.caption = meta.caption;
  1324. }
  1325. }
  1326. if (info.hasAdvTab) {
  1327. if (isString(meta.style)) {
  1328. data.style = meta.style;
  1329. }
  1330. if (isString(meta.vspace)) {
  1331. data.vspace = meta.vspace;
  1332. }
  1333. if (isString(meta.border)) {
  1334. data.border = meta.border;
  1335. }
  1336. if (isString(meta.hspace)) {
  1337. data.hspace = meta.hspace;
  1338. }
  1339. if (isString(meta.borderstyle)) {
  1340. data.borderstyle = meta.borderstyle;
  1341. }
  1342. }
  1343. };
  1344. const formFillFromMeta = (info, api) => {
  1345. const data = api.getData();
  1346. const meta = data.src.meta;
  1347. if (meta !== undefined) {
  1348. const newData = deepMerge({}, data);
  1349. formFillFromMeta2(info, newData, meta);
  1350. api.setData(newData);
  1351. }
  1352. };
  1353. const calculateImageSize = (helpers, info, state, api) => {
  1354. const data = api.getData();
  1355. const url = data.src.value;
  1356. const meta = data.src.meta || {};
  1357. if (!meta.width && !meta.height && info.hasDimensions) {
  1358. if (isNotEmpty(url)) {
  1359. helpers.imageSize(url)
  1360. .then((size) => {
  1361. if (state.open) {
  1362. api.setData({ dimensions: size });
  1363. }
  1364. })
  1365. // eslint-disable-next-line no-console
  1366. .catch((e) => console.error(e));
  1367. }
  1368. else {
  1369. api.setData({ dimensions: { width: '', height: '' } });
  1370. }
  1371. }
  1372. };
  1373. const updateImagesDropdown = (info, state, api) => {
  1374. const data = api.getData();
  1375. const image = ListUtils.findEntry(info.imageList, data.src.value);
  1376. state.prevImage = image;
  1377. api.setData({ images: image.map((entry) => entry.value).getOr('') });
  1378. };
  1379. const changeSrc = (helpers, info, state, api) => {
  1380. addPrependUrl(info, api);
  1381. formFillFromMeta(info, api);
  1382. calculateImageSize(helpers, info, state, api);
  1383. updateImagesDropdown(info, state, api);
  1384. };
  1385. const changeImages = (helpers, info, state, api) => {
  1386. const data = api.getData();
  1387. const image = ListUtils.findEntry(info.imageList, data.images);
  1388. image.each((img) => {
  1389. const updateAlt = data.alt === '' || state.prevImage.map((image) => image.text === data.alt).getOr(false);
  1390. if (updateAlt) {
  1391. if (img.value === '') {
  1392. api.setData({ src: img, alt: state.prevAlt });
  1393. }
  1394. else {
  1395. api.setData({ src: img, alt: img.text });
  1396. }
  1397. }
  1398. else {
  1399. api.setData({ src: img });
  1400. }
  1401. });
  1402. state.prevImage = image;
  1403. changeSrc(helpers, info, state, api);
  1404. };
  1405. const changeFileInput = (helpers, info, state, api) => {
  1406. const data = api.getData();
  1407. api.block('Uploading image'); // What msg do we pass to the lock?
  1408. head(data.fileinput)
  1409. .fold(() => {
  1410. api.unblock();
  1411. }, (file) => {
  1412. const blobUri = URL.createObjectURL(file);
  1413. const finalize = () => {
  1414. api.unblock();
  1415. URL.revokeObjectURL(blobUri);
  1416. };
  1417. const updateSrcAndSwitchTab = (url) => {
  1418. api.setData({ src: { value: url, meta: {} } });
  1419. api.showTab('general');
  1420. changeSrc(helpers, info, state, api);
  1421. api.focus('src');
  1422. };
  1423. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1424. blobToDataUri(file).then((dataUrl) => {
  1425. const blobInfo = helpers.createBlobCache(file, blobUri, dataUrl);
  1426. if (info.automaticUploads) {
  1427. helpers.uploadImage(blobInfo).then((result) => {
  1428. updateSrcAndSwitchTab(result.url);
  1429. finalize();
  1430. }).catch((err) => {
  1431. finalize();
  1432. helpers.alertErr(err, () => {
  1433. api.focus('fileinput');
  1434. });
  1435. });
  1436. }
  1437. else {
  1438. helpers.addToBlobCache(blobInfo);
  1439. updateSrcAndSwitchTab(blobInfo.blobUri());
  1440. api.unblock();
  1441. }
  1442. });
  1443. });
  1444. };
  1445. const changeHandler = (helpers, info, state) => (api, evt) => {
  1446. if (evt.name === 'src') {
  1447. changeSrc(helpers, info, state, api);
  1448. }
  1449. else if (evt.name === 'images') {
  1450. changeImages(helpers, info, state, api);
  1451. }
  1452. else if (evt.name === 'alt') {
  1453. state.prevAlt = api.getData().alt;
  1454. }
  1455. else if (evt.name === 'fileinput') {
  1456. changeFileInput(helpers, info, state, api);
  1457. }
  1458. else if (evt.name === 'isDecorative') {
  1459. api.setEnabled('alt', !api.getData().isDecorative);
  1460. }
  1461. };
  1462. const closeHandler = (state) => () => {
  1463. state.open = false;
  1464. };
  1465. const makeDialogBody = (info) => {
  1466. if (info.hasAdvTab || info.hasUploadUrl || info.hasUploadHandler) {
  1467. const tabPanel = {
  1468. type: 'tabpanel',
  1469. tabs: flatten([
  1470. [MainTab.makeTab(info)],
  1471. info.hasAdvTab ? [AdvTab.makeTab(info)] : [],
  1472. info.hasUploadTab && (info.hasUploadUrl || info.hasUploadHandler) ? [UploadTab.makeTab(info)] : []
  1473. ])
  1474. };
  1475. return tabPanel;
  1476. }
  1477. else {
  1478. const panel = {
  1479. type: 'panel',
  1480. items: MainTab.makeItems(info)
  1481. };
  1482. return panel;
  1483. }
  1484. };
  1485. const submitHandler = (editor, info, helpers) => (api) => {
  1486. const data = deepMerge(fromImageData(info.image), api.getData());
  1487. // The data architecture relies on passing everything through the style field for validation.
  1488. // Since the style field was removed that process must be simulated on submit.
  1489. const finalData = {
  1490. ...data,
  1491. style: getStyleValue(helpers.normalizeCss, toImageData(data, false))
  1492. };
  1493. editor.execCommand('mceUpdateImage', false, toImageData(finalData, info.hasAccessibilityOptions));
  1494. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1495. editor.editorUpload.uploadImagesAuto();
  1496. api.close();
  1497. };
  1498. const imageSize = (editor) => (url) => {
  1499. // If the URL isn't safe then don't attempt to load it to get the sizes
  1500. if (!isSafeImageUrl(editor, url)) {
  1501. return Promise.resolve({ width: '', height: '' });
  1502. }
  1503. else {
  1504. return getImageSize(editor.documentBaseURI.toAbsolute(url)).then((dimensions) => ({
  1505. width: String(dimensions.width),
  1506. height: String(dimensions.height)
  1507. }));
  1508. }
  1509. };
  1510. const createBlobCache = (editor) => (file, blobUri, dataUrl) => {
  1511. var _a;
  1512. return editor.editorUpload.blobCache.create({
  1513. blob: file,
  1514. blobUri,
  1515. name: (_a = file.name) === null || _a === void 0 ? void 0 : _a.replace(/\.[^\.]+$/, ''),
  1516. filename: file.name,
  1517. base64: dataUrl.split(',')[1]
  1518. });
  1519. };
  1520. const addToBlobCache = (editor) => (blobInfo) => {
  1521. editor.editorUpload.blobCache.add(blobInfo);
  1522. };
  1523. const alertErr = (editor) => (message, callback) => {
  1524. editor.windowManager.alert(message, callback);
  1525. };
  1526. const normalizeCss = (editor) => (cssText) => normalizeCss$1(editor, cssText);
  1527. const parseStyle = (editor) => (cssText) => editor.dom.parseStyle(cssText);
  1528. const serializeStyle = (editor) => (stylesArg, name) => editor.dom.serializeStyle(stylesArg, name);
  1529. const uploadImage = (editor) => (blobInfo) => global$1(editor).upload([blobInfo], false).then((results) => {
  1530. var _a;
  1531. if (results.length === 0) {
  1532. return Promise.reject('Failed to upload image');
  1533. }
  1534. else if (results[0].status === false) {
  1535. return Promise.reject((_a = results[0].error) === null || _a === void 0 ? void 0 : _a.message);
  1536. }
  1537. else {
  1538. return results[0];
  1539. }
  1540. });
  1541. const Dialog = (editor) => {
  1542. const helpers = {
  1543. imageSize: imageSize(editor),
  1544. addToBlobCache: addToBlobCache(editor),
  1545. createBlobCache: createBlobCache(editor),
  1546. alertErr: alertErr(editor),
  1547. normalizeCss: normalizeCss(editor),
  1548. parseStyle: parseStyle(editor),
  1549. serializeStyle: serializeStyle(editor),
  1550. uploadImage: uploadImage(editor)
  1551. };
  1552. const open = () => {
  1553. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1554. collect(editor)
  1555. .then((info) => {
  1556. const state = createState(info);
  1557. return {
  1558. title: 'Insert/Edit Image',
  1559. size: 'normal',
  1560. body: makeDialogBody(info),
  1561. buttons: [
  1562. {
  1563. type: 'cancel',
  1564. name: 'cancel',
  1565. text: 'Cancel'
  1566. },
  1567. {
  1568. type: 'submit',
  1569. name: 'save',
  1570. text: 'Save',
  1571. primary: true
  1572. }
  1573. ],
  1574. initialData: fromImageData(info.image),
  1575. onSubmit: submitHandler(editor, info, helpers),
  1576. onChange: changeHandler(helpers, info, state),
  1577. onClose: closeHandler(state)
  1578. };
  1579. })
  1580. .then(editor.windowManager.open);
  1581. };
  1582. return {
  1583. open
  1584. };
  1585. };
  1586. const register$1 = (editor) => {
  1587. editor.addCommand('mceImage', Dialog(editor).open);
  1588. // TODO: This command is likely to be short lived we only need it until we expose the rtc model though a new api so it shouldn't be documented
  1589. // it's just a command since that is a convenient method for the rtc plugin to override the default dom mutation behaviour
  1590. editor.addCommand('mceUpdateImage', (_ui, data) => {
  1591. editor.undoManager.transact(() => insertOrUpdateImage(editor, data));
  1592. });
  1593. };
  1594. const hasImageClass = (node) => {
  1595. const className = node.attr('class');
  1596. return isNonNullable(className) && /\bimage\b/.test(className);
  1597. };
  1598. const toggleContentEditableState = (state) => (nodes) => {
  1599. let i = nodes.length;
  1600. const toggleContentEditable = (node) => {
  1601. node.attr('contenteditable', state ? 'true' : null);
  1602. };
  1603. while (i--) {
  1604. const node = nodes[i];
  1605. if (hasImageClass(node)) {
  1606. node.attr('contenteditable', state ? 'false' : null);
  1607. global.each(node.getAll('figcaption'), toggleContentEditable);
  1608. }
  1609. }
  1610. };
  1611. const setup = (editor) => {
  1612. editor.on('PreInit', () => {
  1613. editor.parser.addNodeFilter('figure', toggleContentEditableState(true));
  1614. editor.serializer.addNodeFilter('figure', toggleContentEditableState(false));
  1615. });
  1616. };
  1617. const onSetupEditable = (editor) => (api) => {
  1618. const nodeChanged = () => {
  1619. api.setEnabled(editor.selection.isEditable());
  1620. };
  1621. editor.on('NodeChange', nodeChanged);
  1622. nodeChanged();
  1623. return () => {
  1624. editor.off('NodeChange', nodeChanged);
  1625. };
  1626. };
  1627. const register = (editor) => {
  1628. editor.ui.registry.addToggleButton('image', {
  1629. icon: 'image',
  1630. tooltip: 'Insert/edit image',
  1631. onAction: Dialog(editor).open,
  1632. onSetup: (buttonApi) => {
  1633. // Set the initial state and then bind to selection changes to update the state when the selection changes
  1634. buttonApi.setActive(isNonNullable(getSelectedImage(editor)));
  1635. const unbindSelectorChanged = editor.selection.selectorChangedWithUnbind('img:not([data-mce-object]):not([data-mce-placeholder]),figure.image', buttonApi.setActive).unbind;
  1636. const unbindEditable = onSetupEditable(editor)(buttonApi);
  1637. return () => {
  1638. unbindSelectorChanged();
  1639. unbindEditable();
  1640. };
  1641. }
  1642. });
  1643. editor.ui.registry.addMenuItem('image', {
  1644. icon: 'image',
  1645. text: 'Image...',
  1646. onAction: Dialog(editor).open,
  1647. onSetup: onSetupEditable(editor)
  1648. });
  1649. editor.ui.registry.addContextMenu('image', {
  1650. update: (element) => editor.selection.isEditable() && (isFigure(element) || (isImage(element) && !isPlaceholderImage(element))) ? ['image'] : []
  1651. });
  1652. };
  1653. var Plugin = () => {
  1654. global$4.add('image', (editor) => {
  1655. register$2(editor);
  1656. setup(editor);
  1657. register(editor);
  1658. register$1(editor);
  1659. });
  1660. };
  1661. Plugin();
  1662. /** *****
  1663. * DO NOT EXPORT ANYTHING
  1664. *
  1665. * IF YOU DO ROLLUP WILL LEAVE A GLOBAL ON THE PAGE
  1666. *******/
  1667. })();