-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
77 lines (65 loc) · 1.94 KB
/
lib.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const cheerio = require('cheerio');
const twemoji = require('twemoji');
// https://github.com/github/gemoji
const emojis = require('./emoji.json');
class CodeBlockExtractor {
constructor() {
this.cipher = '<!-- code block replacement -->';
this.codeCache = [];
}
extract(content) {
return content.replace(/```[a-z]*\n[\s\S]*?\n```|`[^`\n]+`/g, codeBlock => {
this.codeCache.push(codeBlock);
return this.cipher;
});
}
putBack(extracted) {
const regex = new RegExp(this.cipher, 'g');
let i = 0;
return extracted.replace(regex, ciphered => {
const result = this.codeCache[i] ? this.codeCache[i] : ciphered;
i++;
return result;
});
}
}
function shortcutToTwemoji(content, { classname = '', style = {} } = {}) {
const defaultStyle = {
height: `1em`,
width: `1em`,
margin: `0 .05em 0 .1em`,
'vertical-align': `-0.1em`
};
const mergedStyle = Object.assign({}, defaultStyle, style);
// replace shortcuts with unicode
const replaced = replaceShortcut(content, shortcut => {
const unicode = shortcutToUnicode(shortcut);
return unicode ? unicode : shortcut;
});
return parseTwemoji(replaced, classname, mergedStyle);
}
function replaceShortcut(content, replacement) {
let result = content;
content.replace(/(?=(:[\w\-+]+:))/g, (_, substr) => {
result = result.replace(substr, replacement);
});
return result;
}
function shortcutToUnicode(shortcut) {
const alias = shortcut.replace(/:/g, '');
const result = emojis.find(emoji => emoji.aliases.includes(alias));
return result ? result.emoji : null;
}
function parseTwemoji(content, classname, styles) {
const twitterEmoji = twemoji.parse(content);
const $ = cheerio.load(twitterEmoji, { xmlMode: true });
const $emojis = $('img.emoji');
$emojis.addClass(classname).css(styles);
return $.html();
}
module.exports = {
CodeBlockExtractor,
shortcutToTwemoji,
replaceShortcut,
shortcutToUnicode
};