简体   繁体   中英

How to add emoji to ProseMirror?

I started to use prosemirror, but I am struggling with finding extensions for it. Even basic extensions as tags, mentions or emoji are hard to find. Am I missing something with this editor? I understood that it is quite mature (trying to drop draft in favor of it), but I might miss something here.

ProseMirror is a mature framework, but it isn't as easy to drag and drop as Draft.js is because you will have to build out your own nodes for emojis, tags, mentions, etc.

Initially it's going to take a lot of documentation reading, but once you have a firm grasp, building those will be easy.

Let's take emojis for example. We can adapt the dinosaur example from here: https://prosemirror.net/examples/dino/ .

First, we will have to define a NodeSpec ( https://prosemirror.net/docs/ref/#model.NodeSpec ) for emojis.

const EmojiSpec = {
      attrs: {char: {}}, // dynamic values here
      inline: true,
      group: "inline",
      draggable: false,
      selectable: false,
      parseDOM: [{ // how does prosemirror recognize an emoji if its being pasted from clipboard?
        tag: "img[emoji]",
        getAttrs: (dom: HTMLImageElement) => {
          return {char: dom.getAttribute("alt")};
        }
      }],
      toDOM: (node: PMNode) => { // how should prosemirror render the emoji based on the node values?
        return ['img', {class: "emoji", draggable: "false", alt: node.attrs.char}]
      },
}

This is a loose implementation. In production, you'd want to compute an image src based on the node.attrs.char value like so

      toDOM: (node: PMNode) => {
        const src = getImageSrc(node.attrs.char)
        return ['img', {class: "emoji", draggable: "false", alt: node.attrs.char, src}]
      },

Once you have this emoji NodeSpec, you want to combine that with the rest of your custom nodes (like tags mentions) and marks (link, italic, bold) to make a Schema which you plug into the editor. Follow rest of the dinosaur tutorial from here.

Best of luck!

If you're still stuck, I would highly recommend looking at libraries which build upon ProseMirror like tiptap and rich-markdown-editor to see ProseMirror is integrated and used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM