Skip to content

Commit

Permalink
feat(core): add nodePasteRule to core
Browse files Browse the repository at this point in the history
  • Loading branch information
bdbch committed Jun 25, 2022
1 parent ec595ff commit 15123ee
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 11 deletions.
1 change: 1 addition & 0 deletions packages/core/src/pasteRules/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './markPasteRule'
export * from './nodePasteRule'
export * from './textPasteRule'
39 changes: 39 additions & 0 deletions packages/core/src/pasteRules/nodePasteRule.ts
Original file line number Diff line number Diff line change
@@ -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,
})
}
},
})
}
16 changes: 5 additions & 11 deletions packages/extension-youtube/src/youtube.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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 }
},
}),
]
Expand Down

0 comments on commit 15123ee

Please sign in to comment.