elk/composables/tiptap/emoji.ts

76 lines
1.4 KiB
TypeScript
Raw Normal View History

import {
Node,
mergeAttributes,
nodeInputRule,
} from '@tiptap/core'
import { emojiRegEx, getEmojiAttributes } from '~/config/emojis'
2022-12-27 22:13:50 +03:00
export const Emoji = Node.create({
name: 'em-emoji',
2022-12-27 22:13:50 +03:00
inline: () => true,
group: () => 'inline',
draggable: false,
2022-12-27 22:13:50 +03:00
parseHTML() {
return [
{
tag: 'img.iconify-emoji',
2022-12-27 22:13:50 +03:00
},
]
},
addAttributes() {
return {
alt: {
default: null,
},
src: {
default: null,
},
class: {
2022-12-27 23:42:58 +03:00
default: null,
},
}
},
2022-12-27 22:13:50 +03:00
renderHTML(args) {
return ['img', mergeAttributes(this.options.HTMLAttributes, args.HTMLAttributes)]
},
addCommands() {
return {
insertEmoji: code => ({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: getEmojiAttributes(code),
})
},
}
},
addInputRules() {
2022-12-27 23:48:01 +03:00
const inputRule = nodeInputRule({
find: emojiRegEx as RegExp,
2022-12-27 23:48:01 +03:00
type: this.type,
getAttributes: (match) => {
const [native] = match
return getEmojiAttributes(native)
2022-12-27 23:48:01 +03:00
},
})
// Error catch for unsupported emoji
const handler = inputRule.handler.bind(inputRule)
inputRule.handler = (...args) => {
try {
return handler(...args)
}
catch (e) {
return null
}
}
return [
2022-12-27 23:48:01 +03:00
inputRule,
]
},
})