Skip to content

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

UXW-2172 UXW-2174 remove Document cards click actions (#65191)

Denis Berezin9c0910f652be
diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.ts
index d205ec41934..220a89e9610 100644
--- a/e2e/test/scenarios/documents/documents.cy.spec.ts
+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts
@@ -863,6 +863,7 @@ H.describeWithSnowplowEE("documents", () => {
H.getDocumentCard("Orders, Count, Grouped by Created At (year)").should(
"be.visible",
);
+
H.cartesianChartCircle().eq(1).click();
H.popover().findByText("See these Orders").click();
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts
index b41a86f0262..24dfae5fb71 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts
+++ b/enterprise/frontend/src/metabase-enterprise/documents/hooks/use-card-data.ts
@@ -18,7 +18,7 @@ interface UseCardDataProps {
id: number;
}
-interface UseCardDataResult {
+export interface UseCardDataResult {
card?: Card;
dataset?: Dataset;
isLoading: boolean;
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 2d506228a9d..a1786730d66 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
@@ -7,7 +7,6 @@ import {
import cx from "classnames";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { push } from "react-router-redux";
-import { useMount, useUnmount } from "react-use";
import { t } from "ttag";
import { Ellipsified } from "metabase/common/components/Ellipsified";
@@ -21,6 +20,7 @@ import { QuestionDownloadWidget } from "metabase/query_builder/components/Questi
import { useDownloadData } from "metabase/query_builder/components/QuestionDownloadWidget/use-download-data";
import { getMetadata } from "metabase/selectors/metadata";
import { Box, Flex, Icon, Loader, Menu, Text, TextInput } from "metabase/ui";
+import { DocumentMode } from "metabase/visualizations/click-actions/modes/DocumentMode";
import Visualization from "metabase/visualizations/components/Visualization";
import { ErrorView } from "metabase/visualizations/components/Visualization/ErrorView/ErrorView";
import ChartSkeleton from "metabase/visualizations/components/skeletons/ChartSkeleton";
@@ -47,7 +47,7 @@ import { usePublicDocumentContext } from "metabase-enterprise/public/contexts/Pu
import { usePublicDocumentCardData } from "metabase-enterprise/public/hooks/use-public-document-card-data";
import Question from "metabase-lib/v1/Question";
import { getUrl } from "metabase-lib/v1/urls";
-import type { Card, CardDisplayType, Dataset } from "metabase-types/api";
+import type { CardDisplayType, Dataset } from "metabase-types/api";
import { CommentsButton } from "../../components/CommentsButton";
import {
@@ -61,6 +61,9 @@ import styles from "./CardEmbedNode.module.css";
import { ModifyQuestionModal } from "./ModifyQuestionModal";
import { NativeQueryModal } from "./NativeQueryModal";
import { PublicDocumentCardMenu } from "./PublicDocumentCardMenu";
+import { useDndHelpers } from "./use-dnd-helpers";
+import { useUpdateCardOperations } from "./use-update-card-operations";
+import { getEmbedIndex } from "./utils";
interface CardEmbedMenuContext {
canWrite: boolean;
@@ -196,7 +199,6 @@ const CardEmbedMenuDropdown = ({
};
export const DROP_ZONE_COLOR = "var(--mb-color-brand)";
-const DRAG_LEAVE_TIMEOUT = 300;
interface DropZoneProps {
isOver: boolean;
@@ -352,26 +354,15 @@ export const CardEmbedComponent = memo(
const dispatch = useDispatch();
const canWrite = editor.options.editable;
- const isMountedRef = useRef(false);
+ const {
+ isBeingDragged,
+ dragState,
+ setDragState,
+ handleDragOver,
+ cardEmbedRef,
+ } = useDndHelpers({ editor, node, getPos });
- let embedIndex = -1;
-
- if (editor && getPos) {
- const currentPos = getPos() ?? 0;
- let nodeCount = 0;
-
- // Count cardEmbed nodes that appear before this position
- editor.state.doc.descendants((node, pos) => {
- if (node.type.name === "cardEmbed") {
- if (pos < currentPos) {
- nodeCount++;
- } else if (pos === currentPos) {
- embedIndex = nodeCount;
- return false; // Stop traversing
- }
- }
- });
- }
+ const embedIndex = getEmbedIndex(editor, getPos);
// Use public hook when viewing a public document, otherwise use regular hook
const isPublicDocument = Boolean(publicDocumentUuid);
@@ -393,14 +384,6 @@ export const CardEmbedComponent = memo(
const [isModifyModalOpen, setIsModifyModalOpen] = useState(false);
const [isReplaceModalOpen, setIsReplaceModalOpen] = useState(false);
const [menuView, setMenuView] = useState<string | null>(null);
- const [dragState, setDragState] = useState<{
- isDraggedOver: boolean;
- side: "left" | "right" | null;
- }>({ isDraggedOver: false, side: null });
- const draggedOverTimeoutRef = useRef<number | undefined>();
- const cardEmbedRef = useRef<HTMLDivElement>(null);
-
- const isBeingDragged = editor.view.draggingNode === node;
const displayName = name || card?.name;
const question = useMemo(
@@ -415,6 +398,19 @@ export const CardEmbedComponent = memo(
documentId: document?.id,
});
+ const {
+ handleChangeCardAndRun,
+ handleUpdateQuestion,
+ handleUpdateVisualizationSettings,
+ } = useUpdateCardOperations({
+ document,
+ regularCardData,
+ question,
+ editor,
+ embedIndex,
+ cardId: id,
+ });
+
useEffect(() => {
if (isEditingTitle && titleInputRef.current) {
titleInputRef.current.focus();
@@ -422,14 +418,6 @@ export const CardEmbedComponent = memo(
}
}, [isEditingTitle]);
- useMount(() => {
- isMountedRef.current = true;
- });
-
- useUnmount(() => {
- isMountedRef.current = false;
- });
-
const handleTitleSave = () => {
const trimmedTitle = editedTitle.trim();
if (trimmedTitle && trimmedTitle !== card?.name) {
@@ -517,107 +505,6 @@ export const CardEmbedComponent = memo(
editor.chain().focus();
}, [deleteNode, editor, node]);
- // Handle drill-through navigation
- const handleChangeCardAndRun = useCallback(
- ({
- nextCard,
- }: {
- nextCard: Card;
- previousCard?: Card;
- objectId?: number;
- }) => {
- if (!metadata) {
- console.warn("Metadata not available for drill-through navigation");
- return;
- }
-
- try {
- // For drill-through, we need to ensure the card is treated as adhoc
- // Remove the ID so getUrl creates an adhoc question URL instead of navigating to saved question
- const adhocCard = { ...nextCard, id: null };
- const question = new Question(adhocCard, metadata);
- const url = getUrl(question, { includeDisplayIsLocked: true });
- dispatch(navigateToCardFromDocument(url, document));
- } catch (error) {
- console.error("Failed to create question URL:", error);
- // Fallback: navigate to a new question with the dataset_query
- if (nextCard.dataset_query) {
- const params = new URLSearchParams();
- params.set("dataset_query", JSON.stringify(nextCard.dataset_query));
- dispatch(
- navigateToCardFromDocument(
- `/question?${params.toString()}`,
- document,
- ),
- );
- }
- }
- },
- [dispatch, metadata, document],
- );
-
- const handleDragOver = useCallback(
- (e: React.DragEvent) => {
- e.preventDefault();
-
- const draggingNode = editor.view.draggingNode;
- if (
- draggingNode &&
- draggingNode.type.name === "cardEmbed" &&
- cardEmbedRef.current
- ) {
- // Check if this cardEmbed is in a flexContainer that already has 3 children
- const pos = getPos();
- if (pos) {
- const resolvedPos = editor.state.doc.resolve(pos);
- const { parent } = resolvedPos;
-
- if (
- parent.type.name === "flexContainer" &&
- parent.content.childCount >= 3
- ) {
- let containsDraggedNode = false;
-
- for (let i = 0; i < parent.content.childCount; i++) {
- const child = parent.child(i);
- containsDraggedNode =
- containsDraggedNode || child === draggingNode;
- }
-
- if (!containsDraggedNode) {
- // Don't show drop zones if flexContainer is already at max capacity
- setDragState({ isDraggedOver: false, side: null });
- return;
- }
- }
- }
-
- const rect = cardEmbedRef.current.getBoundingClientRect();
- const relativeX = e.clientX - rect.left;
- const nodeWidth = rect.width;
-
- // Determine which side based on cursor position
- let side: "left" | "right" | null = null;
- if (relativeX < nodeWidth * 0.5) {
- side = "left";
- } else if (relativeX >= nodeWidth * 0.5) {
- side = "right";
- }
-
- setDragState({ isDraggedOver: true, side });
-
- window.clearTimeout(draggedOverTimeoutRef.current);
-
- draggedOverTimeoutRef.current = window.setTimeout(() => {
- if (isMountedRef.current) {
- setDragState({ isDraggedOver: false, side: null });
- }
- }, DRAG_LEAVE_TIMEOUT);
- }
- },
- [editor.view.draggingNode, getPos, editor.state.doc],
- );
-
if (isLoading && !card) {
return (
<NodeViewWrapper
@@ -852,9 +739,18 @@ export const CardEmbedComponent = memo(
<Visualization
rawSeries={series}
metadata={metadata}
+ mode={DocumentMode}
onChangeCardAndRun={
isPublicDocument ? undefined : handleChangeCardAndRun
}
+ onUpdateQuestion={
+ isPublicDocument ? undefined : handleUpdateQuestion
+ }
+ onUpdateVisualizationSettings={
+ isPublicDocument
+ ? undefined
+ : handleUpdateVisualizationSettings
+ }
getExtraDataForClick={() => ({})}
isEditing={false}
isDashboard={false}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/use-dnd-helpers.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/use-dnd-helpers.ts
new file mode 100644
index 00000000000..c5441b70961
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/use-dnd-helpers.ts
@@ -0,0 +1,103 @@
+import type { NodeViewProps } from "@tiptap/react";
+import { useCallback, useRef, useState } from "react";
+import { useMount, useUnmount } from "react-use";
+
+const DRAG_LEAVE_TIMEOUT = 300;
+
+export const useDndHelpers = ({
+ editor,
+ node,
+ getPos,
+}: {
+ editor: NodeViewProps["editor"];
+ node: NodeViewProps["node"];
+ getPos: NodeViewProps["getPos"];
+}) => {
+ const [dragState, setDragState] = useState<{
+ isDraggedOver: boolean;
+ side: "left" | "right" | null;
+ }>({ isDraggedOver: false, side: null });
+ const draggedOverTimeoutRef = useRef<number | undefined>();
+ const cardEmbedRef = useRef<HTMLDivElement | null>(null);
+ const isMountedRef = useRef(false);
+
+ const isBeingDragged = editor.view.draggingNode === node;
+
+ const handleDragOver = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+
+ const draggingNode = editor.view.draggingNode;
+ if (
+ draggingNode &&
+ draggingNode.type.name === "cardEmbed" &&
+ cardEmbedRef.current
+ ) {
+ // Check if this cardEmbed is in a flexContainer that already has 3 children
+ const pos = getPos();
+ if (pos) {
+ const resolvedPos = editor.state.doc.resolve(pos);
+ const { parent } = resolvedPos;
+
+ if (
+ parent.type.name === "flexContainer" &&
+ parent.content.childCount >= 3
+ ) {
+ let containsDraggedNode = false;
+
+ for (let i = 0; i < parent.content.childCount; i++) {
+ const child = parent.child(i);
+ containsDraggedNode =
+ containsDraggedNode || child === draggingNode;
+ }
+
+ if (!containsDraggedNode) {
+ // Don't show drop zones if flexContainer is already at max capacity
+ setDragState({ isDraggedOver: false, side: null });
+ return;
+ }
+ }
+ }
+
+ const rect = cardEmbedRef.current?.getBoundingClientRect();
+ const relativeX = e.clientX - rect.left;
+ const nodeWidth = rect.width;
+
+ // Determine which side based on cursor position
+ let side: "left" | "right" | null = null;
+ if (relativeX < nodeWidth * 0.5) {
+ side = "left";
+ } else if (relativeX >= nodeWidth * 0.5) {
+ side = "right";
+ }
+
+ setDragState({ isDraggedOver: true, side });
+
+ window.clearTimeout(draggedOverTimeoutRef.current);
+
+ draggedOverTimeoutRef.current = window.setTimeout(() => {
+ if (isMountedRef.current) {
+ setDragState({ isDraggedOver: false, side: null });
+ }
+ }, DRAG_LEAVE_TIMEOUT);
+ }
+ },
+ [editor.view.draggingNode, getPos, editor.state.doc],
+ );
+
+ useMount(() => {
+ isMountedRef.current = true;
+ });
+
+ useUnmount(() => {
+ isMountedRef.current = false;
+ });
+
+ return {
+ isBeingDragged,
+ dragState,
+ setDragState,
+ handleDragOver,
+ cardEmbedRef,
+ };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/use-update-card-operations.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/use-update-card-operations.ts
new file mode 100644
index 00000000000..04dc9342717
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/use-update-card-operations.ts
@@ -0,0 +1,118 @@
+import type { NodeViewProps } from "@tiptap/core";
+import { useCallback } from "react";
+
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import { getMetadata } from "metabase/selectors/metadata";
+import { navigateToCardFromDocument } from "metabase-enterprise/documents/actions";
+import { updateVizSettings } from "metabase-enterprise/documents/documents.slice";
+import type { UseCardDataResult } from "metabase-enterprise/documents/hooks/use-card-data";
+import { useDraftCardOperations } from "metabase-enterprise/documents/hooks/use-draft-card-operations";
+import Question from "metabase-lib/v1/Question";
+import { getUrl } from "metabase-lib/v1/urls";
+import type { Card, Document, VisualizationSettings } from "metabase-types/api";
+
+export const useUpdateCardOperations = ({
+ document,
+ question,
+ regularCardData,
+ editor,
+ embedIndex,
+ cardId,
+}: {
+ document: Document | null;
+ question: Question | undefined;
+ regularCardData: UseCardDataResult;
+ editor: NodeViewProps["editor"];
+ embedIndex: number;
+ cardId: number;
+}) => {
+ const dispatch = useDispatch();
+ const metadata = useSelector(getMetadata);
+
+ const { card, draftCard, regularDataset } = regularCardData;
+
+ const { ensureDraftCard } = useDraftCardOperations(
+ draftCard,
+ card,
+ cardId,
+ editor,
+ embedIndex,
+ regularDataset,
+ );
+
+ // Handle drill-through navigation
+ const handleChangeCardAndRun = useCallback(
+ ({
+ nextCard,
+ }: {
+ nextCard: Card;
+ previousCard?: Card;
+ objectId?: number;
+ }) => {
+ if (!metadata) {
+ console.warn("Metadata not available for drill-through navigation");
+ return;
+ }
+
+ try {
+ // For drill-through, we need to ensure the card is treated as adhoc
+ // Remove the ID so getUrl creates an adhoc question URL instead of navigating to saved question
+ const adhocCard = { ...nextCard, id: null };
+ const question = new Question(adhocCard, metadata);
+ const url = getUrl(question, { includeDisplayIsLocked: true });
+ dispatch(navigateToCardFromDocument(url, document));
+ } catch (error) {
+ console.error("Failed to create question URL:", error);
+ // Fallback: navigate to a new question with the dataset_query
+ if (nextCard.dataset_query) {
+ const params = new URLSearchParams();
+ params.set("dataset_query", JSON.stringify(nextCard.dataset_query));
+ dispatch(
+ navigateToCardFromDocument(
+ `/question?${params.toString()}`,
+ document,
+ ),
+ );
+ }
+ }
+ },
+ [dispatch, metadata, document],
+ );
+
+ const handleUpdateVisualizationSettings = useCallback(
+ (settings: VisualizationSettings) => {
+ if (embedIndex !== null) {
+ if (!draftCard) {
+ const baseCard = card;
+ const newSettings = {
+ ...baseCard?.visualization_settings,
+ ...settings,
+ };
+ const actualCardId = ensureDraftCard(
+ { visualization_settings: newSettings },
+ true,
+ );
+ dispatch(updateVizSettings({ cardId: actualCardId, settings }));
+ } else {
+ dispatch(updateVizSettings({ cardId, settings }));
+ }
+ }
+ },
+ [card, cardId, dispatch, draftCard, embedIndex, ensureDraftCard],
+ );
+
+ const handleUpdateQuestion = useCallback(() => {
+ if (question) {
+ // this is used by HideColumn action, which changes the question, but in reality it updates visualization_settings
+ const newVizSettings = question.card().visualization_settings;
+
+ handleUpdateVisualizationSettings(newVizSettings);
+ }
+ }, [handleUpdateVisualizationSettings, question]);
+
+ return {
+ handleChangeCardAndRun,
+ handleUpdateQuestion,
+ handleUpdateVisualizationSettings,
+ };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/utils.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/utils.ts
new file mode 100644
index 00000000000..2065af0083b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/utils.ts
@@ -0,0 +1,27 @@
+import type { NodeViewProps } from "@tiptap/react";
+
+export function getEmbedIndex(
+ editor: NodeViewProps["editor"],
+ getPos: NodeViewProps["getPos"],
+) {
+ let embedIndex = -1;
+
+ if (editor && getPos) {
+ const currentPos = getPos() ?? 0;
+ let nodeCount = 0;
+
+ // Count cardEmbed nodes that appear before this position
+ editor.state.doc.descendants((node, pos) => {
+ if (node.type.name === "cardEmbed") {
+ if (pos < currentPos) {
+ nodeCount++;
+ } else if (pos === currentPos) {
+ embedIndex = nodeCount;
+ return false; // Stop traversing
+ }
+ }
+ });
+ }
+
+ return embedIndex;
+}
diff --git a/frontend/src/metabase/visualizations/click-actions/modes/DocumentMode.ts b/frontend/src/metabase/visualizations/click-actions/modes/DocumentMode.ts
new file mode 100644
index 00000000000..0e6bd40a298
--- /dev/null
+++ b/frontend/src/metabase/visualizations/click-actions/modes/DocumentMode.ts
@@ -0,0 +1,32 @@
+import type { QueryClickActionsMode } from "../../types";
+import { ColumnFormattingAction } from "../actions/ColumnFormattingAction";
+import { HideColumnAction } from "../actions/HideColumnAction";
+import { NativeQueryClickFallback } from "../actions/NativeQueryClickFallback";
+
+export const DocumentMode: QueryClickActionsMode = {
+ name: "document-mode",
+ hasDrills: true,
+ clickActions: [HideColumnAction, ColumnFormattingAction],
+ fallback: NativeQueryClickFallback,
+ availableOnlyDrills: [
+ "drill-thru/automatic-insights",
+ "drill-thru/column-extract",
+ "drill-thru/column-filter",
+ "drill-thru/combine-columns",
+ "drill-thru/distribution",
+ "drill-thru/fk-details",
+ "drill-thru/fk-filter",
+ "drill-thru/pivot",
+ "drill-thru/pk",
+ "drill-thru/quick-filter",
+ "drill-thru/sort",
+ "drill-thru/summarize-column-by-time",
+ "drill-thru/summarize-column",
+ "drill-thru/underlying-records",
+ "drill-thru/zoom-in.binning",
+ "drill-thru/zoom-in.geographic",
+ "drill-thru/zoom-in.timeseries",
+
+ // we want to skip "drill-thru/zoom"
+ ],
+};