emoji.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*jslint node: true*/
  2. var toArray = require('lodash/toArray');
  3. var emojiByName = require('./emoji.json');
  4. "use strict";
  5. /**
  6. * regex to parse emoji in a string - finds emoji, e.g. :coffee:
  7. */
  8. var emojiNameRegex = /:([a-zA-Z0-9_\-\+]+):/g;
  9. /**
  10. * regex to trim whitespace
  11. * use instead of String.prototype.trim() for IE8 support
  12. */
  13. var trimSpaceRegex = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
  14. /**
  15. * Removes colons on either side
  16. * of the string if present
  17. * @param {string} str
  18. * @return {string}
  19. */
  20. function stripColons (str) {
  21. var colonIndex = str.indexOf(':');
  22. if (colonIndex > -1) {
  23. // :emoji: (http://www.emoji-cheat-sheet.com/)
  24. if (colonIndex === str.length - 1) {
  25. str = str.substring(0, colonIndex);
  26. return stripColons(str);
  27. } else {
  28. str = str.substr(colonIndex + 1);
  29. return stripColons(str);
  30. }
  31. }
  32. return str;
  33. }
  34. /**
  35. * Adds colons to either side
  36. * of the string
  37. * @param {string} str
  38. * @return {string}
  39. */
  40. function wrapColons (str) {
  41. return (typeof str === 'string' && str.length > 0) ? ':' + str + ':' : str;
  42. }
  43. /**
  44. * Ensure that the word is wrapped in colons
  45. * by only adding them, if they are not there.
  46. * @param {string} str
  47. * @return {string}
  48. */
  49. function ensureColons (str) {
  50. return (typeof str === 'string' && str[0] !== ':') ? wrapColons(str) : str;
  51. }
  52. // Non spacing mark, some emoticons have them. It's the 'Variant Form',
  53. // which provides more information so that emoticons can be rendered as
  54. // more colorful graphics. FE0E is a unicode text version, where as FE0F
  55. // should be rendered as a graphical version. The code gracefully degrades.
  56. var NON_SPACING_MARK = String.fromCharCode(65039); // 65039 - '️' - 0xFE0F;
  57. var nonSpacingRegex = new RegExp(NON_SPACING_MARK, 'g')
  58. // Remove the non-spacing-mark from the code, never send a stripped version
  59. // to the client, as it kills graphical emoticons.
  60. function stripNSB (code) {
  61. return code.replace(nonSpacingRegex, '');
  62. };
  63. // Reversed hash table, where as emojiByName contains a { heart: '❤' }
  64. // dictionary emojiByCode contains { ❤: 'heart' }. The codes are normalized
  65. // to the text version.
  66. var emojiByCode = Object.keys(emojiByName).reduce(function(h,k) {
  67. h[stripNSB(emojiByName[k])] = k;
  68. return h;
  69. }, {});
  70. /**
  71. * Emoji namespace
  72. */
  73. var Emoji = {
  74. emoji: emojiByName,
  75. };
  76. /**
  77. * get emoji code from name. return emoji code back if code is passed in.
  78. * @param {string} emoji
  79. * @return {string}
  80. */
  81. Emoji._get = function _get (emoji) {
  82. if (emojiByCode[stripNSB(emoji)]) {
  83. return emoji;
  84. } else if (emojiByName.hasOwnProperty(emoji)) {
  85. return emojiByName[emoji];
  86. }
  87. return ensureColons(emoji);
  88. };
  89. /**
  90. * get emoji code from :emoji: string or name
  91. * @param {string} emoji
  92. * @return {string}
  93. */
  94. Emoji.get = function get (emoji) {
  95. emoji = stripColons(emoji);
  96. return Emoji._get(emoji);
  97. };
  98. /**
  99. * find the emoji by either code or name
  100. * @param {string} nameOrCode The emoji to find, either `coffee`, `:coffee:` or `☕`;
  101. * @return {object}
  102. */
  103. Emoji.find = function find (nameOrCode) {
  104. return Emoji.findByName(nameOrCode) || Emoji.findByCode(nameOrCode);
  105. };
  106. /**
  107. * find the emoji by name
  108. * @param {string} name The emoji to find either `coffee` or `:coffee:`;
  109. * @return {object}
  110. */
  111. Emoji.findByName = function findByName (name) {
  112. var stripped = stripColons(name);
  113. var emoji = emojiByName[stripped];
  114. return emoji ? ({ emoji: emoji, key: stripped }) : undefined;
  115. };
  116. /**
  117. * find the emoji by code (emoji)
  118. * @param {string} code The emoji to find; for example `☕` or `☔`
  119. * @return {object}
  120. */
  121. Emoji.findByCode = function findByCode (code) {
  122. var stripped = stripNSB(code);
  123. var name = emojiByCode[stripped];
  124. // lookup emoji to ensure the Variant Form is returned
  125. return name ? ({ emoji: emojiByName[name], key: name }) : undefined;
  126. };
  127. /**
  128. * Check if an emoji is known by this library
  129. * @param {string} nameOrCode The emoji to validate, either `coffee`, `:coffee:` or `☕`;
  130. * @return {object}
  131. */
  132. Emoji.hasEmoji = function hasEmoji (nameOrCode) {
  133. return Emoji.hasEmojiByName(nameOrCode) || Emoji.hasEmojiByCode(nameOrCode);
  134. };
  135. /**
  136. * Check if an emoji with given name is known by this library
  137. * @param {string} name The emoji to validate either `coffee` or `:coffee:`;
  138. * @return {object}
  139. */
  140. Emoji.hasEmojiByName = function hasEmojiByName (name) {
  141. var result = Emoji.findByName(name);
  142. return !!result && result.key === stripColons(name);
  143. };
  144. /**
  145. * Check if a given emoji is known by this library
  146. * @param {string} code The emoji to validate; for example `☕` or `☔`
  147. * @return {object}
  148. */
  149. Emoji.hasEmojiByCode = function hasEmojiByCode (code) {
  150. var result = Emoji.findByCode(code);
  151. return !!result && stripNSB(result.emoji) === stripNSB(code);
  152. };
  153. /**
  154. * get emoji name from code
  155. * @param {string} emoji
  156. * @param {boolean} includeColons should the result include the ::
  157. * @return {string}
  158. */
  159. Emoji.which = function which (emoji_code, includeColons) {
  160. var code = stripNSB(emoji_code);
  161. var word = emojiByCode[code];
  162. return includeColons ? wrapColons(word) : word;
  163. };
  164. /**
  165. * emojify a string (replace :emoji: with an emoji)
  166. * @param {string} str
  167. * @param {function} on_missing (gets emoji name without :: and returns a proper emoji if no emoji was found)
  168. * @param {function} format (wrap the returned emoji in a custom element)
  169. * @return {string}
  170. */
  171. Emoji.emojify = function emojify (str, on_missing, format) {
  172. if (!str) return '';
  173. return str.split(emojiNameRegex) // parse emoji via regex
  174. .map(function parseEmoji(s, i) {
  175. // every second element is an emoji, e.g. "test :fast_forward:" -> [ "test ", "fast_forward" ]
  176. if (i % 2 === 0) return s;
  177. var emoji = Emoji._get(s);
  178. var isMissing = emoji.indexOf(':') > -1;
  179. if (isMissing && typeof on_missing === 'function') {
  180. return on_missing(s);
  181. }
  182. if (!isMissing && typeof format === 'function') {
  183. return format(emoji, s);
  184. }
  185. return emoji;
  186. })
  187. .join('') // convert back to string
  188. ;
  189. };
  190. /**
  191. * return a random emoji
  192. * @return {string}
  193. */
  194. Emoji.random = function random () {
  195. var emojiKeys = Object.keys(emojiByName);
  196. var randomIndex = Math.floor(Math.random() * emojiKeys.length);
  197. var key = emojiKeys[randomIndex];
  198. var emoji = Emoji._get(key);
  199. return { key: key, emoji: emoji };
  200. }
  201. /**
  202. * return an collection of potential emoji matches
  203. * @param {string} str
  204. * @return {Array.<Object>}
  205. */
  206. Emoji.search = function search (str) {
  207. var emojiKeys = Object.keys(emojiByName);
  208. var matcher = stripColons(str)
  209. var matchingKeys = emojiKeys.filter(function(key) {
  210. return key.toString().indexOf(matcher) === 0;
  211. });
  212. return matchingKeys.map(function(key) {
  213. return {
  214. key: key,
  215. emoji: Emoji._get(key),
  216. };
  217. });
  218. }
  219. /**
  220. * unemojify a string (replace emoji with :emoji:)
  221. * @param {string} str
  222. * @return {string}
  223. */
  224. Emoji.unemojify = function unemojify (str) {
  225. if (!str) return '';
  226. var words = toArray(str);
  227. return words.map(function(word) {
  228. return Emoji.which(word, true) || word;
  229. }).join('');
  230. };
  231. /**
  232. * replace emojis with replacement value
  233. * @param {string} str
  234. * @param {function|string} the string or callback function to replace the emoji with
  235. * @param {boolean} should trailing whitespaces be cleaned? Defaults false
  236. * @return {string}
  237. */
  238. Emoji.replace = function replace (str, replacement, cleanSpaces) {
  239. if (!str) return '';
  240. var replace = typeof replacement === 'function' ? replacement : function() { return replacement; };
  241. var words = toArray(str);
  242. var replaced = words.map(function(word, idx) {
  243. var emoji = Emoji.findByCode(word);
  244. if (emoji && cleanSpaces && words[idx + 1] === ' ') {
  245. words[idx + 1] = '';
  246. }
  247. return emoji ? replace(emoji) : word;
  248. }).join('');
  249. return cleanSpaces ? replaced.replace(trimSpaceRegex, '') : replaced;
  250. };
  251. /**
  252. * remove all emojis from a string
  253. * @param {string} str
  254. * @return {string}
  255. */
  256. Emoji.strip = function strip (str) {
  257. return Emoji.replace(str, '', true);
  258. };
  259. module.exports = Emoji;