You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.5 KiB

  1. import unicodeMapping from './emoji_unicode_mapping_light';
  2. import Trie from 'substring-trie';
  3. const trie = new Trie(Object.keys(unicodeMapping));
  4. const assetHost = process.env.CDN_HOST || '';
  5. let allowAnimations = false;
  6. const emojify = (str, customEmojis = {}) => {
  7. let rtn = '';
  8. for (;;) {
  9. let match, i = 0, tag;
  10. while (i < str.length && (tag = '<&:'.indexOf(str[i])) === -1 && !(match = trie.search(str.slice(i)))) {
  11. i += str.codePointAt(i) < 65536 ? 1 : 2;
  12. }
  13. let rend, replacement = '';
  14. if (i === str.length) {
  15. break;
  16. } else if (str[i] === ':') {
  17. if (!(() => {
  18. rend = str.indexOf(':', i + 1) + 1;
  19. if (!rend) return false; // no pair of ':'
  20. const lt = str.indexOf('<', i + 1);
  21. if (!(lt === -1 || lt >= rend)) return false; // tag appeared before closing ':'
  22. const shortname = str.slice(i, rend);
  23. // now got a replacee as ':shortname:'
  24. // if you want additional emoji handler, add statements below which set replacement and return true.
  25. if (shortname in customEmojis) {
  26. const filename = allowAnimations ? customEmojis[shortname].url : customEmojis[shortname].static_url;
  27. replacement = `<img draggable="false" class="emojione" alt="${shortname}" title="${shortname}" src="${filename}" />`;
  28. return true;
  29. }
  30. return false;
  31. })()) rend = ++i;
  32. } else if (tag >= 0) { // <, &
  33. rend = str.indexOf('>;'[tag], i + 1) + 1;
  34. if (!rend) break;
  35. i = rend;
  36. } else { // matched to unicode emoji
  37. const { filename, shortCode } = unicodeMapping[match];
  38. const title = shortCode ? `:${shortCode}:` : '';
  39. replacement = `<img draggable="false" class="emojione" alt="${match}" title="${title}" src="${assetHost}/emoji/${filename}.svg" />`;
  40. rend = i + match.length;
  41. }
  42. rtn += str.slice(0, i) + replacement;
  43. str = str.slice(rend);
  44. }
  45. return rtn + str;
  46. };
  47. export default emojify;
  48. export const buildCustomEmojis = (customEmojis, overrideAllowAnimations = false) => {
  49. const emojis = [];
  50. allowAnimations = overrideAllowAnimations;
  51. customEmojis.forEach(emoji => {
  52. const shortcode = emoji.get('shortcode');
  53. const url = allowAnimations ? emoji.get('url') : emoji.get('static_url');
  54. const name = shortcode.replace(':', '');
  55. emojis.push({
  56. id: name,
  57. name,
  58. short_names: [name],
  59. text: '',
  60. emoticons: [],
  61. keywords: [name],
  62. imageUrl: url,
  63. custom: true,
  64. });
  65. });
  66. return emojis;
  67. };