plugin.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. /**
  2. * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3. * Licensed under the LGPL or a commercial license.
  4. * For LGPL see License.txt in the project root for license information.
  5. * For commercial licenses see https://www.tiny.cloud/
  6. *
  7. * Version: 5.5.1 (2020-10-01)
  8. */
  9. (function () {
  10. 'use strict';
  11. var Cell = function (initial) {
  12. var value = initial;
  13. var get = function () {
  14. return value;
  15. };
  16. var set = function (v) {
  17. value = v;
  18. };
  19. return {
  20. get: get,
  21. set: set
  22. };
  23. };
  24. var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
  25. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  26. var noop = function () {
  27. };
  28. var constant = function (value) {
  29. return function () {
  30. return value;
  31. };
  32. };
  33. var never = constant(false);
  34. var always = constant(true);
  35. var none = function () {
  36. return NONE;
  37. };
  38. var NONE = function () {
  39. var eq = function (o) {
  40. return o.isNone();
  41. };
  42. var call = function (thunk) {
  43. return thunk();
  44. };
  45. var id = function (n) {
  46. return n;
  47. };
  48. var me = {
  49. fold: function (n, _s) {
  50. return n();
  51. },
  52. is: never,
  53. isSome: never,
  54. isNone: always,
  55. getOr: id,
  56. getOrThunk: call,
  57. getOrDie: function (msg) {
  58. throw new Error(msg || 'error: getOrDie called on none.');
  59. },
  60. getOrNull: constant(null),
  61. getOrUndefined: constant(undefined),
  62. or: id,
  63. orThunk: call,
  64. map: none,
  65. each: noop,
  66. bind: none,
  67. exists: never,
  68. forall: always,
  69. filter: none,
  70. equals: eq,
  71. equals_: eq,
  72. toArray: function () {
  73. return [];
  74. },
  75. toString: constant('none()')
  76. };
  77. return me;
  78. }();
  79. var some = function (a) {
  80. var constant_a = constant(a);
  81. var self = function () {
  82. return me;
  83. };
  84. var bind = function (f) {
  85. return f(a);
  86. };
  87. var me = {
  88. fold: function (n, s) {
  89. return s(a);
  90. },
  91. is: function (v) {
  92. return a === v;
  93. },
  94. isSome: always,
  95. isNone: never,
  96. getOr: constant_a,
  97. getOrThunk: constant_a,
  98. getOrDie: constant_a,
  99. getOrNull: constant_a,
  100. getOrUndefined: constant_a,
  101. or: self,
  102. orThunk: self,
  103. map: function (f) {
  104. return some(f(a));
  105. },
  106. each: function (f) {
  107. f(a);
  108. },
  109. bind: bind,
  110. exists: bind,
  111. forall: bind,
  112. filter: function (f) {
  113. return f(a) ? me : NONE;
  114. },
  115. toArray: function () {
  116. return [a];
  117. },
  118. toString: function () {
  119. return 'some(' + a + ')';
  120. },
  121. equals: function (o) {
  122. return o.is(a);
  123. },
  124. equals_: function (o, elementEq) {
  125. return o.fold(never, function (b) {
  126. return elementEq(a, b);
  127. });
  128. }
  129. };
  130. return me;
  131. };
  132. var from = function (value) {
  133. return value === null || value === undefined ? NONE : some(value);
  134. };
  135. var Optional = {
  136. some: some,
  137. none: none,
  138. from: from
  139. };
  140. var isSimpleType = function (type) {
  141. return function (value) {
  142. return typeof value === type;
  143. };
  144. };
  145. var isNullable = function (a) {
  146. return a === null || a === undefined;
  147. };
  148. var isNonNullable = function (a) {
  149. return !isNullable(a);
  150. };
  151. var isFunction = isSimpleType('function');
  152. function create(width, height) {
  153. return resize(document.createElement('canvas'), width, height);
  154. }
  155. function clone(canvas) {
  156. var tCanvas = create(canvas.width, canvas.height);
  157. var ctx = get2dContext(tCanvas);
  158. ctx.drawImage(canvas, 0, 0);
  159. return tCanvas;
  160. }
  161. function get2dContext(canvas) {
  162. return canvas.getContext('2d');
  163. }
  164. function resize(canvas, width, height) {
  165. canvas.width = width;
  166. canvas.height = height;
  167. return canvas;
  168. }
  169. function getWidth(image) {
  170. return image.naturalWidth || image.width;
  171. }
  172. function getHeight(image) {
  173. return image.naturalHeight || image.height;
  174. }
  175. var promise = function () {
  176. var Promise = function (fn) {
  177. if (typeof this !== 'object') {
  178. throw new TypeError('Promises must be constructed via new');
  179. }
  180. if (typeof fn !== 'function') {
  181. throw new TypeError('not a function');
  182. }
  183. this._state = null;
  184. this._value = null;
  185. this._deferreds = [];
  186. doResolve(fn, bind(resolve, this), bind(reject, this));
  187. };
  188. var anyWindow = window;
  189. var asap = Promise.immediateFn || typeof anyWindow.setImmediate === 'function' && anyWindow.setImmediate || function (fn) {
  190. setTimeout(fn, 1);
  191. };
  192. function bind(fn, thisArg) {
  193. return function () {
  194. return fn.apply(thisArg, arguments);
  195. };
  196. }
  197. var isArray = Array.isArray || function (value) {
  198. return Object.prototype.toString.call(value) === '[object Array]';
  199. };
  200. function handle(deferred) {
  201. var me = this;
  202. if (this._state === null) {
  203. this._deferreds.push(deferred);
  204. return;
  205. }
  206. asap(function () {
  207. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  208. if (cb === null) {
  209. (me._state ? deferred.resolve : deferred.reject)(me._value);
  210. return;
  211. }
  212. var ret;
  213. try {
  214. ret = cb(me._value);
  215. } catch (e) {
  216. deferred.reject(e);
  217. return;
  218. }
  219. deferred.resolve(ret);
  220. });
  221. }
  222. function resolve(newValue) {
  223. try {
  224. if (newValue === this) {
  225. throw new TypeError('A promise cannot be resolved with itself.');
  226. }
  227. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  228. var then = newValue.then;
  229. if (typeof then === 'function') {
  230. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  231. return;
  232. }
  233. }
  234. this._state = true;
  235. this._value = newValue;
  236. finale.call(this);
  237. } catch (e) {
  238. reject.call(this, e);
  239. }
  240. }
  241. function reject(newValue) {
  242. this._state = false;
  243. this._value = newValue;
  244. finale.call(this);
  245. }
  246. function finale() {
  247. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  248. var deferred = _a[_i];
  249. handle.call(this, deferred);
  250. }
  251. this._deferreds = [];
  252. }
  253. function Handler(onFulfilled, onRejected, resolve, reject) {
  254. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  255. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  256. this.resolve = resolve;
  257. this.reject = reject;
  258. }
  259. function doResolve(fn, onFulfilled, onRejected) {
  260. var done = false;
  261. try {
  262. fn(function (value) {
  263. if (done) {
  264. return;
  265. }
  266. done = true;
  267. onFulfilled(value);
  268. }, function (reason) {
  269. if (done) {
  270. return;
  271. }
  272. done = true;
  273. onRejected(reason);
  274. });
  275. } catch (ex) {
  276. if (done) {
  277. return;
  278. }
  279. done = true;
  280. onRejected(ex);
  281. }
  282. }
  283. Promise.prototype.catch = function (onRejected) {
  284. return this.then(null, onRejected);
  285. };
  286. Promise.prototype.then = function (onFulfilled, onRejected) {
  287. var me = this;
  288. return new Promise(function (resolve, reject) {
  289. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  290. });
  291. };
  292. Promise.all = function () {
  293. var values = [];
  294. for (var _i = 0; _i < arguments.length; _i++) {
  295. values[_i] = arguments[_i];
  296. }
  297. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  298. return new Promise(function (resolve, reject) {
  299. if (args.length === 0) {
  300. return resolve([]);
  301. }
  302. var remaining = args.length;
  303. function res(i, val) {
  304. try {
  305. if (val && (typeof val === 'object' || typeof val === 'function')) {
  306. var then = val.then;
  307. if (typeof then === 'function') {
  308. then.call(val, function (val) {
  309. res(i, val);
  310. }, reject);
  311. return;
  312. }
  313. }
  314. args[i] = val;
  315. if (--remaining === 0) {
  316. resolve(args);
  317. }
  318. } catch (ex) {
  319. reject(ex);
  320. }
  321. }
  322. for (var i = 0; i < args.length; i++) {
  323. res(i, args[i]);
  324. }
  325. });
  326. };
  327. Promise.resolve = function (value) {
  328. if (value && typeof value === 'object' && value.constructor === Promise) {
  329. return value;
  330. }
  331. return new Promise(function (resolve) {
  332. resolve(value);
  333. });
  334. };
  335. Promise.reject = function (reason) {
  336. return new Promise(function (resolve, reject) {
  337. reject(reason);
  338. });
  339. };
  340. Promise.race = function (values) {
  341. return new Promise(function (resolve, reject) {
  342. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  343. var value = values_1[_i];
  344. value.then(resolve, reject);
  345. }
  346. });
  347. };
  348. return Promise;
  349. };
  350. var Promise = window.Promise ? window.Promise : promise();
  351. function imageToBlob(image) {
  352. var src = image.src;
  353. if (src.indexOf('data:') === 0) {
  354. return dataUriToBlob(src);
  355. }
  356. return anyUriToBlob(src);
  357. }
  358. function blobToImage(blob) {
  359. return new Promise(function (resolve, reject) {
  360. var blobUrl = URL.createObjectURL(blob);
  361. var image = new Image();
  362. var removeListeners = function () {
  363. image.removeEventListener('load', loaded);
  364. image.removeEventListener('error', error);
  365. };
  366. function loaded() {
  367. removeListeners();
  368. resolve(image);
  369. }
  370. function error() {
  371. removeListeners();
  372. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  373. }
  374. image.addEventListener('load', loaded);
  375. image.addEventListener('error', error);
  376. image.src = blobUrl;
  377. if (image.complete) {
  378. loaded();
  379. }
  380. });
  381. }
  382. function anyUriToBlob(url) {
  383. return new Promise(function (resolve, reject) {
  384. var xhr = new XMLHttpRequest();
  385. xhr.open('GET', url, true);
  386. xhr.responseType = 'blob';
  387. xhr.onload = function () {
  388. if (this.status === 200) {
  389. resolve(this.response);
  390. }
  391. };
  392. xhr.onerror = function () {
  393. var _this = this;
  394. var corsError = function () {
  395. var obj = new Error('No access to download image');
  396. obj.code = 18;
  397. obj.name = 'SecurityError';
  398. return obj;
  399. };
  400. var genericError = function () {
  401. return new Error('Error ' + _this.status + ' downloading image');
  402. };
  403. reject(this.status === 0 ? corsError() : genericError());
  404. };
  405. xhr.send();
  406. });
  407. }
  408. function dataUriToBlobSync(uri) {
  409. var data = uri.split(',');
  410. var matches = /data:([^;]+)/.exec(data[0]);
  411. if (!matches) {
  412. return Optional.none();
  413. }
  414. var mimetype = matches[1];
  415. var base64 = data[1];
  416. var sliceSize = 1024;
  417. var byteCharacters = atob(base64);
  418. var bytesLength = byteCharacters.length;
  419. var slicesCount = Math.ceil(bytesLength / sliceSize);
  420. var byteArrays = new Array(slicesCount);
  421. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  422. var begin = sliceIndex * sliceSize;
  423. var end = Math.min(begin + sliceSize, bytesLength);
  424. var bytes = new Array(end - begin);
  425. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  426. bytes[i] = byteCharacters[offset].charCodeAt(0);
  427. }
  428. byteArrays[sliceIndex] = new Uint8Array(bytes);
  429. }
  430. return Optional.some(new Blob(byteArrays, { type: mimetype }));
  431. }
  432. function dataUriToBlob(uri) {
  433. return new Promise(function (resolve, reject) {
  434. dataUriToBlobSync(uri).fold(function () {
  435. reject('uri is not base64: ' + uri);
  436. }, resolve);
  437. });
  438. }
  439. function canvasToBlob(canvas, type, quality) {
  440. type = type || 'image/png';
  441. if (isFunction(HTMLCanvasElement.prototype.toBlob)) {
  442. return new Promise(function (resolve, reject) {
  443. canvas.toBlob(function (blob) {
  444. if (blob) {
  445. resolve(blob);
  446. } else {
  447. reject();
  448. }
  449. }, type, quality);
  450. });
  451. } else {
  452. return dataUriToBlob(canvas.toDataURL(type, quality));
  453. }
  454. }
  455. function canvasToDataURL(canvas, type, quality) {
  456. type = type || 'image/png';
  457. return canvas.toDataURL(type, quality);
  458. }
  459. function blobToCanvas(blob) {
  460. return blobToImage(blob).then(function (image) {
  461. revokeImageUrl(image);
  462. var canvas = create(getWidth(image), getHeight(image));
  463. var context = get2dContext(canvas);
  464. context.drawImage(image, 0, 0);
  465. return canvas;
  466. });
  467. }
  468. function blobToDataUri(blob) {
  469. return new Promise(function (resolve) {
  470. var reader = new FileReader();
  471. reader.onloadend = function () {
  472. resolve(reader.result);
  473. };
  474. reader.readAsDataURL(blob);
  475. });
  476. }
  477. function revokeImageUrl(image) {
  478. URL.revokeObjectURL(image.src);
  479. }
  480. var blobToImage$1 = function (blob) {
  481. return blobToImage(blob);
  482. };
  483. var imageToBlob$1 = function (image) {
  484. return imageToBlob(image);
  485. };
  486. var each = function (xs, f) {
  487. for (var i = 0, len = xs.length; i < len; i++) {
  488. var x = xs[i];
  489. f(x, i);
  490. }
  491. };
  492. var foldl = function (xs, f, acc) {
  493. each(xs, function (x) {
  494. acc = f(acc, x);
  495. });
  496. return acc;
  497. };
  498. var findUntil = function (xs, pred, until) {
  499. for (var i = 0, len = xs.length; i < len; i++) {
  500. var x = xs[i];
  501. if (pred(x, i)) {
  502. return Optional.some(x);
  503. } else if (until(x, i)) {
  504. break;
  505. }
  506. }
  507. return Optional.none();
  508. };
  509. var find = function (xs, pred) {
  510. return findUntil(xs, pred, never);
  511. };
  512. function create$1(getCanvas, blob, uri) {
  513. var initialType = blob.type;
  514. var getType = constant(initialType);
  515. function toBlob() {
  516. return Promise.resolve(blob);
  517. }
  518. var toDataURL = constant(uri);
  519. function toBase64() {
  520. return uri.split(',')[1];
  521. }
  522. function toAdjustedBlob(type, quality) {
  523. return getCanvas.then(function (canvas) {
  524. return canvasToBlob(canvas, type, quality);
  525. });
  526. }
  527. function toAdjustedDataURL(type, quality) {
  528. return getCanvas.then(function (canvas) {
  529. return canvasToDataURL(canvas, type, quality);
  530. });
  531. }
  532. function toAdjustedBase64(type, quality) {
  533. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  534. return dataurl.split(',')[1];
  535. });
  536. }
  537. function toCanvas() {
  538. return getCanvas.then(clone);
  539. }
  540. return {
  541. getType: getType,
  542. toBlob: toBlob,
  543. toDataURL: toDataURL,
  544. toBase64: toBase64,
  545. toAdjustedBlob: toAdjustedBlob,
  546. toAdjustedDataURL: toAdjustedDataURL,
  547. toAdjustedBase64: toAdjustedBase64,
  548. toCanvas: toCanvas
  549. };
  550. }
  551. function fromBlob(blob) {
  552. return blobToDataUri(blob).then(function (uri) {
  553. return create$1(blobToCanvas(blob), blob, uri);
  554. });
  555. }
  556. function fromCanvas(canvas, type) {
  557. return canvasToBlob(canvas, type).then(function (blob) {
  558. return create$1(Promise.resolve(canvas), blob, canvas.toDataURL());
  559. });
  560. }
  561. function rotate(ir, angle) {
  562. return ir.toCanvas().then(function (canvas) {
  563. return applyRotate(canvas, ir.getType(), angle);
  564. });
  565. }
  566. function applyRotate(image, type, angle) {
  567. var canvas = create(image.width, image.height);
  568. var context = get2dContext(canvas);
  569. var translateX = 0;
  570. var translateY = 0;
  571. angle = angle < 0 ? 360 + angle : angle;
  572. if (angle === 90 || angle === 270) {
  573. resize(canvas, canvas.height, canvas.width);
  574. }
  575. if (angle === 90 || angle === 180) {
  576. translateX = canvas.width;
  577. }
  578. if (angle === 270 || angle === 180) {
  579. translateY = canvas.height;
  580. }
  581. context.translate(translateX, translateY);
  582. context.rotate(angle * Math.PI / 180);
  583. context.drawImage(image, 0, 0);
  584. return fromCanvas(canvas, type);
  585. }
  586. function flip(ir, axis) {
  587. return ir.toCanvas().then(function (canvas) {
  588. return applyFlip(canvas, ir.getType(), axis);
  589. });
  590. }
  591. function applyFlip(image, type, axis) {
  592. var canvas = create(image.width, image.height);
  593. var context = get2dContext(canvas);
  594. if (axis === 'v') {
  595. context.scale(1, -1);
  596. context.drawImage(image, 0, -canvas.height);
  597. } else {
  598. context.scale(-1, 1);
  599. context.drawImage(image, -canvas.width, 0);
  600. }
  601. return fromCanvas(canvas, type);
  602. }
  603. var flip$1 = function (ir, axis) {
  604. return flip(ir, axis);
  605. };
  606. var rotate$1 = function (ir, angle) {
  607. return rotate(ir, angle);
  608. };
  609. var keys = Object.keys;
  610. var each$1 = function (obj, f) {
  611. var props = keys(obj);
  612. for (var k = 0, len = props.length; k < len; k++) {
  613. var i = props[k];
  614. var x = obj[i];
  615. f(x, i);
  616. }
  617. };
  618. var sendRequest = function (url, headers, withCredentials) {
  619. if (withCredentials === void 0) {
  620. withCredentials = false;
  621. }
  622. return new Promise(function (resolve) {
  623. var xhr = new XMLHttpRequest();
  624. xhr.onreadystatechange = function () {
  625. if (xhr.readyState === 4) {
  626. resolve({
  627. status: xhr.status,
  628. blob: xhr.response
  629. });
  630. }
  631. };
  632. xhr.open('GET', url, true);
  633. xhr.withCredentials = withCredentials;
  634. each$1(headers, function (value, key) {
  635. xhr.setRequestHeader(key, value);
  636. });
  637. xhr.responseType = 'blob';
  638. xhr.send();
  639. });
  640. };
  641. var readBlobText = function (blob) {
  642. return new Promise(function (resolve, reject) {
  643. var reader = new FileReader();
  644. reader.onload = function () {
  645. resolve(reader.result);
  646. };
  647. reader.onerror = function (e) {
  648. reject(e);
  649. };
  650. reader.readAsText(blob);
  651. });
  652. };
  653. var parseJson = function (text) {
  654. try {
  655. return Optional.some(JSON.parse(text));
  656. } catch (ex) {
  657. return Optional.none();
  658. }
  659. };
  660. var friendlyHttpErrors = [
  661. {
  662. code: 404,
  663. message: 'Could not find Image Proxy'
  664. },
  665. {
  666. code: 403,
  667. message: 'Rejected request'
  668. },
  669. {
  670. code: 0,
  671. message: 'Incorrect Image Proxy URL'
  672. }
  673. ];
  674. var friendlyServiceErrors = [
  675. {
  676. type: 'not_found',
  677. message: 'Failed to load image.'
  678. },
  679. {
  680. type: 'key_missing',
  681. message: 'The request did not include an api key.'
  682. },
  683. {
  684. type: 'key_not_found',
  685. message: 'The provided api key could not be found.'
  686. },
  687. {
  688. type: 'domain_not_trusted',
  689. message: 'The api key is not valid for the request origins.'
  690. }
  691. ];
  692. var traverseJson = function (json, path) {
  693. var value = foldl(path, function (result, key) {
  694. return isNonNullable(result) ? result[key] : undefined;
  695. }, json);
  696. return Optional.from(value);
  697. };
  698. var isServiceErrorCode = function (code, blob) {
  699. return (blob === null || blob === void 0 ? void 0 : blob.type) === 'application/json' && (code === 400 || code === 403 || code === 404 || code === 500);
  700. };
  701. var getHttpErrorMsg = function (status) {
  702. var message = find(friendlyHttpErrors, function (error) {
  703. return status === error.code;
  704. }).fold(constant('Unknown ImageProxy error'), function (error) {
  705. return error.message;
  706. });
  707. return 'ImageProxy HTTP error: ' + message;
  708. };
  709. var handleHttpError = function (status) {
  710. var message = getHttpErrorMsg(status);
  711. return Promise.reject(message);
  712. };
  713. var getServiceErrorMsg = function (type) {
  714. return find(friendlyServiceErrors, function (error) {
  715. return error.type === type;
  716. }).fold(constant('Unknown service error'), function (error) {
  717. return error.message;
  718. });
  719. };
  720. var getServiceError = function (text) {
  721. var serviceError = parseJson(text);
  722. var errorMsg = serviceError.bind(function (err) {
  723. return traverseJson(err, [
  724. 'error',
  725. 'type'
  726. ]).map(getServiceErrorMsg);
  727. }).getOr('Invalid JSON in service error message');
  728. return 'ImageProxy Service error: ' + errorMsg;
  729. };
  730. var handleServiceError = function (blob) {
  731. return readBlobText(blob).then(function (text) {
  732. var serviceError = getServiceError(text);
  733. return Promise.reject(serviceError);
  734. });
  735. };
  736. var handleServiceErrorResponse = function (status, blob) {
  737. return isServiceErrorCode(status, blob) ? handleServiceError(blob) : handleHttpError(status);
  738. };
  739. var appendApiKey = function (url, apiKey) {
  740. var separator = url.indexOf('?') === -1 ? '?' : '&';
  741. if (/[?&]apiKey=/.test(url)) {
  742. return url;
  743. } else {
  744. return url + separator + 'apiKey=' + encodeURIComponent(apiKey);
  745. }
  746. };
  747. var isError = function (status) {
  748. return status < 200 || status >= 300;
  749. };
  750. var requestServiceBlob = function (url, apiKey) {
  751. var headers = {
  752. 'Content-Type': 'application/json;charset=UTF-8',
  753. 'tiny-api-key': apiKey
  754. };
  755. return sendRequest(appendApiKey(url, apiKey), headers).then(function (result) {
  756. return isError(result.status) ? handleServiceErrorResponse(result.status, result.blob) : Promise.resolve(result.blob);
  757. });
  758. };
  759. var requestBlob = function (url, withCredentials) {
  760. return sendRequest(url, {}, withCredentials).then(function (result) {
  761. return isError(result.status) ? handleHttpError(result.status) : Promise.resolve(result.blob);
  762. });
  763. };
  764. var getUrl = function (url, apiKey, withCredentials) {
  765. if (withCredentials === void 0) {
  766. withCredentials = false;
  767. }
  768. return apiKey ? requestServiceBlob(url, apiKey) : requestBlob(url, withCredentials);
  769. };
  770. var blobToImageResult = function (blob) {
  771. return fromBlob(blob);
  772. };
  773. var ELEMENT = 1;
  774. var fromHtml = function (html, scope) {
  775. var doc = scope || document;
  776. var div = doc.createElement('div');
  777. div.innerHTML = html;
  778. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  779. console.error('HTML does not have a single root node', html);
  780. throw new Error('HTML must have a single root node');
  781. }
  782. return fromDom(div.childNodes[0]);
  783. };
  784. var fromTag = function (tag, scope) {
  785. var doc = scope || document;
  786. var node = doc.createElement(tag);
  787. return fromDom(node);
  788. };
  789. var fromText = function (text, scope) {
  790. var doc = scope || document;
  791. var node = doc.createTextNode(text);
  792. return fromDom(node);
  793. };
  794. var fromDom = function (node) {
  795. if (node === null || node === undefined) {
  796. throw new Error('Node cannot be null or undefined');
  797. }
  798. return { dom: node };
  799. };
  800. var fromPoint = function (docElm, x, y) {
  801. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  802. };
  803. var SugarElement = {
  804. fromHtml: fromHtml,
  805. fromTag: fromTag,
  806. fromText: fromText,
  807. fromDom: fromDom,
  808. fromPoint: fromPoint
  809. };
  810. var is = function (element, selector) {
  811. var dom = element.dom;
  812. if (dom.nodeType !== ELEMENT) {
  813. return false;
  814. } else {
  815. var elem = dom;
  816. if (elem.matches !== undefined) {
  817. return elem.matches(selector);
  818. } else if (elem.msMatchesSelector !== undefined) {
  819. return elem.msMatchesSelector(selector);
  820. } else if (elem.webkitMatchesSelector !== undefined) {
  821. return elem.webkitMatchesSelector(selector);
  822. } else if (elem.mozMatchesSelector !== undefined) {
  823. return elem.mozMatchesSelector(selector);
  824. } else {
  825. throw new Error('Browser lacks native selectors');
  826. }
  827. }
  828. };
  829. var Global = typeof window !== 'undefined' ? window : Function('return this;')();
  830. var child = function (scope, predicate) {
  831. var pred = function (node) {
  832. return predicate(SugarElement.fromDom(node));
  833. };
  834. var result = find(scope.dom.childNodes, pred);
  835. return result.map(SugarElement.fromDom);
  836. };
  837. var child$1 = function (scope, selector) {
  838. return child(scope, function (e) {
  839. return is(e, selector);
  840. });
  841. };
  842. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  843. var global$3 = tinymce.util.Tools.resolve('tinymce.util.Promise');
  844. var global$4 = tinymce.util.Tools.resolve('tinymce.util.URI');
  845. var getToolbarItems = function (editor) {
  846. return editor.getParam('imagetools_toolbar', 'rotateleft rotateright flipv fliph editimage imageoptions');
  847. };
  848. var getProxyUrl = function (editor) {
  849. return editor.getParam('imagetools_proxy');
  850. };
  851. var getCorsHosts = function (editor) {
  852. return editor.getParam('imagetools_cors_hosts', [], 'string[]');
  853. };
  854. var getCredentialsHosts = function (editor) {
  855. return editor.getParam('imagetools_credentials_hosts', [], 'string[]');
  856. };
  857. var getFetchImage = function (editor) {
  858. return Optional.from(editor.getParam('imagetools_fetch_image', null, 'function'));
  859. };
  860. var getApiKey = function (editor) {
  861. return editor.getParam('api_key', editor.getParam('imagetools_api_key', '', 'string'), 'string');
  862. };
  863. var getUploadTimeout = function (editor) {
  864. return editor.getParam('images_upload_timeout', 30000, 'number');
  865. };
  866. var shouldReuseFilename = function (editor) {
  867. return editor.getParam('images_reuse_filename', false, 'boolean');
  868. };
  869. function getImageSize(img) {
  870. var width, height;
  871. function isPxValue(value) {
  872. return /^[0-9\.]+px$/.test(value);
  873. }
  874. width = img.style.width;
  875. height = img.style.height;
  876. if (width || height) {
  877. if (isPxValue(width) && isPxValue(height)) {
  878. return {
  879. w: parseInt(width, 10),
  880. h: parseInt(height, 10)
  881. };
  882. }
  883. return null;
  884. }
  885. width = img.width;
  886. height = img.height;
  887. if (width && height) {
  888. return {
  889. w: parseInt(width, 10),
  890. h: parseInt(height, 10)
  891. };
  892. }
  893. return null;
  894. }
  895. function setImageSize(img, size) {
  896. var width, height;
  897. if (size) {
  898. width = img.style.width;
  899. height = img.style.height;
  900. if (width || height) {
  901. img.style.width = size.w + 'px';
  902. img.style.height = size.h + 'px';
  903. img.removeAttribute('data-mce-style');
  904. }
  905. width = img.width;
  906. height = img.height;
  907. if (width || height) {
  908. img.setAttribute('width', size.w);
  909. img.setAttribute('height', size.h);
  910. }
  911. }
  912. }
  913. function getNaturalImageSize(img) {
  914. return {
  915. w: img.naturalWidth,
  916. h: img.naturalHeight
  917. };
  918. }
  919. var count = 0;
  920. var getFigureImg = function (elem) {
  921. return child$1(SugarElement.fromDom(elem), 'img');
  922. };
  923. var isFigure = function (editor, elem) {
  924. return editor.dom.is(elem, 'figure');
  925. };
  926. var getEditableImage = function (editor, elem) {
  927. var isImage = function (imgNode) {
  928. return editor.dom.is(imgNode, 'img:not([data-mce-object],[data-mce-placeholder])');
  929. };
  930. var isEditable = function (imgNode) {
  931. return isImage(imgNode) && (isLocalImage(editor, imgNode) || isCorsImage(editor, imgNode) || getProxyUrl(editor));
  932. };
  933. if (isFigure(editor, elem)) {
  934. var imgOpt = getFigureImg(elem);
  935. return imgOpt.map(function (img) {
  936. return isEditable(img.dom) ? Optional.some(img.dom) : Optional.none();
  937. });
  938. }
  939. return isEditable(elem) ? Optional.some(elem) : Optional.none();
  940. };
  941. var displayError = function (editor, error) {
  942. editor.notificationManager.open({
  943. text: error,
  944. type: 'error'
  945. });
  946. };
  947. var getSelectedImage = function (editor) {
  948. var elem = editor.selection.getNode();
  949. if (isFigure(editor, elem)) {
  950. return getFigureImg(elem);
  951. } else {
  952. return Optional.some(SugarElement.fromDom(elem));
  953. }
  954. };
  955. var extractFilename = function (editor, url) {
  956. var m = url.match(/\/([^\/\?]+)?\.(?:jpeg|jpg|png|gif)(?:\?|$)/i);
  957. if (m) {
  958. return editor.dom.encode(m[1]);
  959. }
  960. return null;
  961. };
  962. var createId = function () {
  963. return 'imagetools' + count++;
  964. };
  965. var isLocalImage = function (editor, img) {
  966. var url = img.src;
  967. return url.indexOf('data:') === 0 || url.indexOf('blob:') === 0 || new global$4(url).host === editor.documentBaseURI.host;
  968. };
  969. var isCorsImage = function (editor, img) {
  970. return global$1.inArray(getCorsHosts(editor), new global$4(img.src).host) !== -1;
  971. };
  972. var isCorsWithCredentialsImage = function (editor, img) {
  973. return global$1.inArray(getCredentialsHosts(editor), new global$4(img.src).host) !== -1;
  974. };
  975. var defaultFetchImage = function (editor, img) {
  976. if (isCorsImage(editor, img)) {
  977. return getUrl(img.src, null, isCorsWithCredentialsImage(editor, img));
  978. }
  979. if (!isLocalImage(editor, img)) {
  980. var proxyUrl = getProxyUrl(editor);
  981. var src = proxyUrl + (proxyUrl.indexOf('?') === -1 ? '?' : '&') + 'url=' + encodeURIComponent(img.src);
  982. var apiKey = getApiKey(editor);
  983. return getUrl(src, apiKey, false);
  984. }
  985. return imageToBlob$1(img);
  986. };
  987. var imageToBlob$2 = function (editor, img) {
  988. return getFetchImage(editor).fold(function () {
  989. return defaultFetchImage(editor, img);
  990. }, function (customFetchImage) {
  991. return customFetchImage(img);
  992. });
  993. };
  994. var findBlob = function (editor, img) {
  995. var blobInfo = editor.editorUpload.blobCache.getByUri(img.src);
  996. if (blobInfo) {
  997. return global$3.resolve(blobInfo.blob());
  998. }
  999. return imageToBlob$2(editor, img);
  1000. };
  1001. var startTimedUpload = function (editor, imageUploadTimerState) {
  1002. var imageUploadTimer = global$2.setEditorTimeout(editor, function () {
  1003. editor.editorUpload.uploadImagesAuto();
  1004. }, getUploadTimeout(editor));
  1005. imageUploadTimerState.set(imageUploadTimer);
  1006. };
  1007. var cancelTimedUpload = function (imageUploadTimerState) {
  1008. global$2.clearTimeout(imageUploadTimerState.get());
  1009. };
  1010. var updateSelectedImage = function (editor, ir, uploadImmediately, imageUploadTimerState, selectedImage, size) {
  1011. return ir.toBlob().then(function (blob) {
  1012. var uri, name, blobInfo;
  1013. var blobCache = editor.editorUpload.blobCache;
  1014. uri = selectedImage.src;
  1015. if (shouldReuseFilename(editor)) {
  1016. blobInfo = blobCache.getByUri(uri);
  1017. if (blobInfo) {
  1018. uri = blobInfo.uri();
  1019. name = blobInfo.name();
  1020. } else {
  1021. name = extractFilename(editor, uri);
  1022. }
  1023. }
  1024. blobInfo = blobCache.create({
  1025. id: createId(),
  1026. blob: blob,
  1027. base64: ir.toBase64(),
  1028. uri: uri,
  1029. name: name
  1030. });
  1031. blobCache.add(blobInfo);
  1032. editor.undoManager.transact(function () {
  1033. function imageLoadedHandler() {
  1034. editor.$(selectedImage).off('load', imageLoadedHandler);
  1035. editor.nodeChanged();
  1036. if (uploadImmediately) {
  1037. editor.editorUpload.uploadImagesAuto();
  1038. } else {
  1039. cancelTimedUpload(imageUploadTimerState);
  1040. startTimedUpload(editor, imageUploadTimerState);
  1041. }
  1042. }
  1043. editor.$(selectedImage).on('load', imageLoadedHandler);
  1044. if (size) {
  1045. editor.$(selectedImage).attr({
  1046. width: size.w,
  1047. height: size.h
  1048. });
  1049. }
  1050. editor.$(selectedImage).attr({ src: blobInfo.blobUri() }).removeAttr('data-mce-src');
  1051. });
  1052. return blobInfo;
  1053. });
  1054. };
  1055. var selectedImageOperation = function (editor, imageUploadTimerState, fn, size) {
  1056. return function () {
  1057. var imgOpt = getSelectedImage(editor);
  1058. return imgOpt.fold(function () {
  1059. displayError(editor, 'Could not find selected image');
  1060. }, function (img) {
  1061. return editor._scanForImages().then(function () {
  1062. return findBlob(editor, img.dom);
  1063. }).then(blobToImageResult).then(fn).then(function (imageResult) {
  1064. return updateSelectedImage(editor, imageResult, false, imageUploadTimerState, img.dom, size);
  1065. }, function (error) {
  1066. displayError(editor, error);
  1067. });
  1068. });
  1069. };
  1070. };
  1071. var rotate$2 = function (editor, imageUploadTimerState, angle) {
  1072. return function () {
  1073. var imgOpt = getSelectedImage(editor);
  1074. var flippedSize = imgOpt.fold(function () {
  1075. return null;
  1076. }, function (img) {
  1077. var size = getImageSize(img.dom);
  1078. return size ? {
  1079. w: size.h,
  1080. h: size.w
  1081. } : null;
  1082. });
  1083. return selectedImageOperation(editor, imageUploadTimerState, function (imageResult) {
  1084. return rotate$1(imageResult, angle);
  1085. }, flippedSize)();
  1086. };
  1087. };
  1088. var flip$2 = function (editor, imageUploadTimerState, axis) {
  1089. return function () {
  1090. return selectedImageOperation(editor, imageUploadTimerState, function (imageResult) {
  1091. return flip$1(imageResult, axis);
  1092. })();
  1093. };
  1094. };
  1095. var handleDialogBlob = function (editor, imageUploadTimerState, img, originalSize, blob) {
  1096. return blobToImage$1(blob).then(function (newImage) {
  1097. var newSize = getNaturalImageSize(newImage);
  1098. if (originalSize.w !== newSize.w || originalSize.h !== newSize.h) {
  1099. if (getImageSize(img)) {
  1100. setImageSize(img, newSize);
  1101. }
  1102. }
  1103. URL.revokeObjectURL(newImage.src);
  1104. return blob;
  1105. }).then(blobToImageResult).then(function (imageResult) {
  1106. return updateSelectedImage(editor, imageResult, true, imageUploadTimerState, img);
  1107. }, function () {
  1108. });
  1109. };
  1110. var saveState = 'save-state';
  1111. var disable = 'disable';
  1112. var enable = 'enable';
  1113. var createState = function (blob) {
  1114. return {
  1115. blob: blob,
  1116. url: URL.createObjectURL(blob)
  1117. };
  1118. };
  1119. var makeOpen = function (editor, imageUploadTimerState) {
  1120. return function () {
  1121. var getLoadedSpec = function (currentState) {
  1122. return {
  1123. title: 'Edit Image',
  1124. size: 'large',
  1125. body: {
  1126. type: 'panel',
  1127. items: [{
  1128. type: 'imagetools',
  1129. name: 'imagetools',
  1130. label: 'Edit Image',
  1131. currentState: currentState
  1132. }]
  1133. },
  1134. buttons: [
  1135. {
  1136. type: 'cancel',
  1137. name: 'cancel',
  1138. text: 'Cancel'
  1139. },
  1140. {
  1141. type: 'submit',
  1142. name: 'save',
  1143. text: 'Save',
  1144. primary: true,
  1145. disabled: true
  1146. }
  1147. ],
  1148. onSubmit: function (api) {
  1149. var blob = api.getData().imagetools.blob;
  1150. originalImgOpt.each(function (originalImg) {
  1151. originalSizeOpt.each(function (originalSize) {
  1152. handleDialogBlob(editor, imageUploadTimerState, originalImg.dom, originalSize, blob);
  1153. });
  1154. });
  1155. api.close();
  1156. },
  1157. onCancel: function () {
  1158. },
  1159. onAction: function (api, details) {
  1160. switch (details.name) {
  1161. case saveState:
  1162. if (details.value) {
  1163. api.enable('save');
  1164. } else {
  1165. api.disable('save');
  1166. }
  1167. break;
  1168. case disable:
  1169. api.disable('save');
  1170. api.disable('cancel');
  1171. break;
  1172. case enable:
  1173. api.enable('cancel');
  1174. break;
  1175. }
  1176. }
  1177. };
  1178. };
  1179. var originalImgOpt = getSelectedImage(editor);
  1180. var originalSizeOpt = originalImgOpt.map(function (origImg) {
  1181. return getNaturalImageSize(origImg.dom);
  1182. });
  1183. var imgOpt = getSelectedImage(editor);
  1184. imgOpt.each(function (img) {
  1185. getEditableImage(editor, img.dom).each(function (_) {
  1186. findBlob(editor, img.dom).then(function (blob) {
  1187. var state = createState(blob);
  1188. editor.windowManager.open(getLoadedSpec(state));
  1189. });
  1190. });
  1191. });
  1192. };
  1193. };
  1194. var register = function (editor, imageUploadTimerState) {
  1195. global$1.each({
  1196. mceImageRotateLeft: rotate$2(editor, imageUploadTimerState, -90),
  1197. mceImageRotateRight: rotate$2(editor, imageUploadTimerState, 90),
  1198. mceImageFlipVertical: flip$2(editor, imageUploadTimerState, 'v'),
  1199. mceImageFlipHorizontal: flip$2(editor, imageUploadTimerState, 'h'),
  1200. mceEditImage: makeOpen(editor, imageUploadTimerState)
  1201. }, function (fn, cmd) {
  1202. editor.addCommand(cmd, fn);
  1203. });
  1204. };
  1205. var setup = function (editor, imageUploadTimerState, lastSelectedImageState) {
  1206. editor.on('NodeChange', function (e) {
  1207. var lastSelectedImage = lastSelectedImageState.get();
  1208. if (lastSelectedImage && lastSelectedImage.src !== e.element.src) {
  1209. cancelTimedUpload(imageUploadTimerState);
  1210. editor.editorUpload.uploadImagesAuto();
  1211. lastSelectedImageState.set(null);
  1212. }
  1213. getEditableImage(editor, e.element).each(lastSelectedImageState.set);
  1214. });
  1215. };
  1216. var register$1 = function (editor) {
  1217. var cmd = function (command) {
  1218. return function () {
  1219. return editor.execCommand(command);
  1220. };
  1221. };
  1222. editor.ui.registry.addButton('rotateleft', {
  1223. tooltip: 'Rotate counterclockwise',
  1224. icon: 'rotate-left',
  1225. onAction: cmd('mceImageRotateLeft')
  1226. });
  1227. editor.ui.registry.addButton('rotateright', {
  1228. tooltip: 'Rotate clockwise',
  1229. icon: 'rotate-right',
  1230. onAction: cmd('mceImageRotateRight')
  1231. });
  1232. editor.ui.registry.addButton('flipv', {
  1233. tooltip: 'Flip vertically',
  1234. icon: 'flip-vertically',
  1235. onAction: cmd('mceImageFlipVertical')
  1236. });
  1237. editor.ui.registry.addButton('fliph', {
  1238. tooltip: 'Flip horizontally',
  1239. icon: 'flip-horizontally',
  1240. onAction: cmd('mceImageFlipHorizontal')
  1241. });
  1242. editor.ui.registry.addButton('editimage', {
  1243. tooltip: 'Edit image',
  1244. icon: 'edit-image',
  1245. onAction: cmd('mceEditImage'),
  1246. onSetup: function (buttonApi) {
  1247. var setDisabled = function () {
  1248. var elementOpt = getSelectedImage(editor);
  1249. elementOpt.each(function (element) {
  1250. var disabled = getEditableImage(editor, element.dom).isNone();
  1251. buttonApi.setDisabled(disabled);
  1252. });
  1253. };
  1254. editor.on('NodeChange', setDisabled);
  1255. return function () {
  1256. editor.off('NodeChange', setDisabled);
  1257. };
  1258. }
  1259. });
  1260. editor.ui.registry.addButton('imageoptions', {
  1261. tooltip: 'Image options',
  1262. icon: 'image',
  1263. onAction: cmd('mceImage')
  1264. });
  1265. editor.ui.registry.addContextMenu('imagetools', {
  1266. update: function (element) {
  1267. return getEditableImage(editor, element).fold(function () {
  1268. return [];
  1269. }, function (_) {
  1270. return [{
  1271. text: 'Edit image',
  1272. icon: 'edit-image',
  1273. onAction: cmd('mceEditImage')
  1274. }];
  1275. });
  1276. }
  1277. });
  1278. };
  1279. var register$2 = function (editor) {
  1280. editor.ui.registry.addContextToolbar('imagetools', {
  1281. items: getToolbarItems(editor),
  1282. predicate: function (elem) {
  1283. return getEditableImage(editor, elem).isSome();
  1284. },
  1285. position: 'node',
  1286. scope: 'node'
  1287. });
  1288. };
  1289. function Plugin () {
  1290. global.add('imagetools', function (editor) {
  1291. var imageUploadTimerState = Cell(0);
  1292. var lastSelectedImageState = Cell(null);
  1293. register(editor, imageUploadTimerState);
  1294. register$1(editor);
  1295. register$2(editor);
  1296. setup(editor, imageUploadTimerState, lastSelectedImageState);
  1297. });
  1298. }
  1299. Plugin();
  1300. }());