I tried extending the link plugin in Tiptap editor and it works. but the issue comes when i tried to prevent openOnClick from happening. It used to work before i tried the below and now it doesn't. What can i do?

import Link from "@tiptap/extension-link";

export const CustomLink = Link.extend({
  addCommands() {
    return {
      ...this.parent?.(),
      addLink: function (options) {
        return ({ tr, commands }) => {
          commands.insertContent(
            `<a href='${options.href}' class="custom-link">${options.href}</a>`,
            {
              parseOptions: {
                preserveWhitespace: false,
              },
            }
          );
        };
      },
    };
  },
});

Tiptap.tsx:

const editor = useEditor({
    editable: false,
    extensions: [
            Link.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: "custom-link",
        },
      }),
    ]
});

I tried to import the clickHandler in the extended but its not accepting it.

1

There are 1 answers

0
Akeel Ahmed Qureshi On

To prevent the default behavior, you can modify the clickHandler in your custom extension. You can do this by extending the existing Link extension and overriding the clickHandler method.

By applying this code it will overrides the clickHandler by extending the addNodeView method. The overridden click handler prevents the default behavior and then calls the original click handler if it exists.

 import { Link } from "@tiptap/extension-link";

export const CustomLink = Link.extend({
  addCommands() {
    return {
      ...this.parent?.(),
      addLink: function (options) {
        return ({ tr, commands }) => {
          commands.insertContent(
            `<a href='${options.href}' class="custom-link">${options.href}</a>`,
            {
              parseOptions: {
                preserveWhitespace: false,
              },
            }
          );
        };
      },
    };
  },
  addNodeView() {
    return ({ node, ...props }) => {
      const view = this.parent?.().addNodeView?.({ node, ...props });

      if (view) {
        const originalClickHandler = view.contentDOM.onclick;

        // Override click handler to prevent the default behavior
        view.contentDOM.onclick = (event) => {
          // Add your custom handling here if needed
          console.log("Custom click handler");

          // Prevent the default behavior
          event.preventDefault();

          // Call the original click handler
          if (originalClickHandler) {
            originalClickHandler(event);
          }
        };
      }

      return view;
    };
  },
});