generate-emoji-shortcodes.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const fetch = require('node-fetch');
  2. const fs = require('fs');
  3. const prettier = require('prettier');
  4. function writeFile(path, contents) {
  5. return new Promise((resolve, reject) => {
  6. fs.writeFile(path, contents, err => {
  7. if (err) reject(err);
  8. resolve();
  9. });
  10. });
  11. }
  12. async function writeMapping(data) {
  13. const contents = `const emojiShortcodes = ${JSON.stringify(data, null, 2)};
  14. export type Shortcode = keyof typeof emojiShortcodes;
  15. export default emojiShortcodes;`;
  16. const configFile = await prettier.resolveConfigFile(
  17. 'src/utils/emojiShortcodes.ts'
  18. );
  19. const config = await prettier.resolveConfig(configFile);
  20. const formattedContents = prettier.format(contents, {
  21. ...config,
  22. parser: 'typescript'
  23. });
  24. await writeFile('src/utils/emojiShortcodes.ts', formattedContents);
  25. }
  26. function fullyQualified(line) {
  27. return line.includes('; fully-qualified');
  28. }
  29. function slugify(text) {
  30. return text
  31. .toString()
  32. .toLowerCase()
  33. .replace(/\s+/g, '-') // Replace spaces with -
  34. .replace(/[^\w\-]+/g, '') // Remove all non-word chars
  35. .replace(/\-\-+/g, '-') // Replace multiple - with single -
  36. .replace(/^-+/, '') // Trim - from start of text
  37. .replace(/-+$/, ''); // Trim - from end of text
  38. }
  39. function parseEmoji(l) {
  40. const components = l
  41. .split(';')[0]
  42. .trim()
  43. .split(' ');
  44. const emoji = components
  45. .map(s => String.fromCodePoint(parseInt(s, 16)))
  46. .join('');
  47. const description = l.split('#')[1];
  48. const shortcode = `:${slugify(description)}:`;
  49. return { shortcode, emoji };
  50. }
  51. (async () => {
  52. const res = await fetch(
  53. 'https://unicode.org/Public/emoji/12.0/emoji-test.txt'
  54. );
  55. const rawData = await res.text();
  56. const lines = rawData.split('\n');
  57. const parsedEmoji = lines.filter(fullyQualified).map(parseEmoji);
  58. const mapping = parsedEmoji.reduce((a, b) => {
  59. a[b.shortcode] = b.emoji;
  60. return a;
  61. }, {});
  62. await writeMapping(mapping);
  63. })();