2022-12-27 21:38:57 +03:00
|
|
|
import {
|
|
|
|
Node,
|
|
|
|
mergeAttributes,
|
|
|
|
nodeInputRule,
|
2023-01-05 11:50:11 +03:00
|
|
|
nodePasteRule,
|
2022-12-27 21:38:57 +03:00
|
|
|
} from '@tiptap/core'
|
2023-01-02 07:53:53 +03:00
|
|
|
import { emojiRegEx, getEmojiAttributes } from '~/config/emojis'
|
2022-12-27 21:38:57 +03:00
|
|
|
|
2023-03-30 22:01:24 +03:00
|
|
|
function createEmojiRule<NR extends typeof nodeInputRule | typeof nodePasteRule>(nodeRule: NR,
|
|
|
|
type: Parameters<NR>[0]['type']): ReturnType<NR>[] {
|
2023-01-05 11:50:11 +03:00
|
|
|
const rule = nodeRule({
|
|
|
|
find: emojiRegEx as RegExp,
|
|
|
|
type,
|
|
|
|
getAttributes: (match) => {
|
|
|
|
const [native] = match
|
|
|
|
return getEmojiAttributes(native)
|
|
|
|
},
|
|
|
|
}) as ReturnType<NR>
|
|
|
|
|
|
|
|
// Error catch for unsupported emoji
|
|
|
|
const handler = rule.handler.bind(rule)
|
|
|
|
rule.handler = (...args) => {
|
|
|
|
try {
|
|
|
|
return handler(...args)
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return [
|
|
|
|
rule,
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
2023-01-16 14:40:47 +03:00
|
|
|
export const TiptapPluginEmoji = Node.create({
|
2022-12-27 22:13:50 +03:00
|
|
|
name: 'em-emoji',
|
2022-12-27 21:38:57 +03:00
|
|
|
|
2022-12-27 22:13:50 +03:00
|
|
|
inline: () => true,
|
|
|
|
group: () => 'inline',
|
|
|
|
draggable: false,
|
2022-12-27 21:38:57 +03:00
|
|
|
|
2022-12-27 22:13:50 +03:00
|
|
|
parseHTML() {
|
|
|
|
return [
|
|
|
|
{
|
2023-01-02 07:53:53 +03:00
|
|
|
tag: 'img.iconify-emoji',
|
2022-12-27 22:13:50 +03:00
|
|
|
},
|
|
|
|
]
|
2022-12-27 21:38:57 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
addAttributes() {
|
|
|
|
return {
|
2023-01-02 07:53:53 +03:00
|
|
|
alt: {
|
2022-12-27 21:38:57 +03:00
|
|
|
default: null,
|
|
|
|
},
|
2023-01-02 07:53:53 +03:00
|
|
|
src: {
|
|
|
|
default: null,
|
|
|
|
},
|
|
|
|
class: {
|
2022-12-27 23:42:58 +03:00
|
|
|
default: null,
|
|
|
|
},
|
2022-12-27 21:38:57 +03:00
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2022-12-27 22:13:50 +03:00
|
|
|
renderHTML(args) {
|
2023-01-02 07:53:53 +03:00
|
|
|
return ['img', mergeAttributes(this.options.HTMLAttributes, args.HTMLAttributes)]
|
2022-12-27 21:38:57 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
addCommands() {
|
|
|
|
return {
|
2023-01-02 07:53:53 +03:00
|
|
|
insertEmoji: code => ({ commands }) => {
|
2022-12-27 21:38:57 +03:00
|
|
|
return commands.insertContent({
|
|
|
|
type: this.name,
|
2023-01-02 07:53:53 +03:00
|
|
|
attrs: getEmojiAttributes(code),
|
2022-12-27 21:38:57 +03:00
|
|
|
})
|
|
|
|
},
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
addInputRules() {
|
2023-01-05 11:50:11 +03:00
|
|
|
return createEmojiRule(nodeInputRule, this.type)
|
|
|
|
},
|
|
|
|
|
|
|
|
addPasteRules() {
|
|
|
|
return createEmojiRule(nodePasteRule, this.type)
|
2022-12-27 21:38:57 +03:00
|
|
|
},
|
|
|
|
})
|