aboutsummaryrefslogtreecommitdiff
path: root/src/emojiPlugin.tsx
diff options
context:
space:
mode:
Diffstat (limited to 'src/emojiPlugin.tsx')
-rw-r--r--src/emojiPlugin.tsx48
1 files changed, 48 insertions, 0 deletions
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;