The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(embed js flow): use widget for initial parameters (#62356)
Nicolò Prettoe1c0570dc5b5
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-parameters.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-parameters.cy.spec.tsindex 22c9ead6d20..d7ac0656e68 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-parameters.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-parameters.cy.spec.ts@@ -87,7 +87,8 @@ H.describeWithSnowplow(suiteTitle, () => {});cy.log("set default value for id");- getEmbedSidebar().findByLabelText("ID").type("123").blur();+ getEmbedSidebar().findByLabelText("ID").type("123");+ H.popover().findByText("Add filter").click();H.getSimpleEmbedIframeContent().findByTestId("dashboard-parameters-widget-container")@@ -95,7 +96,8 @@ H.describeWithSnowplow(suiteTitle, () => {.should("contain", "123");cy.log("set default value for product id");- getEmbedSidebar().findByLabelText("Product ID").type("456").blur();+ getEmbedSidebar().findByLabelText("Product ID").type("456");+ H.popover().findByText("Add filter").click();H.getSimpleEmbedIframeContent().findByTestId("dashboard-parameters-widget-container")@@ -114,9 +116,18 @@ H.describeWithSnowplow(suiteTitle, () => {getEmbedSidebar().within(() => {cy.findByText("Get Code").click();codeBlock().should("contain", "initial-parameters=");- codeBlock().should("contain", '"id":"123"');- codeBlock().should("contain", '"product_id":"456"');+ codeBlock().should("contain", '"id":[123]');+ codeBlock().should("contain", '"product_id":[456]');});++ cy.get("metabase-dashboard")+ .invoke("attr", "initial-parameters")+ .then((attr) => {+ expect(JSON.parse(attr!)).to.deep.equal({+ id: [123],+ product_id: [456],+ });+ });});it("can hide dashboard parameters", () => {@@ -151,6 +162,12 @@ H.describeWithSnowplow(suiteTitle, () => {codeBlock().should("contain", '"id"');codeBlock().should("contain", '"product_id"');});++ cy.get("metabase-dashboard")+ .invoke("attr", "hidden-parameters")+ .then((attr) => {+ expect(JSON.parse(attr!)).to.have.members(["id", "product_id"]);+ });});});@@ -189,7 +206,8 @@ H.describeWithSnowplow(suiteTitle, () => {.should("exist");getEmbedSidebar().within(() => {- cy.findByLabelText("ID").type("123").blur();+ cy.findByLabelText("ID").type("123");+ cy.press("Tab"); //.blur() doesn't easily work here});H.getSimpleEmbedIframeContent().within(() => {@@ -211,6 +229,12 @@ H.describeWithSnowplow(suiteTitle, () => {codeBlock().should("not.contain", "hidden-parameters="); // not supported for questions yetcodeBlock().should("contain", '"id":"123"');});++ cy.get("metabase-question")+ .invoke("attr", "initial-sql-parameters")+ .then((attr) => {+ expect(JSON.parse(attr!)).to.deep.equal({ id: "123" });+ });});});diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/ParameterSettings/ParameterSettings.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/ParameterSettings/ParameterSettings.tsxindex f316e06c120..78c11414e13 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/ParameterSettings/ParameterSettings.tsx+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/ParameterSettings/ParameterSettings.tsx@@ -1,15 +1,34 @@import { useDebouncedCallback } from "@mantine/hooks";import { useCallback, useMemo } from "react";-import { c, t } from "ttag";+import { P, match } from "ts-pattern";+import { t } from "ttag";-import { Stack, Text, TextInput } from "metabase/ui";+import CS from "metabase/css/core/index.css";+import { ParameterWidget } from "metabase/parameters/components/ParameterWidget";+import { Group, Stack, Text } from "metabase/ui";import { SET_INITIAL_PARAMETER_DEBOUNCE_MS } from "metabase-enterprise/embedding_iframe_sdk_setup/constants";+import { getValuePopulatedParameters } from "metabase-lib/v1/parameters/utils/parameter-values";import { useSdkIframeEmbedSetupContext } from "../../context";import { ParameterVisibilityToggle } from "./ParameterVisibilityToggle";import { useHideParameter } from "./hooks/use-hide-parameter";-import { getParameterPlaceholder } from "./utils/parameter-placeholder";++function mapValuesBySlugToById(+ valuesBySlug: Record<string, any> | undefined,+ params: { id: string; slug: string }[],+) {+ if (!valuesBySlug) {+ return {};+ }++ return params.reduce<Record<string, any>>((byId, param) => {+ if (param.slug in valuesBySlug) {+ byId[param.id] = valuesBySlug[param.slug];+ }+ return byId;+ }, {});+}export const ParameterSettings = () => {const {@@ -49,15 +68,31 @@ export const ParameterSettings = () => {SET_INITIAL_PARAMETER_DEBOUNCE_MS,);- const parameterValues = useMemo(() => {- if (settings.dashboardId) {- return settings.initialParameters;- } else if (settings.questionId) {- return settings.initialSqlParameters;- }-- return {};- }, [settings]);+ /**+ * Widgets (and most of metabase logic) expect parameter values keyed by+ * **parameter.id**, but in the embed flow settings we store them by+ * **parameter.slug**, as the public API of embeds wants them by slug+ *+ * Here we convert them to "by-id" to make widgets work properly.+ */+ const parameterValuesById = useMemo(() => {+ const valuesBySlug = match(settings)+ .with({ dashboardId: P.nonNullable }, (s) => s.initialParameters)+ .with({ questionId: P.nonNullable }, (s) => s.initialSqlParameters)+ .otherwise(() => ({}));++ return mapValuesBySlugToById(valuesBySlug, availableParameters);+ }, [settings, availableParameters]);++ const uiParameters = useMemo(+ () =>+ getValuePopulatedParameters({+ parameters: availableParameters,+ values: parameterValuesById,+ defaultRequired: true,+ }),+ [availableParameters, parameterValuesById],+ );// Only show parameters for dashboards and questionsif (!isQuestionOrDashboardEmbed) {@@ -75,35 +110,28 @@ export const ParameterSettings = () => {if (availableParameters.length > 0) {return (<Stack>- {availableParameters.map((param) => {- const defaultValue = parameterValues?.[param.slug] ?? undefined;-- const placeholderValue = getParameterPlaceholder(param);-- const placeholderText = c(- `the placeholder text containing examples of how a parameter string looks like. {0} contains the placeholder (e.g. "2025-11-05")`,- ).t`e.g. ${placeholderValue}`;-- return (- <TextInput- key={param.id}- label={param.name}- placeholder={placeholderValue ? placeholderText : undefined}- defaultValue={defaultValue}- onChange={(e) =>- updateInitialParameterValue(param.slug, e.target.value)- }- rightSection={- <ParameterVisibilityToggle- parameterName={param.slug}- experience={experience}- isHidden={isParameterHidden(param.slug)}- onToggle={toggleParameterVisibility}- />+ {uiParameters.map((parameter) => (+ <Group justify="space-between" align="center" key={parameter.id}>+ <ParameterWidget+ className={CS.m0}+ parameter={parameter}+ parameters={uiParameters}+ setValue={(value: string) =>+ updateInitialParameterValue(parameter.slug, value)}+ setParameterValueToDefault={() => {+ updateInitialParameterValue(parameter.slug, parameter.default);+ }}+ enableParameterRequiredBehavior+ />+ <ParameterVisibilityToggle+ parameterName={parameter.slug}+ experience={experience}+ isHidden={isParameterHidden(parameter.slug)}+ onToggle={toggleParameterVisibility}/>- );- })}+ </Group>+ ))}</Stack>);}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-parameter-list.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-parameter-list.tsindex e6bb26995b9..688de2afce2 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-parameter-list.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-parameter-list.ts@@ -1,8 +1,10 @@-import { useMemo } from "react";+import { useEffect, useMemo } from "react";import { useLatest } from "react-use";import { skipToken, useGetCardQuery, useGetDashboardQuery } from "metabase/api";-import { useSelector } from "metabase/lib/redux";+import { useDispatch, useSelector } from "metabase/lib/redux";+import { getSavedDashboardUiParameters } from "metabase/parameters/utils/dashboards";+import { addFields } from "metabase/redux/metadata";import { getMetadata } from "metabase/selectors/metadata";import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";import type { Card, Parameter } from "metabase-types/api";@@ -20,6 +22,7 @@ export const useParameterList = ({dashboardId,questionId,}: UseParameterListProps) => {+ const dispatch = useDispatch();// Fetch dashboard/question data for parameter extractionconst { data: dashboard, isLoading: isDashboardLoading } =useGetDashboardQuery(dashboardId ? { id: dashboardId } : skipToken);@@ -38,13 +41,26 @@ export const useParameterList = ({// Extract parameters from the loaded dashboard/cardconst availableParameters = useMemo((): Parameter[] => {if (experience === "dashboard" && dashboard) {- return dashboard.parameters || [];+ return getSavedDashboardUiParameters(+ dashboard.dashcards,+ dashboard.parameters,+ dashboard.param_fields,+ metadata,+ );} else if (experience === "chart" && card) {return getCardUiParameters(card as Card, metadataRef.current) || [];}return [];- }, [experience, dashboard, card, metadataRef]);+ }, [experience, dashboard, card, metadata, metadataRef]);++ useEffect(() => {+ if (dashboard?.param_fields) {+ // This is needed to make some parameter widget populate the dropdown list+ // otherwise they will use a normal text input+ dispatch(addFields(Object.values(dashboard.param_fields).flat()));+ }+ }, [dashboard?.param_fields, dispatch]);const isLoadingParameters = isDashboardLoading || isCardLoading;diff --git a/frontend/src/metabase/redux/metadata.js b/frontend/src/metabase/redux/metadata.jsindex 60eabfc424d..a3008f59a31 100644--- a/frontend/src/metabase/redux/metadata.js+++ b/frontend/src/metabase/redux/metadata.js@@ -92,7 +92,6 @@ export const updateFieldValues = (fieldId, fieldValuePairs) => {export { ADD_FIELDS } from "metabase/entities/fields";export const addFields = (fields) => {- deprecated("metabase/redux/metadata addFields");return Fields.actions.addFields(fields);};