tiptap/packages/extension-image/index.ts

78 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-10-27 22:32:55 +08:00
import { Command, createNode, nodeInputRule } from '@tiptap/core'
2020-10-29 16:26:24 +08:00
import { VueRenderer } from '@tiptap/vue'
2020-10-27 22:32:55 +08:00
2020-10-28 05:35:31 +08:00
export const inputRegex = /!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\)/
2020-10-27 22:32:55 +08:00
const Image = createNode({
name: 'image',
inline: true,
group: 'inline',
2020-10-28 04:38:29 +08:00
draggable: true,
2020-10-27 22:32:55 +08:00
addAttributes() {
return {
src: {
default: null,
},
alt: {
default: null,
},
title: {
default: null,
},
}
},
parseHTML() {
return [
{
tag: 'img[src]',
},
]
},
renderHTML({ attributes }) {
return ['img', attributes]
},
addCommands() {
return {
2020-10-28 05:35:31 +08:00
image: (options: { src: string, alt?: string, title?: string }): Command => ({ tr }) => {
2020-10-27 22:32:55 +08:00
const { selection } = tr
2020-10-28 05:35:31 +08:00
const node = this.type.create(options)
tr.replaceRangeWith(selection.from, selection.to, node)
2020-10-27 22:32:55 +08:00
return true
},
}
},
addInputRules() {
return [
2020-10-28 05:35:31 +08:00
nodeInputRule(inputRegex, this.type, match => {
2020-10-27 22:32:55 +08:00
const [, alt, src, title] = match
2020-10-28 05:35:31 +08:00
return { src, alt, title }
2020-10-27 22:32:55 +08:00
}),
]
},
2020-10-29 16:26:24 +08:00
addNodeView() {
return VueRenderer({
template: '<div>vue component</div>',
})
},
2020-10-27 22:32:55 +08:00
})
export default Image
declare module '@tiptap/core/src/Editor' {
interface AllExtensions {
Image: typeof Image,
}
}