From 4df5503f3e06761a7096324f8e093ab4c1afefa7 Mon Sep 17 00:00:00 2001
From: eug-vs <eugene@eug-vs.xyz>
Date: Fri, 23 Sep 2022 13:14:11 +0300
Subject: feat: add emoji plugin

---
 src/emojiPlugin.tsx | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 48 insertions(+)
 create mode 100644 src/emojiPlugin.tsx

(limited to 'src/emojiPlugin.tsx')

diff --git a/src/emojiPlugin.tsx b/src/emojiPlugin.tsx
new file mode 100644
index 0000000..a408ed7
--- /dev/null
+++ b/src/emojiPlugin.tsx
@@ -0,0 +1,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;
-- 
cgit v1.2.3

