-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
98 lines (81 loc) · 2.72 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* global hexo */
'use strict'
const _ = require('lodash');
const path = require('path');
const fs = require('fs');
var options = Object.assign({
enable : true,
className: 'emoji',
}, hexo.config.emoji);
if (options.enable !== false) {
const emojis = Object.assign(
require('./emojis.json'),
loadCustomEmojis(options.customEmojis || options.localEmojis)
);
fs.writeFile(
path.join(__dirname, 'emojis.json'),
JSON.stringify(emojis),
function (err) { err && console.warn(err) }
);
hexo.extend.filter.register('before_post_render', data => {
if (data['no-emoji']) return data;
data.content = data.content.replace(
/:(\w+):/ig,
(match, p1) => emojis[p1] ? renderEmoji(emojis, p1) : match
);
return data;
});
hexo.extend.helper.register('emoji', name => renderEmoji(emojis, name));
hexo.extend.tag.register('emoji', args => renderEmoji(emojis, args[0]));
}
function loadCustomEmojis(customEmojis) {
// JSON string
if (_.isString(customEmojis)) {
try {
customEmojis = JSON.parse(customEmojis);
Object.keys(customEmojis).forEach(name => {
if (_.isString(customEmojis[name])) {
customEmojis[name] = {
src: customEmojis[name],
}
}
});
} catch (err) {
customEmojis = {};
console.warn('hexo-filter-emoji: Custom emojis not valid. Skipped.');
}
}
if (!_.isObject(customEmojis)) {
customEmojis = {};
}
Object.values(customEmojis).forEach(emoji => {
if (emoji.codepoints && !_.isArray(emoji.codepoints)) {
emoji.codepoints = emoji.codepoints.split(' ');
}
});
}
function renderEmoji(emojis, name) {
if (!emojis[name]) return name;
const styles = _.isObject(options.styles)
? Object.keys(options.styles)
.filter(k => _.isString(options.styles[k]))
.map(k => k + ': ' + options.styles[k])
: [];
//styles.push(`background-image: url(${emojis[name].src})`);
var codepoints;
if (emojis[name].codepoints && emojis[name].codepoints.length > 1) {
// 对于多个 codepoint 组成的 emoji 添加连接符或修饰符
var firstCode = emojis[name].codepoints[0];
if ((firstCode >= '0030' && firstCode <= '0039') || ['002a', '0023'].includes(firstCode)) {
// 数字或符号(#,*)
codepoints = emojis[name].codepoints.map(c => `&#x${c};`).join('️');
} else {
codepoints = emojis[name].codepoints.map(c => `&#x${c};`).join('️‍');
}
} else {
codepoints = emojis[name].codepoints
? emojis[name].codepoints.map(c => `&#x${c};`).join('')
: ' ';
}
return `<span class="${options.className}" alias="${name}" style="${styles.join('; ')}" fallback-src="${emojis[name].src}">${codepoints}</span>`;
}