Skip to content

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

fix(sdk-bundle): handle same-dashboard and cross-dashboard tab click behavior in SDK (#74083)

Mahatthana (Kelvin) Nomsawadi8477061b4797
diff --git a/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx
index 435d8968983..974365d8b2e 100644
--- a/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/internal-navigation.cy.spec.tsx
@@ -10,7 +10,10 @@ import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-tes
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";
+import {
+ createMockActionParameter,
+ createMockDashboardCard,
+} from "metabase-types/api/mocks";
const { H } = cy;
@@ -622,6 +625,586 @@ describe("scenarios > embedding-sdk > internal-navigation", () => {
});
});
+ describe("same-dashboard navigation (EMB-1714)", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ cy.intercept("GET", "/api/dashboard/*").as("getDashboard");
+ cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query").as(
+ "dashcardQuery",
+ );
+ });
+
+ it("should switch tab and pass parameters when click behavior points to a different tab on the same dashboard", () => {
+ const TAB_1 = { id: 1, name: "Tab 1" };
+ const TAB_2 = { id: 2, name: "Tab 2" };
+ const TAB_3 = { id: 3, name: "Tab 3" };
+
+ const ID_FILTER: Parameter = createMockActionParameter({
+ id: "tabbed-id-filter",
+ name: "ID Filter",
+ slug: "id-filter",
+ type: "number/=",
+ sectionId: "number",
+ isMultiSelect: false,
+ });
+
+ const B_TAB_1 = { id: 11, name: "B Tab 1" };
+ const B_TAB_2 = { id: 12, name: "B Tab 2" };
+
+ // External dashboard used to exercise the cross-dashboard push +
+ // back-restore path (`Go to Dashboard B` click behavior on Tab 3).
+ // It is itself tabbed and the Tab 3 click behavior targets its
+ // second tab, so navigating there overwrites the global
+ // initialDashboardTabId — going back must still restore the source
+ // dashboard's own Tab 3.
+ H.createQuestion({
+ name: "Orders on B Tab 1",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: bTabOneCard }) => {
+ H.createQuestion({
+ name: "Orders on B Tab 2",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: bTabTwoCard }) => {
+ H.createDashboardWithTabs({
+ name: "Dashboard B",
+ tabs: [B_TAB_1, B_TAB_2],
+ dashcards: [
+ createMockDashboardCard({
+ id: -11,
+ card_id: bTabOneCard.id,
+ dashboard_tab_id: B_TAB_1.id,
+ size_x: 12,
+ size_y: 6,
+ }),
+ createMockDashboardCard({
+ id: -12,
+ card_id: bTabTwoCard.id,
+ dashboard_tab_id: B_TAB_2.id,
+ size_x: 12,
+ size_y: 6,
+ }),
+ ],
+ }).then((externalDashboard) => {
+ cy.wrap(externalDashboard.id).as("externalDashboardId");
+ cy.wrap((externalDashboard.tabs ?? [])[1].id).as(
+ "externalDashboardTab2Id",
+ );
+ });
+ });
+ });
+
+ H.createQuestion({
+ name: "Orders on Tab 1",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: tabOneCard }) => {
+ H.createQuestion({
+ name: "Orders on Tab 2",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: tabTwoCard }) => {
+ H.createQuestion({
+ name: "Orders on Tab 3",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: tabThreeCard }) => {
+ H.createDashboardWithTabs({
+ name: "Tabbed Dashboard",
+ parameters: [ID_FILTER],
+ tabs: [TAB_1, TAB_2, TAB_3],
+ dashcards: [
+ createMockDashboardCard({
+ id: -1,
+ card_id: tabOneCard.id,
+ dashboard_tab_id: TAB_1.id,
+ size_x: 12,
+ size_y: 6,
+ }),
+ createMockDashboardCard({
+ id: -2,
+ card_id: tabTwoCard.id,
+ dashboard_tab_id: TAB_2.id,
+ size_x: 12,
+ size_y: 6,
+ parameter_mappings: [
+ {
+ parameter_id: ID_FILTER.id,
+ card_id: tabTwoCard.id,
+ target: ["dimension", ["field", ORDERS.ID, null]],
+ },
+ ],
+ }),
+ createMockDashboardCard({
+ id: -3,
+ card_id: tabThreeCard.id,
+ dashboard_tab_id: TAB_3.id,
+ size_x: 12,
+ size_y: 6,
+ parameter_mappings: [
+ {
+ parameter_id: ID_FILTER.id,
+ card_id: tabThreeCard.id,
+ target: ["dimension", ["field", ORDERS.ID, null]],
+ },
+ ],
+ }),
+ ],
+ }).then((dashboard) => {
+ // After creation, tabs and dashcards have real ids; wire the
+ // click behavior (with parameter mapping + tabId) using those.
+ const tabs = dashboard.tabs ?? [];
+ const resolvedTab1 = tabs[0];
+ const resolvedTab2 = tabs[1];
+ const resolvedTab3 = tabs[2];
+ cy.get<number>("@externalDashboardId").then(
+ (externalDashboardId) => {
+ cy.get<number>("@externalDashboardTab2Id").then(
+ (externalDashboardTab2Id) => {
+ const updatedDashcards = (dashboard.dashcards ?? []).map(
+ (dashcard) => {
+ if (dashcard.dashboard_tab_id === resolvedTab1.id) {
+ return {
+ ...dashcard,
+ visualization_settings: {
+ column_settings: {
+ [`["ref",["field",${ORDERS.ID},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ linkTextTemplate: "Go to Tab 2",
+ targetId: dashboard.id,
+ tabId: resolvedTab2.id,
+ parameterMapping: {
+ [ID_FILTER.id]: {
+ source: {
+ type: "column",
+ id: "ID",
+ name: "ID",
+ },
+ target: {
+ type: "parameter",
+ id: ID_FILTER.id,
+ },
+ id: ID_FILTER.id,
+ },
+ },
+ },
+ },
+ },
+ },
+ };
+ }
+ if (dashcard.dashboard_tab_id === resolvedTab3.id) {
+ return {
+ ...dashcard,
+ visualization_settings: {
+ column_settings: {
+ // ID column on Tab 3 links to Dashboard B's
+ // second tab (cross-dashboard push to a tabbed
+ // dashboard) — exercises the back-restore path
+ // where the destination's tab id must not
+ // clobber the source dashboard's remembered tab.
+ [`["ref",["field",${ORDERS.ID},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ linkTextTemplate: "Go to Dashboard B",
+ targetId: externalDashboardId,
+ tabId: externalDashboardTab2Id,
+ parameterMapping: {},
+ },
+ },
+ },
+ },
+ };
+ }
+ return dashcard;
+ },
+ );
+
+ cy.request("PUT", `/api/dashboard/${dashboard.id}`, {
+ ...dashboard,
+ dashcards: updatedDashcards,
+ });
+
+ cy.wrap(dashboard.entity_id).as(
+ "tabbedDashboardEntityId",
+ );
+ },
+ );
+ },
+ );
+ });
+ });
+ });
+ });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+
+ cy.get<string>("@tabbedDashboardEntityId").then((dashboardId) => {
+ mountSdkContent(
+ <InteractiveDashboard
+ dashboardId={dashboardId}
+ enableEntityNavigation
+ />,
+ );
+ });
+
+ cy.wait("@getDashboard");
+ cy.wait("@dashcardQuery");
+
+ getSdkRoot().within(() => {
+ cy.findByText("Tabbed Dashboard").should("be.visible");
+ cy.findByRole("tab", { name: "Tab 1" }).should(
+ "have.attr",
+ "aria-selected",
+ "true",
+ );
+
+ // Click the first ID cell on Tab 1 — it has click_behavior to Tab 2
+ // with a parameter mapping that should pass the cell's value to the
+ // dashboard's ID filter.
+ H.getDashboardCard().findAllByText("Go to Tab 2").first().click();
+
+ // Expected: Tab 2 becomes the active tab on the same dashboard.
+ // On master this fails: SDK pushes a new dashboard entry, re-mounts on
+ // Tab 1, and never honours the click behavior's tabId.
+ cy.findByRole("tab", { name: "Tab 2" }).should(
+ "have.attr",
+ "aria-selected",
+ "true",
+ );
+ cy.findByText("Orders on Tab 2").should("be.visible");
+
+ // The dashboard's ID filter widget should reflect the value passed by
+ // the click behavior's parameterMapping.
+ H.filterWidget({ name: "ID Filter" }).should("contain.text", "1");
+
+ // No back-button entry should be created for an in-place tab switch.
+ cy.findByText(/Back to/).should("not.exist");
+
+ // Manually switch to Tab 3 — diverges from both the default first
+ // tab and the click-behavior-pushed Tab 2, so a missing live-capture
+ // would fall back to Tab 1 and fail the test.
+ cy.findByRole("tab", { name: "Tab 3" }).click();
+ cy.findByRole("tab", { name: "Tab 3" }).should(
+ "have.attr",
+ "aria-selected",
+ "true",
+ );
+
+ // Manually change the ID filter to a value that differs from the one
+ // set by the click behavior. The live filter value should be captured
+ // into the stack entry on push so it survives the round trip.
+ H.filterWidget({ name: "ID Filter" }).click();
+ });
+ H.popover().within(() => {
+ cy.findByDisplayValue("1").type("{selectall}999");
+ cy.button("Update filter").click();
+ });
+ getSdkRoot().within(() => {
+ H.filterWidget({ name: "ID Filter" }).should("contain.text", "999");
+
+ // Navigate away to a different dashboard from Tab 3 (real
+ // cross-dashboard push, unmounts the source dashboard so
+ // selectedTabId state is lost without the fix).
+ H.getDashboardCard().findAllByText("Go to Dashboard B").first().click();
+ cy.wait("@getDashboard");
+ cy.findByText("Dashboard B").should("be.visible");
+
+ // Dashboard B is itself tabbed; the click behavior targets its
+ // second tab, so it should open directly on B Tab 2.
+ cy.findByRole("tab", { name: "B Tab 2" }).should(
+ "have.attr",
+ "aria-selected",
+ "true",
+ );
+ cy.findByText("Orders on B Tab 2").should("be.visible");
+ cy.findByText("Back to Tabbed Dashboard").should("be.visible");
+
+ // Click back — should restore the manually-selected Tab 3, and the
+ // manually-changed ID filter value (999, not the click-behavior 1)
+ // should still be set. Regression: navigating to a tabbed Dashboard B
+ // overwrites the global initialDashboardTabId with B's tab id, so the
+ // source dashboard re-mounts on its first tab instead of Tab 3.
+ cy.findByText("Back to Tabbed Dashboard").click();
+ cy.findByRole("tab", { name: "Tab 3" }).should(
+ "have.attr",
+ "aria-selected",
+ "true",
+ );
+ H.filterWidget({ name: "ID Filter" }).should("contain.text", "999");
+ });
+ });
+
+ it("should apply mapped parameters when click behavior points to the same tab-less dashboard", () => {
+ const ID_FILTER: Parameter = createMockActionParameter({
+ id: "self-link-id-filter",
+ name: "ID Filter",
+ slug: "id-filter",
+ type: "number/=",
+ sectionId: "number",
+ });
+
+ const QUANTITY_FILTER: Parameter = createMockActionParameter({
+ id: "self-link-quantity-filter",
+ name: "Quantity Filter",
+ slug: "quantity-filter",
+ type: "number/=",
+ sectionId: "number",
+ });
+
+ H.createQuestion({
+ name: "Self-linking card",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: card }) => {
+ H.createDashboard({
+ name: "Self-linking Dashboard",
+ parameters: [ID_FILTER, QUANTITY_FILTER],
+ }).then(({ body: dashboard }) => {
+ H.addOrUpdateDashboardCard({
+ card_id: card.id,
+ dashboard_id: dashboard.id,
+ card: createMockDashboardCard({
+ card_id: card.id,
+ size_x: 24,
+ size_y: 8,
+ parameter_mappings: [
+ {
+ parameter_id: ID_FILTER.id,
+ card_id: card.id,
+ target: ["dimension", ["field", ORDERS.ID, null]],
+ },
+ {
+ parameter_id: QUANTITY_FILTER.id,
+ card_id: card.id,
+ target: ["dimension", ["field", ORDERS.QUANTITY, null]],
+ },
+ ],
+ visualization_settings: {
+ column_settings: {
+ [`["ref",["field",${ORDERS.ID},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ linkTextTemplate: "Self link",
+ targetId: dashboard.id,
+ parameterMapping: {
+ [ID_FILTER.id]: {
+ source: { type: "column", id: "ID", name: "ID" },
+ target: {
+ type: "parameter",
+ id: ID_FILTER.id,
+ },
+ id: ID_FILTER.id,
+ },
+ },
+ },
+ },
+ },
+ },
+ }),
+ });
+ cy.wrap(dashboard.entity_id).as("selfDashboardEntityId");
+ });
+ });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+
+ cy.get<string>("@selfDashboardEntityId").then((dashboardId) => {
+ mountSdkContent(
+ <InteractiveDashboard
+ dashboardId={dashboardId}
+ enableEntityNavigation
+ initialParameters={{ [QUANTITY_FILTER.slug]: "7" }}
+ />,
+ );
+ });
+
+ cy.wait("@getDashboard");
+ cy.wait("@dashcardQuery");
+
+ getSdkRoot().within(() => {
+ cy.findByText("Self-linking Dashboard").should("be.visible");
+ cy.findByText("Self-linking card").should("be.visible");
+
+ // Pre-condition: Quantity filter is pre-set to 7 via initialParameters
+ // and should be preserved across the same-dashboard click behavior.
+ H.filterWidget({ name: "Quantity Filter" }).should("contain.text", "7");
+
+ // Click the self-linking link — same dashboard, same (no) tab, with
+ // a parameter mapping that should set the dashboard's ID filter.
+ H.getDashboardCard().findAllByText("Self link").first().click();
+
+ // Expected: ID filter reflects the mapped cell value AND the
+ // unrelated Quantity filter is retained (matches core app's
+ // per-parameter merge behavior, not a full-replace).
+ //
+ // The table is filtered to Quantity=7, so the first row's ID is 8
+ // (not 1). The click behavior passes that cell's ID to the ID filter.
+ H.filterWidget({ name: "ID Filter" }).should("contain.text", "8");
+ H.filterWidget({ name: "Quantity Filter" }).should("contain.text", "7");
+ cy.findByText(/Back to/).should("not.exist");
+ cy.findByText("Self-linking Dashboard").should("be.visible");
+ cy.findByText("Self-linking card").should("be.visible");
+ });
+ });
+ });
+
+ describe("cross-dashboard navigation with tabId", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ cy.intercept("GET", "/api/dashboard/*").as("getDashboard");
+ cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query").as(
+ "dashcardQuery",
+ );
+ });
+
+ it("should open the target dashboard on the requested tab", () => {
+ const TARGET_TAB_1 = { id: 1, name: "Target Tab 1" };
+ const TARGET_TAB_2 = { id: 2, name: "Target Tab 2" };
+
+ const TARGET_ID_FILTER: Parameter = createMockActionParameter({
+ id: "target-id-filter",
+ name: "ID Filter",
+ slug: "id-filter",
+ type: "number/=",
+ sectionId: "number",
+ });
+
+ H.createQuestion({
+ name: "Card on Target Tab 1",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: targetTab1Card }) => {
+ H.createQuestion({
+ name: "Card on Target Tab 2",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: targetTab2Card }) => {
+ H.createDashboardWithTabs({
+ name: "Target Dashboard",
+ parameters: [TARGET_ID_FILTER],
+ tabs: [TARGET_TAB_1, TARGET_TAB_2],
+ dashcards: [
+ createMockDashboardCard({
+ id: -1,
+ card_id: targetTab1Card.id,
+ dashboard_tab_id: TARGET_TAB_1.id,
+ size_x: 12,
+ size_y: 6,
+ }),
+ createMockDashboardCard({
+ id: -2,
+ card_id: targetTab2Card.id,
+ dashboard_tab_id: TARGET_TAB_2.id,
+ size_x: 12,
+ size_y: 6,
+ parameter_mappings: [
+ {
+ parameter_id: TARGET_ID_FILTER.id,
+ card_id: targetTab2Card.id,
+ target: ["dimension", ["field", ORDERS.ID, null]],
+ },
+ ],
+ }),
+ ],
+ }).then((targetDashboard) => {
+ const resolvedTargetTab2 = (targetDashboard.tabs ?? [])[1];
+
+ H.createQuestion({
+ name: "Source Card",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: sourceCard }) => {
+ H.createDashboard({ name: "Source Dashboard" }).then(
+ ({ body: sourceDashboard }) => {
+ H.addOrUpdateDashboardCard({
+ card_id: sourceCard.id,
+ dashboard_id: sourceDashboard.id,
+ card: createMockDashboardCard({
+ card_id: sourceCard.id,
+ size_x: 24,
+ size_y: 8,
+ visualization_settings: {
+ column_settings: {
+ [`["ref",["field",${ORDERS.ID},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ linkTextTemplate: "Go to Target Tab 2",
+ targetId: targetDashboard.id,
+ tabId: resolvedTargetTab2.id,
+ parameterMapping: {
+ [TARGET_ID_FILTER.id]: {
+ source: {
+ type: "column",
+ id: "ID",
+ name: "ID",
+ },
+ target: {
+ type: "parameter",
+ id: TARGET_ID_FILTER.id,
+ },
+ id: TARGET_ID_FILTER.id,
+ },
+ },
+ },
+ },
+ },
+ },
+ }),
+ });
+ cy.wrap(sourceDashboard.entity_id).as(
+ "sourceDashboardEntityId",
+ );
+ },
+ );
+ });
+ });
+ });
+ });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+
+ cy.get<string>("@sourceDashboardEntityId").then((dashboardId) => {
+ mountSdkContent(
+ <InteractiveDashboard
+ dashboardId={dashboardId}
+ enableEntityNavigation
+ />,
+ );
+ });
+
+ cy.wait("@getDashboard");
+ cy.wait("@dashcardQuery");
+
+ getSdkRoot().within(() => {
+ cy.findByText("Source Dashboard").should("be.visible");
+
+ H.getDashboardCard()
+ .findAllByText("Go to Target Tab 2")
+ .first()
+ .click();
+
+ cy.wait("@getDashboard");
+
+ cy.findByText("Target Dashboard").should("be.visible");
+ cy.findByRole("tab", { name: "Target Tab 2" }).should(
+ "have.attr",
+ "aria-selected",
+ "true",
+ );
+ cy.findByText("Card on Target Tab 2").should("be.visible");
+
+ // Target dashboard's ID filter should reflect the value passed by
+ // the click behavior's parameterMapping.
+ H.filterWidget({ name: "ID Filter" }).should("contain.text", "1");
+
+ cy.findByText("Back to Source Dashboard").should("be.visible");
+ });
+ });
+ });
+
describe("question", () => {
beforeEach(() => {
signInAsAdminAndEnableEmbeddingSdk();
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
index 9f2bac41296..03ccfd69f6b 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
@@ -9,7 +9,16 @@ import {
import { match } from "ts-pattern";
import { SdkDashboardStyledWrapper } from "embedding-sdk-bundle/components/public/dashboard/SdkDashboardStyleWrapper";
+import { useSdkDispatch } from "embedding-sdk-bundle/store";
+import { setInitialDashboardTabId } from "embedding-sdk-bundle/store/reducer";
import type { SdkDashboardId } from "embedding-sdk-bundle/types/dashboard";
+import { setParameterValue } from "metabase/dashboard/actions";
+import {
+ getDashboardComplete,
+ getSelectedTabId,
+} from "metabase/dashboard/selectors";
+import { useSelector } from "metabase/redux";
+import { selectTab } from "metabase/redux/dashboard";
import { Stack } from "metabase/ui";
import { SdkQuestion } from "../../public/SdkQuestion";
@@ -49,10 +58,54 @@ const SdkInternalNavigationProviderInner = ({
keepChildrenMounted = false,
}: Props) => {
const [stack, setStack] = useState<SdkInternalNavigationEntry[]>([]);
-
- const push = useCallback((entry: SdkInternalNavigationEntry) => {
- setStack((prev) => [...prev, entry]);
- }, []);
+ const dispatch = useSdkDispatch();
+ const currentDashboard = useSelector(getDashboardComplete);
+ const selectedTabId = useSelector(getSelectedTabId);
+
+ const push = useCallback(
+ (entry: SdkInternalNavigationEntry) => {
+ // Click behaviors that target the currently loaded dashboard should
+ // switch tab / apply parameters in place rather than push a new stack
+ // entry (which would re-mount the dashboard from scratch and lose the
+ // requested tab).
+ if (
+ entry.type === "dashboard" &&
+ currentDashboard != null &&
+ entry.id === currentDashboard.id
+ ) {
+ if (entry.tabId != null) {
+ dispatch(selectTab({ tabId: entry.tabId }));
+ }
+ if (entry.parameterIdValuePairs) {
+ // Merge per-parameter (matches core app DashboardClickAction) so
+ // unrelated filters keep their current values.
+ for (const [id, value] of entry.parameterIdValuePairs) {
+ dispatch(setParameterValue(id, value));
+ }
+ }
+ return;
+ }
+ // Handle cross dashboard navigation with initial tab.
+ if (entry.type === "dashboard") {
+ dispatch(setInitialDashboardTabId(entry.tabId ?? null));
+ }
+ setStack((prev) => {
+ const top = prev.at(-1);
+ // Capture the live selected tab onto the outgoing dashboard entry so
+ // that popping back restores the tab the user was actually viewing
+ // (which may differ from the tab the entry was opened on).
+ const updated =
+ top?.type === "dashboard"
+ ? [
+ ...prev.slice(0, -1),
+ { ...top, tabId: selectedTabId ?? top.tabId },
+ ]
+ : prev;
+ return [...updated, entry];
+ });
+ },
+ [dispatch, currentDashboard, selectedTabId],
+ );
const pop = useCallback(() => {
setStack((prev) => {
@@ -61,9 +114,16 @@ const SdkInternalNavigationProviderInner = ({
if (poppedEntry && "onPop" in poppedEntry && poppedEntry.onPop) {
poppedEntry.onPop();
}
- return prev.slice(0, -1);
+ const next = prev.slice(0, -1);
+ const newTop = next.at(-1);
+ if (newTop?.type === "dashboard") {
+ // Seed the initial tab so the re-mounted dashboard lands on the tab
+ // the user was last viewing instead of defaulting to the first tab.
+ dispatch(setInitialDashboardTabId(newTop.tabId ?? null));
+ }
+ return next;
});
- }, []);
+ }, [dispatch]);
// Initialize the stack with a dashboard entry (called by dashboard components when the dashboard loads and we have the name)
const initWithDashboard = useCallback(
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
index 685118377a9..0597e780574 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
@@ -3,6 +3,7 @@ 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";
+import type { DashboardTabId, ParameterValueOrArray } from "metabase-types/api";
// This type exists only to have a global place where to put the JSDoc for virtual
type BaseEntry = {
@@ -19,6 +20,9 @@ export type SdkInternalNavigationEntry =
name: string;
virtual?: true;
parameters?: ParameterValues;
+ /** Id-keyed parameter values used for same-dashboard merge dispatch. */
+ parameterIdValuePairs?: [string, ParameterValueOrArray | null][];
+ tabId?: DashboardTabId;
onPop?: () => void;
})
| (BaseEntry & {
diff --git a/frontend/src/embedding-sdk-bundle/store/reducer.ts b/frontend/src/embedding-sdk-bundle/store/reducer.ts
index c8025defc0f..859b361b0d8 100644
--- a/frontend/src/embedding-sdk-bundle/store/reducer.ts
+++ b/frontend/src/embedding-sdk-bundle/store/reducer.ts
@@ -9,6 +9,7 @@ import type {
} from "embedding-sdk-bundle/types/ui";
import type { SdkUsageProblem } from "embedding-sdk-bundle/types/usage-problem";
import type { MetabaseFetchRequestTokenFn } from "metabase/embedding-sdk/types/refresh-token";
+import type { DashboardTabId } from "metabase-types/api";
import { initAuth, refreshTokenAsync } from "./auth";
import {
@@ -56,6 +57,11 @@ export const setUsageProblem = createAction<SdkUsageProblem | null>(
const SET_PLUGINS_READY = "sdk/SET_PLUGINS_READY";
export const setPluginsReady = createAction<boolean>(SET_PLUGINS_READY);
+const SET_INITIAL_DASHBOARD_TAB_ID = "sdk/SET_INITIAL_DASHBOARD_TAB_ID";
+export const setInitialDashboardTabId = createAction<DashboardTabId | null>(
+ SET_INITIAL_DASHBOARD_TAB_ID,
+);
+
const initialState: SdkState = {
isGuestEmbed: null,
metabaseInstanceUrl: "",
@@ -74,6 +80,7 @@ const initialState: SdkState = {
errorComponent: null,
fetchRefreshTokenFn: null,
pluginsReady: false,
+ initialDashboardTabId: null,
};
export const sdk = createReducer(initialState, (builder) => {
@@ -202,4 +209,8 @@ export const sdk = createReducer(initialState, (builder) => {
builder.addCase(setPluginsReady, (state, action) => {
state.pluginsReady = action.payload;
});
+
+ builder.addCase(setInitialDashboardTabId, (state, action) => {
+ state.initialDashboardTabId = action.payload;
+ });
});
diff --git a/frontend/src/embedding-sdk-bundle/store/types.ts b/frontend/src/embedding-sdk-bundle/store/types.ts
index a2475d95d86..c9629dbc5e6 100644
--- a/frontend/src/embedding-sdk-bundle/store/types.ts
+++ b/frontend/src/embedding-sdk-bundle/store/types.ts
@@ -17,6 +17,7 @@ import type {
import type { SdkUsageProblem } from "embedding-sdk-bundle/types/usage-problem";
import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";
import type { State } from "metabase/redux/store";
+import type { DashboardTabId } from "metabase-types/api";
export type EmbeddingSessionTokenState = {
token: MetabaseEmbeddingSessionToken | null;
@@ -44,6 +45,14 @@ export type SdkState = {
errorComponent: null | SdkErrorComponent;
fetchRefreshTokenFn: null | MetabaseAuthConfig["fetchRequestToken"];
pluginsReady: boolean;
+ /**
+ * Tab to apply when the next dashboard mounts via a cross-dashboard
+ * click behavior. Not cleared after use: tab IDs are globally unique
+ * PKs, so stale values can't match another dashboard's tabs, and the
+ * selector falls back to the first tab via a `hasTab` guard. Every
+ * cross-dashboard push overwrites this slot anyway.
+ */
+ initialDashboardTabId: DashboardTabId | null;
};
export interface SdkStoreState extends State {
diff --git a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts b/frontend/src/embedding-sdk-bundle/test/mocks/state.ts
index 1b5cc8123e3..b456566dd08 100644
--- a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts
+++ b/frontend/src/embedding-sdk-bundle/test/mocks/state.ts
@@ -39,6 +39,7 @@ export const createMockSdkState = ({
error: null,
fetchRefreshTokenFn: null,
pluginsReady: true,
+ initialDashboardTabId: null,
...opts,
};
};
diff --git a/frontend/src/metabase-types/api/click-behavior.ts b/frontend/src/metabase-types/api/click-behavior.ts
index 1721d62f857..89cd2e2fd0d 100644
--- a/frontend/src/metabase-types/api/click-behavior.ts
+++ b/frontend/src/metabase-types/api/click-behavior.ts
@@ -79,6 +79,7 @@ export interface DashboardCustomDestinationClickBehavior {
*/
tabId?: DashboardTabId;
parameterMapping?: ClickBehaviorParameterMapping;
+ linkTextTemplate?: string;
}
export interface QuestionCustomDestinationClickBehavior {
@@ -86,6 +87,7 @@ export interface QuestionCustomDestinationClickBehavior {
linkType: "question";
targetId?: CardId;
parameterMapping?: ClickBehaviorParameterMapping;
+ linkTextTemplate?: string;
}
export interface ArbitraryCustomDestinationClickBehavior {
diff --git a/frontend/src/metabase/dashboard/selectors.ts b/frontend/src/metabase/dashboard/selectors.ts
index 63f5616d91b..5b201b9fcc9 100644
--- a/frontend/src/metabase/dashboard/selectors.ts
+++ b/frontend/src/metabase/dashboard/selectors.ts
@@ -2,6 +2,7 @@ import { createSelector } from "@reduxjs/toolkit";
import { createCachedSelector } from "re-reselect";
import _ from "underscore";
+import type { SdkStoreState } from "embedding-sdk-bundle/store/types";
import { LOAD_COMPLETE_FAVICON } from "metabase/common/hooks/constants";
import {
DASHBOARD_SLOW_TIMEOUT,
@@ -45,6 +46,7 @@ import type {
DashboardCard,
DashboardId,
DashboardParameterMapping,
+ DashboardTabId,
ParameterId,
VirtualCard,
} from "metabase-types/api";
@@ -571,13 +573,19 @@ export const getSelectedTabId = createSelector(
(state) => getSetting(state, "site-url"),
getDashboard,
(state) => state.dashboard.selectedTabId,
+ (state: State) =>
+ (state as Partial<SdkStoreState>).sdk?.initialDashboardTabId,
],
- (isWebApp, siteUrl, dashboard, selectedTabId) => {
+ (isWebApp, siteUrl, dashboard, selectedTabId, sdkInitialDashboardTabId) => {
if (dashboard && selectedTabId === null) {
- return getInitialSelectedTabId(dashboard, siteUrl, isWebApp);
+ if (isEmbeddingSdk()) {
+ return getSdkInitialDashboardTabId(dashboard, sdkInitialDashboardTabId);
+ } else {
+ return getInitialSelectedTabId(dashboard, siteUrl, isWebApp);
+ }
+ } else {
+ return selectedTabId;
}
-
- return selectedTabId;
},
);
@@ -591,7 +599,7 @@ export const getSelectedTab = createSelector(
},
);
-export function getInitialSelectedTabId(
+function getInitialSelectedTabId(
dashboard: Dashboard | StoreDashboard,
siteUrl: string,
isWebApp: boolean,
@@ -617,6 +625,19 @@ export function getInitialSelectedTabId(
return dashboard.tabs?.[0]?.id || null;
}
+function getSdkInitialDashboardTabId(
+ dashboard: Dashboard | StoreDashboard,
+ sdkInitialDashboardTabId: DashboardTabId | null | undefined,
+) {
+ const hasTab = dashboard.tabs?.some(
+ (tab) => tab.id === sdkInitialDashboardTabId,
+ );
+ if (hasTab) {
+ return sdkInitialDashboardTabId ?? null;
+ }
+ return dashboard.tabs?.[0]?.id ?? null;
+}
+
export const getCurrentTabDashcards = createSelector(
[getDashboardComplete, getSelectedTabId],
(dashboard, selectedTabId) => {
diff --git a/frontend/src/metabase/visualizations/click-actions/lib/dashboard-click-drill.js b/frontend/src/metabase/visualizations/click-actions/lib/dashboard-click-drill.js
index aa2ed1e5785..e0e0110daf9 100644
--- a/frontend/src/metabase/visualizations/click-actions/lib/dashboard-click-drill.js
+++ b/frontend/src/metabase/visualizations/click-actions/lib/dashboard-click-drill.js
@@ -181,7 +181,7 @@ export function getClickBehaviorData(clicked, clickBehavior) {
return { type, linkType, data, extraData, parameterMapping, tabId, targetId };
}
-function getParameterIdValuePairs(
+export function getParameterIdValuePairs(
parameterMapping,
{ data, extraData, clickBehavior },
) {
diff --git a/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts b/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts
index 32c77eb71e8..9958bb9f804 100644
--- a/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts
+++ b/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkMode.ts
@@ -1,4 +1,5 @@
import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
+import type { DashboardTabId, ParameterValueOrArray } from "metabase-types/api";
import type {
ClickObject,
@@ -13,6 +14,7 @@ import { NativeQueryClickFallback } from "../actions/NativeQueryClickFallback";
import {
getClickBehavior,
getClickBehaviorData,
+ getParameterIdValuePairs,
getParameterValuesBySlug,
} from "../lib/dashboard-click-drill";
@@ -21,6 +23,13 @@ export type ClickBehaviorTarget = {
id: number;
name: string;
parameters: ParameterValues;
+ /**
+ * Same parameter values as {@link parameters}, but keyed by parameter id.
+ * Used for same-dashboard click behaviors that need to dispatch per-id
+ * setParameterValue actions (mirrors core app DashboardClickAction).
+ */
+ parameterIdValuePairs: [string, ParameterValueOrArray | null][];
+ tabId?: DashboardTabId;
};
const getClickBehaviorTarget = (
@@ -31,7 +40,7 @@ const getClickBehaviorTarget = (
return null;
}
- const { linkType, targetId, extraData, parameterMapping, data } =
+ const { linkType, targetId, extraData, parameterMapping, data, tabId } =
getClickBehaviorData(clicked, clickBehavior);
if (linkType !== "dashboard" && linkType !== "question") {
@@ -46,6 +55,16 @@ const getClickBehaviorTarget = (
})
: {};
+ const parameterIdValuePairs = (
+ parameterMapping
+ ? getParameterIdValuePairs(parameterMapping, {
+ data,
+ extraData,
+ clickBehavior,
+ })
+ : []
+ ) as [string, ParameterValueOrArray | null][];
+
const entitiesMap =
linkType === "dashboard" ? extraData?.dashboards : extraData?.questions;
const target = entitiesMap?.[targetId];
@@ -57,7 +76,14 @@ const getClickBehaviorTarget = (
return null;
}
- return { type: linkType, id: target.id, name: target.name, parameters };
+ return {
+ type: linkType,
+ id: target.id,
+ name: target.name,
+ parameters,
+ parameterIdValuePairs,
+ tabId,
+ };
};
type CreateEmbeddingSdkModeOptions = {