fix: link paste handler (#609)

* feat: support pasting markdown

* fix link paste handler
This commit is contained in:
Philip Okugbe
2025-01-04 20:47:49 +00:00
committed by GitHub
parent 287b833838
commit f5bc99b449
4 changed files with 48 additions and 6 deletions

View File

@ -10,11 +10,35 @@ export const LinkExtension = TiptapLink.extend({
return [
{
tag: 'a[href]:not([data-type="button"]):not([href *= "javascript:" i])',
getAttrs: (element) => {
if (
element
.getAttribute("href")
?.toLowerCase()
.startsWith("javascript:")
) {
return false;
}
return null;
},
},
];
},
renderHTML({ HTMLAttributes }) {
if (HTMLAttributes.href?.toLowerCase().startsWith("javascript:")) {
return [
"a",
mergeAttributes(
this.options.HTMLAttributes,
{ ...HTMLAttributes, href: "" },
{ class: "link" },
),
0,
];
}
return [
"a",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {

View File

@ -3,9 +3,15 @@ import { Extension } from "@tiptap/core";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { DOMParser } from "@tiptap/pm/model";
import { markdownToHtml } from "./utils/marked.utils";
import { find } from "linkifyjs";
export const MarkdownClipboard = Extension.create({
name: "markdownClipboard",
priority: 50,
export const MarkdownClipboard = Extension.create({
name: "markdownClipboard",
addOptions() {
return {
transformPastedText: false,
@ -17,9 +23,17 @@ export const MarkdownClipboard = Extension.create({
key: new PluginKey("markdownClipboard"),
props: {
clipboardTextParser: (text, context, plainText) => {
if (plainText || !this.options.transformPastedText) {
return null; // pasting with shift key prevents formatting
const link = find(text, {
defaultProtocol: "http",
}).find((item) => item.isLink && item.value === text);
if (plainText || !this.options.transformPastedText || link) {
// don't parse plaintext link to allow link paste handler to work
// pasting with shift key prevents formatting
return null;
}
const parsed = markdownToHtml(text);
return DOMParser.fromSchema(this.editor.schema).parseSlice(
elementFromString(parsed),