-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathpasteHandler.ts
45 lines (36 loc) · 1.06 KB
/
pasteHandler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { Editor } from '@tiptap/core'
import { MarkType } from '@tiptap/pm/model'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { find } from 'linkifyjs'
type PasteHandlerOptions = {
editor: Editor
defaultProtocol: string
type: MarkType
}
export function pasteHandler(options: PasteHandlerOptions): Plugin {
return new Plugin({
key: new PluginKey('handlePasteLink'),
props: {
handlePaste: (view, event, slice) => {
const { state } = view
const { selection } = state
const { empty } = selection
if (empty) {
return false
}
let textContent = ''
slice.content.forEach(node => {
textContent += node.textContent
})
const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(item => item.isLink && item.value === textContent)
if (!textContent || !link) {
return false
}
options.editor.commands.setMark(options.type, {
href: link.href,
})
return true
},
},
})
}