Skip to content

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

SDK entity navigation drops the click behavior filter when the target is a GUI (MBQL) question (#82409)

Sébastienf1a48e2b5cc8
diff --git a/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx
index dbfbe4be1f6..4133da80b61 100644
--- a/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx
@@ -28,8 +28,22 @@ const DASHBOARD_B_FILTER: Parameter = createMockActionParameter({
sectionId: "number",
});
+// Click-behavior target pointing at the GUI question's own QUANTITY column.
+// Mirrors the shape the click-behavior UI writes for a structured question.
+const GUI_QUESTION_QUANTITY_DIMENSION = [
+ "dimension",
+ ["field", ORDERS.QUANTITY, { "base-type": "type/Integer" }],
+ { "stage-number": 0 },
+];
+const GUI_QUESTION_QUANTITY_TARGET_ID = JSON.stringify(
+ GUI_QUESTION_QUANTITY_DIMENSION,
+);
+
describe("scenarios > embedding-sdk > internal-navigation", () => {
describe("dashboard", () => {
+ // Assigned while the setup commands run, before the dashcard is created.
+ let guiQuestionId: number;
+
beforeEach(() => {
signInAsAdminAndEnableEmbeddingSdk();
@@ -63,7 +77,19 @@ describe("scenarios > embedding-sdk > internal-navigation", () => {
cy.wrap(drillableQuestion.id).as("drillableQuestionId");
});
- // 3. Create Dashboard B with a filter and a card
+ // 3. Create a GUI (MBQL) question used as a click behavior target. It
+ // returns a single column so the applied filter is easy to assert on.
+ H.createQuestion({
+ name: "GUI Question",
+ query: {
+ "source-table": ORDERS_ID,
+ fields: [["field", ORDERS.QUANTITY, { "base-type": "type/Integer" }]],
+ },
+ }).then(({ body: guiQuestion }) => {
+ guiQuestionId = guiQuestion.id;
+ });
+
+ // 4. Create Dashboard B with a filter and a card
// Dashboard B will have a click behavior linking to a question
cy.get<number>("@drillableQuestionId").then((drillableQuestionId) => {
H.createDashboard({
@@ -114,7 +140,7 @@ describe("scenarios > embedding-sdk > internal-navigation", () => {
});
});
- // 4. Create Dashboard A with click behaviors
+ // 5. Create Dashboard A with click behaviors
cy.get<number>("@dashboardBId").then((dashboardBId) => {
cy.get<number>("@nativeQuestionId").then((nativeQuestionId) => {
H.createDashboard({
@@ -130,65 +156,120 @@ describe("scenarios > embedding-sdk > internal-navigation", () => {
limit: 5,
},
}).then(({ body: questionA }) => {
- H.addOrUpdateDashboardCard({
- card_id: questionA.id,
- dashboard_id: dashboardA.id,
- card: {
- row: 0,
- col: 0,
- size_x: 24,
- size_y: 8,
- visualization_settings: {
- column_settings: {
- // ID column links to Dashboard B with parameter
- [`["ref",["field",${ORDERS.ID},null]]`]: {
- click_behavior: {
- type: "link",
- linkType: "dashboard",
- linkTextTemplate: "Go to Dashboard B",
- targetId: dashboardBId,
- parameterMapping: {
- [DASHBOARD_B_FILTER.id]: {
- source: {
- type: "column",
- id: "ID",
- name: "ID",
+ // A second, single-column question whose QUANTITY cells link to
+ // the GUI question. Kept separate so the column is always on
+ // screen, and so the other tests keep using card 0 unchanged.
+ H.createQuestion({
+ name: "Quantities for Dashboard A",
+ query: {
+ "source-table": ORDERS_ID,
+ fields: [
+ ["field", ORDERS.QUANTITY, { "base-type": "type/Integer" }],
+ ],
+ limit: 5,
+ },
+ }).then(({ body: quantitiesQuestion }) => {
+ // Both cards must be set in a single call: addOrUpdateDashboardCard
+ // replaces the dashboard's whole dashcard list, so a second call
+ // would silently drop the first card.
+ H.updateDashboardCards({
+ dashboard_id: dashboardA.id,
+ cards: [
+ {
+ card_id: questionA.id,
+ row: 0,
+ col: 0,
+ size_x: 24,
+ size_y: 8,
+ visualization_settings: {
+ column_settings: {
+ // ID column links to Dashboard B with parameter
+ [`["ref",["field",${ORDERS.ID},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ linkTextTemplate: "Go to Dashboard B",
+ targetId: dashboardBId,
+ parameterMapping: {
+ [DASHBOARD_B_FILTER.id]: {
+ source: {
+ type: "column",
+ id: "ID",
+ name: "ID",
+ },
+ target: {
+ type: "parameter",
+ id: DASHBOARD_B_FILTER.id,
+ },
+ id: DASHBOARD_B_FILTER.id,
+ },
},
- target: {
- type: "parameter",
- id: DASHBOARD_B_FILTER.id,
+ },
+ },
+ // PRODUCT_ID column links to native question with parameter
+ [`["ref",["field",${ORDERS.PRODUCT_ID},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "question",
+ linkTextTemplate: "Go to Native Question",
+ targetId: nativeQuestionId,
+ parameterMapping: {
+ id: {
+ source: {
+ type: "column",
+ id: "PRODUCT_ID",
+ name: "Product ID",
+ },
+ target: {
+ type: "variable",
+ id: "id",
+ },
+ id: "id",
+ },
},
- id: DASHBOARD_B_FILTER.id,
},
},
},
},
- // PRODUCT_ID column links to native question with parameter
- [`["ref",["field",${ORDERS.PRODUCT_ID},null]]`]: {
- click_behavior: {
- type: "link",
- linkType: "question",
- linkTextTemplate: "Go to Native Question",
- targetId: nativeQuestionId,
- parameterMapping: {
- id: {
- source: {
- type: "column",
- id: "PRODUCT_ID",
- name: "Product ID",
- },
- target: {
- type: "variable",
- id: "id",
+ },
+ {
+ card_id: quantitiesQuestion.id,
+ row: 8,
+ col: 0,
+ size_x: 12,
+ size_y: 6,
+ visualization_settings: {
+ column_settings: {
+ // QUANTITY column links to a GUI (MBQL) question, mapping
+ // the clicked quantity onto the target's own column
+ [`["ref",["field",${ORDERS.QUANTITY},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "question",
+ linkTextTemplate: "Go to GUI Question",
+ targetId: guiQuestionId,
+ parameterMapping: {
+ [GUI_QUESTION_QUANTITY_TARGET_ID]: {
+ source: {
+ type: "column",
+ id: "QUANTITY",
+ name: "Quantity",
+ },
+ target: {
+ type: "dimension",
+ id: GUI_QUESTION_QUANTITY_TARGET_ID,
+ dimension: GUI_QUESTION_QUANTITY_DIMENSION,
+ },
+ id: GUI_QUESTION_QUANTITY_TARGET_ID,
+ },
},
- id: "id",
},
},
},
},
},
- },
- },
+ ],
+ });
});
});
});
@@ -202,6 +283,7 @@ describe("scenarios > embedding-sdk > internal-navigation", () => {
cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query").as(
"dashcardQuery",
);
+ cy.intercept("POST", "/api/dataset").as("datasetQuery");
});
it("should pass parameters to the linked dashboard", () => {
@@ -273,6 +355,71 @@ describe("scenarios > embedding-sdk > internal-navigation", () => {
});
});
+ it("should pass the click behavior filter to the linked GUI (MBQL) question", () => {
+ cy.get<number>("@dashboardAId").then((dashboardAId) => {
+ mountSdkContent(
+ <InteractiveDashboard
+ dashboardId={dashboardAId}
+ enableEntityNavigation
+ />,
+ );
+ });
+
+ cy.wait("@getDashboard");
+ cy.wait("@dashcardQuery");
+
+ getSdkRoot().within(() => {
+ // Verify we're on Dashboard A
+ cy.findByText("Dashboard A").should("be.visible");
+
+ // Click on the custom link text that navigates to the GUI question
+ H.getDashboardCard(1)
+ .findAllByText("Go to GUI Question")
+ .first()
+ .click();
+ });
+
+ // A GUI target cannot consume the mapped value as a parameter, so it opens
+ // as an ad-hoc question carrying the value as a filter instead.
+ cy.wait("@datasetQuery").then(({ request }) => {
+ // Request body is a pMBQL query; a filter clause is
+ // [operator, opts, fieldRef, value].
+ const [{ filters }] = request.body.stages;
+ const [filter] = filters;
+
+ expect(filter[0]).to.equal("=");
+ expect(filter[2]).to.include(ORDERS.QUANTITY);
+
+ cy.wrap(filter[3]).as("filteredQuantity");
+ });
+
+ getSdkRoot().within(() => {
+ cy.findByTestId("visualization-root").should("be.visible");
+
+ // The toolbar counts the mapped value as a filter on the question.
+ // Before the fix the saved question opened unfiltered, so this read
+ // "Filter" instead.
+ cy.findByTestId("filter-dropdown-button")
+ .should("be.visible")
+ .and("contain", "1 filter");
+
+ // Every returned row matches the quantity we clicked on
+ cy.get<number>("@filteredQuantity").then((filteredQuantity) => {
+ H.tableInteractiveBody()
+ .findAllByTestId("cell-data")
+ .should("have.length.at.least", 1)
+ .each((cell) => {
+ expect(cell.text()).to.equal(String(filteredQuantity));
+ });
+ });
+
+ // Verify breadcrumb shows Dashboard A, and that going back works
+ cy.findByText("Back to Dashboard A").should("be.visible").click();
+
+ cy.findByText("Dashboard A").should("be.visible");
+ });
+ });
+
it("should navigate to the question when clicking on the dashcard title", () => {
cy.get<number>("@dashboardAId").then((dashboardAId) => {
mountSdkContent(
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
index 5069360f6de..dba2aa35d29 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
@@ -28,6 +28,7 @@ import type {
} from "../../public/SdkQuestion/SdkQuestion";
import { InteractiveDashboardContent } from "../../public/dashboard/InteractiveDashboard/InteractiveDashboard";
import type { SdkDashboardInnerProps } from "../../public/dashboard/SdkDashboard";
+import { SdkAdHocQuestion } from "../SdkAdHocQuestion";
import { SdkInternalNavigationBackButton } from "./SdkInternalNavigationBackButton";
import {
@@ -193,6 +194,11 @@ const SdkInternalNavigationProviderInner = ({
</Stack>
) : null;
+ // We try to infer question props from the starting dashboard when they have a 1:1 mapping
+ const questionPropsInferredFromDashboard: Partial<SdkQuestionProps> = {
+ withDownloads: dashboardProps?.withDownloads,
+ };
+
const content = match({ activeEntry: entryToRender })
.with({ activeEntry: { type: "dashboard" } }, ({ activeEntry }) => (
<InteractiveDashboardContent
@@ -202,25 +208,29 @@ const SdkInternalNavigationProviderInner = ({
enableEntityNavigation
/>
))
- .with({ activeEntry: { type: "question" } }, ({ activeEntry }) => {
- // We try to infer question props from the starting dashboard when they have a 1:1 mapping
- const questionPropsInferredFromDashboard: Partial<SdkQuestionProps> = {
- withDownloads: dashboardProps?.withDownloads,
- };
-
- return (
- <SdkQuestion
- questionId={activeEntry.id}
- onNavigateBack={pop}
- initialSqlParameters={activeEntry.parameters}
- isSaveEnabled
- {...questionPropsInferredFromDashboard}
- {...drillThroughQuestionProps}
- >
- {RenderDrillThroughQuestion && <RenderDrillThroughQuestion />}
- </SdkQuestion>
- );
- })
+ .with({ activeEntry: { type: "ad-hoc-question" } }, ({ activeEntry }) => (
+ <SdkAdHocQuestion
+ questionPath={activeEntry.adHocQuestionPath}
+ onNavigateBack={pop}
+ isSaveEnabled
+ {...questionPropsInferredFromDashboard}
+ {...drillThroughQuestionProps}
+ >
+ {RenderDrillThroughQuestion && <RenderDrillThroughQuestion />}
+ </SdkAdHocQuestion>
+ ))
+ .with({ activeEntry: { type: "question" } }, ({ activeEntry }) => (
+ <SdkQuestion
+ questionId={activeEntry.id}
+ onNavigateBack={pop}
+ initialSqlParameters={activeEntry.parameters}
+ isSaveEnabled
+ {...questionPropsInferredFromDashboard}
+ {...drillThroughQuestionProps}
+ >
+ {RenderDrillThroughQuestion && <RenderDrillThroughQuestion />}
+ </SdkQuestion>
+ ))
.otherwise(() => children);
return (
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
index a8390440275..0577407d50a 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
@@ -33,6 +33,14 @@ export type SdkInternalNavigationEntry =
parameters?: ParameterValues;
onPop?: () => void;
})
+ | (BaseEntry & {
+ /** A pre-filtered ad-hoc question, rendered from its serialized path. */
+ type: "ad-hoc-question";
+ name: string;
+ virtual?: true;
+ adHocQuestionPath: string;
+ onPop?: () => void;
+ })
| (BaseEntry & {
type: "metabase-browser";
virtual: false;
diff --git a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts
index 2763ed09f3b..6baa16ff7f7 100644
--- a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts
@@ -2,6 +2,7 @@ import { DashboardClickAction } from "metabase/dashboard/click-behavior/Dashboar
import {
getClickBehavior,
getClickBehaviorData,
+ getDashboardDrillQuestionUrl,
getParameterIdValuePairs,
getParameterValuesBySlug,
} from "metabase/dashboard/click-behavior/dashboard-click-drill";
@@ -13,9 +14,11 @@ import { NativeQueryClickFallback } from "metabase/querying/click-actions/action
import type { QueryClickActionsMode } from "metabase/querying/click-actions/types";
import { HideColumnAction } from "metabase/visualizations/click-actions/actions/HideColumnAction";
import type { ClickObject, LegacyDrill } from "metabase/visualizations/types";
+import * as Lib from "metabase-lib";
+import Question from "metabase-lib/v1/Question";
import type { CardId, DashboardId, DashboardTabId } from "metabase-types/api";
-export type ClickBehaviorTarget = {
+type ParameterizedTarget = {
name: string;
parameters: ParameterValues;
/**
@@ -24,13 +27,24 @@ export type ClickBehaviorTarget = {
* setParameterValue actions (mirrors core app DashboardClickAction).
*/
parameterIdValuePairs: ParameterIdValuePair[];
-} & (
- | { type: "dashboard"; id: DashboardId; tabId?: DashboardTabId }
- | { type: "question"; id: CardId }
-);
+};
-const getClickBehaviorTarget = (
+export type ClickBehaviorTarget =
+ | (ParameterizedTarget & {
+ type: "dashboard";
+ id: DashboardId;
+ tabId?: DashboardTabId;
+ })
+ | (ParameterizedTarget & { type: "question"; id: CardId })
+ /**
+ * A non-native target question. The mapped values are already encoded as
+ * filters in the path, so there are no parameters left to carry.
+ */
+ | { type: "ad-hoc-question"; name: string; adHocQuestionPath: string };
+
+export const getClickBehaviorTarget = (
clicked: ClickObject,
+ question: Question,
): ClickBehaviorTarget | null => {
const clickBehavior = getClickBehavior(clicked);
if (!clickBehavior) {
@@ -83,19 +97,34 @@ const getClickBehaviorTarget = (
};
}
- const question = extraData?.questions?.[targetId];
+ const targetCard = extraData?.questions?.[targetId];
- if (!question) {
+ if (!targetCard) {
console.warn(
`[SDK Navigation] Could not find question with id ${targetId}`,
);
return null;
}
+ const targetQuestion = new Question(targetCard, question.metadata());
+ const isTargetQuestionNative = Lib.queryDisplayInfo(
+ targetQuestion.query(),
+ ).isNative;
+
+ // Only a native question's template tags can consume the mapped values, so a
+ // non-native target is opened as an ad-hoc, pre-filtered question instead.
+ if (!isTargetQuestionNative) {
+ return {
+ type: "ad-hoc-question",
+ name: targetCard.name,
+ adHocQuestionPath: getDashboardDrillQuestionUrl(question, clicked),
+ };
+ }
+
return {
type: "question",
- id: question.id,
- name: question.name,
+ id: targetCard.id,
+ name: targetCard.name,
parameters,
parameterIdValuePairs,
};
@@ -111,7 +140,7 @@ export const createEmbeddingSdkMode = (
const { pushNavigation } = options;
const SDKDashboardClickAction: LegacyDrill = ({ question, clicked = {} }) => {
- const target = getClickBehaviorTarget(clicked);
+ const target = getClickBehaviorTarget(clicked, question);
if (target && pushNavigation) {
return [
diff --git a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts
new file mode 100644
index 00000000000..7b6e887f9c5
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts
@@ -0,0 +1,158 @@
+import { parse } from "url";
+
+import { createMockMetadata } from "__support__/metadata";
+import { deserializeCardFromUrl } from "metabase/common/utils/card";
+import type { ClickObject } from "metabase/visualizations/types";
+import * as Lib from "metabase-lib";
+import Question from "metabase-lib/v1/Question";
+import type {
+ Card,
+ CardId,
+ ClickBehaviorParameterMapping,
+} from "metabase-types/api";
+import { createMockCard, createMockColumn } from "metabase-types/api/mocks";
+import {
+ PRODUCTS,
+ PRODUCTS_ID,
+ SAMPLE_DB_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
+
+import { getClickBehaviorTarget } from "./EmbeddingSdkMode";
+
+const metadata = createMockMetadata({
+ databases: [createSampleDatabase()],
+});
+const metadataProvider = Lib.metadataProvider(SAMPLE_DB_ID, metadata);
+const sourceQuestion = new Question(createMockCard(), metadata);
+
+const categoryColumn = createMockColumn({ name: "CATEGORY" });
+
+// A dashcard click behavior that links to `targetCard`, mapping the clicked
+// "Gizmo" category value through `parameterMapping`.
+function buildQuestionLinkClicked({
+ targetId,
+ targetCard,
+ parameterMapping,
+}: {
+ targetId: CardId;
+ targetCard: Card;
+ parameterMapping: ClickBehaviorParameterMapping;
+}): ClickObject {
+ return {
+ settings: {
+ click_behavior: {
+ type: "link",
+ linkType: "question",
+ targetId,
+ parameterMapping,
+ },
+ },
+ dimensions: [{ column: categoryColumn, value: "Gizmo" }],
+ extraData: { questions: { [targetId]: targetCard } },
+ };
+}
+
+function parseAdHocQuestionPath(path: string): Card | null {
+ const { hash } = parse(path, true);
+ return hash ? deserializeCardFromUrl(hash) : null;
+}
+
+describe("getClickBehaviorTarget", () => {
+ it("builds an ad-hoc question target with the filter for a GUI (MBQL) target question", () => {
+ const targetCard = createMockCard({
+ id: 5,
+ name: "Products (drill target)",
+ dataset_query: Lib.toJsQuery(
+ Lib.fromJsQuery(metadataProvider, {
+ type: "query",
+ query: { "source-table": PRODUCTS_ID },
+ database: SAMPLE_DB_ID,
+ }),
+ ),
+ });
+
+ // parameterMapping is keyed by the target's own stringified id.
+ const dimensionTargetId = JSON.stringify([
+ "dimension",
+ ["field", PRODUCTS.CATEGORY, null],
+ ]);
+
+ const clicked = buildQuestionLinkClicked({
+ targetId: 5,
+ targetCard,
+ parameterMapping: {
+ [dimensionTargetId]: {
+ id: dimensionTargetId,
+ source: { type: "column", id: "CATEGORY", name: "Category" },
+ target: {
+ id: dimensionTargetId,
+ type: "dimension",
+ dimension: ["dimension", ["field", PRODUCTS.CATEGORY, null]],
+ },
+ },
+ },
+ });
+
+ const target = getClickBehaviorTarget(clicked, sourceQuestion);
+
+ expect(target?.type).toBe("ad-hoc-question");
+ if (target?.type !== "ad-hoc-question") {
+ throw new Error("expected an ad-hoc question target");
+ }
+
+ const card = parseAdHocQuestionPath(target.adHocQuestionPath);
+ expect(card).not.toBeNull();
+
+ const query = Lib.fromJsQuery(metadataProvider, card!.dataset_query);
+ const [filter] = Lib.filters(query, -1);
+
+ expect(Lib.displayInfo(query, -1, filter).longDisplayName).toBe(
+ "Category is Gizmo",
+ );
+ });
+
+ it("keeps a native target question as a saved-question target", () => {
+ const targetCard = createMockCard({
+ id: 6,
+ name: "Native drill target",
+ dataset_query: {
+ type: "native",
+ database: SAMPLE_DB_ID,
+ native: {
+ query: "select * from products where category = {{category}}",
+ "template-tags": {
+ category: {
+ id: "tag-1",
+ name: "category",
+ "display-name": "Category",
+ type: "text",
+ },
+ },
+ },
+ },
+ });
+
+ const clicked = buildQuestionLinkClicked({
+ targetId: 6,
+ targetCard,
+ parameterMapping: {
+ "variable-target": {
+ id: "variable-target",
+ source: { type: "column", id: "CATEGORY", name: "Category" },
+ target: { id: "category", type: "variable" },
+ },
+ },
+ });
+
+ const target = getClickBehaviorTarget(clicked, sourceQuestion);
+
+ expect(target?.type).toBe("question");
+ if (target?.type !== "question") {
+ throw new Error("expected a question target");
+ }
+
+ expect(target.id).toBe(6);
+ expect(target.parameters).toEqual({ category: "Gizmo" });
+ });
+});