1
0
Fork 1
mirror of https://github.com/elk-zone/elk.git synced 2024-11-14 04:49:59 +00:00
elk/composables/tiptap/emoji.ts

90 lines
1.8 KiB
TypeScript
Raw Normal View History

import type { ExtendedRegExpMatchArray } from '@tiptap/core'
import {
Node,
mergeAttributes,
nodeInputRule,
nodePasteRule,
} from '@tiptap/core'
import { emojiRegEx, getEmojiAttributes } from '~/config/emojis'
function wrapHandler<T extends (...args: any[]) => any>(handler: T): T {
return <T>((...args: any[]) => {
try {
return handler(...args)
}
catch (e) {
return null
}
})
}
function createEmojiRule<NR extends typeof nodeInputRule | typeof nodePasteRule>(nodeRule: NR,
type: Parameters<NR>[0]['type']): ReturnType<NR>[] {
const rule = nodeRule({
find: emojiRegEx as RegExp,
type,
getAttributes: (match: ExtendedRegExpMatchArray) => {
const [native] = match
return getEmojiAttributes(native)
},
}) as ReturnType<NR>
// Error catch for unsupported emoji
rule.handler = wrapHandler(rule.handler.bind(rule))
return [rule]
}
2023-01-16 11:40:47 +00:00
export const TiptapPluginEmoji = Node.create({
2022-12-27 19:13:50 +00:00
name: 'em-emoji',
2022-12-27 19:13:50 +00:00
inline: () => true,
group: () => 'inline',
draggable: false,
2022-12-27 19:13:50 +00:00
parseHTML() {
return [
{
tag: 'img.iconify-emoji',
2022-12-27 19:13:50 +00:00
},
]
},
addAttributes() {
return {
alt: {
default: null,
},
src: {
default: null,
},
class: {
2022-12-27 20:42:58 +00:00
default: null,
},
}
},
2022-12-27 19:13:50 +00: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() {
return createEmojiRule(nodeInputRule, this.type)
},
addPasteRules() {
return createEmojiRule(nodePasteRule, this.type)
},
})