-
-
Notifications
You must be signed in to change notification settings - Fork 232
/
emoji-plugin.ts
52 lines (48 loc) 路 1.36 KB
/
emoji-plugin.ts
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
import { EditorSchema, TextParams } from '@remirror/core';
import { Data } from 'emoji-mart';
import emojiRegex from 'emoji-regex/es2015/text';
import { NodeType } from 'prosemirror-model';
import { Plugin, Transaction } from 'prosemirror-state';
import { getEmojiDataByNativeString } from './emoji-helpers';
import { CreateEmojiPluginParams } from './emoji-types';
export const createEmojiPlugin = ({ key, emojiData, type }: CreateEmojiPluginParams) => {
return new Plugin({
key,
props: {
handleTextInput(view, from, to, text) {
const { state } = view;
const originalTr = state.tr;
let tr: Transaction<EditorSchema> | undefined;
if (emojiRegex().exec(text)) {
tr = replaceNativeEmoji({ from, to, text, emojiData, type, tr: originalTr }) || tr;
}
if (tr) {
view.dispatch(tr);
return true;
}
return false;
},
},
});
};
interface ReplaceNativeEmojiParams extends TextParams {
from: number;
to: number;
emojiData: Data;
type: NodeType;
tr: Transaction<EditorSchema>;
}
export const replaceNativeEmoji = ({
text,
from,
to,
emojiData,
type,
tr,
}: ReplaceNativeEmojiParams): Transaction | undefined => {
const data = getEmojiDataByNativeString(text, emojiData);
if (!data) {
return;
}
return tr.replaceWith(from, to, type.create(data));
};