-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
emojify.js
45 lines (40 loc) · 1.42 KB
/
emojify.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import emojiData from './emoji-data.js';
function replaceEmojiShorthand(m, $1, useNativeEmoji) {
const emojiMatch = emojiData.data[$1];
let result = m;
if (emojiMatch) {
if (useNativeEmoji && /unicode/.test(emojiMatch)) {
const emojiUnicode = emojiMatch
.replace('unicode/', '')
.replace(/\.png.*/, '')
.split('-')
.map(u => `&#x${u};`)
// Separate multi-character emoji with zero width joiner sequence (ZWJ)
// Hat tip: https://about.gitlab.com/blog/2018/05/30/journey-in-native-unicode-emoji/#emoji-made-up-of-multiple-characters
.join('‍')
.concat('︎');
result = `<span class="emoji">${emojiUnicode}</span>`;
} else {
result = `<img src="${emojiData.baseURL}${emojiMatch}.png" alt="${$1}" class="emoji" loading="lazy">`;
}
}
return result;
}
export function emojify(text, useNativeEmoji) {
return (
text
// Mark colons in tags
.replace(
/<(code|pre|script|template)[^>]*?>[\s\S]+?<\/(code|pre|script|template)>/g,
m => m.replace(/:/g, '__colon__')
)
// Mark colons in comments
.replace(/<!--[\s\S]+?-->/g, m => m.replace(/:/g, '__colon__'))
// Replace emoji shorthand codes
.replace(/:([a-z0-9_\-+]+?):/g, (m, $1) =>
replaceEmojiShorthand(m, $1, useNativeEmoji)
)
// Restore colons in tags and comments
.replace(/__colon__/g, ':')
);
}