emojify.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Sapphire
  3. *
  4. * Copyright (C) 2018 Alyssa Rosenzweig
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
  19. *
  20. */
  21. /* Utility for transforming plain text into emojified version */
  22. window.emojify = function(text) {
  23. return emoticonToEmojify(colonEmojify(text));
  24. };
  25. /* Transform :emoji: to its Unicode equivalent */
  26. const colonEmojify = function(text) {
  27. return text.replace(/:[^ :]*:/g, (pattern) => {
  28. const raw = pattern.slice(1, -1).toLowerCase();
  29. /* Put it into the two normal forms, underscores or hyphen, and try
  30. * each */
  31. const underscore = raw.replace(/-/g, '_');
  32. if (window.EMOJIS[underscore])
  33. return window.EMOJIS[underscore];
  34. const hyphen = raw.replace(/_/g, '-');
  35. if (window.EMOJIS[hyphen])
  36. return window.EMOJIS[hyphen];
  37. /* Try it as a country name */
  38. const spaced = raw.replace(/[-_]/g, ' ');
  39. const country = window.COUNTRY_NAME_TO_ID[spaced];
  40. if (country) {
  41. const flagName = 'flag-' + country;
  42. if (window.EMOJIS[flagName])
  43. return window.EMOJIS[flagName];
  44. }
  45. /* Otherwise, give up and return as-is */
  46. return pattern;
  47. });
  48. };
  49. /* Transform :p to Unicode */
  50. const emoticonToEmojify = function(s) {
  51. return s.split(' ').map(w => window.EMOTICON_TO_UNICODE[w] || w).join(' ');
  52. };