闭社主体 forked from https://github.com/tootsuite/mastodon
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.

34 lines
1.3 KiB

  1. import { unicodeToFilename } from './emojione_light';
  2. import Trie from 'substring-trie';
  3. const trie = new Trie(Object.keys(unicodeToFilename));
  4. function emojify(str) {
  5. // This walks through the string from start to end, ignoring any tags (<p>, <br>, etc.)
  6. // and replacing valid unicode strings
  7. // that _aren't_ within tags with an <img> version.
  8. // The goal is to be the same as an emojione.regUnicode replacement, but faster.
  9. let i = -1;
  10. let insideTag = false;
  11. let match;
  12. while (++i < str.length) {
  13. const char = str.charAt(i);
  14. if (insideTag && char === '>') {
  15. insideTag = false;
  16. } else if (char === '<') {
  17. insideTag = true;
  18. } else if (!insideTag && (match = trie.search(str.substring(i)))) {
  19. const unicodeStr = match;
  20. if (unicodeStr in unicodeToFilename) {
  21. const filename = unicodeToFilename[unicodeStr];
  22. const alt = unicodeStr;
  23. const replacement = `<img draggable="false" class="emojione" alt="${alt}" src="/emoji/${filename}.svg" />`;
  24. str = str.substring(0, i) + replacement + str.substring(i + unicodeStr.length);
  25. i += (replacement.length - unicodeStr.length); // jump ahead the length we've added to the string
  26. }
  27. }
  28. }
  29. return str;
  30. }
  31. export default emojify;