Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Add Anchor Links to Documents (#67940)

Arkadi Yaroslavtseva92317dd2712
diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.ts
index 8f485e5ea51..98d022a6941 100644
--- a/e2e/test/scenarios/documents/documents.cy.spec.ts
+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts
@@ -1236,6 +1236,155 @@ describe("documents", () => {
});
});
+ describe("anchor links", () => {
+ // Helper to create filler paragraphs for scroll tests
+ const createFillerParagraphs = (count: number, startIndex: number) =>
+ Array.from({ length: count }, (_, i) => ({
+ type: "paragraph",
+ attrs: { _id: `filler-paragraph-${startIndex + i}` },
+ content: [
+ {
+ type: "text",
+ text: `This is filler paragraph ${startIndex + i} to make the document long enough to require scrolling. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.`,
+ },
+ ],
+ }));
+
+ beforeEach(() => {
+ H.createDocument({
+ name: "Anchor Test Document",
+ document: {
+ content: [
+ {
+ type: "heading",
+ attrs: { level: 1, _id: "heading-block-1" },
+ content: [{ type: "text", text: "First Heading" }],
+ },
+ {
+ type: "paragraph",
+ attrs: { _id: "paragraph-block-1" },
+ content: [{ type: "text", text: "Some content here" }],
+ },
+ // Add filler content to ensure scrolling is needed
+ ...createFillerParagraphs(15, 1),
+ {
+ type: "heading",
+ attrs: { level: 2, _id: "heading-block-2" },
+ content: [{ type: "text", text: "Second Heading" }],
+ },
+ {
+ type: "paragraph",
+ attrs: { _id: "paragraph-block-2" },
+ content: [{ type: "text", text: "More content here" }],
+ },
+ // More filler to push blockquote down
+ ...createFillerParagraphs(10, 16),
+ {
+ type: "blockquote",
+ attrs: { _id: "blockquote-block-1" },
+ content: [
+ {
+ type: "paragraph",
+ attrs: { _id: "quote-paragraph" },
+ content: [{ type: "text", text: "A nice quote" }],
+ },
+ ],
+ },
+ ],
+ type: "doc",
+ },
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+ });
+
+ it("should show anchor link icon on left side when hovering over a heading", () => {
+ H.visitDocument("@documentId");
+
+ H.documentContent()
+ .findByRole("heading", { name: "First Heading" })
+ .realHover();
+
+ // Filter to visible one since all blocks have hidden buttons
+ cy.get('[data-testid="anchor-link-menu"]')
+ .filter(":visible")
+ .first()
+ .findByRole("button", { name: /copy link/i })
+ .should("be.visible");
+ });
+
+ it("should copy anchor URL to clipboard when clicking anchor link", () => {
+ H.visitDocument("@documentId");
+
+ cy.wrap(
+ Cypress.automation("remote:debugger:protocol", {
+ command: "Browser.grantPermissions",
+ params: {
+ permissions: ["clipboardReadWrite", "clipboardSanitizedWrite"],
+ origin: window.location.origin,
+ },
+ }),
+ );
+
+ H.documentContent()
+ .findByRole("heading", { name: "First Heading" })
+ .realHover();
+
+ // Filter to visible one since all blocks have hidden buttons
+ cy.get('[data-testid="anchor-link-menu"]')
+ .filter(":visible")
+ .first()
+ .findByRole("button", { name: /copy link/i })
+ .click();
+
+ cy.get("body").findByText("Copied!").should("be.visible");
+
+ cy.window().then((win) => {
+ win.navigator.clipboard.readText().then((text) => {
+ expect(text).to.include("/document/");
+ expect(text).to.include("#heading-block-1");
+ });
+ });
+ });
+
+ it("should scroll to the correct block when navigating with anchor hash", () => {
+ cy.get("@documentId").then((documentId) => {
+ cy.visit(`/document/${documentId}#heading-block-2`);
+
+ H.documentContent()
+ .findByRole("heading", { name: "Second Heading" })
+ .should("be.visible");
+
+ H.documentContent()
+ .findByRole("heading", { name: "First Heading" })
+ .should("not.be.visible");
+ });
+ });
+
+ it("should still show comments menu on right side (regression check)", () => {
+ H.visitDocument("@documentId");
+
+ H.documentContent()
+ .findByRole("heading", { name: "First Heading" })
+ .realHover();
+
+ // Filter to visible one since all blocks have hidden menus
+ cy.get('[data-testid="anchor-link-menu"]')
+ .filter(":visible")
+ .first()
+ .findByRole("button", { name: /copy link/i })
+ .should("be.visible");
+
+ // Comments button uses ForwardRefLink, so it's a link role not button
+ cy.get('[data-testid="comments-menu"]')
+ .filter(":visible")
+ .first()
+ .findByRole("link", { name: /comments/i })
+ .should("be.visible");
+ });
+ });
+
describe("error handling", () => {
it("should display an error toast when creating a new document fails", () => {
// setup
diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsx
index 8cdcc24596f..b55edab86ad 100644
--- a/frontend/src/metabase/documents/components/DocumentPage.tsx
+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx
@@ -8,6 +8,7 @@ import {
useCallback,
useEffect,
useMemo,
+ useRef,
useState,
} from "react";
import type { Route } from "react-router";
@@ -63,6 +64,7 @@ import {
} from "../documents.slice";
import { useDocumentState } from "../hooks/use-document-state";
import { useRegisterDocumentMetabotContext } from "../hooks/use-register-document-metabot-context";
+import { useScrollToAnchor } from "../hooks/use-scroll-to-anchor";
import {
getDraftCards,
getHasUnsavedChanges,
@@ -104,6 +106,7 @@ export const DocumentPage = ({
const [editorInstance, setEditorInstance] = useState<TiptapEditor | null>(
null,
);
+ const editorContainerRef = useRef<HTMLDivElement>(null);
const hasUnsavedEditorChanges = useSelector(getHasUnsavedChanges);
const [createDocument, { isLoading: isCreating }] =
useCreateDocumentMutation();
@@ -205,6 +208,14 @@ export const DocumentPage = ({
dispatch(setChildTargetId(paramsChildTargetId));
}, [dispatch, paramsChildTargetId]);
+ // Scroll to anchor block when navigating with URL hash
+ const blockId = location.hash ? location.hash.slice(1) : null;
+ useScrollToAnchor({
+ blockId,
+ editorContainerRef,
+ isLoading: isDocumentLoading,
+ });
+
const hasUnsavedChanges = useCallback(() => {
const currentTitle = documentTitle.trim();
const originalTitle = documentData?.name || "";
@@ -474,6 +485,7 @@ export const DocumentPage = ({
onChange={handleChange}
editable={canWrite}
isLoading={isDocumentLoading}
+ editorContainerRef={editorContainerRef}
/>
</Box>
</Box>
diff --git a/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkButton.tsx b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkButton.tsx
new file mode 100644
index 00000000000..814ce0bbf9b
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkButton.tsx
@@ -0,0 +1,54 @@
+import { useClipboard } from "@mantine/hooks";
+import type { ComponentPropsWithoutRef, ElementType } from "react";
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import { isPlainKey } from "metabase/common/utils/keyboard";
+import { Button, type ButtonProps, Icon, Text, Tooltip } from "metabase/ui";
+
+type Props<C extends ElementType = "button"> = ButtonProps & {
+ url: string;
+ onCopy?: () => void;
+ component?: C;
+} & Omit<ComponentPropsWithoutRef<C>, keyof ButtonProps | "component">;
+
+export const AnchorLinkButton = <C extends ElementType = "button">({
+ url,
+ onCopy,
+ ...props
+}: Props<C>) => {
+ const clipboard = useClipboard({ timeout: 2000 });
+
+ const handleCopy = useCallback(() => {
+ clipboard.copy(url);
+ onCopy?.();
+ }, [clipboard, url, onCopy]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLButtonElement>) => {
+ if (isPlainKey(e, "Enter") || isPlainKey(e, " ")) {
+ e.preventDefault();
+ handleCopy();
+ }
+ },
+ [handleCopy],
+ );
+
+ return (
+ <Tooltip
+ label={<Text fw={700} c="inherit">{t`Copied!`}</Text>}
+ opened={clipboard.copied}
+ >
+ <Button
+ {...(props as ButtonProps)}
+ aria-label={t`Copy link`}
+ bd={0}
+ leftSection={<Icon name="link" />}
+ px="sm"
+ size="xs"
+ onClick={handleCopy}
+ onKeyDown={handleKeyDown}
+ />
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkButton.unit.spec.tsx b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkButton.unit.spec.tsx
new file mode 100644
index 00000000000..15a28386779
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkButton.unit.spec.tsx
@@ -0,0 +1,81 @@
+import userEvent from "@testing-library/user-event";
+
+import { render, screen } from "__support__/ui";
+
+import { AnchorLinkButton } from "./AnchorLinkButton";
+
+const mockCopy = jest.fn();
+const mockClipboard = {
+ copy: mockCopy,
+ copied: false,
+};
+
+jest.mock("@mantine/hooks", () => ({
+ ...jest.requireActual("@mantine/hooks"),
+ useClipboard: () => mockClipboard,
+}));
+
+describe("AnchorLinkButton", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockClipboard.copied = false;
+ });
+
+ it("renders a link icon button", () => {
+ render(<AnchorLinkButton url="http://example.com/document/1#block-123" />);
+
+ const button = screen.getByRole("button", { name: /copy link/i });
+ expect(button).toBeInTheDocument();
+ });
+
+ it("copies URL to clipboard on click", async () => {
+ const url = "http://example.com/document/1#block-123";
+ render(<AnchorLinkButton url={url} />);
+
+ const button = screen.getByRole("button", { name: /copy link/i });
+ await userEvent.click(button);
+
+ expect(mockCopy).toHaveBeenCalledWith(url);
+ });
+
+ it("copies URL to clipboard on Enter key", async () => {
+ const user = userEvent.setup();
+ const url = "http://example.com/document/1#block-123";
+ render(<AnchorLinkButton url={url} />);
+
+ await user.tab();
+ await user.keyboard("{Enter}");
+
+ expect(mockCopy).toHaveBeenCalledWith(url);
+ });
+
+ it("copies URL to clipboard on Space key", async () => {
+ const user = userEvent.setup();
+ const url = "http://example.com/document/1#block-123";
+ render(<AnchorLinkButton url={url} />);
+
+ await user.tab();
+ await user.keyboard(" ");
+
+ expect(mockCopy).toHaveBeenCalledWith(url);
+ });
+
+ it("shows 'Copied!' tooltip after click", async () => {
+ mockClipboard.copied = true;
+ const url = "http://example.com/document/1#block-123";
+ render(<AnchorLinkButton url={url} />);
+
+ expect(screen.getByText("Copied!")).toBeInTheDocument();
+ });
+
+ it("calls onCopy callback when provided", async () => {
+ const onCopy = jest.fn();
+ const url = "http://example.com/document/1#block-123";
+ render(<AnchorLinkButton url={url} onCopy={onCopy} />);
+
+ const button = screen.getByRole("button", { name: /copy link/i });
+ await userEvent.click(button);
+
+ expect(onCopy).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.module.css b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.module.css
new file mode 100644
index 00000000000..48e159588e9
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.module.css
@@ -0,0 +1,13 @@
+.anchorLinkMenu {
+ opacity: 0;
+ user-select: none;
+
+ &:hover,
+ &:focus-within {
+ opacity: 1;
+ }
+}
+
+.visible {
+ opacity: 1;
+}
diff --git a/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.tsx b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.tsx
new file mode 100644
index 00000000000..630cbd9b0fa
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.tsx
@@ -0,0 +1,35 @@
+import cx from "classnames";
+import { type CSSProperties, forwardRef } from "react";
+import { createPortal } from "react-dom";
+
+import { Box } from "metabase/ui";
+
+import { AnchorLinkButton } from "./AnchorLinkButton";
+import S from "./AnchorLinkMenu.module.css";
+
+interface Props {
+ show: boolean;
+ style: CSSProperties;
+ url: string;
+}
+
+export const AnchorLinkMenu = forwardRef<HTMLDivElement, Props>(
+ function AnchorLinkMenu({ show, style, url }: Props, ref) {
+ return createPortal(
+ <Box
+ className={cx(S.anchorLinkMenu, {
+ [S.visible]: show,
+ })}
+ contentEditable={false}
+ data-testid="anchor-link-menu"
+ draggable={false}
+ pr="0.75rem"
+ ref={ref}
+ style={style}
+ >
+ <AnchorLinkButton url={url} variant="default" />
+ </Box>,
+ document.body,
+ );
+ },
+);
diff --git a/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.unit.spec.tsx b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.unit.spec.tsx
new file mode 100644
index 00000000000..e1a536ab144
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/AnchorLinkMenu.unit.spec.tsx
@@ -0,0 +1,76 @@
+import { render, screen } from "__support__/ui";
+
+import { AnchorLinkMenu } from "./AnchorLinkMenu";
+
+const mockCopy = jest.fn();
+const mockClipboard = {
+ copy: mockCopy,
+ copied: false,
+};
+
+jest.mock("@mantine/hooks", () => ({
+ ...jest.requireActual("@mantine/hooks"),
+ useClipboard: () => mockClipboard,
+}));
+
+describe("AnchorLinkMenu", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockClipboard.copied = false;
+ });
+
+ it("renders AnchorLinkButton with correct URL", () => {
+ const url = "http://example.com/document/1#block-123";
+ render(
+ <AnchorLinkMenu url={url} show={true} style={{ position: "absolute" }} />,
+ );
+
+ const button = screen.getByRole("button", { name: /copy link/i });
+ expect(button).toBeInTheDocument();
+ });
+
+ it("renders into a portal in document.body", () => {
+ const url = "http://example.com/document/1#block-123";
+ render(
+ <AnchorLinkMenu url={url} show={true} style={{ position: "absolute" }} />,
+ );
+
+ // Menu should be portaled to document.body
+ const menu = document.body.querySelector(
+ '[data-testid="anchor-link-menu"]',
+ );
+ expect(menu).toBeInTheDocument();
+ });
+
+ it("applies show prop styles", () => {
+ const url = "http://example.com/document/1#block-123";
+ render(
+ <AnchorLinkMenu
+ url={url}
+ show={false}
+ style={{ position: "absolute" }}
+ />,
+ );
+
+ // Menu should be in DOM (just hidden via CSS opacity)
+ const menu = document.body.querySelector(
+ '[data-testid="anchor-link-menu"]',
+ );
+ expect(menu).toBeInTheDocument();
+ });
+
+ it("accepts ref for floating-ui positioning", () => {
+ const url = "http://example.com/document/1#block-123";
+ const ref = jest.fn();
+ render(
+ <AnchorLinkMenu
+ url={url}
+ show={true}
+ style={{ position: "absolute" }}
+ ref={ref}
+ />,
+ );
+
+ expect(ref).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/index.ts b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/index.ts
new file mode 100644
index 00000000000..f7b5c12c98b
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/AnchorLinkMenu/index.ts
@@ -0,0 +1 @@
+export * from "./AnchorLinkMenu";
diff --git a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx
index ffea5a0d27e..fe95142e698 100644
--- a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx
+++ b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx
@@ -42,6 +42,7 @@ export const CommentsMenu = forwardRef<HTMLDivElement, Props>(
[S.visible]: show || hasUnresolvedComments,
})}
contentEditable={false}
+ data-testid="comments-menu"
draggable={false}
mt={rem(-2)}
pl="lg"
diff --git a/frontend/src/metabase/documents/components/Editor/Editor.tsx b/frontend/src/metabase/documents/components/Editor/Editor.tsx
index f6fcccb9c58..c0f27cdb552 100644
--- a/frontend/src/metabase/documents/components/Editor/Editor.tsx
+++ b/frontend/src/metabase/documents/components/Editor/Editor.tsx
@@ -90,6 +90,8 @@ export interface EditorProps {
onQuestionSelect?: (cardId: number | null) => void;
editable?: boolean;
isLoading?: boolean;
+ /** Ref to the editor container for external access (e.g., anchor scrolling) */
+ editorContainerRef?: React.RefObject<HTMLDivElement>;
}
export const Editor: React.FC<EditorProps> = ({
@@ -100,6 +102,7 @@ export const Editor: React.FC<EditorProps> = ({
editable = true,
onQuestionSelect,
isLoading = false,
+ editorContainerRef,
}) => {
const siteUrl = useSelector((state) => getSetting(state, "site-url"));
const { getState } = useStore();
@@ -228,6 +231,7 @@ export const Editor: React.FC<EditorProps> = ({
<Box className={cx(S.editor, DND_IGNORE_CLASS_NAME)}>
<Box
className={S.editorContent}
+ ref={editorContainerRef}
onClick={(e) => {
// Focus editor when clicking on empty space
const target = e.target as HTMLElement;
diff --git a/frontend/src/metabase/documents/hooks/use-block-menus.ts b/frontend/src/metabase/documents/hooks/use-block-menus.ts
new file mode 100644
index 00000000000..5513af88d3f
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-block-menus.ts
@@ -0,0 +1,118 @@
+import { autoUpdate, useFloating } from "@floating-ui/react";
+import type { Editor, NodeViewProps } from "@tiptap/core";
+import { useCallback, useEffect, useMemo, useState } from "react";
+
+import { useListCommentsQuery } from "metabase/api";
+import { getTargetChildCommentThreads } from "metabase/comments/utils";
+import {
+ getChildTargetId,
+ getCurrentDocument,
+ getHoveredChildTargetId,
+} from "metabase/documents/selectors";
+import { getListCommentsQuery } from "metabase/documents/utils/api";
+import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
+import { isWithinIframe } from "metabase/lib/dom";
+import { useSelector } from "metabase/lib/redux";
+import { documentWithAnchor } from "metabase/lib/urls";
+
+interface UseBlockMenusOptions {
+ node: NodeViewProps["node"];
+ editor: Editor;
+ getPos: NodeViewProps["getPos"];
+ /**
+ * Additional condition to hide menus (e.g., for comments context)
+ */
+ shouldHideMenus?: boolean;
+}
+
+/**
+ * Shared hook for block-level floating menus (anchor links on left, comments on right).
+ * Used by Heading, Paragraph, Blockquote, BulletList, OrderedList, and CodeBlock node views.
+ */
+export function useBlockMenus({
+ node,
+ editor,
+ getPos,
+ shouldHideMenus = false,
+}: UseBlockMenusOptions) {
+ const childTargetId = useSelector(getChildTargetId);
+ const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
+ const document = useSelector(getCurrentDocument);
+ const { data: commentsData } = useListCommentsQuery(
+ getListCommentsQuery(document),
+ );
+ const comments = commentsData?.comments;
+ const [hovered, setHovered] = useState(false);
+ const [rendered, setRendered] = useState(false);
+
+ const { _id } = node.attrs;
+ const isOpen = childTargetId === _id;
+ const isHovered = hoveredChildTargetId === _id;
+
+ const threads = useMemo(
+ () => getTargetChildCommentThreads(comments, _id),
+ [comments, _id],
+ );
+
+ const { refs: commentsRefs, floatingStyles: commentsFloatingStyles } =
+ useFloating({
+ placement: "right-start",
+ whileElementsMounted: autoUpdate,
+ strategy: "fixed",
+ open: rendered,
+ });
+
+ const { refs: anchorRefs, floatingStyles: anchorFloatingStyles } =
+ useFloating({
+ placement: "left",
+ whileElementsMounted: autoUpdate,
+ strategy: "fixed",
+ open: rendered,
+ });
+
+ useEffect(() => {
+ if (!rendered) {
+ setRendered(true);
+ }
+ }, [rendered]);
+
+ const isTopLevelBlock = isTopLevel({ editor, getPos });
+ const hasContent = node.textContent.trim().length > 0;
+ const shouldShowMenus =
+ document &&
+ rendered &&
+ !shouldHideMenus &&
+ isTopLevelBlock &&
+ !isWithinIframe() &&
+ hasContent;
+ const anchorUrl = document ? documentWithAnchor(document, _id) : "";
+
+ // Note: refs.setReference is stable (memoized internally by floating-ui),
+ // but the refs object itself is recreated each render. Depend on the
+ // stable setReference functions directly to avoid unnecessary re-renders.
+ const setReferenceElement = useCallback(
+ (el: HTMLElement | null) => {
+ commentsRefs.setReference(el);
+ anchorRefs.setReference(el);
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [commentsRefs.setReference, anchorRefs.setReference],
+ );
+
+ return {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ anchorUrl,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ anchorRefs,
+ anchorFloatingStyles,
+ };
+}
diff --git a/frontend/src/metabase/documents/hooks/use-scroll-to-anchor.ts b/frontend/src/metabase/documents/hooks/use-scroll-to-anchor.ts
new file mode 100644
index 00000000000..9fc89d21ee3
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-scroll-to-anchor.ts
@@ -0,0 +1,78 @@
+import { useEffect, useRef } from "react";
+
+import styles from "../components/DocumentPage.module.css";
+
+interface UseScrollToAnchorOptions {
+ /** The block ID to scroll to (from location.hash, without the #) */
+ blockId: string | null;
+ /** Ref to the editor's DOM container */
+ editorContainerRef: React.RefObject<HTMLElement>;
+ /** Whether the document is still loading */
+ isLoading: boolean;
+}
+
+/**
+ * Scrolls to and highlights a block element when navigating with an anchor hash.
+ * Uses MutationObserver to wait for the element to appear in the DOM.
+ */
+export function useScrollToAnchor({
+ blockId,
+ editorContainerRef,
+ isLoading,
+}: UseScrollToAnchorOptions): void {
+ const highlightedElementRef = useRef<Element | null>(null);
+ const highlightTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (!blockId || isLoading || !editorContainerRef.current) {
+ return;
+ }
+
+ const container = editorContainerRef.current;
+
+ const scrollToElement = (element: Element) => {
+ element.scrollIntoView({ behavior: "smooth", block: "start" });
+ element.classList.add(styles.highlighted);
+ highlightedElementRef.current = element;
+
+ highlightTimeoutRef.current = setTimeout(() => {
+ element.classList.remove(styles.highlighted);
+ highlightedElementRef.current = null;
+ }, 2000);
+ };
+
+ const selector = `[data-node-id="${CSS.escape(blockId)}"]`;
+ let observer: MutationObserver | null = null;
+
+ const existingElement = container.querySelector(selector);
+ if (existingElement) {
+ scrollToElement(existingElement);
+ } else {
+ observer = new MutationObserver(() => {
+ const element = container.querySelector(selector);
+ if (element) {
+ observer?.disconnect();
+ observer = null;
+ scrollToElement(element);
+ }
+ });
+
+ observer.observe(container, {
+ childList: true,
+ subtree: true,
+ });
+ }
+
+ return () => {
+ observer?.disconnect();
+ if (highlightTimeoutRef.current) {
+ clearTimeout(highlightTimeoutRef.current);
+ }
+ if (highlightedElementRef.current) {
+ highlightedElementRef.current.classList.remove(styles.highlighted);
+ }
+ };
+ }, [blockId, editorContainerRef, isLoading]);
+}
diff --git a/frontend/src/metabase/documents/hooks/use-scroll-to-anchor.unit.spec.ts b/frontend/src/metabase/documents/hooks/use-scroll-to-anchor.unit.spec.ts
new file mode 100644
index 00000000000..8bff863d4eb
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-scroll-to-anchor.unit.spec.ts
@@ -0,0 +1,194 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { createRef } from "react";
+
+import { getScrollIntoViewMock } from "__support__/ui";
+
+import { useScrollToAnchor } from "./use-scroll-to-anchor";
+
+jest.mock("../components/DocumentPage.module.css", () => ({
+ highlighted: "highlighted",
+}));
+
+describe("useScrollToAnchor", () => {
+ let container: HTMLDivElement;
+ let editorContainerRef: React.RefObject<HTMLDivElement>;
+ const mockScrollIntoView = getScrollIntoViewMock();
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ jest.clearAllMocks();
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+
+ editorContainerRef = createRef<HTMLDivElement>();
+ (editorContainerRef as { current: HTMLDivElement }).current = container;
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ // eslint-disable-next-line testing-library/no-node-access -- cleanup of test container
+ if (container.parentNode) {
+ document.body.removeChild(container);
+ }
+ });
+
+ it("does nothing when blockId is null", () => {
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: null,
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(mockScrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when isLoading is true", () => {
+ const targetElement = document.createElement("div");
+ targetElement.setAttribute("data-node-id", "test-block-123");
+ container.appendChild(targetElement);
+
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: "test-block-123",
+ editorContainerRef,
+ isLoading: true,
+ }),
+ );
+
+ expect(mockScrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when editorContainerRef.current is null", () => {
+ const nullRef = createRef<HTMLDivElement>();
+
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: "test-block-123",
+ editorContainerRef: nullRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(mockScrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("scrolls immediately if element already exists in DOM", () => {
+ const targetElement = document.createElement("div");
+ targetElement.setAttribute("data-node-id", "existing-block");
+ container.appendChild(targetElement);
+
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: "existing-block",
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(mockScrollIntoView).toHaveBeenCalledWith({
+ behavior: "smooth",
+ block: "start",
+ });
+ expect(targetElement).toHaveClass("highlighted");
+ });
+
+ it("uses MutationObserver when element doesn't exist yet and scrolls when element appears", async () => {
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: "delayed-block",
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(mockScrollIntoView).not.toHaveBeenCalled();
+
+ const targetElement = document.createElement("div");
+ targetElement.setAttribute("data-node-id", "delayed-block");
+ container.appendChild(targetElement);
+
+ await waitFor(() => {
+ expect(mockScrollIntoView).toHaveBeenCalledWith({
+ behavior: "smooth",
+ block: "start",
+ });
+ });
+ expect(targetElement).toHaveClass("highlighted");
+ });
+
+ it("removes highlight class after timeout", () => {
+ const targetElement = document.createElement("div");
+ targetElement.setAttribute("data-node-id", "highlight-test");
+ container.appendChild(targetElement);
+
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: "highlight-test",
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(targetElement).toHaveClass("highlighted");
+
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+
+ expect(targetElement).not.toHaveClass("highlighted");
+ });
+
+ it("cleanup disconnects observer on unmount when element not found", () => {
+ const { unmount } = renderHook(() =>
+ useScrollToAnchor({
+ blockId: "not-found-block",
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(mockScrollIntoView).not.toHaveBeenCalled();
+ expect(() => unmount()).not.toThrow();
+ });
+
+ it("cleanup clears timeout and removes highlight on unmount", () => {
+ const targetElement = document.createElement("div");
+ targetElement.setAttribute("data-node-id", "cleanup-test");
+ container.appendChild(targetElement);
+
+ const { unmount } = renderHook(() =>
+ useScrollToAnchor({
+ blockId: "cleanup-test",
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(targetElement).toHaveClass("highlighted");
+
+ unmount();
+
+ expect(targetElement).not.toHaveClass("highlighted");
+ });
+
+ it("handles special characters in blockId via CSS.escape", () => {
+ const specialId = "block-with-special-chars";
+ const targetElement = document.createElement("div");
+ targetElement.setAttribute("data-node-id", specialId);
+ container.appendChild(targetElement);
+
+ renderHook(() =>
+ useScrollToAnchor({
+ blockId: specialId,
+ editorContainerRef,
+ isLoading: false,
+ }),
+ );
+
+ expect(mockScrollIntoView).toHaveBeenCalled();
+ expect(targetElement).toHaveClass("highlighted");
+ });
+});
diff --git a/frontend/src/metabase/lib/urls/documents.ts b/frontend/src/metabase/lib/urls/documents.ts
index 0a7bdbfba6d..3bea6405c9b 100644
--- a/frontend/src/metabase/lib/urls/documents.ts
+++ b/frontend/src/metabase/lib/urls/documents.ts
@@ -13,3 +13,11 @@ export function publicDocument(uuid: string) {
const siteUrl = MetabaseSettings.get("site-url");
return `${siteUrl}/public/document/${uuid}`;
}
+
+export function documentWithAnchor(
+ document: Pick<Document, "id">,
+ blockId: string,
+) {
+ const siteUrl = MetabaseSettings.get("site-url");
+ return `${siteUrl}/document/${document.id}#${blockId}`;
+}
diff --git a/frontend/src/metabase/lib/urls/documents.unit.spec.ts b/frontend/src/metabase/lib/urls/documents.unit.spec.ts
new file mode 100644
index 00000000000..b11841eaf18
--- /dev/null
+++ b/frontend/src/metabase/lib/urls/documents.unit.spec.ts
@@ -0,0 +1,58 @@
+import { mockSettings } from "__support__/settings";
+
+import {
+ document,
+ documentWithAnchor,
+ newDocument,
+ publicDocument,
+} from "./documents";
+
+describe("urls > documents", () => {
+ describe("newDocument", () => {
+ it("returns the new document URL", () => {
+ expect(newDocument()).toBe("/document/new");
+ });
+ });
+
+ describe("document", () => {
+ it("returns document URL with id", () => {
+ expect(document({ id: 123 })).toBe("/document/123");
+ });
+ });
+
+ describe("publicDocument", () => {
+ it("returns full public document URL with site-url", () => {
+ mockSettings({ "site-url": "https://metabase.example.com" });
+
+ expect(publicDocument("abc-123-uuid")).toBe(
+ "https://metabase.example.com/public/document/abc-123-uuid",
+ );
+ });
+ });
+
+ describe("documentWithAnchor", () => {
+ it("returns full document URL with anchor hash", () => {
+ mockSettings({ "site-url": "https://metabase.example.com" });
+
+ expect(documentWithAnchor({ id: 456 }, "block-abc-123")).toBe(
+ "https://metabase.example.com/document/456#block-abc-123",
+ );
+ });
+
+ it("handles numeric document id", () => {
+ mockSettings({ "site-url": "http://localhost:3000" });
+
+ expect(documentWithAnchor({ id: 1 }, "heading-1")).toBe(
+ "http://localhost:3000/document/1#heading-1",
+ );
+ });
+
+ it("handles block ids with special characters", () => {
+ mockSettings({ "site-url": "https://example.com" });
+
+ expect(documentWithAnchor({ id: 42 }, "uuid-a1b2c3d4-e5f6")).toBe(
+ "https://example.com/document/42#uuid-a1b2c3d4-e5f6",
+ );
+ });
+ });
+});
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
index aaed593dc03..265bd9957b2 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
@@ -1,4 +1,3 @@
-import { autoUpdate, useFloating } from "@floating-ui/react";
import type { NodeViewProps } from "@tiptap/core";
import { Blockquote } from "@tiptap/extension-blockquote";
import {
@@ -7,20 +6,9 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useEffect, useMemo, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { CommentsMenu } from "metabase/documents/components/Editor/CommentsMenu";
-import {
- getChildTargetId,
- getCurrentDocument,
- getHoveredChildTargetId,
-} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
-import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
-import { isWithinIframe } from "metabase/lib/dom";
-import { useSelector } from "metabase/lib/redux";
+import { useBlockMenus } from "metabase/documents/hooks/use-block-menus";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -46,34 +34,19 @@ export const CustomBlockquote = Blockquote.extend({
});
export const BlockquoteNodeView = ({ node, editor, getPos }: NodeViewProps) => {
- const childTargetId = useSelector(getChildTargetId);
- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
- const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
- const [hovered, setHovered] = useState(false);
- const [rendered, setRendered] = useState(false); // floating ui wrongly positions things without this
- const { _id } = node.attrs;
- const isOpen = childTargetId === _id;
- const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const { refs, floatingStyles } = useFloating({
- placement: "right-start",
- whileElementsMounted: autoUpdate,
- strategy: "fixed",
- open: rendered,
- });
-
- useEffect(() => {
- if (!rendered) {
- setRendered(true);
- }
- }, [rendered]);
+ const {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ } = useBlockMenus({ node, editor, getPos });
return (
<>
@@ -82,26 +55,24 @@ export const BlockquoteNodeView = ({ node, editor, getPos }: NodeViewProps) => {
className={cx(S.root, {
[S.open]: isOpen || isHovered,
})}
- ref={refs.setReference}
+ data-node-id={_id}
+ ref={setReferenceElement}
onMouseOver={() => setHovered(true)}
onMouseOut={() => setHovered(false)}
>
<NodeViewContent<"blockquote"> as="blockquote" />
</NodeViewWrapper>
- {document &&
- rendered &&
- isTopLevel({ editor, getPos }) &&
- !isWithinIframe() && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- style={floatingStyles}
- threads={threads}
- />
- )}
+ {shouldShowMenus && document && (
+ <CommentsMenu
+ active={isOpen}
+ href={`/document/${document.id}/comments/${_id}`}
+ ref={commentsRefs.setFloating}
+ show={isOpen || hovered}
+ style={commentsFloatingStyles}
+ threads={threads}
+ />
+ )}
</>
);
};
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx
index 395d17f9f43..2754673c12e 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx
@@ -1,4 +1,3 @@
-import { autoUpdate, useFloating } from "@floating-ui/react";
import type { NodeViewProps } from "@tiptap/core";
import { BulletList } from "@tiptap/extension-bullet-list";
import {
@@ -7,20 +6,9 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useEffect, useMemo, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { CommentsMenu } from "metabase/documents/components/Editor/CommentsMenu";
-import {
- getChildTargetId,
- getCurrentDocument,
- getHoveredChildTargetId,
-} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
-import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
-import { isWithinIframe } from "metabase/lib/dom";
-import { useSelector } from "metabase/lib/redux";
+import { useBlockMenus } from "metabase/documents/hooks/use-block-menus";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -42,34 +30,19 @@ export const CustomBulletList = BulletList.extend({
});
export const BulletListNodeView = ({ node, editor, getPos }: NodeViewProps) => {
- const childTargetId = useSelector(getChildTargetId);
- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
- const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
- const [hovered, setHovered] = useState(false);
- const [rendered, setRendered] = useState(false); // floating ui wrongly positions things without this
- const { _id } = node.attrs;
- const isOpen = childTargetId === _id;
- const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const { refs, floatingStyles } = useFloating({
- placement: "right-start",
- whileElementsMounted: autoUpdate,
- strategy: "fixed",
- open: rendered,
- });
-
- useEffect(() => {
- if (!rendered) {
- setRendered(true);
- }
- }, [rendered]);
+ const {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ } = useBlockMenus({ node, editor, getPos });
return (
<>
@@ -78,7 +51,8 @@ export const BulletListNodeView = ({ node, editor, getPos }: NodeViewProps) => {
className={cx(S.root, {
[S.open]: isOpen || isHovered,
})}
- ref={refs.setReference}
+ data-node-id={_id}
+ ref={setReferenceElement}
// onMouseEnter/onMouseLeave do not work on list elements living in contentEditable
onMouseOver={() => setHovered(true)}
onMouseOut={() => setHovered(false)}
@@ -86,19 +60,16 @@ export const BulletListNodeView = ({ node, editor, getPos }: NodeViewProps) => {
<NodeViewContent<"ul"> as="ul" />
</NodeViewWrapper>
- {document &&
- rendered &&
- isTopLevel({ editor, getPos }) &&
- !isWithinIframe() && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- threads={threads}
- style={floatingStyles}
- />
- )}
+ {shouldShowMenus && document && (
+ <CommentsMenu
+ active={isOpen}
+ href={`/document/${document.id}/comments/${_id}`}
+ ref={commentsRefs.setFloating}
+ show={isOpen || hovered}
+ style={commentsFloatingStyles}
+ threads={threads}
+ />
+ )}
</>
);
};
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
index 0753668ec54..04c6dbd7e64 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
@@ -1,4 +1,3 @@
-import { autoUpdate, useFloating } from "@floating-ui/react";
import type { NodeViewProps } from "@tiptap/core";
import { CodeBlock } from "@tiptap/extension-code-block";
import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
@@ -8,20 +7,9 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useEffect, useMemo, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { CommentsMenu } from "metabase/documents/components/Editor/CommentsMenu";
-import {
- getChildTargetId,
- getCurrentDocument,
- getHoveredChildTargetId,
-} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
-import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
-import { isWithinIframe } from "metabase/lib/dom";
-import { useSelector } from "metabase/lib/redux";
+import { useBlockMenus } from "metabase/documents/hooks/use-block-menus";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -122,34 +110,19 @@ export const CustomCodeBlock = CodeBlock.extend({
});
export const CodeBlockNodeView = ({ node, editor, getPos }: NodeViewProps) => {
- const childTargetId = useSelector(getChildTargetId);
- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
- const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
- const [hovered, setHovered] = useState(false);
- const [rendered, setRendered] = useState(false); // floating ui wrongly positions things without this
- const { _id } = node.attrs;
- const isOpen = childTargetId === _id;
- const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const { refs, floatingStyles } = useFloating({
- placement: "right-start",
- whileElementsMounted: autoUpdate,
- strategy: "fixed",
- open: rendered,
- });
-
- useEffect(() => {
- if (!rendered) {
- setRendered(true);
- }
- }, [rendered]);
+ const {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ } = useBlockMenus({ node, editor, getPos });
return (
<>
@@ -158,7 +131,8 @@ export const CodeBlockNodeView = ({ node, editor, getPos }: NodeViewProps) => {
className={cx(S.root, {
[S.open]: isOpen || isHovered,
})}
- ref={refs.setReference}
+ data-node-id={_id}
+ ref={setReferenceElement}
onMouseOver={() => setHovered(true)}
onMouseOut={() => setHovered(false)}
>
@@ -174,19 +148,16 @@ export const CodeBlockNodeView = ({ node, editor, getPos }: NodeViewProps) => {
</pre>
</NodeViewWrapper>
- {document &&
- rendered &&
- isTopLevel({ editor, getPos }) &&
- !isWithinIframe() && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- threads={threads}
- style={floatingStyles}
- />
- )}
+ {shouldShowMenus && document && (
+ <CommentsMenu
+ active={isOpen}
+ href={`/document/${document.id}/comments/${_id}`}
+ ref={commentsRefs.setFloating}
+ show={isOpen || hovered}
+ style={commentsFloatingStyles}
+ threads={threads}
+ />
+ )}
</>
);
};
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
index 201e1e8f551..ed33513ccf5 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
@@ -1,4 +1,3 @@
-import { autoUpdate, useFloating } from "@floating-ui/react";
import type { NodeViewProps } from "@tiptap/core";
import { Heading } from "@tiptap/extension-heading";
import {
@@ -7,20 +6,10 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useEffect, useMemo, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
+import { AnchorLinkMenu } from "metabase/documents/components/Editor/AnchorLinkMenu";
import { CommentsMenu } from "metabase/documents/components/Editor/CommentsMenu";
-import {
- getChildTargetId,
- getCurrentDocument,
- getHoveredChildTargetId,
-} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
-import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
-import { isWithinIframe } from "metabase/lib/dom";
-import { useSelector } from "metabase/lib/redux";
+import { useBlockMenus } from "metabase/documents/hooks/use-block-menus";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -59,34 +48,24 @@ const levelNodeMap: Record<Level, ElementType> = {
};
export const HeadingNodeView = ({ node, editor, getPos }: NodeViewProps) => {
- const childTargetId = useSelector(getChildTargetId);
- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
- const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
- const [hovered, setHovered] = useState(false);
- const [rendered, setRendered] = useState(false); // floating ui wrongly positions things without this
- const { _id, level } = node.attrs;
- const isOpen = childTargetId === _id;
- const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const { refs, floatingStyles } = useFloating({
- placement: "right-start",
- whileElementsMounted: autoUpdate,
- strategy: "fixed",
- open: rendered,
- });
+ const { level } = node.attrs;
- useEffect(() => {
- if (!rendered) {
- setRendered(true);
- }
- }, [rendered]);
+ const {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ anchorUrl,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ anchorRefs,
+ anchorFloatingStyles,
+ } = useBlockMenus({ node, editor, getPos });
return (
<>
@@ -95,7 +74,8 @@ export const HeadingNodeView = ({ node, editor, getPos }: NodeViewProps) => {
className={cx(S.root, {
[S.open]: isOpen || isHovered,
})}
- ref={refs.setReference}
+ data-node-id={_id}
+ ref={setReferenceElement}
onMouseOver={() => setHovered(true)}
onMouseOut={() => setHovered(false)}
>
@@ -104,19 +84,24 @@ export const HeadingNodeView = ({ node, editor, getPos }: NodeViewProps) => {
/>
</NodeViewWrapper>
- {document &&
- rendered &&
- isTopLevel({ editor, getPos }) &&
- !isWithinIframe() && (
+ {shouldShowMenus && document && (
+ <>
+ <AnchorLinkMenu
+ ref={anchorRefs.setFloating}
+ show={hovered}
+ style={anchorFloatingStyles}
+ url={anchorUrl}
+ />
<CommentsMenu
active={isOpen}
href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
+ ref={commentsRefs.setFloating}
show={isOpen || hovered}
+ style={commentsFloatingStyles}
threads={threads}
- style={floatingStyles}
/>
- )}
+ </>
+ )}
</>
);
};
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx
index 469cf3521e8..057d4a8f797 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx
@@ -1,4 +1,3 @@
-import { autoUpdate, useFloating } from "@floating-ui/react";
import type { NodeViewProps } from "@tiptap/core";
import { OrderedList } from "@tiptap/extension-ordered-list";
import {
@@ -7,20 +6,9 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useEffect, useMemo, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { CommentsMenu } from "metabase/documents/components/Editor/CommentsMenu";
-import {
- getChildTargetId,
- getCurrentDocument,
- getHoveredChildTargetId,
-} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
-import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
-import { isWithinIframe } from "metabase/lib/dom";
-import { useSelector } from "metabase/lib/redux";
+import { useBlockMenus } from "metabase/documents/hooks/use-block-menus";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -58,34 +46,19 @@ export const OrderedListNodeView = ({
editor,
getPos,
}: NodeViewProps) => {
- const childTargetId = useSelector(getChildTargetId);
- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
- const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
- const [hovered, setHovered] = useState(false);
- const [rendered, setRendered] = useState(false); // floating ui wrongly positions things without this
- const { _id } = node.attrs;
- const isOpen = childTargetId === _id;
- const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const { refs, floatingStyles } = useFloating({
- placement: "right-start",
- whileElementsMounted: autoUpdate,
- strategy: "fixed",
- open: rendered,
- });
-
- useEffect(() => {
- if (!rendered) {
- setRendered(true);
- }
- }, [rendered]);
+ const {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ } = useBlockMenus({ node, editor, getPos });
return (
<>
@@ -94,7 +67,8 @@ export const OrderedListNodeView = ({
className={cx(S.root, {
[S.open]: isOpen || isHovered,
})}
- ref={refs.setReference}
+ data-node-id={_id}
+ ref={setReferenceElement}
// onMouseEnter/onMouseLeave do not work on list elements living in contentEditable
onMouseOver={() => setHovered(true)}
onMouseOut={() => setHovered(false)}
@@ -102,19 +76,16 @@ export const OrderedListNodeView = ({
<NodeViewContent<"ol"> as="ol" />
</NodeViewWrapper>
- {document &&
- rendered &&
- !isWithinIframe() &&
- isTopLevel({ editor, getPos }) && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- threads={threads}
- style={floatingStyles}
- />
- )}
+ {shouldShowMenus && document && (
+ <CommentsMenu
+ active={isOpen}
+ href={`/document/${document.id}/comments/${_id}`}
+ ref={commentsRefs.setFloating}
+ show={isOpen || hovered}
+ style={commentsFloatingStyles}
+ threads={threads}
+ />
+ )}
</>
);
};
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx
index 2f373194838..218cc8309b0 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx
@@ -1,4 +1,3 @@
-import { autoUpdate, useFloating } from "@floating-ui/react";
import type { NodeViewProps } from "@tiptap/core";
import { Paragraph } from "@tiptap/extension-paragraph";
import {
@@ -7,20 +6,9 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useEffect, useMemo, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { CommentsMenu } from "metabase/documents/components/Editor/CommentsMenu";
-import {
- getChildTargetId,
- getCurrentDocument,
- getHoveredChildTargetId,
-} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
-import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
-import { isWithinIframe } from "metabase/lib/dom";
-import { useSelector } from "metabase/lib/redux";
+import { useBlockMenus } from "metabase/documents/hooks/use-block-menus";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -48,36 +36,26 @@ export const ParagraphNodeView = ({
extension,
}: NodeViewProps) => {
const editorContext = extension?.options?.editorContext || "document";
- const shouldHideCommentMenu =
- editorContext === "comments" || isWithinIframe();
- const childTargetId = useSelector(getChildTargetId);
- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
- const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
- const [hovered, setHovered] = useState(false);
- const [rendered, setRendered] = useState(false); // floating ui wrongly positions things without this
- const { _id } = node.attrs;
- const isOpen = childTargetId === _id;
- const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const { refs, floatingStyles } = useFloating({
- placement: "right-start",
- whileElementsMounted: autoUpdate,
- strategy: "fixed",
- open: rendered,
- });
+ const hideMenusInContext = editorContext === "comments";
- useEffect(() => {
- if (!rendered) {
- setRendered(true);
- }
- }, [rendered]);
+ const {
+ _id,
+ isOpen,
+ isHovered,
+ hovered,
+ setHovered,
+ threads,
+ document,
+ shouldShowMenus,
+ setReferenceElement,
+ commentsRefs,
+ commentsFloatingStyles,
+ } = useBlockMenus({
+ node,
+ editor,
+ getPos,
+ shouldHideMenus: hideMenusInContext,
+ });
return (
<>
@@ -86,26 +64,24 @@ export const ParagraphNodeView = ({
className={cx(S.root, {
[S.open]: isOpen || isHovered,
})}
- ref={refs.setReference}
+ data-node-id={_id}
+ ref={setReferenceElement}
onMouseOver={() => setHovered(true)}
onMouseOut={() => setHovered(false)}
>
<NodeViewContent<"p"> as="p" />
</NodeViewWrapper>
- {document &&
- rendered &&
- !shouldHideCommentMenu &&
- isTopLevel({ editor, getPos }) && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- threads={threads}
- style={floatingStyles}
- />
- )}
+ {shouldShowMenus && document && (
+ <CommentsMenu
+ active={isOpen}
+ href={`/document/${document.id}/comments/${_id}`}
+ ref={commentsRefs.setFloating}
+ show={isOpen || hovered}
+ style={commentsFloatingStyles}
+ threads={threads}
+ />
+ )}
</>
);
};