Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(link): restore pasteHandler and add existing url check #4523

Merged
merged 2 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
},
},
})
}
10 changes: 10 additions & 0 deletions 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 @@ -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
},
})
Loading