Skip to content

Commit

Permalink
fix(link): restore pasteHandler and add existing url check (#4523)
Browse files Browse the repository at this point in the history
* fix(link): restore pasteHandler and add existing url check

* make pasteEvent optional
  • Loading branch information
bdbch authored Oct 11, 2023
1 parent 025dfff commit 1a7b428
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
52 changes: 52 additions & 0 deletions packages/extension-link/src/helpers/pasteHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
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
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).find(item => item.isLink && item.value === textContent)

if (!textContent || !link) {
return false
}

const html = event.clipboardData.getData('text/html')

const hrefRegex = /href="([^"]*)"/

const existingLink = html?.match(hrefRegex)

const url = existingLink ? existingLink[1] : link.href

options.editor.commands.setMark(options.type, {
href: url,
})

return true
},
},
})
}
12 changes: 11 additions & 1 deletion packages/extension-link/src/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { find, registerCustomProtocol, reset } from 'linkifyjs'

import { autolink } from './helpers/autolink.js'
import { clickHandler } from './helpers/clickHandler.js'
import { pasteHandler } from './helpers/pasteHandler.js'

export interface LinkProtocolOptions {
scheme: string;
Expand Down Expand Up @@ -167,7 +168,7 @@ export const Link = Mark.create<LinkOptions>({
})),
type: this.type,
getAttributes: (match, pasteEvent) => {
const html = pasteEvent.clipboardData?.getData('text/html')
const html = pasteEvent?.clipboardData?.getData('text/html')
const hrefRegex = /href="([^"]*)"/

const existingLink = html?.match(hrefRegex)
Expand Down Expand Up @@ -206,6 +207,15 @@ export const Link = Mark.create<LinkOptions>({
)
}

if (this.options.linkOnPaste) {
plugins.push(
pasteHandler({
editor: this.editor,
type: this.type,
}),
)
}

return plugins
},
})

0 comments on commit 1a7b428

Please sign in to comment.