aboutsummaryrefslogtreecommitdiff
path: root/src/emojiPlugin.tsx
blob: a408ed7af2348d5ec579d07c989b49117528c4d3 (plain)
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
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}.*`));

      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;