feat(core): add nodePasteRule to core

This commit is contained in:
Dominik Biedebach 2022-06-25 12:07:33 +02:00
parent ec595ff803
commit 15123ee092
3 changed files with 45 additions and 11 deletions

View File

@ -1,2 +1,3 @@
export * from './markPasteRule'
export * from './nodePasteRule'
export * from './textPasteRule'

View File

@ -0,0 +1,39 @@
import { NodeType } from 'prosemirror-model'
import { PasteRule } from '../PasteRule'
import { ExtendedRegExpMatchArray } from '../types'
import { callOrReturn } from '../utilities'
/**
* Build an paste rule that adds a node when the
* matched text is pasted into it.
*/
export function nodePasteRule(config: {
find: RegExp,
type: NodeType,
getAttributes?:
| Record<string, any>
| ((match: ExtendedRegExpMatchArray) => Record<string, any>)
| false
| null,
}) {
return new PasteRule({
find: config.find,
handler({ match, chain, range }) {
const attributes = callOrReturn(config.getAttributes, undefined, match)
if (attributes === false || attributes === null) {
return null
}
if (match.input) {
chain()
.deleteRange(range)
.insertContent({
type: config.type.name,
attrs: attributes,
})
}
},
})
}

View File

@ -1,4 +1,4 @@
import { mergeAttributes, Node, PasteRule } from '@tiptap/core'
import { mergeAttributes, Node, nodePasteRule } from '@tiptap/core'
import { getEmbedURLFromYoutubeURL, isValidYoutubeUrl, YOUTUBE_REGEX_GLOBAL } from './utils'
@ -96,17 +96,11 @@ export const Youtube = Node.create<YoutubeOptions>({
}
return [
new PasteRule({
nodePasteRule({
find: YOUTUBE_REGEX_GLOBAL,
handler({ match, chain, range }) {
if (match.input) {
chain()
.deleteRange(range)
.setYoutubeVideo({
src: match.input,
})
}
type: this.type,
getAttributes: match => {
return { src: match.input }
},
}),
]