emoji.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { autoPlayGif } from '../../initial_state';
  2. import unicodeMapping from './emoji_unicode_mapping_light';
  3. import { assetHost } from 'mastodon/utils/config';
  4. import Trie from 'substring-trie';
  5. const trie = new Trie(Object.keys(unicodeMapping));
  6. // Convert to file names from emojis. (For different variation selector emojis)
  7. const emojiFilenames = (emojis) => {
  8. return emojis.map(v => unicodeMapping[v].filename);
  9. };
  10. // Emoji requiring extra borders depending on theme
  11. const darkEmoji = emojiFilenames(['🎱', '🐜', '⚫', '🖤', '⬛', '◼️', '◾', '◼️', '✒️', '▪️', '💣', '🎳', '📷', '📸', '♣️', '🕶️', '✴️', '🔌', '💂‍♀️', '📽️', '🍳', '🦍', '💂', '🔪', '🕳️', '🕹️', '🕋', '🖊️', '🖋️', '💂‍♂️', '🎤', '🎓', '🎥', '🎼', '♠️', '🎩', '🦃', '📼', '📹', '🎮', '🐃', '🏴', '🐞', '🕺', '📱', '📲', '🚲']);
  12. const lightEmoji = emojiFilenames(['👽', '⚾', '🐔', '☁️', '💨', '🕊️', '👀', '🍥', '👻', '🐐', '❕', '❔', '⛸️', '🌩️', '🔊', '🔇', '📃', '🌧️', '🐏', '🍚', '🍙', '🐓', '🐑', '💀', '☠️', '🌨️', '🔉', '🔈', '💬', '💭', '🏐', '🏳️', '⚪', '⬜', '◽', '◻️', '▫️']);
  13. const emojiFilename = (filename) => {
  14. const borderedEmoji = (document.body && document.body.classList.contains('theme-mastodon-light')) ? lightEmoji : darkEmoji;
  15. return borderedEmoji.includes(filename) ? (filename + '_border') : filename;
  16. };
  17. const domParser = new DOMParser();
  18. const emojifyTextNode = (node, customEmojis) => {
  19. let str = node.textContent;
  20. const fragment = new DocumentFragment();
  21. for (;;) {
  22. let match, i = 0;
  23. if (customEmojis === null) {
  24. while (i < str.length && !(match = trie.search(str.slice(i)))) {
  25. i += str.codePointAt(i) < 65536 ? 1 : 2;
  26. }
  27. } else {
  28. while (i < str.length && str[i] !== ':' && !(match = trie.search(str.slice(i)))) {
  29. i += str.codePointAt(i) < 65536 ? 1 : 2;
  30. }
  31. }
  32. let rend, replacement = '';
  33. if (i === str.length) {
  34. break;
  35. } else if (str[i] === ':') {
  36. if (!(() => {
  37. rend = str.indexOf(':', i + 1) + 1;
  38. if (!rend) return false; // no pair of ':'
  39. const shortname = str.slice(i, rend);
  40. // now got a replacee as ':shortname:'
  41. // if you want additional emoji handler, add statements below which set replacement and return true.
  42. if (shortname in customEmojis) {
  43. const filename = autoPlayGif ? customEmojis[shortname].url : customEmojis[shortname].static_url;
  44. replacement = `<img draggable="false" class="emojione custom-emoji" alt="${shortname}" title="${shortname}" src="${filename}" data-original="${customEmojis[shortname].url}" data-static="${customEmojis[shortname].static_url}" />`;
  45. return true;
  46. }
  47. return false;
  48. })()) rend = ++i;
  49. } else { // matched to unicode emoji
  50. const { filename, shortCode } = unicodeMapping[match];
  51. const title = shortCode ? `:${shortCode}:` : '';
  52. replacement = `<img draggable="false" class="emojione" alt="${match}" title="${title}" src="${assetHost}/emoji/${emojiFilename(filename)}.svg" />`;
  53. rend = i + match.length;
  54. // If the matched character was followed by VS15 (for selecting text presentation), skip it.
  55. if (str.codePointAt(rend) === 65038) {
  56. rend += 1;
  57. }
  58. }
  59. fragment.append(document.createTextNode(str.slice(0, i)));
  60. if (replacement) {
  61. fragment.append(domParser.parseFromString(replacement, 'text/html').documentElement.getElementsByTagName('img')[0]);
  62. }
  63. node.textContent = str.slice(0, i);
  64. str = str.slice(rend);
  65. }
  66. fragment.append(document.createTextNode(str));
  67. node.parentElement.replaceChild(fragment, node);
  68. };
  69. const emojifyNode = (node, customEmojis) => {
  70. for (const child of node.childNodes) {
  71. switch(child.nodeType) {
  72. case Node.TEXT_NODE:
  73. emojifyTextNode(child, customEmojis);
  74. break;
  75. case Node.ELEMENT_NODE:
  76. if (!child.classList.contains('invisible'))
  77. emojifyNode(child, customEmojis);
  78. break;
  79. }
  80. }
  81. };
  82. const emojify = (str, customEmojis = {}) => {
  83. const wrapper = document.createElement('div');
  84. wrapper.innerHTML = str;
  85. if (!Object.keys(customEmojis).length)
  86. customEmojis = null;
  87. emojifyNode(wrapper, customEmojis);
  88. return wrapper.innerHTML;
  89. };
  90. export default emojify;
  91. export const buildCustomEmojis = (customEmojis) => {
  92. const emojis = [];
  93. customEmojis.forEach(emoji => {
  94. const shortcode = emoji.get('shortcode');
  95. const url = autoPlayGif ? emoji.get('url') : emoji.get('static_url');
  96. const name = shortcode.replace(':', '');
  97. emojis.push({
  98. id: name,
  99. name,
  100. short_names: [name],
  101. text: '',
  102. emoticons: [],
  103. keywords: [name],
  104. imageUrl: url,
  105. custom: true,
  106. customCategory: emoji.get('category'),
  107. });
  108. });
  109. return emojis;
  110. };
  111. export const categoriesFromEmojis = customEmojis => customEmojis.reduce((set, emoji) => set.add(emoji.get('category') ? `custom-${emoji.get('category')}` : 'custom'), new Set(['custom']));