plugin.min.js 57 KB

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