]> cat aescling's git repositories - mastodon.git/blob - app/javascript/mastodon/emoji.js
Add emoji autosuggest (#5053)
[mastodon.git] / app / javascript / mastodon / emoji.js
1 import { unicodeMapping } from './emojione_light';
2 import Trie from 'substring-trie';
3
4 const trie = new Trie(Object.keys(unicodeMapping));
5
6 const assetHost = process.env.CDN_HOST || '';
7
8 const emojify = (str, customEmojis = {}) => {
9 let rtn = '';
10 for (;;) {
11 let match, i = 0, tag;
12 while (i < str.length && (tag = '<&'.indexOf(str[i])) === -1 && str[i] !== ':' && !(match = trie.search(str.slice(i)))) {
13 i += str.codePointAt(i) < 65536 ? 1 : 2;
14 }
15 if (i === str.length)
16 break;
17 else if (tag >= 0) {
18 const tagend = str.indexOf('>;'[tag], i + 1) + 1;
19 if (!tagend)
20 break;
21 rtn += str.slice(0, tagend);
22 str = str.slice(tagend);
23 } else if (str[i] === ':') {
24 try {
25 // if replacing :shortname: succeed, exit this block with "continue"
26 const closeColon = str.indexOf(':', i + 1) + 1;
27 if (!closeColon) throw null; // no pair of ':'
28 const lt = str.indexOf('<', i + 1);
29 if (!(lt === -1 || lt >= closeColon)) throw null; // tag appeared before closing ':'
30 const shortname = str.slice(i, closeColon);
31 if (shortname in customEmojis) {
32 rtn += str.slice(0, i) + `<img draggable="false" class="emojione" alt="${shortname}" title="${shortname}" src="${customEmojis[shortname]}" />`;
33 str = str.slice(closeColon);
34 continue;
35 }
36 } catch (e) {}
37 // replacing :shortname: failed
38 rtn += str.slice(0, i + 1);
39 str = str.slice(i + 1);
40 } else {
41 const [filename, shortCode] = unicodeMapping[match];
42 rtn += str.slice(0, i) + `<img draggable="false" class="emojione" alt="${match}" title=":${shortCode}:" src="${assetHost}/emoji/${filename}.svg" />`;
43 str = str.slice(i + match.length);
44 }
45 }
46 return rtn + str;
47 };
48
49 export default emojify;
50
51 export const buildCustomEmojis = customEmojis => {
52 const emojis = [];
53
54 customEmojis.forEach(emoji => {
55 const shortcode = emoji.get('shortcode');
56 const url = emoji.get('url');
57 const name = shortcode.replace(':', '');
58
59 emojis.push({
60 id: name,
61 name,
62 short_names: [name],
63 text: '',
64 emoticons: [],
65 keywords: [name],
66 imageUrl: url,
67 custom: true,
68 });
69 });
70
71 return emojis;
72 };
This page took 0.094551 seconds and 4 git commands to generate.