plugin.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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 global = tinymce.util.Tools.resolve('tinymce.PluginManager');
  12. var noop = function () {
  13. };
  14. var constant = function (value) {
  15. return function () {
  16. return value;
  17. };
  18. };
  19. function curry(fn) {
  20. var initialArgs = [];
  21. for (var _i = 1; _i < arguments.length; _i++) {
  22. initialArgs[_i - 1] = arguments[_i];
  23. }
  24. return function () {
  25. var restArgs = [];
  26. for (var _i = 0; _i < arguments.length; _i++) {
  27. restArgs[_i] = arguments[_i];
  28. }
  29. var all = initialArgs.concat(restArgs);
  30. return fn.apply(null, all);
  31. };
  32. }
  33. var never = constant(false);
  34. var always = constant(true);
  35. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  36. var global$2 = tinymce.util.Tools.resolve('tinymce.util.XHR');
  37. var getCreationDateClasses = function (editor) {
  38. return editor.getParam('template_cdate_classes', 'cdate');
  39. };
  40. var getModificationDateClasses = function (editor) {
  41. return editor.getParam('template_mdate_classes', 'mdate');
  42. };
  43. var getSelectedContentClasses = function (editor) {
  44. return editor.getParam('template_selected_content_classes', 'selcontent');
  45. };
  46. var getPreviewReplaceValues = function (editor) {
  47. return editor.getParam('template_preview_replace_values');
  48. };
  49. var getContentStyle = function (editor) {
  50. return editor.getParam('content_style', '', 'string');
  51. };
  52. var shouldUseContentCssCors = function (editor) {
  53. return editor.getParam('content_css_cors', false, 'boolean');
  54. };
  55. var getTemplateReplaceValues = function (editor) {
  56. return editor.getParam('template_replace_values');
  57. };
  58. var getTemplates = function (editor) {
  59. return editor.getParam('templates');
  60. };
  61. var getCdateFormat = function (editor) {
  62. return editor.getParam('template_cdate_format', editor.translate('%Y-%m-%d'));
  63. };
  64. var getMdateFormat = function (editor) {
  65. return editor.getParam('template_mdate_format', editor.translate('%Y-%m-%d'));
  66. };
  67. var getBodyClassFromHash = function (editor) {
  68. var bodyClass = editor.getParam('body_class', '', 'hash');
  69. return bodyClass[editor.id] || '';
  70. };
  71. var getBodyClass = function (editor) {
  72. var bodyClass = editor.getParam('body_class', '', 'string');
  73. if (bodyClass.indexOf('=') === -1) {
  74. return bodyClass;
  75. } else {
  76. return getBodyClassFromHash(editor);
  77. }
  78. };
  79. var addZeros = function (value, len) {
  80. value = '' + value;
  81. if (value.length < len) {
  82. for (var i = 0; i < len - value.length; i++) {
  83. value = '0' + value;
  84. }
  85. }
  86. return value;
  87. };
  88. var getDateTime = function (editor, fmt, date) {
  89. var daysShort = 'Sun Mon Tue Wed Thu Fri Sat Sun'.split(' ');
  90. var daysLong = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' ');
  91. var monthsShort = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
  92. var monthsLong = 'January February March April May June July August September October November December'.split(' ');
  93. date = date || new Date();
  94. fmt = fmt.replace('%D', '%m/%d/%Y');
  95. fmt = fmt.replace('%r', '%I:%M:%S %p');
  96. fmt = fmt.replace('%Y', '' + date.getFullYear());
  97. fmt = fmt.replace('%y', '' + date.getYear());
  98. fmt = fmt.replace('%m', addZeros(date.getMonth() + 1, 2));
  99. fmt = fmt.replace('%d', addZeros(date.getDate(), 2));
  100. fmt = fmt.replace('%H', '' + addZeros(date.getHours(), 2));
  101. fmt = fmt.replace('%M', '' + addZeros(date.getMinutes(), 2));
  102. fmt = fmt.replace('%S', '' + addZeros(date.getSeconds(), 2));
  103. fmt = fmt.replace('%I', '' + ((date.getHours() + 11) % 12 + 1));
  104. fmt = fmt.replace('%p', '' + (date.getHours() < 12 ? 'AM' : 'PM'));
  105. fmt = fmt.replace('%B', '' + editor.translate(monthsLong[date.getMonth()]));
  106. fmt = fmt.replace('%b', '' + editor.translate(monthsShort[date.getMonth()]));
  107. fmt = fmt.replace('%A', '' + editor.translate(daysLong[date.getDay()]));
  108. fmt = fmt.replace('%a', '' + editor.translate(daysShort[date.getDay()]));
  109. fmt = fmt.replace('%%', '%');
  110. return fmt;
  111. };
  112. var createTemplateList = function (editor, callback) {
  113. return function () {
  114. var templateList = getTemplates(editor);
  115. if (typeof templateList === 'function') {
  116. templateList(callback);
  117. return;
  118. }
  119. if (typeof templateList === 'string') {
  120. global$2.send({
  121. url: templateList,
  122. success: function (text) {
  123. callback(JSON.parse(text));
  124. }
  125. });
  126. } else {
  127. callback(templateList);
  128. }
  129. };
  130. };
  131. var replaceTemplateValues = function (html, templateValues) {
  132. global$1.each(templateValues, function (v, k) {
  133. if (typeof v === 'function') {
  134. v = v(k);
  135. }
  136. html = html.replace(new RegExp('\\{\\$' + k + '\\}', 'g'), v);
  137. });
  138. return html;
  139. };
  140. var replaceVals = function (editor, e) {
  141. var dom = editor.dom, vl = getTemplateReplaceValues(editor);
  142. global$1.each(dom.select('*', e), function (e) {
  143. global$1.each(vl, function (v, k) {
  144. if (dom.hasClass(e, k)) {
  145. if (typeof vl[k] === 'function') {
  146. vl[k](e);
  147. }
  148. }
  149. });
  150. });
  151. };
  152. var hasClass = function (n, c) {
  153. return new RegExp('\\b' + c + '\\b', 'g').test(n.className);
  154. };
  155. var insertTemplate = function (editor, _ui, html) {
  156. var el;
  157. var dom = editor.dom;
  158. var sel = editor.selection.getContent();
  159. html = replaceTemplateValues(html, getTemplateReplaceValues(editor));
  160. el = dom.create('div', null, html);
  161. var n = dom.select('.mceTmpl', el);
  162. if (n && n.length > 0) {
  163. el = dom.create('div', null);
  164. el.appendChild(n[0].cloneNode(true));
  165. }
  166. global$1.each(dom.select('*', el), function (n) {
  167. if (hasClass(n, getCreationDateClasses(editor).replace(/\s+/g, '|'))) {
  168. n.innerHTML = getDateTime(editor, getCdateFormat(editor));
  169. }
  170. if (hasClass(n, getModificationDateClasses(editor).replace(/\s+/g, '|'))) {
  171. n.innerHTML = getDateTime(editor, getMdateFormat(editor));
  172. }
  173. if (hasClass(n, getSelectedContentClasses(editor).replace(/\s+/g, '|'))) {
  174. n.innerHTML = sel;
  175. }
  176. });
  177. replaceVals(editor, el);
  178. editor.execCommand('mceInsertContent', false, el.innerHTML);
  179. editor.addVisual();
  180. };
  181. var register = function (editor) {
  182. editor.addCommand('mceInsertTemplate', curry(insertTemplate, editor));
  183. };
  184. var setup = function (editor) {
  185. editor.on('PreProcess', function (o) {
  186. var dom = editor.dom, dateFormat = getMdateFormat(editor);
  187. global$1.each(dom.select('div', o.node), function (e) {
  188. if (dom.hasClass(e, 'mceTmpl')) {
  189. global$1.each(dom.select('*', e), function (e) {
  190. if (dom.hasClass(e, getModificationDateClasses(editor).replace(/\s+/g, '|'))) {
  191. e.innerHTML = getDateTime(editor, dateFormat);
  192. }
  193. });
  194. replaceVals(editor, e);
  195. }
  196. });
  197. });
  198. };
  199. var none = function () {
  200. return NONE;
  201. };
  202. var NONE = function () {
  203. var eq = function (o) {
  204. return o.isNone();
  205. };
  206. var call = function (thunk) {
  207. return thunk();
  208. };
  209. var id = function (n) {
  210. return n;
  211. };
  212. var me = {
  213. fold: function (n, _s) {
  214. return n();
  215. },
  216. is: never,
  217. isSome: never,
  218. isNone: always,
  219. getOr: id,
  220. getOrThunk: call,
  221. getOrDie: function (msg) {
  222. throw new Error(msg || 'error: getOrDie called on none.');
  223. },
  224. getOrNull: constant(null),
  225. getOrUndefined: constant(undefined),
  226. or: id,
  227. orThunk: call,
  228. map: none,
  229. each: noop,
  230. bind: none,
  231. exists: never,
  232. forall: always,
  233. filter: none,
  234. equals: eq,
  235. equals_: eq,
  236. toArray: function () {
  237. return [];
  238. },
  239. toString: constant('none()')
  240. };
  241. return me;
  242. }();
  243. var some = function (a) {
  244. var constant_a = constant(a);
  245. var self = function () {
  246. return me;
  247. };
  248. var bind = function (f) {
  249. return f(a);
  250. };
  251. var me = {
  252. fold: function (n, s) {
  253. return s(a);
  254. },
  255. is: function (v) {
  256. return a === v;
  257. },
  258. isSome: always,
  259. isNone: never,
  260. getOr: constant_a,
  261. getOrThunk: constant_a,
  262. getOrDie: constant_a,
  263. getOrNull: constant_a,
  264. getOrUndefined: constant_a,
  265. or: self,
  266. orThunk: self,
  267. map: function (f) {
  268. return some(f(a));
  269. },
  270. each: function (f) {
  271. f(a);
  272. },
  273. bind: bind,
  274. exists: bind,
  275. forall: bind,
  276. filter: function (f) {
  277. return f(a) ? me : NONE;
  278. },
  279. toArray: function () {
  280. return [a];
  281. },
  282. toString: function () {
  283. return 'some(' + a + ')';
  284. },
  285. equals: function (o) {
  286. return o.is(a);
  287. },
  288. equals_: function (o, elementEq) {
  289. return o.fold(never, function (b) {
  290. return elementEq(a, b);
  291. });
  292. }
  293. };
  294. return me;
  295. };
  296. var from = function (value) {
  297. return value === null || value === undefined ? NONE : some(value);
  298. };
  299. var Optional = {
  300. some: some,
  301. none: none,
  302. from: from
  303. };
  304. var map = function (xs, f) {
  305. var len = xs.length;
  306. var r = new Array(len);
  307. for (var i = 0; i < len; i++) {
  308. var x = xs[i];
  309. r[i] = f(x, i);
  310. }
  311. return r;
  312. };
  313. var findUntil = function (xs, pred, until) {
  314. for (var i = 0, len = xs.length; i < len; i++) {
  315. var x = xs[i];
  316. if (pred(x, i)) {
  317. return Optional.some(x);
  318. } else if (until(x, i)) {
  319. break;
  320. }
  321. }
  322. return Optional.none();
  323. };
  324. var find = function (xs, pred) {
  325. return findUntil(xs, pred, never);
  326. };
  327. var global$3 = tinymce.util.Tools.resolve('tinymce.Env');
  328. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Promise');
  329. var hasOwnProperty = Object.hasOwnProperty;
  330. var get = function (obj, key) {
  331. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  332. };
  333. var has = function (obj, key) {
  334. return hasOwnProperty.call(obj, key);
  335. };
  336. var entitiesAttr = {
  337. '"': '&quot;',
  338. '<': '&lt;',
  339. '>': '&gt;',
  340. '&': '&amp;',
  341. '\'': '&#039;'
  342. };
  343. var htmlEscape = function (html) {
  344. return html.replace(/["'<>&]/g, function (match) {
  345. return get(entitiesAttr, match).getOr(match);
  346. });
  347. };
  348. var getPreviewContent = function (editor, html) {
  349. if (html.indexOf('<html>') === -1) {
  350. var contentCssEntries_1 = '';
  351. var contentStyle = getContentStyle(editor);
  352. if (contentStyle) {
  353. contentCssEntries_1 += '<style type="text/css">' + contentStyle + '</style>';
  354. }
  355. var cors_1 = shouldUseContentCssCors(editor) ? ' crossorigin="anonymous"' : '';
  356. global$1.each(editor.contentCSS, function (url) {
  357. contentCssEntries_1 += '<link type="text/css" rel="stylesheet" href="' + editor.documentBaseURI.toAbsolute(url) + '"' + cors_1 + '>';
  358. });
  359. var bodyClass = getBodyClass(editor);
  360. var encode = editor.dom.encode;
  361. var isMetaKeyPressed = global$3.mac ? 'e.metaKey' : 'e.ctrlKey && !e.altKey';
  362. var preventClicksOnLinksScript = '<script>' + 'document.addEventListener && document.addEventListener("click", function(e) {' + 'for (var elm = e.target; elm; elm = elm.parentNode) {' + 'if (elm.nodeName === "A" && !(' + isMetaKeyPressed + ')) {' + 'e.preventDefault();' + '}' + '}' + '}, false);' + '</script> ';
  363. var directionality = editor.getBody().dir;
  364. var dirAttr = directionality ? ' dir="' + encode(directionality) + '"' : '';
  365. html = '<!DOCTYPE html>' + '<html>' + '<head>' + '<base href="' + encode(editor.documentBaseURI.getURI()) + '">' + contentCssEntries_1 + preventClicksOnLinksScript + '</head>' + '<body class="' + encode(bodyClass) + '"' + dirAttr + '>' + html + '</body>' + '</html>';
  366. }
  367. return replaceTemplateValues(html, getPreviewReplaceValues(editor));
  368. };
  369. var open = function (editor, templateList) {
  370. var createTemplates = function () {
  371. if (!templateList || templateList.length === 0) {
  372. var message = editor.translate('No templates defined.');
  373. editor.notificationManager.open({
  374. text: message,
  375. type: 'info'
  376. });
  377. return Optional.none();
  378. }
  379. return Optional.from(global$1.map(templateList, function (template, index) {
  380. var isUrlTemplate = function (t) {
  381. return t.url !== undefined;
  382. };
  383. return {
  384. selected: index === 0,
  385. text: template.title,
  386. value: {
  387. url: isUrlTemplate(template) ? Optional.from(template.url) : Optional.none(),
  388. content: !isUrlTemplate(template) ? Optional.from(template.content) : Optional.none(),
  389. description: template.description
  390. }
  391. };
  392. }));
  393. };
  394. var createSelectBoxItems = function (templates) {
  395. return map(templates, function (t) {
  396. return {
  397. text: t.text,
  398. value: t.text
  399. };
  400. });
  401. };
  402. var findTemplate = function (templates, templateTitle) {
  403. return find(templates, function (t) {
  404. return t.text === templateTitle;
  405. });
  406. };
  407. var loadFailedAlert = function (api) {
  408. editor.windowManager.alert('Could not load the specified template.', function () {
  409. return api.focus('template');
  410. });
  411. };
  412. var getTemplateContent = function (t) {
  413. return new global$4(function (resolve, reject) {
  414. t.value.url.fold(function () {
  415. return resolve(t.value.content.getOr(''));
  416. }, function (url) {
  417. return global$2.send({
  418. url: url,
  419. success: function (html) {
  420. resolve(html);
  421. },
  422. error: function (e) {
  423. reject(e);
  424. }
  425. });
  426. });
  427. });
  428. };
  429. var onChange = function (templates, updateDialog) {
  430. return function (api, change) {
  431. if (change.name === 'template') {
  432. var newTemplateTitle = api.getData().template;
  433. findTemplate(templates, newTemplateTitle).each(function (t) {
  434. api.block('Loading...');
  435. getTemplateContent(t).then(function (previewHtml) {
  436. updateDialog(api, t, previewHtml);
  437. }).catch(function () {
  438. updateDialog(api, t, '');
  439. api.disable('save');
  440. loadFailedAlert(api);
  441. });
  442. });
  443. }
  444. };
  445. };
  446. var onSubmit = function (templates) {
  447. return function (api) {
  448. var data = api.getData();
  449. findTemplate(templates, data.template).each(function (t) {
  450. getTemplateContent(t).then(function (previewHtml) {
  451. insertTemplate(editor, false, previewHtml);
  452. api.close();
  453. }).catch(function () {
  454. api.disable('save');
  455. loadFailedAlert(api);
  456. });
  457. });
  458. };
  459. };
  460. var openDialog = function (templates) {
  461. var selectBoxItems = createSelectBoxItems(templates);
  462. var buildDialogSpec = function (bodyItems, initialData) {
  463. return {
  464. title: 'Insert Template',
  465. size: 'large',
  466. body: {
  467. type: 'panel',
  468. items: bodyItems
  469. },
  470. initialData: initialData,
  471. buttons: [
  472. {
  473. type: 'cancel',
  474. name: 'cancel',
  475. text: 'Cancel'
  476. },
  477. {
  478. type: 'submit',
  479. name: 'save',
  480. text: 'Save',
  481. primary: true
  482. }
  483. ],
  484. onSubmit: onSubmit(templates),
  485. onChange: onChange(templates, updateDialog)
  486. };
  487. };
  488. var updateDialog = function (dialogApi, template, previewHtml) {
  489. var content = getPreviewContent(editor, previewHtml);
  490. var bodyItems = [
  491. {
  492. type: 'selectbox',
  493. name: 'template',
  494. label: 'Templates',
  495. items: selectBoxItems
  496. },
  497. {
  498. type: 'htmlpanel',
  499. html: '<p aria-live="polite">' + htmlEscape(template.value.description) + '</p>'
  500. },
  501. {
  502. label: 'Preview',
  503. type: 'iframe',
  504. name: 'preview',
  505. sandboxed: false
  506. }
  507. ];
  508. var initialData = {
  509. template: template.text,
  510. preview: content
  511. };
  512. dialogApi.unblock();
  513. dialogApi.redial(buildDialogSpec(bodyItems, initialData));
  514. dialogApi.focus('template');
  515. };
  516. var dialogApi = editor.windowManager.open(buildDialogSpec([], {
  517. template: '',
  518. preview: ''
  519. }));
  520. dialogApi.block('Loading...');
  521. getTemplateContent(templates[0]).then(function (previewHtml) {
  522. updateDialog(dialogApi, templates[0], previewHtml);
  523. }).catch(function () {
  524. updateDialog(dialogApi, templates[0], '');
  525. dialogApi.disable('save');
  526. loadFailedAlert(dialogApi);
  527. });
  528. };
  529. var optTemplates = createTemplates();
  530. optTemplates.each(openDialog);
  531. };
  532. var showDialog = function (editor) {
  533. return function (templates) {
  534. open(editor, templates);
  535. };
  536. };
  537. var register$1 = function (editor) {
  538. editor.ui.registry.addButton('template', {
  539. icon: 'template',
  540. tooltip: 'Insert template',
  541. onAction: createTemplateList(editor, showDialog(editor))
  542. });
  543. editor.ui.registry.addMenuItem('template', {
  544. icon: 'template',
  545. text: 'Insert template...',
  546. onAction: createTemplateList(editor, showDialog(editor))
  547. });
  548. };
  549. function Plugin () {
  550. global.add('template', function (editor) {
  551. register$1(editor);
  552. register(editor);
  553. setup(editor);
  554. });
  555. }
  556. Plugin();
  557. }());