The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
[feature branch] support internal click behavior with `enableInternalNavigation` prop in SDK and EAJS (#69117)
Nicolò Pretto418117994212
diff --git a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsxindex 44ad89a265b..c946da44855 100644--- a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx@@ -1,6 +1,7 @@const { H } = cy;import { InteractiveQuestion } from "@metabase/embedding-sdk-react";+import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";import { modal, popover } from "e2e/support/helpers";import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers";@@ -164,4 +165,33 @@ describe("scenarios > embedding-sdk > interactive-question", () => {modal().findByRole("heading", { name: "New alert" }).should("be.visible");});});++ describe("BackButton component", () => {+ it("should show BackButton after drilling even with title=false (metabase#68556)", () => {+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} title={false} />,+ );++ getSdkRoot().within(() => {+ // Title should not be visible+ cy.findByText("Orders").should("not.exist");++ // BackButton should not be visible initially+ cy.findByText(/Back to/).should("not.exist");++ // Perform a drill on the first row's Product ID+ H.tableInteractiveBody().findAllByText("14").first().click();+ H.popover().findByText("View this Product's Orders").click();++ // BackButton should be visible after drill+ cy.findByText("Back to Orders").should("be.visible");++ // Click back+ cy.findByText("Back to Orders").click();++ // BackButton should be hidden again+ cy.findByText(/Back to/).should("not.exist");+ });+ });+ });});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.tsxnew file mode 100644index 00000000000..435d8968983--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx@@ -0,0 +1,721 @@+import {+ InteractiveDashboard,+ InteractiveQuestion,+ StaticDashboard,+} from "@metabase/embedding-sdk-react";++import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers";+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";+import type { Parameter } from "metabase-types/api";+import { createMockActionParameter } from "metabase-types/api/mocks";++const { H } = cy;++const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++// Dashboard B filter parameter+const DASHBOARD_B_FILTER: Parameter = createMockActionParameter({+ id: "dashboard-b-filter",+ name: "ID Filter",+ slug: "id-filter",+ type: "number/=",+ sectionId: "number",+});++describe("scenarios > embedding-sdk > internal-navigation", () => {+ describe("dashboard", () => {+ beforeEach(() => {+ signInAsAdminAndEnableEmbeddingSdk();++ // 1. Create a native question with a parameter (for testing parameter passing to questions)+ H.createNativeQuestion({+ name: "Native Question with Param",+ native: {+ query: "SELECT * FROM ORDERS WHERE ID = {{id}} LIMIT 10",+ "template-tags": {+ id: {+ id: "native-id-tag",+ name: "id",+ "display-name": "ID",+ type: "number",+ required: false,+ },+ },+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("nativeQuestionId");+ });++ // 2. Create a regular question that supports drilling (for testing drill navigation)+ H.createQuestion({+ name: "Drillable Question",+ query: {+ "source-table": ORDERS_ID,+ limit: 10,+ },+ }).then(({ body: drillableQuestion }) => {+ cy.wrap(drillableQuestion.id).as("drillableQuestionId");+ });++ // 3. 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({+ name: "Dashboard B",+ parameters: [DASHBOARD_B_FILTER],+ }).then(({ body: dashboardB }) => {+ cy.wrap(dashboardB.id).as("dashboardBId");++ // Add a question card to Dashboard B with click behavior to drillable question+ H.createQuestion({+ name: "Orders for Dashboard B",+ query: {+ "source-table": ORDERS_ID,+ limit: 5,+ },+ }).then(({ body: questionB }) => {+ H.addOrUpdateDashboardCard({+ card_id: questionB.id,+ dashboard_id: dashboardB.id,+ card: {+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 8,+ parameter_mappings: [+ {+ parameter_id: DASHBOARD_B_FILTER.id,+ card_id: questionB.id,+ target: ["dimension", ["field", ORDERS.ID, null]],+ },+ ],+ visualization_settings: {+ column_settings: {+ [`["ref",["field",${ORDERS.ID},null]]`]: {+ click_behavior: {+ type: "link",+ linkType: "question",+ linkTextTemplate: "Go to Question",+ targetId: drillableQuestionId,+ parameterMapping: {},+ },+ },+ },+ },+ },+ });+ });+ });+ });++ // 4. Create Dashboard A with click behaviors+ cy.get<number>("@dashboardBId").then((dashboardBId) => {+ cy.get<number>("@nativeQuestionId").then((nativeQuestionId) => {+ H.createDashboard({+ name: "Dashboard A",+ }).then(({ body: dashboardA }) => {+ cy.wrap(dashboardA.id).as("dashboardAId");++ // Create a question for Dashboard A+ H.createQuestion({+ name: "Orders for Dashboard A",+ query: {+ "source-table": ORDERS_ID,+ 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",+ },+ target: {+ type: "parameter",+ id: DASHBOARD_B_FILTER.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",+ },+ id: "id",+ },+ },+ },+ },+ },+ },+ },+ });+ });+ });+ });+ });++ cy.signOut();+ mockAuthProviderAndJwtSignIn();++ cy.intercept("GET", "/api/dashboard/*").as("getDashboard");+ cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query").as(+ "dashcardQuery",+ );+ });++ it("should pass parameters to the linked dashboard", () => {+ 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 Dashboard B+ H.getDashboardCard().findAllByText("Go to Dashboard B").first().click();++ // Wait for Dashboard B to load+ cy.wait("@getDashboard");++ // Verify we navigated to Dashboard B+ cy.findByText("Dashboard B").should("be.visible");++ // Verify the filter widget shows the passed parameter value+ H.filterWidget().should("be.visible");++ // Verify breadcrumb shows Dashboard A (so we can go back)+ cy.findByText("Back to Dashboard A").should("be.visible").click();++ cy.findByText("Dashboard A").should("be.visible");+ });+ });++ it("should pass parameters to the linked native 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 native question+ H.getDashboardCard()+ .findAllByText("Go to Native Question")+ .first()+ .click();++ // Verify the question loaded (visualization root should be visible)+ cy.findByTestId("visualization-root").should("be.visible");+ // We don't currently show the params on the question, so we can only assert the results+ // TODO check that we only render one row with the correct product id++ // Verify breadcrumb shows Dashboard A+ cy.findByText("Back to Dashboard A").should("be.visible");+ });+ });++ it("should navigate to the question when clicking on the dashcard title", () => {+ 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 dashcard title to navigate to the question+ H.getDashboardCard()+ .findByText("Orders for Dashboard A")+ .should("be.visible")+ .click();++ // Verify the question loaded (visualization root should be visible)+ cy.findByTestId("visualization-root").should("be.visible");++ // Verify breadcrumb shows Dashboard A+ cy.findByText("Back to Dashboard A").should("be.visible");+ // Go back to Dashboard A+ cy.findByText("Back to Dashboard A").click();++ // Verify we're back on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Verify no back button exists (we're at the root)+ cy.findByText(/Back to/).should("not.exist");+ });+ });++ it("should allow drilling directly from the initial dashboard and show the drilled 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 a User ID cell (column without custom click behavior) to trigger drill menu+ // The ID and Product ID columns have custom click behaviors, so we use User ID+ H.getDashboardCard()+ .findByTestId("visualization-root")+ .findAllByRole("gridcell", { name: "1" })+ .first()+ .click();++ // Click on drill option to view orders for this user+ H.popover().findByText("View this User's Orders").click();++ // Verify the drilled question is now shown (not the dashboard)+ cy.findByTestId("visualization-root").should("be.visible");++ // The dashboard title should no longer be visible since we're viewing the drill result+ cy.findByText("Dashboard A").should("not.exist");++ // Verify back button shows Dashboard A+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Click back to return to the dashboard+ cy.findByText("Back to Dashboard A").click();++ // Verify we're back on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Verify no back button exists (we're at the root)+ cy.findByText(/Back to/).should("not.exist");+ });+ });++ it("should support go to question -> drill -> drill -> back", () => {+ cy.get<number>("@dashboardAId").then((dashboardAId) => {+ mountSdkContent(+ <InteractiveDashboard+ dashboardId={dashboardAId}+ enableEntityNavigation+ />,+ );+ });++ cy.wait("@getDashboard");+ cy.wait("@dashcardQuery");++ getSdkRoot().within(() => {+ // Step 1: Verify we start on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Step 2: Navigate to question by clicking on dashcard title+ H.getDashboardCard()+ .findByText("Orders for Dashboard A")+ .should("be.visible")+ .click();++ // Verify we're now viewing the question+ cy.findByTestId("visualization-root").should("be.visible");+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Step 3: First drill - click on Product ID cell+ H.tableInteractiveBody().findByRole("gridcell", { name: "14" }).click();+ H.popover().findByText("View this Product's Orders").click();++ // Verify drill happened - back button should show the question name+ cy.findByText("Back to Orders for Dashboard A").should("be.visible");++ // Step 4: Second drill+ H.tableInteractiveBody().findAllByText("2.07").first().click();+ H.popover().findByText("<").click();++ // Back button should still show the original question+ cy.findByText("Back to Orders for Dashboard A").should("be.visible");++ // Step 5: One back click should undo BOTH drills and return to the question+ cy.findByText("Back to Orders for Dashboard A").click();++ // Verify we're back on the original question (not drill result)+ cy.findByTestId("visualization-root").should("be.visible");+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Step 6: Another back click should return to the dashboard+ cy.findByText("Back to Dashboard A").click();++ // Verify we're back on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Verify no back button exists (we're at the root)+ cy.findByText(/Back to/).should("not.exist");+ });+ });++ it("should support dashboard -> drill -> drill -> back directly to dashboard", () => {+ cy.get<number>("@dashboardAId").then((dashboardAId) => {+ mountSdkContent(+ <InteractiveDashboard+ dashboardId={dashboardAId}+ enableEntityNavigation+ />,+ );+ });++ cy.wait("@getDashboard");+ cy.wait("@dashcardQuery");++ getSdkRoot().within(() => {+ // Step 1: Verify we start on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Step 2: First drill directly from dashboard (click on User ID cell - no custom click behavior)+ H.getDashboardCard()+ .findByTestId("visualization-root")+ .findAllByRole("gridcell", { name: "1" })+ .first()+ .click();++ H.popover().findByText("View this User's Orders").click();++ // Verify we're now on drilled question+ cy.findByTestId("visualization-root").should("be.visible");+ cy.findByText("Dashboard A").should("not.exist");+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Step 3: Second drill on the drill result+ H.tableInteractiveBody().findAllByText("2.07").first().click();+ H.popover().findByText("<").click();++ // Back button should still show Dashboard A (drills don't create navigation entries)+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Step 4: One back click should go directly back to Dashboard A+ cy.findByText("Back to Dashboard A").click();++ // Verify we're back on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Verify no back button exists (we're at the root)+ cy.findByText(/Back to/).should("not.exist");+ });+ });++ it("should forward `withDownloads` prop from the dashboard to the question", () => {+ cy.get<number>("@dashboardAId").then((dashboardAId) => {+ mountSdkContent(+ <InteractiveDashboard+ dashboardId={dashboardAId}+ enableEntityNavigation+ withDownloads+ />,+ );+ });++ cy.wait("@dashcardQuery");++ getSdkRoot().within(() => {+ H.getDashboardCard()+ .findAllByText("Go to Native Question")+ .first()+ .click();++ cy.findByTestId("visualization-root").should("be.visible");++ cy.findByTestId("question-download-widget-button").should("be.visible");+ });+ });++ it("should not be able to navigate when using StaticDashboard even if click behaviors are configured", () => {+ cy.get<number>("@dashboardAId").then((dashboardAId) => {+ mountSdkContent(+ <StaticDashboard+ dashboardId={dashboardAId}+ // this prop isn't actually accepted+ enableEntityNavigation+ />,+ );+ });++ cy.wait("@dashcardQuery");++ getSdkRoot().within(() => {+ // Verify we're on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Click behavior link text should not be rendered in static mode+ H.getDashboardCard()+ .findByText("Go to Dashboard B")+ .should("not.exist");+ });+ });++ it("should support nested navigations dashboard -> dashboard -> question -> multiple drills -> back through all", () => {+ cy.get<number>("@dashboardAId").then((dashboardAId) => {+ mountSdkContent(+ <InteractiveDashboard+ dashboardId={dashboardAId}+ enableEntityNavigation+ />,+ );+ });++ cy.wait("@getDashboard");+ cy.wait("@dashcardQuery");++ getSdkRoot().within(() => {+ // Step 1: Verify we start on Dashboard A+ cy.findByText("Dashboard A").should("be.visible");++ // Step 2: Navigate from Dashboard A to Dashboard B via click behavior+ H.getDashboardCard().findAllByText("Go to Dashboard B").first().click();++ // Verify we're now on Dashboard B+ cy.findByText("Dashboard B").should("be.visible");++ // Verify back button shows Dashboard A+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Step 3: Navigate from Dashboard B to question via click behavior+ H.getDashboardCard().findAllByText("Go to Question").first().click();++ // Verify we're now viewing the question+ cy.findByTestId("visualization-root").should("be.visible");++ // Verify back button shows Dashboard B+ cy.findByText("Back to Dashboard B").should("be.visible");++ // We'll later verify this will be hidden by the drill+ H.tableInteractiveBody().findByText("123").should("be.visible");++ // Step 4: Perform first drill on the question (click on Product ID to drill)++ H.tableInteractiveBody().findByRole("gridcell", { name: "14" }).click();+ H.popover().findByText("View this Product's Orders").click();++ H.tableInteractiveBody().findByText("123").should("not.exist");++ // Verify we're now on an adhoc question (drill result)+ cy.findByTestId("visualization-root").should("be.visible");++ // After drilling, back button should show "Drillable Question"+ cy.findByText("Back to Drillable Question").should("be.visible");++ // We'll later verify this will be hidden by the drill+ H.tableInteractiveBody().findByText("2.26").should("be.visible");++ // Step 5: Perform second drill+ H.tableInteractiveBody().findAllByText("2.07").first().click();++ H.popover().findByText("<").click();++ // Verify drill really happened+ H.tableInteractiveBody().findByText("2.26").should("not.exist");++ // Back button should still show the original question+ cy.findByText("Back to Drillable Question").should("be.visible");++ H.tableInteractiveBody()+ .findAllByText("25.1")+ .first()+ .should("be.visible");++ // Step 6: Perform third drill+ H.tableInteractiveBody().findAllByText("37.65").first().click();++ H.popover().findByText("=").click();++ H.tableInteractiveBody().findByText("25.1").should("not.exist");++ // Back button should still show the original question+ cy.findByText("Back to Drillable Question").should("be.visible");++ // Step 7: One back click should revert ALL drills and return to the original question+ cy.findByText("Back to Drillable Question").click();++ // Verify we're back on the question (not an intermediate drill state)+ cy.findByTestId("visualization-root").should("be.visible");+ cy.findByText("Back to Dashboard B").should("be.visible");++ H.tableInteractiveBody().findByText("110.93").should("be.visible");++ // Step 8: Go back to Dashboard B+ cy.findByText("Back to Dashboard B").click();++ // Verify we're back on Dashboard B+ cy.findByText("Dashboard B").should("be.visible");+ cy.findByText("Back to Dashboard A").should("be.visible");++ // Step 9: Go back to Dashboard A+ cy.findByText("Back to Dashboard A").click();++ // Verify we're back on Dashboard A (root)+ cy.findByText("Dashboard A").should("be.visible");++ // Verify no back button exists (we're at the root)+ cy.findByText(/Back to/).should("not.exist");+ });+ });+ });++ describe("question", () => {+ beforeEach(() => {+ signInAsAdminAndEnableEmbeddingSdk();++ // Create a question that supports drilling+ H.createQuestion({+ name: "Orders Question",+ query: {+ "source-table": ORDERS_ID,+ limit: 10,+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });++ cy.signOut();+ mockAuthProviderAndJwtSignIn();++ cy.intercept("GET", "/api/card/*").as("getCard");+ cy.intercept("POST", "/api/card/*/query").as("cardQuery");+ });++ it("should allow drilling and returning to the original question", () => {+ cy.get<number>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />);+ });++ cy.wait("@getCard");+ cy.wait("@cardQuery");++ getSdkRoot().within(() => {+ // Verify original question+ cy.findByText("Orders Question").should("be.visible");++ // No back button initially+ cy.findByText(/Back to/).should("not.exist");++ // Drill - click on PRODUCT_ID cell+ H.tableInteractiveBody().findByRole("gridcell", { name: "14" }).click();+ H.popover().findByText("View this Product's Orders").click();++ // Verify back button appears after drill+ cy.findByText("Back to Orders Question").should("be.visible");++ // Click back+ cy.findByText("Back to Orders Question").click();++ // Should be back at original question+ cy.findByText("Orders Question").should("be.visible");+ cy.findByText(/Back to/).should("not.exist");+ });+ });++ it("should return to original question after nested drills with one back click", () => {+ cy.get<number>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />);+ });++ cy.wait("@getCard");+ cy.wait("@cardQuery");++ getSdkRoot().within(() => {+ // Verify original question+ cy.findByText("Orders Question").should("be.visible");++ // No back button initially+ cy.findByText(/Back to/).should("not.exist");++ // First drill - click on PRODUCT_ID cell+ H.tableInteractiveBody().findAllByText("14").first().click();+ H.popover().findByText("View this Product's Orders").click();++ // Verify back button appears after first drill+ cy.findByText("Back to Orders Question").should("be.visible");++ // Second drill+ H.tableInteractiveBody().findAllByText("2.07").first().click();+ H.popover().findByText("<").click();++ cy.findByText("Back to Orders Question").should("be.visible");++ // Third drill+ H.tableInteractiveBody().findAllByText("1.09").first().click();+ H.popover().findByText(">").click();++ cy.findByText("Back to Orders Question").should("be.visible");++ // One button click should return to the original question+ cy.findByText("Back to Orders Question").click();++ // Verify we're back at the original question+ cy.findByText("Orders Question").should("be.visible");+ cy.findByText(/Back to/).should("not.exist");+ });+ });+ });+});diff --git a/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsxindex a7c412b0fbd..df4acfb8ba0 100644--- a/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx@@ -511,11 +511,15 @@ describe("scenarios > embedding-sdk > styles", () => {});});- getSdkRoot().findByText("Tooltip test").click();- getSdkRoot().findByLabelText("Back to Test Dashboard").realHover();+ // Set a value on the date filter to make the Clear button appear+ getSdkRoot().findByText("Date filter").click();+ H.popover().findByText("Today").click();++ // Hover over the Clear button which has a Mantine Tooltip+ getSdkRoot().findByRole("button", { name: "Clear" }).realHover();H.tooltip()- .findByText("Back to Test Dashboard")+ .findByText("Clear").should("have.css", "font-family", "Impact");});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.tsnew file mode 100644index 00000000000..dd8c1e57c06--- /dev/null+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.ts@@ -0,0 +1,399 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { getSignedJwtForResource, updateSetting } from "e2e/support/helpers";+import { JWT_SHARED_SECRET } from "e2e/support/helpers/embedding-sdk-helpers/constants";+import type { Parameter } from "metabase-types/api";+import { createMockActionParameter } from "metabase-types/api/mocks";++const { H } = cy;+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++const TARGET_DASHBOARD_FILTER: Parameter = createMockActionParameter({+ id: "target-dashboard-filter",+ name: "ID Filter",+ slug: "id-filter",+ type: "number/=",+ sectionId: "number",+});++describe("scenarios > embedding > sdk iframe embedding > internal-navigation", () => {+ describe("click behavior navigation", () => {+ beforeEach(() => {+ H.prepareSdkIframeEmbedTest({ withToken: "bleeding-edge" });++ // Setup:+ // "Starting Dashboard" with links to:+ // - "Target Dashboard" with a filter parameter+ // - "Native Question" with a parameter++ // 1. Create a native question with a parameter (for question link target)+ H.createNativeQuestion({+ name: "Native Question with Param",+ native: {+ query: "SELECT * FROM ORDERS WHERE ID = {{id}} LIMIT 10",+ "template-tags": {+ id: {+ id: "native-id-tag",+ name: "id",+ "display-name": "ID",+ type: "number",+ required: false,+ },+ },+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("nativeQuestionId");+ });++ // 2. Create target dashboard with a filter parameter+ H.createDashboard({+ name: "Target Dashboard",+ parameters: [TARGET_DASHBOARD_FILTER],+ }).then(({ body: targetDashboard }) => {+ cy.wrap(targetDashboard.id).as("targetDashboardId");++ H.createQuestion({+ name: "Orders for Target Dashboard",+ query: { "source-table": ORDERS_ID, limit: 5 },+ }).then(({ body: targetQuestion }) => {+ H.addOrUpdateDashboardCard({+ card_id: targetQuestion.id,+ dashboard_id: targetDashboard.id,+ card: {+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 8,+ parameter_mappings: [+ {+ parameter_id: TARGET_DASHBOARD_FILTER.id,+ card_id: targetQuestion.id,+ target: ["dimension", ["field", ORDERS.ID, null]],+ },+ ],+ },+ });+ });+ });++ // 3. Create starting dashboard with click behaviors linking to target dashboard and native question+ cy.then(function () {+ H.createDashboard({+ name: "Starting Dashboard",+ enable_embedding: true,+ embedding_type: "guest-embed",+ }).then(({ body: startingDashboard }) => {+ cy.wrap(startingDashboard.id).as("startingDashboardId");++ H.createQuestion({+ name: "Orders for Starting Dashboard",+ query: { "source-table": ORDERS_ID, limit: 5 },+ }).then(({ body: startingQuestion }) => {+ H.addOrUpdateDashboardCard({+ card_id: startingQuestion.id,+ dashboard_id: startingDashboard.id,+ card: {+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 8,+ visualization_settings: {+ column_settings: {+ // ID column links to target dashboard with parameter+ [`["ref",["field",${ORDERS.ID},null]]`]: {+ click_behavior: {+ type: "link",+ linkType: "dashboard",+ linkTextTemplate: "Go to Target Dashboard",+ targetId: this.targetDashboardId,+ parameterMapping: {+ [TARGET_DASHBOARD_FILTER.id]: {+ source: {+ type: "column",+ id: "ID",+ name: "ID",+ },+ target: {+ type: "parameter",+ id: TARGET_DASHBOARD_FILTER.id,+ },+ id: TARGET_DASHBOARD_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: this.nativeQuestionId,+ parameterMapping: {+ id: {+ source: {+ type: "column",+ id: "PRODUCT_ID",+ name: "Product ID",+ },+ target: {+ type: "variable",+ id: "id",+ },+ id: "id",+ },+ },+ },+ },+ },+ },+ },+ });+ });+ });+ });+ });++ it("should navigate to a linked dashboard with filters when clicking a dashboard link", () => {+ cy.get<number>("@startingDashboardId").then((startingDashboardId) => {+ H.visitCustomHtmlPage(`+ ${H.getNewEmbedScriptTag()}+ ${H.getNewEmbedConfigurationScript({})}+ <metabase-dashboard dashboard-id="${startingDashboardId}" drills enable-entity-navigation />+ `);+ });++ cy.wait("@getDashCardQuery");++ cy.log("click on the dashboard link");+ H.getSimpleEmbedIframeContent()+ .findAllByText("Go to Target Dashboard")+ .first()+ .click();++ cy.wait("@getDashboard");++ cy.log("verify we navigated to Target Dashboard");+ H.getSimpleEmbedIframeContent()+ .findByText("Target Dashboard")+ .should("be.visible");++ cy.log("verify the filter was passed");+ H.getSimpleEmbedIframeContent()+ .findByTestId("dashboard-parameters-widget-container")+ .findByLabelText("ID Filter")+ .should("contain", "1");++ cy.log("verify back button and navigate back");+ H.getSimpleEmbedIframeContent()+ .findByText("Back to Starting Dashboard")+ .should("be.visible")+ .click();++ cy.log("verify we returned to Starting Dashboard");+ H.getSimpleEmbedIframeContent()+ .findByText("Starting Dashboard")+ .should("be.visible");+ H.getSimpleEmbedIframeContent()+ .findByText(/Back to/)+ .should("not.exist");+ });++ it("should navigate to a linked question with parameters when clicking a question link", () => {+ cy.get<number>("@startingDashboardId").then((startingDashboardId) => {+ H.visitCustomHtmlPage(`+ ${H.getNewEmbedScriptTag()}+ ${H.getNewEmbedConfigurationScript({})}+ <metabase-dashboard dashboard-id="${startingDashboardId}" drills enable-entity-navigation />+ `);+ });++ cy.wait("@getDashCardQuery");++ cy.log("click on the question link");+ H.getSimpleEmbedIframeContent()+ .findAllByText("Go to Native Question")+ .first()+ .click();++ cy.log("verify the question loaded");+ H.getSimpleEmbedIframeContent()+ .findByTestId("query-visualization-root")+ .should("be.visible");++ cy.log("verify back button is visible");+ H.getSimpleEmbedIframeContent()+ .findByText("Back to Starting Dashboard")+ .should("be.visible");+ });++ it("should not navigate when drills are disabled", () => {+ cy.get<number>("@startingDashboardId").then((startingDashboardId) => {+ H.visitCustomHtmlPage(`+ ${H.getNewEmbedScriptTag()}+ ${H.getNewEmbedConfigurationScript({})}+ <metabase-dashboard dashboard-id="${startingDashboardId}" drills="false" enable-entity-navigation />+ `);+ });++ cy.wait("@getDashCardQuery");++ cy.log("click on a cell that has click behavior configured");+ H.getSimpleEmbedIframeContent().findAllByText("37.65").first().click();++ cy.log("no drill popover should appear");+ H.getSimpleEmbedIframeContent()+ .findByText(/Filter by this value/)+ .should("not.exist");++ cy.log("no navigation should happen");+ H.getSimpleEmbedIframeContent()+ .findByText("Target Dashboard")+ .should("not.exist");+ H.getSimpleEmbedIframeContent()+ .findByText(/Back to/)+ .should("not.exist");+ });++ it("should not support internal navigation on guest embeds", () => {+ // Enable guest embedding settings+ cy.request("PUT", "/api/setting/enable-embedding-simple", {+ value: true,+ });+ cy.request("PUT", "/api/setting/enable-embedding-static", {+ value: true,+ });+ updateSetting("embedding-secret-key", JWT_SHARED_SECRET);++ cy.get("@startingDashboardId").then(async (dashboardId) => {+ const token = await getSignedJwtForResource({+ resourceId: dashboardId as unknown as number,+ resourceType: "dashboard",+ });++ const frame = H.loadSdkIframeEmbedTestPage({+ metabaseConfig: { isGuest: true },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ token,+ drills: true,+ },+ },+ ],+ });++ frame.within(() => {+ cy.log("dashboard should render");+ cy.findByText("Orders for Starting Dashboard", {+ timeout: 10000,+ }).should("be.visible");++ cy.log(+ "click behavior link text should not be shown, actual data values should be visible instead",+ );+ cy.findByText("Go to Target Dashboard").should("not.exist");+ });+ });+ });+ });++ describe("<metabase-browser> breadcrumbs", () => {+ beforeEach(() => {+ H.prepareSdkIframeEmbedTest({ withToken: "bleeding-edge" });++ H.createQuestion({+ name: "Target Question",+ query: { "source-table": ORDERS_ID, limit: 5 },+ }).then(({ body }) => cy.wrap(body.id).as("targetQuestionId"));++ cy.then(function () {+ H.createDashboard({ name: "First Dashboard" }).then(+ ({ body: dashboard }) => {+ H.createQuestion({+ name: "Orders in First Dashboard",+ query: { "source-table": ORDERS_ID, limit: 5 },+ }).then(({ body: dashQuestion }) => {+ H.addOrUpdateDashboardCard({+ card_id: dashQuestion.id,+ dashboard_id: dashboard.id,+ card: {+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 8,+ visualization_settings: {+ column_settings: {+ [`["ref",["field",${ORDERS.ID},null]]`]: {+ click_behavior: {+ type: "link",+ linkType: "question",+ linkTextTemplate: "Go to Target Question",+ targetId: this.targetQuestionId,+ parameterMapping: {},+ },+ },+ },+ },+ },+ });+ });+ },+ );+ });+ });++ it("should hide breadcrumbs during internal navigation and show them again after going back", () => {+ H.visitCustomHtmlPage(`+ ${H.getNewEmbedScriptTag()}+ ${H.getNewEmbedConfigurationScript({})}+ <metabase-browser initial-collection="root" enable-entity-navigation />+ `);++ cy.log("click on the dashboard to open it");+ H.getSimpleEmbedIframeContent()+ .findByText("First Dashboard")+ .should("be.visible")+ .click();++ cy.wait("@getDashCardQuery");++ cy.log("breadcrumbs should be visible");+ H.getSimpleEmbedIframeContent()+ .findByTestId("sdk-breadcrumbs")+ .should("be.visible");++ cy.log("no back button should exist");+ H.getSimpleEmbedIframeContent()+ .findByText(/Back to/)+ .should("not.exist");++ cy.log("click on click behavior link to trigger internal navigation");+ H.getSimpleEmbedIframeContent()+ .findAllByText("Go to Target Question")+ .first()+ .click();++ cy.log("breadcrumbs should be hidden after navigating");+ H.getSimpleEmbedIframeContent()+ .findByTestId("sdk-breadcrumbs")+ .should("not.exist");++ cy.log("back button should be visible");+ H.getSimpleEmbedIframeContent()+ .findByText(/Back to/)+ .should("be.visible")+ .click();++ cy.log("breadcrumbs should return after going back");+ H.getSimpleEmbedIframeContent()+ .findByTestId("sdk-breadcrumbs")+ .should("be.visible");++ cy.log("back button should be gone");+ H.getSimpleEmbedIframeContent()+ .findByText(/Back to/)+ .should("not.exist");+ });+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsxindex e2a34973c08..79fe6b263c6 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx@@ -14,7 +14,6 @@ interface SdkAdHocQuestionProps {export const SdkAdHocQuestion = ({questionPath,- withResetButton = true,title,plugins,height,@@ -32,10 +31,10 @@ export const SdkAdHocQuestion = ({initialSqlParameters,onNavigateBack,onVisualizationChange,+ navigateToNewCard,}: SdkAdHocQuestionProps &Pick<SdkQuestionProps,- | "withResetButton"| "title"| "plugins"| "height"@@ -52,6 +51,7 @@ export const SdkAdHocQuestion = ({| "withDownloads"| "initialSqlParameters"| "onVisualizationChange"+ | "navigateToNewCard">) => {const { location, params } = useMemo(() => getQuestionParameters(questionPath),@@ -82,12 +82,12 @@ export const SdkAdHocQuestion = ({initialSqlParameters={initialSqlParameters}withDownloads={withDownloads}onNavigateBack={onNavigateBack}+ navigateToNewCard={navigateToNewCard}height={height}width={width}className={className}style={style}title={title}- withResetButton={withResetButton}withChartTypeSelector={withChartTypeSelector}onVisualizationChange={onVisualizationChange}>diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsxindex 87237725d7d..ee6c54c0c42 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx@@ -25,10 +25,10 @@ export const SdkBreadcrumbs = ({style,onBreadcrumbClick,}: SdkBreadcrumbProps) => {- const { breadcrumbs, navigateTo } = useSdkBreadcrumbs();+ const { breadcrumbs, navigateTo, isBreadcrumbEnabled } = useSdkBreadcrumbs();const tc = useTranslateContent();- if (breadcrumbs.length === 0) {+ if (breadcrumbs.length === 0 || !isBreadcrumbEnabled) {return null;}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbsProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbsProvider.tsxindex 17fe52ecfd3..fc7524fb0e2 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbsProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbsProvider.tsx@@ -1,5 +1,6 @@import { type ReactNode, createContext, useCallback, useState } from "react";+import { useSdkInternalNavigationOptional } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";import type {SdkBreadcrumbItem,SdkBreadcrumbsContextType,@@ -21,6 +22,8 @@ export const SdkBreadcrumbsProvider = ({children,}: SdkBreadcrumbsProviderProps) => {const [breadcrumbs, setBreadcrumbs] = useState<SdkBreadcrumbItem[]>([]);+ const navigationContext = useSdkInternalNavigationOptional();+ const isInInternalNavigation = navigationContext?.canGoBack ?? false;const reportLocation = useCallback((item: SdkBreadcrumbItem) => {setBreadcrumbs((prevBreadcrumbs) =>@@ -44,7 +47,7 @@ export const SdkBreadcrumbsProvider = ({breadcrumbs.length > 0 ? breadcrumbs[breadcrumbs.length - 1] : null;const value: SdkBreadcrumbsContextType = {- isBreadcrumbEnabled: true,+ isBreadcrumbEnabled: !isInInternalNavigation,breadcrumbs,currentLocation,navigateTo,diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton.module.css b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton.module.cssnew file mode 100644index 00000000000..523507eadd1--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton.module.css@@ -0,0 +1,5 @@+.backButton:not([data-css-specificity-hack]) {+ &:hover {+ color: var(--mb-color-brand);+ }+}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton.tsxnew file mode 100644index 00000000000..f9c0a1e148d--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton.tsx@@ -0,0 +1,61 @@+import cx from "classnames";+import { t } from "ttag";++import { useTranslateContent } from "metabase/i18n/hooks";+import { Button, Icon } from "metabase/ui";++import { withPublicComponentWrapper } from "../PublicComponentWrapper";++import S from "./SdkInternalNavigationBackButton.module.css";+import { useSdkInternalNavigationOptional } from "./context";++/**+ * A back button that navigates to the previous entry in the SDK internal navigation stack.+ * Returns null if there's no navigation context or if there's no previous entry to go back to.+ */+const SdkInternalNavigationBackButtonInner = ({+ style,+ className,+}: {+ style?: React.CSSProperties;+ className?: string;+}) => {+ const navigation = useSdkInternalNavigationOptional();+ const tc = useTranslateContent();++ if (!navigation?.canGoBack) {+ return null;+ }++ const { previousEntry, pop } = navigation;++ const previousName =+ previousEntry && "name" in previousEntry+ ? tc(previousEntry.name)+ : undefined;++ const label = previousName ? t`Back to ${previousName}` : t`Back`;++ return (+ <Button+ variant="subtle"+ color="text-secondary"+ size="sm"+ leftSection={<Icon name="chevronleft" />}+ onClick={pop}+ pl={0}+ style={style}+ className={cx(className, S.backButton)}+ aria-label={label}+ >+ {label}+ </Button>+ );+};++export const SdkInternalNavigationBackButton = withPublicComponentWrapper(+ SdkInternalNavigationBackButtonInner,+ {+ supportsGuestEmbed: false,+ },+);diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsxnew file mode 100644index 00000000000..92c837c530d--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx@@ -0,0 +1,178 @@+import {+ type CSSProperties,+ type ReactNode,+ useCallback,+ useContext,+ useMemo,+ useState,+} from "react";+import { match } from "ts-pattern";++import { SdkDashboardStyledWrapper } from "embedding-sdk-bundle/components/public/dashboard/SdkDashboardStyleWrapper";+import type { SdkDashboardId } from "embedding-sdk-bundle/types/dashboard";+import { Stack } from "metabase/ui";++import { SdkQuestion } from "../../public/SdkQuestion";+import type {+ DrillThroughQuestionProps,+ SdkQuestionProps,+} from "../../public/SdkQuestion/SdkQuestion";+import { InteractiveDashboardContent } from "../../public/dashboard/InteractiveDashboard/InteractiveDashboard";+import type { SdkDashboardInnerProps } from "../../public/dashboard/SdkDashboard";++import { SdkInternalNavigationBackButton } from "./SdkInternalNavigationBackButton";+import {+ SdkInternalNavigationContext,+ type SdkInternalNavigationEntry,+} from "./context";++type Props = {+ children: ReactNode;+ dashboardProps?: Partial<Omit<SdkDashboardInnerProps, "dashboardId">>;+ /** Custom renderer for drill-through questions */+ renderDrillThroughQuestion?: () => ReactNode;+ /** Props to pass to drill-through question components */+ drillThroughQuestionProps?: DrillThroughQuestionProps;+ style?: CSSProperties;+ className?: string;+};++const SdkInternalNavigationProviderInner = ({+ style,+ className,+ children,+ dashboardProps,+ renderDrillThroughQuestion: RenderDrillThroughQuestion,+ drillThroughQuestionProps,+}: Props) => {+ const [stack, setStack] = useState<SdkInternalNavigationEntry[]>([]);++ const push = useCallback((entry: SdkInternalNavigationEntry) => {+ setStack((prev) => [...prev, entry]);+ }, []);++ const pop = useCallback(() => {+ setStack((prev) => {+ const poppedEntry = prev.at(-1);+ // Call onPop for placeholder entries that require special logic+ if (poppedEntry && "onPop" in poppedEntry && poppedEntry.onPop) {+ poppedEntry.onPop();+ }+ return prev.slice(0, -1);+ });+ }, []);++ // Initialize the stack with a dashboard entry (called by dashboard components when the dashboard loads and we have the name)+ const initWithDashboard = useCallback(+ (dashboard: { id: SdkDashboardId; name: string }) => {+ if (stack.length === 0) {+ setStack([+ { type: "dashboard", id: dashboard.id, name: dashboard.name },+ ]);+ }+ },+ [stack.length],+ );++ const value = useMemo(+ () => ({+ stack,+ push,+ pop,+ currentEntry: stack.at(-1),+ previousEntry: stack.at(-2),+ canGoBack: stack.length > 1,+ initWithDashboard,+ }),+ [stack, push, pop, initWithDashboard],+ );++ // "Virtual" entries are entries that are rendered by the previous entity (ie: drills, new question from dashboard)+ // we don't have to render them, but we need them in the stack to make the back button work correctly+ const nonVirtualEntries = useMemo(+ () => stack.filter((entry) => !entry.type.startsWith("virtual")),+ [stack],+ );++ const entryToRender = nonVirtualEntries.at(-1);+ const entryIndex = entryToRender ? stack.indexOf(entryToRender) : -1;+ // If the entry is the original entry, we just need to return the children.+ const entryIsOriginalEntity = stack.length === 0 || entryIndex === 0;++ const shouldRenderBackButton = match(stack.at(-1)?.type ?? null)+ .with(null, () => false)+ .with("dashboard", () => true)+ .with("question", () => false) // questions render their button in the header toolbar+ .otherwise(() => false); // all other navigations end up rendering a question (ad-hoc, new question etc)++ const maybeButton = shouldRenderBackButton ? (+ // Same padding as when the button is rendered inside the question, to minimize movement while navigating+ <Stack align="flex-start" p="md">+ <SdkInternalNavigationBackButton />+ </Stack>+ ) : null;++ const content = match({ activeEntry: entryToRender })+ .with({ activeEntry: { type: "dashboard" } }, ({ activeEntry }) => (+ <InteractiveDashboardContent+ {...dashboardProps}+ style={undefined}+ className={undefined}+ dashboardId={activeEntry.id}+ initialParameters={activeEntry.parameters}+ 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>+ );+ })+ .otherwise(() => children);++ // When we don't render the children directly, we need to render a wrapper with the styles applied.+ // Otherwise we don pass `style` and `className` to anything, we can't always wrap it otherwise we may render+ // paddings and borders twice.+ return (+ <SdkInternalNavigationContext.Provider value={value}>+ {entryIsOriginalEntity ? (+ children+ ) : (+ <SdkDashboardStyledWrapper className={className} style={style}>+ {maybeButton}+ {content}+ </SdkDashboardStyledWrapper>+ )}+ </SdkInternalNavigationContext.Provider>+ );+};++/**+ * Outer component that handles the nesting check.+ * If already inside a navigation provider, just render children directly.+ * This allows us to just wrap components with this and this will make sure to not+ * re-render the actual context provider.+ */+export const SdkInternalNavigationProvider = (props: Props) => {+ const isNested = useContext(SdkInternalNavigationContext);++ if (isNested) {+ return props.children;+ }++ return <SdkInternalNavigationProviderInner {...props} />;+};diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsxnew file mode 100644index 00000000000..c9fcf6df037--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx@@ -0,0 +1,68 @@+import { createContext, useContext } from "react";++import type { SdkDashboardId } from "embedding-sdk-bundle/types/dashboard";+import type { SdkQuestionId } from "embedding-sdk-bundle/types/question";+import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";++export type SdkInternalNavigationEntry =+ | {+ type: "dashboard";+ id: SdkDashboardId;+ name: string;+ parameters?: ParameterValues;+ }+ | {+ type: "question";+ id: SdkQuestionId;+ name: string;+ parameters?: ParameterValues;+ }+ | {+ /** Virtual entry for question drills - parent component handles rendering, this just tracks navigation depth */+ type: "virtual-question-drill";+ name: string;+ onPop?: () => void;+ }+ | {+ /** Virtual entry for opening a card from dashboard (clicking card title or click behavior) */+ type: "virtual-open-card";+ name: string;+ onPop?: () => void;+ }+ | {+ /** Virtual entry for new question creation from dashboard */+ type: "virtual-new-question";+ onPop?: () => void;+ };++export type SdkInternalNavigationContextValue = {+ stack: SdkInternalNavigationEntry[];+ push: (entry: SdkInternalNavigationEntry) => void;+ pop: () => void;+ currentEntry: SdkInternalNavigationEntry | undefined;+ canGoBack: boolean;+ previousEntry: SdkInternalNavigationEntry | undefined;+ initWithDashboard: (dashboard: { id: SdkDashboardId; name: string }) => void;+};++export const SdkInternalNavigationContext =+ createContext<SdkInternalNavigationContextValue | null>(null);++export const useSdkInternalNavigation =+ (): SdkInternalNavigationContextValue => {+ const ctx = useContext(SdkInternalNavigationContext);+ if (!ctx) {+ throw new Error(+ "useSdkInternalNavigation must be used within SdkInternalNavigationProvider",+ );+ }+ return ctx;+ };++/**+ * Optional version of useSdkInternalNavigation that returns null if outside provider.+ * Useful for components that may be rendered outside the navigation context.+ */+export const useSdkInternalNavigationOptional = () => {+ return useContext(SdkInternalNavigationContext);+};diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex d9fb70c235d..8f16cc7b019 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -1,7 +1,14 @@-import { createContext, useContext, useEffect, useMemo } from "react";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+} from "react";import { t } from "ttag";import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { useSdkInternalNavigationOptional } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";import { SdkQuestionAlertListModal } from "embedding-sdk-bundle/components/private/notifications/SdkQuestionAlertListModal";import { QuestionAlertModalProvider } from "embedding-sdk-bundle/components/private/notifications/context/QuestionAlertModalProvider";import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";@@ -67,6 +74,7 @@ export const SdkQuestionProvider = ({onVisualizationChange,}: SdkQuestionProviderProps) => {const isGuestEmbed = useSdkSelector(getIsGuestEmbed);+ const navigation = useSdkInternalNavigationOptional();const {resourceId: questionId,@@ -170,6 +178,25 @@ export const SdkQuestionProvider = ({const mode = (question && getClickActionMode({ question })) ?? null;+ // Wrap navigateToNewCard to push the virtual entry for the internal navigation system+ const navigateToNewCardWithSdkInternalNavigation = useCallback(+ async (params: Parameters<NonNullable<typeof navigateToNewCard>>[0]) => {+ // This actually changes what gets rendered+ await navigateToNewCard?.(params);++ // Push virtual entry if last entry is NOT already a question drill+ const currentEntry = navigation?.stack.at(-1);+ if (currentEntry?.type !== "virtual-question-drill") {+ navigation?.push({+ type: "virtual-question-drill",+ name: question?.displayName() ?? t`Question`,+ onPop: () => loadAndQueryQuestion(),+ });+ }+ },+ [navigateToNewCard, navigation, question, loadAndQueryQuestion],+ );+const questionContext: SdkQuestionContextType = {originalId: questionId,token,@@ -184,8 +211,8 @@ export const SdkQuestionProvider = ({updateParameterValues,navigateToNewCard:userNavigateToNewCard !== undefined- ? userNavigateToNewCard- : navigateToNewCard,+ ? navigateToNewCard+ : navigateToNewCardWithSdkInternalNavigation,plugins,question,originalQuestion,@@ -212,6 +239,23 @@ export const SdkQuestionProvider = ({loadAndQueryQuestion();}, [loadAndQueryQuestion, tokenError]);+ // Push the question name to the stack if the stack is empty (ie: this is the root question)+ // We need to wait for the question to load to have the name+ useEffect(() => {+ if (+ question &&+ !!questionId &&+ navigation &&+ navigation.stack.length === 0+ ) {+ navigation.push({+ type: "question",+ id: questionId,+ name: question.displayName() || t`Question`,+ });+ }+ }, [questionId, question, navigation]);+const dispatch = useSdkDispatch();useEffect(() => {diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsxindex 309c7d44d8c..419ac75a3f8 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsx@@ -1,67 +1,36 @@-import { c, t } from "ttag";-import { getQuestionTitle } from "embedding-sdk-bundle/lib/sdk-question/get-question-title";import { useTranslateContent } from "metabase/i18n/hooks";-import { Anchor, Stack, Text } from "metabase/ui";+import { Stack, Text } from "metabase/ui";import { useSdkQuestionContext } from "../SdkQuestion/context";import type { SdkQuestionDefaultViewProps } from "./SdkQuestionDefaultView";-interface DefaultViewTitleTextProps- extends Pick<SdkQuestionDefaultViewProps, "withResetButton" | "title"> {- isQuestionChanged?: boolean;- onReset?: () => void;- originalName?: string | null;-}+type DefaultViewTitleTextProps = Pick<SdkQuestionDefaultViewProps, "title">;-const DefaultViewTitleText = ({- title: Title,- withResetButton = false,- isQuestionChanged = false,- onReset,- originalName,-}: DefaultViewTitleTextProps) => (- <Stack gap="xs">- {originalName && withResetButton && isQuestionChanged && (- <Text fw={600} size="sm">- {c("{0} refers to the name of the original question").jt`Return to ${(- <Anchor- key="anchor"- size="sm"- ml="xs"- color="brand"- onClick={onReset}- >- {originalName}- </Anchor>- )}`}- </Text>- )}- {typeof Title === "function" ? <Title></Title> : Title}- </Stack>-);+const DefaultViewTitleText = ({ title: Title }: DefaultViewTitleTextProps) => {+ return (+ <Stack gap="xs" align="flex-start">+ {typeof Title === "function" ? <Title></Title> : Title}+ </Stack>+ );+};-export const DefaultViewTitle = ({- title,- withResetButton = false,-}: SdkQuestionDefaultViewProps) => {- const { question, originalQuestion, onReset } = useSdkQuestionContext();+export const DefaultViewTitle = ({ title }: SdkQuestionDefaultViewProps) => {+ const { question } = useSdkQuestionContext();const tc = useTranslateContent();- const isQuestionChanged = originalQuestion- ? question?.isQueryDirtyComparedTo(originalQuestion)- : true;-if (title === false) {return null;}if (title === undefined || title === true) {- const originalName = tc(originalQuestion?.displayName());-const titleText = getQuestionTitle(question, tc);+ if (titleText === null) {+ return null;+ }+return (<DefaultViewTitleTexttitle={@@ -71,10 +40,6 @@ export const DefaultViewTitle = ({</Text>)}- withResetButton={withResetButton}- isQuestionChanged={isQuestionChanged}- onReset={onReset}- originalName={originalName}/>);}@@ -89,10 +54,6 @@ export const DefaultViewTitle = ({{titleText}</Text>}- withResetButton={withResetButton}- isQuestionChanged={isQuestionChanged}- onReset={onReset}- originalName={t`the original exploration`}/>);}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsxindex 85b6b157d89..386bf561829 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx@@ -36,7 +36,7 @@ import {FlexibleSizeComponent,type FlexibleSizeProps,} from "../FlexibleSizeComponent";-import { BackButton } from "../SdkQuestion/components/BackButton/BackButton";+import { SdkInternalNavigationBackButton } from "../SdkInternalNavigation/SdkInternalNavigationBackButton";import { BreakoutDropdown } from "../SdkQuestion/components/Breakout/BreakoutDropdown";import { ChartTypeDropdown } from "../SdkQuestion/components/ChartTypeDropdown";import { DownloadWidgetDropdown } from "../SdkQuestion/components/DownloadWidget";@@ -61,11 +61,6 @@ export interface SdkQuestionDefaultViewProps extends FlexibleSizeProps {*/title?: SdkQuestionTitleProps;- /**- * Determines whether a reset button is displayed. Only relevant when using the default layout.- */- withResetButton?: boolean;-/*** Determines whether the chart type selector and corresponding settings button are shown. Only relevant when using the default layout.*/@@ -78,7 +73,6 @@ export const SdkQuestionDefaultView = ({className,style,title,- withResetButton,withChartTypeSelector,}: SdkQuestionDefaultViewProps): ReactElement => {const { isLocaleLoading } = useLocale();@@ -95,7 +89,7 @@ export const SdkQuestionDefaultView = ({queryQuestion,} = useSdkQuestionContext();- const { isBreadcrumbEnabled, reportLocation } = useSdkBreadcrumbs();+ const { reportLocation } = useSdkBreadcrumbs();const isGuestEmbed = useSdkSelector(getIsGuestEmbed);const isQuestionSaved = question?.isSaved();@@ -211,17 +205,10 @@ export const SdkQuestionDefaultView = ({data-hide-empty><Group gap="xs" data-hide-empty>- <Box- className={InteractiveQuestionS.BackButtonWrapper}- mr="sm"- data-hide-empty- >- <BackButton data-hide-empty />- </Box>- <DefaultViewTitle- title={title}- withResetButton={withResetButton && !isBreadcrumbEnabled}- />+ <Stack align="flex-start">+ <SdkInternalNavigationBackButton />+ <DefaultViewTitle title={title} />+ </Stack></Group>{showSaveButton && <SaveButton onClick={openSaveModal} />}</Group>diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.tsindex 5fd39189722..a87e4a72856 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts@@ -40,7 +40,6 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionProps> = Yup.object({withChartTypeSelector: Yup.mixed().optional(),withDownloads: Yup.mixed().optional(),withAlerts: Yup.mixed().optional(),- withResetButton: Yup.mixed().optional(),onVisualizationChange: Yup.mixed().optional(),}).noUnknown();diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.stories.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.stories.tsxindex a33d05ddc1f..80854407a3a 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.stories.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.stories.tsx@@ -89,7 +89,6 @@ export const Default = {isSaveEnabled: true,targetCollection: undefined,title: true,- withResetButton: true,},};diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsxindex bd9cf15070e..9556c5c24ca 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx@@ -1,6 +1,7 @@import type { ReactNode } from "react";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";import {BackButton,Breakout,@@ -56,6 +57,7 @@ export type BaseSdkQuestionProps = SdkQuestionIdProps & {| "isSaveEnabled"| "initialSqlParameters"| "withDownloads"+ | "withAlerts"| "targetCollection"| "onRun">;@@ -145,46 +147,71 @@ export const _SdkQuestion = ({className,style,title,- withResetButton = true,withChartTypeSelector = true,onVisualizationChange,-}: SdkQuestionProps): JSX.Element | null => (- <SdkQuestionProvider- questionId={questionId}- token={token}- options={options}- deserializedCard={deserializedCard}- componentPlugins={plugins}- onNavigateBack={onNavigateBack}- onBeforeSave={onBeforeSave}- onSave={onSave}- onRun={onRun}- isSaveEnabled={isSaveEnabled}- entityTypes={entityTypes}- targetCollection={targetCollection}- initialSqlParameters={initialSqlParameters}- hiddenParameters={hiddenParameters}- withDownloads={withDownloads}- withAlerts={withAlerts}- targetDashboardId={targetDashboardId}- backToDashboard={backToDashboard}- getClickActionMode={getClickActionMode}- navigateToNewCard={navigateToNewCard}- onVisualizationChange={onVisualizationChange}- >- {children ?? (- <SdkQuestionDefaultView- height={height}- width={width}- className={className}- style={style}- title={title}- withResetButton={withResetButton}- withChartTypeSelector={withChartTypeSelector}- />- )}- </SdkQuestionProvider>-);+}: SdkQuestionProps): JSX.Element | null => {+ const drillThroughQuestionProps: DrillThroughQuestionProps = {+ height,+ width,+ className,+ style,+ title,+ withChartTypeSelector,+ isSaveEnabled,+ targetCollection,+ entityTypes,+ onBeforeSave,+ onSave,+ onRun,+ withDownloads,+ withAlerts,+ plugins,+ };++ return (+ <SdkInternalNavigationProvider+ renderDrillThroughQuestion={() => <SdkQuestionDefaultView />}+ drillThroughQuestionProps={drillThroughQuestionProps}+ style={style}+ className={className}+ >+ <SdkQuestionProvider+ questionId={questionId}+ token={token}+ options={options}+ deserializedCard={deserializedCard}+ componentPlugins={plugins}+ onNavigateBack={onNavigateBack}+ onBeforeSave={onBeforeSave}+ onSave={onSave}+ onRun={onRun}+ isSaveEnabled={isSaveEnabled}+ entityTypes={entityTypes}+ targetCollection={targetCollection}+ initialSqlParameters={initialSqlParameters}+ hiddenParameters={hiddenParameters}+ withDownloads={withDownloads}+ withAlerts={withAlerts}+ targetDashboardId={targetDashboardId}+ backToDashboard={backToDashboard}+ getClickActionMode={getClickActionMode}+ navigateToNewCard={navigateToNewCard}+ onVisualizationChange={onVisualizationChange}+ >+ {children ?? (+ <SdkQuestionDefaultView+ height={height}+ width={width}+ className={className}+ style={style}+ title={title}+ withChartTypeSelector={withChartTypeSelector}+ />+ )}+ </SdkQuestionProvider>+ </SdkInternalNavigationProvider>+ );+};const subComponents: SdkQuestionComponents = {BackButton: BackButton,diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.tsindex 339bc9b54b5..7ee4cf321f6 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.ts@@ -32,7 +32,6 @@ const propsSchema: Yup.SchemaOf<EditableDashboardProps> = Yup.object({width: Yup.mixed().optional(),withChartTypeSelector: Yup.mixed().optional(),withDownloads: Yup.mixed().optional(),- withResetButton: Yup.mixed().optional(),}).optional().noUnknown(),@@ -54,6 +53,7 @@ const propsSchema: Yup.SchemaOf<EditableDashboardProps> = Yup.object({withSubscriptions: Yup.mixed().optional(),withTitle: Yup.mixed().optional(),onVisualizationChange: Yup.mixed().optional(),+ enableEntityNavigation: Yup.mixed().optional(),}).noUnknown();export const editableDashboardSchema: FunctionSchema = {diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsxindex 7bc8578a899..bc8e5befffd 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx@@ -1,9 +1,13 @@+import { useCallback } from "react";+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";+import { useSdkInternalNavigation } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";import { DASHBOARD_EDITING_ACTIONS } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants";import { DASHBOARD_ACTION } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys";import type { MetabasePluginsConfig as InternalMetabasePluginsConfig } from "metabase/embedding-sdk/types/plugins";import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";-import { EmbeddingSdkMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkMode";+import { createEmbeddingSdkMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkMode";import {type EditableDashboardOwnProps,@@ -22,7 +26,9 @@ import { editableDashboardSchema } from "./EditableDashboard.schema";export type EditableDashboardProps = SdkDashboardProps &EditableDashboardOwnProps;-export const EditableDashboardInner = (props: EditableDashboardProps) => {+const EditableDashboardContent = (props: EditableDashboardProps) => {+ const { push: pushNavigation } = useSdkInternalNavigation();+const dashboardActions: SdkDashboardInnerProps["dashboardActions"] = ({isEditing,}) =>@@ -35,15 +41,21 @@ export const EditableDashboardInner = (props: EditableDashboardProps) => {DASHBOARD_ACTION.REFRESH_INDICATOR,];- const getClickActionMode: SdkDashboardInnerProps["getClickActionMode"] = ({- question,- }) =>- getEmbeddingMode({- question,- queryMode: EmbeddingSdkMode,- plugins: props.drillThroughQuestionProps- ?.plugins as InternalMetabasePluginsConfig,- });+ const getClickActionMode: SdkDashboardInnerProps["getClickActionMode"] =+ useCallback(+ ({+ question,+ }: Parameters<+ NonNullable<SdkDashboardInnerProps["getClickActionMode"]>+ >[0]) =>+ getEmbeddingMode({+ question,+ queryMode: createEmbeddingSdkMode({ pushNavigation }),+ plugins: props.drillThroughQuestionProps+ ?.plugins as InternalMetabasePluginsConfig,+ }),+ [pushNavigation, props.drillThroughQuestionProps?.plugins],+ );return (<SdkDashboard@@ -54,6 +66,18 @@ export const EditableDashboardInner = (props: EditableDashboardProps) => {);};+export const EditableDashboardInner = (props: EditableDashboardProps) => {+ return (+ <SdkInternalNavigationProvider+ style={props.style}+ className={props.className}+ dashboardProps={props}+ >+ <EditableDashboardContent {...props} />+ </SdkInternalNavigationProvider>+ );+};+export const EditableDashboard = Object.assign(withPublicComponentWrapper(EditableDashboardInner, {supportsGuestEmbed: false,diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsxindex b43b2a09946..81cc43786aa 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx@@ -121,16 +121,12 @@ describe("EditableDashboard", () => {// We should be in the query builderexpect(- await screen.findByRole("button", { name: "Back to Test dashboard" }),+ await screen.findByLabelText(/Back to Test dashboard/),).toBeInTheDocument();- await userEvent.click(- screen.getByRole("button", { name: "Back to Test dashboard" }),- );+ await userEvent.click(screen.getByLabelText(/Back to Test dashboard/));// We should be back in the dashboard- expect(- screen.getByText("You're editing this dashboard."),- ).toBeInTheDocument();+ expect(screen.getByText("Test dashboard")).toBeInTheDocument();});it("should allow to pass `dataPickerProps.entityTypes` to the query builder", async () => {diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.tsindex 6335ed69dfa..3387281818d 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.ts@@ -32,7 +32,6 @@ const propsSchema: Yup.SchemaOf<InteractiveDashboardProps> = Yup.object({width: Yup.mixed().optional(),withChartTypeSelector: Yup.mixed().optional(),withDownloads: Yup.mixed().optional(),- withResetButton: Yup.mixed().optional(),}).optional().noUnknown(),@@ -56,6 +55,7 @@ const propsSchema: Yup.SchemaOf<InteractiveDashboardProps> = Yup.object({withSubscriptions: Yup.mixed().optional(),withTitle: Yup.mixed().optional(),onVisualizationChange: Yup.mixed().optional(),+ enableEntityNavigation: Yup.mixed().optional(),}).noUnknown();export const interactiveDashboardSchema: FunctionSchema = {diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsxindex 624c665bda5..4d5f8e48a42 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx@@ -1,6 +1,8 @@import { useCallback, useMemo } from "react";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";+import { useSdkInternalNavigation } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";import { useSdkSelector } from "embedding-sdk-bundle/store";import { getPlugins } from "embedding-sdk-bundle/store/selectors";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";@@ -9,10 +11,14 @@ import { DASHBOARD_ACTION } from "metabase/dashboard/components/DashboardHeader/import { isQuestionCard } from "metabase/dashboard/utils";import type { MetabasePluginsConfig as InternalMetabasePluginsConfig } from "metabase/embedding-sdk/types/plugins";import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";-import { EmbeddingSdkMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkMode";+import { createEmbeddingSdkMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkMode";import type { ClickActionModeGetter } from "metabase/visualizations/types";-import { SdkDashboard, type SdkDashboardProps } from "../SdkDashboard";+import {+ SdkDashboard,+ type SdkDashboardInnerProps,+ type SdkDashboardProps,+} from "../SdkDashboard";import { interactiveDashboardSchema } from "./InteractiveDashboard.schema";@@ -23,8 +29,11 @@ import { interactiveDashboardSchema } from "./InteractiveDashboard.schema";*/export type InteractiveDashboardProps = SdkDashboardProps;-const InteractiveDashboardInner = (props: InteractiveDashboardProps) => {+export const InteractiveDashboardContent = (+ props: InteractiveDashboardProps,+) => {const globalPlugins = useSdkSelector(getPlugins);+ const { push: pushNavigation } = useSdkInternalNavigation();const plugins: MetabasePluginsConfig = useMemo(() => {return { ...globalPlugins, ...props.plugins };@@ -34,30 +43,46 @@ const InteractiveDashboardInner = (props: InteractiveDashboardProps) => {({ question }) =>getEmbeddingMode({question,- queryMode: EmbeddingSdkMode,+ queryMode: createEmbeddingSdkMode({ pushNavigation }),plugins: plugins as InternalMetabasePluginsConfig,}),- [plugins],+ [plugins, pushNavigation],);- return (- <SdkDashboard- {...props}- getClickActionMode={getClickActionMode}- dashboardActions={[+ const dashboardProps: SdkDashboardInnerProps = useMemo(+ () => ({+ ...props,+ getClickActionMode,+ dashboardActions: [DASHBOARD_ACTION.DASHBOARD_SUBSCRIPTIONS,DASHBOARD_ACTION.DOWNLOAD_PDF,DASHBOARD_ACTION.REFRESH_INDICATOR,- ]}- dashcardMenu={({ dashcard, result, downloadsEnabled }) =>+ ],+ dashcardMenu: ({ dashcard, result, downloadsEnabled }) =>downloadsEnabled?.results &&isQuestionCard(dashcard.card) &&!!result?.data &&!result?.error && (<PublicOrEmbeddedDashCardMenu result={result} dashcard={dashcard} />- )- }- />+ ),+ }),+ [props, getClickActionMode],+ );++ return <SdkDashboard {...dashboardProps} />;+};++const InteractiveDashboardInner = (props: InteractiveDashboardProps) => {+ return (+ <SdkInternalNavigationProvider+ style={props.style}+ className={props.className}+ dashboardProps={props}+ renderDrillThroughQuestion={props.renderDrillThroughQuestion}+ drillThroughQuestionProps={props.drillThroughQuestionProps}+ >+ <InteractiveDashboardContent {...props} />+ </SdkInternalNavigationProvider>);};diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex d2a9f7ffcc5..71d29c4bdec 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -2,6 +2,7 @@ import {type CSSProperties,type PropsWithChildren,type ReactNode,+ useCallback,useEffect,useMemo,useRef,@@ -10,6 +11,7 @@ import {import { useUnmount } from "react-use";import { match } from "ts-pattern";import { t } from "ttag";+import { isEqual } from "underscore";import {DashboardNotFoundError,@@ -18,6 +20,7 @@ import {withPublicComponentWrapper,} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { SdkAdHocQuestion } from "embedding-sdk-bundle/components/private/SdkAdHocQuestion";+import { useSdkInternalNavigationOptional } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";import { useDashboardLoadHandlers } from "embedding-sdk-bundle/hooks/private/use-dashboard-load-handlers";import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";@@ -169,6 +172,7 @@ const SdkDashboardInner = ({withDownloads = false,withSubscriptions = false,hiddenParameters = [],+ enableEntityNavigation = false, // SDK defaults to false (core app defaults to true)drillThroughQuestionHeight,plugins,onLoad,@@ -223,7 +227,7 @@ const SdkDashboardInner = ({adhocQuestionUrl,onNavigateBackToDashboard,onEditQuestion,- onNavigateToNewCardFromDashboard,+ onNavigateToNewCardFromDashboard: baseOnNavigateToNewCardFromDashboard,} = useCommonDashboardParams({dashboardId,});@@ -287,6 +291,54 @@ const SdkDashboardInner = ({const { modalContent, show } = useConfirmation();const isDashboardDirty = useSelector(getIsDirty);+ const sdkNavigation = useSdkInternalNavigationOptional();++ // Initialize navigation stack with dashboard entry when we have the name+ useEffect(() => {+ if (dashboard && sdkNavigation) {+ sdkNavigation.initWithDashboard({+ id: dashboard.id,+ name: dashboard.name,+ });+ }+ }, [dashboard, sdkNavigation]);++ // Wrap the navigation handler to push a virtual entry for back button support+ const onNavigateToNewCardFromDashboard = useCallback(+ (opts: Parameters<typeof baseOnNavigateToNewCardFromDashboard>[0]) => {+ baseOnNavigateToNewCardFromDashboard(opts);++ // If the id and query are the same, it means we're opening a card after having clicked its title+ const isClickingOnCardTitle =+ opts.nextCard.id === opts.previousCard.id &&+ isEqual(opts.nextCard.dataset_query, opts.previousCard.dataset_query);++ if (!isClickingOnCardTitle) {+ // For drills, only push if not already a question drill+ // One press of back button should undo all of them+ const currentEntry = sdkNavigation?.stack.at(-1);+ if (currentEntry?.type !== "virtual-question-drill") {+ sdkNavigation?.push({+ type: "virtual-question-drill",+ name: opts.previousCard.name ?? t`Question`,+ onPop: () => onNavigateBackToDashboard(),+ });+ }+ } else {+ sdkNavigation?.push({+ type: "virtual-open-card",+ name: opts.previousCard.name ?? t`Question`,+ onPop: () => onNavigateBackToDashboard(),+ });+ }+ },+ [+ baseOnNavigateToNewCardFromDashboard,+ sdkNavigation,+ onNavigateBackToDashboard,+ ],+ );+if (isLocaleLoading) {return (<SdkDashboardStyledWrapper className={className} style={style}>@@ -357,6 +409,10 @@ const SdkDashboardInner = ({* Dispatch the same actions as in the DashboardLeaveConfirmationModal.* @see {@link https://github.com/metabase/metabase/blob/4453fa8363eb37062a159f398050d050d91397a9/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx#L30-L34}*/+ sdkNavigation?.push({+ type: "virtual-new-question",+ onPop: () => setRenderMode("dashboard"),+ });setRenderMode("queryBuilder");dispatch(dismissAllUndo());await dispatch(updateDashboardAndCards());@@ -368,6 +424,10 @@ const SdkDashboardInner = ({},});} else {+ sdkNavigation?.push({+ type: "virtual-new-question",+ onPop: () => setRenderMode("dashboard"),+ });setRenderMode("queryBuilder");}}}@@ -390,6 +450,7 @@ const SdkDashboardInner = ({dispatch(toggleSidebar(SIDEBAR_NAME.addQuestion));}}autoScrollToDashcardId={autoScrollToDashcardId}+ enableEntityNavigation={enableEntityNavigation}>{match({ finalRenderMode, isGuestEmbed }).with({ finalRenderMode: "question" }, () => (@@ -435,11 +496,11 @@ const SdkDashboardInner = ({<DashboardQueryBuilderonCreate={(question) => {setNewDashboardQuestionId(question.id);- setRenderMode("dashboard");+ sdkNavigation?.pop(); // onPop handles setRenderMode("dashboard")dashboardContextProviderRef.current?.refetchDashboard();}}onNavigateBack={() => {- setRenderMode("dashboard");+ sdkNavigation?.pop(); // onPop handles setRenderMode("dashboard")}}dataPickerProps={dataPickerProps}onVisualizationChange={onVisualizationChange}@@ -529,7 +590,6 @@ function DashboardQueryBuilder({name: dashboard.name,}}entityTypes={dataPickerProps?.entityTypes}- withResetButtonwithChartTypeSelector// The default value is 600px and it cuts off the "Visualize" button.height="700px"diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsxindex 1d387cfa9b3..aa6f10bf141 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx@@ -24,6 +24,7 @@ export type StaticDashboardProps = Omit<| "drillThroughQuestionProps"| "drillThroughQuestionHeight"| "renderDrillThroughQuestion"+ | "enableEntityNavigation"> &SdkDashboardEntityPublicProps;diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsxindex 0d07e4a78c8..0dab4912120 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx@@ -20,6 +20,7 @@ import {import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";import { screen } from "__support__/ui";+import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";@@ -241,11 +242,13 @@ export const setupSdkDashboard = async ({renderWithSDKProviders(<Box h="500px">- <Component- dashboardId={dashboardId}- dataPickerProps={dataPickerProps}- {...props}- />+ <SdkInternalNavigationProvider>+ <Component+ dashboardId={dashboardId}+ dataPickerProps={dataPickerProps}+ {...props}+ />+ </SdkInternalNavigationProvider></Box>,{componentProviderProps: {diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.tsindex 3ce7eef633a..cb911adaf78 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.ts@@ -54,6 +54,12 @@ export type SdkDashboardDisplayProps = SdkDashboardEntityInternalProps & {* - Combining {@link SdkDashboardProps.initialParameters | initialParameters} and {@link SdkDashboardDisplayProps.hiddenParameters | hiddenParameters} to declutter the user interface is fine.**/hiddenParameters?: string[];++ /**+ * When true, internal click behaviors (links to dashboards/questions) are preserved.+ * When false (default for SDK), these click behaviors are filtered out.+ */+ enableEntityNavigation?: boolean;} & CommonStylingProps;export const useSdkDashboardParams = ({diff --git a/frontend/src/metabase-lib/v1/queries/drills/dashboard-click-drill.js b/frontend/src/metabase-lib/v1/queries/drills/dashboard-click-drill.jsindex e52a2264eee..dfd751134fa 100644--- a/frontend/src/metabase-lib/v1/queries/drills/dashboard-click-drill.js+++ b/frontend/src/metabase-lib/v1/queries/drills/dashboard-click-drill.js@@ -160,7 +160,7 @@ export function getDashboardDrillQuestionUrl(question, clicked) {: `${ML_Urls.getUrl(targetQuestion)}?${querystring.stringify(queryParams)}`;}-function getClickBehavior(clicked) {+export function getClickBehavior(clicked) {const settings = (clicked && clicked.settings) || {};const columnSettings =(clicked &&@@ -172,7 +172,7 @@ function getClickBehavior(clicked) {return columnSettings.click_behavior || settings.click_behavior;}-function getClickBehaviorData(clicked, clickBehavior) {+export function getClickBehaviorData(clicked, clickBehavior) {const data = getDataFromClicked(clicked);const { type, linkType, parameterMapping, tabId, targetId } = clickBehavior;const { extraData } = clicked || {};@@ -196,7 +196,7 @@ function getParameterIdValuePairs(});}-function getParameterValuesBySlug(+export function getParameterValuesBySlug(parameterMapping,{ data, extraData, clickBehavior },) {diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsxindex 57ba8c50859..fde3501a010 100644--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx@@ -257,6 +257,7 @@ export function DashCardVisualization({isFullscreen = false,isEditingParameter,onChangeLocation,+ enableEntityNavigation,} = useDashboardContext();const datasets = useSelector((state) => getDashcardData(state, dashcard.id));@@ -629,6 +630,7 @@ export function DashCardVisualization({renderLoadingView={renderLoadingView}titleMenuItems={titleMenuItems}errorMessageOverride={visualizerErrMsg}+ enableEntityNavigation={enableEntityNavigation}/></EmbeddingEntityContextProvider></div>diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsxindex d05b0fd1a3b..a41fd2c8e02 100644--- a/frontend/src/metabase/dashboard/context/context.tsx+++ b/frontend/src/metabase/dashboard/context/context.tsx@@ -77,6 +77,11 @@ export type DashboardContextOwnProps = {* Forcing passing it isn't ideal since we only need to do this in a couple of places*/onNewQuestion?: () => void;+ /**+ * When true, internal click behaviors (dashboard/question links) are preserved+ * instead of being filtered out. Used by the SDK for internal navigation.+ */+ enableEntityNavigation?: boolean;};export type DashboardContextOwnResult = {@@ -148,6 +153,7 @@ const DashboardContextProviderInner = forwardRef(cardTitled = true,getClickActionMode = undefined,withFooter = true,+ enableEntityNavigation = true, // true in core app, SDK passes it down as false// redux selectorsdashboard,@@ -433,6 +439,7 @@ const DashboardContextProviderInner = forwardRef(cardTitled,getClickActionMode,withFooter,+ enableEntityNavigation,// redux selectorsselectedTabId,diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsxindex 8287b68e2fa..3722fe924ac 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx@@ -111,12 +111,14 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {withDownloadsstyle={{ height: "100%" }}drillThroughQuestionProps={{ isSaveEnabled: false }}+ enableEntityNavigation={settings.enableEntityNavigation}/>) : (<EditableDashboardwithCardTitledashboardId={id}style={{ height: "100%" }}+ enableEntityNavigation={settings.enableEntityNavigation}/>);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsxindex 484c713e33b..36f2bbf281c 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx@@ -4,6 +4,7 @@ import { P, match } from "ts-pattern";import { PublicComponentStylesWrapper } from "embedding-sdk-bundle/components/private/PublicComponentStylesWrapper";import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { SdkBreadcrumbsProvider } from "embedding-sdk-bundle/components/private/SdkBreadcrumbs";+import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";import { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";import { MetabotQuestion } from "embedding-sdk-bundle/components/public/MetabotQuestion";import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";@@ -139,10 +140,12 @@ const SdkIframeEmbedView = ({componentName: "metabase-browser",},(settings) => (- // re-mount breadcrumbs when initial collection changes- <SdkBreadcrumbsProvider key={settings.initialCollection}>- <MetabaseBrowser settings={settings} />- </SdkBreadcrumbsProvider>+ <SdkInternalNavigationProvider>+ {/* re-mount breadcrumbs when initial collection changes */}+ <SdkBreadcrumbsProvider key={settings.initialCollection}>+ <MetabaseBrowser settings={settings} />+ </SdkBreadcrumbsProvider>+ </SdkInternalNavigationProvider>),).with(@@ -199,6 +202,7 @@ const SdkIframeEmbedView = ({withSubscriptions={settings.withSubscriptions}initialParameters={settings.initialParameters}hiddenParameters={settings.hiddenParameters}+ enableEntityNavigation={settings.enableEntityNavigation}drillThroughQuestionHeight="100%"drillThroughQuestionProps={{ isSaveEnabled: false }}/>diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.tsindex 3f97544c3d4..faf30c857e4 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts@@ -38,6 +38,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"initialParameters","hiddenParameters","drills",+ "enableEntityNavigation",] satisfies (keyof DashboardEmbedOptions)[],chart: ["questionId",@@ -66,6 +67,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"dataPickerEntityTypes","withNewQuestion","withNewDashboard",+ "enableEntityNavigation",] satisfies (keyof BrowserEmbedOptions)[],metabot: ["layout",diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.tsindex 625f8446aa8..86c2e240935 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts@@ -529,6 +529,7 @@ const MetabaseDashboardElement = createCustomElement("metabase-dashboard", ["drills","initial-parameters","hidden-parameters",+ "enable-entity-navigation",]);const MetabaseQuestionElement = createCustomElement("metabase-question", [@@ -554,6 +555,7 @@ const MetabaseManageContentElement = createCustomElement("metabase-browser", ["with-new-question","with-new-dashboard","read-only",+ "enable-entity-navigation",]);const MetabaseMetabotElement = createCustomElement("metabase-metabot", [diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.tsindex b03ec51a702..535030557f2 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts@@ -92,6 +92,7 @@ export type DashboardEmbedOptions = StrictUnion<// parametersinitialParameters?: ParameterValues;hiddenParameters?: string[];+ enableEntityNavigation?: boolean;// incompatible optionstemplate?: never;@@ -161,6 +162,9 @@ export interface BrowserEmbedOptions {/** Whether to show the "New dashboard" button. Defaults to true. Only applies when readOnly is false. */withNewDashboard?: boolean;+ /** Whether to enable internal entity navigation (links to dashboards/questions). Defaults to false. */+ enableEntityNavigation?: boolean;+template?: never;questionId?: never;dashboardId?: never;diff --git a/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts b/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.tsindex 452d9c67a08..f9e40e813bd 100644--- a/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts+++ b/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts@@ -1,35 +1,122 @@-import type { QueryClickActionsMode } from "../../types";+import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";+import {+ getClickBehavior,+ getClickBehaviorData,+ getParameterValuesBySlug,+} from "metabase-lib/v1/queries/drills/dashboard-click-drill";++import type {+ ClickObject,+ LegacyDrill,+ QueryClickActionsMode,+} from "../../types";import { CombineColumnsAction } from "../actions/CombineColumnsAction";import { DashboardClickAction } from "../actions/DashboardClickAction";import { ExtractColumnAction } from "../actions/ExtractColumnAction";import { HideColumnAction } from "../actions/HideColumnAction";import { NativeQueryClickFallback } from "../actions/NativeQueryClickFallback";-export const EmbeddingSdkMode: QueryClickActionsMode = {- name: "embedding-sdk",- hasDrills: true,- availableOnlyDrills: [- "drill-thru/column-extract",- "drill-thru/column-filter",- "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",- ],- clickActions: [- HideColumnAction,- DashboardClickAction,- ExtractColumnAction,- CombineColumnsAction,- ],- fallback: NativeQueryClickFallback,+export type ClickBehaviorTarget = {+ type: "dashboard" | "question";+ id: number;+ name: string;+ parameters: ParameterValues;+};++const getClickBehaviorTarget = (+ clicked: ClickObject,+): ClickBehaviorTarget | null => {+ const clickBehavior = getClickBehavior(clicked);+ if (!clickBehavior) {+ return null;+ }++ const { linkType, targetId, extraData, parameterMapping, data } =+ getClickBehaviorData(clicked, clickBehavior);++ if (linkType !== "dashboard" && linkType !== "question") {+ return null;+ }++ const parameters = parameterMapping+ ? getParameterValuesBySlug(parameterMapping, {+ data,+ extraData,+ clickBehavior,+ })+ : {};++ const entitiesMap =+ linkType === "dashboard" ? extraData?.dashboards : extraData?.questions;+ const target = entitiesMap?.[targetId];++ if (!target) {+ console.warn(+ `[SDK Navigation] Could not find ${linkType} with id ${targetId}`,+ );+ return null;+ }++ return { type: linkType, id: target.id, name: target.name, parameters };};++type CreateEmbeddingSdkModeOptions = {+ pushNavigation?: (target: ClickBehaviorTarget) => void;+};++export const createEmbeddingSdkMode = (+ options: CreateEmbeddingSdkModeOptions = {},+): QueryClickActionsMode => {+ const { pushNavigation } = options;++ const SDKDashboardClickAction: LegacyDrill = ({ question, clicked = {} }) => {+ const target = getClickBehaviorTarget(clicked);++ if (target && pushNavigation) {+ return [+ {+ name: "click_behavior",+ defaultAlways: true,+ onClick: () => {+ pushNavigation(target);+ },+ },+ ];+ }++ // Fall back to default behavior if no navigation handler+ return DashboardClickAction({ question, clicked });+ };++ return {+ name: "embedding-sdk",+ hasDrills: true,+ availableOnlyDrills: [+ "drill-thru/column-extract",+ "drill-thru/column-filter",+ "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",+ ],+ clickActions: [+ HideColumnAction,+ SDKDashboardClickAction,+ ExtractColumnAction,+ CombineColumnsAction,+ ],+ fallback: NativeQueryClickFallback,+ };+};++// Keep backwards compat export (without navigation)+export const EmbeddingSdkMode = createEmbeddingSdkMode();diff --git a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsxindex c5d910804bc..0eda4219664 100644--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx@@ -179,6 +179,8 @@ type VisualizationOwnProps = {) => void;onUpdateWarnings?: (warnings: string[]) => void;onVisualizationRendered?: (series: Series) => void;+ /** When true, internal click behaviors (dashboard/question links) are preserved */+ enableEntityNavigation?: boolean;} & VisualizationPassThroughProps;type VisualizationProps = StateDispatchProps &@@ -238,7 +240,9 @@ const deriveStateFromProps = (props: VisualizationProps) => {const series = transformed?.series ?? null;const computedSettings = !isLoading(series)- ? getComputedSettingsForSeries(series)+ ? getComputedSettingsForSeries(series, {+ enableEntityNavigation: props.enableEntityNavigation,+ }): {};return {@@ -304,7 +308,8 @@ class Visualization extends PureComponent<!equals(props.selectedTimelineEventIds,state._lastProps?.selectedTimelineEventIds,- )+ ) ||+ props.enableEntityNavigation !== state._lastProps?.enableEntityNavigation) {return {...deriveStateFromProps(props),@@ -321,6 +326,7 @@ class Visualization extends PureComponent<"settings","timelineEvents","selectedTimelineEventIds",+ "enableEntityNavigation",]),};}diff --git a/frontend/src/metabase/visualizations/lib/settings.js b/frontend/src/metabase/visualizations/lib/settings.jsindex 68415bdca30..b4d7d7beb17 100644--- a/frontend/src/metabase/visualizations/lib/settings.js+++ b/frontend/src/metabase/visualizations/lib/settings.js@@ -52,10 +52,17 @@ export function getComputedSettings(}if (isEmbeddingSdk()) {- return _.compose(- removeInternalClickBehaviors,+ const shouldKeepInternalClickBehavior = extra.enableEntityNavigation;++ const result = _.compose(+ // remove internal click behaviors unless internal navigation is enabled+ shouldKeepInternalClickBehavior+ ? _.identity+ : removeInternalClickBehaviors,convertLinkColumnToClickBehavior,)(computedSettings);++ return result;}return computedSettings;diff --git a/frontend/src/metabase/visualizations/lib/settings/nested.js b/frontend/src/metabase/visualizations/lib/settings/nested.jsindex 36f7f077f84..31c14f168c3 100644--- a/frontend/src/metabase/visualizations/lib/settings/nested.js+++ b/frontend/src/metabase/visualizations/lib/settings/nested.js@@ -92,7 +92,7 @@ export function nestedSettings(series,objects,settings[id],- { series, settings },+ { series, settings, ...extra },);return {series,@@ -108,7 +108,7 @@ export function nestedSettings(...def,},[objectName]: {- getDefault(series, settings) {+ getDefault(series, settings, extra) {const cache = new Map();return (object) => {const key = getObjectKey(object);@@ -124,7 +124,7 @@ export function nestedSettings(...inheritedSettings,...storedSettings,},- { series, settings },+ { series, settings, ...extra },),});}diff --git a/frontend/src/metabase/visualizations/lib/settings/visualization.js b/frontend/src/metabase/visualizations/lib/settings/visualization.jsindex a0a347564d0..c4794d66b65 100644--- a/frontend/src/metabase/visualizations/lib/settings/visualization.js+++ b/frontend/src/metabase/visualizations/lib/settings/visualization.js@@ -97,16 +97,18 @@ export function getStoredSettingsForSeries(series) {/*** @import { ComputedVisualizationSettings } from "metabase/visualizations/types";*+ * @param {any} series+ * @param {{ enableEntityNavigation?: boolean }} [extra]* @returns {ComputedVisualizationSettings}*/-export function getComputedSettingsForSeries(series) {+export function getComputedSettingsForSeries(series, extra = {}) {if (!series) {return {};}const settingsDefs = getSettingDefinitionsForSeries(series);const storedSettings = getStoredSettingsForSeries(series);- return getComputedSettings(settingsDefs, series, storedSettings);+ return getComputedSettings(settingsDefs, series, storedSettings, extra);}export function getPersistableDefaultSettingsForSeries(series) {diff --git a/frontend/src/metabase/visualizations/types/click-actions.ts b/frontend/src/metabase/visualizations/types/click-actions.tsindex 7cb33c89974..3d988d9b290 100644--- a/frontend/src/metabase/visualizations/types/click-actions.ts+++ b/frontend/src/metabase/visualizations/types/click-actions.ts@@ -130,10 +130,16 @@ export type DefaultClickAction = ClickActionBase & {default: true;} & AlwaysDefaultClickActionSubAction;+type OnClickActionBase = {+ onClick: (parameters: CustomClickActionContext) => void;+};+export type AlwaysDefaultClickActionSubAction =| QuestionChangeClickActionBase| ReduxClickActionBase- | UrlClickActionBase;+ | UrlClickActionBase+ | CustomClickActionBase+ | OnClickActionBase;export type AlwaysDefaultClickAction = {name: string;