From 15123ee092261fe86352d491121804607e08e031 Mon Sep 17 00:00:00 2001 From: Dominik Biedebach Date: Sat, 25 Jun 2022 12:07:33 +0200 Subject: [PATCH] feat(core): add nodePasteRule to core --- packages/core/src/pasteRules/index.ts | 1 + packages/core/src/pasteRules/nodePasteRule.ts | 39 +++++++++++++++++++ packages/extension-youtube/src/youtube.ts | 16 +++----- 3 files changed, 45 insertions(+), 11 deletions(-) create mode 100644 packages/core/src/pasteRules/nodePasteRule.ts diff --git a/packages/core/src/pasteRules/index.ts b/packages/core/src/pasteRules/index.ts index c1921cc2..0c7761ee 100644 --- a/packages/core/src/pasteRules/index.ts +++ b/packages/core/src/pasteRules/index.ts @@ -1,2 +1,3 @@ export * from './markPasteRule' +export * from './nodePasteRule' export * from './textPasteRule' diff --git a/packages/core/src/pasteRules/nodePasteRule.ts b/packages/core/src/pasteRules/nodePasteRule.ts new file mode 100644 index 00000000..a3392ae0 --- /dev/null +++ b/packages/core/src/pasteRules/nodePasteRule.ts @@ -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 + | ((match: ExtendedRegExpMatchArray) => Record) + | 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, + }) + } + }, + }) +} diff --git a/packages/extension-youtube/src/youtube.ts b/packages/extension-youtube/src/youtube.ts index d0cdb5bb..93c79fe7 100644 --- a/packages/extension-youtube/src/youtube.ts +++ b/packages/extension-youtube/src/youtube.ts @@ -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({ } 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 } }, }), ]