Skip to content

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

add `navigatedEntityParameters` and `onNavigatedEntityParametersChange` to the react sdk and EAJS (#84504)

Nicolò Prettofecab094b7d4
diff --git a/e2e/test-component/scenarios/embedding-sdk/navigated-entity-parameters.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/navigated-entity-parameters.cy.spec.tsx
new file mode 100644
index 00000000000..38c7fdf279c
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/navigated-entity-parameters.cy.spec.tsx
@@ -0,0 +1,323 @@
+import {
+ InteractiveDashboard,
+ type NavigatedEntityParameters,
+ type ParameterValues,
+} from "@metabase/embedding-sdk-react";
+import { useState } from "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, TemplateTags } from "metabase-types/api";
+import {
+ createMockActionParameter,
+ createMockParameter,
+} from "metabase-types/api/mocks";
+
+const { H } = cy;
+
+const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;
+
+// On the TARGET dashboard. The click behavior maps the clicked row's ID onto this one.
+const TARGET_ID_FILTER: Parameter = createMockActionParameter({
+ id: "target-id-filter",
+ name: "ID Filter",
+ slug: "id-filter",
+ type: "number/=",
+ sectionId: "number",
+});
+
+// Also on the TARGET dashboard, but the click behavior does NOT map it.
+// The host controls it through `navigatedEntityParameters`.
+const TARGET_QUANTITY_FILTER: Parameter = createMockActionParameter({
+ id: "target-quantity-filter",
+ name: "Quantity Filter",
+ slug: "quantity-filter",
+ type: "number/=",
+ sectionId: "number",
+});
+
+// On the ORIGIN dashboard, so the root has a filter of its own. No test sets it.
+const ORIGIN_FILTER: Parameter = createMockActionParameter({
+ id: "origin-city-filter",
+ name: "City Filter",
+ slug: "city-filter",
+ type: "string/=",
+ sectionId: "string",
+});
+
+const HOST_QUANTITY_VALUE = 2;
+
+type HostProps = {
+ dashboardId: number;
+ valuesToWrite: ParameterValues;
+};
+
+// Like a host with its own filter panel: it learns the `navigationId` from
+// `initial-state` and writes its values for that visit.
+const HostWritingOnInitialState = ({
+ dashboardId,
+ valuesToWrite,
+}: HostProps) => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+
+ return (
+ <InteractiveDashboard
+ dashboardId={dashboardId}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ if (payload.source === "initial-state") {
+ setNavigatedEntityParameters((prev) => {
+ // If the map already has this navigationId, this is a back navigation
+ // and we don't want to change the parameters
+ if (prev[payload.navigationId]) {
+ return prev;
+ }
+ return { ...prev, [payload.navigationId]: valuesToWrite };
+ });
+ }
+ }}
+ />
+ );
+};
+
+describe("scenarios > embedding-sdk > navigated entity parameters", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ H.createDashboard({
+ name: "Target Dashboard",
+ parameters: [TARGET_ID_FILTER, TARGET_QUANTITY_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_ID_FILTER.id,
+ card_id: targetQuestion.id,
+ target: ["dimension", ["field", ORDERS.ID, null]],
+ },
+ {
+ parameter_id: TARGET_QUANTITY_FILTER.id,
+ card_id: targetQuestion.id,
+ target: ["dimension", ["field", ORDERS.QUANTITY, null]],
+ },
+ ],
+ },
+ });
+ });
+ });
+
+ cy.get<number>("@targetDashboardId").then((targetDashboardId) => {
+ H.createDashboard({
+ name: "Origin Dashboard",
+ parameters: [ORIGIN_FILTER],
+ }).then(({ body: originDashboard }) => {
+ cy.wrap(originDashboard.id).as("originDashboardId");
+
+ H.createQuestion({
+ name: "Orders for Origin Dashboard",
+ query: { "source-table": ORDERS_ID, limit: 5 },
+ }).then(({ body: originQuestion }) => {
+ H.addOrUpdateDashboardCard({
+ card_id: originQuestion.id,
+ dashboard_id: originDashboard.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: "dashboard",
+ linkTextTemplate: "Go to Target Dashboard",
+ targetId: targetDashboardId,
+ // Only `id-filter` is mapped. `quantity-filter` is left
+ // to the host.
+ 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.signOut();
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ it("replaces the click-behavior values with the host entry for the visit, like root `parameters`", () => {
+ cy.get<number>("@originDashboardId").then((originDashboardId) => {
+ mountSdkContent(
+ <HostWritingOnInitialState
+ dashboardId={originDashboardId}
+ valuesToWrite={{ "quantity-filter": HOST_QUANTITY_VALUE }}
+ />,
+ );
+ });
+
+ getSdkRoot().within(() => {
+ cy.findByText("Origin Dashboard").should("be.visible");
+
+ H.getDashboardCard()
+ .findAllByText("Go to Target Dashboard")
+ .should("have.length", 5)
+ .first()
+ .click();
+
+ cy.findByText("Target Dashboard").should("be.visible");
+
+ cy.log("The host value lands on the slug it named");
+ H.filterWidget({ name: "Quantity Filter" }).should(
+ "contain.text",
+ String(HOST_QUANTITY_VALUE),
+ );
+
+ cy.log("The slug the host omitted falls back to its default, empty");
+ H.filterWidget({ name: "ID Filter" })
+ .should("be.visible")
+ .icon("close")
+ .should("not.exist");
+ });
+ });
+});
+
+const SQL_TARGET_TEMPLATE_TAGS: TemplateTags = {
+ category: {
+ id: "category",
+ name: "category",
+ "display-name": "Category",
+ type: "dimension",
+ "widget-type": "string/=",
+ dimension: ["field", PRODUCTS.CATEGORY, null],
+ },
+};
+
+describe("scenarios > embedding-sdk > navigated entity parameters > SQL question targets", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ H.createNativeQuestion({
+ name: "SQL Target Question",
+ native: {
+ query: "SELECT * FROM PRODUCTS WHERE {{category}}",
+ "template-tags": SQL_TARGET_TEMPLATE_TAGS,
+ },
+ parameters: [
+ createMockParameter({
+ id: "category",
+ name: "Category",
+ slug: "category",
+ type: "string/=",
+ target: ["dimension", ["template-tag", "category"]],
+ }),
+ ],
+ }).then(({ body: sqlQuestion }) => {
+ H.createDashboard({ name: "SQL Origin Dashboard" }).then(
+ ({ body: originDashboard }) => {
+ cy.wrap(originDashboard.id).as("originDashboardId");
+
+ H.createQuestion({
+ name: "Products for SQL Origin Dashboard",
+ query: { "source-table": PRODUCTS_ID, limit: 5 },
+ }).then(({ body: originQuestion }) => {
+ H.addOrUpdateDashboardCard({
+ card_id: originQuestion.id,
+ dashboard_id: originDashboard.id,
+ card: {
+ row: 0,
+ col: 0,
+ size_x: 24,
+ size_y: 8,
+ visualization_settings: {
+ column_settings: {
+ [`["ref",["field",${PRODUCTS.CATEGORY},null]]`]: {
+ click_behavior: {
+ type: "link",
+ linkType: "question",
+ linkTextTemplate: "Go to SQL target",
+ targetId: sqlQuestion.id,
+ parameterMapping: {
+ category: {
+ id: "category",
+ source: {
+ type: "column",
+ id: "CATEGORY",
+ name: "Category",
+ },
+ target: { type: "variable", id: "category" },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+ });
+ },
+ );
+ });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ it("controls the SQL target with the host entry for the visit instead of the click-behavior value", () => {
+ cy.get<number>("@originDashboardId").then((originDashboardId) => {
+ mountSdkContent(
+ <HostWritingOnInitialState
+ dashboardId={originDashboardId}
+ valuesToWrite={{ category: "Widget" }}
+ />,
+ );
+ });
+
+ getSdkRoot().within(() => {
+ H.getDashboardCard()
+ .findAllByText("Go to SQL target")
+ .should("have.length", 5)
+ .first()
+ .click();
+ cy.findByText("SQL Target Question").should("be.visible");
+ });
+
+ cy.log("The host value replaces the clicked Gizmo");
+ H.tableInteractiveBody().findAllByText("Widget").should("not.be.empty");
+ H.ensureParameterColumnValue({
+ columnName: "CATEGORY",
+ columnValue: "Widget",
+ });
+ });
+});
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.ts
index d9be12e0350..71ca7fee039 100644
--- 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.ts
@@ -1,6 +1,11 @@
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 {
+ NavigatedEntityParameterChangePayload,
+ NavigationId,
+} from "embedding-sdk-bundle/types/navigation";
+import type { MetabaseDashboardElement } from "metabase/embedding/embedding-iframe-sdk/embed";
import type { Parameter } from "metabase-types/api";
import { createMockActionParameter } from "metabase-types/api/mocks";
@@ -50,6 +55,7 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", (
parameters: [TARGET_DASHBOARD_FILTER],
}).then(({ body: targetDashboard }) => {
cy.wrap(targetDashboard.id).as("targetDashboardId");
+ cy.wrap(targetDashboard.entity_id).as("targetDashboardEntityId");
H.createQuestion({
name: "Orders for Target Dashboard",
@@ -214,6 +220,103 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", (
.should("be.visible");
});
+ it("should report and control the parameters of a navigated dashboard through the custom element", () => {
+ const onNavigatedEntityParametersChange = cy
+ .stub()
+ .as("onNavigatedEntityParametersChange");
+
+ cy.get<number>("@startingDashboardId").then((startingDashboardId) => {
+ H.visitCustomHtmlPage(`
+ ${H.getNewEmbedScriptTag()}
+ ${H.getNewEmbedConfigurationScript({})}
+ <metabase-dashboard dashboard-id="${startingDashboardId}" drills enable-entity-navigation />
+ `);
+ });
+
+ cy.window().then((win) => {
+ cy.get("metabase-dashboard").then(([dashboardElement]) => {
+ dashboardElement.addEventListener(
+ "navigated-entity-parameters-change",
+ (event) => {
+ if (event instanceof win.CustomEvent) {
+ const payload: unknown = event.detail;
+ onNavigatedEntityParametersChange(payload);
+ }
+ },
+ );
+ });
+ });
+
+ cy.wait("@getDashCardQuery");
+
+ cy.log("click on the dashboard link");
+ H.getSimpleEmbedIframeContent()
+ .findAllByText("Go to Target Dashboard")
+ .should("have.length", 5)
+ .first()
+ .click();
+
+ H.getSimpleEmbedIframeContent()
+ .findByText("Target Dashboard")
+ .should("be.visible");
+
+ cy.log("the navigation reports the initial state of the target");
+ cy.get<string>("@targetDashboardEntityId").then(
+ (targetDashboardEntityId) => {
+ cy.get("@onNavigatedEntityParametersChange").should(
+ "have.been.calledWithMatch",
+ {
+ source: "initial-state",
+ entityType: "dashboard",
+ entityId: targetDashboardEntityId,
+ navigationId: Cypress.sinon.match.string,
+ clickParameters: { [TARGET_DASHBOARD_FILTER.slug]: [1] },
+ },
+ );
+ },
+ );
+
+ cy.get<sinon.SinonStub<[NavigatedEntityParameterChangePayload]>>(
+ "@onNavigatedEntityParametersChange",
+ )
+ .then((stub) => stub.firstCall.args[0].navigationId)
+ .as("navigationId");
+
+ cy.log("the host sets the filter of this visit via the element property");
+ cy.get<NavigationId>("@navigationId").then((navigationId) => {
+ cy.get<MetabaseDashboardElement>("metabase-dashboard").then(
+ ([dashboardElement]) => {
+ dashboardElement.navigatedEntityParameters = {
+ [navigationId]: { [TARGET_DASHBOARD_FILTER.slug]: [2] },
+ };
+ },
+ );
+ });
+
+ H.getSimpleEmbedIframeContent()
+ .findByTestId("dashboard-parameters-widget-container")
+ .findByLabelText("ID Filter")
+ .should("contain", "2")
+ .and("not.contain", "1");
+
+ cy.log("the user clears the filter in the iframe");
+ H.getSimpleEmbedIframeContent().within(() => {
+ H.filterWidget({ name: "ID Filter" }).icon("close").click();
+ });
+
+ cy.get<NavigationId>("@navigationId").then((navigationId) => {
+ cy.get("@onNavigatedEntityParametersChange").should(
+ "have.been.calledWithMatch",
+ {
+ source: "manual-change",
+ entityType: "dashboard",
+ navigationId,
+ parameters: { [TARGET_DASHBOARD_FILTER.slug]: null },
+ },
+ );
+ });
+ });
+
it("should not navigate when drills are disabled", () => {
cy.get<number>("@startingDashboardId").then((startingDashboardId) => {
H.visitCustomHtmlPage(`
diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.ts
index 5dc30ed0e56..bf678db4ce9 100644
--- a/enterprise/frontend/src/embedding-sdk-package/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts
@@ -155,6 +155,9 @@ export type {
MetabotIncompleteResponse,
MetabotMessage,
MetabotUserTextMessage,
+ NavigatedEntityParameterChangePayload,
+ NavigatedEntityParameters,
+ NavigationId,
ParameterChangeSource,
ParameterChangePayload,
UseMetabotResult,
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 dba2aa35d29..fd16179bcd4 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx
@@ -9,17 +9,20 @@ import {
import { match } from "ts-pattern";
import { SdkDashboardStyledWrapper } from "embedding-sdk-bundle/components/public/dashboard/SdkDashboardStyleWrapper";
-import { useSdkDispatch } from "embedding-sdk-bundle/store";
+import { buildClickParameters } from "embedding-sdk-bundle/lib/controlled-parameters";
+import { useSdkDispatch, useSdkStore } 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,
+ getParameters,
getSelectedTabId,
} from "metabase/dashboard/selectors";
import { useSelector } from "metabase/redux";
import { selectTab } from "metabase/redux/dashboard";
import { Stack } from "metabase/ui";
+import { uuid } from "metabase/utils/uuid";
import { SdkQuestion } from "../../public/SdkQuestion";
import type {
@@ -34,6 +37,7 @@ import { SdkInternalNavigationBackButton } from "./SdkInternalNavigationBackButt
import {
SdkInternalNavigationContext,
type SdkInternalNavigationEntry,
+ type SdkInternalNavigationStackEntry,
} from "./context";
// Strips props that are only meant for the root dashboard before forwarding to a drill-through target.
@@ -41,10 +45,17 @@ function getDrillThroughDashboardProps({
parameters: _parameters,
onParametersChange: _onParametersChange,
initialParameters: _initialParameters,
+ navigatedEntityParameters: _navigatedEntityParameters,
+ onNavigatedEntityParametersChange: _onNavigatedEntityParametersChange,
...props
}: Partial<SdkDashboardInnerProps> = {}): Omit<
SdkDashboardInnerProps,
- "dashboardId" | "parameters" | "onParametersChange" | "initialParameters"
+ | "dashboardId"
+ | "parameters"
+ | "onParametersChange"
+ | "initialParameters"
+ | "navigatedEntityParameters"
+ | "onNavigatedEntityParametersChange"
> {
return props;
}
@@ -71,7 +82,7 @@ const SdkInternalNavigationProviderInner = ({
drillThroughQuestionProps,
keepChildrenMounted = false,
}: Props) => {
- const [stack, setStack] = useState<SdkInternalNavigationEntry[]>([]);
+ const [stack, setStack] = useState<SdkInternalNavigationStackEntry[]>([]);
const dispatch = useSdkDispatch();
const currentDashboard = useSelector(getDashboardComplete);
const selectedTabId = useSelector(getSelectedTabId);
@@ -103,6 +114,7 @@ const SdkInternalNavigationProviderInner = ({
if (entry.type === "dashboard") {
dispatch(setInitialDashboardTabId(entry.tabId ?? null));
}
+ const navigationId = uuid();
setStack((prev) => {
const top = prev.at(-1);
// Capture the live selected tab onto the outgoing dashboard entry so
@@ -115,7 +127,7 @@ const SdkInternalNavigationProviderInner = ({
{ ...top, tabId: selectedTabId ?? top.tabId },
]
: prev;
- return [...updated, entry];
+ return [...updated, { ...entry, navigationId }];
});
},
[dispatch, currentDashboard, selectedTabId],
@@ -144,7 +156,12 @@ const SdkInternalNavigationProviderInner = ({
(dashboard: { id: SdkDashboardId; name: string }) => {
if (stack.length === 0) {
setStack([
- { type: "dashboard", id: dashboard.id, name: dashboard.name },
+ {
+ type: "dashboard",
+ id: dashboard.id,
+ name: dashboard.name,
+ navigationId: uuid(),
+ },
]);
}
},
@@ -164,6 +181,14 @@ const SdkInternalNavigationProviderInner = ({
const entryIsOriginalEntity = stack.length === 0 || entryIndex === 0;
const hasNavigatedToEntity = !entryIsOriginalEntity;
+ const navigatedEntityParameters = dashboardProps?.navigatedEntityParameters;
+ const onNavigatedEntityParametersChange =
+ dashboardProps?.onNavigatedEntityParametersChange;
+ const store = useSdkStore();
+ const controlledParameters = entryToRender
+ ? navigatedEntityParameters?.[entryToRender.navigationId]
+ : undefined;
+
const value = useMemo(
() => ({
stack,
@@ -200,14 +225,36 @@ const SdkInternalNavigationProviderInner = ({
};
const content = match({ activeEntry: entryToRender })
- .with({ activeEntry: { type: "dashboard" } }, ({ activeEntry }) => (
- <InteractiveDashboardContent
- {...getDrillThroughDashboardProps(dashboardProps)}
- dashboardId={activeEntry.id}
- initialParameters={activeEntry.parameters}
- enableEntityNavigation
- />
- ))
+ .with({ activeEntry: { type: "dashboard" } }, ({ activeEntry }) => {
+ const { entityId, navigationId } = activeEntry;
+
+ return (
+ <InteractiveDashboardContent
+ {...getDrillThroughDashboardProps(dashboardProps)}
+ dashboardId={activeEntry.id}
+ {...(controlledParameters
+ ? { parameters: controlledParameters }
+ : { initialParameters: activeEntry.parameters })}
+ onParametersChange={
+ entityId !== undefined
+ ? (payload) =>
+ onNavigatedEntityParametersChange?.({
+ ...payload,
+ entityType: "dashboard",
+ entityId,
+ navigationId,
+ // Read the store now: on the first load, the render still has the previous dashboard
+ clickParameters: buildClickParameters(
+ activeEntry.parameters ?? {},
+ getParameters(store.getState()),
+ ),
+ })
+ : undefined
+ }
+ enableEntityNavigation
+ />
+ );
+ })
.with({ activeEntry: { type: "ad-hoc-question" } }, ({ activeEntry }) => (
<SdkAdHocQuestion
questionPath={activeEntry.adHocQuestionPath}
@@ -219,18 +266,40 @@ const SdkInternalNavigationProviderInner = ({
{RenderDrillThroughQuestion && <RenderDrillThroughQuestion />}
</SdkAdHocQuestion>
))
- .with({ activeEntry: { type: "question" } }, ({ activeEntry }) => (
- <SdkQuestion
- questionId={activeEntry.id}
- onNavigateBack={pop}
- initialSqlParameters={activeEntry.parameters}
- isSaveEnabled
- {...questionPropsInferredFromDashboard}
- {...drillThroughQuestionProps}
- >
- {RenderDrillThroughQuestion && <RenderDrillThroughQuestion />}
- </SdkQuestion>
- ))
+ .with({ activeEntry: { type: "question" } }, ({ activeEntry }) => {
+ const { entityId, navigationId } = activeEntry;
+
+ return (
+ <SdkQuestion
+ questionId={activeEntry.id}
+ onNavigateBack={pop}
+ // When using controlled parameters we pass `sqlParameters`, not `initialSqlParameters`
+ initialSqlParameters={
+ controlledParameters ? undefined : activeEntry.parameters
+ }
+ isSaveEnabled
+ {...questionPropsInferredFromDashboard}
+ {...drillThroughQuestionProps}
+ sqlParameters={controlledParameters}
+ navigatedEntity={
+ entityId !== undefined
+ ? {
+ rawClickParameters: activeEntry.parameters ?? {},
+ onParametersChange: (payload) =>
+ onNavigatedEntityParametersChange?.({
+ ...payload,
+ entityType: "question",
+ entityId,
+ navigationId,
+ }),
+ }
+ : undefined
+ }
+ >
+ {RenderDrillThroughQuestion && <RenderDrillThroughQuestion />}
+ </SdkQuestion>
+ );
+ })
.otherwise(() => children);
return (
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
index 0577407d50a..81caa1ec694 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx
@@ -1,6 +1,8 @@
import { createContext, useContext } from "react";
import type { SdkDashboardId } from "embedding-sdk-bundle/types/dashboard";
+import type { SdkEntityId } from "embedding-sdk-bundle/types/entity";
+import type { NavigationId } from "embedding-sdk-bundle/types/navigation";
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";
@@ -17,6 +19,8 @@ export type SdkInternalNavigationEntry =
| (BaseEntry & {
type: "dashboard";
id: SdkDashboardId;
+ /** Set for click-behavior targets. */
+ entityId?: SdkEntityId;
name: string;
virtual?: true;
parameters?: ParameterValues;
@@ -28,6 +32,8 @@ export type SdkInternalNavigationEntry =
| (BaseEntry & {
type: "question";
id: SdkQuestionId | null;
+ /** Set for click-behavior targets. */
+ entityId?: SdkEntityId;
name: string;
virtual?: true;
parameters?: ParameterValues;
@@ -67,13 +73,18 @@ export type SdkInternalNavigationEntry =
onPop?: () => void;
});
+export type SdkInternalNavigationStackEntry = SdkInternalNavigationEntry & {
+ /** Random id of this visit, set when the entry is added to the stack. Key into `navigatedEntityParameters`. */
+ navigationId: NavigationId;
+};
+
export type SdkInternalNavigationContextValue = {
- stack: SdkInternalNavigationEntry[];
+ stack: SdkInternalNavigationStackEntry[];
push: (entry: SdkInternalNavigationEntry) => void;
pop: () => void;
- currentEntry: SdkInternalNavigationEntry | undefined;
+ currentEntry: SdkInternalNavigationStackEntry | undefined;
canGoBack: boolean;
- previousEntry: SdkInternalNavigationEntry | undefined;
+ previousEntry: SdkInternalNavigationStackEntry | undefined;
initWithDashboard: (dashboard: { id: SdkDashboardId; name: string }) => void;
/**
* True when nav stack has pushed beyond the original entity. SdkDashboard reads
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.tsx
index faab7d64ad0..cda52c1e58a 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
@@ -91,6 +91,7 @@ export const SdkQuestionProvider = ({
clickActionMode: userClickActionMode,
navigateToNewCard: userNavigateToNewCard,
onDrillThrough,
+ navigatedEntity,
onVisualizationChange,
initialVisualization,
}: SdkQuestionProviderProps) => {
@@ -225,6 +226,7 @@ export const SdkQuestionProvider = ({
useSdkControlledSqlParameters({
sqlParameters,
onSqlParametersChange,
+ navigatedEntity,
question,
parameterValues: parameterValues ?? {},
updateParameterValues,
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
index 3184c53c151..3da7b9fee7b 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
@@ -1,6 +1,7 @@
import type { PropsWithChildren } from "react";
import type { LoadQuestionHookResult } from "embedding-sdk-bundle/hooks/private/use-load-question";
+import type { NavigatedSqlEntityOptions } from "embedding-sdk-bundle/hooks/private/use-sdk-controlled-sql-parameters";
import type { SdkEntityToken } from "embedding-sdk-bundle/types";
import type { SdkCollectionId } from "embedding-sdk-bundle/types/collection";
import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";
@@ -201,6 +202,14 @@ export type SdkQuestionProviderProps = PropsWithChildren<
},
defaultNavigate: () => Promise<void>,
) => Promise<void>;
+
+ /**
+ * For a SQL question opened by a click behavior: its raw click values, and a
+ * callback that gets each `onSqlParametersChange` payload plus `clickParameters`.
+ *
+ * @internal
+ */
+ navigatedEntity?: NavigatedSqlEntityOptions;
}
>;
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
index 89a8525c9e0..a74995bcf23 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
@@ -51,6 +51,7 @@ export type InteractiveQuestionBaseProps = Omit<
| "clickActionMode"
| "navigateToNewCard"
| "backToDashboard"
+ | "navigatedEntity"
>;
/**
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
index 87e36b5d3e9..dd4213ad6d3 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
@@ -74,9 +74,16 @@ export type BaseSdkQuestionProps = SdkQuestionIdProps & {
*/
export type DrillThroughQuestionProps = Omit<
BaseSdkQuestionProps,
- "questionId"
+ "questionId" | "initialSqlParameters"
> &
- SdkQuestionDefaultViewProps;
+ SdkQuestionDefaultViewProps & {
+ /**
+ * Initial values for SQL parameters, slug-keyed, applied to every SQL question that opens from the dashboard.
+ *
+ * To control a SQL question opened by a click behavior, use the dashboard's `navigatedEntityParameters` and `onNavigatedEntityParametersChange`.
+ */
+ initialSqlParameters?: BaseSdkQuestionProps["initialSqlParameters"];
+ };
/**
* @interface
@@ -156,6 +163,7 @@ export const _SdkQuestion = ({
clickActionMode,
navigateToNewCard,
onDrillThrough,
+ navigatedEntity,
height,
width,
@@ -219,6 +227,7 @@ export const _SdkQuestion = ({
clickActionMode={clickActionMode}
navigateToNewCard={navigateToNewCard}
onDrillThrough={onDrillThrough}
+ navigatedEntity={navigatedEntity}
onVisualizationChange={onVisualizationChange}
>
{children ?? (
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
index 0b56652087e..189e86f63ea 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
@@ -432,6 +432,7 @@ describe("InteractiveQuestion", () => {
type: "dashboard" as const,
id: 1,
name: "Sales Dashboard",
+ navigationId: "visit-1",
};
const mockNavigation = makeMockNavigation({ stack: [existingEntry] });
await setup({ mockNavigation });
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.ts
index e1055d6c412..0066f3743ef 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
@@ -40,6 +40,8 @@ const propsSchema: Yup.SchemaOf<EditableDashboardProps> = Yup.object({
initialParameters: Yup.mixed().optional(),
parameters: Yup.mixed().optional(),
onParametersChange: Yup.mixed().optional(),
+ navigatedEntityParameters: Yup.mixed().optional(),
+ onNavigatedEntityParametersChange: Yup.mixed().optional(),
onLoad: Yup.mixed().optional(),
onLoadWithoutCards: Yup.mixed().optional(),
plugins: Yup.object({
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.ts
index d5472829ad3..9d6c1b54612 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
@@ -34,6 +34,8 @@ const propsSchema: Yup.SchemaOf<InteractiveDashboardProps> = Yup.object({
initialParameters: Yup.mixed().optional(),
parameters: Yup.mixed().optional(),
onParametersChange: Yup.mixed().optional(),
+ navigatedEntityParameters: Yup.mixed().optional(),
+ onNavigatedEntityParametersChange: Yup.mixed().optional(),
onLoad: Yup.mixed().optional(),
onLoadWithoutCards: Yup.mixed().optional(),
plugins: Yup.object({
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/navigated-entity-parameters.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/navigated-entity-parameters.unit.spec.tsx
new file mode 100644
index 00000000000..4a9acc00b2f
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/navigated-entity-parameters.unit.spec.tsx
@@ -0,0 +1,1183 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+import { type ReactElement, useState } from "react";
+import _ from "underscore";
+
+import {
+ setupAdhocQueryMetadataEndpoint,
+ setupBookmarksEndpoints,
+ setupCardDataset,
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
+ setupCollectionsEndpoints,
+ setupDashboardEndpoints,
+ setupDashboardQueryMetadataEndpoint,
+ setupDatabasesEndpoints,
+ setupLastDownloadFormatEndpoints,
+} from "__support__/server-mocks";
+import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";
+import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";
+import { mockGetBoundingClientRect, screen, waitFor } from "__support__/ui";
+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";
+import type { ParameterChangePayload } from "embedding-sdk-bundle/types/dashboard";
+import type {
+ NavigatedEntityParameterChangePayload,
+ NavigatedEntityParameters,
+ NavigationId,
+} from "embedding-sdk-bundle/types/navigation";
+import { loadVisualizationComponents } from "metabase/viz-core";
+import { getColumnKey } from "metabase-lib/v1/queries/utils/column-key";
+import type { Card, ClickBehavior, Dashboard } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockCollection,
+ createMockColumn,
+ createMockDashboard,
+ createMockDashboardCard,
+ createMockDashboardQueryMetadata,
+ createMockDataset,
+ createMockDatasetData,
+ createMockNativeDatasetQuery,
+ createMockParameter,
+ createMockStructuredDatasetQuery,
+ createMockTextDashboardCard,
+} from "metabase-types/api/mocks";
+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";
+import {
+ PRODUCTS_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
+
+import { InteractiveDashboard } from "../InteractiveDashboard";
+
+// Tests that control the target write their host `App` inline on purpose, so
+// they also show the code a customer would write.
+
+beforeAll(() => {
+ mockGetBoundingClientRect();
+ return loadVisualizationComponents(["table"]);
+});
+
+const DATABASE = createSampleDatabase();
+
+const ROOT_DASHBOARD_ID = 1;
+const TARGET_DASHBOARD_ID = 2;
+const OTHER_DASHBOARD_ID = 3;
+const SQL_QUESTION_ID = 30;
+const GUI_QUESTION_ID = 40;
+
+const CATEGORY_COLUMN = createMockColumn({
+ name: "CATEGORY",
+ display_name: "Category",
+ base_type: "type/Text",
+});
+
+// Table dashcards only use column click behaviors
+const createCategoryClickBehaviorSettings = (clickBehavior: ClickBehavior) => ({
+ column_settings: {
+ [getColumnKey(CATEGORY_COLUMN)]: { click_behavior: clickBehavior },
+ },
+});
+
+const createCategoryDataset = (categories: string[]) =>
+ createMockDataset({
+ data: createMockDatasetData({
+ cols: [CATEGORY_COLUMN],
+ rows: categories.map((category) => [category]),
+ }),
+ });
+
+const createNativeCard = (
+ card: Partial<Card> & Pick<Card, "id" | "name">,
+ templateTags: string[] = [],
+) =>
+ createMockCard({
+ display: "table",
+ dataset_query: createMockNativeDatasetQuery({
+ database: DATABASE.id,
+ native: {
+ query: "select category from products",
+ "template-tags": Object.fromEntries(
+ templateTags.map((tag) => [
+ tag,
+ { id: `tag-${tag}`, name: tag, "display-name": tag, type: "text" },
+ ]),
+ ),
+ },
+ }),
+ ...card,
+ });
+
+const CATEGORY_PARAMETER = createMockParameter({
+ id: "p-category",
+ slug: "category",
+ name: "Category",
+ type: "string/=",
+});
+
+const VENDOR_PARAMETER = createMockParameter({
+ id: "p-vendor",
+ slug: "vendor",
+ name: "Vendor",
+ type: "string/=",
+ default: ["Acme"],
+ isMultiSelect: false,
+});
+
+const CATEGORY_SOURCE = {
+ type: "column",
+ id: "CATEGORY",
+ name: "Category",
+} as const;
+
+const linkToTargetDashboard = ({
+ mapsCategory,
+}: {
+ mapsCategory: boolean;
+}): ClickBehavior => ({
+ type: "link",
+ linkType: "dashboard",
+ targetId: TARGET_DASHBOARD_ID,
+ parameterMapping: mapsCategory
+ ? {
+ [CATEGORY_PARAMETER.id]: {
+ id: CATEGORY_PARAMETER.id,
+ source: CATEGORY_SOURCE,
+ target: { type: "parameter", id: CATEGORY_PARAMETER.id },
+ },
+ }
+ : {},
+});
+
+const LINK_TO_TARGET_DASHBOARD_VENDOR: ClickBehavior = {
+ type: "link",
+ linkType: "dashboard",
+ targetId: TARGET_DASHBOARD_ID,
+ parameterMapping: {
+ [VENDOR_PARAMETER.id]: {
+ id: VENDOR_PARAMETER.id,
+ source: CATEGORY_SOURCE,
+ target: { type: "parameter", id: VENDOR_PARAMETER.id },
+ },
+ },
+};
+
+const LINK_TO_SQL_QUESTION: ClickBehavior = {
+ type: "link",
+ linkType: "question",
+ targetId: SQL_QUESTION_ID,
+ parameterMapping: {
+ category: {
+ id: "category",
+ source: CATEGORY_SOURCE,
+ target: { type: "variable", id: "category" },
+ },
+ },
+};
+
+const LINK_TO_GUI_QUESTION: ClickBehavior = {
+ type: "link",
+ linkType: "question",
+ targetId: GUI_QUESTION_ID,
+ parameterMapping: {},
+};
+
+const ROOT_CARD = createNativeCard({ id: 10, name: "Root card" });
+
+const TARGET_CARD = createNativeCard({ id: 20, name: "Target card" }, [
+ "category",
+ "vendor",
+]);
+
+const TARGET_DASHCARD = createMockDashboardCard({
+ id: 20,
+ dashboard_id: TARGET_DASHBOARD_ID,
+ card_id: TARGET_CARD.id,
+ card: TARGET_CARD,
+ parameter_mappings: [
+ {
+ card_id: TARGET_CARD.id,
+ parameter_id: CATEGORY_PARAMETER.id,
+ target: ["variable", ["template-tag", "category"]],
+ },
+ {
+ card_id: TARGET_CARD.id,
+ parameter_id: VENDOR_PARAMETER.id,
+ target: ["variable", ["template-tag", "vendor"]],
+ },
+ ],
+ visualization_settings: createCategoryClickBehaviorSettings({
+ type: "link",
+ linkType: "dashboard",
+ targetId: OTHER_DASHBOARD_ID,
+ parameterMapping: {},
+ }),
+});
+
+const OTHER_DASHBOARD = createMockDashboard({
+ id: OTHER_DASHBOARD_ID,
+ name: "Other",
+ dashcards: [createMockTextDashboardCard({ id: 30, text: "Other text" })],
+});
+
+const SQL_QUESTION = createNativeCard(
+ {
+ id: SQL_QUESTION_ID,
+ name: "SQL question",
+ entity_id: createMockEntityId("sql-question-entity-id"),
+ },
+ ["category"],
+);
+
+const GUI_QUESTION = createMockCard({
+ id: GUI_QUESTION_ID,
+ name: "GUI question",
+ dataset_query: createMockStructuredDatasetQuery({
+ database: DATABASE.id,
+ query: { "source-table": PRODUCTS_ID },
+ }),
+});
+
+const TARGET_QUERY_PATH = `path:/api/dashboard/${TARGET_DASHBOARD_ID}/dashcard/${TARGET_DASHCARD.id}/card/${TARGET_CARD.id}/query`;
+const SQL_QUESTION_QUERY_PATH = `path:/api/card/${SQL_QUESTION_ID}/query`;
+
+const setupEndpoints = ({
+ clickBehavior,
+ targetLastUsedParameterValues = {},
+}: {
+ clickBehavior: ClickBehavior;
+ targetLastUsedParameterValues?: Dashboard["last_used_param_values"];
+}) => {
+ const rootDashcard = createMockDashboardCard({
+ id: 10,
+ dashboard_id: ROOT_DASHBOARD_ID,
+ card_id: ROOT_CARD.id,
+ card: ROOT_CARD,
+ visualization_settings: createCategoryClickBehaviorSettings(clickBehavior),
+ });
+ const rootDashboard = createMockDashboard({
+ id: ROOT_DASHBOARD_ID,
+ name: "Root",
+ dashcards: [rootDashcard],
+ });
+ const targetDashboard = createMockDashboard({
+ id: TARGET_DASHBOARD_ID,
+ entity_id: createMockEntityId("target-dashboard-entity-id"),
+ name: "Target",
+ parameters: [CATEGORY_PARAMETER, VENDOR_PARAMETER],
+ dashcards: [TARGET_DASHCARD],
+ last_used_param_values: targetLastUsedParameterValues,
+ });
+ const cardQueryMetadata = createMockCardQueryMetadata({
+ databases: [DATABASE],
+ });
+
+ setupDashboardEndpoints(rootDashboard);
+ setupDashboardQueryMetadataEndpoint(
+ rootDashboard,
+ createMockDashboardQueryMetadata({
+ databases: [DATABASE],
+ dashboards: [targetDashboard],
+ cards: [SQL_QUESTION, GUI_QUESTION],
+ }),
+ );
+ setupDashcardQueryEndpoints(
+ ROOT_DASHBOARD_ID,
+ rootDashcard,
+ createCategoryDataset(["Gizmo"]),
+ );
+
+ setupDashboardEndpoints(targetDashboard);
+ setupDashboardQueryMetadataEndpoint(
+ targetDashboard,
+ createMockDashboardQueryMetadata({
+ databases: [DATABASE],
+ dashboards: [OTHER_DASHBOARD],
+ }),
+ );
+ setupDashcardQueryEndpoints(
+ TARGET_DASHBOARD_ID,
+ TARGET_DASHCARD,
+ createCategoryDataset(["Widget"]),
+ );
+
+ setupDashboardEndpoints(OTHER_DASHBOARD);
+ setupDashboardQueryMetadataEndpoint(
+ OTHER_DASHBOARD,
+ createMockDashboardQueryMetadata({ databases: [DATABASE] }),
+ );
+
+ setupCardEndpoints(SQL_QUESTION);
+ setupCardQueryMetadataEndpoint(SQL_QUESTION, cardQueryMetadata);
+ setupCardQueryEndpoints(SQL_QUESTION, createCategoryDataset(["Gizmo"]));
+
+ setupCardEndpoints(GUI_QUESTION);
+ setupCardQueryMetadataEndpoint(GUI_QUESTION, cardQueryMetadata);
+ setupCardQueryEndpoints(GUI_QUESTION, createCategoryDataset(["Gizmo"]));
+ setupAdhocQueryMetadataEndpoint(cardQueryMetadata);
+ setupCardDataset({
+ dataset: { data: { cols: [CATEGORY_COLUMN], rows: [["Gizmo"]] } },
+ });
+
+ setupCollectionsEndpoints({ collections: [] });
+ setupCollectionByIdEndpoint({
+ collections: [createMockCollection({ id: 1 })],
+ });
+ setupDatabasesEndpoints([DATABASE]);
+ setupLastDownloadFormatEndpoints();
+ setupBookmarksEndpoints([]);
+ setupNotificationChannelsEndpoints({});
+};
+
+const renderWithSdk = async (app: ReactElement) => {
+ const { state } = setupSdkState();
+
+ renderWithSDKProviders(app, {
+ componentProviderProps: { authConfig: createMockSdkConfig() },
+ storeInitialState: state,
+ });
+
+ expect(await screen.findByRole("gridcell", { name: "Gizmo" })).toBeVisible();
+};
+
+type QueryRequestParameter = { id: string; target: unknown; value: unknown };
+
+const getQueryRequestParameters = (path: string): QueryRequestParameter[][] =>
+ fetchMock.callHistory
+ .calls(path)
+ .map((call) => JSON.parse(String(call.options.body)).parameters);
+
+const getTargetQueryValues = () =>
+ getQueryRequestParameters(TARGET_QUERY_PATH).map((parameters) =>
+ Object.fromEntries(
+ parameters.map((parameter) => [parameter.id, parameter.value]),
+ ),
+ );
+
+const getLastTargetQueryValues = () => getTargetQueryValues().at(-1);
+
+const waitForTargetQueries = (count: number) =>
+ waitFor(() => expect(getTargetQueryValues()).toHaveLength(count));
+
+const getSqlQuestionCategoryValues = () =>
+ getQueryRequestParameters(SQL_QUESTION_QUERY_PATH).map(
+ (parameters) =>
+ parameters.find((parameter) =>
+ _.isEqual(parameter.target, ["variable", ["template-tag", "category"]]),
+ )?.value,
+ );
+
+const clickCell = async (value: string) =>
+ userEvent.click(await screen.findByRole("gridcell", { name: value }));
+
+const openTargetDashboard = async () => {
+ await clickCell("Gizmo");
+ await waitForTargetQueries(1);
+};
+
+const typeInVendorFilter = async (value: string) => {
+ const input = await screen.findByPlaceholderText("Vendor");
+ await userEvent.clear(input);
+ await userEvent.type(input, `${value}{enter}`);
+};
+
+const clickAppButton = async (name: string) =>
+ userEvent.click(screen.getByRole("button", { name }));
+
+describe("InteractiveDashboard navigated entity parameters", () => {
+ describe("the host app can observe the target", () => {
+ it("gets initial-state with the entity, the navigation id and the click values", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ await openTargetDashboard();
+
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith({
+ source: "initial-state",
+ entityType: "dashboard",
+ entityId: "target-dashboard-entity-id",
+ navigationId: expect.any(String),
+ parameters: { category: ["Gizmo"], vendor: ["Acme"] },
+ defaultParameters: { category: null, vendor: ["Acme"] },
+ lastUsedParameters: { category: null, vendor: null },
+ clickParameters: { category: ["Gizmo"] },
+ });
+ });
+
+ it("gets manual-change when the user edits a filter, with the same navigation id", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ await openTargetDashboard();
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ const [[initialState]] = onNavigatedEntityParametersChange.mock.calls;
+
+ await typeInVendorFilter("Globex");
+
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith({
+ ...initialState,
+ source: "manual-change",
+ parameters: { category: ["Gizmo"], vendor: "Globex" },
+ }),
+ );
+ });
+
+ it("gets the click values also when it adds the callback after the first load", async () => {
+ setupEndpoints({ clickBehavior: LINK_TO_TARGET_DASHBOARD_VENDOR });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+ const App = () => {
+ const [isListening, setIsListening] = useState(false);
+
+ return (
+ <>
+ <button onClick={() => setIsListening(true)}>Listen</button>
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={
+ isListening ? onNavigatedEntityParametersChange : undefined
+ }
+ />
+ </>
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+ await clickAppButton("Listen");
+ await typeInVendorFilter("Globex");
+
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "manual-change",
+ clickParameters: { vendor: ["Gizmo"] },
+ }),
+ ),
+ );
+ });
+
+ it('gets initial-state when the click opens a SQL question, with entityType "question"', async () => {
+ setupEndpoints({ clickBehavior: LINK_TO_SQL_QUESTION });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ await clickCell("Gizmo");
+
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith({
+ source: "initial-state",
+ entityType: "question",
+ entityId: "sql-question-entity-id",
+ navigationId: expect.any(String),
+ parameters: { category: ["Gizmo"] },
+ defaultParameters: { category: null },
+ clickParameters: { category: ["Gizmo"] },
+ });
+ expect(getSqlQuestionCategoryValues().at(-1)).toEqual(["Gizmo"]);
+ });
+
+ it("gets nothing for questions built with the query builder", async () => {
+ setupEndpoints({ clickBehavior: LINK_TO_GUI_QUESTION });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ await clickCell("Gizmo");
+
+ expect(
+ await screen.findByTestId("query-visualization-root"),
+ ).toBeInTheDocument();
+ expect(onNavigatedEntityParametersChange).not.toHaveBeenCalled();
+ });
+
+ it("does not get target changes through the root onParametersChange", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onParametersChange = jest.fn<void, [ParameterChangePayload]>();
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onParametersChange={onParametersChange}
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ const rootEventCount = onParametersChange.mock.calls.length;
+ await openTargetDashboard();
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+
+ expect(onParametersChange).toHaveBeenCalledTimes(rootEventCount);
+ });
+ });
+
+ describe("the host app can control the target", () => {
+ it("keeps the target's values, by setting each payload's parameters as the entry, without another query", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+
+ return (
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ onNavigatedEntityParametersChange(payload);
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [payload.navigationId]: payload.parameters,
+ }));
+ }}
+ />
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ expect(getTargetQueryValues()).toEqual([
+ { [CATEGORY_PARAMETER.id]: ["Gizmo"], [VENDOR_PARAMETER.id]: ["Acme"] },
+ ]);
+ });
+
+ it("applies the click values and the defaults of the other filters, by setting clickParameters as the entry for the visit", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+
+ return (
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ onNavigatedEntityParametersChange(payload);
+ if (payload.source === "initial-state") {
+ setNavigatedEntityParameters((prev) => {
+ // If the map already has this navigationId, this is a back navigation
+ // and we don't want to change the parameters
+ if (prev[payload.navigationId]) {
+ return prev;
+ }
+ return {
+ ...prev,
+ [payload.navigationId]: payload.clickParameters,
+ };
+ });
+ }
+ }}
+ />
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalled(),
+ );
+ expect(getTargetQueryValues()).toEqual([
+ { [CATEGORY_PARAMETER.id]: ["Gizmo"], [VENDOR_PARAMETER.id]: ["Acme"] },
+ ]);
+ });
+
+ it("applies its own values plus the click values", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+
+ return (
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ const { navigationId } = payload;
+
+ switch (payload.source) {
+ case "initial-state":
+ setNavigatedEntityParameters((prev) => {
+ // If the map already has this navigationId, this is a back navigation
+ // and we don't want to change the parameters
+ if (prev[navigationId]) {
+ return prev;
+ }
+ return {
+ ...prev,
+ [navigationId]: {
+ ...payload.defaultParameters,
+ vendor: ["Globex"],
+ ...payload.clickParameters,
+ },
+ };
+ });
+ break;
+ case "manual-change":
+ case "auto-change":
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [navigationId]: payload.parameters,
+ }));
+ break;
+ }
+ }}
+ />
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await clickCell("Gizmo");
+
+ await waitForTargetQueries(2);
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: ["Gizmo"],
+ [VENDOR_PARAMETER.id]: ["Globex"],
+ });
+ });
+
+ it("replaces the click values with its own values", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+ const [navigationId, setNavigationId] = useState<NavigationId | null>(
+ null,
+ );
+
+ return (
+ <>
+ <button
+ onClick={() =>
+ navigationId &&
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [navigationId]: { vendor: ["Globex"] },
+ }))
+ }
+ >
+ Only Globex
+ </button>
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) =>
+ setNavigationId(payload.navigationId)
+ }
+ />
+ </>
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+ await clickAppButton("Only Globex");
+
+ await waitForTargetQueries(2);
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: null,
+ [VENDOR_PARAMETER.id]: ["Globex"],
+ });
+ });
+
+ it("applies the defaults, by setting defaultParameters as the entry for the visit", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+ const [lastPayload, setLastPayload] =
+ useState<NavigatedEntityParameterChangePayload | null>(null);
+
+ return (
+ <>
+ <button
+ onClick={() =>
+ lastPayload &&
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [lastPayload.navigationId]: lastPayload.defaultParameters,
+ }))
+ }
+ >
+ Reset filters
+ </button>
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={setLastPayload}
+ />
+ </>
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+ await clickAppButton("Reset filters");
+
+ await waitForTargetQueries(2);
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: null,
+ [VENDOR_PARAMETER.id]: ["Acme"],
+ });
+ });
+
+ it("applies the user's last used values, by setting lastUsedParameters as the entry for the visit", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ targetLastUsedParameterValues: { [VENDOR_PARAMETER.id]: ["Globex"] },
+ });
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+
+ return (
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ if (
+ payload.entityType === "dashboard" &&
+ payload.source === "initial-state"
+ ) {
+ setNavigatedEntityParameters((prev) => {
+ // If the map already has this navigationId, this is a back navigation
+ // and we don't want to change the parameters
+ if (prev[payload.navigationId]) {
+ return prev;
+ }
+ return {
+ ...prev,
+ [payload.navigationId]: payload.lastUsedParameters,
+ };
+ });
+ }
+ }}
+ />
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await clickCell("Gizmo");
+
+ await waitForTargetQueries(2);
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: null,
+ [VENDOR_PARAMETER.id]: ["Globex"],
+ });
+ });
+
+ it("follows later changes", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+ const [navigationId, setNavigationId] = useState<NavigationId | null>(
+ null,
+ );
+
+ const setVendor = (vendor: string) =>
+ navigationId &&
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [navigationId]: { vendor: [vendor] },
+ }));
+
+ return (
+ <>
+ <button onClick={() => setVendor("Globex")}>Only Globex</button>
+ <button onClick={() => setVendor("Initech")}>Only Initech</button>
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) =>
+ setNavigationId(payload.navigationId)
+ }
+ />
+ </>
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+ await clickAppButton("Only Globex");
+ await waitForTargetQueries(2);
+ await clickAppButton("Only Initech");
+ await waitForTargetQueries(3);
+
+ expect(getLastTargetQueryValues()).toMatchObject({
+ [VENDOR_PARAMETER.id]: ["Initech"],
+ });
+ });
+
+ it("controls a SQL question target", async () => {
+ setupEndpoints({ clickBehavior: LINK_TO_SQL_QUESTION });
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+ const [navigationId, setNavigationId] = useState<NavigationId | null>(
+ null,
+ );
+
+ return (
+ <>
+ <button
+ onClick={() =>
+ navigationId &&
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [navigationId]: { category: ["Widget"] },
+ }))
+ }
+ >
+ Only Widget
+ </button>
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) =>
+ setNavigationId(payload.navigationId)
+ }
+ />
+ </>
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await clickCell("Gizmo");
+ await waitFor(() =>
+ expect(getSqlQuestionCategoryValues().at(-1)).toEqual(["Gizmo"]),
+ );
+ await clickAppButton("Only Widget");
+
+ await waitFor(() =>
+ expect(getSqlQuestionCategoryValues().at(-1)).toEqual(["Widget"]),
+ );
+ });
+ });
+
+ describe("without an entry, the target works as before", () => {
+ it("loads with the click values and the defaults of the other filters", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ />,
+ );
+ await openTargetDashboard();
+
+ expect(getTargetQueryValues()).toEqual([
+ {
+ [CATEGORY_PARAMETER.id]: ["Gizmo"],
+ [VENDOR_PARAMETER.id]: ["Acme"],
+ },
+ ]);
+ });
+
+ it("ignores the user's last used values when the click sets a filter", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ targetLastUsedParameterValues: { [VENDOR_PARAMETER.id]: ["Globex"] },
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ await openTargetDashboard();
+
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: ["Gizmo"],
+ [VENDOR_PARAMETER.id]: ["Acme"],
+ });
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parameters: { category: ["Gizmo"], vendor: ["Acme"] },
+ lastUsedParameters: { category: null, vendor: ["Globex"] },
+ }),
+ ),
+ );
+ });
+
+ it("uses the user's last used values when the click sets no filter", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: false }),
+ targetLastUsedParameterValues: { [VENDOR_PARAMETER.id]: ["Globex"] },
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ await renderWithSdk(
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ onNavigatedEntityParametersChange={onNavigatedEntityParametersChange}
+ />,
+ );
+ await openTargetDashboard();
+
+ expect(getLastTargetQueryValues()).toMatchObject({
+ [VENDOR_PARAMETER.id]: ["Globex"],
+ });
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parameters: { category: null, vendor: ["Globex"] },
+ clickParameters: {},
+ }),
+ ),
+ );
+ });
+ });
+
+ describe("back navigation", () => {
+ it("keeps the navigation id and the host values, so the user's edits come back", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+
+ return (
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ onNavigatedEntityParametersChange(payload);
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [payload.navigationId]: payload.parameters,
+ }));
+ }}
+ />
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ const [[initialState]] = onNavigatedEntityParametersChange.mock.calls;
+ await typeInVendorFilter("Globex");
+ await waitFor(() =>
+ expect(getLastTargetQueryValues()).toMatchObject({
+ [VENDOR_PARAMETER.id]: ["Globex"],
+ }),
+ );
+
+ await clickCell("Widget");
+ expect(await screen.findByText("Other text")).toBeInTheDocument();
+ const queryCountBeforeBack = getTargetQueryValues().length;
+ onNavigatedEntityParametersChange.mockClear();
+ await userEvent.click(screen.getByLabelText("Back to Target"));
+
+ await waitForTargetQueries(queryCountBeforeBack + 1);
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: ["Gizmo"],
+ [VENDOR_PARAMETER.id]: ["Globex"],
+ });
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "initial-state",
+ navigationId: initialState.navigationId,
+ parameters: { category: ["Gizmo"], vendor: ["Globex"] },
+ clickParameters: { category: ["Gizmo"] },
+ }),
+ ),
+ );
+ });
+
+ it("starts a new visit when the user opens the same dashboard again", async () => {
+ setupEndpoints({
+ clickBehavior: linkToTargetDashboard({ mapsCategory: true }),
+ });
+ const onNavigatedEntityParametersChange = jest.fn<
+ void,
+ [NavigatedEntityParameterChangePayload]
+ >();
+
+ const App = () => {
+ const [navigatedEntityParameters, setNavigatedEntityParameters] =
+ useState<NavigatedEntityParameters>({});
+ const [navigationId, setNavigationId] = useState<NavigationId | null>(
+ null,
+ );
+
+ return (
+ <>
+ <button
+ onClick={() =>
+ navigationId &&
+ setNavigatedEntityParameters((prev) => ({
+ ...prev,
+ [navigationId]: { vendor: ["Globex"] },
+ }))
+ }
+ >
+ Only Globex
+ </button>
+ <InteractiveDashboard
+ dashboardId={ROOT_DASHBOARD_ID}
+ enableEntityNavigation
+ navigatedEntityParameters={navigatedEntityParameters}
+ onNavigatedEntityParametersChange={(payload) => {
+ onNavigatedEntityParametersChange(payload);
+ setNavigationId(payload.navigationId);
+ }}
+ />
+ </>
+ );
+ };
+
+ await renderWithSdk(<App />);
+ await openTargetDashboard();
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ const [[firstVisit]] = onNavigatedEntityParametersChange.mock.calls;
+ await clickAppButton("Only Globex");
+ await waitForTargetQueries(2);
+
+ await userEvent.click(screen.getByLabelText("Back to Root"));
+ onNavigatedEntityParametersChange.mockClear();
+ await clickCell("Gizmo");
+
+ await waitForTargetQueries(3);
+ expect(getLastTargetQueryValues()).toEqual({
+ [CATEGORY_PARAMETER.id]: ["Gizmo"],
+ [VENDOR_PARAMETER.id]: ["Acme"],
+ });
+ await waitFor(() =>
+ expect(onNavigatedEntityParametersChange).toHaveBeenCalledTimes(1),
+ );
+ const [[secondVisit]] = onNavigatedEntityParametersChange.mock.calls;
+ expect(secondVisit.navigationId).not.toBe(firstVisit.navigationId);
+ });
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx
index 754c3c3a4b2..d04191b8ef8 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx
@@ -52,6 +52,10 @@ import type {
ParameterChangePayload,
SdkDashboardId,
} from "embedding-sdk-bundle/types/dashboard";
+import type {
+ NavigatedEntityParameterChangePayload,
+ NavigatedEntityParameters,
+} from "embedding-sdk-bundle/types/navigation";
import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";
import { getErrorMessage } from "metabase/api/utils/errors";
import { useConfirmation } from "metabase/common/hooks";
@@ -206,6 +210,36 @@ export type SdkDashboardProps = PropsWithChildren<
* Fires on parameters change. The payload's `source` distinguishes the initial state on load (`'initial-state'`), user edits in the UI (`'manual-change'`), and auto-updates (`'auto-change'`).
*/
onParametersChange?: (payload: ParameterChangePayload) => void;
+
+ /**
+ * Parameter values for entities the user reaches through entity navigation, keyed by the `navigationId` that {@link SdkDashboardProps.onNavigatedEntityParametersChange | onNavigatedEntityParametersChange} reports.
+ * <br/>
+ * Each navigation gets a new `navigationId`, and going back keeps it. So an entry applies only to the visit it was written for, never to a later visit of the same entity.
+ * <br/>
+ * Inside each entry, keys are filter slugs for a dashboard and template tag names for a SQL question. Each entry works like {@link SdkDashboardProps.parameters | parameters} on the root and replaces the values of that visit: keys you omit use their default. Use `null` to clear a value.
+ * <br/>
+ * To keep the values the click set, start from the `clickParameters` of {@link SdkDashboardProps.onNavigatedEntityParametersChange | onNavigatedEntityParametersChange}.
+ * <br/>
+ * Questions built with the query builder have no named parameters, so they cannot be controlled.
+ * <br/>
+ * A visit without an entry keeps the click-behavior values and is not controlled.
+ * <br/>
+ * Requires {@link SdkDashboardDisplayProps.enableEntityNavigation | enableEntityNavigation}.
+ */
+ navigatedEntityParameters?: NavigatedEntityParameters;
+
+ /**
+ * Fires on parameters change on entities the user reaches through entity navigation. The root dashboard keeps reporting through {@link SdkDashboardProps.onParametersChange | onParametersChange}.
+ * <br/>
+ * The payload's `navigationId` identifies the visit, `entityType` and `entityId` the entity. `source` has the same meaning as in `onParametersChange`: `'initial-state'` fires after each navigation to the entity, also when the user comes back to it. It reports parameter values, it is not a navigation event.
+ * <br/>
+ * `clickParameters` holds the values the click behavior set. To compose your own values, do it on the first `'initial-state'` of a `navigationId` only, so going back keeps the user's edits.
+ * <br/>
+ * Dashboards without filters send `parameters: {}`. SQL questions without template tags and questions built with the query builder send no event.
+ */
+ onNavigatedEntityParametersChange?: (
+ payload: NavigatedEntityParameterChangePayload,
+ ) => void;
} & SdkDashboardDisplayProps &
DashboardEventHandlersProps
>;
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.tsx
index cba29a2d07d..63bf14af978 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
@@ -29,6 +29,8 @@ export type StaticDashboardProps = Omit<
| "drillThroughQuestionHeight"
| "renderDrillThroughQuestion"
| "enableEntityNavigation"
+ | "navigatedEntityParameters"
+ | "onNavigatedEntityParametersChange"
> &
SdkDashboardEntityPublicProps;
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-sql-parameters.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-sql-parameters.ts
index 4eedd85e80a..5d86af570b9 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-sql-parameters.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-sql-parameters.ts
@@ -3,6 +3,7 @@ import { useLatest } from "react-use";
import { isEqual } from "underscore";
import {
+ buildClickParameters,
buildControlledParameters,
buildParametersPayload,
} from "embedding-sdk-bundle/lib/controlled-parameters";
@@ -13,11 +14,21 @@ import type { ParameterValuesMap } from "metabase-types/api";
import type { SqlParameterValues } from "../../types";
+export type NavigatedSqlEntityOptions = {
+ rawClickParameters: SqlParameterValues;
+ onParametersChange: (
+ payload: SqlParameterChangePayload & {
+ clickParameters: SqlParameterValues;
+ },
+ ) => void;
+};
+
type Options = {
sqlParameters: SqlParameterValues | null | undefined;
onSqlParametersChange:
| ((payload: SqlParameterChangePayload) => void)
| undefined;
+ navigatedEntity?: NavigatedSqlEntityOptions;
question: Question | undefined;
parameterValues: ParameterValuesMap;
updateParameterValues: (next: ParameterValuesMap) => void;
@@ -33,6 +44,7 @@ type Options = {
export const useSdkControlledSqlParameters = ({
sqlParameters,
onSqlParametersChange,
+ navigatedEntity,
question,
parameterValues,
updateParameterValues,
@@ -57,6 +69,7 @@ export const useSdkControlledSqlParameters = ({
parameterDefinitions,
parameterValues,
onSqlParametersChange,
+ navigatedEntity,
lastSqlParametersPushRef,
});
};
@@ -126,6 +139,7 @@ const useObserveAppliedSqlParameters = ({
parameterDefinitions,
parameterValues,
onSqlParametersChange,
+ navigatedEntity,
lastSqlParametersPushRef,
}: {
question: Question | undefined;
@@ -134,6 +148,7 @@ const useObserveAppliedSqlParameters = ({
onSqlParametersChange:
| ((payload: SqlParameterChangePayload) => void)
| undefined;
+ navigatedEntity: NavigatedSqlEntityOptions | undefined;
lastSqlParametersPushRef: MutableRefObject<SqlParameterValues | null>;
}) => {
// Tracks question id change, so we can fire event with `source: initial-state`
@@ -141,6 +156,7 @@ const useObserveAppliedSqlParameters = ({
const emittedValuesRef = useRef<ParameterValuesMap | null>(null);
const callbackRef = useLatest(onSqlParametersChange);
+ const navigatedEntityRef = useLatest(navigatedEntity);
useEffect(() => {
if (!question || parameterDefinitions.length === 0) {
@@ -162,8 +178,22 @@ const useObserveAppliedSqlParameters = ({
parameterDefinitions,
);
+ const emit = (source: SqlParameterChangePayload["source"]) => {
+ const event = { source, ...payload };
+ callbackRef.current?.(event);
+
+ const navigated = navigatedEntityRef.current;
+ navigated?.onParametersChange({
+ ...event,
+ clickParameters: buildClickParameters(
+ navigated.rawClickParameters,
+ parameterDefinitions,
+ ),
+ });
+ };
+
if (isLoadEvent) {
- callbackRef.current?.({ source: "initial-state", ...payload });
+ emit("initial-state");
return;
}
@@ -173,15 +203,16 @@ const useObserveAppliedSqlParameters = ({
if (lastSqlParametersPush !== null) {
if (!isEqual(payload.parameters, lastSqlParametersPush)) {
- callbackRef.current?.({ source: "auto-change", ...payload });
+ emit("auto-change");
}
return;
}
- callbackRef.current?.({ source: "manual-change", ...payload });
+ emit("manual-change");
}, [
callbackRef,
+ navigatedEntityRef,
question,
parameterDefinitions,
parameterValues,
diff --git a/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts b/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts
index 36637d2ca29..04ff72e6a09 100644
--- a/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts
@@ -1,3 +1,5 @@
+import { pick } from "underscore";
+
import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
import { getParameterValuesByIdFromQueryParams } from "metabase/parameters/utils/parameter-parsing";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
@@ -94,3 +96,27 @@ export function buildParametersPayload(
}),
};
}
+
+/**
+ * Builds `clickParameters` for a navigated entity: the raw click values parsed
+ * with the target's parameter definitions, like the target parses them on load
+ * (`"Gizmo"` -> `["Gizmo"]`), keeping only the keys the click set.
+ */
+export const buildClickParameters = (
+ rawClickParameters: ParameterValues,
+ parameterDefinitions: UiParameter[],
+): ParameterValues => {
+ // `getParameterValuesBySlug` prefers `value`, which holds the current values
+ const definitionsWithoutValues = parameterDefinitions.map((parameter) => ({
+ ...parameter,
+ value: undefined,
+ }));
+
+ return pick(
+ getParameterValuesBySlug(
+ definitionsWithoutValues,
+ buildControlledParameters(rawClickParameters, definitionsWithoutValues),
+ ),
+ Object.keys(rawClickParameters),
+ );
+};
diff --git a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts
index 6baa16ff7f7..7246424dbb3 100644
--- a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.ts
@@ -1,3 +1,4 @@
+import type { SdkEntityId } from "embedding-sdk-bundle/types/entity";
import { DashboardClickAction } from "metabase/dashboard/click-behavior/DashboardClickAction";
import {
getClickBehavior,
@@ -20,6 +21,7 @@ import type { CardId, DashboardId, DashboardTabId } from "metabase-types/api";
type ParameterizedTarget = {
name: string;
+ entityId: SdkEntityId;
parameters: ParameterValues;
/**
* Same parameter values as {@link parameters}, but keyed by parameter id.
@@ -90,6 +92,7 @@ export const getClickBehaviorTarget = (
return {
type: "dashboard",
id: dashboard.id,
+ entityId: dashboard.entity_id,
name: dashboard.name,
parameters,
parameterIdValuePairs,
@@ -124,6 +127,7 @@ export const getClickBehaviorTarget = (
return {
type: "question",
id: targetCard.id,
+ entityId: targetCard.entity_id,
name: targetCard.name,
parameters,
parameterIdValuePairs,
diff --git a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts
index 7b6e887f9c5..0d9a1adc756 100644
--- a/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/modes/EmbeddingSdkMode.unit.spec.ts
@@ -10,7 +10,12 @@ import type {
CardId,
ClickBehaviorParameterMapping,
} from "metabase-types/api";
-import { createMockCard, createMockColumn } from "metabase-types/api/mocks";
+import {
+ createMockCard,
+ createMockColumn,
+ createMockDashboard,
+} from "metabase-types/api/mocks";
+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";
import {
PRODUCTS,
PRODUCTS_ID,
@@ -115,6 +120,7 @@ describe("getClickBehaviorTarget", () => {
it("keeps a native target question as a saved-question target", () => {
const targetCard = createMockCard({
id: 6,
+ entity_id: createMockEntityId("native-target-entity-id"),
name: "Native drill target",
dataset_query: {
type: "native",
@@ -153,6 +159,38 @@ describe("getClickBehaviorTarget", () => {
}
expect(target.id).toBe(6);
+ expect(target.entityId).toBe("native-target-entity-id");
expect(target.parameters).toEqual({ category: "Gizmo" });
});
+
+ it("carries the entity id of a target dashboard", () => {
+ const targetDashboard = createMockDashboard({
+ id: 7,
+ entity_id: createMockEntityId("dashboard-target-entity-id"),
+ name: "Dashboard drill target",
+ });
+
+ const clicked: ClickObject = {
+ settings: {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ targetId: 7,
+ parameterMapping: {},
+ },
+ },
+ dimensions: [{ column: categoryColumn, value: "Gizmo" }],
+ extraData: { dashboards: { 7: targetDashboard } },
+ };
+
+ const target = getClickBehaviorTarget(clicked, sourceQuestion);
+
+ expect(target?.type).toBe("dashboard");
+ if (target?.type !== "dashboard") {
+ throw new Error("expected a dashboard target");
+ }
+
+ expect(target.id).toBe(7);
+ expect(target.entityId).toBe("dashboard-target-entity-id");
+ });
});
diff --git a/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx b/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx
index b3d9d506aea..a8bc3190362 100644
--- a/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx
+++ b/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx
@@ -9,6 +9,7 @@ import {
} from "__support__/state";
import { ComponentProviderInternal } from "embedding-sdk-bundle/components/public/ComponentProvider";
import { sdkReducers } from "embedding-sdk-bundle/store";
+import { sdkListenerMiddleware } from "embedding-sdk-bundle/store/listener-middleware";
import type { SdkStore } from "embedding-sdk-bundle/store/types";
import { createMockSdkState } from "embedding-sdk-bundle/test/mocks/state";
import type { MetabaseProviderProps } from "embedding-sdk-bundle/types/metabase-provider";
@@ -70,7 +71,8 @@ export function renderWithSDKProviders(
};
}
- const storeMiddleware = _.compact([Api.middleware]);
+ // Same middleware as the real SDK store
+ const storeMiddleware = [Api.middleware, sdkListenerMiddleware.middleware];
// Unjustified type cast. FIXME
const store = getStore(
diff --git a/frontend/src/embedding-sdk-bundle/types/index.ts b/frontend/src/embedding-sdk-bundle/types/index.ts
index a49a1e76a9a..5240c7162b0 100644
--- a/frontend/src/embedding-sdk-bundle/types/index.ts
+++ b/frontend/src/embedding-sdk-bundle/types/index.ts
@@ -5,6 +5,7 @@ export type * from "./dashboard";
export type * from "./entity";
export type * from "./events";
export type * from "./metabot";
+export type * from "./navigation";
export type * from "./plugins";
export type * from "./question";
export type * from "./theme";
diff --git a/frontend/src/embedding-sdk-bundle/types/navigation.ts b/frontend/src/embedding-sdk-bundle/types/navigation.ts
new file mode 100644
index 00000000000..aa998563413
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/types/navigation.ts
@@ -0,0 +1,46 @@
+import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
+
+import type { ParameterChangePayload } from "./dashboard";
+import type { SdkEntityId } from "./entity";
+import type { SqlParameterChangePayload } from "./question";
+
+/**
+ * Opaque ID of one visit to an entity the user reached through entity navigation.
+ *
+ * @category Dashboard
+ */
+export type NavigationId = string;
+
+/**
+ * Parameter values for entities the user reaches through entity navigation, keyed by {@link NavigationId}.
+ *
+ * @category Dashboard
+ */
+export type NavigatedEntityParameters = Record<NavigationId, ParameterValues>;
+
+/**
+ * @inline
+ */
+export type NavigatedEntityFields = {
+ /** Entity ID of the dashboard or question on screen. */
+ entityId: SdkEntityId;
+ /** The values the click behavior set, in the same shape as `parameters`. Empty when the click maps no filter. */
+ clickParameters: ParameterValues;
+ /**
+ * Opaque ID of this visit. A new navigation gets a new ID, going back keeps it.
+ * Use it as the key in `navigatedEntityParameters`.
+ */
+ navigationId: NavigationId;
+};
+
+/**
+ * Payload passed to `onNavigatedEntityParametersChange` callback.
+ * The root payload of the same entity type, plus `entityType`, `entityId`, `navigationId` and `clickParameters`.
+ *
+ * @category Dashboard
+ */
+export type NavigatedEntityParameterChangePayload =
+ | (ParameterChangePayload &
+ NavigatedEntityFields & { entityType: "dashboard" })
+ | (SqlParameterChangePayload &
+ NavigatedEntityFields & { entityType: "question" });
diff --git a/frontend/src/metabase/dashboard/actions/parameters.tsx b/frontend/src/metabase/dashboard/actions/parameters.tsx
index a3a38d96ccd..fd5620e5bdd 100644
--- a/frontend/src/metabase/dashboard/actions/parameters.tsx
+++ b/frontend/src/metabase/dashboard/actions/parameters.tsx
@@ -947,16 +947,17 @@ export const setParameterFilteringParameters = createThunkAction(
export const setParameterValue = createThunkAction(
SET_PARAMETER_VALUE,
- (parameterId: ParameterId, value: unknown) => (_dispatch, getState) => {
- const isSettingDraftParameterValues = !getIsAutoApplyFilters(getState());
- const isValueEmpty = isParameterValueEmpty(value);
-
- return {
- id: parameterId,
- value: isValueEmpty ? PULSE_PARAM_EMPTY : value,
- isDraft: isSettingDraftParameterValues,
- };
- },
+ (parameterId: ParameterId, value: ParameterValuesMap[ParameterId]) =>
+ (_dispatch, getState) => {
+ const isSettingDraftParameterValues = !getIsAutoApplyFilters(getState());
+ const isValueEmpty = isParameterValueEmpty(value);
+
+ return {
+ id: parameterId,
+ value: isValueEmpty ? PULSE_PARAM_EMPTY : value,
+ isDraft: isSettingDraftParameterValues,
+ };
+ },
);
// Auto-apply filters
diff --git a/frontend/src/metabase/dashboard/reducers.ts b/frontend/src/metabase/dashboard/reducers.ts
index 17a8f4eb6dc..60a75dd72c9 100644
--- a/frontend/src/metabase/dashboard/reducers.ts
+++ b/frontend/src/metabase/dashboard/reducers.ts
@@ -1,5 +1,5 @@
import { type UnknownAction, createReducer } from "@reduxjs/toolkit";
-import { assoc, chain, merge, updateIn } from "icepick";
+import { chain, merge, updateIn } from "icepick";
import { actionApi } from "metabase/api";
import { combineReducers } from "metabase/redux";
@@ -235,9 +235,13 @@ const draftParameterValues = createReducer(
type: string;
payload: PayloadFromThunkActionCreator<typeof setParameterValue>;
}
- >(SET_PARAMETER_VALUE, (state, { payload: { id, value } }) =>
- assoc(state ?? {}, id, value),
- )
+ >(SET_PARAMETER_VALUE, (state, { payload: { id, value } }) => {
+ // Like icepick `assoc`: skip equal values, so `undefined` for a missing filter
+ // doesn't add a key and show a fake unapplied change
+ if (state[id] !== value) {
+ state[id] = value;
+ }
+ })
.addCase<string, { type: string; payload: DraftParameterValuesState }>(
SET_PARAMETER_VALUES,
(_state, { payload }) => payload,
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/DashboardParametersBridge.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/DashboardParametersBridge.tsx
index 290dac0d5a5..f1bfebeda22 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/DashboardParametersBridge.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/DashboardParametersBridge.tsx
@@ -1,6 +1,7 @@
import { type ReactNode, useCallback } from "react";
import type { ParameterChangePayload } from "embedding-sdk-bundle/types/dashboard";
+import type { NavigatedEntityParameterChangePayload } from "embedding-sdk-bundle/types/navigation";
import { isEmbeddingEajs } from "metabase/embedding-sdk/config";
import { sendMessage } from "../hooks/use-sdk-iframe-embed-event-bus";
@@ -8,6 +9,9 @@ import { sendMessage } from "../hooks/use-sdk-iframe-embed-event-bus";
type DashboardParametersBridgeProps = {
children: (api: {
onParametersChange: (payload: ParameterChangePayload) => void;
+ onNavigatedEntityParametersChange: (
+ payload: NavigatedEntityParameterChangePayload,
+ ) => void;
}) => ReactNode;
};
@@ -25,5 +29,21 @@ export const DashboardParametersBridge = ({
});
}, []);
- return <>{children({ onParametersChange })}</>;
+ const onNavigatedEntityParametersChange = useCallback(
+ (payload: NavigatedEntityParameterChangePayload) => {
+ if (!isEmbeddingEajs()) {
+ return;
+ }
+
+ sendMessage({
+ type: "metabase.embed.navigatedEntityParametersChange",
+ data: payload,
+ });
+ },
+ [],
+ );
+
+ return (
+ <>{children({ onParametersChange, onNavigatedEntityParametersChange })}</>
+ );
};
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
index 445475cd061..c9207ce7e03 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
@@ -238,7 +238,7 @@ const SdkIframeEmbedView = ({
},
(settings) => (
<DashboardParametersBridge>
- {({ onParametersChange }) => (
+ {({ onParametersChange, onNavigatedEntityParametersChange }) => (
<InteractiveDashboard
key={rerenderKey}
className={SdkIframeEmbedRouteS.Dashboard}
@@ -253,6 +253,10 @@ const SdkIframeEmbedView = ({
onParametersChange={onParametersChange}
hiddenParameters={settings.hiddenParameters}
enableEntityNavigation={settings.enableEntityNavigation}
+ navigatedEntityParameters={settings.navigatedEntityParameters}
+ onNavigatedEntityParametersChange={
+ onNavigatedEntityParametersChange
+ }
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.ts
index 64950638131..87b8f34a734 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
@@ -44,6 +44,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {
"hiddenParameters",
"drills",
"enableEntityNavigation",
+ "navigatedEntityParameters",
"customContext",
] satisfies (keyof DashboardEmbedOptions)[],
chart: [
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
index f85b4a8916f..a4d242e752c 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
@@ -1,4 +1,7 @@
-import type { SqlParameterValues } from "embedding-sdk-bundle/types";
+import type {
+ NavigatedEntityParameters,
+ SqlParameterValues,
+} from "embedding-sdk-bundle/types";
import { MetabaseError, SSO_NOT_ALLOWED } from "embedding-sdk-shared/errors";
import * as MetabaseErrors from "embedding-sdk-shared/errors";
import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
@@ -496,6 +499,14 @@ export abstract class MetabaseEmbedElement<T extends string[] = string[]>
new CustomEvent("sql-parameters-change", { detail: message.data }),
);
}
+
+ if (message.type === "metabase.embed.navigatedEntityParametersChange") {
+ this.dispatchEvent(
+ new CustomEvent("navigated-entity-parameters-change", {
+ detail: message.data,
+ }),
+ );
+ }
};
sendMessage<Message extends SdkIframeEmbedMessage>(
@@ -663,7 +674,7 @@ export abstract class MetabaseEmbedElement<T extends string[] = string[]>
return data.jwt;
}
- // `parameters` and `sqlParameters` are JS properties whose value
+ // `parameters`, `sqlParameters` and `navigatedEntityParameters` are JS properties whose value
// lives in the element's attribute of the same name. Reading the
// property parses the attribute as JSON; writing the property
// serializes the value back into the attribute. So setting the
@@ -797,6 +808,7 @@ export const MetabaseDashboardElement = createCustomElement(
"parameters",
"hidden-parameters",
"enable-entity-navigation",
+ "navigated-entity-parameters",
],
(Base) =>
class extends Base {
@@ -806,6 +818,20 @@ export const MetabaseDashboardElement = createCustomElement(
set parameters(values: ParameterValues | undefined) {
this._writeJsonProperty("parameters", "parameters", values);
}
+ get navigatedEntityParameters(): NavigatedEntityParameters | undefined {
+ return this._readJsonAttribute<NavigatedEntityParameters>(
+ "navigated-entity-parameters",
+ );
+ }
+ set navigatedEntityParameters(
+ values: NavigatedEntityParameters | undefined,
+ ) {
+ this._writeJsonProperty(
+ "navigatedEntityParameters",
+ "navigated-entity-parameters",
+ values,
+ );
+ }
},
);
export type MetabaseDashboardElement = InstanceType<
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts
index 001cf55cb66..970f4060d95 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts
@@ -2,6 +2,8 @@ import fetchMock from "fetch-mock";
import jwt from "jsonwebtoken";
import { act } from "react-dom/test-utils";
+import type { NavigatedEntityParameterChangePayload } from "embedding-sdk-bundle/types/navigation";
+
import {
type MetabaseDashboardElement,
MetabaseEmbedElement,
@@ -716,6 +718,61 @@ describe("embed.js script tag for sdk iframe embedding", () => {
const event = handler.mock.calls[0][0] as CustomEvent;
expect(event.detail).toEqual(payload);
});
+
+ it("reflects to the attribute and pushes a setSettings update when the `navigatedEntityParameters` property is set", async () => {
+ const { embed, iframePostMessageSpy, markReady } = setupDashboard();
+ await markReady();
+ iframePostMessageSpy.mockClear();
+
+ const navigatedEntityParameters = {
+ "navigation-id": { category: ["Widget"] },
+ };
+ embed.navigatedEntityParameters = navigatedEntityParameters;
+
+ expect(embed).toHaveAttribute(
+ "navigated-entity-parameters",
+ JSON.stringify(navigatedEntityParameters),
+ );
+ expect(embed.navigatedEntityParameters).toEqual(
+ navigatedEntityParameters,
+ );
+
+ const setSettingsCalls = iframePostMessageSpy.mock.calls.filter(
+ ([message]) => message?.type === "metabase.embed.setSettings",
+ );
+ expect(setSettingsCalls).toHaveLength(1);
+ expect(setSettingsCalls[0][0].data.navigatedEntityParameters).toEqual(
+ navigatedEntityParameters,
+ );
+ });
+
+ it("dispatches a `navigated-entity-parameters-change` event when the iframe broadcasts a change", async () => {
+ const { iframe, embed, markReady } = setupDashboard();
+ await markReady();
+
+ const handler = jest.fn();
+ embed.addEventListener("navigated-entity-parameters-change", handler);
+
+ const payload = {
+ entityType: "dashboard",
+ entityId: "target-entity-id",
+ navigationId: "navigation-id",
+ source: "initial-state",
+ parameters: { category: ["Widget"], date: null },
+ defaultParameters: { category: null, date: null },
+ lastUsedParameters: {},
+ clickParameters: { category: ["Widget"] },
+ } satisfies NavigatedEntityParameterChangePayload;
+ triggerIframeMessage(iframe, {
+ type: "metabase.embed.navigatedEntityParametersChange",
+ data: payload,
+ });
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(handler).toHaveBeenCalledWith(
+ expect.objectContaining({ detail: payload }),
+ );
+ });
});
describe("SQL parameter API", () => {
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
index 18c54689b5a..28b91a6da14 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
@@ -6,6 +6,10 @@ import type {
SqlParameterValues,
} from "embedding-sdk-bundle/types";
import type { ParameterChangePayload } from "embedding-sdk-bundle/types/dashboard";
+import type {
+ NavigatedEntityParameterChangePayload,
+ NavigatedEntityParameters,
+} from "embedding-sdk-bundle/types/navigation";
import type { SqlParameterChangePayload } from "embedding-sdk-bundle/types/question";
import type { MetabaseError } from "embedding-sdk-shared/errors";
import type { MetabaseErrorCode } from "embedding-sdk-shared/errors/error-code";
@@ -99,6 +103,10 @@ export type SdkIframeEmbedComponentTagMessage =
| {
type: "metabase.embed.sqlParametersChange";
data: SqlParameterChangePayload;
+ }
+ | {
+ type: "metabase.embed.navigatedEntityParametersChange";
+ data: NavigatedEntityParameterChangePayload;
};
// --- Embed Option Interfaces ---
@@ -119,6 +127,7 @@ export type DashboardEmbedOptions = StrictUnion<
parameters?: ParameterValues;
hiddenParameters?: string[];
enableEntityNavigation?: boolean;
+ navigatedEntityParameters?: NavigatedEntityParameters;
customContext?: string | Record<string, unknown>;
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts
index 792a907cb30..93e0233c8cc 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts
@@ -101,6 +101,21 @@ export interface MetabaseDashboardAttributes {
*/
"enable-entity-navigation"?: boolean;
+ /**
+ * Filter values for dashboards and SQL questions the user reaches through
+ * entity navigation. Needs `enable-entity-navigation`. Keyed by the `navigationId` that the
+ * `navigated-entity-parameters-change` DOM event reports, e.g.
+ * `{ '<navigationId>': { 'productId': '42' } }`.
+ * Each navigation gets a new `navigationId`, going back keeps it.
+ * Each entry works like `parameters` and replaces the values of that visit:
+ * keys you omit use their default, `null` clears a value. To keep the values
+ * the click set, start from the event's `clickParameters`. A visit
+ * without an entry keeps the click-behavior values and is not controlled.
+ *
+ * @remarks Pro/Enterprise
+ */
+ "navigated-entity-parameters"?: object;
+
/**
* Optional custom context string passed through to the guest token endpoint.
*