The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Feat: Document link editing (#65399)
Brad Anderson5d3f2f806126
diff --git a/e2e/test/scenarios/documents/document-links.cy.spec.ts b/e2e/test/scenarios/documents/document-links.cy.spec.tsindex 57c2f7e1596..10d6f6c76d1 100644--- a/e2e/test/scenarios/documents/document-links.cy.spec.ts+++ b/e2e/test/scenarios/documents/document-links.cy.spec.ts@@ -1,3 +1,5 @@+import { times } from "underscore";+import { PRODUCTS_AVERAGE_BY_CATEGORY } from "e2e/support/test-visualizer-data";const { H } = cy;@@ -9,6 +11,63 @@ describe("Links in documents", () => {H.activateToken("bleeding-edge");});+ describe("plain links", () => {+ it("should support adding, editing, and removing links via floating menu", () => {+ cy.visit("/document/new");+ H.documentContent().click();++ cy.log("Add text and make a link");+ H.addToDocument("Click here", false);+ times("here".length, () => cy.realPress(["Shift", "{leftarrow}"]));+ H.documentFormattingMenu().findByRole("button", { name: /link/ }).click();+ cy.realType("test.com{enter}");++ cy.log("Assert link exists with correct href");+ H.documentContent()+ .findByRole("link", { name: "here" })+ .invoke("attr", "href")+ .then((href) => expect(href).to.equal("https://test.com"));++ cy.log("Edit link url");+ H.documentContent().findByRole("link", { name: "here" }).realHover();+ cy.icon("pencil").click();+ cy.findByTestId("document-formatting-menu")+ .get("input")+ .should("be.focused");+ cy.realType("url.com/a/1?k=v");+ cy.icon("check").click();++ cy.log("Assert link still exists, has updated href");+ H.documentContent()+ .findByRole("link", { name: "here" })+ .invoke("attr", "href")+ .then((href) => expect(href).to.equal("https://url.com/a/1?k=v"));++ cy.log("Remove link");+ H.documentContent().findByRole("link", { name: "here" }).realHover();+ cy.icon("pencil").click();+ cy.findByTestId("document-formatting-menu").icon("trash").click();++ cy.log("Assert link is unlinked");+ H.documentContent()+ .findByRole("paragraph")+ .should("contain.text", "Click here")+ .findByRole("link", { name: "here" })+ .should("not.exist");+ });++ it("should convert markdown links to real links", () => {+ cy.visit("/document/new");+ H.documentContent().click();+ H.addToDocument("Click [here](url.com).", false);+ H.documentContent()+ .findByRole("paragraph")+ .should("contain.text", "Click here.")+ .findByRole("link", { name: "here" })+ .should("exist");+ });+ });+describe("smart links", () => {beforeEach(() => {H.createQuestion(PRODUCTS_AVERAGE_BY_CATEGORY, { wrapId: true });diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.cssindex 944a368f13c..1ce52cf3796 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.css+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.module.css@@ -10,12 +10,16 @@position: relative;}+.editorContent :global(.ProseMirror),+.editorContentInner {+ max-width: 56.25rem;+ margin: 0 auto;+}+.editorContent :global(.ProseMirror) {padding: 1.5rem 0 2rem 0;min-height: 100%;outline: none;- max-width: 56.25rem;- margin: 0 auto;color: var(--mb-color-text-dark);font-size: 1rem;line-height: 1.5;diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsxindex 7a205e1c9ed..e6417f44e1d 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx@@ -1,5 +1,4 @@import Image from "@tiptap/extension-image";-import Link from "@tiptap/extension-link";import { Placeholder } from "@tiptap/extension-placeholder";import type { JSONContent, Editor as TiptapEditor } from "@tiptap/react";import { EditorContent, useEditor } from "@tiptap/react";@@ -10,7 +9,6 @@ import { useLatest, usePrevious } from "react-use";import { t } from "ttag";import { DND_IGNORE_CLASS_NAME } from "metabase/common/components/dnd";-import CS from "metabase/css/core/index.css";import { useSelector, useStore } from "metabase/lib/redux";import { getSetting } from "metabase/selectors/settings";import { Box, Loader } from "metabase/ui";@@ -29,6 +27,7 @@ import { CustomStarterKit } from "metabase-enterprise/rich_text_editing/tiptap/eimport { DisableMetabotSidebar } from "metabase-enterprise/rich_text_editing/tiptap/extensions/DisableMetabotSidebar";import { FlexContainer } from "metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer";import { HandleEditorDrop } from "metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/HandleEditorDrop";+import { LinkHoverMenu } from "metabase-enterprise/rich_text_editing/tiptap/extensions/LinkHoverMenu/LinkHoverMenu";import { MentionExtension } from "metabase-enterprise/rich_text_editing/tiptap/extensions/Mention/MentionExtension";import { MentionSuggestion } from "metabase-enterprise/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion";import {@@ -37,6 +36,7 @@ import {} from "metabase-enterprise/rich_text_editing/tiptap/extensions/MetabotEmbed";import { MetabotMentionExtension } from "metabase-enterprise/rich_text_editing/tiptap/extensions/MetabotMention/MetabotMentionExtension";import { MetabotMentionSuggestion } from "metabase-enterprise/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestion";+import { PlainLink } from "metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink";import { ResizeNode } from "metabase-enterprise/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode";import { SmartLink } from "metabase-enterprise/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";import { createSuggestionRenderer } from "metabase-enterprise/rich_text_editing/tiptap/extensions/suggestionRenderer";@@ -121,10 +121,8 @@ export const Editor: React.FC<EditorProps> = ({},siteUrl,}),- Link.configure({- HTMLAttributes: {- class: CS.link,- },+ PlainLink.configure({+ defaultProtocol: "https",}),Placeholder.configure({placeholder: t`Start writing, type "/" to list commands, or "@" to mention an item...`,@@ -262,6 +260,11 @@ export const Editor: React.FC<EditorProps> = ({disallowedNodes={BUBBLE_MENU_DISALLOWED_NODES}/>)}+ <Box pos="absolute" top={0} left={0} w="100%">+ <Box className={S.editorContentInner} pos="relative">+ <LinkHoverMenu editor={editor} editable={editable} />+ </Box>+ </Box></Box></Box>);diff --git a/enterprise/frontend/src/metabase-enterprise/documents/utils/processUrl.ts b/enterprise/frontend/src/metabase-enterprise/documents/utils/processUrl.tsnew file mode 100644index 00000000000..7c848a660c2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/documents/utils/processUrl.ts@@ -0,0 +1,20 @@+/**+ * Converts a url-like string (e.g. "metabase.com") to a real url (like "https://metabase.com").+ */+export const processUrl = (urlLike: string): string => {+ let processedUrl = urlLike.trim();++ if (!processedUrl.startsWith("/") && processedUrl.includes(".")) {+ const hasProtocol = /^\S+:\/\//.test(processedUrl);+ if (!hasProtocol) {+ const isEmailLike = /^\S+@\S+$/.test(processedUrl);+ if (!isEmailLike) {+ processedUrl = `https://${processedUrl}`;+ } else if (!processedUrl.startsWith("mailto:")) {+ processedUrl = `mailto:${processedUrl}`;+ }+ }+ }++ return processedUrl;+};diff --git a/enterprise/frontend/src/metabase-enterprise/documents/utils/processUrl.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/documents/utils/processUrl.unit.spec.tsnew file mode 100644index 00000000000..3119163b8b3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/documents/utils/processUrl.unit.spec.ts@@ -0,0 +1,69 @@+import { processUrl } from "./processUrl";++const urlsSansProtocol = [+ "example.com",+ "www.example.com",+ "example.com/path",+ "example.com?param=value",+ "example.com#section",+ "subdomain.example.com/path?param=value#section",+];++describe("processUrl", () => {+ describe("URLs without protocols", () => {+ it("should add https to domain-like URLs", () => {+ urlsSansProtocol.forEach((url) => {+ expect(processUrl(url)).toBe(`https://${url}`);+ });+ });+ });++ describe("URLs that already have protocols", () => {+ it("should not modify https URLs", () => {+ const urlsWithProtocol = urlsSansProtocol.map((u) => `https://${u}`);+ urlsWithProtocol.forEach((url) => {+ expect(processUrl(url)).toBe(url);+ });+ });++ it("should not modify custom protocol URLs", () => {+ const url = "custom://something";+ expect(processUrl(url)).toBe(url);+ });+ });++ describe("email addresses", () => {+ it("should add mailto to simple email addresses", () => {+ expect(processUrl("[email protected]")).toBe("mailto:[email protected]");+ });++ it("should add mailto to complex email addresses", () => {+ expect(processUrl("[email protected]")).toBe(+ "mailto:[email protected]",+ );+ });++ it("should not modify email addresses that already have mailto", () => {+ const email = "mailto:[email protected]";+ expect(processUrl(email)).toBe(email);+ });+ });++ describe("relative paths and other strings", () => {+ it("should not modify relative paths starting with /", () => {+ const path = "/relative/path";+ expect(processUrl(path)).toBe(path);+ });++ it("should not modify IP addresses", () => {+ expect(processUrl("192.168.1.1")).toBe("https://192.168.1.1");+ expect(processUrl("192.168.1.1:8080")).toBe("https://192.168.1.1:8080");+ });+ });++ describe("edge cases", () => {+ it("should trim whitespace from input", () => {+ expect(processUrl(" example.com ")).toBe("https://example.com");+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/EditorBubbleMenu.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/EditorBubbleMenu.tsxindex 9846ae886c0..0aed11d4695 100644--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/EditorBubbleMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/EditorBubbleMenu.tsx@@ -5,7 +5,7 @@ import type { Editor as TiptapEditor } from "@tiptap/react";// @ts-expect-error - BubbleMenu is a Tiptap extension that is registered through @tiptap/extension-bubble-menuimport { BubbleMenu } from "@tiptap/react/menus";import type React from "react";-import { useEffect } from "react";+import { useEffect, useState } from "react";import { t } from "ttag";import { useForceUpdate } from "metabase/common/hooks/use-force-update";@@ -14,8 +14,15 @@ import { Flex } from "metabase/ui";import { FormatButton } from "../FormatButton/FormatButton";import S from "./EditorBubbleMenu.module.css";+import { LinkEditor } from "./LinkEditor";import type { FormattingOptions } from "./types";+declare module "@tiptap/core" {+ interface EditorEvents {+ openLinkEditor: string; // The href of the link+ }+}+const DEFAULT_ALLOWED_FORMATTING: FormattingOptions = {bold: true,italic: true,@@ -28,6 +35,7 @@ const DEFAULT_ALLOWED_FORMATTING: FormattingOptions = {quote: true,inline_code: true,code_block: true,+ link: true,};interface EditorBubbleMenuProps {@@ -46,21 +54,47 @@ export const EditorBubbleMenu: React.FC<EditorBubbleMenuProps> = ({className,}) => {const forceUpdate = useForceUpdate();+ const [initialLinkUrl, setInitialLinkUrl] = useState<string | null>(null);++ const handleLinkClick = () => {+ const existingLink = editor.getAttributes("link");+ setInitialLinkUrl(existingLink.href || "");+ };++ const handleLinkSubmit = (url: string) => {+ if (url.trim()) {+ editor.chain().focus().setLink({ href: url.trim() }).run();+ } else {+ editor.chain().focus().unsetLink().run();+ }+ editor.commands.setTextSelection(editor.state.selection.to);+ setInitialLinkUrl(null);+ };++ const handleLinkCancel = () => {+ setInitialLinkUrl(null);+ };useEffect(() => {editor.on("selectionUpdate", forceUpdate);editor.on("update", forceUpdate);+ editor.on("openLinkEditor", setInitialLinkUrl);return () => {editor.off("selectionUpdate", forceUpdate);editor.off("update", forceUpdate);+ editor.off("openLinkEditor", setInitialLinkUrl);};}, [editor, forceUpdate]);+return (<BubbleMenuclassName={className}editor={editor}- options={options}+ options={{+ onHide: () => setInitialLinkUrl(null),+ ...options,+ }}shouldShow={({editor,state,@@ -105,99 +139,117 @@ export const EditorBubbleMenu: React.FC<EditorBubbleMenuProps> = ({className={S.bubbleMenu}data-testid="document-formatting-menu">- {allowedFormatting.bold && (- <FormatButton- isActive={editor.isActive("bold")}- onClick={() => editor.chain().focus().toggleBold().run()}- tooltip={t`Bold`}- icon="text_bold"- />- )}- {allowedFormatting.italic && (- <FormatButton- isActive={editor.isActive("italic")}- onClick={() => editor.chain().focus().toggleItalic().run()}- tooltip={t`Italic`}- icon="text_italic"- />- )}- {allowedFormatting.strikethrough && (- <FormatButton- isActive={editor.isActive("strike")}- onClick={() => editor.chain().focus().toggleStrike().run()}- tooltip={t`Strikethrough`}- icon="text_strike"- />- )}- {allowedFormatting.inline_code && (- <FormatButton- isActive={editor.isActive("code")}- onClick={() => editor.chain().focus().toggleCode().run()}- tooltip={t`Inline code`}- icon="format_code"- />- )}- {allowedFormatting.h1 && (- <FormatButton- isActive={editor.isActive("heading", { level: 1 })}- onClick={() =>- editor.chain().focus().toggleHeading({ level: 1 }).run()- }- tooltip={t`Heading 1`}- text="H1"- />- )}- {allowedFormatting.h2 && (- <FormatButton- isActive={editor.isActive("heading", { level: 2 })}- onClick={() =>- editor.chain().focus().toggleHeading({ level: 2 }).run()- }- tooltip={t`Heading 2`}- text="H2"- />- )}- {allowedFormatting.h3 && (- <FormatButton- isActive={editor.isActive("heading", { level: 3 })}- onClick={() =>- editor.chain().focus().toggleHeading({ level: 3 }).run()- }- tooltip={t`Heading 3`}- text="H3"- />- )}- {allowedFormatting.list && (- <FormatButton- isActive={editor.isActive("bulletList")}- onClick={() => editor.chain().focus().toggleBulletList().run()}- tooltip={t`Bullet list`}- icon="list"- />- )}- {allowedFormatting.ordered_list && (- <FormatButton- isActive={editor.isActive("orderedList")}- onClick={() => editor.chain().focus().toggleOrderedList().run()}- tooltip={t`Numbered list`}- icon="ordered_list"- />- )}- {allowedFormatting.quote && (- <FormatButton- isActive={editor.isActive("blockquote")}- onClick={() => editor.chain().focus().toggleBlockquote().run()}- tooltip={t`Quote`}- icon="quote"- />- )}- {allowedFormatting.code_block && (- <FormatButton- isActive={editor.isActive("codeBlock")}- onClick={() => editor.chain().focus().toggleCodeBlock().run()}- tooltip={t`Code block`}- icon="code_block"+ {initialLinkUrl != null ? (+ <LinkEditor+ initialUrl={initialLinkUrl}+ onSubmit={handleLinkSubmit}+ onCancel={handleLinkCancel}/>+ ) : (+ <>+ {allowedFormatting.bold && (+ <FormatButton+ isActive={editor.isActive("bold")}+ onClick={() => editor.chain().focus().toggleBold().run()}+ tooltip={t`Bold`}+ icon="text_bold"+ />+ )}+ {allowedFormatting.italic && (+ <FormatButton+ isActive={editor.isActive("italic")}+ onClick={() => editor.chain().focus().toggleItalic().run()}+ tooltip={t`Italic`}+ icon="text_italic"+ />+ )}+ {allowedFormatting.strikethrough && (+ <FormatButton+ isActive={editor.isActive("strike")}+ onClick={() => editor.chain().focus().toggleStrike().run()}+ tooltip={t`Strikethrough`}+ icon="text_strike"+ />+ )}+ {allowedFormatting.inline_code && (+ <FormatButton+ isActive={editor.isActive("code")}+ onClick={() => editor.chain().focus().toggleCode().run()}+ tooltip={t`Inline code`}+ icon="format_code"+ />+ )}+ {allowedFormatting.link && (+ <FormatButton+ isActive={initialLinkUrl != null || editor.isActive("link")}+ onClick={handleLinkClick}+ tooltip={t`Link`}+ icon="link"+ />+ )}+ {allowedFormatting.h1 && (+ <FormatButton+ isActive={editor.isActive("heading", { level: 1 })}+ onClick={() =>+ editor.chain().focus().toggleHeading({ level: 1 }).run()+ }+ tooltip={t`Heading 1`}+ text="H1"+ />+ )}+ {allowedFormatting.h2 && (+ <FormatButton+ isActive={editor.isActive("heading", { level: 2 })}+ onClick={() =>+ editor.chain().focus().toggleHeading({ level: 2 }).run()+ }+ tooltip={t`Heading 2`}+ text="H2"+ />+ )}+ {allowedFormatting.h3 && (+ <FormatButton+ isActive={editor.isActive("heading", { level: 3 })}+ onClick={() =>+ editor.chain().focus().toggleHeading({ level: 3 }).run()+ }+ tooltip={t`Heading 3`}+ text="H3"+ />+ )}+ {allowedFormatting.list && (+ <FormatButton+ isActive={editor.isActive("bulletList")}+ onClick={() => editor.chain().focus().toggleBulletList().run()}+ tooltip={t`Bullet list`}+ icon="list"+ />+ )}+ {allowedFormatting.ordered_list && (+ <FormatButton+ isActive={editor.isActive("orderedList")}+ onClick={() => editor.chain().focus().toggleOrderedList().run()}+ tooltip={t`Numbered list`}+ icon="ordered_list"+ />+ )}+ {allowedFormatting.quote && (+ <FormatButton+ isActive={editor.isActive("blockquote")}+ onClick={() => editor.chain().focus().toggleBlockquote().run()}+ tooltip={t`Quote`}+ icon="quote"+ />+ )}+ {allowedFormatting.code_block && (+ <FormatButton+ isActive={editor.isActive("codeBlock")}+ onClick={() => editor.chain().focus().toggleCodeBlock().run()}+ tooltip={t`Code block`}+ icon="code_block"+ />+ )}+ </>)}</Flex></BubbleMenu>diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/LinkEditor.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/LinkEditor.tsxnew file mode 100644index 00000000000..b0c0dda4674--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/LinkEditor.tsx@@ -0,0 +1,90 @@+import { useEffect, useRef, useState } from "react";+import { t } from "ttag";++import {+ ActionIcon,+ Box,+ FixedSizeIcon,+ Flex,+ TextInput,+ Tooltip,+} from "metabase/ui";+import { processUrl } from "metabase-enterprise/documents/utils/processUrl";++interface LinkPopupProps {+ initialUrl: string;+ onSubmit: (url: string) => void;+ onCancel: () => void;+}++export const LinkEditor = ({+ initialUrl,+ onSubmit,+ onCancel,+}: LinkPopupProps) => {+ const [url, setUrl] = useState(initialUrl);+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ setUrl(initialUrl);+ const input = inputRef.current;+ if (!input) {+ return;+ }+ // Something strange happens in BubbleMenu. select() doesn't take unless you put it in an IntersectionObserver.+ const observer = new IntersectionObserver(() => input.select());+ observer.observe(input);+ return () => observer.disconnect();+ }, [initialUrl]);++ const handleSubmit = () => {+ onSubmit(processUrl(url) ?? "");+ setUrl("");+ };++ const handleCancel = () => {+ onCancel();+ setUrl("");+ };++ return (+ <Flex align="center" gap="xs">+ <Box style={{ flexGrow: 1 }}>+ <TextInput+ ref={inputRef}+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ placeholder={t`Enter URL...`}+ size="xs"+ styles={{ input: { fontSize: "0.875rem" } }}+ miw="18rem"+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleSubmit();+ } else if (e.key === "Escape") {+ handleCancel();+ }+ }}+ autoFocus+ />+ </Box>+ <Box c="text-secondary">+ <Tooltip label={t`Save`}>+ <ActionIcon c="inherit" onClick={handleSubmit}>+ <FixedSizeIcon name="check" />+ </ActionIcon>+ </Tooltip>+ <Tooltip label={t`Remove link`}>+ <ActionIcon c="inherit" onClick={() => onSubmit("")}>+ <FixedSizeIcon name="trash" />+ </ActionIcon>+ </Tooltip>+ <Tooltip label={t`Formatting`}>+ <ActionIcon c="inherit" onClick={handleCancel}>+ <FixedSizeIcon name="ellipsis" />+ </ActionIcon>+ </Tooltip>+ </Box>+ </Flex>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/types.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/types.tsindex 605f5bdb07d..74caf0277a3 100644--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/types.ts+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/components/EditorBubbleMenu/types.ts@@ -10,4 +10,5 @@ export type FormattingOptions = {quote?: boolean;inline_code?: boolean;code_block?: boolean;+ link?: boolean;};diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/LinkHoverMenu/LinkHoverMenu.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/LinkHoverMenu/LinkHoverMenu.tsxnew file mode 100644index 00000000000..5c75d8b4c73--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/LinkHoverMenu/LinkHoverMenu.tsx@@ -0,0 +1,141 @@+import type { Editor } from "@tiptap/core";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from "react";++import { Ellipsified } from "metabase/common/components/Ellipsified";+import ExternalLink from "metabase/common/components/ExternalLink";+import { ActionIcon, Box, Card, FixedSizeIcon, Flex } from "metabase/ui";++import S from "../PlainLink/PlainLink.module.css";++const HOVER_TIMEOUT_MS = 200;+const MAX_W = 480;++interface LinkHoverMenuProps {+ editor: Editor;+ editable: boolean;+}++export const LinkHoverMenu = ({ editor, editable }: LinkHoverMenuProps) => {+ const [hoverPosition, setHoverPosition] = useState({ top: 0, left: 0 });+ const [hoveredLink, setHoveredLink] = useState<HTMLElement | null>(null);+ const hoverTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const clearHoverTimeout = useCallback(() => {+ if (hoverTimeoutRef.current) {+ clearTimeout(hoverTimeoutRef.current);+ hoverTimeoutRef.current = null;+ }+ }, []);++ const startHoverTimeout = useCallback(() => {+ clearHoverTimeout();+ hoverTimeoutRef.current = setTimeout(() => {+ setHoveredLink(null);+ }, HOVER_TIMEOUT_MS);+ }, [clearHoverTimeout]);++ useEffect(() => {+ if (!editor) {+ return;+ }++ const handleMouseOver = (event: MouseEvent) => {+ const target = event.target as HTMLElement;+ if (target.tagName === "A" && target.classList.contains(S.plainLink)) {+ clearHoverTimeout();+ setHoveredLink(target);+ }+ };++ const handleMouseOut = (event: MouseEvent) => {+ const target = event.target as HTMLElement;+ if (target.tagName === "A" && target.classList.contains(S.plainLink)) {+ startHoverTimeout();+ }+ };++ const editorElement = editor.view.dom;+ editorElement.addEventListener("mouseover", handleMouseOver);+ editorElement.addEventListener("mouseout", handleMouseOut);++ return () => {+ editorElement.removeEventListener("mouseover", handleMouseOver);+ editorElement.removeEventListener("mouseout", handleMouseOut);+ clearHoverTimeout();+ };+ }, [clearHoverTimeout, editor, startHoverTimeout]);++ const ref = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => {+ if (!hoveredLink) {+ return;+ }+ const linkRect = hoveredLink.getBoundingClientRect();+ const editorRect = editor.view.dom.getBoundingClientRect();+ const hoverMenuRect = ref.current?.getBoundingClientRect();++ const leftMax = editorRect.width - (hoverMenuRect?.width ?? MAX_W);+ setHoverPosition({+ top: linkRect.bottom - editorRect.top,+ left: Math.min(linkRect.left - editorRect.left, leftMax),+ });+ }, [hoveredLink, editor]);++ const href = hoveredLink?.getAttribute("href");+ if (!href || !hoveredLink) {+ return null;+ }++ return (+ <Box+ ref={ref}+ mt="xs"+ ml="-sm"+ pos="absolute"+ style={hoverPosition}+ onMouseEnter={() => clearHoverTimeout()}+ onMouseLeave={() => startHoverTimeout()}+ >+ <Card+ shadow="0 2px 8px var(--mb-color-shadow)"+ bd="1px solid var(--mb-color-border)"+ bdrs="sm"+ px="sm"+ py="xs"+ maw={MAX_W}+ >+ <Flex align="center">+ <Ellipsified showTooltip={false}>+ <ExternalLink href={href} target="_blank">+ {href}+ </ExternalLink>+ </Ellipsified>+ {editable && (+ <ActionIcon+ ml="sm"+ c="var(--mb-color-text-secondary)"+ onClick={() => {+ editor.commands.focus();+ const pos = editor.view.posAtDOM(hoveredLink, 0);+ editor.commands.setTextSelection({+ from: pos,+ to: pos + (hoveredLink.textContent?.length || 0),+ });+ editor.emit("openLinkEditor", href);+ setHoveredLink(null);+ }}+ >+ <FixedSizeIcon name="pencil" />+ </ActionIcon>+ )}+ </Flex>+ </Card>+ </Box>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.module.css b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.module.cssnew file mode 100644index 00000000000..5e4e181e303--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.module.css@@ -0,0 +1,3 @@+.plainLink > * {+ pointer-events: none; /* prevents bold/italic/etc link children from messing with mouseover event delegation in LinkHoverMenu */+}diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.tsnew file mode 100644index 00000000000..ea99889ad4c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.ts@@ -0,0 +1,131 @@+import {+ InputRule,+ PasteRule,+ markInputRule,+ markPasteRule,+} from "@tiptap/core";+import { Link } from "@tiptap/extension-link";+import cx from "classnames";++import CS from "metabase/css/core/index.css";+import { processUrl } from "metabase-enterprise/documents/utils/processUrl";++import S from "./PlainLink.module.css";++// Adapted from https://github.com/ueberdosis/tiptap/discussions/1865#discussioncomment-2568739++/**+ * The input regex for Markdown links with title support, and multiple quotation marks (required+ * in case the `Typography` extension is being included).+ *+ * @see https://stephenweiss.dev/regex-markdown-link+ */+const inputRegex =+ /(?:^|\s)\[([^\]]*)?\]\(([A-Za-z0-9:/. ]+)(?:["“](.+)["”])?\)$/;++/**+ * The paste regex for Markdown links with title support, and multiple quotation marks (required+ * in case the `Typography` extension is being included).+ *+ * @see https://stephenweiss.dev/regex-markdown-link+ */+const pasteRegex =+ /(?:^|\s)\[([^\]]*)?\]\(([A-Za-z0-9:/. ]+)(?:["“](.+)["”])?\)/g;++/**+ * Input rule built specifically for the `Link` extension, which ignores the auto-linked URL in+ * parentheses (e.g., `(https://doist.dev)`).+ *+ * @see https://github.com/ueberdosis/tiptap/discussions/1865+ */+function linkInputRule(config: Parameters<typeof markInputRule>[0]) {+ const defaultMarkInputRule = markInputRule(config);++ return new InputRule({+ find: config.find,+ handler: (props) => {+ const { tr } = props.state;++ defaultMarkInputRule.handler(props);+ tr.setMeta("preventAutolink", true);+ },+ });+}++/**+ * Paste rule built specifically for the `Link` extension, which ignores the auto-linked URL in+ * parentheses (e.g., `(https://doist.dev)`).+ *+ * @see https://github.com/ueberdosis/tiptap/discussions/1865+ */+function linkPasteRule(config: Parameters<typeof markPasteRule>[0]) {+ const defaultMarkInputRule = markPasteRule(config);++ return new PasteRule({+ find: config.find,+ handler: (props) => {+ const { tr } = props.state;++ defaultMarkInputRule.handler(props);+ tr.setMeta("preventAutolink", true);+ },+ });+}++/**+ * Custom extension that extends the built-in `Link` extension to add additional input and paste+ * rules for converting the Markdown link syntax [Doist](https://doist.com) into links. This+ * extension also adds support for the `title` attribute.+ */+export const PlainLink = Link.extend({+ // Typing after a link (e.g. hitting space) should not be linked - https://github.com/ueberdosis/tiptap/issues/2571#issuecomment-1712057913+ inclusive: false,+}).extend({+ addOptions() {+ const base = this.parent?.();+ return {+ ...base,+ HTMLAttributes: {+ ...base?.HTMLAttributes,+ class: cx(CS.link, S.plainLink, base?.HTMLAttributes?.class),+ },+ };+ },++ addInputRules() {+ return [+ linkInputRule({+ find: inputRegex,+ type: this.type,++ // We need to use `pop()` to remove the last capture groups from the match to+ // satisfy Tiptap's `markPasteRule` expectation of having the content as the last+ // capture group in the match (this makes the attribute order important)+ getAttributes(match) {+ return {+ title: match.pop()?.trim(),+ href: processUrl(match.pop()?.trim() ?? ""),+ };+ },+ }),+ ];+ },+ addPasteRules() {+ return [+ linkPasteRule({+ find: pasteRegex,+ type: this.type,++ // We need to use `pop()` to remove the last capture groups from the match to+ // satisfy Tiptap's `markInputRule` expectation of having the content as the last+ // capture group in the match (this makes the attribute order important)+ getAttributes(match) {+ return {+ title: match.pop()?.trim(),+ href: processUrl(match.pop()?.trim() ?? ""),+ };+ },+ }),+ ];+ },+});diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsxindex 09a4bd2355a..92130b45f53 100644--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx@@ -224,23 +224,34 @@ export const SmartLink = Node.create<{addPasteRules() {return [- nodePasteRule({+ {find: /https?:\/\/[^\s]+/g,- type: this.type,- getAttributes: (match) => {+ handler: ({ state, range, match }) => {const url = match[0];++ // Check if the preceding characters are "](" which indicates the user is typing a markdown link+ const start = range.from;+ if (start >= 2) {+ const textBefore = state.doc.textBetween(start - 2, start);+ if (textBefore === "](") {+ return;+ }+ }+const parsedEntity = parseEntityUrl(url, this.options.siteUrl);if (parsedEntity) {- return {- entityId: parsedEntity.entityId,- model: parsedEntity.model,- };+ state.tr.replaceRangeWith(+ range.from,+ range.to,+ this.type.create({+ entityId: parsedEntity.entityId,+ model: parsedEntity.model,+ }),+ );}-- return null; // Return null to prevent node creation},- }),+ },nodePasteRule({find: new RegExp(METABSE_PROTOCOL_MD_LINK, "g"),type: this.type,