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
|
import _ from 'lodash';
import { Node } from 'unist';
import { visitParents } from 'unist-util-visit-parents'
const emojiPlugin = (emojiFileNames: string[]) => () => {
const visitor = (node: any, ancestors: any[]) => {
const parent = _.last(ancestors);
const nodeIndex = parent?.children.indexOf(node);
const text: string = node.value;
const match = text?.match(/(:.*?:)/);
if (match && match.index !== undefined) {
const emoji = match[0]?.replaceAll(':', '') || '';
const src = emojiFileNames.find(fileName => fileName.match(`${emoji}.*`));
if (src) {
const beforeNode = {
type: 'text',
value: text.slice(0, match.index),
}
const emojiNode = {
type: 'element',
tagName: 'emoji',
children: [{
type: 'text',
value: src,
}],
}
const afterNode = {
type: 'text',
value: text.slice(match.index + emoji?.length + 2),
}
parent.children.splice(nodeIndex, 1, ...[beforeNode, emojiNode, afterNode])
}
}
}
return (tree: Node) => {
visitParents(tree, { type: 'text' }, visitor);
}
}
export default emojiPlugin;
|