Been trying to figure out the idiomatic way of solving what I imagine is a fairly common use case.
In my particular case, if a unicode emoji is typed or pasted into the editor, I want it replaced with the emojiNodeSpec I’ve defined for rendering emojis in the editor.
Here’s where I’m at so far: import {schema} from "prosemirror-schema-basic";import {EditorState, Plugin} - Pastebin.com
I was thinking I should probably use transformPasted and handleTextInput but I haven’t had much luck actually getting either of those to work and I couldn’t find any good code examples to cheat off of.
What would be the idiomatic/conventional approach here?
So I ended up using the combination of:
- prosemirror-paste-rules (remirror)
import {pasteRules} from "prosemirror-paste-rules";
const emojiInputRegex = new RegExp(`(${EMOJI_REGEX.source})`);
/** @type {(nodeType) => import("prosemirror-paste-rules").PasteRule} */
const emojiPasteRule = nodeType => ({
type: 'node',
nodeType: nodeType,
regexp: emojiInputRegex,
getContent: () => {},
getAttributes: match => {
return {emoji: match[0]};
}
});
// ...
{
plugins: [
pasteRules([emojiPasteRule(inlineSchema.nodes.emoji)]),
]
}
- Custom plugin with
handleTextInput
// Plugin to handle text input
const emojiInputPlugin = new Plugin({
props: {
handleTextInput(view, from, to, text) {
let matchingEmoji;
if( matchingEmoji = text?.match(emojiInputRegex)?.[0] ) {
view.dispatch(
view.state.tr.insert(from, view.state.schema.nodes.emoji.createChecked({emoji: matchingEmoji}))
);
return true;
}
return false;
}
}
});