Skip to content

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

Documents supporting text (#65705)

Brad Anderson6e0186703f38
diff --git a/.loki/reference/chrome_laptop_Components_Documents_Markdown.png b/.loki/reference/chrome_laptop_Components_Documents_Markdown.png
index 12822c6b922..e37cdcdbea3 100644
Binary files a/.loki/reference/chrome_laptop_Components_Documents_Markdown.png and b/.loki/reference/chrome_laptop_Components_Documents_Markdown.png differ
diff --git a/e2e/test/scenarios/documents/supporting-text.cy.spec.ts b/e2e/test/scenarios/documents/supporting-text.cy.spec.ts
new file mode 100644
index 00000000000..840a465a0c5
--- /dev/null
+++ b/e2e/test/scenarios/documents/supporting-text.cy.spec.ts
@@ -0,0 +1,458 @@
+import {
+ DOCUMENT_WITH_THREE_CARDS_AND_COLUMNS,
+ DOCUMENT_WITH_TWO_CARDS,
+} from "e2e/support/document-initial-data";
+
+const { H } = cy;
+
+describe("documents supporting text", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ });
+
+ it("should add supporting text to a standalone cardEmbed", () => {
+ H.createDocument({
+ name: "Supporting Text Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Verify no supporting text or flexContainer exists initially
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("not.exist");
+ H.documentContent().find('[data-type="flexContainer"]').should("not.exist");
+
+ // Open the card menu and click "Add supporting text"
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+
+ // Verify a flexContainer was created
+ H.documentContent().find('[data-type="flexContainer"]').should("exist");
+
+ // Verify supporting text was added
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("exist");
+
+ // Verify the supporting text has the placeholder text
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("contain.text", "Write whatever you'd like to");
+
+ // Verify the flexContainer contains both supporting text and the card
+ H.documentContent()
+ .find('[data-type="flexContainer"]')
+ .within(() => {
+ cy.findByTestId("document-card-supporting-text").should("exist");
+ cy.findByTestId("document-card-embed").should("exist");
+ });
+
+ // Verify the card is still there
+ H.getDocumentCard("Orders").should("exist");
+ });
+
+ it("should add supporting text to a cardEmbed in a flexContainer", () => {
+ H.createDocument({
+ name: "Supporting Text Flex Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+ H.getDocumentCard("Orders, Count")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Create a flexContainer by dropping one card onto another
+ H.dragAndDropCardOnAnotherCard("Orders", "Orders, Count");
+
+ // Verify flexContainer was created
+ H.documentContent().find('[data-type="flexContainer"]').should("exist");
+
+ // Verify no supporting text exists yet
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("not.exist");
+
+ // Open the card menu and click "Add supporting text"
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+
+ // Verify supporting text was added at the beginning of the flexContainer
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("exist");
+
+ // Verify the supporting text has the placeholder text
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("contain.text", "Write whatever you'd like to");
+
+ // Verify the flexContainer now contains supporting text and both cards
+ H.documentContent()
+ .find('[data-type="flexContainer"]')
+ .within(() => {
+ cy.findByTestId("document-card-supporting-text").should("exist");
+ cy.findAllByTestId("document-card-embed").should("have.length", 2);
+ });
+ });
+
+ it("should allow editing supporting text content", () => {
+ H.createDocument({
+ name: "Edit Supporting Text Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Add supporting text
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+
+ // Verify supporting text was added
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("exist");
+
+ // Type some content
+ const testText = "# Hdg{enter}Lorem ipsum";
+ cy.realType(testText);
+
+ // Verify the text was added
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .contains("h1", "Hdg")
+ .should("exist");
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .contains("p", "Lorem ipsum")
+ .should("exist");
+ });
+
+ it("should disable 'Add supporting text' when supporting text already exists in flexContainer", () => {
+ H.createDocument({
+ name: "Disable Supporting Text Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Add supporting text to the first card
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+
+ // Verify supporting text was added
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("exist");
+
+ // Try to add another supporting text to the same flexContainer
+ H.openDocumentCardMenu("Orders");
+
+ // Verify the "Add supporting text" option is disabled
+ H.popover()
+ .findByText("Add supporting text")
+ .closest("button")
+ .should("have.attr", "data-disabled");
+ });
+
+ it("should disable 'Add supporting text' when flexContainer has 3 cards", () => {
+ H.createDocument({
+ name: "Max Cards Supporting Text Test Document",
+ document: DOCUMENT_WITH_THREE_CARDS_AND_COLUMNS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for all cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+ H.getDocumentCard("Orders, Count")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Add the third card to reach MAX_GROUP_SIZE
+ H.dragAndDropCardOnAnotherCard(
+ "Orders, Count, Grouped by Created At (year)",
+ "Orders",
+ { side: "right" },
+ );
+
+ // Verify flexContainer has 3 cards
+ H.documentContent()
+ .find('[data-type="flexContainer"]')
+ .within(() => {
+ cy.findAllByTestId("document-card-embed").should("have.length", 3);
+ });
+
+ // Open the card menu
+ H.openDocumentCardMenu("Orders");
+
+ // Verify the "Add supporting text" option is disabled
+ H.popover()
+ .findByText("Add supporting text")
+ .closest("button")
+ .should("have.attr", "data-disabled");
+ });
+
+ it("should remove supporting text when it becomes empty and Backspace is pressed", () => {
+ H.createDocument({
+ name: "Remove Empty Supporting Text Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Add supporting text
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+
+ // Verify supporting text was added
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("exist");
+
+ // Click into the supporting text
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .within(() => cy.get(".node-paragraph").click());
+
+ // Press Backspace to delete the empty supporting text
+ cy.realPress("Backspace");
+
+ // Verify supporting text was removed
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("not.exist");
+
+ // Verify the flexContainer was also removed (unwrapped)
+ H.documentContent().find('[data-type="flexContainer"]').should("not.exist");
+
+ // Verify the card is still there as a standalone card
+ H.getDocumentCard("Orders").should("exist");
+ });
+
+ it("should allow resizing supporting text and persist width after save", () => {
+ cy.intercept({
+ method: "GET",
+ path: "/api/ee/document/*",
+ }).as("documentGet");
+
+ H.createDocument({
+ name: "Resize Supporting Text Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for cards to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Add supporting text to create a flexContainer
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+
+ // Verify flexContainer and supporting text were created
+ H.documentContent().find('[data-type="flexContainer"]').should("exist");
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("exist");
+
+ // Get initial widths of supporting text and card
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .then(($supportingText) => {
+ const initialSupportingTextWidth = $supportingText.width() as number;
+ cy.wrap(initialSupportingTextWidth).as("initialSupportingTextWidth");
+
+ H.getDocumentCard("Orders").then(($card) => {
+ const initialCardWidth = $card.width() as number;
+ cy.wrap(initialCardWidth).as("initialCardWidth");
+ });
+ });
+
+ // Get the flex container and resize handles
+ const flexContainer = H.documentContent().find(
+ '[data-type="flexContainer"]',
+ );
+ const handles = H.getResizeHandlesForFlexContianer(flexContainer);
+
+ // Drag the handle to resize (increase supporting text width, decrease card width)
+ H.documentDoDrag(handles.eq(0), { x: 150 });
+
+ // Verify the widths changed
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .then(($supportingText) => {
+ const newSupportingTextWidth = $supportingText.width() as number;
+ cy.wrap(newSupportingTextWidth).as("newSupportingTextWidth");
+
+ H.getDocumentCard("Orders").then(($card) => {
+ const newCardWidth = $card.width() as number;
+ cy.wrap(newCardWidth).as("newCardWidth");
+
+ cy.get<number>("@initialSupportingTextWidth").then((initialWidth) => {
+ // Supporting text should be wider
+ expect(newSupportingTextWidth).to.be.greaterThan(initialWidth);
+ // The change should be close to the drag distance
+ expect(newSupportingTextWidth).to.be.closeTo(
+ initialWidth + 150,
+ 10,
+ );
+ });
+
+ cy.get<number>("@initialCardWidth").then((initialWidth) => {
+ // Card should be narrower
+ expect(newCardWidth).to.be.lessThan(initialWidth);
+ // The change should be close to the drag distance
+ expect(newCardWidth).to.be.closeTo(initialWidth - 150, 10);
+ });
+ });
+ });
+
+ // Click into the supporting text to edit it
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .within(() => cy.get(".node-paragraph").click());
+
+ // Type some content
+ const testText = "Supporting text for Orders chart";
+ cy.realType(testText);
+ cy.realPress("Tab");
+
+ // Verify the text was added
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("contain.text", testText);
+
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .should("contain.text", testText);
+
+ // Save the document
+ H.documentSaveButton().should("not.be.disabled").click();
+
+ // Wait for save confirmation
+ cy.findByTestId("toast-undo")
+ .should("be.visible")
+ .and("contain.text", "Document saved");
+
+ // Reload the page to verify persistence
+ cy.reload();
+
+ cy.wait("@documentGet");
+
+ // Wait for the document to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Verify the widths are still the same after reload
+ H.documentContent()
+ .findByTestId("document-card-supporting-text")
+ .then(($supportingText) => {
+ const reloadedSupportingTextWidth = $supportingText.width() as number;
+
+ H.getDocumentCard("Orders").then(($card) => {
+ const reloadedCardWidth = $card.width() as number;
+
+ cy.get<number>("@newSupportingTextWidth").then((savedWidth) => {
+ // Supporting text width should be preserved
+ expect(reloadedSupportingTextWidth).to.be.closeTo(savedWidth, 10);
+ });
+
+ cy.get<number>("@newCardWidth").then((savedWidth) => {
+ // Card width should be preserved
+ expect(reloadedCardWidth).to.be.closeTo(savedWidth, 10);
+ });
+ });
+ });
+ });
+
+ it("should remove supporting text when the last chart in its group is removed", () => {
+ H.createDocument({
+ name: "Supporting Text auto-cleanup",
+ document: DOCUMENT_WITH_THREE_CARDS_AND_COLUMNS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+ H.visitDocument("@documentId");
+
+ H.openDocumentCardMenu("Orders");
+ H.popover().findByText("Add supporting text").click();
+ cy.realType("Lorem ipsum");
+
+ const targetCardTitle = "Orders, Count, Grouped by Created At (year)";
+
+ cy.log("One card remaining in group, supportingText should exist");
+ H.dragAndDropCardOnAnotherCard("Orders", targetCardTitle);
+ H.documentContent().findByText("Lorem ipsum").should("exist");
+
+ cy.log("No cards remaining in group, supportingText should not exist");
+ H.dragAndDropCardOnAnotherCard("Orders, Count", targetCardTitle);
+ H.documentContent().findByText("Lorem ipsum").should("not.exist");
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/analytics.ts b/enterprise/frontend/src/metabase-enterprise/documents/analytics.ts
index 7e908cfdd72..fdfa85d95e0 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/analytics.ts
+++ b/enterprise/frontend/src/metabase-enterprise/documents/analytics.ts
@@ -57,3 +57,10 @@ export const trackDocumentBookmark = () => {
triggered_from: "document_header",
});
};
+
+export const trackDocumentAddSupportingText = (document?: Document | null) => {
+ trackSimpleEvent({
+ event: "document_add_supporting_text",
+ target_id: document?.id || null,
+ });
+};
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.css
index 1ce52cf3796..73659fd1d60 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
@@ -59,6 +59,14 @@
line-height: 1.4;
}
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(h1), :global(h2), :global(h3)):first-child:not(
+ :global(.editor-style-boundary) *
+ ) {
+ margin-top: 0;
+}
+
.editorContent
:global(.ProseMirror)
:global(p):not(:global(.editor-style-boundary) *) {
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx
index e6417f44e1d..fbee97e5112 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/Editor.tsx
@@ -39,6 +39,7 @@ import { MetabotMentionSuggestion } from "metabase-enterprise/rich_text_editing/
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 { SupportingText } from "metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText";
import { createSuggestionRenderer } from "metabase-enterprise/rich_text_editing/tiptap/extensions/suggestionRenderer";
import S from "./Editor.module.css";
@@ -50,10 +51,13 @@ const BUBBLE_MENU_DISALLOWED_NODES: string[] = [
MetabotNode.name,
SmartLink.name,
Image.name,
- FlexContainer.name,
"codeBlock",
];
+const BUBBLE_MENU_DISALLOWED_FULLY_SELECTED_NODES: string[] = [
+ SupportingText.name,
+];
+
const getMetabotPromptSerializer =
(getState: () => DocumentsStoreState): PromptSerializer =>
(node) => {
@@ -129,6 +133,7 @@ export const Editor: React.FC<EditorProps> = ({
}),
CardEmbed,
FlexContainer,
+ SupportingText,
MentionExtension.configure({
suggestion: {
allow: ({ state }) => !isMetabotBlock(state),
@@ -258,6 +263,9 @@ export const Editor: React.FC<EditorProps> = ({
<EditorBubbleMenu
editor={editor}
disallowedNodes={BUBBLE_MENU_DISALLOWED_NODES}
+ disallowedFullySelectedNodes={
+ BUBBLE_MENU_DISALLOWED_FULLY_SELECTED_NODES
+ }
/>
)}
<Box pos="absolute" top={0} left={0} w="100%">
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json
index 1280e3e2030..dc2750f722a 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/data/data.json
@@ -34,7 +34,8 @@
}
}
]
- }
+ },
+ { "type": "paragraph" }
]
},
"card114Query": {
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/constants.ts b/enterprise/frontend/src/metabase-enterprise/documents/constants.ts
index 6b2fb534c43..4e84398bdbf 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/constants.ts
+++ b/enterprise/frontend/src/metabase-enterprise/documents/constants.ts
@@ -1 +1,3 @@
export const DOCUMENT_TITLE_MAX_LENGTH = 100;
+
+export const MAX_GROUP_SIZE = 3;
diff --git a/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx
index bcdc74ec873..cb6204639f8 100644
--- a/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx
@@ -22,6 +22,7 @@ import { CustomStarterKit } from "metabase-enterprise/rich_text_editing/tiptap/e
import { FlexContainer } from "metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer";
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 { SupportingText } from "metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText";
import type { Document } from "metabase-types/api";
import S from "./PublicDocument.module.css";
@@ -77,6 +78,7 @@ export const PublicDocument = ({ params }: PublicDocumentProps) => {
CardEmbed,
FlexContainer,
ResizeNode,
+ SupportingText,
],
[siteUrl],
);
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.tsx
index 0aed11d4695..f37ed27b753 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
@@ -41,6 +41,7 @@ const DEFAULT_ALLOWED_FORMATTING: FormattingOptions = {
interface EditorBubbleMenuProps {
editor: TiptapEditor;
disallowedNodes: string[];
+ disallowedFullySelectedNodes?: string[];
allowedFormatting?: FormattingOptions;
options?: BubbleMenuOptions["options"];
className?: string;
@@ -49,6 +50,7 @@ interface EditorBubbleMenuProps {
export const EditorBubbleMenu: React.FC<EditorBubbleMenuProps> = ({
editor,
disallowedNodes,
+ disallowedFullySelectedNodes,
allowedFormatting = DEFAULT_ALLOWED_FORMATTING,
options,
className,
@@ -123,8 +125,13 @@ export const EditorBubbleMenu: React.FC<EditorBubbleMenuProps> = ({
// Check if selection contains any disallowed nodes
let hasDisallowedNode = false;
- state.doc.nodesBetween(from, to, (node) => {
- if (disallowedNodes.includes(node.type.name)) {
+ state.doc.nodesBetween(from, to, (node, pos) => {
+ if (disallowedFullySelectedNodes?.includes(node.type.name)) {
+ if (from <= pos && to >= pos + node.nodeSize) {
+ hasDisallowedNode = true;
+ return false;
+ }
+ } else if (disallowedNodes.includes(node.type.name)) {
hasDisallowedNode = true;
return false; // Stop traversing
}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
index 657a6db21f8..666bbc136cf 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
@@ -20,6 +20,7 @@ import {
getHoveredChildTargetId,
} from "metabase-enterprise/documents/selectors";
import { getListCommentsQuery } from "metabase-enterprise/documents/utils/api";
+import { isTopLevel } from "metabase-enterprise/documents/utils/editorNodeUtils";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -44,7 +45,7 @@ export const CustomBlockquote = Blockquote.extend({
},
});
-export const BlockquoteNodeView = ({ node }: NodeViewProps) => {
+export const BlockquoteNodeView = ({ node, editor, getPos }: NodeViewProps) => {
const childTargetId = useSelector(getChildTargetId);
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
@@ -88,16 +89,19 @@ export const BlockquoteNodeView = ({ node }: NodeViewProps) => {
<NodeViewContent<"blockquote"> as="blockquote" />
</NodeViewWrapper>
- {document && rendered && !isWithinIframe() && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- style={floatingStyles}
- threads={threads}
- />
- )}
+ {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}
+ />
+ )}
</>
);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
index 0e31330748f..b88b9492eb8 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
@@ -1,4 +1,8 @@
-import { Node, mergeAttributes } from "@tiptap/core";
+import {
+ Node,
+ findParentNodeClosestToPos,
+ mergeAttributes,
+} from "@tiptap/core";
import {
type NodeViewProps,
NodeViewWrapper,
@@ -28,9 +32,13 @@ import { getGenericErrorMessage } from "metabase/visualizations/lib/errors";
import { useListCommentsQuery } from "metabase-enterprise/api";
import { getTargetChildCommentThreads } from "metabase-enterprise/comments/utils";
import { navigateToCardFromDocument } from "metabase-enterprise/documents/actions";
-import { trackDocumentReplaceCard } from "metabase-enterprise/documents/analytics";
+import {
+ trackDocumentAddSupportingText,
+ trackDocumentReplaceCard,
+} from "metabase-enterprise/documents/analytics";
import { getUnresolvedComments } from "metabase-enterprise/documents/components/Editor/CommentsMenu";
import { EDITOR_STYLE_BOUNDARY_CLASS } from "metabase-enterprise/documents/components/Editor/constants";
+import { MAX_GROUP_SIZE } from "metabase-enterprise/documents/constants";
import {
loadMetadataForDocumentCard,
openVizSettingsSidebar,
@@ -85,6 +93,7 @@ interface CardEmbedMenuActions {
setIsModifyModalOpen: (open: boolean) => void;
handleReplaceQuestion: () => void;
handleRemoveNode: () => void;
+ handleAddSupportingText?: () => void;
}
interface CardEmbedMenuState {
@@ -112,6 +121,7 @@ const CardEmbedMenuDropdown = ({
setIsModifyModalOpen,
handleReplaceQuestion,
handleRemoveNode,
+ handleAddSupportingText,
// State
menuView,
setMenuView,
@@ -151,6 +161,13 @@ const CardEmbedMenuDropdown = ({
{t`Comment`}
</Menu.Item>
)}
+ <Menu.Item
+ onClick={handleAddSupportingText}
+ disabled={!canWrite || !handleAddSupportingText}
+ leftSection={<Icon name="add_list" size={14} />}
+ >
+ {t`Add supporting text`}
+ </Menu.Item>
<Menu.Item
onClick={handleEditVisualizationSettings}
leftSection={<Icon name="palette" size={14} />}
@@ -385,6 +402,74 @@ export const CardEmbedComponent = memo(
const [isReplaceModalOpen, setIsReplaceModalOpen] = useState(false);
const [menuView, setMenuView] = useState<string | null>(null);
+ const shouldAllowAddingSupportingText = () => {
+ const pos = getPos();
+ if (!pos) {
+ return false;
+ }
+ const resolvedPos = editor.state.doc.resolve(pos);
+ const match = findParentNodeClosestToPos(
+ resolvedPos,
+ (n) => n.type.name === "flexContainer",
+ );
+ if (!match) {
+ return true;
+ }
+ if (match.node.content.childCount >= MAX_GROUP_SIZE) {
+ return false;
+ }
+ const hasSupportingText = match?.node.content.content.some(
+ (n) => n.type.name === "supportingText",
+ );
+ return !hasSupportingText;
+ };
+
+ const handleAddSupportingText = !shouldAllowAddingSupportingText()
+ ? undefined
+ : async () => {
+ await Promise.resolve(); // Wait for the menu to close. The transaction below may cause this item to disable and the mouseup isn't registered (so the menu stays open).
+ const pos = getPos();
+ if (!pos) {
+ return;
+ }
+ const resolvedPos = editor.state.doc.resolve(pos);
+ const match = findParentNodeClosestToPos(
+ resolvedPos,
+ (n) =>
+ n.type.name === "flexContainer" || n.type.name === "resizeNode",
+ );
+ if (!match) {
+ return;
+ }
+ const { schema, tr } = editor.view.state;
+ const supportingText = schema.nodes.supportingText.create({}, [
+ schema.nodes.paragraph.create({}),
+ ]);
+ if (match.node.type.name === "flexContainer") {
+ tr.insert(match.start, supportingText);
+ editor.view.dispatch(tr);
+ editor.commands.focus(match.start + 1);
+ trackDocumentAddSupportingText(document);
+ return;
+ }
+ const flexContainer =
+ editor.view.state.schema.nodes.flexContainer.create(
+ {
+ columnWidths: [
+ (1 / MAX_GROUP_SIZE) * 100,
+ ((MAX_GROUP_SIZE - 1) / MAX_GROUP_SIZE) * 100,
+ ],
+ },
+ [supportingText, node],
+ );
+ const endPos = match.start + match.node.nodeSize;
+ tr.replaceWith(match.start, endPos, flexContainer);
+
+ editor.view.dispatch(tr);
+ editor.commands.focus(match.start + 2);
+ trackDocumentAddSupportingText(document);
+ };
+
const displayName = name || card?.name;
const question = useMemo(
() => (card != null ? new Question(card, metadata) : undefined),
@@ -720,6 +805,7 @@ export const CardEmbedComponent = memo(
handleEditVisualizationSettings={
handleEditVisualizationSettings
}
+ handleAddSupportingText={handleAddSupportingText}
setIsModifyModalOpen={setIsModifyModalOpen}
handleReplaceQuestion={handleReplaceQuestion}
handleRemoveNode={handleRemoveNode}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
index 80f45b6b5ea..25792b42757 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
@@ -21,6 +21,7 @@ import {
getHoveredChildTargetId,
} from "metabase-enterprise/documents/selectors";
import { getListCommentsQuery } from "metabase-enterprise/documents/utils/api";
+import { isTopLevel } from "metabase-enterprise/documents/utils/editorNodeUtils";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -120,7 +121,7 @@ export const CustomCodeBlock = CodeBlock.extend({
},
});
-export const CodeBlockNodeView = ({ node }: NodeViewProps) => {
+export const CodeBlockNodeView = ({ node, editor, getPos }: NodeViewProps) => {
const childTargetId = useSelector(getChildTargetId);
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
@@ -173,16 +174,19 @@ export const CodeBlockNodeView = ({ node }: NodeViewProps) => {
</pre>
</NodeViewWrapper>
- {document && rendered && !isWithinIframe() && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- threads={threads}
- style={floatingStyles}
- />
- )}
+ {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}
+ />
+ )}
</>
);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx
index 4248aa7c144..398e09d7865 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx
@@ -120,29 +120,39 @@ export const CommandSuggestion = forwardRef<
() => allCommandSections.flatMap((section) => section.items),
[allCommandSections],
);
+ const allowedCommandOptions = useMemo(() => {
+ return allCommandOptions.filter(
+ (item) => item.isAllowedAtPosition?.(editor) ?? true,
+ );
+ }, [allCommandOptions, editor]);
// Filter command options based on query when not in link search mode
const commandOptions = useMemo(() => {
if (viewMode === "linkTo" || viewMode === "embedQuestion") {
- return allCommandOptions;
+ return allowedCommandOptions;
}
if (!query) {
- return allCommandOptions;
+ return allowedCommandOptions;
}
const lowerQuery = query.toLowerCase();
- return allCommandOptions.filter((option) =>
+ return allowedCommandOptions.filter((option) =>
option.label.toLowerCase().includes(lowerQuery),
);
- }, [viewMode, query, allCommandOptions]);
+ }, [viewMode, query, allowedCommandOptions]);
const createQuestionsMenuItems = useCreateQuestionsMenuItems({
onSelectItem: setNewQuestionType,
});
+ const areChartsAllowed = !editor.isActive("supportingText");
+ const canBrowseAll = areChartsAllowed || viewMode === "linkTo";
+
const canCreateNewQuestion =
- createQuestionsMenuItems.length > 0 && viewMode !== "linkTo";
+ createQuestionsMenuItems.length > 0 &&
+ viewMode !== "linkTo" &&
+ areChartsAllowed;
const onSelectLinkEntity = useCallback(
(item: { id: number | string; model: string }) => {
@@ -174,11 +184,11 @@ export const CommandSuggestion = forwardRef<
query,
editor,
onSelectEntity: onSelectLinkEntity,
- enabled: true,
+ enabled: canBrowseAll,
searchModels:
viewMode === "linkTo" ? LINK_SEARCH_MODELS : EMBED_SEARCH_MODELS,
canFilterSearchModels: false,
- canBrowseAll: true,
+ canBrowseAll,
canCreateNewQuestion,
onTriggerCreateNewQuestion,
});
@@ -427,15 +437,15 @@ export const CommandSuggestion = forwardRef<
</>
) : (
// When not searching, show sections
- allCommandSections.map((section, sectionIndex) => {
- const filteredItems = section.items.filter((item) =>
- commandOptions.includes(item),
- );
- if (filteredItems.length === 0) {
- return null;
- }
-
- return (
+ allCommandSections
+ .map((section) => ({
+ ...section,
+ items: section.items.filter((item) =>
+ commandOptions.includes(item),
+ ),
+ }))
+ .filter((section) => section.items.length)
+ .map((section, sectionIndex) => (
<Box key={sectionIndex}>
{section.title && sectionIndex > 0 && (
<Box>
@@ -451,7 +461,7 @@ export const CommandSuggestion = forwardRef<
</Text>
</Box>
)}
- {filteredItems.map((option) => {
+ {section.items.map((option) => {
const index = commandOptions.indexOf(option);
return (
<CommandMenuItem
@@ -465,8 +475,7 @@ export const CommandSuggestion = forwardRef<
);
})}
</Box>
- );
- })
+ ))
)}
</>
) : (
@@ -476,7 +485,9 @@ export const CommandSuggestion = forwardRef<
</Box>
{query && (
<>
- <Divider my="sm" mx="sm" />
+ {(canCreateNewQuestion || canBrowseAll) && (
+ <Divider my="sm" mx="sm" />
+ )}
{canCreateNewQuestion && (
<CreateNewQuestionFooter
isSelected={selectedIndex === 0}
@@ -485,28 +496,30 @@ export const CommandSuggestion = forwardRef<
/>
)}
- <SearchResultsFooter
- isSelected={
- selectedIndex ===
- getBrowseAllItemIndex(
- searchMenuItems.length,
- canCreateNewQuestion,
- )
- }
- onMouseEnter={() =>
- setSelectedIndex(
+ {canBrowseAll && (
+ <SearchResultsFooter
+ isSelected={
+ selectedIndex ===
getBrowseAllItemIndex(
searchMenuItems.length,
canCreateNewQuestion,
- ),
- )
- }
- onClick={() => {
- // Switch to embed mode so selected questions get embedded
- setViewMode("embedQuestion");
- entityHandlers.openModal();
- }}
- />
+ )
+ }
+ onMouseEnter={() =>
+ setSelectedIndex(
+ getBrowseAllItemIndex(
+ searchMenuItems.length,
+ canCreateNewQuestion,
+ ),
+ )
+ }
+ onClick={() => {
+ // Switch to embed mode so selected questions get embedded
+ setViewMode("embedQuestion");
+ entityHandlers.openModal();
+ }}
+ />
+ )}
</>
)}
</>
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
index d5c4bd15d61..544384a59bb 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
@@ -121,6 +121,8 @@ const setup = ({
commands: {
focus: jest.fn(),
},
+ schema: { nodes: {} },
+ isActive: jest.fn(),
};
setupSearchEndpoints(SEARCH_ITEMS);
@@ -352,6 +354,8 @@ describe("CommandSuggestion", () => {
commands: {
focus: jest.fn(),
},
+ schema: { nodes: {} },
+ isActive: jest.fn(),
};
renderWithProviders(
@@ -391,6 +395,8 @@ describe("CommandSuggestion", () => {
commands: {
focus: jest.fn(),
},
+ schema: { nodes: {} },
+ isActive: jest.fn(),
};
renderWithProviders(
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/types.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/types.ts
index 961458f55b2..05991a275b1 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/types.ts
@@ -1,3 +1,5 @@
+import type { Editor } from "@tiptap/core";
+
import type { IconName } from "metabase/ui";
import type { MenuItem } from "metabase-enterprise/documents/components/Editor/shared/MenuComponents";
@@ -6,6 +8,7 @@ export interface CommandOption {
text?: string;
label: string;
command: string;
+ isAllowedAtPosition?: (editor: Editor) => boolean;
}
export interface CommandSection {
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/utils.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/utils.ts
index 4f5e26802a0..484f8961a74 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/utils.ts
@@ -11,16 +11,19 @@ export const getAllCommandSections = (): CommandSection[] => {
...(PLUGIN_METABOT.isEnabled()
? ([
{
- icon: "metabot",
+ icon: "metabot" as const,
label: t`Ask Metabot`,
command: "metabot",
+ isAllowedAtPosition: (editor) =>
+ !editor.isActive("supportingText"),
},
- ] as const)
+ ] satisfies CommandSection["items"])
: []),
{
icon: "lineandbar",
label: t`Chart`,
command: "embedQuestion",
+ isAllowedAtPosition: (editor) => !editor.isActive("supportingText"),
},
{
icon: "link",
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.module.css b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.module.css
index ab650a4fec1..bc1a57aa7f3 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.module.css
@@ -48,6 +48,19 @@
padding-right: 0;
}
+.flexContent :global(.node-supportingText) {
+ padding-left: 0.5rem;
+ padding-right: 0.5rem;
+}
+
+.flexContent :global(.node-supportingText):first-child {
+ padding-left: 0;
+}
+
+.flexContent :global(.node-supportingText):last-child {
+ padding-right: 0;
+}
+
/* Resize handles */
.resizeHandle {
position: absolute;
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.tsx
index bdacb30f405..302435d74c7 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.tsx
@@ -25,7 +25,7 @@ export const FlexContainer: Node<{
}> = Node.create({
name: "flexContainer",
group: "block",
- content: "cardEmbed{1,3}", // Contains 1-3 CardEmbed nodes only
+ content: "(supportingText | cardEmbed){1,3}", // Contains 1-3 CardEmbed or SupportingText nodes only
defining: true,
draggable: false,
selectable: false,
@@ -88,7 +88,7 @@ const FlexContainerComponent: React.FC<NodeViewProps> = ({
// Get column count and current widths
const columnCount = node.content.childCount;
- const currentWidths = node.attrs.columnWidths;
+ const currentWidths: number[] = node.attrs.columnWidths;
// Calculate default equal widths if not set
const columnWidths = useMemo(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToDocument.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToDocument.ts
index 484033c89af..b6accf31541 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToDocument.ts
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToDocument.ts
@@ -1,3 +1,5 @@
+import { Fragment, type Node as ProseMirrorNode } from "@tiptap/pm/model";
+
import {
RESIZE_NODE_DEFAULT_HEIGHT,
RESIZE_NODE_MIN_HEIGHT,
@@ -10,15 +12,30 @@ export const handleCardDropOnDocument = (payload: DroppedCardEmbedNodeData) => {
originalPos,
view,
cameFromFlexContainer,
- event: e,
cardEmbedNode,
dropPos,
} = payload;
+ let diffSize = 0;
+ const tr = view.state.tr;
+
+ /**
+ * Works like `tr.replaceWith` except keeps track of how much is added/deleted so previously calculated positions can be adjusted
+ */
+ const replaceWith = (
+ from: number,
+ to: number,
+ content: Fragment | ProseMirrorNode,
+ ) => {
+ const oldContentSize = to - from;
+ const newContentSize =
+ content instanceof Fragment ? content.size : content.nodeSize;
+ diffSize += newContentSize - oldContentSize;
+ return tr.replaceWith(from, to, content);
+ };
+
if (cameFromFlexContainer) {
// Handle moving from FlexContainer to document
if (originalPos !== null && originalParent?.type.name === "flexContainer") {
- const tr = view.state.tr;
-
// First, update/remove from FlexContainer (do this BEFORE insertion to avoid position shifting)
const flexContainerPos = view.state.doc.resolve(originalPos).before();
const flexContainer = originalParent;
@@ -56,19 +73,29 @@ export const handleCardDropOnDocument = (payload: DroppedCardEmbedNodeData) => {
if (containerParent.type.name === "resizeNode") {
// FlexContainer is wrapped in resizeNode, replace the entire wrapper
const wrapperPos = containerResolvedPos.before();
- tr.replaceWith(
+ replaceWith(
wrapperPos,
wrapperPos + containerParent.nodeSize,
wrappedRemainingCard,
);
} else {
// FlexContainer is not wrapped, just replace it
- tr.replaceWith(
+ replaceWith(
flexContainerPos,
flexContainerPos + flexContainer.nodeSize,
wrappedRemainingCard,
);
}
+ } else {
+ // Only a SupportingText is left, remove the entire FlexContainer and its wrapper
+ const containerResolvedPos = view.state.doc.resolve(flexContainerPos);
+ const containerParent = containerResolvedPos.parent;
+ const wrapperPos = containerResolvedPos.before();
+ replaceWith(
+ wrapperPos,
+ wrapperPos + containerParent.nodeSize,
+ Fragment.empty,
+ );
}
} else if (newChildren.length > 1) {
// Multiple cards left, keep as FlexContainer
@@ -76,7 +103,7 @@ export const handleCardDropOnDocument = (payload: DroppedCardEmbedNodeData) => {
flexContainer.attrs,
newChildren,
);
- tr.replaceWith(
+ replaceWith(
flexContainerPos,
flexContainerPos + flexContainer.nodeSize,
newFlexContainer,
@@ -89,12 +116,17 @@ export const handleCardDropOnDocument = (payload: DroppedCardEmbedNodeData) => {
if (containerParent.type.name === "resizeNode") {
// Remove the entire resizeNode wrapper
const wrapperPos = containerResolvedPos.before();
- tr.delete(wrapperPos, wrapperPos + containerParent.nodeSize);
+ replaceWith(
+ wrapperPos,
+ wrapperPos + containerParent.nodeSize,
+ Fragment.empty,
+ );
} else {
// Remove just the FlexContainer
- tr.delete(
+ replaceWith(
flexContainerPos,
flexContainerPos + flexContainer.nodeSize,
+ Fragment.empty,
);
}
}
@@ -111,15 +143,7 @@ export const handleCardDropOnDocument = (payload: DroppedCardEmbedNodeData) => {
// Calculate adjusted drop position if the FlexContainer operations affected positions
let adjustedDropPos = dropPos;
if (dropPos > flexContainerPos) {
- // If dropping after the FlexContainer, positions might have shifted
- // This is complex to calculate, so let's recalculate
- const coords = view.posAtCoords({
- left: e.clientX,
- top: e.clientY,
- });
- if (coords) {
- adjustedDropPos = tr.doc.resolve(coords.pos).pos;
- }
+ adjustedDropPos += diffSize;
}
tr.insert(adjustedDropPos, wrappedNode);
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToFlexContainer.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToFlexContainer.ts
index 82492b75e5f..db1516d1c30 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToFlexContainer.ts
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/DropHandlers/cardToFlexContainer.ts
@@ -213,6 +213,11 @@ export const handleCardDropToFlexContainer = (
wrappedRemainingCard,
);
}
+ } else {
+ tr.deleteRange(
+ sourceFlexContainerPos,
+ sourceFlexContainerPos + sourceFlexContainer.nodeSize,
+ );
}
} else if (sourceNewChildren.length > 1) {
// Multiple cards left in source, keep as flexContainer
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/HandleEditorDrop.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/HandleEditorDrop.tsx
index 26f8e3e1a74..44a500f91de 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/HandleEditorDrop.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/HandleEditorDrop.tsx
@@ -54,6 +54,10 @@ export const HandleEditorDrop = Extension.create({
return handleCardDropOnParagraph(cardEmbedInitialData);
}
+ if (dropToParent.type.name === "supportingText") {
+ return true;
+ }
+
// Check if dropping into document (not into another flexContainer or cardEmbed)
if (
dropToParent.type.name !== "flexContainer" &&
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/utils.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/utils.ts
index e6a6fcb3cd7..7365f3d83db 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/HandleEditorDrop/utils.ts
@@ -148,7 +148,9 @@ export const cleanupFlexContainerNodes = (view: EditorView) => {
const child = node.firstChild;
if (child) {
view.dispatch(
- view.state.tr.replaceWith(pos, pos + node.nodeSize, child),
+ child.type.name === "supportingText"
+ ? view.state.tr.deleteRange(pos, pos + node.nodeSize)
+ : view.state.tr.replaceWith(pos, pos + node.nodeSize, child),
);
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Heading/Heading.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
index cecb804be15..0260fcc34e0 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
@@ -20,6 +20,7 @@ import {
getHoveredChildTargetId,
} from "metabase-enterprise/documents/selectors";
import { getListCommentsQuery } from "metabase-enterprise/documents/utils/api";
+import { isTopLevel } from "metabase-enterprise/documents/utils/editorNodeUtils";
import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
import S from "../extensions.module.css";
@@ -57,7 +58,7 @@ const levelNodeMap: Record<Level, ElementType> = {
6: "h6",
};
-export const HeadingNodeView = ({ node }: NodeViewProps) => {
+export const HeadingNodeView = ({ node, editor, getPos }: NodeViewProps) => {
const childTargetId = useSelector(getChildTargetId);
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
@@ -103,16 +104,19 @@ export const HeadingNodeView = ({ node }: NodeViewProps) => {
/>
</NodeViewWrapper>
- {document && rendered && !isWithinIframe() && (
- <CommentsMenu
- active={isOpen}
- href={`/document/${document.id}/comments/${_id}`}
- ref={refs.setFloating}
- show={isOpen || hovered}
- threads={threads}
- style={floatingStyles}
- />
- )}
+ {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}
+ />
+ )}
</>
);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode.tsx
index 509135981bb..6fce97bf908 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode.tsx
@@ -23,7 +23,6 @@ export const ResizeNode: Node<{
name: "resizeNode",
group: "block",
content: "(flexContainer | cardEmbed)",
- atom: true,
draggable: false,
selectable: false,
disableDropCursor: true,
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.module.css b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.module.css
new file mode 100644
index 00000000000..cf7f1cd1e0f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.module.css
@@ -0,0 +1,66 @@
+.wrapper {
+ height: 100%;
+ position: relative;
+ border-radius: var(--mantine-radius-md);
+ overflow: hidden;
+ background-color: var(--mb-color-background-light);
+ border: 1px solid transparent;
+ transition:
+ background-color 150ms,
+ border-color 150ms;
+
+ &:hover {
+ background-color: color-mix(
+ in srgb,
+ var(--mb-color-background-inverse) 2%,
+ var(--mb-color-background-light)
+ );
+ }
+
+ &:not(:hover) .showOnHover:not(:focus-within) {
+ /* Inclusively hidden so it can still be focused via keyboard navigation */
+ clip: rect(0 0 0 0);
+ clip-path: inset(50%);
+ height: 1px;
+ overflow: hidden;
+ position: absolute;
+ white-space: nowrap;
+ width: 1px;
+ }
+
+ &.selected {
+ border-color: var(--mb-color-brand);
+ }
+}
+
+.scrollContainer {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ overflow: auto;
+ padding: 1.5rem 1rem;
+ cursor: text;
+ caret-color: auto;
+}
+
+.handle {
+ cursor: pointer;
+ height: 1rem;
+ position: absolute;
+ top: 0;
+ width: 100%;
+
+ &:focus-visible {
+ outline: none !important;
+ }
+}
+
+.placeholder {
+ position: absolute;
+ pointer-events: none;
+ color: var(--mb-color-text-light);
+}
+
+.commentsButton[data-variant="default"]:not(:hover) {
+ background-color: transparent;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
new file mode 100644
index 00000000000..5537eedfedc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
@@ -0,0 +1,221 @@
+import {
+ Node,
+ type NodeViewProps,
+ findParentNode,
+ mergeAttributes,
+} from "@tiptap/core";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import {
+ NodeViewContent,
+ NodeViewWrapper,
+ ReactNodeViewRenderer,
+} from "@tiptap/react";
+import cx from "classnames";
+import { useMemo } from "react";
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import { isWithinIframe } from "metabase/lib/dom";
+import { useDispatch, useSelector } from "metabase/lib/redux/hooks";
+import { Box } from "metabase/ui";
+import { useListCommentsQuery } from "metabase-enterprise/api/comment";
+import { getTargetChildCommentThreads } from "metabase-enterprise/comments/utils";
+import { getUnresolvedComments } from "metabase-enterprise/documents/components/Editor/CommentsMenu";
+import {
+ getChildTargetId,
+ getCurrentDocument,
+} from "metabase-enterprise/documents/selectors";
+import { getListCommentsQuery } from "metabase-enterprise/documents/utils/api";
+
+import { CommentsButton } from "../../components/CommentsButton";
+import { cleanupFlexContainerNodes } from "../HandleEditorDrop/utils";
+import { createIdAttribute, createProseMirrorPlugin } from "../NodeIds";
+
+import S from "./SupportingText.module.css";
+
+export const SupportingText = Node.create<{
+ HTMLAttributes: Record<string, any>;
+}>({
+ name: "supportingText",
+ group: "block",
+ content: "(paragraph|heading|bulletList|orderedList|blockquote|codeBlock)+",
+ draggable: true,
+ isolating: true,
+ disableDropCursor: true,
+
+ addAttributes() {
+ return {
+ ...createIdAttribute(),
+ };
+ },
+
+ addOptions() {
+ return {
+ HTMLAttributes: {},
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'div[data-type="supportingText"]',
+ },
+ ];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return [
+ "div",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "supportingText",
+ }),
+ 0,
+ ];
+ },
+
+ addNodeView() {
+ return ReactNodeViewRenderer(SupportingTextComponent);
+ },
+
+ addKeyboardShortcuts() {
+ return {
+ // Select all the text inside a SupportingText block if the user pressed cmd/ctrl+a inside one
+ "mod-a": ({ editor }) => {
+ const match = findParentNode((n) => n.type.name === this.name)(
+ editor.state.selection,
+ );
+ if (match) {
+ const from = match.pos + 2;
+ const to = match.pos + match.node.nodeSize - 2;
+ editor.commands.setTextSelection({ from, to });
+ return true;
+ }
+ return false;
+ },
+
+ // Remove this SupportingText block if the user hit Backspace and there was nothing in it
+ Backspace: ({ editor }) => {
+ const { selection } = editor.state;
+ if (!selection.empty) {
+ return false;
+ }
+ const match = findParentNode((n) => n.type === this.type)(selection);
+ if (!match) {
+ return false;
+ }
+ if (isNodeEmpty(match.node)) {
+ editor
+ .chain()
+ .setNodeSelection(match.pos)
+ .deleteSelection()
+ .focus(match.pos)
+ .run();
+ cleanupFlexContainerNodes(editor.view);
+ return true;
+ }
+
+ return false;
+ },
+ };
+ },
+
+ addProseMirrorPlugins() {
+ return [createProseMirrorPlugin(this.name)];
+ },
+});
+
+const isNodeEmpty = (node: ProseMirrorNode): boolean => {
+ const [firstChild] = node.content.content;
+ return node.content.content.length === 1 && !firstChild.content.size;
+};
+
+const SupportingTextComponent = ({
+ deleteNode,
+ editor,
+ getPos,
+ node,
+ selected,
+}: NodeViewProps) => {
+ const childTargetId = useSelector(getChildTargetId);
+ const document = useSelector(getCurrentDocument);
+ const { data: commentsData } = useListCommentsQuery(
+ getListCommentsQuery(document),
+ );
+ const comments = commentsData?.comments;
+ const { _id } = node.attrs;
+ const isOpen = childTargetId === _id;
+ const threads = useMemo(
+ () => getTargetChildCommentThreads(comments, _id),
+ [comments, _id],
+ );
+ const unresolvedCommentsCount = useMemo(
+ () => getUnresolvedComments(threads).length,
+ [threads],
+ );
+ const commentsPath = document
+ ? `/document/${document.id}/comments/${_id}`
+ : "";
+ const dispatch = useDispatch();
+
+ return (
+ <NodeViewWrapper
+ className={cx(S.wrapper, { [S.selected]: selected })}
+ data-testid="document-card-supporting-text"
+ >
+ <div className={S.scrollContainer}>
+ {isNodeEmpty(node) && (
+ <div contentEditable={false} className={S.placeholder}>
+ {t`Write whatever you'd like to`}
+ </div>
+ )}
+ <NodeViewContent />
+ </div>
+ <button
+ contentEditable={false}
+ aria-label={t`Supporting text`}
+ className={S.handle}
+ onClick={() => {
+ const pos = getPos();
+ pos && editor.commands.setNodeSelection(pos);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Backspace" || e.key === "Delete") {
+ const pos = getPos();
+ deleteNode();
+ cleanupFlexContainerNodes(editor.view);
+ if (pos != null) {
+ editor.commands.focus(pos);
+ }
+ }
+ }}
+ />
+ {document && !isWithinIframe() && (
+ <Box
+ pos="absolute"
+ top="0.25rem"
+ right="0.25rem"
+ className={cx({
+ [S.showOnHover]: !isOpen && !unresolvedCommentsCount,
+ })}
+ >
+ <CommentsButton
+ className={S.commentsButton}
+ disabled={!commentsPath}
+ variant={isOpen ? "filled" : "default"}
+ unresolvedCommentsCount={unresolvedCommentsCount}
+ onClick={(e) => {
+ e.preventDefault();
+ dispatch(
+ push(
+ unresolvedCommentsCount > 0
+ ? commentsPath
+ : `${commentsPath}?new=true`,
+ ),
+ );
+ }}
+ />
+ </Box>
+ )}
+ </NodeViewWrapper>
+ );
+};
diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.ts
index b27f8e18ccf..639e77d7565 100644
--- a/frontend/src/metabase-types/analytics/event.ts
+++ b/frontend/src/metabase-types/analytics/event.ts
@@ -317,6 +317,11 @@ export type DocumentPrintEvent = ValidateEvent<{
target_id: number | null;
}>;
+export type DocumentAddSupportingTextEvent = ValidateEvent<{
+ event: "document_add_supporting_text";
+ target_id: number | null;
+}>;
+
export type DatabaseHelpClickedEvent = ValidateEvent<{
event: "database_help_clicked";
triggered_from: "admin" | "setup";
@@ -537,6 +542,7 @@ export type SimpleEvent =
| TransformCreateEvent
| DocumentAddCardEvent
| DocumentAddSmartLinkEvent
+ | DocumentAddSupportingTextEvent
| DocumentAskMetabotEvent
| DocumentCreatedEvent
| DocumentReplaceCardEvent
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/add_list.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/add_list.svg
new file mode 100644
index 00000000000..4446baa9576
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/add_list.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <path d="M10.667 11.917a.75.75 0 0 1 0 1.5H2a.75.75 0 0 1 0-1.5h8.667zM12 5.25a.75.75 0 0 1 .75.75v1.25H14a.75.75 0 0 1 0 1.5h-1.25V10a.75.75 0 0 1-1.5 0V8.75H10a.75.75 0 0 1 0-1.5h1.25V6a.75.75 0 0 1 .75-.75zm-5.25 2a.75.75 0 0 1 0 1.5H2a.75.75 0 0 1 0-1.5h4.75zm3.917-4.667a.75.75 0 0 1 0 1.5H2a.75.75 0 0 1 0-1.5h8.667z" fill="currentcolor"/>
+</svg>
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
index 35b1078b642..d8bd3850744 100644
--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
@@ -12,6 +12,8 @@ import add_data_component from "./add_data.svg?component";
import add_data_source from "./add_data.svg?source";
import add_folder_component from "./add_folder.svg?component";
import add_folder_source from "./add_folder.svg?source";
+import add_list_component from "./add_list.svg?component";
+import add_list_source from "./add_list.svg?source";
import add_row_component from "./add_row.svg?component";
import add_row_source from "./add_row.svg?source";
import add_to_dash_component from "./add_to_dash.svg?component";
@@ -521,6 +523,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: add_folder_component,
source: add_folder_source,
},
+ add_list: {
+ component: add_list_component,
+ source: add_list_source,
+ },
add_row: {
component: add_row_component,
source: add_row_source,
@@ -1532,6 +1538,7 @@ export type IconName =
| "add_column"
| "add_data"
| "add_folder"
+ | "add_list"
| "add_row"
| "add_to_dash"
| "add_comment"