Skip to content

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

feat(embed-js): Convert EmbedJS wizard into a modal (#65113)

Timofey Kachalov63f85c370678
diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
index 4f661059cb6..3399b8fe01b 100644
--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
@@ -1,5 +1,6 @@
import { match } from "ts-pattern";
+import { openSharingMenu } from "e2e/support/helpers/e2e-sharing-helpers";
import type { MetabaseTheme } from "metabase/embedding-sdk/theme/MetabaseTheme";
import type { CreateApiKeyResponse } from "metabase-types/api";
@@ -339,3 +340,9 @@ export const mockEmbedJsToDevServer = () => {
}
});
};
+
+export function openEmbedJsModal() {
+ openSharingMenu("Embed");
+
+ cy.findByText("Embedded Analytics JS").click();
+}
diff --git a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
index 5dfafbbaad2..3806e8351d5 100644
--- a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
@@ -154,7 +154,11 @@ describe("scenarios - embedding hub", () => {
.findByText("Get embed snippet")
.click();
- cy.url().should("include", "/embed-js?auth_method=user_session");
+ H.modal()
+ .first()
+ .within(() => {
+ cy.findByText("Select your embed experience").should("be.visible");
+ });
});
it("Embed in production step should be locked until JWT is enabled", () => {
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/common.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/common.cy.spec.ts
new file mode 100644
index 00000000000..fa263eba17e
--- /dev/null
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/common.cy.spec.ts
@@ -0,0 +1,45 @@
+import { completeWizard, navigateToEntitySelectionStep } from "./helpers";
+
+const { H } = cy;
+
+const DASHBOARD_NAME = "Orders in a dashboard";
+
+describe("scenarios > embedding > sdk iframe embed setup > common", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.enableTracking();
+ H.updateSetting("enable-embedding-simple", true);
+
+ cy.intercept("GET", "/api/dashboard/**").as("dashboard");
+
+ H.mockEmbedJsToDevServer();
+ });
+
+ it("should close wizard when clicking `close` button on the modal", () => {
+ navigateToEntitySelectionStep({
+ experience: "dashboard",
+ resourceName: DASHBOARD_NAME,
+ });
+
+ H.modal()
+ .first()
+ .within(() => {
+ cy.get("[aria-label='Close']").click();
+ });
+
+ H.modal().should("not.exist");
+ cy.findAllByTestId("sdk-setting-card").should("be.visible");
+ });
+
+ it("should close wizard when clicking `Done` button on the last step", () => {
+ completeWizard({
+ experience: "dashboard",
+ resourceName: DASHBOARD_NAME,
+ });
+
+ H.modal().should("not.exist");
+ cy.findAllByTestId("sdk-setting-card").should("be.visible");
+ });
+});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-flow-enable-embed-js.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-flow-enable-embed-js.cy.spec.ts
index a4cf9d2eb4d..9b2066c1c63 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-flow-enable-embed-js.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/embed-flow-enable-embed-js.cy.spec.ts
@@ -13,7 +13,13 @@ describe("scenarios > embedding > sdk iframe embed setup > enable embed js", ()
});
it("shows the Enable to Continue button and enables embedding on click", () => {
- cy.visit("/embed-js");
+ cy.visit("/admin/embedding");
+
+ cy.findAllByTestId("sdk-setting-card")
+ .first()
+ .within(() => {
+ cy.findByText("New embed").click();
+ });
cy.log("shows tooltip with fair usage info");
getEmbedSidebar().findByLabelText("info icon").trigger("mouseover");
@@ -49,7 +55,14 @@ describe("scenarios > embedding > sdk iframe embed setup > enable embed js", ()
it("hides the enable card when embedding is already enabled", () => {
H.updateSetting("enable-embedding-simple", true);
- cy.visit("/embed-js");
+
+ cy.visit("/admin/embedding");
+
+ cy.findAllByTestId("sdk-setting-card")
+ .first()
+ .within(() => {
+ cy.findByText("New embed").click();
+ });
getEmbedSidebar()
.contains("Enable Embedded Analytics JS to get started.")
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts
index a8d392fb57c..613e78ec443 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts
@@ -1,6 +1,6 @@
import { match } from "ts-pattern";
-import { entityPickerModal } from "e2e/support/helpers";
+import { entityPickerModal, modal } from "e2e/support/helpers";
import type { Dashboard, RecentItem } from "metabase-types/api";
type RecentActivityIntercept = {
@@ -11,21 +11,24 @@ type DashboardIntercept = {
response: Cypress.Response<Dashboard>;
};
-export const getEmbedSidebar = () => cy.findByRole("complementary");
+export const getEmbedSidebar = () =>
+ modal()
+ .first()
+ .within(() => cy.findByRole("complementary"));
export const getRecentItemCards = () =>
cy.findAllByTestId("embed-recent-item-card");
-export const visitNewEmbedPage = ({ locale }: { locale?: string } = {}) => {
+export const visitNewEmbedPage = () => {
cy.intercept("GET", "/api/dashboard/*").as("dashboard");
- const params = new URLSearchParams();
+ cy.visit("/admin/embedding");
- if (locale) {
- params.append("locale", locale);
- }
-
- cy.visit("/embed-js?" + params);
+ cy.findAllByTestId("sdk-setting-card")
+ .first()
+ .within(() => {
+ cy.findByText("New embed").click();
+ });
cy.wait("@dashboard");
@@ -139,4 +142,13 @@ export const navigateToGetCodeStep = (options: NavigateToStepOptions) => {
});
};
+export const completeWizard = (options: NavigateToStepOptions) => {
+ navigateToGetCodeStep(options);
+
+ cy.log("complete wizard");
+ getEmbedSidebar().within(() => {
+ cy.findByText("Done").click();
+ });
+};
+
export const codeBlock = () => cy.get(".cm-content");
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-experience.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-experience.cy.spec.ts
index 65f2e3dbd59..cfdae7159b5 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-experience.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-experience.cy.spec.ts
@@ -1,4 +1,7 @@
-import { ORDERS_COUNT_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+import {
+ ORDERS_COUNT_QUESTION_ID,
+ ORDERS_QUESTION_ID,
+} from "e2e/support/cypress_sample_instance_data";
import {
assertDashboard,
@@ -186,27 +189,10 @@ H.describeWithSnowplow(suiteTitle, () => {
);
});
- it("localizes the iframe preview when ?locale is passed", () => {
- visitNewEmbedPage({ locale: "fr" });
-
- // TODO: update this test once "Exploration" is localized in french.
- getEmbedSidebar().findByText("Exploration").click();
-
- H.waitForSimpleEmbedIframesToLoad();
-
- H.getSimpleEmbedIframeContent().within(() => {
- cy.log("data picker is localized");
-
- cy.findByText("Données", { timeout: 10_000 }).should("be.visible");
-
- cy.findByText("Choisissez vos données de départ", {
- timeout: 10_000,
- }).should("be.visible");
- });
- });
-
it("should show a fake loading indicator in embed preview", () => {
- cy.visit("/embed-js");
+ cy.visit(`/question/${ORDERS_QUESTION_ID}`);
+
+ H.openEmbedJsModal();
cy.get("#iframe-embed-container")
.findByTestId("preview-loading-indicator", { timeout: 20_000 })
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts
index deba1ce08b6..066d78d85ce 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts
@@ -46,9 +46,14 @@ describe("scenarios > embedding > sdk iframe embed setup > user settings persist
.should("have.css", "color", "rgb(255, 0, 0)");
cy.log("2. reload the page");
- waitAndReload();
+ cy.wait("@persistSettings");
cy.log("3. brand color should be persisted");
+ navigateToEmbedOptionsStep({
+ experience: "dashboard",
+ resourceName: DASHBOARD_NAME,
+ });
+
H.getSimpleEmbedIframeContent()
.findAllByTestId("cell-data")
.first()
@@ -74,7 +79,7 @@ describe("scenarios > embedding > sdk iframe embed setup > user settings persist
});
cy.log("2. reload the page");
- waitAndReload();
+ cy.wait("@persistSettings");
cy.log("3. auth method should persist");
navigateToGetCodeStep({
@@ -89,11 +94,3 @@ describe("scenarios > embedding > sdk iframe embed setup > user settings persist
});
});
});
-
-const waitAndReload = () => {
- cy.wait("@persistSettings");
-
- cy.reload();
-
- H.waitForSimpleEmbedIframesToLoad();
-};
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts
index b2e30e73cbc..1a28ede4a61 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts
@@ -413,11 +413,13 @@ H.describeWithSnowplowEE(
});
it("should not send an Embedded Analytics JS usage event in the preview", () => {
- cy.visit("/embed-js");
+ cy.visit(`/question/${ORDERS_QUESTION_ID}`);
+
+ H.openEmbedJsModal();
H.waitForSimpleEmbedIframesToLoad();
H.getSimpleEmbedIframeContent().within(() => {
- cy.findByText("Orders in a dashboard").should("be.visible");
+ cy.findByText("Orders").should("be.visible");
});
H.expectUnstructuredSnowplowEvent(
diff --git a/e2e/test/scenarios/sharing/public-sharing-embed-flow.cy.spec.ts b/e2e/test/scenarios/sharing/public-sharing-embed-flow.cy.spec.ts
index fb194889477..e118d22e5c9 100644
--- a/e2e/test/scenarios/sharing/public-sharing-embed-flow.cy.spec.ts
+++ b/e2e/test/scenarios/sharing/public-sharing-embed-flow.cy.spec.ts
@@ -28,18 +28,11 @@ H.describeWithSnowplow(suiteTitle, () => {
H.openSharingMenu("Embed");
H.getEmbedModalSharingPane().within(() => {
- cy.findByRole("link", { name: "Embedded Analytics JS" }).click();
+ cy.findByRole("button", { name: "Embedded Analytics JS" }).click();
});
H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });
- cy.location("search").should((search) => {
- const params = new URLSearchParams(search);
-
- expect(params.get("resource_type")).to.equal("dashboard");
- expect(params.get("resource_id")).to.equal(String(ORDERS_DASHBOARD_ID));
- });
-
getEmbedSidebar().within(() => {
cy.findByText("Behavior").should("be.visible");
cy.findByText("Appearance").should("be.visible");
@@ -64,18 +57,11 @@ H.describeWithSnowplow(suiteTitle, () => {
H.openSharingMenu("Embed");
H.getEmbedModalSharingPane()
- .findByRole("link", { name: "Embedded Analytics JS" })
+ .findByRole("button", { name: "Embedded Analytics JS" })
.click();
H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });
- cy.location("search").should((search) => {
- const params = new URLSearchParams(search);
-
- expect(params.get("resource_type")).to.equal("question");
- expect(params.get("resource_id")).to.equal(String(ORDERS_QUESTION_ID));
- });
-
getEmbedSidebar().within(() => {
cy.findByText("Behavior").should("be.visible");
cy.findByText("Appearance").should("be.visible");
@@ -100,7 +86,7 @@ H.describeWithSnowplow(suiteTitle, () => {
H.openSharingMenu("Embed");
H.getEmbedModalSharingPane().within(() => {
- cy.findByRole("link", { name: "Embedded Analytics JS" }).click();
+ cy.findByRole("button", { name: "Embedded Analytics JS" }).click();
});
H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });
@@ -123,7 +109,7 @@ H.describeWithSnowplow(suiteTitle, () => {
H.openSharingMenu("Embed");
H.getEmbedModalSharingPane().within(() => {
- cy.findByRole("link", { name: "Embedded Analytics JS" }).click();
+ cy.findByRole("button", { name: "Embedded Analytics JS" }).click();
});
H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css
index 378d46f8378..3dd371a8721 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css
@@ -1,3 +1,7 @@
+.EmbedPreviewIframe {
+ box-shadow: 0 6px 24px 0 rgba(0, 0, 0, 0.1);
+}
+
.EmbedPreviewIframe > * {
/* makes the metabase-* elements full height */
height: 100%;
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx
index 674d5458943..f3502fbcfdb 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx
@@ -6,7 +6,6 @@ import {
useRef,
useState,
} from "react";
-import { useSearchParam } from "react-use";
import { match } from "ts-pattern";
import { useSetting } from "metabase/common/hooks";
@@ -38,8 +37,6 @@ export const SdkIframeEmbedPreview = () => {
const { settings } = useSdkIframeEmbedSetupContext();
const [isLoading, setIsLoading] = useState(true);
- const localeOverride = useSearchParam("locale");
-
const instanceUrl = useSetting("site-url");
const applicationColors = useSetting("application-colors");
@@ -85,10 +82,9 @@ export const SdkIframeEmbedPreview = () => {
() => ({
instanceUrl,
theme: derivedTheme,
- ...(localeOverride ? { locale: localeOverride } : {}),
useExistingUserSession: true,
}),
- [instanceUrl, localeOverride, derivedTheme],
+ [instanceUrl, derivedTheme],
);
// initial configuration, needed so that the element finds the config on first render
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.module.css b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.module.css
index a30dd5dbc65..69f3871123b 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.module.css
@@ -14,10 +14,10 @@
width: 4px;
height: 100%;
cursor: col-resize;
- background-color: var(--mb-color-border);
position: absolute;
right: 0;
top: 0;
+ transition: background-color 0.4s ease;
}
.Sidebar {
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupModal.tsx
similarity index 82%
rename from enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.tsx
rename to enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupModal.tsx
index 4398077f3c2..365d82dcb14 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetup.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupModal.tsx
@@ -8,6 +8,9 @@ import "react-resizable/css/styles.css";
import noResultsSource from "assets/img/no_results.svg";
import { useUpdateSettingsMutation } from "metabase/api";
import { useSetting } from "metabase/common/hooks";
+import { useDispatch } from "metabase/lib/redux";
+import type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";
+import { closeModal } from "metabase/redux/ui";
import {
Box,
Button,
@@ -16,6 +19,7 @@ import {
Group,
Icon,
Image,
+ Modal,
Stack,
} from "metabase/ui";
import type { SettingKey } from "metabase-types/api";
@@ -28,6 +32,7 @@ import S from "./SdkIframeEmbedSetup.module.css";
import { SdkIframeEmbedSetupProvider } from "./SdkIframeEmbedSetupProvider";
export const SdkIframeEmbedSetupContent = () => {
+ const dispatch = useDispatch();
const [updateSettings] = useUpdateSettingsMutation();
const { currentStep, settings } = useSdkIframeEmbedSetupContext();
@@ -44,7 +49,7 @@ export const SdkIframeEmbedSetupContent = () => {
updateSettings({ [settingKey]: true });
- window.history.back();
+ dispatch(closeModal());
}
const nextStepButton = match(currentStep)
@@ -96,6 +101,8 @@ export const SdkIframeEmbedSetupContent = () => {
<Box className={S.PreviewPanel}>
<Stack h="100%">
+ <Modal.CloseButton />
+
{isSimpleEmbeddingEnabled ? (
<SdkIframeEmbedPreview />
) : (
@@ -129,8 +136,22 @@ const SidebarResizer = ({ children }: { children: React.ReactNode }) => {
);
};
-export const SdkIframeEmbedSetup = () => (
- <SdkIframeEmbedSetupProvider>
- <SdkIframeEmbedSetupContent />
- </SdkIframeEmbedSetupProvider>
+export const SdkIframeEmbedSetupModal = ({
+ opened,
+ onClose,
+ initialState,
+}: SdkIframeEmbedSetupModalProps) => (
+ <Modal
+ opened={opened}
+ fullScreen
+ withCloseButton={false}
+ transitionProps={{ transition: "fade", duration: 200 }}
+ onClose={onClose}
+ >
+ <Modal.Content style={{ overflow: "hidden" }}>
+ <SdkIframeEmbedSetupProvider initialState={initialState}>
+ <SdkIframeEmbedSetupContent />
+ </SdkIframeEmbedSetupProvider>
+ </Modal.Content>
+ </Modal>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupProvider.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupProvider.tsx
index d2ccd2eef39..7366e63f614 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupProvider.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedSetupProvider.tsx
@@ -1,7 +1,7 @@
import { type ReactNode, useMemo, useState } from "react";
-import { useLocation } from "react-use";
import { useSearchQuery } from "metabase/api";
+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";
import {
SdkIframeEmbedSetupContext,
@@ -14,21 +14,18 @@ import {
useRecentItems,
} from "../hooks";
import { useSdkIframeEmbedSettings } from "../hooks/use-sdk-iframe-embed-settings";
-import type {
- SdkIframeEmbedSetupStep,
- SdkIframeEmbedSetupUrlParams,
-} from "../types";
+import type { SdkIframeEmbedSetupStep } from "../types";
import { getExperienceFromSettings } from "../utils/get-default-sdk-iframe-embed-setting";
interface SdkIframeEmbedSetupProviderProps {
children: ReactNode;
+ initialState: SdkIframeEmbedSetupModalInitialState | undefined;
}
export const SdkIframeEmbedSetupProvider = ({
children,
+ initialState,
}: SdkIframeEmbedSetupProviderProps) => {
- const location = useLocation();
-
// We don't want to re-fetch the recent items every time we switch between
// steps, therefore we load recent items once in the provider.
const {
@@ -46,27 +43,15 @@ export const SdkIframeEmbedSetupProvider = ({
const modelCount = searchData?.total ?? 0;
- // EmbeddingHub passes `auth_method`.
- // EmbedContentModal passes `resource_type` and `resource_id`.
- const urlParams: SdkIframeEmbedSetupUrlParams = useMemo(() => {
- const params = new URLSearchParams(location.search);
-
- return {
- authMethod: params.get("auth_method"),
- resourceType: params.get("resource_type"),
- resourceId: params.get("resource_id"),
- };
- }, [location.search]);
-
// Default to the embed options step if both resource type and id are provided.
// This is to skip the experience and resource selection steps as we know both.
const defaultStep: SdkIframeEmbedSetupStep = useMemo(() => {
- if (urlParams.resourceType !== null && urlParams.resourceId !== null) {
+ if (!!initialState?.resourceType && !!initialState?.resourceId) {
return "select-embed-options";
}
return "select-embed-experience";
- }, [urlParams]);
+ }, [initialState]);
const [currentStep, setCurrentStep] =
useState<SdkIframeEmbedSetupStep>(defaultStep);
@@ -78,7 +63,7 @@ export const SdkIframeEmbedSetupProvider = ({
replaceSettings,
updateSettings,
} = useSdkIframeEmbedSettings({
- urlParams,
+ initialState,
recentDashboards,
isRecentsLoading,
modelCount,
@@ -108,6 +93,7 @@ export const SdkIframeEmbedSetupProvider = ({
const value: SdkIframeEmbedSetupContextType = {
currentStep,
setCurrentStep,
+ initialState,
experience,
resource,
isError,
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx
index f46185ab5e5..04d1d447b72 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx
@@ -4,26 +4,25 @@ import { screen } from "__support__/ui";
import { setup, waitForUpdateSetting } from "./test-setup";
-const mockLocation = (search: string) =>
- jest.mock("react-use", () => ({ useLocation: jest.fn(() => ({ search })) }));
-
describe("Embed flow > embedding hub step completion tracking", () => {
afterEach(() => {
jest.clearAllMocks();
});
it.each([
- { authMethod: "user_session", trigger: "copy" },
- { authMethod: "sso", trigger: "copy" },
- { authMethod: "user_session", trigger: "done" },
- { authMethod: "sso", trigger: "done" },
+ { useExistingUserSession: true, trigger: "copy" },
+ { useExistingUserSession: false, trigger: "copy" },
+ { useExistingUserSession: true, trigger: "done" },
+ { useExistingUserSession: false, trigger: "done" },
])(
"updates setting on $trigger with $authMethod",
- async ({ authMethod, trigger }) => {
- mockLocation(`auth_method=${authMethod}`);
+ async ({ useExistingUserSession, trigger }) => {
setup({
- jwtReady: authMethod === "sso",
+ jwtReady: !useExistingUserSession,
simpleEmbeddingEnabled: true,
+ initialState: {
+ useExistingUserSession,
+ },
});
await userEvent.click(screen.getByRole("button", { name: "Next" }));
@@ -31,7 +30,7 @@ describe("Embed flow > embedding hub step completion tracking", () => {
await userEvent.click(screen.getByRole("button", { name: "Get code" }));
const authRadio = screen.getByDisplayValue(
- authMethod === "user_session" ? "user-session" : "sso",
+ useExistingUserSession ? "user-session" : "sso",
);
await userEvent.click(authRadio);
@@ -43,10 +42,9 @@ describe("Embed flow > embedding hub step completion tracking", () => {
await userEvent.click(actionButton);
- const expectedSetting =
- authMethod === "sso"
- ? "embedding-hub-production-embed-snippet-created"
- : "embedding-hub-test-embed-snippet-created";
+ const expectedSetting = !useExistingUserSession
+ ? "embedding-hub-production-embed-snippet-created"
+ : "embedding-hub-test-embed-snippet-created";
const matchingRequest = await waitForUpdateSetting(expectedSetting, true);
expect(matchingRequest).toBeDefined();
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx
index 77d5050e2a5..4e04240c210 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx
@@ -120,7 +120,10 @@ describe("Embed flow > pre-selection via url parameter", () => {
setup({
simpleEmbeddingEnabled: true,
- urlSearchParams: "?resource_type=question&resource_id=456",
+ initialState: {
+ resourceType: "question",
+ resourceId: 456,
+ },
});
// Starts at the "select embed options" step.
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx
index 45710e28a48..9d9f03ee985 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx
@@ -8,6 +8,7 @@ import {
setupUpdateSettingsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, waitFor } from "__support__/ui";
+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";
import {
createMockDashboard,
createMockDashboardQueryMetadata,
@@ -18,19 +19,12 @@ import {
createMockState,
} from "metabase-types/store/mocks";
-import { SdkIframeEmbedSetup } from "../SdkIframeEmbedSetup";
-
-const mockUseLocation = jest.fn();
-
-jest.mock("react-use", () => ({
- ...jest.requireActual("react-use"),
- useLocation: () => mockUseLocation(),
-}));
+import { SdkIframeEmbedSetupModal } from "../SdkIframeEmbedSetupModal";
export const setup = (options?: {
simpleEmbeddingEnabled?: boolean;
jwtReady?: boolean;
- urlSearchParams?: string;
+ initialState?: SdkIframeEmbedSetupModalInitialState;
}) => {
const mockDatabase = createMockDatabase();
const mockDashboard = createMockDashboard();
@@ -46,19 +40,25 @@ export const setup = (options?: {
setupUpdateSettingsEndpoint();
setupUpdateSettingEndpoint();
- mockUseLocation.mockReturnValue({
- search: options?.urlSearchParams || "",
- });
-
- renderWithProviders(<SdkIframeEmbedSetup />, {
- storeInitialState: createMockState({
- settings: createMockSettingsState({
- "enable-embedding-simple": options?.simpleEmbeddingEnabled ?? false,
- "jwt-enabled": options?.jwtReady ?? false,
- "jwt-configured": options?.jwtReady ?? false,
+ renderWithProviders(
+ <SdkIframeEmbedSetupModal
+ opened
+ initialState={{
+ useExistingUserSession: true,
+ ...options?.initialState,
+ }}
+ onClose={jest.fn()}
+ />,
+ {
+ storeInitialState: createMockState({
+ settings: createMockSettingsState({
+ "enable-embedding-simple": options?.simpleEmbeddingEnabled ?? false,
+ "jwt-enabled": options?.jwtReady ?? false,
+ "jwt-configured": options?.jwtReady ?? false,
+ }),
}),
- }),
- });
+ },
+ );
};
export async function waitForPutRequests() {
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/context.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/context.ts
index 635e598f79e..470dabf67ba 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/context.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/context.ts
@@ -1,5 +1,6 @@
import { createContext, useContext } from "react";
+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";
import type { EmbeddingParametersValues } from "metabase/public/lib/types";
import type { Card, Dashboard, Parameter } from "metabase-types/api";
@@ -16,6 +17,9 @@ export interface SdkIframeEmbedSetupContextType {
currentStep: SdkIframeEmbedSetupStep;
setCurrentStep: (step: SdkIframeEmbedSetupStep) => void;
+ // Initial state
+ initialState: SdkIframeEmbedSetupModalInitialState | undefined;
+
experience: SdkIframeEmbedSetupExperience;
// Loaded resources
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-sdk-iframe-embed-settings.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-sdk-iframe-embed-settings.ts
index 81cb0823ab5..2e3e02f715b 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-sdk-iframe-embed-settings.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/hooks/use-sdk-iframe-embed-settings.ts
@@ -3,6 +3,7 @@ import { P, match } from "ts-pattern";
import _ from "underscore";
import { useUserSetting } from "metabase/common/hooks";
+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";
import {
EMBED_FALLBACK_DASHBOARD_ID,
USER_SETTINGS_DEBOUNCE_MS,
@@ -10,7 +11,6 @@ import {
import type {
SdkIframeEmbedSetupRecentItem,
SdkIframeEmbedSetupSettings,
- SdkIframeEmbedSetupUrlParams,
} from "metabase-enterprise/embedding_iframe_sdk_setup/types";
import { trackEmbedWizardOpened } from "../analytics";
@@ -48,12 +48,12 @@ const usePersistedSettings = () => {
};
export const useSdkIframeEmbedSettings = ({
- urlParams,
+ initialState,
recentDashboards,
isRecentsLoading,
modelCount,
}: {
- urlParams: SdkIframeEmbedSetupUrlParams;
+ initialState: SdkIframeEmbedSetupModalInitialState | undefined;
recentDashboards: SdkIframeEmbedSetupRecentItem[];
isRecentsLoading: boolean;
modelCount: number;
@@ -62,18 +62,22 @@ export const useSdkIframeEmbedSettings = ({
const [persistedSettings, persistSettings] = usePersistedSettings();
const defaultSettings = useMemo(() => {
- return match([urlParams.resourceType, urlParams.resourceId])
- .with(["dashboard", P.nonNullable], ([, resourceId]) =>
- getDefaultSdkIframeEmbedSettings({
- experience: "dashboard",
- resourceId,
- }),
+ return match(initialState)
+ .with(
+ { resourceType: "dashboard", resourceId: P.nonNullable },
+ (initialState) =>
+ getDefaultSdkIframeEmbedSettings({
+ experience: "dashboard",
+ resourceId: initialState.resourceId,
+ }),
)
- .with(["question", P.nonNullable], ([, resourceId]) =>
- getDefaultSdkIframeEmbedSettings({
- experience: "chart",
- resourceId,
- }),
+ .with(
+ { resourceType: "question", resourceId: P.nonNullable },
+ (initialState) =>
+ getDefaultSdkIframeEmbedSettings({
+ experience: "chart",
+ resourceId: initialState.resourceId,
+ }),
)
.otherwise(() =>
getDefaultSdkIframeEmbedSettings({
@@ -81,7 +85,7 @@ export const useSdkIframeEmbedSettings = ({
resourceId: recentDashboards[0]?.id ?? EMBED_FALLBACK_DASHBOARD_ID,
}),
);
- }, [recentDashboards, urlParams]);
+ }, [recentDashboards, initialState]);
const [rawSettings, setRawSettings] = useState<SdkIframeEmbedSetupSettings>();
@@ -137,10 +141,10 @@ export const useSdkIframeEmbedSettings = ({
...settings,
...persistedSettings,
- // Override the persisted settings if `auth_method` is specified.
+ // Override the persisted settings if `useExistingUserSession` is specified.
// This is used for Embedding Hub.
- ...(urlParams.authMethod !== null && {
- useExistingUserSession: urlParams.authMethod === "user_session",
+ ...(initialState?.useExistingUserSession !== undefined && {
+ useExistingUserSession: initialState.useExistingUserSession,
}),
});
@@ -153,7 +157,7 @@ export const useSdkIframeEmbedSettings = ({
isEmbedSettingsLoaded,
settings,
isRecentsLoading,
- urlParams,
+ initialState,
]);
return {
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts
index 087f5ba7d3b..a88d615e1be 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts
@@ -1,12 +1,13 @@
import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
-import { SdkIframeEmbedSetup } from "./components/SdkIframeEmbedSetup";
+import { SdkIframeEmbedSetupModal } from "./components/SdkIframeEmbedSetupModal";
// Feature gate the embed setup for gradual rollouts.
// In the future, we may drop this to enable users to try out new iframe embedding.
if (hasPremiumFeature("embedding_simple")) {
PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = () => true;
PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.shouldShowEmbedInNewItemMenu = () => true;
- PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetup = SdkIframeEmbedSetup;
+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetupModal =
+ SdkIframeEmbedSetupModal;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/types.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/types.ts
index cf3863371d9..c58e857d0bd 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/types.ts
@@ -51,9 +51,3 @@ export type SdkIframeEmbedSetupSettings = Omit<
"instanceUrl"
> &
SdkIframeEmbedSetupTemplateSettings;
-
-export type SdkIframeEmbedSetupUrlParams = {
- authMethod?: string | null;
- resourceType?: string | null;
- resourceId?: string | null;
-};
diff --git a/frontend/src/metabase-types/store/mocks/modal.ts b/frontend/src/metabase-types/store/mocks/modal.ts
new file mode 100644
index 00000000000..22478efdf5b
--- /dev/null
+++ b/frontend/src/metabase-types/store/mocks/modal.ts
@@ -0,0 +1,11 @@
+import type { ModalState } from "metabase-types/store/modal";
+
+export const createMockModalState = (
+ opts?: Partial<ModalState>,
+): ModalState => {
+ return {
+ id: null,
+ props: null,
+ ...opts,
+ };
+};
diff --git a/frontend/src/metabase-types/store/mocks/state.ts b/frontend/src/metabase-types/store/mocks/state.ts
index 2ea390c41c5..71c9a694a66 100644
--- a/frontend/src/metabase-types/store/mocks/state.ts
+++ b/frontend/src/metabase-types/store/mocks/state.ts
@@ -10,6 +10,7 @@ import { createMockDashboardState } from "./dashboard";
import { createMockEmbedState } from "./embed";
import { createMockEmbeddingDataPickerState } from "./embedding-data-picker";
import { createMockNormalizedEntitiesState } from "./entities";
+import { createMockModalState } from "./modal";
import { createMockParametersState } from "./parameters";
import { createMockQueryBuilderState } from "./qb";
import { createMockRequestsState } from "./requests";
@@ -47,7 +48,7 @@ export function createMockState(opts: any) {
present: createMockVisualizerState(),
future: [],
},
- modal: null,
+ modal: createMockModalState(),
...opts,
};
}
diff --git a/frontend/src/metabase-types/store/modal.ts b/frontend/src/metabase-types/store/modal.ts
new file mode 100644
index 00000000000..03b7bbfbf6b
--- /dev/null
+++ b/frontend/src/metabase-types/store/modal.ts
@@ -0,0 +1,12 @@
+export type ModalName =
+ | null
+ | "collection"
+ | "dashboard"
+ | "action"
+ | "help"
+ | "embed";
+
+export type ModalState<TProps = Record<string, unknown>> = {
+ id: ModalName | null;
+ props: TProps | null;
+};
diff --git a/frontend/src/metabase-types/store/state.ts b/frontend/src/metabase-types/store/state.ts
index 02677575905..3def458ed3a 100644
--- a/frontend/src/metabase-types/store/state.ts
+++ b/frontend/src/metabase-types/store/state.ts
@@ -11,6 +11,7 @@ import type { DownloadsState } from "./downloads";
import type { EmbedState } from "./embed";
import type { EmbeddingDataPickerState } from "./embedding-data-picker";
import type { EntitiesState } from "./entities";
+import type { ModalState } from "./modal";
import type { ParametersState } from "./parameters";
import type { QueryBuilderState } from "./qb";
import type { RequestsState } from "./requests";
@@ -20,8 +21,6 @@ import type { UndoState } from "./undo";
import type { FileUploadState } from "./upload";
import type { VisualizerState } from "./visualizer";
-type ModalName = null | "collection" | "dashboard" | "action" | "help";
-
type MetabaseApiState = ReturnType<typeof Api.reducer>;
export interface State {
@@ -40,7 +39,7 @@ export interface State {
settings: SettingsState;
setup: SetupState;
upload: FileUploadState;
- modal: ModalName;
+ modal: ModalState;
undo: UndoState;
downloads: DownloadsState;
visualizer: {
diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx
index 5c43603d1a2..c6c63b26d75 100644
--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx
+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx
@@ -1,5 +1,4 @@
import cx from "classnames";
-import { Link } from "react-router";
import { match } from "ts-pattern";
import { c, jt, t } from "ttag";
@@ -14,11 +13,13 @@ import { UpsellSdkLink } from "metabase/admin/upsells/UpsellSdkLink";
import ExternalLink from "metabase/common/components/ExternalLink";
import { useDocsUrl, useSetting, useUrlWithUtm } from "metabase/common/hooks";
import CS from "metabase/css/core/index.css";
+import { useDispatch } from "metabase/lib/redux";
import { isEEBuild } from "metabase/lib/utils";
import {
PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,
PLUGIN_EMBEDDING_SDK,
} from "metabase/plugins";
+import { setOpenModalWithProps } from "metabase/redux/ui";
import { Box, Button, Group, HoverCard, Icon, Stack, Text } from "metabase/ui";
import { AdminSettingInput } from "../../widgets/AdminSettingInput";
@@ -33,6 +34,7 @@ const utmTags = {
};
export function EmbeddingSdkSettings() {
+ const dispatch = useDispatch();
const isEE = isEEBuild();
const isReactSdkEnabled = useSetting("enable-embedding-sdk");
@@ -153,11 +155,15 @@ export function EmbeddingSdkSettings() {
}
actionButton={
isSimpleEmbedFeatureAvailable && (
- <Link to="/embed-js" className={CS.cursorPointer}>
- <Button variant="brand" size="sm">
- {t`New embed`}
- </Button>
- </Link>
+ <Button
+ variant="brand"
+ size="sm"
+ onClick={() => {
+ dispatch(setOpenModalWithProps({ id: "embed" }));
+ }}
+ >
+ {t`New embed`}
+ </Button>
)
}
testId="sdk-setting-card"
diff --git a/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsx b/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsx
index 616bc604817..55034591c95 100644
--- a/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsx
+++ b/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsx
@@ -1,8 +1,17 @@
import { t } from "ttag";
import { useHasTokenFeature } from "metabase/common/hooks";
+import { useDispatch } from "metabase/lib/redux";
import { isEEBuild } from "metabase/lib/utils";
-import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";
+import {
+ PLUGIN_ADMIN_SETTINGS,
+ type SdkIframeEmbedSetupModalProps,
+} from "metabase/plugins";
+import type {
+ EmbedResource,
+ EmbedResourceType,
+} from "metabase/public/lib/types";
+import { setOpenModalWithProps } from "metabase/redux/ui";
import { Box } from "metabase/ui";
import { UpsellCta } from "./components/UpsellCta";
@@ -10,10 +19,16 @@ import { trackUpsellClicked } from "./components/analytics";
import { useUpsellLink } from "./components/use-upsell-link";
export function useUpsellEmbedJsCta({
- embedFlowUrl,
+ resource,
+ resourceType,
+ closeModal,
}: {
- embedFlowUrl: string;
+ resource: EmbedResource;
+ resourceType: EmbedResourceType;
+ closeModal: () => void;
}) {
+ const dispatch = useDispatch();
+
const campaign = "embedded-analytics-js";
const location = "static-embed-popover";
@@ -33,7 +48,26 @@ export function useUpsellEmbedJsCta({
});
if (isEmbedJsEnabled) {
- return { internalLink: embedFlowUrl };
+ return {
+ openEmbedFlow: () => {
+ const modalProps: Pick<SdkIframeEmbedSetupModalProps, "initialState"> =
+ {
+ initialState: {
+ resourceType,
+ resourceId: resource.id,
+ },
+ };
+
+ closeModal();
+
+ dispatch(
+ setOpenModalWithProps({
+ id: "embed",
+ props: modalProps,
+ }),
+ );
+ },
+ };
}
return {
@@ -43,9 +77,17 @@ export function useUpsellEmbedJsCta({
};
}
-export function UpsellEmbedJsCta({ embedFlowUrl }: { embedFlowUrl: string }) {
- const { url, internalLink, triggerUpsellFlow, trackUpsell } =
- useUpsellEmbedJsCta({ embedFlowUrl });
+export function UpsellEmbedJsCta({
+ resource,
+ resourceType,
+ closeModal,
+}: {
+ resource: EmbedResource;
+ resourceType: EmbedResourceType;
+ closeModal: () => void;
+}) {
+ const { openEmbedFlow, url, triggerUpsellFlow, trackUpsell } =
+ useUpsellEmbedJsCta({ resource, resourceType, closeModal });
if (!isEEBuild()) {
return null;
@@ -54,8 +96,14 @@ export function UpsellEmbedJsCta({ embedFlowUrl }: { embedFlowUrl: string }) {
return (
<Box>
<UpsellCta
- onClick={triggerUpsellFlow}
- internalLink={internalLink}
+ onClick={() => {
+ if (triggerUpsellFlow) {
+ triggerUpsellFlow();
+ } else if (openEmbedFlow) {
+ openEmbedFlow();
+ }
+ }}
+ internalLink={undefined}
buttonText={t`Try for free`}
url={url}
onClickCapture={() => trackUpsell?.()}
diff --git a/frontend/src/metabase/api/settings.ts b/frontend/src/metabase/api/settings.ts
index 5e30497c1ff..3e42134fae5 100644
--- a/frontend/src/metabase/api/settings.ts
+++ b/frontend/src/metabase/api/settings.ts
@@ -65,7 +65,10 @@ export const settingsApi = Api.injectEndpoints({
body: settings,
}),
invalidatesTags: (_, error) =>
- invalidateTags(error, [tag("session-properties")]),
+ invalidateTags(error, [
+ tag("session-properties"),
+ listTag("embedding-hub-checklist"),
+ ]),
}),
}),
});
diff --git a/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx b/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx
index 871c40365dd..31e226922ba 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx
@@ -66,6 +66,7 @@ export const DashboardSharingEmbeddingModal = ({
})
}
getPublicUrl={getPublicUrl}
+ onClose={onClose}
/>
)}
</EmbedModal>
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.tsx b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.tsx
index 992c1e929fd..25f687dcb55 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.tsx
+++ b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.tsx
@@ -4,12 +4,14 @@ import { P, match } from "ts-pattern";
import { CreateDashboardModal } from "metabase/dashboard/containers/CreateDashboardModal";
import { AddDataModal } from "metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal";
-import { useCompletedEmbeddingHubSteps } from "../hooks";
+import {
+ useCompletedEmbeddingHubSteps,
+ useGetEmbeddingHubSteps,
+} from "../hooks";
import type {
EmbeddingHubModalToTrigger,
EmbeddingHubStepId,
} from "../types/embedding-checklist";
-import { getEmbeddingHubSteps } from "../utils";
import { EmbeddingHubXrayPickerModal } from "./EmbeddingHubXrayPickerModal";
import {
@@ -19,7 +21,7 @@ import {
} from "./StepperWithCards/StepperWithCards";
export const EmbeddingHub = () => {
- const embeddingSteps = useMemo(() => getEmbeddingHubSteps(), []);
+ const embeddingSteps = useGetEmbeddingHubSteps();
const { data: completedSteps } = useCompletedEmbeddingHubSteps();
const [openedModal, setOpenedModal] =
@@ -43,6 +45,10 @@ export const EmbeddingHub = () => {
const clickAction: StepperCardClickAction | undefined = match(action)
.with({ to: P.string }, ({ to }) => ({ type: "link" as const, to }))
+ .with({ onClick: P.nonNullable }, ({ onClick }) => ({
+ type: "click" as const,
+ onClick,
+ }))
.with({ docsPath: P.string }, ({ docsPath }) => ({
type: "docs" as const,
docsPath,
diff --git a/frontend/src/metabase/embedding/embedding-hub/hooks/index.ts b/frontend/src/metabase/embedding/embedding-hub/hooks/index.ts
index a4d6d73369d..b467db7e0f2 100644
--- a/frontend/src/metabase/embedding/embedding-hub/hooks/index.ts
+++ b/frontend/src/metabase/embedding/embedding-hub/hooks/index.ts
@@ -1 +1,2 @@
export { useCompletedEmbeddingHubSteps } from "./use-completed-embedding-hub-steps";
+export { useGetEmbeddingHubSteps } from "./use-get-embedding-hub-steps";
diff --git a/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.ts b/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.ts
new file mode 100644
index 00000000000..f22efa6de4b
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.ts
@@ -0,0 +1,158 @@
+import { useCallback, useMemo } from "react";
+import { t } from "ttag";
+
+import { useDispatch } from "metabase/lib/redux";
+import type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";
+import { setOpenModalWithProps } from "metabase/redux/ui";
+
+import type { EmbeddingHubStep } from "../types";
+
+export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {
+ const dispatch = useDispatch();
+
+ const openEmbedModal = useCallback(
+ (props: Pick<SdkIframeEmbedSetupModalProps, "initialState">) => {
+ dispatch(
+ setOpenModalWithProps({
+ id: "embed",
+ props,
+ }),
+ );
+ },
+ [dispatch],
+ );
+
+ return useMemo(() => {
+ const TEST_EMBED: EmbeddingHubStep = {
+ id: "create-test-embed",
+ title: t`Create embed`,
+ icon: "test_tube",
+ actions: [
+ {
+ title: t`Get embed snippet`,
+ description: t`Embed a dashboard, question, the query builder or the collection browser. Configure the experience and customize the appearance.`,
+ onClick: () => {
+ openEmbedModal({
+ initialState: { useExistingUserSession: true },
+ });
+ },
+ variant: "outline",
+ },
+ ],
+ image: {
+ src: "app/assets/img/embedding_hub_create_embed.png",
+ srcSet: "app/assets/img/[email protected] 2x",
+ alt: t`Screenshot of creating an embed`,
+ },
+ };
+
+ const ADD_DATA: EmbeddingHubStep = {
+ id: "add-data",
+ title: t`Add your data`,
+ icon: "add_data",
+ image: {
+ src: "app/assets/img/onboarding_data_diagram.png",
+ srcSet: "app/assets/img/[email protected] 2x",
+ alt: t`Data sources and ETL diagram`,
+ },
+ actions: [
+ {
+ title: t`Connect a database`,
+ description: t`Connect your own database or upload a CSV and start working with your real data.`,
+ modal: { type: "add-data", initialTab: "db" },
+ variant: "outline",
+ },
+ ],
+ };
+
+ const CREATE_DASHBOARD: EmbeddingHubStep = {
+ id: "create-dashboard",
+ title: t`Prepare data`,
+ icon: "dashboard",
+ video: {
+ id: "FOAXF4p1AL0",
+ trackingId: "COmu2w0SqGagUoVp",
+ title: t`How to find and use X-rays?`,
+ },
+ actions: [
+ {
+ title: t`Create a dashboard`,
+ description: t`Automatically generate a dashboard from your data using x-rays.`,
+ modal: { type: "xray-dashboard" },
+ variant: "outline",
+ },
+ {
+ title: t`Create models`,
+ description: t`Set up data models for your embedded analytics.`,
+ to: "/model/new",
+ optional: true,
+ stepId: "create-models",
+ },
+ ],
+ };
+
+ const SECURE_EMBEDS: EmbeddingHubStep = {
+ id: "secure-embeds",
+ title: t`Security and permissions`,
+ icon: "lock",
+ actions: [
+ {
+ title: t`Configure SSO`,
+ description: t`Configure JWT or SAML authentication to ensure only authorized users can access your embeds.`,
+ docsPath: "embedding/embedded-analytics-js#set-up-sso",
+ variant: "outline",
+ stepId: "secure-embeds",
+ },
+ {
+ title: t`Configure data permissions`,
+ docsPath:
+ "permissions/embedding#one-database-for-all-customers-commingled-setups",
+ description: t`Manage permissions to limit what data your users can access.`,
+ variant: "outline",
+ stepId: "configure-row-column-security",
+ optional: true,
+ },
+ ],
+ image: {
+ src: "app/assets/img/embedding_hub_secure_embeds_diagram.png",
+ srcSet: "app/assets/img/[email protected] 2x",
+ alt: t`Diagram of the SSO authentication workflow`,
+ },
+ };
+
+ const EMBED_PRODUCTION: EmbeddingHubStep = {
+ id: "embed-production",
+ title: t`Deployment`,
+ icon: "code_block",
+ actions: [
+ {
+ title: t`Embed in production`,
+ description: t`Deploy your embedded dashboard to a production environment and share with your users.`,
+ onClick: () => {
+ openEmbedModal({
+ initialState: { useExistingUserSession: false },
+ });
+ },
+ variant: "outline",
+ },
+ ],
+ image: {
+ src: "app/assets/img/embedding_hub_create_embed.png",
+ srcSet: "app/assets/img/[email protected] 2x",
+ alt: t`Screenshot of creating an embed`,
+ },
+ infoAlert: {
+ type: "locked",
+ message: t`Configure SSO authentication to unlock this step.`,
+ },
+ };
+
+ return [
+ ADD_DATA,
+ CREATE_DASHBOARD,
+ TEST_EMBED,
+ SECURE_EMBEDS,
+ EMBED_PRODUCTION,
+ ];
+ }, [openEmbedModal]);
+};
diff --git a/frontend/src/metabase/embedding/embedding-hub/index.ts b/frontend/src/metabase/embedding/embedding-hub/index.ts
index 474613d4483..777db88cce3 100644
--- a/frontend/src/metabase/embedding/embedding-hub/index.ts
+++ b/frontend/src/metabase/embedding/embedding-hub/index.ts
@@ -1,4 +1,3 @@
export * from "./components";
-export * from "./utils";
export * from "./hooks";
export * from "./types";
diff --git a/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts b/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts
index 135f94396f3..59996f08f88 100644
--- a/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts
+++ b/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts
@@ -43,6 +43,11 @@ interface EmbeddingHubAction {
/** Internal link to a Metabase route. */
to?: string;
+ /**
+ * Click handler
+ */
+ onClick?: () => void;
+
/** Path of the documentation page, e.g. `embedding/embedded-analytics-js` */
docsPath?: string;
diff --git a/frontend/src/metabase/embedding/embedding-hub/utils/embedding-hub-steps.ts b/frontend/src/metabase/embedding/embedding-hub/utils/embedding-hub-steps.ts
deleted file mode 100644
index 3c789671721..00000000000
--- a/frontend/src/metabase/embedding/embedding-hub/utils/embedding-hub-steps.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { t } from "ttag";
-
-import type { EmbeddingHubStep } from "../types";
-
-export const getEmbeddingHubSteps = (): EmbeddingHubStep[] => {
- const TEST_EMBED: EmbeddingHubStep = {
- id: "create-test-embed",
- title: t`Create embed`,
- icon: "test_tube",
- actions: [
- {
- title: t`Get embed snippet`,
- description: t`Embed a dashboard, question, the query builder or the collection browser. Configure the experience and customize the appearance.`,
- to: "/embed-js?auth_method=user_session",
- variant: "outline",
- },
- ],
- image: {
- src: "app/assets/img/embedding_hub_create_embed.png",
- srcSet: "app/assets/img/[email protected] 2x",
- alt: t`Screenshot of creating an embed`,
- },
- };
-
- const ADD_DATA: EmbeddingHubStep = {
- id: "add-data",
- title: t`Add your data`,
- icon: "add_data",
- image: {
- src: "app/assets/img/onboarding_data_diagram.png",
- srcSet: "app/assets/img/[email protected] 2x",
- alt: t`Data sources and ETL diagram`,
- },
- actions: [
- {
- title: t`Connect a database`,
- description: t`Connect your own database or upload a CSV and start working with your real data.`,
- modal: { type: "add-data", initialTab: "db" },
- variant: "outline",
- },
- ],
- };
-
- const CREATE_DASHBOARD: EmbeddingHubStep = {
- id: "create-dashboard",
- title: t`Prepare data`,
- icon: "dashboard",
- video: {
- id: "FOAXF4p1AL0",
- trackingId: "COmu2w0SqGagUoVp",
- title: t`How to find and use X-rays?`,
- },
- actions: [
- {
- title: t`Create a dashboard`,
- description: t`Automatically generate a dashboard from your data using x-rays.`,
- modal: { type: "xray-dashboard" },
- variant: "outline",
- },
- {
- title: t`Create models`,
- description: t`Set up data models for your embedded analytics.`,
- to: "/model/new",
- optional: true,
- stepId: "create-models",
- },
- ],
- };
-
- const SECURE_EMBEDS: EmbeddingHubStep = {
- id: "secure-embeds",
- title: t`Security and permissions`,
- icon: "lock",
- actions: [
- {
- title: t`Configure SSO`,
- description: t`Configure JWT or SAML authentication to ensure only authorized users can access your embeds.`,
- docsPath: "embedding/embedded-analytics-js#set-up-sso",
- variant: "outline",
- stepId: "secure-embeds",
- },
- {
- title: t`Configure data permissions`,
- docsPath:
- "permissions/embedding#one-database-for-all-customers-commingled-setups",
- description: t`Manage permissions to limit what data your users can access.`,
- variant: "outline",
- stepId: "configure-row-column-security",
- optional: true,
- },
- ],
- image: {
- src: "app/assets/img/embedding_hub_secure_embeds_diagram.png",
- srcSet: "app/assets/img/[email protected] 2x",
- alt: t`Diagram of the SSO authentication workflow`,
- },
- };
-
- const EMBED_PRODUCTION: EmbeddingHubStep = {
- id: "embed-production",
- title: t`Deployment`,
- icon: "code_block",
- actions: [
- {
- title: t`Embed in production`,
- description: t`Deploy your embedded dashboard to a production environment and share with your users.`,
- to: "/embed-js?auth_method=sso",
- variant: "outline",
- },
- ],
- image: {
- src: "app/assets/img/embedding_hub_create_embed.png",
- srcSet: "app/assets/img/[email protected] 2x",
- alt: t`Screenshot of creating an embed`,
- },
- infoAlert: {
- type: "locked",
- message: t`Configure SSO authentication to unlock this step.`,
- },
- };
-
- return [
- ADD_DATA,
- CREATE_DASHBOARD,
- TEST_EMBED,
- SECURE_EMBEDS,
- EMBED_PRODUCTION,
- ];
-};
diff --git a/frontend/src/metabase/embedding/embedding-hub/utils/index.ts b/frontend/src/metabase/embedding/embedding-hub/utils/index.ts
deleted file mode 100644
index 3b76c3fa01f..00000000000
--- a/frontend/src/metabase/embedding/embedding-hub/utils/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { getEmbeddingHubSteps } from "./embedding-hub-steps";
diff --git a/frontend/src/metabase/lib/objects.ts b/frontend/src/metabase/lib/objects.ts
index bd8bcfb9d52..1b6713a76b2 100644
--- a/frontend/src/metabase/lib/objects.ts
+++ b/frontend/src/metabase/lib/objects.ts
@@ -13,3 +13,50 @@ export const getObjectKeys = <K extends string>(
export const getObjectValues = <V>(obj: Record<string, V>): V[] => {
return Object.values(obj) as V[];
};
+
+export function isSerializable(value: unknown): boolean {
+ if (value === null || value === undefined) {
+ return true;
+ }
+
+ const type = typeof value;
+
+ if (
+ type === "string" ||
+ type === "number" ||
+ type === "boolean" ||
+ type === "bigint"
+ ) {
+ return true;
+ }
+
+ if (type === "function" || type === "symbol") {
+ return false;
+ }
+
+ if (value instanceof Date) {
+ return false;
+ }
+
+ if (type === "object") {
+ const proto = Object.getPrototypeOf(value);
+
+ if (
+ proto === Object.prototype ||
+ proto === Array.prototype ||
+ proto === null
+ ) {
+ if (Array.isArray(value)) {
+ return value.every(isSerializable);
+ }
+
+ return Object.values(value as Record<string, unknown>).every(
+ isSerializable,
+ );
+ }
+
+ return false;
+ }
+
+ return false;
+}
diff --git a/frontend/src/metabase/lib/objects.unit.spec.ts b/frontend/src/metabase/lib/objects.unit.spec.ts
new file mode 100644
index 00000000000..9b6b014f169
--- /dev/null
+++ b/frontend/src/metabase/lib/objects.unit.spec.ts
@@ -0,0 +1,249 @@
+import { isSerializable } from "./objects";
+
+describe("isSerializable", () => {
+ describe("primitive values", () => {
+ it("should return true for null", () => {
+ expect(isSerializable(null)).toBe(true);
+ });
+
+ it("should return true for undefined", () => {
+ expect(isSerializable(undefined)).toBe(true);
+ });
+
+ it("should return true for strings", () => {
+ expect(isSerializable("hello")).toBe(true);
+ expect(isSerializable("")).toBe(true);
+ });
+
+ it("should return true for numbers", () => {
+ expect(isSerializable(42)).toBe(true);
+ expect(isSerializable(0)).toBe(true);
+ expect(isSerializable(-1)).toBe(true);
+ expect(isSerializable(3.14)).toBe(true);
+ });
+
+ it("should return true for booleans", () => {
+ expect(isSerializable(true)).toBe(true);
+ expect(isSerializable(false)).toBe(true);
+ });
+
+ it("should return true for bigint", () => {
+ expect(isSerializable(BigInt(123))).toBe(true);
+ });
+ });
+
+ describe("non-serializable values", () => {
+ it("should return false for functions", () => {
+ expect(isSerializable(() => {})).toBe(false);
+ expect(isSerializable(function () {})).toBe(false);
+ expect(isSerializable(async () => {})).toBe(false);
+ });
+
+ it("should return false for symbols", () => {
+ expect(isSerializable(Symbol("test"))).toBe(false);
+ expect(isSerializable(Symbol.for("test"))).toBe(false);
+ });
+
+ it("should return false for class instances", () => {
+ class MyClass {
+ value = 42;
+ }
+ expect(isSerializable(new MyClass())).toBe(false);
+ });
+
+ it("should return false for Error instances", () => {
+ expect(isSerializable(new Error("test"))).toBe(false);
+ expect(isSerializable(new TypeError("test"))).toBe(false);
+ });
+
+ it("should return false for RegExp instances", () => {
+ expect(isSerializable(/test/)).toBe(false);
+ expect(isSerializable(new RegExp("test"))).toBe(false);
+ });
+
+ it("should return false for Map instances", () => {
+ expect(isSerializable(new Map())).toBe(false);
+ });
+
+ it("should return false for Set instances", () => {
+ expect(isSerializable(new Set())).toBe(false);
+ });
+
+ it("should return false for WeakMap instances", () => {
+ expect(isSerializable(new WeakMap())).toBe(false);
+ });
+
+ it("should return false for WeakSet instances", () => {
+ expect(isSerializable(new WeakSet())).toBe(false);
+ });
+ });
+
+ describe("Date objects", () => {
+ it("should return false for Date instances", () => {
+ expect(isSerializable(new Date())).toBe(false);
+ expect(isSerializable(new Date("2024-01-01"))).toBe(false);
+ });
+ });
+
+ describe("plain objects", () => {
+ it("should return true for empty objects", () => {
+ expect(isSerializable({})).toBe(true);
+ });
+
+ it("should return true for objects with serializable values", () => {
+ expect(
+ isSerializable({
+ name: "test",
+ count: 42,
+ active: true,
+ }),
+ ).toBe(true);
+ });
+
+ it("should return true for nested objects with serializable values", () => {
+ expect(
+ isSerializable({
+ user: {
+ name: "test",
+ metadata: {
+ age: 25,
+ },
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it("should return true for objects created with Object.create(null)", () => {
+ const obj = Object.create(null);
+ obj.key = "value";
+ expect(isSerializable(obj)).toBe(true);
+ });
+
+ it("should return false for objects containing functions", () => {
+ expect(
+ isSerializable({
+ name: "test",
+ callback: () => {},
+ }),
+ ).toBe(false);
+ });
+
+ it("should return false for objects containing symbols", () => {
+ expect(
+ isSerializable({
+ name: "test",
+ sym: Symbol("test"),
+ }),
+ ).toBe(false);
+ });
+
+ it("should return false for nested objects containing functions", () => {
+ expect(
+ isSerializable({
+ user: {
+ name: "test",
+ onClick: () => {},
+ },
+ }),
+ ).toBe(false);
+ });
+ });
+
+ describe("arrays", () => {
+ it("should return true for empty arrays", () => {
+ expect(isSerializable([])).toBe(true);
+ });
+
+ it("should return true for arrays with serializable values", () => {
+ expect(isSerializable([1, 2, 3])).toBe(true);
+ expect(isSerializable(["a", "b", "c"])).toBe(true);
+ expect(isSerializable([true, false])).toBe(true);
+ });
+
+ it("should return true for arrays with mixed serializable types", () => {
+ expect(isSerializable([1, "test", true, null])).toBe(true);
+ });
+
+ it("should return true for nested arrays", () => {
+ expect(
+ isSerializable([
+ [1, 2],
+ [3, 4],
+ ]),
+ ).toBe(true);
+ });
+
+ it("should return true for arrays of objects", () => {
+ expect(
+ isSerializable([
+ { id: 1, name: "first" },
+ { id: 2, name: "second" },
+ ]),
+ ).toBe(true);
+ });
+
+ it("should return false for arrays containing functions", () => {
+ expect(isSerializable([1, 2, () => {}])).toBe(false);
+ });
+
+ it("should return false for arrays containing symbols", () => {
+ expect(isSerializable([1, 2, Symbol("test")])).toBe(false);
+ });
+
+ it("should return false for arrays containing class instances", () => {
+ class MyClass {}
+ expect(isSerializable([1, 2, new MyClass()])).toBe(false);
+ });
+
+ it("should return false for nested arrays containing non-serializable values", () => {
+ expect(
+ isSerializable([
+ [1, 2],
+ [3, () => {}],
+ ]),
+ ).toBe(false);
+ });
+ });
+
+ describe("complex nested structures", () => {
+ it("should return true for deeply nested serializable structures", () => {
+ expect(
+ isSerializable({
+ users: [
+ {
+ name: "Alice",
+ posts: [
+ { title: "Post 1", likes: 10 },
+ { title: "Post 2", likes: 5 },
+ ],
+ },
+ {
+ name: "Bob",
+ posts: [{ title: "Post 3", likes: 8 }],
+ },
+ ],
+ metadata: {
+ total: 2,
+ active: true,
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it("should return false for deeply nested structures with non-serializable values", () => {
+ expect(
+ isSerializable({
+ users: [
+ {
+ name: "Alice",
+ posts: [
+ { title: "Post 1", onClick: () => {} },
+ { title: "Post 2", likes: 5 },
+ ],
+ },
+ ],
+ }),
+ ).toBe(false);
+ });
+ });
+});
diff --git a/frontend/src/metabase/nav/containers/Navbar.unit.spec.tsx b/frontend/src/metabase/nav/containers/Navbar.unit.spec.tsx
index ed199eb3d8b..cea100a86d7 100644
--- a/frontend/src/metabase/nav/containers/Navbar.unit.spec.tsx
+++ b/frontend/src/metabase/nav/containers/Navbar.unit.spec.tsx
@@ -117,7 +117,7 @@ describe("nav > containers > Navbar > Core App", () => {
expect(screen.queryByTestId("main-navbar-root")).not.toBeInTheDocument();
});
- ["question/1", "model/1", "dashboard/1", "embed-js"].forEach((pathname) => {
+ ["question/1", "model/1", "dashboard/1"].forEach((pathname) => {
it(`should be hidden on initial load for a ${pathname}`, async () => {
await setup({ pathname: `/${pathname}` });
await expectNavbarClosed();
diff --git a/frontend/src/metabase/new/components/NewModals/NewModals.tsx b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
index 56f0858af4c..96df3ffb8dd 100644
--- a/frontend/src/metabase/new/components/NewModals/NewModals.tsx
+++ b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
@@ -12,12 +12,18 @@ import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { PaletteShortcutsModal } from "metabase/palette/components/PaletteShortcutsModal/PaletteShortcutsModal";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
+import {
+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,
+ type SdkIframeEmbedSetupModalProps,
+} from "metabase/plugins";
import { closeModal, setOpenModal } from "metabase/redux/ui";
-import { currentOpenModal } from "metabase/selectors/ui";
+import { getCurrentOpenModalState } from "metabase/selectors/ui";
import type { WritebackAction } from "metabase-types/api";
export const NewModals = withRouter((props: WithRouterProps) => {
- const currentNewModal = useSelector(currentOpenModal);
+ const { id: currentNewModalId, props: currentNewModalProps } = useSelector(
+ getCurrentOpenModalState<SdkIframeEmbedSetupModalProps>,
+ );
const dispatch = useDispatch();
const collectionId = useSelector((state) =>
Collections.selectors.getInitialCollectionId(state, props),
@@ -40,7 +46,7 @@ export const NewModals = withRouter((props: WithRouterProps) => {
{
id: "shortcuts-modal",
perform: () => {
- if (currentNewModal) {
+ if (currentNewModalId) {
handleModalClose();
} else {
dispatch(setOpenModal("help"));
@@ -48,10 +54,10 @@ export const NewModals = withRouter((props: WithRouterProps) => {
},
},
],
- [currentNewModal],
+ [currentNewModalId],
);
- switch (currentNewModal) {
+ switch (currentNewModalId) {
case "collection":
return (
<CreateCollectionModal
@@ -77,11 +83,20 @@ export const NewModals = withRouter((props: WithRouterProps) => {
/>
</Modal>
);
+ case "embed": {
+ return (
+ <PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetupModal
+ opened
+ initialState={currentNewModalProps?.initialState}
+ onClose={handleModalClose}
+ />
+ );
+ }
default:
return (
<PaletteShortcutsModal
onClose={handleModalClose}
- open={currentNewModal === "help"}
+ open={currentNewModalId === "help"}
/>
);
}
diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
index dbd298072d2..5071b969103 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
@@ -13,9 +13,16 @@ import {
import Collections from "metabase/entities/collections/collections";
import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
-import { PLUGIN_DOCUMENTS } from "metabase/plugins";
+import {
+ PLUGIN_DOCUMENTS,
+ type SdkIframeEmbedSetupModalProps,
+} from "metabase/plugins";
import { openDiagnostics } from "metabase/redux/app";
-import { closeModal, setOpenModal } from "metabase/redux/ui";
+import {
+ closeModal,
+ setOpenModal,
+ setOpenModalWithProps,
+} from "metabase/redux/ui";
import {
getHasDataAccess,
getHasDatabaseWithActionsEnabled,
@@ -26,6 +33,7 @@ import {
getUserPersonalCollectionId,
} from "metabase/selectors/user";
import { useColorScheme } from "metabase/ui";
+import type { ModalName } from "metabase-types/store/modal";
import {
type RegisterShortcutProps,
@@ -60,12 +68,22 @@ export const useCommandPaletteBasicActions = ({
const hasEmbedJsFeature = useHasTokenFeature("embedding_simple");
const openNewModal = useCallback(
- (modalId: string) => {
+ (modalId: ModalName) => {
dispatch(closeModal());
dispatch(setOpenModal(modalId));
},
[dispatch],
);
+ const openNewModalWithProps = useCallback(
+ <TProps extends Record<string, unknown>>(
+ modalId: ModalName,
+ props?: TProps,
+ ) => {
+ dispatch(closeModal());
+ dispatch(setOpenModalWithProps({ id: modalId, props }));
+ },
+ [dispatch],
+ );
const initialActions = useMemo<RegisterShortcutProps[]>(() => {
const actions: RegisterShortcutProps[] = [];
@@ -233,7 +251,10 @@ export const useCommandPaletteBasicActions = ({
section: "basic",
icon: "embed",
keywords: "embed flow, new embed, embed js",
- perform: () => dispatch(push("/embed-js")),
+ perform: () =>
+ openNewModalWithProps<
+ Pick<SdkIframeEmbedSetupModalProps, "initialState">
+ >("embed"),
});
}
@@ -266,6 +287,7 @@ export const useCommandPaletteBasicActions = ({
hasNativeWrite,
collectionId,
openNewModal,
+ openNewModalWithProps,
isAdmin,
personalCollectionId,
hasEmbedJsFeature,
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 5dc0d5e3daa..182f2195139 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -585,10 +585,24 @@ export const PLUGIN_EMBEDDING_IFRAME_SDK = {
SdkIframeEmbedRoute: (): ReactNode => null,
};
+export type SdkIframeEmbedSetupModalProps = {
+ opened: boolean;
+ onClose: () => void;
+ initialState?: SdkIframeEmbedSetupModalInitialState;
+};
+
+export type SdkIframeEmbedSetupModalInitialState = {
+ resourceType?: string | null;
+ resourceId?: string | number | null;
+ useExistingUserSession?: boolean;
+};
+
export const PLUGIN_EMBEDDING_IFRAME_SDK_SETUP = {
isFeatureEnabled: () => false,
shouldShowEmbedInNewItemMenu: () => false,
- SdkIframeEmbedSetup: (): ReactNode => null,
+ SdkIframeEmbedSetupModal: (
+ _props: SdkIframeEmbedSetupModalProps,
+ ): ReactNode => null,
};
export const PLUGIN_CONTENT_VERIFICATION = {
diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsx
index 245e34b31a2..487d68d4674 100644
--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsx
+++ b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsx
@@ -26,6 +26,8 @@ export interface EmbedModalContentProps {
onDeletePublicLink: () => void;
getPublicUrl: (publicUuid: string, extension?: ExportFormatType) => string;
+ onClose: () => void;
+
className?: string;
}
@@ -43,6 +45,7 @@ export const EmbedModalContent = (
onCreatePublicLink,
onDeletePublicLink,
getPublicUrl,
+ onClose,
} = props;
if (embedType == null) {
@@ -54,6 +57,7 @@ export const EmbedModalContent = (
onDeletePublicLink={onDeletePublicLink}
getPublicUrl={getPublicUrl}
goToNextStep={goToNextStep}
+ closeModal={onClose}
/>
);
}
diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.premium.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.premium.unit.spec.tsx
index fd5b5939d9c..7b172393171 100644
--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.premium.unit.spec.tsx
+++ b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.premium.unit.spec.tsx
@@ -49,15 +49,6 @@ describe("EmbedModalContent", () => {
},
});
- // The card is clickable
- expect(
- screen.getByRole("link", { name: INTERACTIVE_EMBEDDING_TITLE }),
- ).toHaveProperty(
- "href",
- // I have no idea why only this URL is absolute in the test, it is relative in the markup 🤷
- "http://localhost/embed-js?resource_type=dashboard",
- );
-
// We don't show the link at the bottom of the card
const withinInteractiveEmbeddingCard = within(
screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),
diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsx
index fedc4976aa3..72bbf63f905 100644
--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsx
+++ b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsx
@@ -50,6 +50,7 @@ export function setup(
onUpdateEnableEmbedding = jest.fn(),
onCreatePublicLink = jest.fn(),
onDeletePublicLink = jest.fn(),
+ onClose = jest.fn(),
} = {},
hasEnterprisePlugins,
tokenFeatures = createMockTokenFeatures(),
@@ -92,6 +93,7 @@ export function setup(
onUpdateEnableEmbedding={onUpdateEnableEmbedding}
onCreatePublicLink={onCreatePublicLink}
onDeletePublicLink={onDeletePublicLink}
+ onClose={onClose}
/>
);
}}
diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsx b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsx
index 868afdaa6e0..11badd8dac5 100644
--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsx
+++ b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsx
@@ -1,6 +1,6 @@
import cx from "classnames";
import type React from "react";
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { t } from "ttag";
import {
@@ -40,6 +40,7 @@ interface SelectEmbedTypePaneProps {
onDeletePublicLink: () => void;
getPublicUrl: (publicUuid: string, extension?: ExportFormatType) => string;
goToNextStep: () => void;
+ closeModal: () => void;
}
export function SelectEmbedTypePane({
@@ -49,20 +50,9 @@ export function SelectEmbedTypePane({
onDeletePublicLink,
getPublicUrl,
goToNextStep,
+ closeModal,
}: SelectEmbedTypePaneProps) {
- const embedFlowUrl = useMemo(() => {
- const params = new URLSearchParams();
-
- params.set("resource_type", resourceType);
-
- if (resource.id) {
- params.set("resource_id", resource.id.toString());
- }
-
- return "/embed-js?" + params.toString();
- }, [resourceType, resource.id]);
-
- const { url } = useUpsellEmbedJsCta({ embedFlowUrl });
+ const { url } = useUpsellEmbedJsCta({ resource, resourceType, closeModal });
const hasPublicLink = resource.public_uuid != null;
const utmTags = {
@@ -144,8 +134,10 @@ export function SelectEmbedTypePane({
{/* Embedded Analytics JS: render either upsell or embed flow link */}
<MaybeLinkEmbedJs
+ resource={resource}
+ resourceType={resourceType}
shouldRenderLink={!isEmbedJsAvailable || isEmbedJsEnabled}
- embedFlowUrl={embedFlowUrl}
+ closeModal={closeModal}
>
<SharingPaneButton
title={t`Embedded Analytics JS`}
@@ -155,7 +147,11 @@ export function SelectEmbedTypePane({
disabledLink="/admin/embedding/modular"
actionHint={
!isEmbedJsAvailable ? (
- <UpsellEmbedJsCta embedFlowUrl={embedFlowUrl} />
+ <UpsellEmbedJsCta
+ resource={resource}
+ resourceType={resourceType}
+ closeModal={closeModal}
+ />
) : undefined
}
>
@@ -242,26 +238,38 @@ function LearnMore({ url }: { url: string | undefined }) {
}
function MaybeLinkEmbedJs({
+ resource,
+ resourceType,
shouldRenderLink,
- embedFlowUrl,
+ closeModal,
...props
}: {
- shouldRenderLink?: boolean;
- embedFlowUrl: string;
children: React.ReactNode;
+ resource: EmbedResource;
+ resourceType: EmbedResourceType;
+ shouldRenderLink?: boolean;
+ closeModal: () => void;
}) {
- const { url, internalLink, triggerUpsellFlow } = useUpsellEmbedJsCta({
- embedFlowUrl,
+ const { openEmbedFlow, url, triggerUpsellFlow } = useUpsellEmbedJsCta({
+ resource,
+ resourceType,
+ closeModal,
});
if (!shouldRenderLink) {
return props.children;
}
- if (triggerUpsellFlow) {
+ if (openEmbedFlow || triggerUpsellFlow) {
return (
<UnstyledButton
- onClick={triggerUpsellFlow}
+ onClick={() => {
+ if (triggerUpsellFlow) {
+ triggerUpsellFlow();
+ } else if (openEmbedFlow) {
+ openEmbedFlow();
+ }
+ }}
type="button"
aria-label={t`Embedded Analytics JS`}
>
@@ -281,15 +289,5 @@ function MaybeLinkEmbedJs({
);
}
- if (internalLink) {
- return (
- <Link
- {...props}
- to={internalLink}
- aria-label={t`Embedded Analytics JS`}
- />
- );
- }
-
return props.children;
}
diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.unit.spec.tsx
index 3b836b024bd..1f3406e9ec0 100644
--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.unit.spec.tsx
+++ b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.unit.spec.tsx
@@ -31,6 +31,7 @@ const setup = ({
const onDeletePublicLink = jest.fn();
const getPublicUrl = jest.fn((uuid) => uuid);
const goToNextStep = jest.fn();
+ const closeModal = jest.fn();
const { history } = renderWithProviders(
<Route
@@ -43,6 +44,7 @@ const setup = ({
onDeletePublicLink={onDeletePublicLink}
getPublicUrl={getPublicUrl}
goToNextStep={goToNextStep}
+ closeModal={closeModal}
/>
)}
></Route>,
diff --git a/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx b/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx
index 7b80706cabd..0157cdd128c 100644
--- a/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx
+++ b/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx
@@ -54,6 +54,7 @@ export const QuestionEmbedWidget = (props: QuestionEmbedWidgetProps) => {
updateEmbeddingParams({ id: card.id, embedding_params })
}
getPublicUrl={getPublicQuestionUrl}
+ onClose={onClose}
/>
)}
</EmbedModal>
diff --git a/frontend/src/metabase/redux/app.ts b/frontend/src/metabase/redux/app.ts
index fb74173d2b2..8de460d8561 100644
--- a/frontend/src/metabase/redux/app.ts
+++ b/frontend/src/metabase/redux/app.ts
@@ -77,7 +77,7 @@ const errorPage = handleActions(
// regexr.com/7r89i
// A word boundary is added to /model so it doesn't match /browse/models
const PATH_WITH_COLLAPSED_NAVBAR =
- /\/(model\b|question|dashboard|metabot|embed-js|document).*/;
+ /\/(model\b|question|dashboard|metabot|document).*/;
export function isNavbarOpenForPathname(pathname: string, prevState: boolean) {
return (
diff --git a/frontend/src/metabase/redux/ui.ts b/frontend/src/metabase/redux/ui.ts
index 6316a08567f..1277b7a7c0a 100644
--- a/frontend/src/metabase/redux/ui.ts
+++ b/frontend/src/metabase/redux/ui.ts
@@ -1,15 +1,70 @@
-import { createAction, handleActions } from "metabase/lib/redux";
+import { type PayloadAction, createSlice } from "@reduxjs/toolkit";
-export const SET_OPEN_MODAL = "metabase/ui/SET_OPEN_MODAL";
-export const CLOSE_MODAL = "metabase/ui/CLOSE_MODAL";
+import { isProduction } from "metabase/env";
+import { isSerializable } from "metabase/lib/objects";
+import type { ModalState } from "metabase-types/store/modal";
-export const setOpenModal = createAction(SET_OPEN_MODAL);
-export const closeModal = createAction(CLOSE_MODAL);
+type SetOpenModalPayload = ModalState["id"];
+type SetOpenModalWithPropsPayload<T = ModalState["props"]> = {
+ id: ModalState["id"];
+ props?: T;
+};
-export const modal = handleActions(
- {
- [SET_OPEN_MODAL]: (state, { payload }) => payload,
- [CLOSE_MODAL]: () => null,
+/**
+ * Validates that modal props are serializable.
+ * Throws an error in development if non-serializable values are detected.
+ */
+function validateSerializableProps(props: unknown): void {
+ if (isProduction || !props) {
+ return;
+ }
+
+ if (isSerializable(props)) {
+ return;
+ }
+
+ console.error("Non-serializable modal props detected:", props);
+ throw new Error(
+ "Modal props must be serializable. Avoid passing functions, class instances, or other non-serializable values.",
+ );
+}
+
+const DEFAULT_MODAL_STATE: ModalState = {
+ id: null,
+ props: null,
+};
+
+const modalSlice = createSlice({
+ name: "modal",
+ initialState: DEFAULT_MODAL_STATE,
+ reducers: {
+ setOpenModal: (state, action: PayloadAction<SetOpenModalPayload>) => {
+ state.id = action.payload;
+ state.props = null;
+ },
+ setOpenModalWithProps: (
+ state,
+ action: PayloadAction<SetOpenModalWithPropsPayload>,
+ ) => {
+ validateSerializableProps(action.payload.props);
+
+ state.id = action.payload.id;
+ state.props = action.payload.props ?? null;
+ },
+ closeModal: (state) => {
+ state.id = DEFAULT_MODAL_STATE.id;
+ state.props = DEFAULT_MODAL_STATE.props;
+ },
},
- null,
-);
+});
+
+export const modal = modalSlice.reducer;
+
+export const { setOpenModal, closeModal } = modalSlice.actions;
+
+export const setOpenModalWithProps = <T = ModalState["props"]>(
+ payload: SetOpenModalWithPropsPayload<T>,
+): ReturnType<typeof modalSlice.actions.setOpenModalWithProps> =>
+ modalSlice.actions.setOpenModalWithProps(
+ payload as SetOpenModalWithPropsPayload,
+ );
diff --git a/frontend/src/metabase/redux/ui.unit.spec.ts b/frontend/src/metabase/redux/ui.unit.spec.ts
new file mode 100644
index 00000000000..46296a0b152
--- /dev/null
+++ b/frontend/src/metabase/redux/ui.unit.spec.ts
@@ -0,0 +1,116 @@
+import { configureStore } from "@reduxjs/toolkit";
+
+import { closeModal, modal, setOpenModal, setOpenModalWithProps } from "./ui";
+
+jest.mock("metabase/env", () => ({
+ isProduction: false,
+}));
+
+describe("metabase/redux/ui", () => {
+ const createMockStore = () => {
+ return configureStore({
+ reducer: { modal },
+ });
+ };
+
+ describe("setOpenModal", () => {
+ it("should set the modal id and clear props", () => {
+ const store = createMockStore();
+
+ store.dispatch(setOpenModal("dashboard"));
+
+ expect(store.getState().modal).toEqual({
+ id: "dashboard",
+ props: null,
+ });
+ });
+ });
+
+ describe("closeModal", () => {
+ it("should clear the modal state", () => {
+ const store = createMockStore();
+
+ store.dispatch(setOpenModal("dashboard"));
+ store.dispatch(closeModal());
+
+ expect(store.getState().modal).toEqual({
+ id: null,
+ props: null,
+ });
+ });
+ });
+
+ describe("setOpenModalWithProps", () => {
+ it("should set the modal id and props", () => {
+ const store = createMockStore();
+ const props = { dashboardId: 123, title: "My Dashboard" };
+
+ store.dispatch(setOpenModalWithProps({ id: "dashboard", props }));
+
+ expect(store.getState().modal).toEqual({
+ id: "dashboard",
+ props,
+ });
+ });
+
+ it("should handle null props", () => {
+ const store = createMockStore();
+
+ store.dispatch(setOpenModalWithProps({ id: "dashboard", props: null }));
+
+ expect(store.getState().modal).toEqual({
+ id: "dashboard",
+ props: null,
+ });
+ });
+
+ it("should handle undefined props", () => {
+ const store = createMockStore();
+
+ store.dispatch(setOpenModalWithProps({ id: "dashboard" }));
+
+ expect(store.getState().modal).toEqual({
+ id: "dashboard",
+ props: null,
+ });
+ });
+
+ describe("validation", () => {
+ it("should throw an error when props contain non-serializable values in development", () => {
+ const store = createMockStore();
+ const props = { callback: () => {} };
+
+ expect(() => {
+ store.dispatch(setOpenModalWithProps({ id: "dashboard", props }));
+ }).toThrow("Modal props must be serializable");
+ });
+
+ it("should not throw an error when props contain non-serializable values in production", () => {
+ jest.resetModules();
+ jest.doMock("metabase/env", () => ({
+ isProduction: true,
+ }));
+
+ /* eslint-disable @typescript-eslint/no-var-requires */
+ const { configureStore } = require("@reduxjs/toolkit");
+ const {
+ modal: productionModal,
+ setOpenModalWithProps: productionSetOpenModalWithProps,
+ } = require("./ui");
+ /* eslint-enable @typescript-eslint/no-var-requires */
+
+ const store = configureStore({
+ reducer: { modal: productionModal },
+ });
+
+ const props = { callback: () => {} };
+
+ expect(() => {
+ store.dispatch(
+ productionSetOpenModalWithProps({ id: "dashboard", props }),
+ );
+ }).not.toThrow();
+ });
+ });
+ });
+});
diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsx
index 06dd9ae9131..6a664bc2907 100644
--- a/frontend/src/metabase/routes.jsx
+++ b/frontend/src/metabase/routes.jsx
@@ -41,7 +41,6 @@ import { getRoutes as getModelRoutes } from "metabase/models/routes";
import {
PLUGIN_COLLECTIONS,
PLUGIN_DOCUMENTS,
- PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,
PLUGIN_LANDING_PAGE,
PLUGIN_METABOT,
PLUGIN_TABLE_EDITING,
@@ -165,11 +164,6 @@ export const getRoutes = (store) => {
{PLUGIN_DOCUMENTS.getRoutes()}
- <Route
- path="embed-js"
- component={PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetup}
- />
-
<Route
path="collection/entity/:entity_id(**)"
component={createEntityIdRedirect({
diff --git a/frontend/src/metabase/selectors/ui.ts b/frontend/src/metabase/selectors/ui.ts
index 0312d3513df..f279ef2f7ae 100644
--- a/frontend/src/metabase/selectors/ui.ts
+++ b/frontend/src/metabase/selectors/ui.ts
@@ -1,3 +1,6 @@
import type { State } from "metabase-types/store";
+import type { ModalState } from "metabase-types/store/modal";
-export const currentOpenModal = (state: State) => state.modal;
+export const getCurrentOpenModalState = <TProps>(state: State) =>
+ state.modal as ModalState<TProps>;
+export const getCurrentOpenModal = (state: State) => state.modal.id;