2020-11-16 18:19:43 +08:00
|
|
|
import { Command, Node, nodeInputRule } from '@tiptap/core'
|
2020-10-27 22:32:55 +08:00
|
|
|
|
2020-10-30 23:57:55 +08:00
|
|
|
export interface ImageOptions {
|
|
|
|
inline: boolean,
|
2020-11-13 23:44:22 +08:00
|
|
|
HTMLAttributes: {
|
|
|
|
[key: string]: any
|
|
|
|
},
|
2020-10-30 23:57: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
|
|
|
|
2020-11-16 18:19:43 +08:00
|
|
|
const Image = Node.create({
|
2020-10-27 22:32:55 +08:00
|
|
|
name: 'image',
|
|
|
|
|
2020-10-30 23:57:55 +08:00
|
|
|
defaultOptions: <ImageOptions>{
|
|
|
|
inline: false,
|
2020-11-13 23:44:22 +08:00
|
|
|
HTMLAttributes: {},
|
2020-10-30 23:57:55 +08:00
|
|
|
},
|
|
|
|
|
|
|
|
inline() {
|
|
|
|
return this.options.inline
|
|
|
|
},
|
2020-10-27 22:32:55 +08:00
|
|
|
|
2020-10-30 23:57:55 +08:00
|
|
|
group() {
|
|
|
|
return this.options.inline ? 'inline' : 'block'
|
|
|
|
},
|
2020-10-27 22:32:55 +08:00
|
|
|
|
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]',
|
|
|
|
},
|
|
|
|
]
|
|
|
|
},
|
|
|
|
|
2020-11-13 23:07:20 +08:00
|
|
|
renderHTML({ HTMLAttributes }) {
|
|
|
|
return ['img', HTMLAttributes]
|
2020-10-27 22:32:55 +08:00
|
|
|
},
|
|
|
|
|
|
|
|
addCommands() {
|
|
|
|
return {
|
2020-11-13 22:08:30 +08:00
|
|
|
/**
|
|
|
|
* Add an image
|
|
|
|
*/
|
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
|
|
|
}),
|
|
|
|
]
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
export default Image
|
|
|
|
|
2020-11-11 04:18:22 +08:00
|
|
|
declare module '@tiptap/core' {
|
2020-10-27 22:32:55 +08:00
|
|
|
interface AllExtensions {
|
|
|
|
Image: typeof Image,
|
|
|
|
}
|
|
|
|
}
|