mirror of
https://github.com/ueberdosis/tiptap.git
synced 2024-12-24 01:17:50 +08:00
8c6751f0c6
* chore: add precommit hook for eslint fixes, fix linting issues * chore: add eslint import sort plugin
100 lines
1.7 KiB
TypeScript
100 lines
1.7 KiB
TypeScript
import {
|
|
mergeAttributes,
|
|
Node,
|
|
nodeInputRule,
|
|
} from '@tiptap/core'
|
|
|
|
export interface ImageOptions {
|
|
inline: boolean,
|
|
allowBase64: boolean,
|
|
HTMLAttributes: Record<string, any>,
|
|
}
|
|
|
|
declare module '@tiptap/core' {
|
|
interface Commands<ReturnType> {
|
|
image: {
|
|
/**
|
|
* Add an image
|
|
*/
|
|
setImage: (options: { src: string, alt?: string, title?: string }) => ReturnType,
|
|
}
|
|
}
|
|
}
|
|
|
|
export const inputRegex = /(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/
|
|
|
|
export const Image = Node.create<ImageOptions>({
|
|
name: 'image',
|
|
|
|
addOptions() {
|
|
return {
|
|
inline: false,
|
|
allowBase64: false,
|
|
HTMLAttributes: {},
|
|
}
|
|
},
|
|
|
|
inline() {
|
|
return this.options.inline
|
|
},
|
|
|
|
group() {
|
|
return this.options.inline ? 'inline' : 'block'
|
|
},
|
|
|
|
draggable: true,
|
|
|
|
addAttributes() {
|
|
return {
|
|
src: {
|
|
default: null,
|
|
},
|
|
alt: {
|
|
default: null,
|
|
},
|
|
title: {
|
|
default: null,
|
|
},
|
|
}
|
|
},
|
|
|
|
parseHTML() {
|
|
return [
|
|
{
|
|
tag: this.options.allowBase64
|
|
? 'img[src]'
|
|
: 'img[src]:not([src^="data:"])',
|
|
},
|
|
]
|
|
},
|
|
|
|
renderHTML({ HTMLAttributes }) {
|
|
return ['img', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]
|
|
},
|
|
|
|
addCommands() {
|
|
return {
|
|
setImage: options => ({ commands }) => {
|
|
return commands.insertContent({
|
|
type: this.name,
|
|
attrs: options,
|
|
})
|
|
},
|
|
}
|
|
},
|
|
|
|
addInputRules() {
|
|
return [
|
|
nodeInputRule({
|
|
find: inputRegex,
|
|
type: this.type,
|
|
getAttributes: match => {
|
|
const [,, alt, src, title] = match
|
|
|
|
return { src, alt, title }
|
|
},
|
|
}),
|
|
]
|
|
},
|
|
})
|