plugin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /**
  2. * TinyMCE version 6.0.3 (2022-05-25)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global$1 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  7. const eq = t => a => t === a;
  8. const isNull = eq(null);
  9. const isNullable = a => a === null || a === undefined;
  10. const isNonNullable = a => !isNullable(a);
  11. const noop = () => {
  12. };
  13. const constant = value => {
  14. return () => {
  15. return value;
  16. };
  17. };
  18. const never = constant(false);
  19. class Optional {
  20. constructor(tag, value) {
  21. this.tag = tag;
  22. this.value = value;
  23. }
  24. static some(value) {
  25. return new Optional(true, value);
  26. }
  27. static none() {
  28. return Optional.singletonNone;
  29. }
  30. fold(onNone, onSome) {
  31. if (this.tag) {
  32. return onSome(this.value);
  33. } else {
  34. return onNone();
  35. }
  36. }
  37. isSome() {
  38. return this.tag;
  39. }
  40. isNone() {
  41. return !this.tag;
  42. }
  43. map(mapper) {
  44. if (this.tag) {
  45. return Optional.some(mapper(this.value));
  46. } else {
  47. return Optional.none();
  48. }
  49. }
  50. bind(binder) {
  51. if (this.tag) {
  52. return binder(this.value);
  53. } else {
  54. return Optional.none();
  55. }
  56. }
  57. exists(predicate) {
  58. return this.tag && predicate(this.value);
  59. }
  60. forall(predicate) {
  61. return !this.tag || predicate(this.value);
  62. }
  63. filter(predicate) {
  64. if (!this.tag || predicate(this.value)) {
  65. return this;
  66. } else {
  67. return Optional.none();
  68. }
  69. }
  70. getOr(replacement) {
  71. return this.tag ? this.value : replacement;
  72. }
  73. or(replacement) {
  74. return this.tag ? this : replacement;
  75. }
  76. getOrThunk(thunk) {
  77. return this.tag ? this.value : thunk();
  78. }
  79. orThunk(thunk) {
  80. return this.tag ? this : thunk();
  81. }
  82. getOrDie(message) {
  83. if (!this.tag) {
  84. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  85. } else {
  86. return this.value;
  87. }
  88. }
  89. static from(value) {
  90. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  91. }
  92. getOrNull() {
  93. return this.tag ? this.value : null;
  94. }
  95. getOrUndefined() {
  96. return this.value;
  97. }
  98. each(worker) {
  99. if (this.tag) {
  100. worker(this.value);
  101. }
  102. }
  103. toArray() {
  104. return this.tag ? [this.value] : [];
  105. }
  106. toString() {
  107. return this.tag ? `some(${ this.value })` : 'none()';
  108. }
  109. }
  110. Optional.singletonNone = new Optional(false);
  111. const exists = (xs, pred) => {
  112. for (let i = 0, len = xs.length; i < len; i++) {
  113. const x = xs[i];
  114. if (pred(x, i)) {
  115. return true;
  116. }
  117. }
  118. return false;
  119. };
  120. const map$1 = (xs, f) => {
  121. const len = xs.length;
  122. const r = new Array(len);
  123. for (let i = 0; i < len; i++) {
  124. const x = xs[i];
  125. r[i] = f(x, i);
  126. }
  127. return r;
  128. };
  129. const each$1 = (xs, f) => {
  130. for (let i = 0, len = xs.length; i < len; i++) {
  131. const x = xs[i];
  132. f(x, i);
  133. }
  134. };
  135. const Cell = initial => {
  136. let value = initial;
  137. const get = () => {
  138. return value;
  139. };
  140. const set = v => {
  141. value = v;
  142. };
  143. return {
  144. get,
  145. set
  146. };
  147. };
  148. const last = (fn, rate) => {
  149. let timer = null;
  150. const cancel = () => {
  151. if (!isNull(timer)) {
  152. clearTimeout(timer);
  153. timer = null;
  154. }
  155. };
  156. const throttle = (...args) => {
  157. cancel();
  158. timer = setTimeout(() => {
  159. timer = null;
  160. fn.apply(null, args);
  161. }, rate);
  162. };
  163. return {
  164. cancel,
  165. throttle
  166. };
  167. };
  168. const insertEmoticon = (editor, ch) => {
  169. editor.insertContent(ch);
  170. };
  171. const keys = Object.keys;
  172. const hasOwnProperty = Object.hasOwnProperty;
  173. const each = (obj, f) => {
  174. const props = keys(obj);
  175. for (let k = 0, len = props.length; k < len; k++) {
  176. const i = props[k];
  177. const x = obj[i];
  178. f(x, i);
  179. }
  180. };
  181. const map = (obj, f) => {
  182. return tupleMap(obj, (x, i) => ({
  183. k: i,
  184. v: f(x, i)
  185. }));
  186. };
  187. const tupleMap = (obj, f) => {
  188. const r = {};
  189. each(obj, (x, i) => {
  190. const tuple = f(x, i);
  191. r[tuple.k] = tuple.v;
  192. });
  193. return r;
  194. };
  195. const has = (obj, key) => hasOwnProperty.call(obj, key);
  196. const shallow = (old, nu) => {
  197. return nu;
  198. };
  199. const baseMerge = merger => {
  200. return (...objects) => {
  201. if (objects.length === 0) {
  202. throw new Error(`Can't merge zero objects`);
  203. }
  204. const ret = {};
  205. for (let j = 0; j < objects.length; j++) {
  206. const curObject = objects[j];
  207. for (const key in curObject) {
  208. if (has(curObject, key)) {
  209. ret[key] = merger(ret[key], curObject[key]);
  210. }
  211. }
  212. }
  213. return ret;
  214. };
  215. };
  216. const merge = baseMerge(shallow);
  217. const singleton = doRevoke => {
  218. const subject = Cell(Optional.none());
  219. const revoke = () => subject.get().each(doRevoke);
  220. const clear = () => {
  221. revoke();
  222. subject.set(Optional.none());
  223. };
  224. const isSet = () => subject.get().isSome();
  225. const get = () => subject.get();
  226. const set = s => {
  227. revoke();
  228. subject.set(Optional.some(s));
  229. };
  230. return {
  231. clear,
  232. isSet,
  233. get,
  234. set
  235. };
  236. };
  237. const value = () => {
  238. const subject = singleton(noop);
  239. const on = f => subject.get().each(f);
  240. return {
  241. ...subject,
  242. on
  243. };
  244. };
  245. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  246. const contains = (str, substr) => {
  247. return str.indexOf(substr) !== -1;
  248. };
  249. const startsWith = (str, prefix) => {
  250. return checkRange(str, prefix, 0);
  251. };
  252. var global = tinymce.util.Tools.resolve('tinymce.Resource');
  253. const DEFAULT_ID = 'tinymce.plugins.emoticons';
  254. const option = name => editor => editor.options.get(name);
  255. const register$2 = (editor, pluginUrl) => {
  256. const registerOption = editor.options.register;
  257. registerOption('emoticons_database', {
  258. processor: 'string',
  259. default: 'emojis'
  260. });
  261. registerOption('emoticons_database_url', {
  262. processor: 'string',
  263. default: `${ pluginUrl }/js/${ getEmojiDatabase(editor) }${ editor.suffix }.js`
  264. });
  265. registerOption('emoticons_database_id', {
  266. processor: 'string',
  267. default: DEFAULT_ID
  268. });
  269. registerOption('emoticons_append', {
  270. processor: 'object',
  271. default: {}
  272. });
  273. registerOption('emoticons_images_url', {
  274. processor: 'string',
  275. default: 'https://twemoji.maxcdn.com/v/13.0.1/72x72/'
  276. });
  277. };
  278. const getEmojiDatabase = option('emoticons_database');
  279. const getEmojiDatabaseUrl = option('emoticons_database_url');
  280. const getEmojiDatabaseId = option('emoticons_database_id');
  281. const getAppendedEmoji = option('emoticons_append');
  282. const getEmojiImageUrl = option('emoticons_images_url');
  283. const ALL_CATEGORY = 'All';
  284. const categoryNameMap = {
  285. symbols: 'Symbols',
  286. people: 'People',
  287. animals_and_nature: 'Animals and Nature',
  288. food_and_drink: 'Food and Drink',
  289. activity: 'Activity',
  290. travel_and_places: 'Travel and Places',
  291. objects: 'Objects',
  292. flags: 'Flags',
  293. user: 'User Defined'
  294. };
  295. const translateCategory = (categories, name) => has(categories, name) ? categories[name] : name;
  296. const getUserDefinedEmoji = editor => {
  297. const userDefinedEmoticons = getAppendedEmoji(editor);
  298. return map(userDefinedEmoticons, value => ({
  299. keywords: [],
  300. category: 'user',
  301. ...value
  302. }));
  303. };
  304. const initDatabase = (editor, databaseUrl, databaseId) => {
  305. const categories = value();
  306. const all = value();
  307. const emojiImagesUrl = getEmojiImageUrl(editor);
  308. const getEmoji = lib => {
  309. if (startsWith(lib.char, '<img')) {
  310. return lib.char.replace(/src="([^"]+)"/, (match, url) => `src="${ emojiImagesUrl }${ url }"`);
  311. } else {
  312. return lib.char;
  313. }
  314. };
  315. const processEmojis = emojis => {
  316. const cats = {};
  317. const everything = [];
  318. each(emojis, (lib, title) => {
  319. const entry = {
  320. title,
  321. keywords: lib.keywords,
  322. char: getEmoji(lib),
  323. category: translateCategory(categoryNameMap, lib.category)
  324. };
  325. const current = cats[entry.category] !== undefined ? cats[entry.category] : [];
  326. cats[entry.category] = current.concat([entry]);
  327. everything.push(entry);
  328. });
  329. categories.set(cats);
  330. all.set(everything);
  331. };
  332. editor.on('init', () => {
  333. global.load(databaseId, databaseUrl).then(emojis => {
  334. const userEmojis = getUserDefinedEmoji(editor);
  335. processEmojis(merge(emojis, userEmojis));
  336. }, err => {
  337. console.log(`Failed to load emojis: ${ err }`);
  338. categories.set({});
  339. all.set([]);
  340. });
  341. });
  342. const listCategory = category => {
  343. if (category === ALL_CATEGORY) {
  344. return listAll();
  345. }
  346. return categories.get().bind(cats => Optional.from(cats[category])).getOr([]);
  347. };
  348. const listAll = () => all.get().getOr([]);
  349. const listCategories = () => [ALL_CATEGORY].concat(keys(categories.get().getOr({})));
  350. const waitForLoad = () => {
  351. if (hasLoaded()) {
  352. return Promise.resolve(true);
  353. } else {
  354. return new Promise((resolve, reject) => {
  355. let numRetries = 15;
  356. const interval = setInterval(() => {
  357. if (hasLoaded()) {
  358. clearInterval(interval);
  359. resolve(true);
  360. } else {
  361. numRetries--;
  362. if (numRetries < 0) {
  363. console.log('Could not load emojis from url: ' + databaseUrl);
  364. clearInterval(interval);
  365. reject(false);
  366. }
  367. }
  368. }, 100);
  369. });
  370. }
  371. };
  372. const hasLoaded = () => categories.isSet() && all.isSet();
  373. return {
  374. listCategories,
  375. hasLoaded,
  376. waitForLoad,
  377. listAll,
  378. listCategory
  379. };
  380. };
  381. const emojiMatches = (emoji, lowerCasePattern) => contains(emoji.title.toLowerCase(), lowerCasePattern) || exists(emoji.keywords, k => contains(k.toLowerCase(), lowerCasePattern));
  382. const emojisFrom = (list, pattern, maxResults) => {
  383. const matches = [];
  384. const lowerCasePattern = pattern.toLowerCase();
  385. const reachedLimit = maxResults.fold(() => never, max => size => size >= max);
  386. for (let i = 0; i < list.length; i++) {
  387. if (pattern.length === 0 || emojiMatches(list[i], lowerCasePattern)) {
  388. matches.push({
  389. value: list[i].char,
  390. text: list[i].title,
  391. icon: list[i].char
  392. });
  393. if (reachedLimit(matches.length)) {
  394. break;
  395. }
  396. }
  397. }
  398. return matches;
  399. };
  400. const patternName = 'pattern';
  401. const open = (editor, database) => {
  402. const initialState = {
  403. pattern: '',
  404. results: emojisFrom(database.listAll(), '', Optional.some(300))
  405. };
  406. const currentTab = Cell(ALL_CATEGORY);
  407. const scan = dialogApi => {
  408. const dialogData = dialogApi.getData();
  409. const category = currentTab.get();
  410. const candidates = database.listCategory(category);
  411. const results = emojisFrom(candidates, dialogData[patternName], category === ALL_CATEGORY ? Optional.some(300) : Optional.none());
  412. dialogApi.setData({ results });
  413. };
  414. const updateFilter = last(dialogApi => {
  415. scan(dialogApi);
  416. }, 200);
  417. const searchField = {
  418. label: 'Search',
  419. type: 'input',
  420. name: patternName
  421. };
  422. const resultsField = {
  423. type: 'collection',
  424. name: 'results'
  425. };
  426. const getInitialState = () => {
  427. const body = {
  428. type: 'tabpanel',
  429. tabs: map$1(database.listCategories(), cat => ({
  430. title: cat,
  431. name: cat,
  432. items: [
  433. searchField,
  434. resultsField
  435. ]
  436. }))
  437. };
  438. return {
  439. title: 'Emojis',
  440. size: 'normal',
  441. body,
  442. initialData: initialState,
  443. onTabChange: (dialogApi, details) => {
  444. currentTab.set(details.newTabName);
  445. updateFilter.throttle(dialogApi);
  446. },
  447. onChange: updateFilter.throttle,
  448. onAction: (dialogApi, actionData) => {
  449. if (actionData.name === 'results') {
  450. insertEmoticon(editor, actionData.value);
  451. dialogApi.close();
  452. }
  453. },
  454. buttons: [{
  455. type: 'cancel',
  456. text: 'Close',
  457. primary: true
  458. }]
  459. };
  460. };
  461. const dialogApi = editor.windowManager.open(getInitialState());
  462. dialogApi.focus(patternName);
  463. if (!database.hasLoaded()) {
  464. dialogApi.block('Loading emojis...');
  465. database.waitForLoad().then(() => {
  466. dialogApi.redial(getInitialState());
  467. updateFilter.throttle(dialogApi);
  468. dialogApi.focus(patternName);
  469. dialogApi.unblock();
  470. }).catch(_err => {
  471. dialogApi.redial({
  472. title: 'Emojis',
  473. body: {
  474. type: 'panel',
  475. items: [{
  476. type: 'alertbanner',
  477. level: 'error',
  478. icon: 'warning',
  479. text: 'Could not load emojis'
  480. }]
  481. },
  482. buttons: [{
  483. type: 'cancel',
  484. text: 'Close',
  485. primary: true
  486. }],
  487. initialData: {
  488. pattern: '',
  489. results: []
  490. }
  491. });
  492. dialogApi.focus(patternName);
  493. dialogApi.unblock();
  494. });
  495. }
  496. };
  497. const register$1 = (editor, database) => {
  498. editor.addCommand('mceEmoticons', () => open(editor, database));
  499. };
  500. const setup = editor => {
  501. editor.on('PreInit', () => {
  502. editor.parser.addAttributeFilter('data-emoticon', nodes => {
  503. each$1(nodes, node => {
  504. node.attr('data-mce-resize', 'false');
  505. node.attr('data-mce-placeholder', '1');
  506. });
  507. });
  508. });
  509. };
  510. const init = (editor, database) => {
  511. editor.ui.registry.addAutocompleter('emoticons', {
  512. ch: ':',
  513. columns: 'auto',
  514. minChars: 2,
  515. fetch: (pattern, maxResults) => database.waitForLoad().then(() => {
  516. const candidates = database.listAll();
  517. return emojisFrom(candidates, pattern, Optional.some(maxResults));
  518. }),
  519. onAction: (autocompleteApi, rng, value) => {
  520. editor.selection.setRng(rng);
  521. editor.insertContent(value);
  522. autocompleteApi.hide();
  523. }
  524. });
  525. };
  526. const register = editor => {
  527. const onAction = () => editor.execCommand('mceEmoticons');
  528. editor.ui.registry.addButton('emoticons', {
  529. tooltip: 'Emojis',
  530. icon: 'emoji',
  531. onAction
  532. });
  533. editor.ui.registry.addMenuItem('emoticons', {
  534. text: 'Emojis...',
  535. icon: 'emoji',
  536. onAction
  537. });
  538. };
  539. var Plugin = () => {
  540. global$1.add('emoticons', (editor, pluginUrl) => {
  541. register$2(editor, pluginUrl);
  542. const databaseUrl = getEmojiDatabaseUrl(editor);
  543. const databaseId = getEmojiDatabaseId(editor);
  544. const database = initDatabase(editor, databaseUrl, databaseId);
  545. register$1(editor, database);
  546. register(editor);
  547. init(editor, database);
  548. setup(editor);
  549. });
  550. };
  551. Plugin();
  552. })();