Render a tooltip under the anchor elements in Tiptap

1k views Asked by At

I'm creating an editor with Tiptap and I'm struggling trying to implement a notion-style anchor element in my rich text editor.

Basically, I need to render a tooltip under the links with the href and an edit link option

Is there a way to render custom components for certain elements (<a> tags in this case)?

I'm getting the current hovered node this way, but now I can't figure out how to access that element and render the tooltip...

  const handleLinkHover = React.useCallback(
    (event: React.MouseEvent<HTMLDivElement>) => {
      if (!editor) return
      const target = event.target as HTMLElement
      const view = editor.view as EditorView
      const pos = view.posAtDOM(target, 0)

      if (pos === null || pos < 0) return

      const node = view.state.doc.nodeAt(pos)
      if (!node || !node.isAtom) return

      const linkMark = node.marks.filter((mark) => mark.type.name === 'link')

      if (linkMark.length > 0) {
        const href = linkMark[0]?.attrs.href
        const rect = target.getBoundingClientRect()

        setCurrentLinkTooltip({
          href,
          top: rect.top,
          left: rect.left,
        })
      } else {
        setCurrentLinkTooltip({
          href: null,
          top: 0,
          left: 0,
        })
      }
    },
    [editor]
  )

For Tooltips I'm using Radix UI

Any help? Thanks!

1

There are 1 answers

0
Nakul Sharma On

We had this requirement in our application where we wanted to show a tooltip with button actions when a user clicks on a link.

Tiptap does something similar with the Bubble Menu. When text is selected in the editor, a tooltip with button actions appears on top of the selected text. I started digging-in the Tiptap's repo to see how Tiptap does it. Here are the details for Bubble Menu -

  • Tiptap menus use tippy.js for the tooltip, actions buttons are added in this tooltip component.
  • A ProseMirror plugin adds this tooltip in the editor view - BubbleMenuPlugin
  • This plugin is registered in the BubbleMenu component and BubbleMenu extension if you are using the extension.

That's it. I followed the exact same steps for implementing the action menu for links.

Here's the Stackblitz with the working code. Notice that the shouldShow method is changed in the LinkActionsPlugin.ts to detect the cursor on links, you can use the same approach to open action menu tooltips on any node/ mark.