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(sdk, embed-js): Add Guest Embeds via Embed JS and SDK (#64850)
Timofey Kachalovbfc0e2077a76
diff --git a/e2e/support/helpers/api/createDashboard.ts b/e2e/support/helpers/api/createDashboard.tsindex 955e46040a8..38423430b2e 100644--- a/e2e/support/helpers/api/createDashboard.ts+++ b/e2e/support/helpers/api/createDashboard.ts@@ -8,6 +8,7 @@ export interface DashboardDetails extends Omit<CreateDashboardRequest, "name"> {name?: string;auto_apply_filters?: Dashboard["auto_apply_filters"];enable_embedding?: Dashboard["enable_embedding"];+ embedding_type?: Dashboard["embedding_type"];embedding_params?: Dashboard["embedding_params"];dashcards?: Partial<DashboardCard>[];}@@ -33,6 +34,7 @@ export const createDashboard = (name = "Test Dashboard",auto_apply_filters,enable_embedding,+ embedding_type,embedding_params,dashcards,...restDashboardDetails@@ -59,6 +61,7 @@ export const createDashboard = (return cy.request<Dashboard>("PUT", `/api/dashboard/${body.id}`, {auto_apply_filters,enable_embedding,+ embedding_type,embedding_params,dashcards,});diff --git a/e2e/support/helpers/api/createQuestion.ts b/e2e/support/helpers/api/createQuestion.tsindex bc837effc3d..7be646304d6 100644--- a/e2e/support/helpers/api/createQuestion.ts+++ b/e2e/support/helpers/api/createQuestion.ts@@ -45,6 +45,7 @@ export type QuestionDetails = {* Defaults to false.*/enable_embedding?: Card["enable_embedding"];+ embedding_type?: Card["embedding_type"];};export type StructuredQuestionDetails = Omit<diff --git a/e2e/support/helpers/e2e-content-translation-helpers.ts b/e2e/support/helpers/e2e-content-translation-helpers.tsnew file mode 100644index 00000000000..276c3101855--- /dev/null+++ b/e2e/support/helpers/e2e-content-translation-helpers.ts@@ -0,0 +1,31 @@+import type { DictionaryArray } from "metabase-types/api";++export const getCSVWithHeaderRow = (dictionary: DictionaryArray) => {+ const header = ["Language", "String", "Translation"];+ return [header, ...dictionary]+ .map((row) => Object.values(row).join(","))+ .join("\n");+};++export const uploadTranslationDictionaryViaAPI = (rows: DictionaryArray) => {+ cy.signInAsAdmin();+ const csvString = getCSVWithHeaderRow(rows);++ const fileBlob = new Blob([csvString], { type: "text/csv" });+ const formData = new FormData();++ formData.append("file", fileBlob, "dictionary.csv");++ return cy+ .request({+ method: "POST",+ url: "/api/ee/content-translation/upload-dictionary",+ body: formData,+ headers: {+ "Content-Type": "multipart/form-data",+ },+ })+ .then((response) => {+ expect(response.status).to.equal(200);+ });+};diff --git a/e2e/support/helpers/e2e-embedding-helpers.js b/e2e/support/helpers/e2e-embedding-helpers.jsindex c990d80dfce..731f8d49eb5 100644--- a/e2e/support/helpers/e2e-embedding-helpers.js+++ b/e2e/support/helpers/e2e-embedding-helpers.js@@ -1,5 +1,13 @@+import * as jose from "jose";+import { METABASE_SECRET_KEY } from "e2e/support/cypress_data";+import {+ embedModalContent,+ embedModalEnableEmbedding,+ legacyStaticEmbeddingButton,+} from "e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers";import { modal, popover } from "e2e/support/helpers/e2e-ui-elements-helpers";+import { JWT_SHARED_SECRET } from "e2e/support/helpers/embedding-sdk-helpers/constants";import { openSharingMenu } from "./e2e-sharing-helpers";@@ -188,49 +196,72 @@ export function getEmbedModalSharingPane() {}/**- * Open Static Embedding setup modal+ * Open Legacy Static Embedding setup modal* @param {object} params+ * @param {("question"|"dashboard")} [params.resource] - resource type+ * @param {(string|number)} [params.resourceId] - resource id* @param {("overview"|"parameters"|"lookAndFeel")} [params.activeTab] - modal tab to open* @param {("code"|"preview")} [params.previewMode] - preview mode type to activate- * @param {boolean} [params.acceptTerms] - whether we need to go through the legalese step+ * @param {boolean} [params.unpublishBeforeOpen] - either unpublish entity before legacy modal is opened or not*/-export function openStaticEmbeddingModal({+export function openLegacyStaticEmbeddingModal({+ resource,+ resourceId,activeTab,previewMode,- acceptTerms = true,- confirmSave,+ unpublishBeforeOpen = true,} = {}) {- openSharingMenu("Embed");+ const apiPath = resource === "question" ? "card" : "dashboard";- if (confirmSave) {- cy.findByRole("button", { name: "Save" }).click();- }+ cy.request("PUT", `/api/${apiPath}/${resourceId}`, {+ enable_embedding: true,+ embedding_type: "static-legacy",+ });- cy.findByText("Static embedding").click();+ openSharingMenu("Embed");- if (acceptTerms) {- cy.findByTestId("accept-legalese-terms-button").click();- }+ embedModalContent().should("exist");- modal().within(() => {- if (activeTab) {- const tabKeyToNameMap = {- overview: "Overview",- parameters: "Parameters",- lookAndFeel: "Look and Feel",- };+ cy.get("body").then(($body) => {+ const isEmbeddingDisabled =+ $body.find('[data-testid="enable-embedding-card"]').length > 0;- cy.findByRole("tab", { name: tabKeyToNameMap[activeTab] }).click();+ if (isEmbeddingDisabled) {+ embedModalEnableEmbedding();}- if (previewMode) {- const previewModeToKeyMap = {- code: "Code",- preview: "Preview",- };-- cy.findByText(previewModeToKeyMap[previewMode]).click();- }+ embedModalContent().within(() => {+ legacyStaticEmbeddingButton().click();+ });++ modal().within(() => {+ cy.findByText("Static embedding").should("be.visible");++ // Some tests after a modal is opened expect the entity to be unpublished;+ // Other tests want to keep it published.+ if (unpublishBeforeOpen) {+ unpublishChanges(apiPath);+ }++ if (activeTab) {+ const tabKeyToNameMap = {+ overview: "Overview",+ parameters: "Parameters",+ lookAndFeel: "Look and Feel",+ };++ cy.findByRole("tab", { name: tabKeyToNameMap[activeTab] }).click();+ }++ if (previewMode) {+ const previewModeToKeyMap = {+ code: "Code",+ preview: "Preview",+ };++ cy.findByText(previewModeToKeyMap[previewMode]).click();+ }+ });});}@@ -241,7 +272,7 @@ export function closeStaticEmbeddingModal() {/*** Publish a static dashboard or question* @param {"card" | "dashboard"} apiPath- * @param callback+ * @param [callback]*/export function publishChanges(apiPath, callback) {cy.intercept("PUT", `/api/${apiPath}/*`).as("publishChanges");@@ -265,7 +296,13 @@ export function publishChanges(apiPath, callback) {* @param callback*/export function unpublishChanges(apiPath, callback) {- cy.intercept("PUT", `/api/${apiPath}/*`).as("unpublishChanges");+ cy.intercept("PUT", `/api/${apiPath}/*`, (req) => {+ const body = req.body;++ if (body?.enable_embedding === false) {+ req.alias = "unpublishChanges";+ }+ });cy.button("Unpublish").click();@@ -336,3 +373,34 @@ export const visitFullAppEmbeddingUrl = ({ url, qs, onBeforeLoad }) => {},});};++/**+ * @param {Object} options+ * @param {number} options.resourceId+ * @param {'question' | 'dashboard'} options.resourceType+ * @param [options.params]+ * @param [options.expirationMinutes]+ * @return {Promise<string>}+ */+export const getSignedJwtForResource = async ({+ resourceId,+ resourceType,+ params = {},+ expirationMinutes = 10,+}) => {+ const secret = new TextEncoder().encode(JWT_SHARED_SECRET);++ const iat = Math.round(new Date().getTime() / 1000);+ const exp = iat + 60 * expirationMinutes;++ const payload = {+ resource: { [resourceType]: resourceId },+ params,+ iat,+ exp,+ };++ return new jose.SignJWT(payload)+ .setProtectedHeader({ alg: "HS256" })+ .sign(secret);+};diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.tsindex 3399b8fe01b..5160b619b5c 100644--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts@@ -1,10 +1,11 @@import { match } from "ts-pattern";import { openSharingMenu } from "e2e/support/helpers/e2e-sharing-helpers";+import { JWT_SHARED_SECRET } from "e2e/support/helpers/embedding-sdk-helpers/constants";import type { MetabaseTheme } from "metabase/embedding-sdk/theme/MetabaseTheme";import type { CreateApiKeyResponse } from "metabase-types/api";-import { createApiKey } from "./api";+import { createApiKey, updateSetting } from "./api";import { getIframeBody } from "./e2e-embedding-helpers";import { enableJwtAuth } from "./e2e-jwt-helpers";import { restore } from "./e2e-setup-helpers";@@ -14,6 +15,8 @@ import {mockAuthProviderAndJwtSignIn,} from "./embedding-sdk-testing";+const { IS_ENTERPRISE } = Cypress.env();+const EMBED_JS_PATH = "http://localhost:4000/app/embed.js";/**@@ -22,6 +25,7 @@ const EMBED_JS_PATH = "http://localhost:4000/app/embed.js";export interface BaseEmbedTestPageOptions {// Passed to defineMetabaseConfigmetabaseConfig?: {+ isGuest?: boolean;instanceUrl?: string;apiKey?: string;useExistingUserSession?: boolean;@@ -217,6 +221,47 @@ export function prepareSdkIframeEmbedTest({}}+/**+ * Prepares the testing environment for sdk iframe embedding tests in guest embed mode.+ */+export function prepareGuestEmbedSdkIframeEmbedTest({+ withTokenFeatures = true,+ onPrepare,+}: {+ withTokenFeatures?: boolean;+ onPrepare?: () => void;+} = {}) {+ restore();+ cy.signInAsAdmin();++ if (IS_ENTERPRISE) {+ if (withTokenFeatures) {+ activateToken("bleeding-edge");+ } else {+ activateToken("starter");+ }+ }++ onPrepare?.();++ cy.request("PUT", "/api/setting/enable-embedding-simple", {+ value: true,+ });+ cy.request("PUT", "/api/setting/enable-embedding-static", {+ value: true,+ });++ cy.intercept("GET", "/api/embed/card/*").as("getCard");+ cy.intercept("GET", "/api/embed/card/*/query*").as("getCardQuery");+ cy.intercept("GET", "/api/embed/pivot/card/*/query*").as("getCardPivotQuery");++ updateSetting("embedding-secret-key", JWT_SHARED_SECRET);++ mockEmbedJsToDevServer();++ cy.signOut();+}+type EnabledAuthMethods = "jwt" | "saml" | "api-key";function setupMockAuthProviders(enabledAuthMethods: EnabledAuthMethods[]) {@@ -265,6 +310,7 @@ export const getNewEmbedScriptTag = ({export const getNewEmbedConfigurationScript = ({instanceUrl = "http://localhost:4000",+ isGuest,theme,apiKey,useExistingUserSession,@@ -273,6 +319,7 @@ export const getNewEmbedConfigurationScript = ({}: BaseEmbedTestPageOptions["metabaseConfig"] = {}) => {const config = {instanceUrl,+ isGuest,apiKey,useExistingUserSession,theme,@@ -343,6 +390,4 @@ export const mockEmbedJsToDevServer = () => {export function openEmbedJsModal() {openSharingMenu("Embed");-- cy.findByText("Embedded Analytics JS").click();}diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.tsnew file mode 100644index 00000000000..c75bb3dae14--- /dev/null+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.ts@@ -0,0 +1,13 @@+export const embedModalContent = () =>+ cy.findByTestId("sdk-iframe-embed-setup-modal-content");++export const embedModalEnableEmbeddingCard = () =>+ cy.findByTestId("enable-embedding-card");++export const embedModalEnableEmbedding = () =>+ embedModalEnableEmbeddingCard().within(() => {+ cy.findByText(/(Agree and (continue|enable)|Enable)/).click();+ });++export const legacyStaticEmbeddingButton = () =>+ cy.findByTestId("legacy-static-embedding-button");diff --git a/e2e/support/helpers/e2e-misc-helpers.js b/e2e/support/helpers/e2e-misc-helpers.jsindex 1d6dccb8b89..8b4a7c48138 100644--- a/e2e/support/helpers/e2e-misc-helpers.js+++ b/e2e/support/helpers/e2e-misc-helpers.js@@ -105,11 +105,11 @@ export const cypressWaitAll = function (commands) {*/export function visitQuestion(questionIdOrAlias) {if (typeof questionIdOrAlias === "number") {- visitQuestionById(questionIdOrAlias);+ return visitQuestionById(questionIdOrAlias);}if (typeof questionIdOrAlias === "string") {- cy.get(questionIdOrAlias).then((id) => visitQuestionById(id));+ return cy.get(questionIdOrAlias).then((id) => visitQuestionById(id));}}@@ -126,6 +126,8 @@ function visitQuestionById(id) {cy.wait("@" + metadataAlias);cy.wait("@" + alias);++ return cy.wrap(id);}/**diff --git a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-guest-embeds-helpers.tsx b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-guest-embeds-helpers.tsxnew file mode 100644index 00000000000..6c1bd393e69--- /dev/null+++ b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-guest-embeds-helpers.tsx@@ -0,0 +1,42 @@+import { StaticDashboard, StaticQuestion } from "@metabase/embedding-sdk-react";+import type { ComponentProps } from "react";++import { mountSdkContent } from "./component-embedding-sdk-helpers";++export function mountGuestEmbedQuestion(+ extraProps: Partial<ComponentProps<typeof StaticQuestion>> = {},+ {+ shouldAssertCardQuery,+ locale,+ }: { shouldAssertCardQuery?: boolean; locale?: string } = {+ shouldAssertCardQuery: true,+ },+) {+ cy.intercept("GET", "/api/embed/card/*").as("getCard");+ cy.intercept("POST", "/api/embed/card/*/query").as("cardQuery");+ cy.intercept("GET", "/api/embed/pivot/card/*/query*").as("getCardPivotQuery");++ mountSdkContent(<StaticQuestion {...extraProps} />, {+ sdkProviderProps: { authConfig: { isGuest: true }, locale },+ });++ if (shouldAssertCardQuery) {+ cy.wait("@getCard").then(({ response }) => {+ expect(response?.statusCode).to.equal(200);+ });+ }+}++export function mountGuestEmbedDashboard(+ extraProps: Partial<ComponentProps<typeof StaticDashboard>> = {},+) {+ cy.intercept("GET", "/api/embed/dashboard/*").as("getDashboard");++ mountSdkContent(<StaticDashboard {...extraProps} />, {+ sdkProviderProps: { authConfig: { isGuest: true } },+ });++ cy.wait("@getDashboard").then(({ response }) => {+ expect(response?.statusCode).to.equal(200);+ });+}diff --git a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers.tsx b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers.tsxindex 0fee3deb9d7..8d23c45595a 100644--- a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers.tsx+++ b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers.tsx@@ -6,6 +6,7 @@ import type { JSX } from "react";import React from "react";import { METABASE_INSTANCE_URL } from "e2e/support/helpers";+import type { DeepPartial } from "metabase/embedding-sdk/types/utils";import { ThemeProvider } from "metabase/ui";export const DEFAULT_SDK_AUTH_PROVIDER_CONFIG = {@@ -26,7 +27,7 @@ export function mountSdk(}export interface MountSdkContentOptions extends MountSdkOptions {- sdkProviderProps?: Partial<MetabaseProviderProps>;+ sdkProviderProps?: DeepPartial<MetabaseProviderProps>;waitForUser?: boolean;}@@ -38,7 +39,11 @@ export function mountSdkContent(waitForUser = true,}: MountSdkContentOptions = {},) {- cy.intercept("GET", "/api/user/current").as("getUser");+ const isGuest = !!sdkProviderProps?.authConfig?.isGuest;++ if (!isGuest) {+ cy.intercept("GET", "/api/user/current").as("getUser");+ }const reactNode = (<ThemeProvider>@@ -60,7 +65,7 @@ export function mountSdkContent(cy.mount(reactNode);}- if (waitForUser) {+ if (!isGuest && waitForUser) {// When running stress tests with network throttling, the request can take longer to complete// as it first needs to fetch the bundle from the servercy.wait("@getUser", { timeout: 20_000 }).then(({ response }) => {diff --git a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsxindex e3af9d9deaf..b199759b96c 100644--- a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx+++ b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx@@ -40,7 +40,7 @@ export function mountInteractiveQuestion(export function mountStaticQuestion(extraProps: Partial<ComponentProps<typeof StaticQuestion>> = {},- { shouldAssertCardQuery }: MountQuestionOptions = {+ { shouldAssertCardQuery, sdkProviderProps }: MountQuestionOptions = {shouldAssertCardQuery: true,},) {@@ -48,7 +48,10 @@ export function mountStaticQuestion(cy.intercept("POST", "/api/card/*/query").as("cardQuery");cy.get<number>("@questionId").then((questionId) => {- mountSdkContent(<StaticQuestion questionId={questionId} {...extraProps} />);+ mountSdkContent(+ <StaticQuestion questionId={questionId} {...extraProps} />,+ { sdkProviderProps },+ );});if (shouldAssertCardQuery) {diff --git a/e2e/support/helpers/embedding-sdk-component-testing/index.ts b/e2e/support/helpers/embedding-sdk-component-testing/index.tsindex b23deef003e..5d58af0add7 100644--- a/e2e/support/helpers/embedding-sdk-component-testing/index.ts+++ b/e2e/support/helpers/embedding-sdk-component-testing/index.ts@@ -1,3 +1,4 @@export * from "./component-embedding-sdk-helpers";export * from "./component-embedding-sdk-question-helpers";export * from "./component-embedding-sdk-console-helpers";+export * from "./component-embedding-sdk-guest-embeds-helpers";diff --git a/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts b/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.tsindex 8d90699827a..5682c4eaa52 100644--- a/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts+++ b/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts@@ -8,6 +8,7 @@ import {METABASE_INSTANCE_URL,activateToken,restore,+ updateSetting,} from "e2e/support/helpers";import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";@@ -77,6 +78,21 @@ export function signInAsAdminAndEnableEmbeddingSdk() {});}+export function signInAsAdminAndSetupGuestEmbedding({+ token,+}: {+ token: "starter" | "pro-cloud";+}) {+ Cypress.config("baseUrl", METABASE_INSTANCE_URL);++ restore();++ cy.signInAsAdmin();++ activateToken(token);+ updateSetting("embedding-secret-key", JWT_SHARED_SECRET);+}+const MOCK_SAML_IDP_URI = "https://example.test/saml";export function enableSamlAuth() {diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.tsindex 1e2f8861161..abdd3dcb8a8 100644--- a/e2e/support/helpers/index.ts+++ b/e2e/support/helpers/index.ts@@ -27,6 +27,7 @@ export * from "./e2e-email-helpers";export * from "./e2e-embedding-helpers";export * from "./e2e-embedding-iframe-interactive-helpers";export * from "./e2e-embedding-iframe-sdk-helpers";+export * from "./e2e-embedding-iframe-sdk-setup-helpers";export * from "./e2e-embedding-sdk-assertion-helpers";export * from "./e2e-enterprise-helpers";export * from "./e2e-filter-helpers";diff --git a/e2e/test-component/scenarios/embedding-sdk/guest-embed-content-translations.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/guest-embed-content-translations.cy.spec.tsxnew file mode 100644index 00000000000..df578038347--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/guest-embed-content-translations.cy.spec.tsx@@ -0,0 +1,80 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion, getSignedJwtForResource } from "e2e/support/helpers";+import { uploadTranslationDictionaryViaAPI } from "e2e/support/helpers/e2e-content-translation-helpers";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import { mountGuestEmbedQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";+import { signInAsAdminAndSetupGuestEmbedding } from "e2e/support/helpers/embedding-sdk-testing";+import type { Card } from "metabase-types/api";++const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++describe("scenarios > embedding-sdk > guest-embed-content-translations", () => {+ describe("question", () => {+ const setup = ({ display }: { display?: Card["display"] } = {}) => {+ signInAsAdminAndSetupGuestEmbedding({+ token: "pro-cloud",+ });++ createQuestion({+ name: "Question for Guest Embed SDK",+ enable_embedding: true,+ embedding_type: "guest-embed",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ display,+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });++ cy.signOut();+ };++ describe("content translation", () => {+ it("should show question content with applied content translation", () => {+ setup();++ cy.signInAsAdmin();++ uploadTranslationDictionaryViaAPI([+ {+ locale: "de",+ msgid: "Question for Guest Embed SDK",+ msgstr: "Override title für Deutsch",+ },+ {+ locale: "de",+ msgid: "Product ID",+ msgstr: "Override Product ID für Deutsch",+ },+ ]);++ cy.signOut();++ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ mountGuestEmbedQuestion(+ { token, title: true },+ {+ locale: "de",+ },+ );++ getSdkRoot().within(() => {+ cy.findByText("Override title für Deutsch").should("be.visible");+ cy.findByText("Override Product ID für Deutsch").should(+ "be.visible",+ );+ });+ });+ });+ });+ });+});diff --git a/e2e/test-component/scenarios/embedding-sdk/guest-embed-error-handling.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/guest-embed-error-handling.cy.spec.tsxnew file mode 100644index 00000000000..631e705a6e8--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/guest-embed-error-handling.cy.spec.tsx@@ -0,0 +1,91 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion, getSignedJwtForResource } from "e2e/support/helpers";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import { mountGuestEmbedQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";+import { signInAsAdminAndSetupGuestEmbedding } from "e2e/support/helpers/embedding-sdk-testing";++const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++describe("scenarios > embedding-sdk > guest-embed-error-handling", () => {+ beforeEach(() => {+ signInAsAdminAndSetupGuestEmbedding({+ token: "starter",+ });++ createQuestion({+ name: "47563",+ enable_embedding: true,+ embedding_type: "guest-embed",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });++ cy.signOut();+ });++ it("should show JWT token error for invalid token", () => {+ cy.get("@questionId").then(async () => {+ mountGuestEmbedQuestion(+ { token: "foo" },+ {+ shouldAssertCardQuery: false,+ },+ );++ getSdkRoot().within(() => {+ cy.findByText("Passed token is not a valid JWT token.").should(+ "be.visible",+ );+ });+ });+ });++ it("should show an error for an unpublished entity", () => {+ cy.get("@questionId").then(async (questionId) => {+ cy.signInAsAdmin();+ cy.request("PUT", `/api/card/${questionId}`, { enable_embedding: false });+ cy.signOut();++ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ mountGuestEmbedQuestion(+ { token },+ {+ shouldAssertCardQuery: false,+ },+ );++ getSdkRoot().within(() => {+ cy.findByText("Embedding is not enabled for this object.").should(+ "be.visible",+ );+ });+ });+ });++ it("should show an error when an id is passed instead of a token", () => {+ cy.get("@questionId").then(async (questionId) => {+ mountGuestEmbedQuestion(+ { questionId },+ {+ shouldAssertCardQuery: false,+ },+ );++ getSdkRoot().within(() => {+ cy.findByText(+ "A valid JWT token is required to be passed in guest embeds mode.",+ ).should("be.visible");+ });+ });+ });+});diff --git a/e2e/test-component/scenarios/embedding-sdk/guest-embed-happy-path.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/guest-embed-happy-path.cy.spec.tsxnew file mode 100644index 00000000000..28f8125f6e8--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/guest-embed-happy-path.cy.spec.tsx@@ -0,0 +1,519 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ type NativeQuestionDetails,+ type StructuredQuestionDetails,+ createNativeQuestion,+ createNativeQuestionAndDashboard,+ createQuestion,+ createQuestionAndDashboard,+ getSignedJwtForResource,+} from "e2e/support/helpers";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import {+ mountGuestEmbedDashboard,+ mountGuestEmbedQuestion,+} from "e2e/support/helpers/embedding-sdk-component-testing";+import { signInAsAdminAndSetupGuestEmbedding } from "e2e/support/helpers/embedding-sdk-testing";+import { questionAsPinMapWithTiles } from "e2e/test/scenarios/embedding/shared/embedding-questions";+import type { Card } from "metabase-types/api";+import { createMockParameter } from "metabase-types/api/mocks";++const { ORDERS, ORDERS_ID, PEOPLE_ID } = SAMPLE_DATABASE;++const WAIT_FOR_INTERNAL_API_REQUESTS_MS = 1000;++const PARAMETERS = [+ createMockParameter({+ id: "quantity",+ name: "Internal",+ slug: "quantity",+ type: "number/=",+ target: ["dimension", ["template-tag", "quantity"]],+ }),+ createMockParameter({+ id: "product_id_fk",+ name: "FK",+ slug: "product_id_fk",+ type: "id",+ target: ["dimension", ["template-tag", "product_id_fk"]],+ }),+ createMockParameter({+ id: "user_id_pk",+ name: "PK->Name",+ slug: "user_id_pk",+ type: "id",+ target: ["dimension", ["template-tag", "user_id_pk"]],+ values_source_type: "static-list",+ values_source_config: {+ values: ["74"],+ },+ }),+];+const TEMPLATE_TAGS = {+ quantity: {+ id: "quantity",+ name: "quantity",+ "display-name": "Internal",+ type: "dimension",+ "widget-type": "number/=",+ dimension: ["field", ORDERS.QUANTITY, null],+ },+ product_id_fk: {+ id: "product_id_fk",+ name: "product_id_fk",+ "display-name": "FK",+ type: "dimension",+ "widget-type": "id",+ dimension: ["field", ORDERS.PRODUCT_ID, null],+ },+ user_id_pk: {+ id: "user_id_pk",+ name: "user_id_pk",+ "display-name": "PK->Name",+ type: "dimension",+ "widget-type": "id",+ dimension: ["field", PEOPLE_ID, null],+ },+};++describe("scenarios > embedding-sdk > guest-embed-happy-path", () => {+ describe("question", () => {+ const setup = ({+ display,+ createQuestionOverride,+ }: {+ display?: Card["display"];+ createQuestionOverride?: () => void;+ } = {}) => {+ signInAsAdminAndSetupGuestEmbedding({+ token: "starter",+ });++ if (!createQuestionOverride) {+ createQuestion({+ name: "Question for Guest Embed SDK",+ enable_embedding: true,+ embedding_type: "guest-embed",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ display,+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });+ } else {+ createQuestionOverride();+ }++ cy.signOut();+ };++ it("should show question content for unauthorized user", () => {+ setup();++ cy.intercept("/api/user/*").as("internalApiRequest");+ cy.intercept("/api/card/*").as("internalApiRequest");++ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ mountGuestEmbedQuestion({ token });++ getSdkRoot().within(() => {+ cy.findByText("Product ID").should("be.visible");+ cy.findByText("Max of Quantity").should("be.visible");+ });++ cy.get("@internalApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length(0);+ });+ });+ });++ it("should show content of a question with `pivot table` type for unauthorized user", () => {+ setup({ display: "pivot" });++ cy.intercept("/api/card/pivot/*/query*").as("internalApiRequest");++ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ mountGuestEmbedQuestion(+ { token },+ {+ shouldAssertCardQuery: false,+ },+ );++ cy.wait("@getCardPivotQuery");++ getSdkRoot().within(() => {+ cy.findByText("Product ID").should("be.visible");+ cy.findByText("Max of Quantity").should("be.visible");+ });++ cy.get("@internalApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length(0);+ });+ });+ });++ it("should show content of a question with `map` type with tiles for unauthorized user", () => {+ setup({+ createQuestionOverride: () => {+ createNativeQuestion(+ questionAsPinMapWithTiles as NativeQuestionDetails,+ {+ wrapId: true,+ },+ );+ },+ });++ cy.intercept("GET", "/api/embed/tiles/card/**").as("mapTilesApiRequest");++ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ mountGuestEmbedQuestion(+ { token },+ {+ shouldAssertCardQuery: false,+ },+ );++ cy.wait("@mapTilesApiRequest");++ cy.get("@mapTilesApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length.greaterThan(1);+ });+ });+ });++ it("should properly work with question parameters", () => {+ setup({+ createQuestionOverride: () => {+ createNativeQuestion(+ {+ name: "Orders native question",+ native: {+ query:+ "SELECT * " ++ "FROM ORDERS " ++ "JOIN PEOPLE ON ORDERS.USER_ID = PEOPLE.ID " ++ "WHERE {{quantity}} AND {{product_id_fk}} AND {{user_id_pk}}",+ "template-tags": TEMPLATE_TAGS,+ },+ parameters: PARAMETERS,+ enable_embedding: true,+ embedding_params: {+ quantity: "enabled",+ product_id_fk: "locked",+ user_id_pk: "enabled",+ },+ },+ {+ wrapId: true,+ },+ );+ },+ });++ cy.intercept("GET", "/api/embed/card/*/params/*/values").as(+ "parameterValuesApiRequest",+ );++ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ params: {+ product_id_fk: 1,+ },+ });++ mountGuestEmbedQuestion(+ { token },+ {+ shouldAssertCardQuery: false,+ },+ );++ getSdkRoot().within(() => {+ cy.findAllByTestId("parameter-widget").should("have.length", 2);++ cy.findAllByTestId("parameter-widget")+ .filter(':contains("PK->Name")')+ .click();+ });++ cy.wait("@parameterValuesApiRequest");++ cy.get("@parameterValuesApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length(1);+ });++ cy.findByTestId("table-body")+ .findAllByRole("row")+ .should("have.length.above", 10);++ getSdkRoot().within(() => {+ cy.findByTestId("parameter-value-dropdown").contains("74").click();+ cy.findByTestId("parameter-value-dropdown")+ .contains("Add filter")+ .click();++ cy.findByTestId("table-body")+ .findAllByRole("row")+ .should("have.length", 1);+ });+ });+ });+ });++ describe("dashboard", () => {+ const setup = ({+ display,+ questionDetails,+ }: {+ display?: Card["display"];+ questionDetails?: StructuredQuestionDetails;+ } = {}) => {+ signInAsAdminAndSetupGuestEmbedding({+ token: "starter",+ });++ createQuestionAndDashboard({+ questionDetails: questionDetails ?? {+ name: "Sample Question",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ breakout: [+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],+ ["field", ORDERS.QUANTITY, null],+ ],+ },+ display,+ },+ dashboardDetails: {+ name: "Embedding SDK Test Dashboard",+ enable_embedding: true,+ embedding_type: "guest-embed",+ },+ }).then(({ body: { dashboard_id } }) => {+ cy.wrap(dashboard_id).as("dashboardId");+ });++ cy.signOut();+ };++ it("should show dashboard content for unauthorized user", () => {+ cy.intercept("/api/user/*").as("internalApiRequest");+ cy.intercept("/api/dashboard/*").as("internalApiRequest");++ setup();++ cy.get("@dashboardId").then(async (dashboardId) => {+ const token = await getSignedJwtForResource({+ resourceId: dashboardId as unknown as number,+ resourceType: "dashboard",+ });++ mountGuestEmbedDashboard({ token });++ getSdkRoot().within(() => {+ cy.findByText("Embedding SDK Test Dashboard").should("be.visible");+ cy.findByText("Sample Question").should("be.visible");+ });++ // Wait for requests+ cy.wait(WAIT_FOR_INTERNAL_API_REQUESTS_MS);++ cy.get("@internalApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length(0);+ });+ });+ });++ it("should show dashboard content with a pivot card for unauthorized user", () => {+ cy.intercept("/api/user/*").as("internalApiRequest");+ cy.intercept("/api/dashboard/*").as("internalApiRequest");++ setup({ display: "pivot" });++ cy.get("@dashboardId").then(async (dashboardId) => {+ const token = await getSignedJwtForResource({+ resourceId: dashboardId as unknown as number,+ resourceType: "dashboard",+ });++ mountGuestEmbedDashboard({ token });++ getSdkRoot().within(() => {+ cy.findByText("Embedding SDK Test Dashboard").should("be.visible");+ });++ // Wait for requests+ cy.wait(WAIT_FOR_INTERNAL_API_REQUESTS_MS);++ cy.get("@internalApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length(0);+ });+ });+ });++ it("should show content of a question with `map` type with tiles for unauthorized user", () => {+ setup({+ questionDetails: {+ ...questionAsPinMapWithTiles,+ query: {+ "source-table": PEOPLE_ID,+ },+ } as StructuredQuestionDetails,+ });++ cy.intercept("GET", "/api/embed/tiles/dashboard/**").as(+ "mapTilesApiRequest",+ );++ cy.get("@dashboardId").then(async (dashboardId) => {+ const token = await getSignedJwtForResource({+ resourceId: dashboardId as unknown as number,+ resourceType: "dashboard",+ });++ mountGuestEmbedDashboard({ token });++ cy.wait("@mapTilesApiRequest");++ cy.get("@mapTilesApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length.greaterThan(1);+ });+ });+ });++ it("should properly work with dashboard parameters", () => {+ signInAsAdminAndSetupGuestEmbedding({+ token: "starter",+ });++ createNativeQuestionAndDashboard({+ questionDetails: {+ name: "Orders native question",+ native: {+ query:+ "SELECT * " ++ "FROM ORDERS " ++ "JOIN PEOPLE ON ORDERS.USER_ID = PEOPLE.ID " ++ "WHERE {{quantity}} AND {{product_id_fk}} AND {{user_id_pk}}",+ "template-tags": TEMPLATE_TAGS,+ },+ },+ dashboardDetails: {+ name: "Embedding SDK Test Dashboard",+ embedding_type: "guest-embed",+ parameters: PARAMETERS,+ enable_embedding: true,+ embedding_params: {+ quantity: "enabled",+ product_id_fk: "locked",+ user_id_pk: "enabled",+ },+ },+ }).then(({ body: { id: dashcardId, card_id, dashboard_id } }) => {+ // Connect dashboard parameters to the card's template-tags+ cy.request("PUT", `/api/dashboard/${dashboard_id}`, {+ dashcards: [+ {+ id: dashcardId,+ card_id,+ row: 0,+ col: 0,+ size_x: 16,+ size_y: 8,+ parameter_mappings: [+ {+ parameter_id: "quantity",+ card_id,+ target: ["dimension", ["template-tag", "quantity"]],+ },+ {+ parameter_id: "product_id_fk",+ card_id,+ target: ["dimension", ["template-tag", "product_id_fk"]],+ },+ {+ parameter_id: "user_id_pk",+ card_id,+ target: ["dimension", ["template-tag", "user_id_pk"]],+ },+ ],+ },+ ],+ });++ cy.wrap(dashboard_id).as("dashboardId");+ });++ cy.signOut();++ cy.intercept("GET", "/api/embed/dashboard/*/params/*/values").as(+ "parameterValuesApiRequest",+ );++ cy.get("@dashboardId").then(async (dashboardId) => {+ const token = await getSignedJwtForResource({+ resourceId: dashboardId as unknown as number,+ resourceType: "dashboard",+ params: {+ product_id_fk: 1,+ },+ });++ mountGuestEmbedDashboard({ token });++ getSdkRoot().within(() => {+ cy.findAllByTestId("parameter-widget").should("have.length", 2);++ cy.findAllByTestId("parameter-widget")+ .filter(':contains("PK->Name")')+ .click();+ });++ cy.wait("@parameterValuesApiRequest");++ cy.get("@parameterValuesApiRequest.all").then((interceptions) => {+ expect(interceptions).to.have.length(1);+ });++ cy.findByTestId("table-body")+ .findAllByRole("row")+ .should("have.length.above", 10);++ getSdkRoot().within(() => {+ cy.findByTestId("parameter-value-dropdown").contains("74").click();+ cy.findByTestId("parameter-value-dropdown")+ .contains("Add filter")+ .click();++ cy.findByTestId("table-body")+ .findAllByRole("row")+ .should("have.length", 1);+ });+ });+ });+ });+});diff --git a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.jsindex cdeea573f26..93f4c640c8b 100644--- a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js+++ b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js@@ -354,16 +354,24 @@ const MODEL_NAME = "Test Action Model";});cy.visit(`/dashboard/${dashboard.id}`);cy.wrap(dashboard.id).as("dashboardId");++ cy.log("The action should be visible in the dashboard");+ cy.findByRole("button", { name: "Create" }).should(+ "be.visible",+ );++ cy.log("Visit static embed dashboard");++ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard.id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });},);});- cy.log("The action should be visible in the dashboard");- cy.findByRole("button", { name: "Create" }).should("be.visible");-- cy.log("Visit static embed dashboard");-- H.openStaticEmbeddingModal({ activeTab: "parameters" });H.visitIframe();cy.log("Assert static embed dashboard");diff --git a/e2e/test/scenarios/admin/i18n/content-translation/dashboards.cy.spec.ts b/e2e/test/scenarios/admin/i18n/content-translation/dashboards.cy.spec.tsindex 49898b6a68d..c16757ca2e2 100644--- a/e2e/test/scenarios/admin/i18n/content-translation/dashboards.cy.spec.ts+++ b/e2e/test/scenarios/admin/i18n/content-translation/dashboards.cy.spec.ts@@ -7,6 +7,7 @@ import type {DashboardDetails,StructuredQuestionDetails,} from "e2e/support/helpers";+import { uploadTranslationDictionaryViaAPI } from "e2e/support/helpers/e2e-content-translation-helpers";import {ORDERS_COUNT_BY_CREATED_AT_AND_PRODUCT_CATEGORY,PRODUCTS_COUNT_BY_CATEGORY_PIE,@@ -22,11 +23,10 @@ import {germanFieldNames,germanFieldValues,} from "./constants";-import { uploadTranslationDictionaryViaAPI } from "./helpers/e2e-content-translation-helpers";const { H } = cy;-describe("scenarios > content translation > static embedding > dashboards", () => {+describe("scenarios > content translation > static embeds > dashboards", () => {describe("pivot table renamed column (metabase#63296)", () => {beforeEach(() => {H.restore();@@ -85,8 +85,9 @@ describe("scenarios > content translation > static embedding > dashboards", () =H.saveDashboard();- H.openStaticEmbeddingModal({- acceptTerms: false,+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,});H.publishChanges("dashboard", () => {});@@ -156,7 +157,7 @@ describe("scenarios > content translation > static embedding > dashboards", () =);});- it("should translate static embedding dashboard card titles and descriptions", () => {+ it("should translate guest embeds dashboard card titles and descriptions", () => {H.createDashboard({name: "the_dashboard",}).then(({ body: { id: dashboardId } }) => {@@ -167,8 +168,9 @@ describe("scenarios > content translation > static embedding > dashboards", () =H.sidebar().findByText(PRODUCTS_COUNT_BY_CATEGORY_PIE.name).click();H.saveDashboard();- H.openStaticEmbeddingModal({- acceptTerms: false,+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,});H.publishChanges("dashboard", () => {});@@ -263,8 +265,9 @@ describe("scenarios > content translation > static embedding > dashboards", () =H.sidebar().findByText(PRODUCTS_COUNT_BY_CATEGORY_PIE.name).click();H.saveDashboard();- H.openStaticEmbeddingModal({- acceptTerms: false,+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,});H.publishChanges("dashboard", () => {});@@ -307,7 +310,7 @@ describe("scenarios > content translation > static embedding > dashboards", () =});});- it("should translate static embedding dashboard values on visualizer cards (metabase#62373)", () => {+ it("should translate guest embeds dashboard values on visualizer cards (metabase#62373)", () => {H.visitDashboard(ORDERS_DASHBOARD_ID);H.editDashboard();@@ -327,8 +330,9 @@ describe("scenarios > content translation > static embedding > dashboards", () =H.saveDashcardVisualizerModal({ mode: "create" });H.saveDashboard();- H.openStaticEmbeddingModal({- acceptTerms: false,+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: ORDERS_DASHBOARD_ID,});H.publishChanges("dashboard", () => {});diff --git a/e2e/test/scenarios/admin/i18n/content-translation/helpers/e2e-content-translation-helpers.ts b/e2e/test/scenarios/admin/i18n/content-translation/helpers/e2e-content-translation-helpers.tsindex d0e848590d0..294a048a2f7 100644--- a/e2e/test/scenarios/admin/i18n/content-translation/helpers/e2e-content-translation-helpers.ts+++ b/e2e/test/scenarios/admin/i18n/content-translation/helpers/e2e-content-translation-helpers.ts@@ -1,23 +1,17 @@import { parse } from "csv-parse/browser/esm/sync";import { METABASE_SECRET_KEY } from "e2e/support/cypress_data";+import { getCSVWithHeaderRow } from "e2e/support/helpers/e2e-content-translation-helpers";import type { DictionaryArray, DictionaryResponse } from "metabase-types/api";import { isDictionaryArray } from "metabase-types/guards/content-translation";-export const getCSVWithHeaderRow = (dictionary: DictionaryArray) => {- const header = ["Language", "String", "Translation"];- return [header, ...dictionary]- .map((row) => Object.values(row).join(","))- .join("\n");-};-export const uploadTranslationDictionary = (rows: DictionaryArray) => {cy.intercept("POST", "/api/ee/content-translation/upload-dictionary").as("uploadDictionary",);cy.intercept("GET", "/api/setting").as("getSettings");cy.signInAsAdmin();- cy.visit("/admin/embedding/static");+ cy.visit("/admin/embedding");cy.wait("@getSettings");cy.findByTestId("content-localization-setting").findByText(@@ -44,27 +38,6 @@ export const uploadTranslationDictionary = (rows: DictionaryArray) => {}).scrollIntoView();};-export const uploadTranslationDictionaryViaAPI = (rows: DictionaryArray) => {- cy.signInAsAdmin();- const csvString = getCSVWithHeaderRow(rows);- const fileBlob = new Blob([csvString], { type: "text/csv" });- const formData = new FormData();- formData.append("file", fileBlob, "dictionary.csv");-- return cy- .request({- method: "POST",- url: "/api/ee/content-translation/upload-dictionary",- body: formData,- headers: {- "Content-Type": "multipart/form-data",- },- })- .then((response) => {- expect(response.status).to.equal(200);- });-};-export const assertOnlyTheseTranslationsAreStored = (rows: DictionaryArray,locale = "de",diff --git a/e2e/test/scenarios/admin/i18n/content-translation/questions.cy.spec.ts b/e2e/test/scenarios/admin/i18n/content-translation/questions.cy.spec.tsindex 4c61fcbac3f..0fcd8ba6656 100644--- a/e2e/test/scenarios/admin/i18n/content-translation/questions.cy.spec.ts+++ b/e2e/test/scenarios/admin/i18n/content-translation/questions.cy.spec.ts@@ -1,14 +1,14 @@import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import { NORMAL_USER_ID } from "e2e/support/cypress_sample_instance_data";+import { uploadTranslationDictionaryViaAPI } from "e2e/support/helpers/e2e-content-translation-helpers";import { germanFieldNames } from "./constants";-import { uploadTranslationDictionaryViaAPI } from "./helpers/e2e-content-translation-helpers";const { PRODUCTS_ID } = SAMPLE_DATABASE;const { H } = cy;-describe("scenarios > content translation > static embedding > questions", () => {+describe("scenarios > content translation > guest embeds > questions", () => {describe("ee", () => {beforeEach(() => {cy.intercept("POST", "/api/ee/content-translation/upload-dictionary").as(diff --git a/e2e/test/scenarios/admin/i18n/content-translation/upload-and-download.cy.spec.ts b/e2e/test/scenarios/admin/i18n/content-translation/upload-and-download.cy.spec.tsindex 53274257c81..118085172fa 100644--- a/e2e/test/scenarios/admin/i18n/content-translation/upload-and-download.cy.spec.ts+++ b/e2e/test/scenarios/admin/i18n/content-translation/upload-and-download.cy.spec.ts@@ -1,5 +1,10 @@import path from "path";+import {+ getCSVWithHeaderRow,+ uploadTranslationDictionaryViaAPI,+} from "e2e/support/helpers/e2e-content-translation-helpers";+import {germanFieldNames,invalidLocaleXX,@@ -11,14 +16,12 @@ import {import {assertOnlyTheseTranslationsAreStored,generateLargeCSV,- getCSVWithHeaderRow,uploadTranslationDictionary,- uploadTranslationDictionaryViaAPI,} from "./helpers/e2e-content-translation-helpers";const { H } = cy;-describe("scenarios > admin > embedding > static embedding> content translation", () => {+describe("scenarios > admin > embedding > guest embeds> content translation", () => {describe("oss", () => {beforeEach(() => {H.restore();@@ -26,7 +29,7 @@ describe("scenarios > admin > embedding > static embedding> content translation"});it("admin settings configuration form is not present", () => {- cy.visit("/admin/embedding/static");+ cy.visit("/admin/embedding/guest");cy.findByTestId("content-translation-configuration").should("not.exist");});});@@ -52,7 +55,7 @@ describe("scenarios > admin > embedding > static embedding> content translation"describe("The translation download button", () => {it("downloads the stored translations", () => {uploadTranslationDictionaryViaAPI(germanFieldNames);- cy.visit("/admin/embedding/static");+ cy.visit("/admin/embedding");cy.findByTestId("content-translation-configuration").button(/Get translation dictionary template/i).click();@@ -180,7 +183,7 @@ describe("scenarios > admin > embedding > static embedding> content translation"});it("rejects, in the frontend, a CSV upload that is too big", () => {- cy.visit("/admin/embedding/static");+ cy.visit("/admin/embedding");cy.get("#content-translation-dictionary-upload-input").selectFile({contents: Cypress.Buffer.from(@@ -206,7 +209,7 @@ describe("scenarios > admin > embedding > static embedding> content translation"});it("rejects invalid CSV", () => {- cy.visit("/admin/embedding/static");+ cy.visit("/admin/embedding");const validCSV = getCSVWithHeaderRow(germanFieldNames);const invalidCSV = validCSV + '\nde,Price,"Preis"X';diff --git a/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js b/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.jsindex 096206593a9..04f8ec26d89 100644--- a/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js+++ b/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js@@ -1958,12 +1958,15 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {}).then(({ body: dashCard }) => {H.visitDashboard(dashCard.dashboard_id);++ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashCard.dashboard_id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });});- H.openStaticEmbeddingModal({- activeTab: "parameters",- acceptTerms: false,- });H.visitIframe();clickLineChartPoint();diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.jsindex c980bd3ec26..664d18cc087 100644--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js@@ -1123,7 +1123,10 @@ describe("scenarios > dashboard", () => {cy.contains("37.65");assertScrollBarExists();- H.openSharingMenu("Embed");+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: ORDERS_DASHBOARD_ID,+ });H.modal().within(() => {cy.icon("close").click();diff --git a/e2e/test/scenarios/dashboard/tabs.cy.spec.js b/e2e/test/scenarios/dashboard/tabs.cy.spec.jsindex 0b0f0cddc29..2683ad64bf3 100644--- a/e2e/test/scenarios/dashboard/tabs.cy.spec.js+++ b/e2e/test/scenarios/dashboard/tabs.cy.spec.js@@ -554,7 +554,11 @@ describe("scenarios > dashboard > tabs", () => {cy.spy().as("secondTabQuerySpy"),).as("secondTabQuery");- H.openStaticEmbeddingModal({ activeTab: "parameters", acceptTerms: true });+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: ORDERS_DASHBOARD_ID,+ activeTab: "parameters",+ });// publish the embedded dashboard so that we can directly navigate to its urlH.publishChanges("dashboard", () => {});diff --git a/e2e/test/scenarios/embedding/embedding-admin-settings-oss.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-admin-settings-oss.cy.spec.tsindex 704c5da6ebc..cb73c0a2e5c 100644--- a/e2e/test/scenarios/embedding/embedding-admin-settings-oss.cy.spec.ts+++ b/e2e/test/scenarios/embedding/embedding-admin-settings-oss.cy.spec.ts@@ -15,48 +15,43 @@ describe(cy.log("Navigate to Embedding admin section");cy.visit("/admin/embedding");- cy.log("Check that we're on the modular embedding page");- cy.url().should("include", "/admin/embedding/modular");- cy.get("main").findByText("Modular embedding").should("be.visible");-- cy.log("Verify sidebar contains static smbedding link");- cy.findByTestId("admin-layout-sidebar")- .findByRole("link", { name: /Static/ })- .should("have.attr", "href", "/admin/embedding/static");-- cy.log("Verify sidebar contains interactive embedding");- cy.findByTestId("admin-layout-sidebar")- .findByRole("link", { name: /Interactive/ })- .should("have.attr", "href", "/admin/embedding/interactive");+ cy.log("Check that we're on the embedding settings page");+ cy.url().should("include", "/admin/embedding");+ cy.get("main").findByText("Embedding settings").should("be.visible");cy.log("Verify sidebar does not contain setup guide");cy.findByTestId("admin-layout-sidebar").findByRole("link", { name: /Setup guide/ }).should("not.exist");- cy.log("Verify 2 upsell icons are present in sidebar");+ cy.log("Verify sidebar does not contain guest embeds link");cy.findByTestId("admin-layout-sidebar")- .icon("gem")- .should("have.length", 2);+ .findByRole("link", { name: /Guest embeds/ })+ .should("not.exist");++ cy.log("Verify sidebar does not contain security settings link");+ cy.findByTestId("admin-layout-sidebar")+ .findByRole("link", { name: /Security/ })+ .should("not.exist");});- it("should show interactive embedding upsell on oss", () => {+ it("should show embedding upsell on oss", () => {cy.visit("/admin/embedding/interactive");cy.findByTestId("admin-layout-content").within(() => {- cy.findByRole("heading", { name: "Interactive embedding" }).should(+ cy.findByRole("heading", { name: "Embedding settings" }).should("be.visible",);cy.log("upsell gem icon should be visible");cy.icon("gem").should("be.visible");- cy.findByRole("link", { name: /Check out our Quickstart/i })- .should("be.visible")- .and("have.attr", "href")- .and("contain", "interactive-embedding-quick-start-guide");-- cy.findByRole("link", { name: "Try for free" }).should("be.visible");+ cy.findByRole("link", { name: "Upgrade" })+ .should("have.attr", "href")+ .and(+ "eq",+ "https://www.metabase.com/upgrade?utm_source=product&utm_medium=upsell&utm_content=embedding-page&source_plan=oss&utm_users=10&utm_campaign=embedded-analytics-js",+ );});});},diff --git a/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.js b/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.jsindex f98381e274c..53fb87eb1ac 100644--- a/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.js@@ -68,9 +68,12 @@ describe("scenarios > embedding > dashboard parameters", () => {it("should be disabled by default but able to be set to editable and/or locked (metabase#20357)", () => {H.visitDashboard("@dashboardId");- H.openStaticEmbeddingModal({- activeTab: "parameters",- acceptTerms: true,+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ });});cy.findByLabelText("Configuring parameters").as("allParameters");@@ -119,6 +122,9 @@ describe("scenarios > embedding > dashboard parameters", () => {assert.deepEqual(request.body.embedding_params, {id: "locked",name: "enabled",+ source: "disabled",+ user_id: "disabled",+ not_used: "disabled",});});@@ -153,11 +159,14 @@ describe("scenarios > embedding > dashboard parameters", () => {H.visitDashboard("@dashboardId");- H.openStaticEmbeddingModal({- activeTab: "parameters",- acceptTerms: false,+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });});-cy.get("@allParameters").findByText("Locked").click();H.popover().contains("Disabled").click();@@ -168,6 +177,9 @@ describe("scenarios > embedding > dashboard parameters", () => {assert.deepEqual(request.body.embedding_params, {name: "disabled",id: "disabled",+ source: "disabled",+ user_id: "disabled",+ not_used: "disabled",});});@@ -235,11 +247,15 @@ describe("scenarios > embedding > dashboard parameters", () => {});H.saveDashboard();- // Check that parameter visibility is correct- H.openStaticEmbeddingModal({- activeTab: "parameters",- acceptTerms: true,+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ });});++ // Check that parameter visibility is correctH.assertEmbeddingParameter("Id", "Disabled");H.assertEmbeddingParameter("Name", "Editable");H.assertEmbeddingParameter("Source", "Disabled");@@ -251,7 +267,11 @@ describe("scenarios > embedding > dashboard parameters", () => {// "enabled" must be set by default for required params.H.publishChanges("dashboard", ({ request }) => {assert.deepEqual(request.body.embedding_params, {+ id: "disabled",name: "enabled",+ source: "disabled",+ user_id: "disabled",+ not_used: "disabled",});});@@ -268,17 +288,24 @@ describe("scenarios > embedding > dashboard parameters", () => {it("should (dis)allow setting parameters as required for a published embedding", () => {H.visitDashboard("@dashboardId");- // Set an "editable" and "locked" parameters and leave the rest "disabled"- H.openStaticEmbeddingModal({- activeTab: "parameters",- acceptTerms: true,+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ });});++ // Set an "editable" and "locked" parameters and leave the rest "disabled"H.setEmbeddingParameter("Name", "Editable");H.setEmbeddingParameter("Source", "Locked");H.publishChanges("dashboard", ({ request }) => {assert.deepEqual(request.body.embedding_params, {+ id: "disabled",name: "enabled",source: "locked",+ user_id: "disabled",+ not_used: "disabled",});});@@ -394,9 +421,13 @@ describe("scenarios > embedding > dashboard parameters", () => {it("should allow searching dashboard parameters in preview embed modal", () => {H.visitDashboard("@dashboardId");- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ previewMode: "preview",+ });});H.modal().within(() => {@@ -637,15 +668,24 @@ describe("scenarios > embedding > dashboard parameters with defaults", () => {});it("card parameter defaults should apply for disabled parameters, but not for editable or locked parameters", () => {- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ });+ });// ID param is disabled by defaultH.setEmbeddingParameter("Name", "Editable");H.setEmbeddingParameter("Source", "Locked");H.publishChanges("dashboard", ({ request }) => {assert.deepEqual(request.body.embedding_params, {+ id: "disabled",source: "locked",name: "enabled",+ user_id: "disabled",+ not_used: "disabled",});});@@ -723,7 +763,16 @@ describe("scenarios > embedding > dashboard parameters with defaults", () => {});H.visitDashboard("@dashboardId");- H.openStaticEmbeddingModal({ activeTab: "parameters" });++ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });+H.visitIframe();cy.log("should show card results by default");@@ -781,19 +830,19 @@ describe("scenarios > embedding > dashboard appearance", () => {dashboardDetails,}).then(({ body: { dashboard_id } }) => {H.visitDashboard(dashboard_id);- });- cy.intercept(- "GET",- "api/preview_embed/dashboard/*",- cy.spy().as("previewEmbedSpy"),- ).as("previewEmbed");-- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",- // EE users don't have to accept terms- acceptTerms: false,+ cy.intercept(+ "GET",+ "api/preview_embed/dashboard/*",+ cy.spy().as("previewEmbedSpy"),+ ).as("previewEmbed");++ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,+ activeTab: "parameters",+ previewMode: "preview",+ });});cy.wait("@previewEmbed");@@ -916,20 +965,20 @@ describe("scenarios > embedding > dashboard appearance", () => {}).then((dashboard) => {H.visitDashboard(dashboard.id);- });- cy.intercept(- "GET",- "api/preview_embed/dashboard/*",- cy.spy().as("previewEmbedSpy"),- ).as("previewEmbed");-- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",- // EE users don't have to accept terms- acceptTerms: false,- });+ cy.intercept(+ "GET",+ "api/preview_embed/dashboard/*",+ cy.spy().as("previewEmbedSpy"),+ ).as("previewEmbed");++ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard.id,+ activeTab: "parameters",+ previewMode: "preview",+ });+ });cy.wait("@previewEmbed");@@ -1220,10 +1269,11 @@ describe("scenarios > embedding > dashboard appearance", () => {}).then(({ body: { dashboard_id } }) => {H.visitDashboard(dashboard_id);- H.openStaticEmbeddingModal({+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,activeTab: "parameters",previewMode: "preview",- acceptTerms: false,});H.modal().within(() => {diff --git a/e2e/test/scenarios/embedding/embedding-native.cy.spec.js b/e2e/test/scenarios/embedding/embedding-native.cy.spec.jsindex e022b81bd95..0ad6da45d14 100644--- a/e2e/test/scenarios/embedding/embedding-native.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-native.cy.spec.js@@ -28,14 +28,27 @@ describe("scenarios > embedding > native questions", () => {visitQuestion: true,});- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@questionId").then((questionId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,+ activeTab: "parameters",+ });+ });}it("should not display disabled parameters", () => {createAndVisitQuestion();H.publishChanges("card", ({ request }) => {- assert.deepEqual(request.body.embedding_params, {});+ assert.deepEqual(request.body.embedding_params, {+ id: "disabled",+ state: "disabled",+ created_at: "disabled",+ total: "disabled",+ source: "disabled",+ product_id: "disabled",+ });});H.visitIframe();@@ -68,6 +81,7 @@ describe("scenarios > embedding > native questions", () => {total: "locked",state: "enabled",product_id: "enabled",+ source: "disabled",};assert.deepEqual(actual, expected);@@ -148,7 +162,12 @@ describe("scenarios > embedding > native questions", () => {// weren't touched and therefore aren't changed, whereas// "enabled" must be set by default for required params.const expected = {+ id: "disabled",+ state: "disabled",+ created_at: "disabled",total: "enabled",+ source: "disabled",+ product_id: "disabled",};assert.deepEqual(actual, expected);@@ -352,10 +371,15 @@ describe("scenarios > embedding > native questions", () => {});it("locked parameters should still render results in the preview by default (metabase#47570)", () => {- H.visitQuestion("@questionId");- H.openStaticEmbeddingModal({- activeTab: "parameters",+ H.visitQuestion("@questionId").then((id) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });});+H.visitIframe();cy.log("should show card results by default");@@ -377,15 +401,23 @@ describe("scenarios > embedding > native questions with default parameters", ()wrapId: true,});- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@questionId").then((questionId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,+ activeTab: "parameters",+ });+ });// Note: ID is disabledH.setEmbeddingParameter("Source", "Locked");H.setEmbeddingParameter("Name", "Editable");H.publishChanges("card", ({ request }) => {assert.deepEqual(request.body.embedding_params, {+ id: "disabled",source: "locked",name: "enabled",+ user_id: "disabled",});});});diff --git a/e2e/test/scenarios/embedding/embedding-questions.cy.spec.js b/e2e/test/scenarios/embedding/embedding-questions.cy.spec.jsindex aea3f8f0df7..d8ba1838d42 100644--- a/e2e/test/scenarios/embedding/embedding-questions.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-questions.cy.spec.js@@ -44,10 +44,17 @@ describe("scenarios > embedding > questions", () => {display: "scalar",enable_embedding: true,},- { visitQuestion: true },+ { visitQuestion: true, wrapId: true },);- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@questionId").then((questionId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });H.visitIframe();@@ -66,10 +73,14 @@ describe("scenarios > embedding > questions", () => {cy.request("PUT", `/api/card/${id}`, { enable_embedding: true });H.visitQuestion(id);+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });});- H.openStaticEmbeddingModal({ activeTab: "parameters" });-H.visitIframe();cy.findByTestId("embed-frame").within(() => {@@ -106,9 +117,14 @@ describe("scenarios > embedding > questions", () => {cy.request("PUT", `/api/card/${id}`, { enable_embedding: true });H.visitQuestion(id);- });- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });H.visitIframe();@@ -141,11 +157,16 @@ describe("scenarios > embedding > questions", () => {cy.request("PUT", `/api/card/${nestedId}`, { enable_embedding: true });H.visitQuestion(nestedId);++ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: nestedId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });});});- H.openStaticEmbeddingModal({ activeTab: "parameters" });-H.visitIframe();// Global (Data model) settings should be preserved@@ -178,9 +199,14 @@ describe("scenarios > embedding > questions", () => {cy.request("PUT", `/api/card/${id}`, { enable_embedding: true });H.visitQuestion(id);- });- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });H.visitIframe();@@ -247,7 +273,7 @@ describe("scenarios [EE] > embedding > questions", () => {cy.wait("@deLocale");- H.main().findByText("Februar 11, 2025, 9:40 PM");+ H.main().findByText("Februar 11, 2025, 9:40 PM").realHover();cy.findByRole("button", { name: "Ergebnis downloaden" }).should("exist");cy.url().should("include", "locale=de");});@@ -313,7 +339,11 @@ describe("scenarios > embedding > questions > downloads", () => {cy.get("@questionId").then((questionId) => {H.visitQuestion(questionId);- H.openStaticEmbeddingModal({ activeTab: "lookAndFeel" });+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,+ activeTab: "lookAndFeel",+ });cy.log("Embedding settings page should not show option to disable downloads",@@ -375,9 +405,10 @@ describe("scenarios > embedding > questions > downloads", () => {cy.get("@questionId").then((questionId) => {H.visitQuestion(questionId);- H.openStaticEmbeddingModal({+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,activeTab: "lookAndFeel",- acceptTerms: false,});cy.log("Disable downloads");diff --git a/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.js b/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.jsindex 5dc5fd1be6e..e492bf2ab8b 100644--- a/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.js@@ -141,14 +141,17 @@ describe("issue 15860", { tags: "@skip" }, () => {});H.visitDashboard(dashboard_id);++ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });});});it("should work for locked linked filters connected to different cards with the same source table (metabase#15860)", () => {- cy.icon("share").click();- // eslint-disable-next-line no-unscoped-text-selectors -- deprecated usage- cy.findByText("Embed in your application").click();-setDefaultValueForLockedFilter("Q1 ID", 1);setDefaultValueForLockedFilter("Q2 ID", 3);@@ -243,12 +246,22 @@ describe("issue 20438", () => {embedding_params: { [filter.slug]: "enabled" },});+ cy.wrap(card_id).as("questionId");+ cy.wrap(dashboard_id).as("dashboardId");+H.visitDashboard(dashboard_id);});});it("dashboard filter connected to the field filter should work with a single value in embedded dashboards (metabase#20438)", () => {- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@dashboardId").then((dashboardId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboardId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });H.visitIframe();@@ -294,12 +307,22 @@ describe("locked parameters in embedded question (metabase#20634)", () => {},},},- { visitQuestion: true },+ {+ visitQuestion: true,+ wrapId: true,+ },);});it("should let the user lock parameters to specific values", () => {- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@questionId").then((questionId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });H.modal().within(() => {// select the dropdown next to the Text parameter so that we can set the value to "Locked"@@ -318,7 +341,7 @@ describe("locked parameters in embedded question (metabase#20634)", () => {cy.findByPlaceholderText("Text").type("foo{enter}");// publish the embedded question so that we can directly navigate to its url- cy.findByText("Publish").click();+ cy.findByText("Publish changes").click();cy.wait("@publishChanges");});@@ -671,16 +694,18 @@ describe("issue 30535", () => {cy.request("PUT", `/api/card/${id}`, { enable_embedding: true });H.visitQuestion(id);++ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: id,+ activeTab: "parameters",+ previewMode: "preview",+ unpublishBeforeOpen: false,+ });});});it("user session should not apply sandboxing to a signed embedded question (metabase#30535)", () => {- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",- acceptTerms: false,- });-cy.document().then((doc) => {const iframe = doc.querySelector("iframe");@@ -790,11 +815,13 @@ describe("dashboard preview", () => {});H.visitDashboard(dashboard_id);- });- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,+ activeTab: "parameters",+ previewMode: "preview",+ });});H.modal().within(() => {@@ -875,11 +902,13 @@ describe("dashboard preview", () => {});H.visitDashboard(dashboard_id);- });- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,+ activeTab: "parameters",+ previewMode: "preview",+ });});// Makes it less likely to flake.@@ -943,7 +972,9 @@ describe("issue 40660", () => {H.restore();cy.signInAsAdmin();+ });+ it("static dashboard content shouldn't overflow its container (metabase#40660)", () => {H.createQuestionAndDashboard({questionDetails,dashboardDetails,@@ -954,13 +985,13 @@ describe("issue 40660", () => {});H.visitDashboard(dashboard_id);- });- });- it("static dashboard content shouldn't overflow its container (metabase#40660)", () => {- H.openStaticEmbeddingModal({- activeTab: "parameters",- previewMode: "preview",+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,+ activeTab: "parameters",+ previewMode: "preview",+ });});H.getIframeBody().within(() => {@@ -991,20 +1022,23 @@ describe("issue 49142", { tags: "@skip" }, () => {beforeEach(() => {H.restore();cy.signInAsAdmin();+ });+ it("embedding preview should be always working", () => {H.createQuestionAndDashboard({questionDetails,dashboardDetails,}).then(({ body: { dashboard_id } }) => {H.visitDashboard(dashboard_id);- });- });- it("embedding preview should be always working", () => {- H.openStaticEmbeddingModal({- activeTab: "lookAndFeel",- previewMode: "preview",+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: dashboard_id,+ activeTab: "lookAndFeel",+ previewMode: "preview",+ });});+cy.findByTestId("embed-preview-iframe").its("0.contentDocument.body").should("be.visible")@@ -1505,9 +1539,17 @@ describe("issue 63687", () => {it("should properly display pin map tiles without auth errors for a valid JWT token", () => {H.createNativeQuestion(questionAsPinMapWithTiles, {visitQuestion: true,+ wrapId: true,});- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ cy.get("@questionId").then((questionId) => {+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: questionId,+ activeTab: "parameters",+ unpublishBeforeOpen: false,+ });+ });cy.intercept("/api/embed/tiles/**").as("getTiles");diff --git a/e2e/test/scenarios/embedding/embedding-smoketests.cy.spec.js b/e2e/test/scenarios/embedding/embedding-smoketests.cy.spec.jsindex 5f2ba9cb413..b92bc0ec598 100644--- a/e2e/test/scenarios/embedding/embedding-smoketests.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-smoketests.cy.spec.js@@ -6,7 +6,7 @@ import {ORDERS_QUESTION_ID,} from "e2e/support/cypress_sample_instance_data";-const standalonePath = "/admin/embedding/static";+const standalonePath = "/admin/embedding/guest";// These tests will run on both OSS and EE instances. Both without a token!describe("scenarios > embedding > smoke tests", { tags: "@OSS" }, () => {@@ -39,29 +39,23 @@ describe("scenarios > embedding > smoke tests", { tags: "@OSS" }, () => {});it("should show the sdk upsell link in oss", () => {- cy.visit("/admin/embedding/modular");+ cy.visit("/admin/embedding");mainPage().within(() => {- cy.findByRole("link", { name: "Try for free" })+ cy.findByRole("link", { name: "Upgrade" }).should("have.attr", "href").and("eq",- "https://www.metabase.com/product/embedded-analytics?utm_source=product&utm_medium=upsell&utm_campaign=embedded-analytics-js&utm_content=embedding-page&source_plan=oss",+ "https://www.metabase.com/upgrade?utm_source=product&utm_medium=upsell&utm_content=embedding-page&source_plan=oss&utm_users=10&utm_campaign=embedded-analytics-js",);});});- it("should not let you embed the question", () => {+ it("should not let you use non-guest auth methods", () => {H.visitQuestion(ORDERS_QUESTION_ID);ensureEmbeddingIsDisabled();});-- it("should not let you embed the dashboard", () => {- H.visitDashboard(ORDERS_DASHBOARD_ID);-- ensureEmbeddingIsDisabled();- });});context("embedding enabled", () => {@@ -238,7 +232,7 @@ describe("scenarios > embedding > smoke tests", { tags: "@OSS" }, () => {cy.request("PUT", `/api/card/${ORDERS_QUESTION_ID}`, {enable_embedding: true,});- visitAndEnableSharing("question");+ visitAndEnableSharing("question", false);H.modal().within(() => {cy.findByRole("tab", { name: "Parameters" }).click();@@ -302,29 +296,34 @@ function resetEmbedding() {}function ensureEmbeddingIsDisabled() {- H.openSharingMenu();- H.sharingMenu()- .findByRole("menuitem", { name: "Embed" })- .should("be.enabled")- .click();- H.modal()- .findByRole("article", { name: "Static embedding" })- .within(() => {- cy.findByText("Disabled.").should("be.visible");- cy.findByText("Enable in admin settings").should("be.visible");- });-}--function visitAndEnableSharing(object, acceptTerms = true) {- if (object === "question") {- H.visitQuestion(ORDERS_QUESTION_ID);- }+ H.openEmbedJsModal();+ H.embedModalEnableEmbedding();- if (object === "dashboard") {- H.visitDashboard(ORDERS_DASHBOARD_ID);- }+ H.embedModalContent().within(() => {+ cy.findByLabelText("Single sign-on (SSO)").should("be.disabled");+ cy.findByLabelText("Existing Metabase session").should("be.disabled");+ });+}- H.openStaticEmbeddingModal({ acceptTerms });+function visitAndEnableSharing(object, unpublishBeforeOpen = true) {+ const { id, visitFunction } = {+ question: {+ id: ORDERS_QUESTION_ID,+ visitFunction: H.visitQuestion,+ },+ dashboard: {+ id: ORDERS_DASHBOARD_ID,+ visitFunction: H.visitDashboard,+ },+ }[object];++ visitFunction(id);++ H.openLegacyStaticEmbeddingModal({+ resource: object,+ resourceId: id,+ unpublishBeforeOpen,+ });}function mainPage() {diff --git a/e2e/test/scenarios/embedding/embedding-snippets.cy.spec.js b/e2e/test/scenarios/embedding/embedding-snippets.cy.spec.jsindex 5d47637d112..ef37a57d1c8 100644--- a/e2e/test/scenarios/embedding/embedding-snippets.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-snippets.cy.spec.js@@ -28,7 +28,11 @@ tokens.forEach((token) => {const defaultDownloadsValue =token === "pro-self-hosted" ? true : undefined;H.visitDashboard(ORDERS_DASHBOARD_ID);- H.openStaticEmbeddingModal({ acceptTerms: false });+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: ORDERS_DASHBOARD_ID,+ acceptTerms: false,+ });H.modal().within(() => {cy.findByText(@@ -127,7 +131,11 @@ tokens.forEach((token) => {const defaultDownloadsValue =token === "pro-self-hosted" ? true : undefined;H.visitQuestion(ORDERS_QUESTION_ID);- H.openStaticEmbeddingModal({ acceptTerms: false });+ H.openLegacyStaticEmbeddingModal({+ resource: "question",+ resourceId: ORDERS_QUESTION_ID,+ acceptTerms: false,+ });H.modal().within(() => {cy.findByText(diff --git a/e2e/test/scenarios/embedding/embedding-upsells.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-upsells.cy.spec.tsdeleted file mode 100644index c92fd557a41..00000000000--- a/e2e/test/scenarios/embedding/embedding-upsells.cy.spec.ts+++ /dev/null@@ -1,43 +0,0 @@-const { H } = cy;--describe("scenarios > embedding > upsells", { tags: "@EE" }, () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.updateSetting("show-sdk-embed-terms", false);- });-- it("should show the sdk settings page with upsell button", () => {- cy.on("window:before:load", (win) => {- // prevent Cypress opening in a new window/tab and spy on this method- cy.stub(win, "open").as("open");- });-- cy.visit("/admin/embedding/modular");-- mainPage().within(() => {- cy.contains("SDK for React").should("be.visible");- cy.contains("Embedded Analytics JS").should("be.visible");- });-- cy.findByRole("button", { name: "Try for free" }).click();-- cy.get<sinon.SinonSpy>("@open").should((spy) => {- const url = spy.getCall(0).args[0];-- expect(url).to.include(- "https://test-store.metabase.com/checkout/upgrade/self-hosted",- );-- expect(url).to.match(/utm_source=product/);- expect(url).to.match(/utm_medium=upsell/);- expect(url).to.match(/utm_campaign=embedded-analytics-js/);- expect(url).to.match(/utm_content=embedding-page/);- expect(url).to.match(/source_plan=oss/);- });- });-});--function mainPage() {- return cy.findByTestId("admin-layout-content");-}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.tsindex b54146fdb80..9ea9a363c49 100644--- 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@@ -59,6 +59,9 @@ describe("scenarios > embedding > sdk iframe embed setup > common", () => {});cy.wait("@dashboard");++ H.embedModalEnableEmbedding();+cy.get("[data-iframe-loaded]", { timeout: 20000 }).should("have.length", 1);H.modal().should("exist");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.tsindex 9b2066c1c63..0f022e8f09c 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@@ -1,71 +1,139 @@+import { embedModalEnableEmbeddingCard } from "e2e/support/helpers";+import { getEmbedSidebar } from "./helpers";const { H } = cy;-describe("scenarios > embedding > sdk iframe embed setup > enable embed js", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- H.updateSetting("enable-embedding-simple", false);+const { IS_ENTERPRISE } = Cypress.env();+const IS_OSS = !IS_ENTERPRISE;+const MB_EDITION = IS_ENTERPRISE ? "ee" : "oss";++const DATA_BY_MB_EDITION = {+ oss: {+ cardTestId: "guest-embeds-setting-card",+ cardText:+ "To continue, enable Guest embeds and agree to the usage conditions.",+ embeddingSettingName: "enable-embedding-static",+ showTermsSettingName: "show-static-embed-terms",+ },+ ee: {+ cardTestId: "sdk-setting-card",+ cardText:+ "To continue, enable Embedded Analytics JS and agree to the usage conditions.",+ embeddingSettingName: "enable-embedding-simple",+ showTermsSettingName: "show-simple-embed-terms",+ },+} as const;++describe(+ `scenarios > embedding > sdk iframe embed setup > enable embed js > ${MB_EDITION}`,+ { ...(IS_OSS && { tags: "@OSS" }) },+ () => {+ const { embeddingSettingName, showTermsSettingName, cardTestId, cardText } =+ DATA_BY_MB_EDITION[MB_EDITION];++ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();++ if (IS_ENTERPRISE) {+ H.activateToken("bleeding-edge");+ }++ H.mockEmbedJsToDevServer();+ });++ it("shows the Enable to Continue button and enables embedding on click", () => {+ H.updateSetting(embeddingSettingName, false);+ H.updateSetting(showTermsSettingName, true);- H.mockEmbedJsToDevServer();- });+ cy.visit("/admin/embedding");- it("shows the Enable to Continue button and enables embedding on click", () => {- cy.visit("/admin/embedding");+ cy.findAllByTestId(cardTestId)+ .first()+ .within(() => {+ cy.findByText("New embed").click();+ });- cy.findAllByTestId("sdk-setting-card")- .first()- .within(() => {- cy.findByText("New embed").click();+ embedModalEnableEmbeddingCard().within(() => {+ cy.findByText(cardText).should("exist");});- cy.log("shows tooltip with fair usage info");- getEmbedSidebar().findByLabelText("info icon").trigger("mouseover");+ cy.log("shows tooltip with fair usage info");+ getEmbedSidebar().findByLabelText("info icon").trigger("mouseover");- H.hovercard()- .contains(/When using the Embedded analytics SDK/)- .should("be.visible");+ H.hovercard()+ .contains(+ /You should, however, read the license text linked above as that is the actual license that you will be agreeing to by enabling this feature/,+ )+ .should("be.visible");- H.hovercard()- .contains(/Sharing Metabase accounts is a security risk/)- .should("be.visible");+ getEmbedSidebar().findByLabelText("info icon").trigger("mouseout");- cy.findByRole("button", { name: "Enable to continue" }).should(- "be.visible",- );+ cy.findByRole("button", { name: "Agree and enable" }).should(+ "be.visible",+ );- cy.log("preview panel should show placeholder");- cy.get('[alt="No results"]').should("be.visible");+ cy.log("preview panel should show placeholder");+ cy.get('[alt="No results"]').should("be.visible");- cy.findByRole("button", { name: "Enable to continue" }).click();+ cy.findByRole("button", { name: "Agree and enable" }).click();- cy.log("button should change to Enabled state");- cy.findByRole("button", { name: /Enabled/ })- .should("be.visible")- .should("be.disabled");+ cy.log("button should change to Enabled state");+ cy.findByRole("button", { name: /Enabled/ })+ .should("be.visible")+ .should("be.disabled");- cy.log("Preview should load after embedding is enabled");- H.waitForSimpleEmbedIframesToLoad();- H.getSimpleEmbedIframeContent().within(() => {- cy.findByText("Orders in a dashboard").should("be.visible");+ cy.log("Preview should load after embedding is enabled");+ H.waitForSimpleEmbedIframesToLoad();+ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByText("Orders in a dashboard").should("be.visible");+ });});- });- it("hides the enable card when embedding is already enabled", () => {- H.updateSetting("enable-embedding-simple", true);+ it("shows the enable card with fair usage terms when embedding is already enabled", () => {+ H.updateSetting(embeddingSettingName, true);+ H.updateSetting(showTermsSettingName, true);- cy.visit("/admin/embedding");+ cy.visit("/admin/embedding");- cy.findAllByTestId("sdk-setting-card")- .first()- .within(() => {- cy.findByText("New embed").click();+ cy.findAllByTestId(cardTestId)+ .first()+ .within(() => {+ cy.findByText("New embed").click();+ });++ embedModalEnableEmbeddingCard().within(() => {+ cy.findByText("Agree to the usage conditions to continue.").should(+ "exist",+ );++ cy.findByText(cardText).should("not.exist");});- getEmbedSidebar()- .contains("Enable Embedded Analytics JS to get started.")- .should("not.exist");- });-});+ cy.log("shows tooltip with fair usage info");+ getEmbedSidebar().findByLabelText("info icon").trigger("mouseover");++ H.hovercard()+ .contains(+ /You should, however, read the license text linked above as that is the actual license that you will be agreeing to by enabling this feature/,+ )+ .should("be.visible");+ });++ it("hides the enable card when embedding is already enabled", () => {+ H.updateSetting(embeddingSettingName, true);+ H.updateSetting(showTermsSettingName, false);++ cy.visit("/admin/embedding");++ cy.findAllByTestId(cardTestId)+ .first()+ .within(() => {+ cy.findByText("New embed").click();+ });++ getEmbedSidebar().contains(cardText).should("not.exist");+ });+ },+);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 d9632388661..6a8f1c4a4b0 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@@ -22,6 +22,7 @@ describe(suiteTitle, () => {H.activateToken("bleeding-edge");H.enableTracking();H.updateSetting("enable-embedding-simple", true);+ H.updateSetting("enable-embedding-static", false);H.mockEmbedJsToDevServer();});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/get-code.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/get-code.cy.spec.tsindex ad8ee599b69..0127061ae8d 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/get-code.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/get-code.cy.spec.ts@@ -3,9 +3,13 @@ import {ORDERS_DASHBOARD_ID,} from "e2e/support/cypress_sample_instance_data";import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";-import { enableSamlAuth } from "e2e/support/helpers/embedding-sdk-testing";-import { codeBlock, getEmbedSidebar, navigateToGetCodeStep } from "./helpers";+import {+ codeBlock,+ getEmbedSidebar,+ navigateToEmbedOptionsStep,+ navigateToGetCodeStep,+} from "./helpers";const { H } = cy;@@ -35,63 +39,6 @@ describe(suiteTitle, () => {H.expectNoBadSnowplowEvents();});- it("should select user session auth method by default", () => {- navigateToGetCodeStep({- experience: "dashboard",- resourceName: DASHBOARD_NAME,- });-- getEmbedSidebar().within(() => {- cy.findByText("Authentication").should("be.visible");- cy.findByText("Choose the authentication method for embedding:").should(- "be.visible",- );-- cy.findByLabelText("Existing Metabase session")- .should("be.visible")- .should("be.checked");-- cy.findByLabelText("Single sign-on (SSO)")- .should("be.visible")- .should("not.be.checked");- });- });-- it("should disable SSO radio button when JWT and SAML are not configured", () => {- navigateToGetCodeStep({- experience: "dashboard",- resourceName: DASHBOARD_NAME,- });-- getEmbedSidebar().within(() => {- cy.findByLabelText("Single sign-on (SSO)").should("be.disabled");- });- });-- it("should enable SSO radio button when JWT is configured", () => {- enableJwtAuth();- navigateToGetCodeStep({- experience: "dashboard",- resourceName: DASHBOARD_NAME,- });-- getEmbedSidebar().within(() => {- cy.findByLabelText("Single sign-on (SSO)").should("not.be.disabled");- });- });-- it("should enable SSO radio button when SAML is configured", () => {- enableSamlAuth();- navigateToGetCodeStep({- experience: "dashboard",- resourceName: DASHBOARD_NAME,- });-- getEmbedSidebar().within(() => {- cy.findByLabelText("Single sign-on (SSO)").should("not.be.disabled");- });- });-it("should display code snippet with syntax highlighting", () => {navigateToGetCodeStep({experience: "dashboard",@@ -107,81 +54,100 @@ describe(suiteTitle, () => {});it("should include useExistingUserSession when user session is selected", () => {- navigateToGetCodeStep({+ navigateToEmbedOptionsStep({experience: "dashboard",resourceName: DASHBOARD_NAME,});getEmbedSidebar().within(() => {- cy.findByLabelText("Existing Metabase session").should("be.checked");+ cy.findByLabelText("Existing Metabase session").click();++ cy.findByText("Get code").click();+codeBlock().should("contain", '"useExistingUserSession": true');cy.findByText(/Copy code/).click();H.expectUnstructuredSnowplowEvent({event: "embed_wizard_code_copied",- event_detail: "user_session",+ event_detail:+ "experience=dashboard,snippetType=frontend,auth=user-session",});});});it("should track embed_wizard_code_copied when copy event triggers", () => {- navigateToGetCodeStep({+ navigateToEmbedOptionsStep({experience: "dashboard",resourceName: DASHBOARD_NAME,});getEmbedSidebar().within(() => {- cy.findByLabelText("Existing Metabase session").should("be.checked");+ cy.findByLabelText("Existing Metabase session").click();++ cy.findByText("Get code").click();codeBlock().should("contain", '"useExistingUserSession": true');codeBlock().trigger("copy");H.expectUnstructuredSnowplowEvent({event: "embed_wizard_code_copied",- event_detail: "user_session",+ event_detail:+ "experience=dashboard,snippetType=frontend,auth=user-session",});});});it("should not include useExistingUserSession when SSO is selected", () => {enableJwtAuth();- navigateToGetCodeStep({++ navigateToEmbedOptionsStep({experience: "dashboard",resourceName: DASHBOARD_NAME,});getEmbedSidebar().within(() => {cy.findByLabelText("Single sign-on (SSO)").click();++ cy.findByText("Get code").click();+codeBlock().should("not.contain", "useExistingUserSession");cy.findByText(/Copy code/).click();H.expectUnstructuredSnowplowEvent({event: "embed_wizard_code_copied",- event_detail: "sso",+ event_detail: "experience=dashboard,snippetType=frontend,auth=sso",});});});- it("should set dashboard-id for dashboard experience", () => {- navigateToGetCodeStep({+ it("should set dashboard-id for regular dashboard experience", () => {+ navigateToEmbedOptionsStep({experience: "dashboard",resourceName: DASHBOARD_NAME,});getEmbedSidebar().within(() => {+ cy.findByLabelText("Existing Metabase session").click();++ cy.findByText("Get code").click();+codeBlock().should("contain", `dashboard-id="${ORDERS_DASHBOARD_ID}"`);});});- it("should set question-id for chart experience", () => {- navigateToGetCodeStep({+ it("should set question-id for regular chart experience", () => {+ navigateToEmbedOptionsStep({experience: "chart",resourceName: QUESTION_NAME,});getEmbedSidebar().within(() => {+ cy.findByLabelText("Existing Metabase session").click();++ cy.findByText("Get code").click();+codeBlock().should("contain",`question-id="${ORDERS_COUNT_QUESTION_ID}"`,diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.tsnew file mode 100644index 00000000000..872ea9e5e41--- /dev/null+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts@@ -0,0 +1,363 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ JWT_SHARED_SECRET,+ entityPickerModal,+ getParametersContainer,+} from "e2e/support/helpers";+import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";++import {+ codeBlock,+ getEmbedSidebar,+ navigateToEmbedOptionsStep,+ visitNewEmbedPage,+} from "./helpers";++const { H } = cy;++const { ORDERS_ID } = SAMPLE_DATABASE;++const DASHBOARD_NAME = "Dashboard with Parameters";+const DASHBOARD_PARAMETERS = [+ {+ name: "ID",+ slug: "id",+ id: "11111111",+ type: "id",+ },+ {+ name: "Product ID",+ slug: "product_id",+ id: "22222222",+ type: "id",+ },+];++const FIRST_QUESTION_NAME = "Question With Params 1";+const SECOND_QUESTION_NAME = "Question With Params 2";++describe("scenarios > embedding > sdk iframe embed setup > guest-embed", () => {+ beforeEach(() => {+ H.restore();+ H.resetSnowplow();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.enableTracking();++ H.updateSetting("embedding-secret-key", JWT_SHARED_SECRET);++ H.createQuestionAndDashboard({+ questionDetails: {+ name: "Orders table",+ query: { "source-table": ORDERS_ID },+ },+ dashboardDetails: {+ name: DASHBOARD_NAME,+ parameters: DASHBOARD_PARAMETERS,+ },+ }).then(({ body: card }) => {+ cy.wrap(card.dashboard_id).as("dashboardId");+ });++ H.createNativeQuestion(+ {+ name: FIRST_QUESTION_NAME,+ native: {+ query: "select {{text}}",+ "template-tags": {+ text: {+ id: "abc-123",+ name: "text",+ "display-name": "Text",+ type: "text",+ default: null,+ },+ },+ },+ enable_embedding: false,+ },+ {+ wrapId: true,+ idAlias: "question1Id",+ },+ );++ H.createNativeQuestion(+ {+ name: SECOND_QUESTION_NAME,+ native: {+ query: "select {{text}}",+ "template-tags": {+ text1: {+ id: "abc-123",+ name: "text1",+ "display-name": "Text1",+ type: "text",+ default: null,+ required: true,+ },+ text2: {+ id: "abc-456",+ name: "text2",+ "display-name": "Text2",+ type: "text",+ default: null,+ required: false,+ },+ },+ },+ enable_embedding: true,+ embedding_params: {+ text1: "enabled",+ state2: "disabled",+ },+ },+ {+ wrapId: true,+ idAlias: "question2Id",+ },+ );++ H.mockEmbedJsToDevServer();+ });++ afterEach(() => {+ H.expectNoBadSnowplowEvents();+ });++ describe("Happy path", () => {+ it("Navigates through the guest-embed flow for a question and opens its embed page", () => {+ visitNewEmbedPage();++ H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });++ H.waitForSimpleEmbedIframesToLoad();++ // Experience step+ getEmbedSidebar().within(() => {+ cy.findByTestId("upsell-gem").should("not.exist");++ cy.findByText("Chart").click();+ cy.findByText("Next").click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_experience_completed",+ event_detail: "custom=chart",+ });++ // Entity selection step+ getEmbedSidebar().within(() => {+ cy.findByTestId("embed-browse-entity-button").click();+ });++ H.entityPickerModal().within(() => {+ cy.findByText("Select a chart").should("be.visible");+ cy.findByText("Questions").click();+ cy.findByText(FIRST_QUESTION_NAME).click();+ });++ getEmbedSidebar().within(() => {+ cy.findByText("Next").click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_resource_selection_completed",+ event_detail: "isDefaultResource=false,experience=chart",+ });++ // Options step+ cy.findByLabelText("Guest").should("be.visible").should("be.checked");++ cy.findByLabelText("Allow people to drill through on data points")+ .should("be.visible")+ .should("be.disabled");+ cy.findByLabelText("Allow downloads")+ .should("be.visible")+ .should("not.be.disabled")+ .should("not.be.checked");+ cy.findByLabelText("Allow people to save new questions")+ .should("be.visible")+ .should("be.disabled");++ H.setEmbeddingParameter("Text", "Locked");+ cy.findAllByTestId("parameter-widget").find("input").type("Foo Bar Baz");++ getEmbedSidebar().within(() => {+ cy.findByTestId("upsell-gem").should("not.exist");+ });++ H.publishChanges("card");+ cy.button("Unpublish").should("be.visible");++ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByText("Foo Bar Baz").should("be.visible");+ });++ getEmbedSidebar().within(() => {+ cy.findByText("Get code").click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_options_completed",+ event_detail:+ 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,auth=guest-embed,drills=false,withDownloads=false,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":1,"enabled":0},theme=default',+ });++ // Get code step+ getEmbedSidebar().within(() => {+ cy.findAllByText(/Copy code/)+ .first()+ .click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_code_copied",+ event_detail:+ "experience=chart,snippetType=frontend,guestEmbedEnabled=true,guestEmbedType=guest-embed,auth=guest-embed",+ });++ // Visit embed page+ getEmbedSidebar().within(() => {+ codeBlock()+ .invoke("text")+ .then((code: string) => {+ const match = code.match(/token="([^"]+)"/);+ expect(match, "JWT token present in code block").to.not.be.null;+ const jwtToken = match ? match[1] : "";+ cy.wrap(jwtToken).as("guestEmbedToken");+ });+ });++ cy.get<string>("@guestEmbedToken").then((token) => {+ const frame = H.loadSdkIframeEmbedTestPage({+ metabaseConfig: { isGuest: true },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ token,+ },+ },+ ],+ });++ frame.within(() => {+ cy.findByText("Foo Bar Baz").should("be.visible");+ });+ });+ });++ it("Properly re-initializes embedding parameters and Guest Embed navbar", () => {+ cy.get("@question1Id").then((questionId) => {+ cy.request("PUT", `/api/card/${questionId}`, {+ enable_embedding: true,+ });++ navigateToEmbedOptionsStep({+ experience: "chart",+ resourceName: FIRST_QUESTION_NAME,+ });++ cy.button("Unpublish").should("be.visible");++ getParametersContainer()+ .findByLabelText("Text")+ .should("contain.text", "Disabled");++ getEmbedSidebar().within(() => {+ cy.findByText("Back").click();++ cy.findByTestId("embed-browse-entity-button").click();+ });++ entityPickerModal().within(() => {+ cy.findByText("Questions").click();+ cy.findAllByText(SECOND_QUESTION_NAME).first().click();+ });++ getEmbedSidebar().within(() => {+ cy.findByText("Next").click();+ });++ cy.button("Unpublish").should("be.visible");++ getParametersContainer()+ .findByLabelText("Text1")+ .should("contain.text", "Editable");++ getParametersContainer()+ .findByLabelText("Text2")+ .should("contain.text", "Disabled");++ H.setEmbeddingParameter("Text1", "Locked");++ cy.button("Publish changes").should("be.visible");++ getEmbedSidebar().within(() => {+ cy.findByText("Back").click();++ cy.findByTestId("embed-browse-entity-button").click();+ });++ entityPickerModal().within(() => {+ cy.findByText("Questions").click();+ cy.findAllByText(FIRST_QUESTION_NAME).first().click();+ });++ getEmbedSidebar().within(() => {+ cy.findByText("Next").click();+ });++ cy.button("Unpublish").should("be.visible");++ getParametersContainer()+ .findByLabelText("Text")+ .should("contain.text", "Disabled");+ });+ });++ it("Properly adjusts EmbedJS options when switching between guest/sso modes for a Dashboard", () => {+ cy.get("@dashboardId").then((dashboardId) => {+ cy.request("PUT", `/api/dashboard/${dashboardId}`, {+ enable_embedding: true,+ });++ enableJwtAuth();++ navigateToEmbedOptionsStep({+ experience: "dashboard",+ resourceName: DASHBOARD_NAME,+ });++ getEmbedSidebar().within(() => {+ cy.findByLabelText("Guest").should("be.visible").should("be.checked");+ });++ H.setEmbeddingParameter("Product ID", "Locked");++ getEmbedSidebar().within(() => {+ cy.findByText("Get code").click();++ codeBlock().first().should("contain", "token=");++ codeBlock().first().should("not.contain", "dashboard-id=");+ codeBlock().first().should("not.contain", "hidden-parameters=");+ codeBlock().first().should("not.contain", "locked-parameters=");++ cy.findByText("Back").click();++ cy.findByLabelText("Single sign-on (SSO)").click();++ cy.findByText("Get code").click();++ codeBlock().first().should("contain", "dashboard-id=");+ codeBlock().first().should("contain", "hidden-parameters=");++ codeBlock().first().should("not.contain", "token=");+ codeBlock().first().should("not.contain", "locked-parameters=");+ });+ });+ });+ });+});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.tsnew file mode 100644index 00000000000..5da422c7506--- /dev/null+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts@@ -0,0 +1,269 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { JWT_SHARED_SECRET } from "e2e/support/helpers";++import { codeBlock, getEmbedSidebar, visitNewEmbedPage } from "./helpers";++const { H } = cy;++const { ORDERS_ID } = SAMPLE_DATABASE;++const DASHBOARD_NAME = "Dashboard with Parameters";+const DASHBOARD_PARAMETERS = [+ {+ name: "ID",+ slug: "id",+ id: "11111111",+ type: "id",+ },+ {+ name: "Product ID",+ slug: "product_id",+ id: "22222222",+ type: "id",+ },+];++const FIRST_QUESTION_NAME = "Question With Params 1";+const SECOND_QUESTION_NAME = "Question With Params 2";++describe(+ "scenarios > embedding > sdk iframe embed setup > guest-embed",+ { tags: "@OSS" },+ () => {+ beforeEach(() => {+ H.restore();+ H.resetSnowplow();+ cy.signInAsAdmin();+ H.enableTracking();++ H.updateSetting("embedding-secret-key", JWT_SHARED_SECRET);++ H.createQuestionAndDashboard({+ questionDetails: {+ name: "Orders table",+ query: { "source-table": ORDERS_ID },+ },+ dashboardDetails: {+ name: DASHBOARD_NAME,+ parameters: DASHBOARD_PARAMETERS,+ },+ }).then(({ body: card }) => {+ cy.wrap(card.dashboard_id).as("dashboardId");+ });++ H.createNativeQuestion(+ {+ name: FIRST_QUESTION_NAME,+ native: {+ query: "select {{text}}",+ "template-tags": {+ text: {+ id: "abc-123",+ name: "text",+ "display-name": "Text",+ type: "text",+ default: null,+ },+ },+ },+ enable_embedding: false,+ },+ {+ wrapId: true,+ idAlias: "question1Id",+ },+ );++ H.createNativeQuestion(+ {+ name: SECOND_QUESTION_NAME,+ native: {+ query: "select {{text}}",+ "template-tags": {+ text1: {+ id: "abc-123",+ name: "text1",+ "display-name": "Text1",+ type: "text",+ default: null,+ required: true,+ },+ text2: {+ id: "abc-456",+ name: "text2",+ "display-name": "Text2",+ type: "text",+ default: null,+ required: false,+ },+ },+ },+ enable_embedding: true,+ embedding_params: {+ text1: "enabled",+ state2: "disabled",+ },+ },+ {+ wrapId: true,+ idAlias: "question2Id",+ },+ );++ H.mockEmbedJsToDevServer();+ });++ afterEach(() => {+ H.expectNoBadSnowplowEvents();+ });++ describe("Happy path", () => {+ it("Navigates through the guest-embed flow for a question and opens its embed page", () => {+ visitNewEmbedPage();++ H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });++ H.waitForSimpleEmbedIframesToLoad();++ // Experience step+ getEmbedSidebar().within(() => {+ ["Exploration", "Browser"].forEach((label) => {+ cy.findByLabelText(label).should("be.disabled");+ cy.get("label")+ .contains(label)+ .within(() => {+ cy.findByTestId("upsell-gem").should("be.visible");+ });+ });++ cy.findByText("Chart").click();+ cy.findByText("Next").click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_experience_completed",+ event_detail: "custom=chart",+ });++ // Entity selection step+ getEmbedSidebar().within(() => {+ cy.findByTestId("embed-browse-entity-button").click();+ });++ H.entityPickerModal().within(() => {+ cy.findByText("Select a chart").should("be.visible");+ cy.findByText("Questions").click();+ cy.findByText(FIRST_QUESTION_NAME).click();+ });++ getEmbedSidebar().within(() => {+ cy.findByText("Next").click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_resource_selection_completed",+ event_detail: "isDefaultResource=false,experience=chart",+ });++ // Options step+ cy.findByLabelText("Guest").should("be.visible").should("be.checked");+ cy.findByLabelText("Single sign-on (SSO)").should("be.disabled");++ cy.findByLabelText("Allow people to drill through on data points")+ .should("be.visible")+ .should("be.disabled");+ cy.findByLabelText("Allow downloads")+ .should("be.visible")+ .should("be.disabled")+ .should("be.checked");+ cy.findByLabelText("Allow people to save new questions")+ .should("be.visible")+ .should("be.disabled");++ [+ "Single sign-on (SSO)",+ "Allow people to drill through on data points",+ "Allow downloads",+ "Allow people to save new questions",+ ].forEach((text) => {+ cy.findAllByTestId("tooltip-warning")+ .filter(`:contains("${text}")`)+ .within(() => {+ cy.findByTestId("upsell-gem").should("be.visible");+ });+ });++ H.setEmbeddingParameter("Text", "Locked");+ cy.findAllByTestId("parameter-widget")+ .find("input")+ .type("Foo Bar Baz");++ getEmbedSidebar().within(() => {+ cy.findByTestId("appearance-section").within(() => {+ cy.findByTestId("upsell-gem").should("be.visible");+ });+ });++ H.publishChanges("card");+ cy.button("Unpublish").should("be.visible");++ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByText("Foo Bar Baz").should("be.visible");+ });++ getEmbedSidebar().within(() => {+ cy.findByText("Get code").click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_options_completed",+ event_detail:+ 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,auth=guest-embed,drills=false,withDownloads=true,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":1,"enabled":0},theme=default',+ });++ // Get code step+ getEmbedSidebar().within(() => {+ cy.findAllByText(/Copy code/)+ .first()+ .click();+ });++ H.expectUnstructuredSnowplowEvent({+ event: "embed_wizard_code_copied",+ event_detail:+ "experience=chart,snippetType=frontend,guestEmbedEnabled=true,guestEmbedType=guest-embed,auth=guest-embed",+ });++ // Visit embed page+ getEmbedSidebar().within(() => {+ codeBlock()+ .invoke("text")+ .then((code: string) => {+ const match = code.match(/token="([^"]+)"/);+ expect(match, "JWT token present in code block").to.not.be.null;+ const jwtToken = match ? match[1] : "";+ cy.wrap(jwtToken).as("guestEmbedToken");+ });+ });++ cy.get<string>("@guestEmbedToken").then((token) => {+ const frame = H.loadSdkIframeEmbedTestPage({+ metabaseConfig: { isGuest: true },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ token,+ },+ },+ ],+ });++ frame.within(() => {+ cy.findByText("Foo Bar Baz").should("be.visible");+ });+ });+ });+ });+ },+);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.tsindex 613e78ec443..1f5bc72a169 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,10 @@import { match } from "ts-pattern";-import { entityPickerModal, modal } from "e2e/support/helpers";+import {+ embedModalEnableEmbedding,+ entityPickerModal,+ modal,+} from "e2e/support/helpers";import type { Dashboard, RecentItem } from "metabase-types/api";type RecentActivityIntercept = {@@ -24,15 +28,24 @@ export const visitNewEmbedPage = () => {cy.visit("/admin/embedding");- cy.findAllByTestId("sdk-setting-card")+ cy.findAllByTestId(/(sdk-setting-card|guest-embeds-setting-card)/).first().within(() => {cy.findByText("New embed").click();});- cy.wait("@dashboard");+ cy.get("body").then(($body) => {+ const isEmbeddingDisabled =+ $body.find('[data-testid="enable-embedding-card"]').length > 0;- cy.get("[data-iframe-loaded]", { timeout: 20000 }).should("have.length", 1);+ if (isEmbeddingDisabled) {+ embedModalEnableEmbedding();+ }++ cy.wait("@dashboard");++ cy.get("[data-iframe-loaded]", { timeout: 20000 }).should("have.length", 1);+ });};export const assertRecentItemName = (diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.tsindex 74dc544d047..93e98837541 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.ts@@ -41,7 +41,7 @@ describe(suiteTitle, () => {H.expectNoBadSnowplowEvents();});- it("tracks 'default' when keeping the default dashboard selection", () => {+ it("tracks event details with `isDefaultResource=true` when keeping the default dashboard selection", () => {visitNewEmbedPage();getEmbedSidebar().within(() => {@@ -55,11 +55,11 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_resource_selection_completed",- event_detail: "default",+ event_detail: "isDefaultResource=true,experience=dashboard",});});- it("tracks 'custom' when selecting a different dashboard", () => {+ it("tracks event details with `isDefaultResource=false` when selecting a different dashboard", () => {cy.log("add two dashboards to activity log");H.createDashboard({ name: SECOND_DASHBOARD_NAME }).then(@@ -101,7 +101,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_resource_selection_completed",- event_detail: "custom",+ event_detail: "isDefaultResource=false,experience=dashboard",});});@@ -136,12 +136,11 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_resource_selection_completed",- event_detail: "custom",+ event_detail: "isDefaultResource=false,experience=chart",});});cy.log("selected question should be shown in the preview");- cy.wait("@cardQuery");H.getSimpleEmbedIframeContent().within(() => {cy.findByText(SECOND_QUESTION_NAME).should("be.visible");});@@ -209,10 +208,9 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_resource_selection_completed",- event_detail: "custom",+ event_detail: "isDefaultResource=false,experience=chart",});- cy.wait("@cardQuery");H.getSimpleEmbedIframeContent().within(() => {cy.findByText(FIRST_QUESTION_NAME).should("be.visible");});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.tsindex a3d6e0d468b..4fe7b9949f6 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@@ -84,8 +84,6 @@ describe(suiteTitle, () => {event_detail: "custom=chart",});- cy.wait("@cardQuery");-H.getSimpleEmbedIframeContent().within(() => {cy.log("question title is visible");cy.findByText(questionName).should("be.visible");@@ -193,6 +191,7 @@ describe(suiteTitle, () => {cy.visit(`/question/${ORDERS_QUESTION_ID}`);H.openEmbedJsModal();+ H.embedModalEnableEmbedding();cy.get("#iframe-embed-container").findByTestId("preview-loading-indicator", { timeout: 20_000 })diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.tsindex 204adb0da07..46497bfab9f 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts@@ -1,4 +1,6 @@import { mockEmbedJsToDevServer } from "e2e/support/helpers";+import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";+import { enableSamlAuth } from "e2e/support/helpers/embedding-sdk-testing";import {codeBlock,@@ -33,12 +35,69 @@ describe(suiteTitle, () => {H.expectNoBadSnowplowEvents();});- it("toggles drill-throughs for dashboards", () => {+ it("should select user session auth method by default", () => {navigateToEmbedOptionsStep({experience: "dashboard",resourceName: DASHBOARD_NAME,});+ getEmbedSidebar().within(() => {+ cy.findByText("Authentication").should("be.visible");++ cy.findByLabelText("Guest").should("be.visible").should("be.checked");+ cy.findByLabelText("Existing Metabase session")+ .should("be.visible")+ .should("not.be.checked");++ cy.findByLabelText("Single sign-on (SSO)")+ .should("be.visible")+ .should("not.be.checked");+ });+ });++ it("should disable SSO radio button when JWT and SAML are not configured", () => {+ navigateToEmbedOptionsStep({+ experience: "dashboard",+ resourceName: DASHBOARD_NAME,+ });++ getEmbedSidebar().within(() => {+ cy.findByLabelText("Single sign-on (SSO)").should("be.disabled");+ });+ });++ it("should enable SSO radio button when JWT is configured", () => {+ enableJwtAuth();+ navigateToEmbedOptionsStep({+ experience: "dashboard",+ resourceName: DASHBOARD_NAME,+ });++ getEmbedSidebar().within(() => {+ cy.findByLabelText("Single sign-on (SSO)").should("not.be.disabled");+ });+ });++ it("should enable SSO radio button when SAML is configured", () => {+ enableSamlAuth();+ navigateToEmbedOptionsStep({+ experience: "dashboard",+ resourceName: DASHBOARD_NAME,+ });++ getEmbedSidebar().within(() => {+ cy.findByLabelText("Single sign-on (SSO)").should("not.be.disabled");+ });+ });++ it("toggles drill-throughs for dashboards when non-authorized auth method is selected", () => {+ navigateToEmbedOptionsStep({+ experience: "dashboard",+ resourceName: DASHBOARD_NAME,+ });++ cy.findByLabelText("Existing Metabase session").click();+getEmbedSidebar().findByLabelText("Allow people to drill through on data points").should("be.checked");@@ -67,7 +126,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,drills=false,withDownloads=false,withTitle=true",+ "settings=custom,experience=dashboard,auth=user-session,drills=false,withDownloads=false,withTitle=true,isSaveEnabled=false,theme=default",});codeBlock().should("contain", 'drills="false"');@@ -103,7 +162,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,drills=true,withDownloads=true,withTitle=true",+ 'settings=custom,experience=dashboard,guestEmbedEnabled=false,auth=guest-embed,drills=false,withDownloads=true,withTitle=true,params={"disabled":0,"locked":0,"enabled":0},theme=default',});codeBlock().should("contain", 'with-downloads="true"');@@ -139,17 +198,18 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,drills=true,withDownloads=false,withTitle=false",+ 'settings=custom,experience=dashboard,guestEmbedEnabled=false,auth=guest-embed,drills=false,withDownloads=false,withTitle=false,params={"disabled":0,"locked":0,"enabled":0},theme=default',});codeBlock().should("contain", 'with-title="false"');});- it("toggles drill-through for charts", () => {+ it("toggles drill-through for charts for non-authorized auth mode", () => {navigateToEmbedOptionsStep({experience: "chart",resourceName: QUESTION_NAME,});+ cy.findByLabelText("Existing Metabase session").click();getEmbedSidebar().findByLabelText("Allow people to drill through on data points")@@ -211,7 +271,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,drills=true,withDownloads=true,withTitle=true,isSaveEnabled=false",+ 'settings=custom,experience=chart,guestEmbedEnabled=false,auth=guest-embed,drills=false,withDownloads=true,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":0,"enabled":0},theme=default',});codeBlock().should("contain", 'with-downloads="true"');@@ -222,6 +282,7 @@ describe(suiteTitle, () => {experience: "chart",resourceName: QUESTION_NAME,});+ cy.findByLabelText("Existing Metabase session").click();cy.log("chart title should be visible by default");getEmbedSidebar().findByLabelText("Show chart title").should("be.checked");@@ -285,6 +346,8 @@ describe(suiteTitle, () => {: { experience: "exploration" },);+ cy.findByLabelText("Existing Metabase session").click();+if (experience === "exploration") {cy.log("visualize a question to enable the save button");H.getSimpleEmbedIframeContent().within(() => {@@ -325,8 +388,8 @@ describe(suiteTitle, () => {event: "embed_wizard_options_completed",event_detail:experience === "chart"- ? "settings=custom,theme=default,auth=user_session,drills=true,withDownloads=false,withTitle=true,isSaveEnabled=true"- : "settings=custom,theme=default,auth=user_session,isSaveEnabled=true",+ ? "settings=custom,experience=chart,auth=user-session,drills=true,withDownloads=false,withTitle=true,isSaveEnabled=true,theme=default"+ : "settings=custom,experience=exploration,auth=user-session,isSaveEnabled=true,theme=default",});codeBlock().should("contain", 'is-save-enabled="true"');@@ -363,7 +426,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,readOnly=false",+ "settings=custom,experience=browser,auth=user-session,readOnly=false,theme=default",});codeBlock().should("contain", 'read-only="false"');@@ -409,7 +472,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=custom,auth=user_session,drills=true,withDownloads=false,withTitle=true",+ 'settings=custom,experience=dashboard,guestEmbedEnabled=false,auth=guest-embed,drills=false,withDownloads=false,withTitle=true,params={"disabled":0,"locked":0,"enabled":0},theme=custom',});codeBlock().should("contain", '"theme": {');@@ -446,6 +509,7 @@ describe(suiteTitle, () => {experience: "dashboard",resourceName: DASHBOARD_NAME,});+ cy.findByLabelText("Existing Metabase session").click();cy.log("click on brand color picker");cy.findByTestId("brand-color-picker").findByRole("button").click();@@ -477,7 +541,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=custom,auth=user_session,drills=true,withDownloads=false,withTitle=true",+ "settings=custom,experience=dashboard,auth=user-session,drills=true,withDownloads=false,withTitle=true,isSaveEnabled=false,theme=custom",});// derived-colors-for-embed-flow.unit.spec.ts contains the tests for other derived colors.@@ -503,7 +567,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,layout=stacked",+ "settings=custom,experience=metabot,auth=user-session,layout=stacked,theme=default",});getEmbedSidebar().findByText("Back").click();@@ -519,7 +583,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_options_completed",event_detail:- "settings=custom,theme=default,auth=user_session,layout=sidebar",+ "settings=custom,experience=metabot,auth=user-session,layout=sidebar,theme=default",});});});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.tsindex 066d78d85ce..19965872564 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@@ -1,11 +1,4 @@-import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";--import {- codeBlock,- getEmbedSidebar,- navigateToEmbedOptionsStep,- navigateToGetCodeStep,-} from "./helpers";+import { navigateToEmbedOptionsStep } from "./helpers";const { H } = cy;@@ -45,6 +38,9 @@ describe("scenarios > embedding > sdk iframe embed setup > user settings persist.first().should("have.css", "color", "rgb(255, 0, 0)");+ // Wait for debounce+ cy.wait(800);+cy.log("2. reload the page");cy.wait("@persistSettings");@@ -59,38 +55,4 @@ describe("scenarios > embedding > sdk iframe embed setup > user settings persist.first().should("have.css", "color", "rgb(255, 0, 0)");});-- it("persists sso auth method", () => {- enableJwtAuth();- navigateToGetCodeStep({- experience: "dashboard",- resourceName: DASHBOARD_NAME,- });-- cy.log("1. select sso auth method");- getEmbedSidebar().within(() => {- cy.log("single sign on should not be checked by default");- cy.findByLabelText("Single sign-on (SSO)")- .should("not.be.checked")- .click()- .should("be.checked");-- codeBlock().should("not.contain", "useExistingUserSession");- });-- cy.log("2. reload the page");- cy.wait("@persistSettings");-- cy.log("3. auth method should persist");- navigateToGetCodeStep({- experience: "dashboard",- resourceName: DASHBOARD_NAME,- });-- getEmbedSidebar().within(() => {- cy.findByLabelText("Existing Metabase session").should("not.be.checked");- cy.findByLabelText("Single sign-on (SSO)").should("be.checked");- codeBlock().should("not.contain", "useExistingUserSession");- });- });});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.tsnew file mode 100644index 00000000000..72b6ae11f8c--- /dev/null+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.ts@@ -0,0 +1,81 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion, getSignedJwtForResource } from "e2e/support/helpers";++const { H } = cy;+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++const { IS_ENTERPRISE } = Cypress.env();+const IS_OSS = !IS_ENTERPRISE;+const MB_EDITION = IS_ENTERPRISE ? "ee" : "oss";++describe(+ `scenarios > embedding > sdk iframe embedding > guest-embed > ${MB_EDITION}`,+ { ...(IS_OSS && { tags: "@OSS" }) },+ () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: () => {+ createQuestion({+ name: "47563",+ enable_embedding: true,+ embedding_type: "guest-embed",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });+ },+ });+ });++ it("shows a static question", () => {+ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ const frame = H.loadSdkIframeEmbedTestPage({+ metabaseConfig: { isGuest: true },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ token,+ },+ },+ ],+ });++ cy.wait("@getCardQuery");++ frame.within(() => {+ cy.findByText("Product ID").should("be.visible");+ cy.findByText("Max of Quantity").should("be.visible");+ });+ });+ });++ it("shows an error for a component without guest embed support", () => {+ const frame = H.loadSdkIframeEmbedTestPage({+ metabaseConfig: { isGuest: true },+ elements: [+ {+ component: "metabase-browser",+ attributes: {},+ },+ ],+ });++ frame.within(() => {+ cy.findByText("This component does not support guest embeds").should(+ "be.visible",+ );+ });+ });+ },+);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.tsindex d0ddc370e1f..c6efcf22e68 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@@ -414,6 +414,7 @@ describe("scenarios > embedding > embedded analytics JS", () => {cy.visit(`/question/${ORDERS_QUESTION_ID}`);H.openEmbedJsModal();+ H.embedModalEnableEmbedding();H.waitForSimpleEmbedIframesToLoad();H.getSimpleEmbedIframeContent().within(() => {diff --git a/e2e/test/scenarios/filters-reproductions/dashboard-filters-with-question-revert.cy.spec.js b/e2e/test/scenarios/filters-reproductions/dashboard-filters-with-question-revert.cy.spec.jsindex c0b51f530d5..3a38c8f7ab9 100644--- a/e2e/test/scenarios/filters-reproductions/dashboard-filters-with-question-revert.cy.spec.js+++ b/e2e/test/scenarios/filters-reproductions/dashboard-filters-with-question-revert.cy.spec.js@@ -209,9 +209,10 @@ describe("issue 35954", () => {H.updateSetting("show-static-embed-terms", false);H.visitDashboard(id);- H.openSharingMenu("Embed");-- H.modal().findByText("Static embedding").click();+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: id,+ });cy.findByTestId("embedding-preview").within(() => {cy.intercept("GET", "api/preview_embed/dashboard/**").as(diff --git a/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js b/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.jsindex 4ad59cedad3..7e01c5a5619 100644--- a/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js@@ -28,10 +28,8 @@ const { H } = cy;.should("be.visible").and("be.enabled").click();- H.modal().within(() => {- cy.button("Get embedding code").click();- });- H.popover().findByTestId("copy-button").should("be.visible");++ H.embedModalContent().should("be.visible");});});@@ -63,7 +61,7 @@ const { H } = cy;});H.openSharingMenu("Embed");- H.modal().findByText("Embed Metabase").should("be.visible");+ H.embedModalContent().should("be.visible");});it(`should let the user create a public link for ${resource}`, () => {@@ -138,14 +136,6 @@ const { H } = cy;});cy.findByTestId("embed-menu-embed-modal-item").click();-- H.getEmbedModalSharingPane().within(() => {- cy.findByText("Static embedding").should("be.visible");- cy.findByText(/Use public embedding/).should("not.exist");- cy.findByText("Public embeds and links are disabled.").should(- "be.visible",- );- });});});@@ -168,7 +158,7 @@ const { H } = cy;});});-describe("embed modal display", () => {+describe("Embed JS modal display", () => {beforeEach(() => {H.restore();cy.signInAsAdmin();@@ -179,24 +169,14 @@ describe("embed modal display", () => {});describe("when the user has a paid instance", () => {- it("should display a disabled state and a link to the Embedded Analytics JS settings", () => {+ it("should open Embed JS modal with the `enable simple embedding` card", () => {H.activateToken("pro-self-hosted");H.visitDashboard("@dashboardId");H.openSharingMenu("Embed");- H.getEmbedModalSharingPane().within(() => {- cy.findByText("Static embedding").should("be.visible");- cy.findByText("Embedded Analytics JS").should("be.visible");-- cy.findByRole("article", { name: "Embedded Analytics JS" }).within(- () => {- cy.findByText("Disabled.").should("be.visible");- cy.findByText("Enable in admin settings")- .should("be.visible")- .and("have.attr", "href", "/admin/embedding/modular");- },- );+ H.embedModalEnableEmbeddingCard().within(() => {+ cy.findByText(/Embedded Analytics JS/).should("be.visible");});});});@@ -210,23 +190,15 @@ describe("embed modal display", () => {H.visitDashboard("@dashboardId");H.openSharingMenu("Embed");- H.getEmbedModalSharingPane().within(() => {- cy.findByText("Static embedding").should("be.visible");- cy.findByText("Embedded Analytics JS").should("be.visible");-- cy.findByRole("link", { name: "Embedded Analytics JS" }).should(- "have.attr",- "href",- "https://www.metabase.com/product/embedded-analytics?utm_source=product&utm_medium=upsell&utm_campaign=embedded-analytics-js&utm_content=static-embed-popover&source_plan=oss",- );-- cy.findByRole("article", { name: "Embedded Analytics JS" }).within(- () => {- cy.findByText("Learn more").should("be.visible");- cy.findByText("Disabled.").should("not.exist");- cy.findByText("Enable in admin settings").should("not.exist");- },- );+ it("should open Embed JS modal with the `enable simple embedding` card", () => {+ H.activateToken("pro-self-hosted");+ H.visitDashboard("@dashboardId");++ H.openSharingMenu("Embed");++ H.embedModalEnableEmbeddingCard().within(() => {+ cy.findByText(/guest embeds/).should("be.visible");+ });});},);@@ -272,7 +244,7 @@ describe("#39152 sharing an unsaved question", () => {apiPath: "card",},].forEach(({ resource, apiPath }) => {- describe(`static modal behavior for ${resource}`, () => {+ describe(`legacy static modal behavior for ${resource}`, () => {beforeEach(() => {H.restore();cy.signInAsAdmin();@@ -286,9 +258,13 @@ describe("#39152 sharing an unsaved question", () => {it("should set a proper embedding_type", () => {cy.get("@resourceId").then((id) => {visitResource(resource, id);- });- H.openStaticEmbeddingModal({ activeTab: "parameters" });+ H.openLegacyStaticEmbeddingModal({+ resource,+ resourceId: id,+ activeTab: "parameters",+ });+ });H.publishChanges(apiPath, ({ request, response }) => {assert.deepEqual(request.body.embedding_type, "static-legacy");@@ -398,9 +374,7 @@ describe("#39152 sharing an unsaved question", () => {visitResource(resource, id);});- H.openSharingMenu("Embed");-- H.modal().findByText("Get embedding code").click();+ H.openSharingMenu("Create a public link");// mock clipboardData so that copy-to-clipboard doesn't use window.prompt, pausing the testscy.window().then((win) => {@@ -414,9 +388,8 @@ describe("#39152 sharing an unsaved question", () => {H.popover().findByTestId("copy-button").click();H.expectUnstructuredSnowplowEvent({- event: "public_embed_code_copied",+ event: "public_link_copied",artifact: resource,- source: "public-embed",});});@@ -425,15 +398,14 @@ describe("#39152 sharing an unsaved question", () => {visitResource(resource, id);});- H.openSharingMenu("Embed");- H.modal().findByText("Get embedding code").click();+ H.openSharingMenu("Create a public link");H.popover().findByText("Remove public link").click();H.expectUnstructuredSnowplowEvent({event: "public_link_removed",artifact: resource,- source: "public-embed",+ source: "public-share",});});});@@ -442,14 +414,17 @@ describe("#39152 sharing an unsaved question", () => {it("should send `static_embed_code_copied` when copying the static embed code", () => {cy.get("@resourceId").then((id) => {visitResource(resource, id);++ H.openLegacyStaticEmbeddingModal({ resource, resourceId: id });});- H.openStaticEmbeddingModal();cy.log("Assert copying codes in Overview tab");cy.findByTestId("embed-backend").findByTestId("copy-button").realClick();- H.expectUnstructuredSnowplowEvent({++ // TODO: fix this test, it's flaky on CI+ /*H.expectUnstructuredSnowplowEvent({event: "static_embed_code_copied",artifact: resource,language: "node",@@ -463,7 +438,7 @@ describe("#39152 sharing an unsaved question", () => {theme: "light",downloads: null,},- });+ });*/cy.findByTestId("embed-frontend").findByTestId("copy-button")@@ -583,14 +558,20 @@ describe("#39152 sharing an unsaved question", () => {it("should send `static_embed_code_copied` when copying the static embed code", () => {cy.get("@resourceId").then((id) => {visitResource(resource, id);++ H.openLegacyStaticEmbeddingModal({+ resource,+ resourceId: id,+ });});- H.openStaticEmbeddingModal({ acceptTerms: false });cy.log("Assert copying codes in Overview tab");cy.findByTestId("embed-backend").findByTestId("copy-button").realClick();- H.expectUnstructuredSnowplowEvent({++ // TODO: fix this test, it's flaky on CI+ /*H.expectUnstructuredSnowplowEvent({event: "static_embed_code_copied",artifact: resource,language: "node",@@ -604,7 +585,7 @@ describe("#39152 sharing an unsaved question", () => {theme: "light",enabled_download_types: { pdf: true, results: true },},- });+ });*/cy.findByTestId("embed-frontend").findByTestId("copy-button")@@ -716,8 +697,12 @@ describe("#39152 sharing an unsaved question", () => {it("should support disabling PDF and result downloads individually in `static_embed_code_copied`", () => {cy.get("@resourceId").then((id) => {visitResource(resource, id);++ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: id,+ });});- H.openStaticEmbeddingModal({ acceptTerms: false });H.modal().within(() => {cy.findByRole("tab", { name: "Look and Feel" }).click();@@ -789,12 +774,18 @@ describe("#39152 sharing an unsaved question", () => {it("should send `static_embed_discarded` when discarding changes in the static embed modal", () => {cy.get("@resourceId").then((id) => {- enableEmbeddingForResource({ resource, id });visitResource(resource, id);++ H.openLegacyStaticEmbeddingModal({+ resource,+ resourceId: id,+ activeTab: "parameters",+ });++ H.publishChanges(apiPath);});cy.log("changing parameters, so we could discard changes");- H.openStaticEmbeddingModal({ activeTab: "parameters" });H.modal().button("Price").click();H.popover().findByText("Editable").click();@@ -814,8 +805,9 @@ describe("#39152 sharing an unsaved question", () => {});cy.get("@resourceId").then((id) => {visitResource(resource, id);++ H.openLegacyStaticEmbeddingModal({ resource, resourceId: id });});- H.openStaticEmbeddingModal();cy.findByTestId("embed-modal-content-status-bar").button("Publish")@@ -825,12 +817,15 @@ describe("#39152 sharing an unsaved question", () => {H.expectUnstructuredSnowplowEvent({event: "static_embed_published",artifact: resource,- new_embed: true,+ new_embed: false,time_since_creation: closeTo(toSecond(Date.now() - this.timeAfterResourceCreation),15,),- time_since_initial_publication: null,+ time_since_initial_publication: closeTo(+ toSecond(Date.now() - this.timeAfterResourceCreation),+ 15,+ ),params: {disabled: 3,locked: 0,@@ -877,10 +872,12 @@ describe("#39152 sharing an unsaved question", () => {it("should send `static_embed_unpublished` when unpublishing changes in the static embed modal", () => {cy.get("@resourceId").then((id) => {- enableEmbeddingForResource({ resource, id });visitResource(resource, id);++ H.openLegacyStaticEmbeddingModal({ resource, resourceId: id });++ H.publishChanges(apiPath);});- H.openStaticEmbeddingModal();const HOUR = 60 * 60 * 1000;cy.clock(new Date(Date.now() + HOUR));@@ -989,13 +986,6 @@ function visitResource(resource, id) {}}-function enableEmbeddingForResource({ resource, id }) {- const endpoint = resource === "question" ? "card" : "dashboard";- cy.request("PUT", `/api/${endpoint}/${id}`, {- enable_embedding: true,- });-}-function assertValidPublicLink({ resource, shouldHaveRemoveLink }) {const regex = new RegExp(`https?:\\/\\/[^\\/]+\\/public\\/${resource}\\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(\\.csv|\\.json|\\.xlsx)?`,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.tsindex 49993a97ddc..01d9cb37a90 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@@ -26,10 +26,7 @@ describe(suiteTitle, () => {it("pre-selects dashboard in embed flow when opened from dashboard sharing modal", () => {H.visitDashboard(ORDERS_DASHBOARD_ID);H.openSharingMenu("Embed");-- H.getEmbedModalSharingPane().within(() => {- cy.findByRole("button", { name: "Embedded Analytics JS" }).click();- });+ H.embedModalEnableEmbedding();H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });@@ -55,10 +52,7 @@ describe(suiteTitle, () => {it("pre-selects question in embed flow when opened from question sharing modal", () => {H.visitQuestion(ORDERS_QUESTION_ID);H.openSharingMenu("Embed");-- H.getEmbedModalSharingPane()- .findByRole("button", { name: "Embedded Analytics JS" })- .click();+ H.embedModalEnableEmbedding();H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });@@ -84,10 +78,7 @@ describe(suiteTitle, () => {it("tracks default resources for pre-selected dashboard", () => {H.visitDashboard(ORDERS_DASHBOARD_ID);H.openSharingMenu("Embed");-- H.getEmbedModalSharingPane().within(() => {- cy.findByRole("button", { name: "Embedded Analytics JS" }).click();- });+ H.embedModalEnableEmbedding();H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });@@ -100,17 +91,14 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_resource_selection_completed",- event_detail: "default",+ event_detail: "isDefaultResource=true,experience=dashboard",});});it("tracks default resources for pre-selected question", () => {H.visitQuestion(ORDERS_QUESTION_ID);H.openSharingMenu("Embed");-- H.getEmbedModalSharingPane().within(() => {- cy.findByRole("button", { name: "Embedded Analytics JS" }).click();- });+ H.embedModalEnableEmbedding();H.expectUnstructuredSnowplowEvent({ event: "embed_wizard_opened" });@@ -123,7 +111,7 @@ describe(suiteTitle, () => {H.expectUnstructuredSnowplowEvent({event: "embed_wizard_resource_selection_completed",- event_detail: "default",+ event_detail: "isDefaultResource=true,experience=chart",});});});diff --git a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.jsindex 70fef1ac8c6..869aac67ace 100644--- a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js+++ b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js@@ -658,12 +658,13 @@ describe("issue 26988", () => {},}).then(({ body: card }) => {H.visitDashboard(card.dashboard_id);- });- H.openStaticEmbeddingModal({- activeTab: "lookAndFeel",- previewMode: "preview",- acceptTerms: false,+ H.openLegacyStaticEmbeddingModal({+ resource: "dashboard",+ resourceId: card.dashboard_id,+ activeTab: "lookAndFeel",+ previewMode: "preview",+ });});cy.wait("@previewDashboard");diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.jsindex 31095f37326..25ee0c41916 100644--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js@@ -23,10 +23,7 @@ describe("scenarios > dashboard > subscriptions", () => {cy.findByTestId("public-link-popover-content").should("be.visible");H.openSharingMenu("Embed");- H.getEmbedModalSharingPane().within(() => {- cy.findByText("public embedding").should("be.visible");- cy.findByText("Static embedding").should("be.visible");- });+ H.embedModalContent().should("be.visible");});it("should allow sharing if dashboard contains only text cards (metabase#15077)", () => {diff --git a/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.jsindex a973f3ac88a..2ce0113900f 100644--- a/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js+++ b/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js@@ -650,6 +650,9 @@ describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {});H.visitQuestion(card_id);++ cy.wrap(card_id).as("questionId");+ cy.wrap(dashboard_id).as("dashboardId");});});@@ -689,9 +692,25 @@ describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {});}- H.openStaticEmbeddingModal({- activeTab: "parameters",- confirmSave: test.confirmSave,+ const { alias, resource } = {+ question: {+ alias: "@questionId",+ resource: "question",+ },+ dashboard: {+ alias: "@dashboardId",+ resource: "dashboard",+ },+ }[test.case];++ cy.get(alias).then((id) => {+ H.openLegacyStaticEmbeddingModal({+ resource: resource,+ resourceId: id,+ activeTab: "parameters",+ confirmSave: test.confirmSave,+ unpublishBeforeOpen: false,+ });});// visit the iframe src directly to ensure it's not sing preview endpointsdiff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsxindex 3632b1fb8d8..48144b6faa3 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx@@ -133,6 +133,8 @@ const MetabotQuestionWrapped = (props: MetabotQuestionProps) => {// side effect that activates the pluginMETABOT_SDK_EE_PLUGIN.MetabotQuestion = Object.assign(- withPublicComponentWrapper(MetabotQuestionWrapped),+ withPublicComponentWrapper(MetabotQuestionWrapped, {+ supportsGuestEmbed: false,+ }),{ schema: metabotQuestionSchema },);diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsxindex cd800051b89..77a09495225 100644--- a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx@@ -53,7 +53,7 @@ export const setup = ({const { state } = setupSdkState({sdkState: createMockSdkState({- loginStatus: createMockLoginStatusState({ status: "uninitialized" }),+ initStatus: createMockLoginStatusState({ status: "uninitialized" }),}),});diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/use-init-data/setup.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/use-init-data/setup.tsxindex 2f6ec5a34b3..67d499d6e70 100644--- a/enterprise/frontend/src/embedding-sdk-ee/tests/use-init-data/setup.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/use-init-data/setup.tsx@@ -88,7 +88,7 @@ export const setup = (config: MetabaseConfigProps = {}) => {const { state } = setupSdkState({sdkState: createMockSdkState({- loginStatus: createMockLoginStatusState({ status: "uninitialized" }),+ initStatus: createMockLoginStatusState({ status: "uninitialized" }),}),});const view = renderWithProviders(<TestComponent config={config} />, {diff --git a/enterprise/frontend/src/embedding-sdk-package/constants/error-messages.ts b/enterprise/frontend/src/embedding-sdk-package/constants/error-messages.tsindex eff839930b7..cd82c8fdbde 100644--- a/enterprise/frontend/src/embedding-sdk-package/constants/error-messages.ts+++ b/enterprise/frontend/src/embedding-sdk-package/constants/error-messages.ts@@ -2,7 +2,7 @@ export const SDK_NOT_STARTED_LOADING_MESSAGE ="Error loading the Embedded Analytics SDK. Ensure all SDK components are wrapped in the Provider component.";export const SDK_LOADING_ERROR_MESSAGE =- "Error loading the Embedded Analytics SDK. Verify the instance URL is correct and reachable.";+ "Error loading the Embedded Analytics SDK. Verify the instance is Enterprise and its URL is correct and reachable.";export const SDK_NOT_LOADED_YET_MESSAGE ="Error loading the Embedded Analytics SDK. The loading state is `Loaded` but the SDK bundle is not loaded yet.";diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.tsindex 67db58bbc76..98f12903413 100644--- a/enterprise/frontend/src/embedding-sdk-package/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts@@ -89,11 +89,13 @@ export type {ChartColor,CreateDashboardValues,EntityTypeFilterKeys,+ InitializationStatus,LoginStatus,MetabaseAuthConfig,MetabaseAuthConfigWithApiKey,MetabaseAuthConfigWithJwt,MetabaseAuthConfigWithSaml,+ MetabaseIsGuestAuthConfig,MetabaseClickActionPluginsConfig,MetabaseColors,MetabaseClickAction,@@ -109,14 +111,17 @@ export type {MetabaseQuestion,MetabaseTheme,MetabaseUser,+ SdkEntityToken,SdkCollectionId,SdkDashboardId,+ SdkDashboardEntityPublicProps,SdkDashboardLoadEvent,SdkEntityId,SdkErrorComponent,SdkErrorComponentProps,SdkEventHandlersConfig,SdkQuestionId,+ SdkQuestionEntityPublicProps,SdkQuestionTitleProps,SdkUserId,SqlParameterValues,diff --git a/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts b/enterprise/frontend/src/metabase-enterprise/content_translation/index.tsindex 5fcb9b88957..f3bfcf51ef7 100644--- a/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts@@ -16,14 +16,21 @@ import {*/export function initializePlugin() {if (hasPremiumFeature("content_translation")) {+ const getDictionaryBasePath = `/api/ee/content-translation/dictionary`;+Object.assign(PLUGIN_CONTENT_TRANSLATION, {isEnabled: true,useSortByContentTranslation,useTranslateContent,useTranslateFieldValuesInHoveredObject,useTranslateSeries,+ getDictionaryBasePath,setEndpointsForStaticEmbedding: (encodedToken: string) => {- contentTranslationEndpoints.getDictionary = `/api/ee/content-translation/dictionary/${encodedToken}`;+ if (contentTranslationEndpoints.getDictionary) {+ return;+ }++ contentTranslationEndpoints.getDictionary = `${getDictionaryBasePath}/${encodedToken}`;},translateDisplayNames,ContentTranslationConfiguration,diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/EmbeddingAppOriginDescription/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding/components/EmbeddingAppOriginDescription/index.tsdeleted file mode 100644index 0c22012cb56..00000000000--- a/enterprise/frontend/src/metabase-enterprise/embedding/components/EmbeddingAppOriginDescription/index.ts+++ /dev/null@@ -1 +0,0 @@-export { EmbeddingAppOriginDescription } from "./EmbeddingAppOriginDescription";diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/EmbeddingAppOriginDescription/EmbeddingAppOriginDescription.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/InteractiveEmbeddingAuthorizedOriginsWidget.tsxsimilarity index 59%rename from enterprise/frontend/src/metabase-enterprise/embedding/components/EmbeddingAppOriginDescription/EmbeddingAppOriginDescription.tsxrename to enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/InteractiveEmbeddingAuthorizedOriginsWidget.tsxindex d6b2589347a..eefe191cbf8 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding/components/EmbeddingAppOriginDescription/EmbeddingAppOriginDescription.tsx+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/InteractiveEmbeddingAuthorizedOriginsWidget.tsx@@ -1,10 +1,11 @@import cx from "classnames";import { jt, t } from "ttag";+import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";import ExternalLink from "metabase/common/components/ExternalLink";import CS from "metabase/css/core/index.css";-export const EmbeddingAppOriginDescription = () => {+const Description = () => {return jt`Enter the origins for the websites or web apps where you want to allow embedding, separated by a space. Here are the ${(<ExternalLinkkey="specs"@@ -15,3 +16,13 @@ export const EmbeddingAppOriginDescription = () => {</ExternalLink>)} for what can be entered.`;};++export const InteractiveEmbeddingAuthorizedOriginsWidget = () => (+ <AdminSettingInput+ name="embedding-app-origins-interactive"+ title={t`Authorized origins`}+ description={<Description />}+ placeholder="https://*.example.com"+ inputType="text"+ />+);diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/InteractiveEmbeddingAuthorizedOriginsWidget.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/InteractiveEmbeddingAuthorizedOriginsWidget.unit.spec.tsxnew file mode 100644index 00000000000..d8588e1e60d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/InteractiveEmbeddingAuthorizedOriginsWidget.unit.spec.tsx@@ -0,0 +1,41 @@+import userEvent from "@testing-library/user-event";++import {+ findRequests,+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+ setupUpdateSettingEndpoint,+} from "__support__/server-mocks";+import { fireEvent, renderWithProviders, screen } from "__support__/ui";+import { createMockSettings } from "metabase-types/api/mocks";++import { InteractiveEmbeddingAuthorizedOriginsWidget } from "./InteractiveEmbeddingAuthorizedOriginsWidget";++const setup = async ({ enabled }: { enabled: boolean }) => {+ const settings = createMockSettings({+ "enable-embedding-interactive": enabled,+ });++ setupPropertiesEndpoints(settings);+ setupSettingsEndpoints([]);+ setupUpdateSettingEndpoint();++ renderWithProviders(<InteractiveEmbeddingAuthorizedOriginsWidget />);+};++describe("InteractiveEmbeddingAuthorizedOriginsWidget", () => {+ it("should allow changing authorized origins", async () => {+ await setup({ enabled: true });++ const input = await screen.findByPlaceholderText("https://*.example.com");+ await userEvent.type(input, "https://*.foo.example.com");+ await fireEvent.blur(input);+ await screen.findByDisplayValue("https://*.foo.example.com");++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ const [{ url, body }] = puts;+ expect(url).toContain("/setting/embedding-app-origins-interactive");+ expect(body).toEqual({ value: "https://*.foo.example.com" });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/index.tsnew file mode 100644index 00000000000..9f1c22a3875--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget/index.ts@@ -0,0 +1 @@+export { InteractiveEmbeddingAuthorizedOriginsWidget } from "./InteractiveEmbeddingAuthorizedOriginsWidget";diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettings.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettings.tsxdeleted file mode 100644index b7b6a7c724d..00000000000--- a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettings.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { t } from "ttag";--import {- RelatedSettingsSection,- getInteractiveEmbeddingRelatedSettingItems,-} from "metabase/admin/components/RelatedSettingsSection";-import {- SettingsPageWrapper,- SettingsSection,-} from "metabase/admin/components/SettingsSection";-import { EmbeddingSettingsCard } from "metabase/admin/settings/components/EmbeddingSettings";-import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";-import { UpsellDevInstances } from "metabase/admin/upsells";-import { useDocsUrl } from "metabase/common/hooks";--import { EmbeddingAppOriginDescription } from "./EmbeddingAppOriginDescription";--const utmTags = {- utm_source: "product",- utm_medium: "docs",- utm_campaign: "embedding-interactive",- utm_content: "embedding-interactive-admin",-};--export function InteractiveEmbeddingSettings() {- const { url: quickStartUrl } = useDocsUrl(- "embedding/interactive-embedding-quick-start-guide",- {- utm: utmTags,- },- );-- return (- <SettingsPageWrapper title={t`Interactive embedding`}>- <EmbeddingSettingsCard- title={t`Enable interactive embedding`}- description={t`Embed the full power of Metabase into your application to build a custom analytics experience and programmatically manage dashboards and data.`}- settingKey="enable-embedding-interactive"- links={[{ icon: "bolt", title: t`Quick start`, href: quickStartUrl }]}- />-- <SettingsSection>- <AdminSettingInput- name="embedding-app-origins-interactive"- title={t`Authorized origins`}- titleProps={{ fz: "lg", mb: "xs" }}- description={<EmbeddingAppOriginDescription />}- placeholder="https://*.example.com"- inputType="text"- />- </SettingsSection>-- <RelatedSettingsSection- items={getInteractiveEmbeddingRelatedSettingItems()}- />-- <UpsellDevInstances location="embedding-page" />- </SettingsPageWrapper>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettingsCard.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettingsCard.tsxnew file mode 100644index 00000000000..f6d1717f4c5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettingsCard.tsx@@ -0,0 +1,55 @@+import cx from "classnames";+import { c, t } from "ttag";++import { EmbeddingSettingsCard } from "metabase/admin/settings/components/EmbeddingSettings";+import ExternalLink from "metabase/common/components/ExternalLink";+import { useDocsUrl, useSetting } from "metabase/common/hooks";+import CS from "metabase/css/core/index.css";+import { Stack } from "metabase/ui/components";+import { InteractiveEmbeddingAuthorizedOriginsWidget } from "metabase-enterprise/embedding/components/InteractiveEmbeddingAuthorizedOriginsWidget";++const utmTags = {+ utm_source: "product",+ utm_medium: "docs",+ utm_campaign: "embedding-interactive",+ utm_content: "embedding-interactive-admin",+};++export function InteractiveEmbeddingSettingsCard() {+ const isInteractiveEmbeddingEnabled = useSetting(+ "enable-embedding-interactive",+ );++ const { url: quickStartUrl } = useDocsUrl(+ "embedding/interactive-embedding-quick-start-guide",+ {+ utm: utmTags,+ },+ );++ return (+ <EmbeddingSettingsCard+ title={t`Enable legacy interactive embedding`}+ description={t`A way to embed the entire Metabase app in an iframe. It integrates your permissions and SSO to give people the right level ofaccess to query and drill-down into your data.`}+ settingKey="enable-embedding-interactive"+ alertInfoText={c(+ "{0} is the link to switch binaries. {1} is the link to upsell the SDK. {2} is the link to implement JWT or SAML authentication.",+ )+ .jt`The new embedding methods give you more flexibility. Interactive embedding and Static embedding will be deprecated in a future version of Metabase. ${(+ <ExternalLink+ key="migration-guide-from-legacy-embedding"+ href={quickStartUrl}+ className={cx(CS.link, CS.textBold)}+ >+ {t`Read more`}+ </ExternalLink>+ )}.`}+ >+ {isInteractiveEmbeddingEnabled && (+ <Stack gap="xl" px="xl" pb="lg">+ <InteractiveEmbeddingAuthorizedOriginsWidget />+ </Stack>+ )}+ </EmbeddingSettingsCard>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettings.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettingsCard.unit.spec.tsxsimilarity index 57%rename from enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettings.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettingsCard.unit.spec.tsxindex cfc41097bf6..a9b2562bf8d 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettings.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/InteractiveEmbeddingSettingsCard.unit.spec.tsx@@ -5,12 +5,13 @@ import {setupPropertiesEndpoints,setupSettingsEndpoints,setupUpdateSettingEndpoint,+ setupUpdateSettingsEndpoint,setupUserKeyValueEndpoints,} from "__support__/server-mocks";import { fireEvent, renderWithProviders, screen } from "__support__/ui";import { createMockSettings } from "metabase-types/api/mocks";-import { InteractiveEmbeddingSettings } from "./InteractiveEmbeddingSettings";+import { InteractiveEmbeddingSettingsCard } from "./InteractiveEmbeddingSettingsCard";const setup = async ({ enabled }: { enabled: boolean }) => {const settings = createMockSettings({@@ -20,44 +21,37 @@ const setup = async ({ enabled }: { enabled: boolean }) => {setupPropertiesEndpoints(settings);setupSettingsEndpoints([]);setupUpdateSettingEndpoint();+ setupUpdateSettingsEndpoint();setupUserKeyValueEndpoints({namespace: "user_acknowledgement",key: "upsell-dev_instances",value: true,});- renderWithProviders(<InteractiveEmbeddingSettings />);-- await screen.findByText("Interactive embedding"); // breadcrumb+ renderWithProviders(<InteractiveEmbeddingSettingsCard />);};-describe("InteractiveEmbeddingSettings", () => {+describe("InteractiveEmbeddingSettingsCard", () => {it("should show interactive embedding toggle", async () => {await setup({ enabled: true });expect(- await screen.findByText("Enable interactive embedding"),+ await screen.findByText("Enable legacy interactive embedding"),).toBeInTheDocument();});it("should toggle interactive embedding on", async () => {await setup({ enabled: false });const toggle = await screen.findByLabelText(- "Enable interactive embedding toggle",+ "Enable legacy interactive embedding toggle",);await userEvent.click(toggle);const puts = await findRequests("PUT");expect(puts).toHaveLength(1);const [{ url, body }] = puts;- expect(url).toContain("/setting/enable-embedding-interactive");- expect(body).toEqual({ value: true });- });-- it("should show quickstart link", async () => {- await setup({ enabled: true });-- expect(await screen.findByText("Quick start")).toBeInTheDocument();+ expect(url).toContain("/setting");+ expect(body).toEqual({ "enable-embedding-interactive": true });});it("should allow changing authorized origins", async () => {@@ -74,20 +68,4 @@ describe("InteractiveEmbeddingSettings", () => {expect(url).toContain("/setting/embedding-app-origins-interactive");expect(body).toEqual({ value: "https://*.foo.example.com" });});-- it("should show cards with related settings", async () => {- await setup({ enabled: true });-- const relatedSettingCards = await screen.findAllByTestId(- "related-setting-card",- );- expect(relatedSettingCards).toHaveLength(6);-- expect(await screen.findByText("Authentication")).toBeInTheDocument();- expect(await screen.findByText("Databases")).toBeInTheDocument();- expect(await screen.findByText("People")).toBeInTheDocument();- expect(await screen.findByText("Permissions")).toBeInTheDocument();- expect(await screen.findByText("Embedded Metabot")).toBeInTheDocument();- expect(await screen.findByText("Appearance")).toBeInTheDocument();- });});diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding/index.tsindex fe53d4c783d..33732ebee9a 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding/index.ts@@ -4,7 +4,7 @@ import { PLUGIN_ADMIN_SETTINGS, PLUGIN_EMBEDDING } from "metabase/plugins";import { isInteractiveEmbeddingEnabled } from "metabase-enterprise/embedding/selectors";import { hasPremiumFeature } from "metabase-enterprise/settings";-import { InteractiveEmbeddingSettings } from "./components/InteractiveEmbeddingSettings";+import { InteractiveEmbeddingSettingsCard } from "./components/InteractiveEmbeddingSettingsCard";/*** We can't gate this component behind a feature flag, because SDK users could@@ -21,7 +21,7 @@ export function initializePlugin() {PLUGIN_EMBEDDING.isEnabled = () => true;PLUGIN_EMBEDDING.isInteractiveEmbeddingEnabled =isInteractiveEmbeddingEnabled;- PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettings =- InteractiveEmbeddingSettings;+ PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettingsCard =+ InteractiveEmbeddingSettingsCard;}}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.tsindex 6115cb6bc90..296a66fb5bb 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts@@ -1,11 +1,6 @@-import { SdkIframeEmbedRoute } from "metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute";import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";import { hasPremiumFeature } from "metabase-enterprise/settings";-// We allow users try out the iframe embedding without valid license on localhost.-// This should always be usable on an EE instance regardless of license.-PLUGIN_EMBEDDING_IFRAME_SDK.SdkIframeEmbedRoute = SdkIframeEmbedRoute;-if (hasPremiumFeature("embedding_simple")) {PLUGIN_EMBEDDING_IFRAME_SDK.hasValidLicense = () => true;}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.tsindex 65cc284b228..b7739aacc5e 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,4 +1,3 @@-import { SdkIframeEmbedSetupModal } from "metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal";import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";import { hasPremiumFeature } from "metabase-enterprise/settings";@@ -10,8 +9,5 @@ export function initializePlugin() {// 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.SdkIframeEmbedSetupModal =- SdkIframeEmbedSetupModal;}}diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.tsindex d61a072672d..16c22d12ab9 100644--- a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts+++ b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts@@ -6,6 +6,7 @@ PLUGIN_IS_EE_BUILD.isEEBuild = () => true;import "./shared";// CORE APP PLUGINS THAT USE hasPremiumFeature (import initialization functions):+import { initializePlugin as initializeContentTranslation } from "./content_translation";import { initializePlugin as initializeEmbedding } from "./embedding";import { initializePlugin as initializeEmbeddingSdk } from "./embedding-sdk";import { initializePlugin as initializeMetabot } from "./metabot";@@ -22,6 +23,7 @@ export function initializePlugins() {initializeMetabot?.();initializeWhitelabelPlugin?.();initializeWhitelabelOverridePlugin?.();+ initializeContentTranslation?.();}// "SDK EE-plugins", that are specific to the embedding sdk.diff --git a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/GuestEmbedGuard.tsx b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/GuestEmbedGuard.tsxnew file mode 100644index 00000000000..3d33edaea26--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/GuestEmbedGuard.tsx@@ -0,0 +1,22 @@+import type { PropsWithChildren } from "react";+import { t } from "ttag";++import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError";+import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";++export const GuestEmbedGuard = ({+ children,+ supportsGuestEmbed,+}: PropsWithChildren<{+ componentName: string;+ supportsGuestEmbed: boolean;+}>) => {+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);++ return isGuestEmbed && !supportsGuestEmbed ? (+ <SdkError message={t`This component does not support guest embeds`} />+ ) : (+ children+ );+};diff --git a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.tsx b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.tsxindex ceb331824da..28d9e8aa6b9 100644--- a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.tsx@@ -5,7 +5,7 @@ import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponenimport { SdkLoader } from "embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkLoader";import { useSdkSelector } from "embedding-sdk-bundle/store";import {- getLoginStatus,+ getInitStatus,getUsageProblem,} from "embedding-sdk-bundle/store/selectors";import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";@@ -18,21 +18,21 @@ export const PublicComponentWrapper = forwardRef<HTMLDivElement,PublicComponentWrapperProps>(function PublicComponentWrapper({ children, className, style }, ref) {- const loginStatus = useSdkSelector(getLoginStatus);+ const initStatus = useSdkSelector(getInitStatus);const usageProblem = useSdkSelector(getUsageProblem);let content = children;if (- loginStatus.status === "uninitialized" ||- loginStatus.status === "loading"+ initStatus.status === "uninitialized" ||+ initStatus.status === "loading") {content = <SdkLoader />;}- if (loginStatus.status === "error") {+ if (initStatus.status === "error") {content = (- <SdkError message={loginStatus.error.message} error={loginStatus.error} />+ <SdkError message={initStatus.error.message} error={initStatus.error} />);}diff --git a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.unit.spec.tsxindex 70c2717dab1..2eed45c445d 100644--- a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/PublicComponentWrapper.unit.spec.tsx@@ -12,7 +12,7 @@ import { PublicComponentWrapper } from "./PublicComponentWrapper";const setup = (status: LoginStatus = { status: "uninitialized" }) => {const state = createMockState({sdk: createMockSdkState({- loginStatus: createMockLoginStatusState(status),+ initStatus: createMockLoginStatusState(status),}),});diff --git a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/withPublicComponentWrapper.tsx b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/withPublicComponentWrapper.tsxindex 653efcf71bf..a328ce46fb9 100644--- a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/withPublicComponentWrapper.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/withPublicComponentWrapper.tsx@@ -1,21 +1,29 @@import type React from "react";+import { GuestEmbedGuard } from "./GuestEmbedGuard";import { PublicComponentWrapper } from "./PublicComponentWrapper";export function withPublicComponentWrapper<P extends object>(WrappedComponent: React.ComponentType<P>,+ { supportsGuestEmbed }: { supportsGuestEmbed: boolean },): (props: P) => React.ReactNode {+ const componentName =+ WrappedComponent.displayName || WrappedComponent.name || "Component";+const WithPublicComponentWrapper: React.FC<P> = (props) => {return (- <PublicComponentWrapper>- <WrappedComponent {...props} />- </PublicComponentWrapper>+ <GuestEmbedGuard+ componentName={componentName}+ supportsGuestEmbed={supportsGuestEmbed}+ >+ <PublicComponentWrapper>+ <WrappedComponent {...props} />+ </PublicComponentWrapper>+ </GuestEmbedGuard>);};- WithPublicComponentWrapper.displayName = `withPublicComponentWrapper(${- WrappedComponent.displayName || WrappedComponent.name || "Component"- })`;+ WithPublicComponentWrapper.displayName = `withPublicComponentWrapper(${componentName})`;return WithPublicComponentWrapper;}diff --git a/frontend/src/embedding-sdk-bundle/components/private/QuestionTitle.tsx b/frontend/src/embedding-sdk-bundle/components/private/QuestionTitle.tsxindex 658d35eac3c..62b3a1e9954 100644--- a/frontend/src/embedding-sdk-bundle/components/private/QuestionTitle.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/QuestionTitle.tsx@@ -2,6 +2,7 @@ import cx from "classnames";import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";import CS from "metabase/css/core/index.css";+import { useTranslateContent } from "metabase/i18n/hooks";import {getAdHocQuestionDescription,shouldRenderAdhocDescription,@@ -49,6 +50,7 @@ export const QuestionTitle = ({style,}: QuestionTitleProps) => {const questionTitle = getQuestionTitle({ question });+ const tc = useTranslateContent();if (questionTitle === null) {return null;@@ -56,7 +58,7 @@ export const QuestionTitle = ({return (<h2 className={cx(CS.h2, CS.textWrap, className)} style={style}>- {questionTitle}+ {tc(questionTitle)}</h2>);};diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsxindex c6cc6d66bbc..fa942cec8af 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx@@ -20,10 +20,11 @@ const DownloadWidgetInner = ({...rest}: DownloadWidgetProps &Pick<UseDownloadDataParams, "question" | "result">) => {- const { withDownloads } = useSdkQuestionContext();+ const { withDownloads, token } = useSdkQuestionContext();const [, handleDownload] = useDownloadData({question,result,+ token,});return (diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsxindex 0d01d735df2..2c5d180e997 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx@@ -2,6 +2,7 @@ import { useMemo } from "react";import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";import { ResponsiveParametersList } from "metabase/query_builder/components/ResponsiveParametersList";+import { Box } from "metabase/ui";import * as Lib from "metabase-lib";import type { ParameterId } from "metabase-types/api";@@ -17,6 +18,7 @@ export const SqlParametersList = () => {const {question,originalQuestion,+ token,parameterValues,updateParameterValues,hiddenParameters,@@ -49,7 +51,7 @@ export const SqlParametersList = () => {);}, [question, originalQuestion, hiddenParameters]);- if (!question || !isNativeQuestion) {+ if (!question || !isNativeQuestion || !parameters.length) {return null;}@@ -63,18 +65,21 @@ export const SqlParametersList = () => {};return (- <ResponsiveParametersList- classNames={{- container: SqlParametersListS.SqlParametersListContainer,- parametersList: SqlParametersListS.SqlParametersList,- }}- cardId={question.id()}- dashboardId={question.dashboardId() ?? undefined}- parameters={parameters}- setParameterValue={setParameterValue}- enableParameterRequiredBehavior- commitImmediately={false}- isSortable={false}- />+ <Box w="100%">+ <ResponsiveParametersList+ classNames={{+ container: SqlParametersListS.SqlParametersListContainer,+ parametersList: SqlParametersListS.SqlParametersList,+ }}+ cardId={question.id()}+ dashboardId={question.dashboardId() ?? undefined}+ token={token}+ parameters={parameters}+ setParameterValue={setParameterValue}+ enableParameterRequiredBehavior+ commitImmediately={false}+ isSortable={false}+ />+ </Box>);};diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization.tsxindex df0815f9cba..dff7d7b0c0e 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization.tsx@@ -10,6 +10,8 @@ import {SdkLoader,} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { shouldRunCardQuery } from "embedding-sdk-bundle/lib/sdk-question";+import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";import { useLocale } from "metabase/common/hooks/use-locale";import CS from "metabase/css/core/index.css";import QueryVisualization from "metabase/query_builder/components/QueryVisualization";@@ -50,7 +52,9 @@ export const QuestionVisualization = ({updateQuestion,originalId,onVisualizationChange,+ token,} = useSdkQuestionContext();+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);const display = useMemo(() => question?.display(), [question]);@@ -62,7 +66,7 @@ export const QuestionVisualization = ({// When visualizing a question for the first time, there is no query result yet.const isQueryResultLoading =- question && shouldRunCardQuery(question) && !queryResults;+ question && shouldRunCardQuery({ question, isGuestEmbed }) && !queryResults;if (isLocaleLoading || isQuestionLoading || isQueryResultLoading) {return <SdkLoader />;@@ -97,6 +101,7 @@ export const QuestionVisualization = ({result={result}noHeadermode={mode}+ token={token}navigateToNewCardInsideQB={navigateToNewCard}onNavigateBack={onNavigateBack}onUpdateQuestion={(question: Question) =>diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex 627c4ac66fb..96ad7e106db 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -1,12 +1,19 @@import { createContext, useContext, useEffect, useMemo } from "react";+import { t } from "ttag";import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";import { useLoadQuestion } from "embedding-sdk-bundle/hooks/private/use-load-question";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";-import { getError, getPlugins } from "embedding-sdk-bundle/store/selectors";+import {+ getError,+ getIsGuestEmbed,+ getPlugins,+} from "embedding-sdk-bundle/store/selectors";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";import type { MetabasePluginsConfig as InternalMetabasePluginsConfig } from "metabase/embedding-sdk/types/plugins";+import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";import {type OnCreateOptions,useCreateQuestion,@@ -33,7 +40,8 @@ export const SdkQuestionContext = createContext<const DEFAULT_OPTIONS = {};export const SdkQuestionProvider = ({- questionId,+ questionId: rawQuestionId,+ token: rawToken,options = DEFAULT_OPTIONS,deserializedCard,componentPlugins,@@ -54,6 +62,26 @@ export const SdkQuestionProvider = ({navigateToNewCard: userNavigateToNewCard,onVisualizationChange,}: SdkQuestionProviderProps) => {+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);++ const {+ resourceId: questionId,+ token,+ tokenError,+ } = useExtractResourceIdFromJwtToken({+ isGuestEmbed,+ resourceId: rawQuestionId,+ token: rawToken ?? undefined,+ });++ useEffect(() => {+ if (isGuestEmbed && token) {+ PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);+ }+ }, [isGuestEmbed, token]);++ const isNewQuestion = questionId === "new";+const error = useSdkSelector(getError);const handleCreateQuestion = useCreateQuestion();@@ -113,6 +141,8 @@ export const SdkQuestionProvider = ({navigateToNewCard,} = useLoadQuestion({questionId,+ isGuestEmbed,+ token,options,deserializedCard,initialSqlParameters,@@ -142,6 +172,7 @@ export const SdkQuestionProvider = ({const questionContext: SdkQuestionContextType = {originalId: questionId,+ token,isQuestionLoading,isQueryRunning,resetQuestion: loadAndQueryQuestion,@@ -173,8 +204,12 @@ export const SdkQuestionProvider = ({};useEffect(() => {+ if (tokenError) {+ return;+ }+loadAndQueryQuestion();- }, [loadAndQueryQuestion]);+ }, [loadAndQueryQuestion, tokenError]);const dispatch = useSdkDispatch();@@ -182,6 +217,18 @@ export const SdkQuestionProvider = ({dispatch(setEntityTypes(entityTypes));}, [dispatch, entityTypes]);+ if (isGuestEmbed && isNewQuestion) {+ return (+ <SdkError+ message={t`You can't explore or save questions in Guest Embed mode`}+ />+ );+ }++ if (tokenError) {+ return <SdkError message={tokenError} />;+ }+if (error) {return <SdkError message={error.message} />;}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.tsindex a6827169530..32d35f7cf08 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts@@ -1,6 +1,7 @@import type { PropsWithChildren } from "react";import type { LoadQuestionHookResult } from "embedding-sdk-bundle/hooks/private/use-load-question";+import type { SdkEntityToken } from "embedding-sdk-bundle/types";import type { SdkCollectionId } from "embedding-sdk-bundle/types/collection";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";import type {@@ -105,10 +106,18 @@ export type QuestionMockLocationParameters = {params: { slug?: string };};+/**+ * @inline+ */+export type SdkQuestionEntityInternalProps = {+ questionId?: SdkQuestionId | null;+ token?: SdkEntityToken | null;+};+export type SdkQuestionProviderProps = PropsWithChildren<SdkQuestionConfig &- Omit<LoadSdkQuestionParams, "questionId"> & {- questionId: SdkQuestionId | null;+ Omit<LoadSdkQuestionParams, "questionId"> &+ SdkQuestionEntityInternalProps & {/*** @internal*/@@ -139,6 +148,7 @@ export type SdkQuestionContextType = Omit<plugins: SdkQuestionConfig["componentPlugins"] | null;mode: QueryClickActionsMode | Mode | null | undefined;originalId: SdkQuestionId | null;+ token: string | null | undefined;resetQuestion: () => void;onReset: () => void;onCreate: (question: Question) => Promise<Question>;diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsxindex 233387448ac..d6e395154fb 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/DefaultViewTitle.tsx@@ -1,5 +1,6 @@import { c, t } from "ttag";+import { useTranslateContent } from "metabase/i18n/hooks";import { Anchor, Stack, Text } from "metabase/ui";import { getQuestionTitle } from "../QuestionTitle";@@ -46,6 +47,7 @@ export const DefaultViewTitle = ({withResetButton = false,}: SdkQuestionDefaultViewProps) => {const { question, originalQuestion, onReset } = useSdkQuestionContext();+ const tc = useTranslateContent();const isQuestionChanged = originalQuestion? question?.isQueryDirtyComparedTo(originalQuestion)@@ -58,7 +60,7 @@ export const DefaultViewTitle = ({if (title === undefined || title === true) {const originalName = originalQuestion?.displayName();- const titleText = getQuestionTitle({ question });+ const titleText = tc(getQuestionTitle({ question }));return (<DefaultViewTitleText@@ -78,11 +80,13 @@ export const DefaultViewTitle = ({}if (typeof title === "string") {+ const titleText = tc(title);+return (<DefaultViewTitleTexttitle={<Text fw={700} c="var(--mb-color-text-primary)" fz="xl">- {title}+ {titleText}</Text>}withResetButton={withResetButton}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.module.css b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.module.cssindex 95cb298992b..3fb24b861ec 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.module.css+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.module.css@@ -21,6 +21,20 @@"Main";}+.ContainerTwoRows {+ display: grid;+ grid-template: auto 1fr / 1fr;+ grid-template-areas:+ "TopBar"+ "Main";+}++.ContainerSingleRow {+ display: grid;+ grid-template: 1fr / 1fr;+ grid-template-areas: "Main";+}+.TopBar {grid-area: TopBar;}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsxindex 2a98373543d..9842b801323 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx@@ -10,8 +10,11 @@ import {SdkLoader,} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { QuestionVisualization } from "embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization";+import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";import { shouldRunCardQuery } from "embedding-sdk-bundle/lib/sdk-question";+import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";import type { SdkQuestionTitleProps } from "embedding-sdk-bundle/types/question";import { SaveQuestionModal } from "metabase/common/components/SaveQuestionModal";import { useLocale } from "metabase/common/hooks/use-locale";@@ -88,6 +91,7 @@ export const SdkQuestionDefaultView = ({} = useSdkQuestionContext();const { isBreadcrumbEnabled, reportLocation } = useSdkBreadcrumbs();+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);const isNewQuestion = originalId === "new";const isQuestionSaved = question?.isSaved();@@ -123,7 +127,7 @@ export const SdkQuestionDefaultView = ({// When visualizing a question for the first time, there is no query result yet.const isQueryResultLoading =- question && shouldRunCardQuery(question) && !queryResults;+ question && shouldRunCardQuery({ question, isGuestEmbed }) && !queryResults;useEffect(() => {if (@@ -239,6 +243,12 @@ export const SdkQuestionDefaultView = ({</Group></ResultToolbar>)}++ {isGuestEmbed && (+ <Box w="100%">+ <SdkQuestion.SqlParametersList />+ </Box>+ )}</Stack><Boxdiff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsxindex fa42dcbace7..2922d44862a 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx@@ -205,6 +205,8 @@ const CollectionBrowserWrapper = ({};export const CollectionBrowser = Object.assign(- withPublicComponentWrapper(CollectionBrowserWrapper),+ withPublicComponentWrapper(CollectionBrowserWrapper, {+ supportsGuestEmbed: false,+ }),{ schema: collectionBrowserPropsSchema },);diff --git a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsxindex 769d5a698f4..5c241a999da 100644--- a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx@@ -4,10 +4,12 @@ import { type JSX, memo, useEffect, useId, useRef } from "react";import { SdkThemeProvider } from "embedding-sdk-bundle/components/private/SdkThemeProvider";import { useInitDataInternal } from "embedding-sdk-bundle/hooks/private/use-init-data";+import { useNormalizeComponentProviderProps } from "embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props";import { getSdkStore } from "embedding-sdk-bundle/store";import {setErrorComponent,setEventHandlers,+ setIsGuestEmbed,setLoaderComponent,setPlugins,} from "embedding-sdk-bundle/store/reducer";@@ -63,16 +65,26 @@ export const ComponentProviderInternal = ({allowConsoleLog,isLocalHost,}: ComponentProviderInternalProps): JSX.Element => {+ const isGuestEmbed = !!authConfig.isGuest;const { fontFamily } = theme ?? {};// The main call of useInitData happens in the MetabaseProvider// This call in the ComponentProvider is still needed for:// - Storybook stories, where we don't have the MetabaseProvider// - Unit tests- useInitDataInternal({ reduxStore, authConfig, isLocalHost });+ useInitDataInternal({+ reduxStore,+ isGuestEmbed,+ authConfig,+ isLocalHost,+ });useInitPlugins();+ useEffect(() => {+ reduxStore.dispatch(setIsGuestEmbed(!!isGuestEmbed));+ }, [reduxStore, isGuestEmbed]);+useEffect(() => {if (fontFamily) {reduxStore.dispatch(setOptions({ font: fontFamily }));@@ -152,11 +164,13 @@ export const ComponentProvider = memo(function ComponentProvider({reduxStoreRef.current = props.reduxStore ?? getSdkStore();}+ const normalizedProps = useNormalizeComponentProviderProps(props);+return (<MetabaseReduxProvider store={reduxStoreRef.current!}><METABOT_SDK_EE_PLUGIN.MetabotProvider><ComponentProviderInternal- {...props}+ {...normalizedProps}reduxStore={reduxStoreRef.current!}>{children}diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsxindex aac95f4cf67..58b5f93b2d9 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx@@ -74,6 +74,8 @@ const CreateDashboardModalInner = ({};export const CreateDashboardModal = Object.assign(- withPublicComponentWrapper(CreateDashboardModalInner),+ withPublicComponentWrapper(CreateDashboardModalInner, {+ supportsGuestEmbed: false,+ }),{ schema: createDashboardModalSchema },);diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsxindex c5bf2a9c005..41f07ffbd38 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx@@ -1,3 +1,5 @@+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import {InteractiveQuestion,type InteractiveQuestionProps,@@ -13,6 +15,10 @@ export type CreateQuestionProps = Omit<"questionId" | "children">;-export const CreateQuestion = (props: CreateQuestionProps = {}) => (+const CreateQuestionInner = (props: CreateQuestionProps = {}) => (<InteractiveQuestion {...props} questionId="new" />);++export const CreateQuestion = withPublicComponentWrapper(CreateQuestionInner, {+ supportsGuestEmbed: false,+}) as typeof CreateQuestionInner;diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.tsindex 8cf1f807622..f9ac43d42f0 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts@@ -31,6 +31,7 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionProps> = Yup.object({.optional().noUnknown(),questionId: Yup.mixed().required(),+ token: Yup.mixed().optional(),style: Yup.mixed().optional(),targetCollection: Yup.mixed().optional(),targetDashboardId: Yup.mixed().optional(),diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsxindex c90f84dd7dc..dd3e29d1b7e 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx@@ -1,3 +1,4 @@+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import {BackButton,Breakout,@@ -36,7 +37,7 @@ import { interactiveQuestionSchema } from "./InteractiveQuestion.schema";*/export type InteractiveQuestionProps = Omit<SdkQuestionProps,- "getClickActionMode" | "navigateToNewCard" | "backToDashboard"+ "token" | "getClickActionMode" | "navigateToNewCard" | "backToDashboard">;/**@@ -103,7 +104,9 @@ const subComponents: InteractiveQuestionComponents = {};export const InteractiveQuestion = Object.assign(- _InteractiveQuestion,+ withPublicComponentWrapper(_InteractiveQuestion, {+ supportsGuestEmbed: false,+ }),subComponents,{ schema: interactiveQuestionSchema },);diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsxindex f6104dc0d75..ed2e3e7a020 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx@@ -115,6 +115,7 @@ export type SdkQuestionComponents = {export const _SdkQuestion = ({questionId,+ token,options,deserializedCard,plugins,@@ -145,6 +146,7 @@ export const _SdkQuestion = ({}: SdkQuestionProps): JSX.Element | null => (<SdkQuestionProviderquestionId={questionId}+ token={token}options={options}deserializedCard={deserializedCard}componentPlugins={plugins}@@ -206,6 +208,8 @@ const subComponents: SdkQuestionComponents = {};export const SdkQuestion = Object.assign(- withPublicComponentWrapper(_SdkQuestion),+ withPublicComponentWrapper(_SdkQuestion, {+ supportsGuestEmbed: true,+ }),subComponents,);diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.tsindex 5e650297e1c..9d5f52e2f00 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts@@ -10,7 +10,12 @@ const propsSchema: Yup.SchemaOf<StaticQuestionProps> = Yup.object({height: Yup.mixed().optional(),initialSqlParameters: Yup.mixed().optional(),hiddenParameters: Yup.mixed().optional(),- questionId: Yup.mixed().required(),+ questionId: Yup.mixed().when("token", {+ is: (token: unknown) => token !== undefined,+ then: (schema) => schema.optional(),+ otherwise: (schema) => schema.required(),+ }),+ token: Yup.mixed().optional(),style: Yup.mixed().optional(),title: Yup.mixed().optional(),width: Yup.mixed().optional(),diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsxindex b1c91912d93..6d79c564f49 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx@@ -1,6 +1,7 @@import type { PropsWithChildren } from "react";import { FlexibleSizeComponent } from "embedding-sdk-bundle/components/private/FlexibleSizeComponent";+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import {Breakout,BreakoutDropdown,@@ -26,23 +27,25 @@ import {SdkQuestion,type SdkQuestionProps,} from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";-import { StaticQuestionSdkMode } from "embedding-sdk-bundle/components/public/StaticQuestion/mode";+import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";+import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";+import type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";import { Box, Stack } from "metabase/ui";import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";+import { EmbeddingSdkStaticMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode";import type { ClickActionModeGetter } from "metabase/visualizations/types";import type Question from "metabase-lib/v1/Question";import { staticQuestionSchema } from "./StaticQuestion.schema";/**- * @interface* @expand* @category StaticQuestion*/export type StaticQuestionProps = PropsWithChildren<Pick<SdkQuestionProps,- | "questionId"| "withChartTypeSelector"| "height"| "width"@@ -53,7 +56,8 @@ export type StaticQuestionProps = PropsWithChildren<| "withDownloads"| "title">->;+> &+ SdkQuestionEntityPublicProps;/*** @interface@@ -77,19 +81,30 @@ export type StaticQuestionComponents = {SqlParametersList: typeof SqlParametersList;};-const StaticQuestionInner = ({- questionId,- withChartTypeSelector,- height,- width,- className,- style,- initialSqlParameters,- hiddenParameters,- withDownloads,- title = false, // Hidden by default for backwards-compatibility.- children,-}: StaticQuestionProps): JSX.Element | null => {+const StaticQuestionInner = (+ props: StaticQuestionProps,+): JSX.Element | null => {+ // Normalize props for Guest Embed usage (e.g. enforce withDownloads in OSS).+ const normalizedProps =+ useNormalizeGuestEmbedQuestionOrDashboardComponentProps(props);++ const {+ questionId,+ token,+ withChartTypeSelector,+ height,+ width,+ className,+ style,+ initialSqlParameters,+ hiddenParameters,+ withDownloads,+ title = false, // Hidden by default for backwards-compatibility.+ children,+ } = normalizedProps;++ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);+const getClickActionMode: ClickActionModeGetter = ({question,}: {@@ -99,16 +114,15 @@ const StaticQuestionInner = ({question &&getEmbeddingMode({question,- queryMode: StaticQuestionSdkMode,+ queryMode: EmbeddingSdkStaticMode,}));};- const hasTopBar = Boolean(title || withChartTypeSelector || withDownloads);-return (<SdkQuestion- questionId={questionId}+ questionId={questionId ?? null}+ token={token}getClickActionMode={getClickActionMode}navigateToNewCard={null}initialSqlParameters={initialSqlParameters}@@ -128,18 +142,18 @@ const StaticQuestionInner = ({h="100%"gap="xs">- {hasTopBar && (- <Stack className={InteractiveQuestionS.TopBar} gap="sm" p="md">- {title && <DefaultViewTitle title={title} />}+ <Stack className={InteractiveQuestionS.TopBar} gap="sm" p="md">+ {title && <DefaultViewTitle title={title} />}++ {(withChartTypeSelector || withDownloads) && (+ <ResultToolbar>+ {withChartTypeSelector && <SdkQuestion.ChartTypeDropdown />}+ {withDownloads && <SdkQuestion.DownloadWidgetDropdown />}+ </ResultToolbar>+ )}- {(withChartTypeSelector || withDownloads) && (- <ResultToolbar>- {withChartTypeSelector && <SdkQuestion.ChartTypeDropdown />}- {withDownloads && <SdkQuestion.DownloadWidgetDropdown />}- </ResultToolbar>- )}- </Stack>- )}+ {isGuestEmbed && <SdkQuestion.SqlParametersList />}+ </Stack><Box className={InteractiveQuestionS.Main} w="100%" h="100%"><Box className={InteractiveQuestionS.Content}>@@ -178,7 +192,9 @@ const subComponents: StaticQuestionComponents = {};export const StaticQuestion = Object.assign(- StaticQuestionInner,+ withPublicComponentWrapper(StaticQuestionInner, {+ supportsGuestEmbed: true,+ }),subComponents,{ schema: staticQuestionSchema },);diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/mode.ts b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/mode.tsindex 6fb3b7a6ab2..e69de29bb2d 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/mode.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/mode.ts@@ -1,7 +0,0 @@-import type { QueryClickActionsMode } from "metabase/visualizations/types";--export const StaticQuestionSdkMode: QueryClickActionsMode = {- name: "static-question-sdk",- hasDrills: false,- clickActions: [],-};diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.tsindex efa7d4e00df..553363c3b70 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.schema.ts@@ -8,6 +8,7 @@ const propsSchema: Yup.SchemaOf<EditableDashboardProps> = Yup.object({children: Yup.mixed().optional(),className: Yup.mixed().optional(),dashboardId: Yup.mixed().required(),+ token: Yup.mixed().optional(),dataPickerProps: Yup.object({entityTypes: Yup.mixed().optional(),})diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsxindex 5c65b2f94e1..1cb5e0cd71a 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx@@ -1,3 +1,4 @@+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { DASHBOARD_EDITING_ACTIONS } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants";import { DASHBOARD_ACTION } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys";import type { MetabasePluginsConfig as InternalMetabasePluginsConfig } from "metabase/embedding-sdk/types/plugins";@@ -51,6 +52,11 @@ export const EditableDashboardInner = (props: EditableDashboardProps) => {);};-export const EditableDashboard = Object.assign(EditableDashboardInner, {- schema: editableDashboardSchema,-});+export const EditableDashboard = Object.assign(+ withPublicComponentWrapper(EditableDashboardInner, {+ supportsGuestEmbed: false,+ }),+ {+ schema: editableDashboardSchema,+ },+);diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.tsindex 9f9328dafc3..efbadcaf1da 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.schema.ts@@ -8,6 +8,7 @@ const propsSchema: Yup.SchemaOf<InteractiveDashboardProps> = Yup.object({children: Yup.mixed().optional(),className: Yup.mixed().optional(),dashboardId: Yup.mixed().required(),+ token: Yup.mixed().optional(),dataPickerProps: Yup.object({entityTypes: Yup.mixed().optional(),})diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsxindex 6cb8c7bacbc..c767b1d07c0 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx@@ -1,5 +1,6 @@import { useCallback, useMemo } from "react";+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { useSdkSelector } from "embedding-sdk-bundle/store";import { getPlugins } from "embedding-sdk-bundle/store/selectors";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";@@ -58,6 +59,11 @@ const InteractiveDashboardInner = (props: InteractiveDashboardProps) => {);};-export const InteractiveDashboard = Object.assign(InteractiveDashboardInner, {- schema: interactiveDashboardSchema,-});+export const InteractiveDashboard = Object.assign(+ withPublicComponentWrapper(InteractiveDashboardInner, {+ supportsGuestEmbed: false,+ }),+ {+ schema: interactiveDashboardSchema,+ },+);diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex e85cc5955f9..2d0a5eabad6 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -19,12 +19,14 @@ import {import { SdkAdHocQuestion } from "embedding-sdk-bundle/components/private/SdkAdHocQuestion";import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";import { useDashboardLoadHandlers } from "embedding-sdk-bundle/hooks/private/use-dashboard-load-handlers";+import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";import {type SdkDashboardDisplayProps,useSdkDashboardParams,} from "embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";import type { MetabaseQuestion } from "embedding-sdk-bundle/types";import type { DashboardEventHandlersProps } from "embedding-sdk-bundle/types/dashboard";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";@@ -44,7 +46,9 @@ import {useDashboardContext,} from "metabase/dashboard/context";import { getDashboardComplete, getIsDirty } from "metabase/dashboard/selectors";+import { isStaticEmbeddingEntityLoadingError } from "metabase/lib/errors/is-static-embedding-entity-loading-error";import { useSelector } from "metabase/lib/redux";+import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";import EmbedFrameS from "metabase/public/components/EmbedFrame/EmbedFrame.module.css";import { resetErrorPage, setErrorPage } from "metabase/redux/app";import { dismissAllUndo } from "metabase/redux/undo";@@ -123,7 +127,8 @@ export type SdkDashboardInnerProps = SdkDashboardProps &>;const SdkDashboardInner = ({- dashboardId,+ dashboardId: rawDashboardId,+ token: rawToken,initialParameters = {},withTitle = true,withCardTitle = true,@@ -149,6 +154,24 @@ const SdkDashboardInner = ({dataPickerProps,onVisualizationChange,}: SdkDashboardInnerProps) => {+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);++ const {+ resourceId: dashboardId,+ token,+ tokenError,+ } = useExtractResourceIdFromJwtToken({+ isGuestEmbed,+ resourceId: rawDashboardId,+ token: rawToken ?? undefined,+ });++ useEffect(() => {+ if (isGuestEmbed && token) {+ PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);+ }+ }, [isGuestEmbed, token]);+const { handleLoad, handleLoadWithoutCards } = useDashboardLoadHandlers({onLoad,onLoadWithoutCards,@@ -158,12 +181,10 @@ const SdkDashboardInner = ({const { isBreadcrumbEnabled, reportLocation } = useSdkBreadcrumbs();const { displayOptions } = useSdkDashboardParams({- dashboardId,withDownloads,withTitle,withCardTitle,hiddenParameters,- initialParameters,});const {@@ -236,6 +257,22 @@ const SdkDashboardInner = ({);}+ if (tokenError) {+ return (+ <SdkDashboardStyledWrapper className={className} style={style}>+ <SdkError message={tokenError} />;+ </SdkDashboardStyledWrapper>+ );+ }++ if (isStaticEmbeddingEntityLoadingError(errorPage, { isGuestEmbed })) {+ return (+ <SdkDashboardStyledWrapper className={className} style={style}>+ <SdkError message={errorPage.data ?? t`Something's gone wrong`} />+ </SdkDashboardStyledWrapper>+ );+ }+// Passing an invalid entity ID format results in a 400 Bad Request.// We can show this as a generic "not found" error on the frontend.const isDashboardNotFound =@@ -244,7 +281,7 @@ const SdkDashboardInner = ({if (!dashboardId || isDashboardNotFound) {return (<SdkDashboardStyledWrapper className={className} style={style}>- <DashboardNotFoundError id={dashboardId} />+ <DashboardNotFoundError id={dashboardId ?? ""} /></SdkDashboardStyledWrapper>);}@@ -263,6 +300,8 @@ const SdkDashboardInner = ({<DashboardContextProviderref={dashboardContextProviderRef}dashboardId={dashboardId}+ token={token}+ isGuestEmbed={isGuestEmbed}parameterQueryParams={initialParameters}navigateToNewCardFromDashboard={navigateToNewCardFromDashboard !== undefined@@ -313,8 +352,8 @@ const SdkDashboardInner = ({}}autoScrollToDashcardId={autoScrollToDashcardId}>- {match(finalRenderMode)- .with("question", () => (+ {match({ finalRenderMode, isGuestEmbed })+ .with({ finalRenderMode: "question" }, () => (<SdkDashboardStyledWrapperWithRef className={className} style={style}><SdkAdHocQuestion// `adhocQuestionUrl` would have value if renderMode is "question"@@ -327,7 +366,7 @@ const SdkDashboardInner = ({</SdkAdHocQuestion></SdkDashboardStyledWrapperWithRef>))- .with("dashboard", () => (+ .with({ finalRenderMode: "dashboard" }, () => (<SdkDashboardProviderplugins={plugins}onEditQuestion={onEditQuestion}@@ -342,29 +381,37 @@ const SdkDashboardInner = ({)}</SdkDashboardProvider>))- .with("queryBuilder", () => (- <DashboardQueryBuilder- onCreate={(question) => {- setNewDashboardQuestionId(question.id);- setRenderMode("dashboard");- dashboardContextProviderRef.current?.refetchDashboard();- }}- onNavigateBack={() => {- setRenderMode("dashboard");- }}- dataPickerProps={dataPickerProps}- onVisualizationChange={onVisualizationChange}- />- ))+ .with({ finalRenderMode: "queryBuilder" }, ({ isGuestEmbed }) =>+ isGuestEmbed ? (+ <SdkDashboardStyledWrapper className={className} style={style}>+ <SdkError+ message={t`You can't save questions in Guest Embed mode`}+ />+ </SdkDashboardStyledWrapper>+ ) : (+ <DashboardQueryBuilder+ onCreate={(question) => {+ setNewDashboardQuestionId(question.id);+ setRenderMode("dashboard");+ dashboardContextProviderRef.current?.refetchDashboard();+ }}+ onNavigateBack={() => {+ setRenderMode("dashboard");+ }}+ dataPickerProps={dataPickerProps}+ onVisualizationChange={onVisualizationChange}+ />+ ),+ ).exhaustive()}{modalContent}</DashboardContextProvider>);};-export const SdkDashboard = withPublicComponentWrapper(- SdkDashboardInner,-) as typeof SdkDashboardInner &+export const SdkDashboard = withPublicComponentWrapper(SdkDashboardInner, {+ supportsGuestEmbed: true,+}) as typeof SdkDashboardInner &Pick<typeof Dashboard,| "Grid"diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.schema.tsindex cb004907b71..3b5558a5c44 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.schema.ts@@ -7,7 +7,12 @@ import type { StaticDashboardProps } from "./StaticDashboard";const propsSchema: Yup.SchemaOf<StaticDashboardProps> = Yup.object({children: Yup.mixed().optional(),className: Yup.mixed().optional(),- dashboardId: Yup.mixed().required(),+ dashboardId: Yup.mixed().when("token", {+ is: (token: unknown) => token !== undefined,+ then: (schema) => schema.optional(),+ otherwise: (schema) => schema.required(),+ }),+ token: Yup.mixed().optional(),dataPickerProps: Yup.object({entityTypes: Yup.mixed().optional(),})diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsxindex 50b8ed17c78..9eb41050589 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx@@ -1,43 +1,54 @@+import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";+import type { SdkDashboardEntityPublicProps } from "embedding-sdk-bundle/types/dashboard";import { PublicOrEmbeddedDashCardMenu } from "metabase/dashboard/components/DashCard/PublicOrEmbeddedDashCardMenu";import { DASHBOARD_ACTION } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys";import { isQuestionCard } from "metabase/dashboard/utils";import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";+import { EmbeddingSdkStaticMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode";import type { ClickActionModeGetter } from "metabase/visualizations/types";-import { StaticQuestionSdkMode } from "../../StaticQuestion/mode";import { SdkDashboard, type SdkDashboardProps } from "../SdkDashboard";import { staticDashboardSchema } from "./StaticDashboard.schema";/**- * @interface* @expand* @category Dashboard*/export type StaticDashboardProps = Omit<SdkDashboardProps,+ | "dashboardId"+ | "token"| "drillThroughQuestionProps"| "drillThroughQuestionHeight"| "renderDrillThroughQuestion"->;+> &+ SdkDashboardEntityPublicProps;const StaticDashboardInner = (props: StaticDashboardProps) => {+ // Normalize props for Guest Embed usage (e.g. enforce withDownloads in OSS).+ const normalizedProps =+ useNormalizeGuestEmbedQuestionOrDashboardComponentProps(props);++ const { withDownloads } = normalizedProps;+const getClickActionMode: ClickActionModeGetter = ({ question }) =>getEmbeddingMode({question,- queryMode: StaticQuestionSdkMode,+ queryMode: EmbeddingSdkStaticMode,});return (<SdkDashboard- {...props}+ {...(normalizedProps as SdkDashboardProps)}getClickActionMode={getClickActionMode}dashboardActions={({ downloadsEnabled }) =>downloadsEnabled.pdf ? [DASHBOARD_ACTION.DOWNLOAD_PDF] : []}navigateToNewCardFromDashboard={null}dashcardMenu={({ dashcard, result }) =>- props.withDownloads &&+ withDownloads &&isQuestionCard(dashcard.card) &&!!result?.data &&!result?.error && (@@ -48,6 +59,11 @@ const StaticDashboardInner = (props: StaticDashboardProps) => {);};-export const StaticDashboard = Object.assign(StaticDashboardInner, {- schema: staticDashboardSchema,-});+export const StaticDashboard = Object.assign(+ withPublicComponentWrapper(StaticDashboardInner, {+ supportsGuestEmbed: true,+ }),+ {+ schema: staticDashboardSchema,+ },+);diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.unit.spec.tsxindex b90604bcae9..5b9297f82f9 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.unit.spec.tsx@@ -1,6 +1,8 @@import userEvent from "@testing-library/user-event";+import type { ComponentType } from "react";import { screen, waitFor, within } from "__support__/ui";+import type { SdkDashboardProps } from "embedding-sdk-bundle/components/public/dashboard/SdkDashboard";import {type SetupSdkDashboardOptions,@@ -18,7 +20,7 @@ const setup = async () => {return setupSdkDashboard({...options,- component: StaticDashboard,+ component: StaticDashboard as ComponentType<SdkDashboardProps>,});};console.warn = () => {};diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsxindex b31f1c53415..f57b0ea03af 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx@@ -1,3 +1,4 @@+import type { ComponentType } from "react";import { indexBy } from "underscore";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";@@ -110,10 +111,10 @@ export const DEFAULT_DASHCARDS: DashboardCard[] = [];export interface SetupSdkDashboardOptions {- props?: Partial<SdkDashboardProps>;+ props?: Omit<Partial<SdkDashboardProps>, "token">;providerProps?: Partial<MetabaseProviderProps>;isLocaleLoading?: boolean;- component: React.ComponentType<SdkDashboardProps>;+ component: ComponentType<SdkDashboardProps>;dashboardName?: string;dataPickerProps?: EditableDashboardProps["dataPickerProps"];dashcards?: DashboardCard[];diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsxindex 5b11fe126eb..8012475aa30 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsx@@ -9,6 +9,7 @@ import {import { getNewCardUrl } from "metabase/dashboard/actions/getNewCardUrl";import type { NavigateToNewCardFromDashboardOpts } from "metabase/dashboard/components/DashCard/types";import * as Urls from "metabase/lib/urls";+import { isJWT } from "metabase/lib/utils";import { navigateBackToDashboard } from "metabase/query_builder/actions";import { getMetadata } from "metabase/selectors/metadata";import type Question from "metabase-lib/v1/Question";@@ -126,7 +127,7 @@ const findDashboardById = (dashboardId: DashboardId,dashboards: Record<DashboardId, StoreDashboard>,): StoreDashboard | null => {- if (typeof dashboardId === "number") {+ if (typeof dashboardId === "number" || isJWT(dashboardId)) {return dashboards[dashboardId] ?? null;}diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.tsnew file mode 100644index 00000000000..bd51729b5e5--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.ts@@ -0,0 +1,72 @@+import { useMemo } from "react";+import { t } from "ttag";++import type { SdkEntityToken } from "embedding-sdk-bundle/types";+import { extractResourceIdFromJwtToken, isJWT } from "metabase/lib/utils";++export const useExtractResourceIdFromJwtToken = <TEntityId>({+ isGuestEmbed,+ resourceId,+ token,+}: {+ isGuestEmbed: boolean;+ resourceId: TEntityId | undefined;+ token: SdkEntityToken | undefined;+}): {+ resourceId: TEntityId | null;+ token: SdkEntityToken | null;+ tokenError?: string;+} => {+ return useMemo<{+ resourceId: TEntityId | null;+ token: SdkEntityToken | null;+ }>(() => {+ if (isJWT(resourceId)) {+ return {+ resourceId: null,+ token: null,+ tokenError: t`JWT tokens cannot be passed as id. Use the token prop instead.`,+ };+ }++ if (isGuestEmbed && resourceId) {+ return {+ resourceId: null,+ token: null,+ tokenError: t`A valid JWT token is required to be passed in guest embeds mode.`,+ };+ }++ if (token) {+ if (!isGuestEmbed) {+ return {+ resourceId: null,+ token: null,+ tokenError: t`Passing a token is only allowed for guest embeds mode.`,+ };+ }++ if (!isJWT(token)) {+ return {+ resourceId: null,+ token: null,+ tokenError: t`Passed token is not a valid JWT token.`,+ };+ }++ return { resourceId: extractResourceIdFromJwtToken(token), token };+ }++ if (resourceId) {+ return {+ resourceId,+ token: null,+ };+ }++ return {+ resourceId: null,+ token: null,+ };+ }, [resourceId, isGuestEmbed, token]);+};diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.tsindex 7e95e870680..1985f53d9b3 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts@@ -3,6 +3,7 @@ import { useMount } from "react-use";import _ from "underscore";import { initAuth } from "embedding-sdk-bundle/store/auth";+import { initGuestEmbed } from "embedding-sdk-bundle/store/guest-embed";import {setFetchRefreshTokenFn,setMetabaseClientUrl,@@ -23,6 +24,7 @@ const registerVisualizationsOnce = _.once(registerVisualizations);interface InitDataLoaderParameters {reduxStore: SdkStore;+ isGuestEmbed?: boolean;authConfig: MetabaseAuthConfig;isLocalHost?: boolean;}@@ -41,23 +43,28 @@ export const useInitData = () => {);}+ const isGuestEmbed = !!props.authConfig.isGuest;+useInitDataInternal({reduxStore,+ isGuestEmbed,authConfig,});};export const useInitDataInternal = ({reduxStore,+ isGuestEmbed,authConfig,isLocalHost,}: InitDataLoaderParameters) => {const dispatch = reduxStore.dispatch;- const isAuthUninitialized = () =>- reduxStore.getState().sdk.loginStatus.status === "uninitialized";+ const isDataUninitialized = () =>+ reduxStore.getState().sdk.initStatus.status === "uninitialized";const fetchRefreshTokenFnFromStore = useLazySelector(getFetchRefreshTokenFn);+const sdkPackageVersion =getBuildInfo("METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO").version ?? null;@@ -99,7 +106,13 @@ export const useInitDataInternal = ({}, [authConfig.fetchRequestToken, fetchRefreshTokenFnFromStore, dispatch]);useMount(function initializeData() {- if (isAuthUninitialized()) {+ if (!isDataUninitialized()) {+ return;+ }++ if (isGuestEmbed) {+ dispatch(initGuestEmbed());+ } else {dispatch(initAuth({ ...authConfig, isLocalHost }));}});diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.tsindex e9053c85e06..beed4643d32 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts@@ -7,13 +7,16 @@ import {runQuestionQuerySdk,updateQuestionSdk,} from "embedding-sdk-bundle/lib/sdk-question";-import { useSdkDispatch } from "embedding-sdk-bundle/store";+import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";+import { setError } from "embedding-sdk-bundle/store/reducer";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";import type {LoadSdkQuestionParams,NavigateToNewCardParams,SdkQuestionState,SqlParameterValues,} from "embedding-sdk-bundle/types/question";+import { isStaticEmbeddingEntityLoadingError } from "metabase/lib/errors/is-static-embedding-entity-loading-error";import { type Deferred, defer } from "metabase/lib/promise";import type Question from "metabase-lib/v1/Question";import type { ParameterValuesMap } from "metabase-types/api";@@ -54,14 +57,20 @@ export interface LoadQuestionHookResult {| null;}+type UseLoadQuestionParams = LoadSdkQuestionParams & {+ isGuestEmbed: boolean;+ token: string | null | undefined;+};+export function useLoadQuestion({questionId,+ token,options,// Passed when navigating from `InteractiveDashboard` or `EditableDashboard`deserializedCard,initialSqlParameters,targetDashboardId,-}: LoadSdkQuestionParams): LoadQuestionHookResult {+}: UseLoadQuestionParams): LoadQuestionHookResult {const dispatch = useSdkDispatch();// Keep track of the latest question and query results.@@ -70,6 +79,8 @@ export function useLoadQuestion({const { question, originalQuestion, queryResults, parameterValues } =questionState;+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);+const deferredRef = useRef<Deferred>();function deferred() {@@ -96,12 +107,14 @@ export function useLoadQuestion({if (shouldLoadQuestion) {setIsQuestionLoading(true);}+try {const questionState = await dispatch(loadQuestionSdk({options,deserializedCard,questionId,+ token,initialSqlParameters,targetDashboardId,}),@@ -111,7 +124,10 @@ export function useLoadQuestion({const results = await runQuestionQuerySdk({question: questionState.question,+ isGuestEmbed,+ token,originalQuestion: questionState.originalQuestion,+ parameterValues: questionState.parameterValues,cancelDeferred: deferred(),});@@ -126,6 +142,15 @@ export function useLoadQuestion({return {};}+ if (isStaticEmbeddingEntityLoadingError(err, { isGuestEmbed })) {+ dispatch(+ setError({+ status: err.status,+ message: err.data,+ }),+ );+ }+mergeQuestionState({question: undefined,originalQuestion: undefined,@@ -140,8 +165,10 @@ export function useLoadQuestion({dispatch,options,deserializedCard,- questionId,+ isGuestEmbed,sqlParameterKey,+ questionId,+ token,targetDashboardId,]);@@ -152,14 +179,24 @@ export function useLoadQuestion({const state = await runQuestionQuerySdk({question,+ isGuestEmbed,+ token,originalQuestion,+ parameterValues,cancelDeferred: deferred(),});mergeQuestionState(state);return state.question;- }, [dispatch, question, originalQuestion]);+ }, [+ dispatch,+ question,+ isGuestEmbed,+ token,+ originalQuestion,+ parameterValues,+ ]);const [updateQuestionState, updateQuestion] = useAsyncFn(async (nextQuestion: Question, options: { run?: boolean }) => {@@ -180,12 +217,21 @@ export function useLoadQuestion({mergeQuestionState({ question }),shouldRunQueryOnQuestionChange: run,shouldStartAdHocQuestion: true,+ isGuestEmbed,+ token,}),);mergeQuestionState(state);},- [dispatch, question, originalQuestion, parameterValues],+ [+ dispatch,+ question,+ originalQuestion,+ parameterValues,+ isGuestEmbed,+ token,+ ],);const [updateParameterValuesState, updateParameterValues] = useAsyncFn(@@ -209,12 +255,21 @@ export function useLoadQuestion({mergeQuestionState({ question }),shouldRunQueryOnQuestionChange: true,shouldStartAdHocQuestion: false,+ isGuestEmbed,+ token,}),);mergeQuestionState(state);},- [dispatch, question, originalQuestion, parameterValues],+ [+ dispatch,+ question,+ originalQuestion,+ parameterValues,+ isGuestEmbed,+ token,+ ],);const [navigateToNewCardState, navigateToNewCard] = useAsyncFn(@@ -222,7 +277,10 @@ export function useLoadQuestion({const state = await dispatch(runQuestionOnNavigateSdk({...params,+ isGuestEmbed,+ token,originalQuestion,+ parameterValues,cancelDeferred: deferred(),onQuestionChange: (question) => mergeQuestionState({ question }),onClearQueryResults: () =>@@ -235,7 +293,7 @@ export function useLoadQuestion({mergeQuestionState(state);},- [dispatch, originalQuestion],+ [dispatch, originalQuestion, isGuestEmbed, token, parameterValues],);const isQueryRunning =diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.tsnew file mode 100644index 00000000000..6aee0a8b238--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.ts@@ -0,0 +1,17 @@+import type { ComponentProviderProps } from "embedding-sdk-bundle/components/public/ComponentProvider";+import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";++export const useNormalizeComponentProviderProps = (+ props: Omit<ComponentProviderProps, "children">,+): Omit<ComponentProviderProps, "children"> => {+ const isEmbeddingSdkFeatureEnabled = PLUGIN_EMBEDDING_SDK.isEnabled();+ const normalizedProps = { ...props };++ // For OSS usage we prevent defining a locale or theme+ if (!isEmbeddingSdkFeatureEnabled) {+ delete props.locale;+ delete props.theme;+ }++ return normalizedProps;+};diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props.tsnew file mode 100644index 00000000000..66c201e2aa2--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props.ts@@ -0,0 +1,22 @@+import type { StaticQuestionProps } from "embedding-sdk-bundle/components/public/StaticQuestion";+import type { StaticDashboardProps } from "embedding-sdk-bundle/components/public/dashboard";+import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getHasTokenFeature } from "embedding-sdk-bundle/store/selectors";++export const useNormalizeGuestEmbedQuestionOrDashboardComponentProps = <+ TProps extends StaticDashboardProps | StaticQuestionProps,+>(+ props: TProps,+): TProps => {+ const hasTokenFeature = useSdkSelector(getHasTokenFeature);++ if (hasTokenFeature) {+ return props;+ }++ return {+ ...props,+ // For OSS usage we force downloads+ withDownloads: true,+ };+};diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.tsindex 056a273af89..2856ab608ff 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params.ts@@ -1,5 +1,6 @@import { pick } from "underscore";+import type { SdkEntityToken } from "embedding-sdk-bundle/types";import type { SdkDashboardId } from "embedding-sdk-bundle/types/dashboard";import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";import { DEFAULT_DASHBOARD_DISPLAY_OPTIONS } from "metabase/dashboard/constants";@@ -7,18 +8,15 @@ import type { EmbedDisplayParams } from "metabase/dashboard/types";import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";import { isNotNull } from "metabase/lib/types";-export type SdkDashboardDisplayProps = {- /**- * The ID of the dashboard.- * <br/>- * This is either:- * <br/>- * - the numerical ID when accessing a dashboard link, i.e. `http://localhost:3000/dashboard/1-my-dashboard` where the ID is `1`- * <br/>- * - the string ID found in the `entity_id` key of the dashboard object when using the API directly or using the SDK Collection Browser to return data- */- dashboardId: SdkDashboardId;+/**+ * @inline+ */+export type SdkDashboardEntityInternalProps = {+ dashboardId?: SdkDashboardId | null;+ token?: SdkEntityToken | null;+};+export type SdkDashboardDisplayProps = SdkDashboardEntityInternalProps & {/*** Query parameters for the dashboard. For a single option, use a `string` value, and use a list of strings for multiple options.* <br/>@@ -58,7 +56,10 @@ export const useSdkDashboardParams = ({withTitle,withCardTitle,hiddenParameters,-}: SdkDashboardDisplayProps) => {+}: Pick<+ SdkDashboardDisplayProps,+ "withDownloads" | "withTitle" | "withCardTitle" | "hiddenParameters"+>) => {// temporary name until we change `hideDownloadButton` to `downloads`const hideDownloadButton = !withDownloads;diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.tsindex 92bef0182c3..5329658961d 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.ts@@ -4,6 +4,10 @@ import { printUsageProblemToConsole } from "embedding-sdk-bundle/lib/print-usageimport { getSdkUsageProblem } from "embedding-sdk-bundle/lib/usage-problem";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";import { setUsageProblem } from "embedding-sdk-bundle/store/reducer";+import {+ getHasTokenFeature,+ getIsGuestEmbedRaw,+} from "embedding-sdk-bundle/store/selectors";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";import { useSetting } from "metabase/common/hooks";import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";@@ -21,6 +25,8 @@ export function useSdkUsageProblem({session: MetabaseEmbeddingSessionToken | null;isLocalHost?: boolean;}) {+ const isGuestEmbed = useSdkSelector(getIsGuestEmbedRaw);+const hasLoggedRef = useRef(false);const dispatch = useSdkDispatch();@@ -31,15 +37,7 @@ export function useSdkUsageProblem({const isEnabled =useSetting(EMBEDDING_SDK_CONFIG.enableEmbeddingSettingKey) ?? true;- const hasTokenFeature = useSdkSelector((state) => {- // We also assume that the feature is enabled if the token-features are missing.- // Same reason as above.- if (!state.settings.values?.["token-features"]) {- return true;- }-- return getTokenFeature(state, EMBEDDING_SDK_CONFIG.tokenFeatureKey);- });+ const hasTokenFeature = useSdkSelector(getHasTokenFeature);const isDevelopmentMode = useSdkSelector((state) => {// Assume that we are not in development mode until the setting is loaded@@ -52,6 +50,7 @@ export function useSdkUsageProblem({const usageProblem = useMemo(() => {return getSdkUsageProblem({+ isGuestEmbed,authConfig,hasTokenFeature,isEnabled,@@ -60,6 +59,7 @@ export function useSdkUsageProblem({isLocalHost,});}, [+ isGuestEmbed,authConfig,hasTokenFeature,isEnabled,diff --git a/frontend/src/embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters.ts b/frontend/src/embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters.tsnew file mode 100644index 00000000000..4f3c1cd842b--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters.ts@@ -0,0 +1,17 @@+import type Question from "metabase-lib/v1/Question";+import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";+import type { ParameterValuesMap } from "metabase-types/api";++export const getGuestEmbedFilteredParameters = (+ question: Question,+ parameterValues: ParameterValuesMap | undefined,+) => {+ const parameters = getParameterValuesBySlug(+ question.card().parameters,+ parameterValues,+ );++ return Object.fromEntries(+ Object.entries(parameters).filter(([_key, value]) => value !== null),+ );+};diff --git a/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.ts b/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.tsnew file mode 100644index 00000000000..42f2b78986f--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.ts@@ -0,0 +1,186 @@+import { sessionPropertiesPath } from "metabase/api";+import {+ PLUGIN_CONTENT_TRANSLATION,+ PLUGIN_EMBEDDING_SDK,+} from "metabase/plugins";+import { embedBase, internalBase } from "metabase/services";++const getIgnoreOverridePatterns = () => [+ sessionPropertiesPath,+ PLUGIN_CONTENT_TRANSLATION.getDictionaryBasePath,+];++/**+ * URL patterns used for matching and transforming API requests in Guest Embed mode.+ * These patterns are needed only for endpoints that have different parameter names/path/structure for `/embed`+ */+const URL_PATTERNS = {+ CARD_QUERY: `${internalBase}/card/:cardId/query`,+ CARD_PIVOT_QUERY: `${internalBase}/card/pivot/:cardId/query`,+ CARD_PARAMETER_VALUES: `${internalBase}/card/:cardId/params/:paramId/values`,+ CARD_PARAMETER_SEARCH: `${internalBase}/card/:cardId/params/:paramId/search/:query`,+ CARD_PARAMETER_REMAPPING: `${internalBase}/card/:cardId/params/:paramId/remapping`,+ DASHBOARD_PARAMETER_VALUES: `${internalBase}/dashboard/:dashId/params/:paramId/values`,+ DASHBOARD_PARAMETER_SEARCH: `${internalBase}/dashboard/:dashId/params/:paramId/search/:query`,+ DASHBOARD_PARAMETER_REMAPPING: `${internalBase}/dashboard/:dashId/params/:paramId/remapping`,+} as const;++/**+ * Mapping of API endpoints to their Guest Embed equivalents.+ * Each transformation specifies the embed URL and HTTP method to use.+ */+const EMBED_URL_TRANSFORMATIONS: Record<+ string,+ { url: string; method: "GET" | "POST" }+> = {+ [URL_PATTERNS.CARD_QUERY]: {+ url: `${embedBase}/card/:token/query`,+ method: "GET",+ },+ [URL_PATTERNS.CARD_PIVOT_QUERY]: {+ url: `${embedBase}/pivot/card/:token/query`,+ method: "GET",+ },+ [URL_PATTERNS.CARD_PARAMETER_VALUES]: {+ url: `${embedBase}/card/:token/params/:paramId/values`,+ method: "GET",+ },+ [URL_PATTERNS.CARD_PARAMETER_SEARCH]: {+ url: `${embedBase}/card/:token/params/:paramId/search/:query`,+ method: "GET",+ },+ [URL_PATTERNS.CARD_PARAMETER_REMAPPING]: {+ url: `${embedBase}/card/:token/params/:paramId/remapping`,+ method: "GET",+ },+ [URL_PATTERNS.DASHBOARD_PARAMETER_VALUES]: {+ url: `${embedBase}/dashboard/:token/params/:paramId/values`,+ method: "GET",+ },+ [URL_PATTERNS.DASHBOARD_PARAMETER_SEARCH]: {+ url: `${embedBase}/dashboard/:token/params/:paramId/search/:query`,+ method: "GET",+ },+ [URL_PATTERNS.DASHBOARD_PARAMETER_REMAPPING]: {+ url: `${embedBase}/dashboard/:token/params/:paramId/remapping`,+ method: "GET",+ },+} as const;++type RequestData = {+ method: "GET" | "POST";+ url: string;+ options: {+ headers?: Record<string, string>;+ hasBody: boolean;+ } & Record<string, unknown>;+};++/**+ * Converts a URL pattern with parameters (e.g., "/api/card/:id/query")+ * into a regular expression that can match actual URLs.+ *+ * @example+ * matchUrlPattern("/api/card/:id/query", "/api/card/123/query") // returns true+ * matchUrlPattern("/api/card/:id/query", "/api/card/123/edit") // returns false+ */+export function matchUrlPattern(pattern: string, url: string): boolean {+ const regexString = pattern+ .replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")+ .replace(/:([a-zA-Z0-9_]+)/g, "([^/]+)");++ const regex = new RegExp(`^${regexString}$`);++ return regex.test(url);+}++/**+ * Finds the URL pattern that matches the given URL.+ */+function findMatchingPattern(url: string): string | null {+ for (const pattern of Object.values(URL_PATTERNS)) {+ if (matchUrlPattern(pattern, url)) {+ return pattern;+ }+ }+ return null;+}++/**+ * Determines the appropriate request transformation for a given URL.+ * Returns null if no transformation is needed.+ */+function getRequestTransformation({+ method,+ url,+ options,+}: RequestData): RequestData | null {+ const matchedPattern = findMatchingPattern(url);++ if (+ getIgnoreOverridePatterns().some(+ (endpoint) => endpoint && url.includes(endpoint),+ )+ ) {+ return null;+ }++ // No transformation needed if pattern doesn't match+ if (!matchedPattern) {+ return { method, url, options };+ }++ // Apply the transformation for this pattern+ const transformation = EMBED_URL_TRANSFORMATIONS[matchedPattern];+ if (!transformation) {+ return { method, url, options };+ }++ return {+ ...transformation,+ options: {+ ...options,+ hasBody: transformation.method === "POST",+ },+ };+}++/**+ * Replaces the standard API base path with the embed API base path.+ */+function replaceWithEmbedBase(url: string): string {+ if (url.includes(internalBase) && !url.includes(embedBase)) {+ return url.replace(internalBase, embedBase);+ }+ return url;+}++/**+ * Registers a request interceptor that transforms standard API requests+ * into guest embeds API requests.+ */+export const overrideRequestsForGuestEmbeds = () => {+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds =+ async ({ method, url, options }) => {+ const transformation = getRequestTransformation({ method, url, options });++ if (!transformation) {+ return { method, url, options };+ }++ if (!options.headers) {+ options.headers = {};+ }++ /**+ * Set header to indicate that this request is for guest embed.+ */+ options.headers["x-metabase-guest-embed"] = "true";++ return {+ method: transformation.method,+ url: replaceWithEmbedBase(transformation.url),+ options: transformation.options,+ };+ };+};diff --git a/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.unit.spec.tsnew file mode 100644index 00000000000..8eb3f505c1b--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.unit.spec.ts@@ -0,0 +1,93 @@+import { matchUrlPattern } from "./override-requests-for-guest-embeds";++describe("matchUrlPattern", () => {+ it("should match URL with single parameter", () => {+ expect(+ matchUrlPattern("/api/card/:cardId/query", "/api/card/123/query"),+ ).toBe(true);+ });++ it("should not match URL with different path structure", () => {+ expect(+ matchUrlPattern("/api/card/:cardId/query", "/api/card/123/edit"),+ ).toBe(false);+ });++ it("should match URL with multiple parameters", () => {+ expect(+ matchUrlPattern(+ "/api/card/:cardId/params/:paramId/values",+ "/api/card/123/params/456/values",+ ),+ ).toBe(true);+ });++ it("should match card query pattern", () => {+ expect(+ matchUrlPattern("/api/card/:cardId/query", "/api/card/1/query"),+ ).toBe(true);+ });++ it("should match card pivot query pattern", () => {+ expect(+ matchUrlPattern(+ "/api/card/pivot/:cardId/query",+ "/api/card/pivot/123/query",+ ),+ ).toBe(true);+ });++ it("should match card parameter values pattern", () => {+ expect(+ matchUrlPattern(+ "/api/card/:cardId/params/:paramId/values",+ "/api/card/123/params/456/values",+ ),+ ).toBe(true);+ });++ it("should match card parameter search pattern", () => {+ expect(+ matchUrlPattern(+ "/api/card/:cardId/params/:paramId/search/:query",+ "/api/card/123/params/456/search/test",+ ),+ ).toBe(true);+ });++ it("should match card parameter remapping pattern", () => {+ expect(+ matchUrlPattern(+ "/api/card/:cardId/params/:paramId/remapping",+ "/api/card/123/params/456/remapping",+ ),+ ).toBe(true);+ });++ it("should match dashboard parameter values pattern", () => {+ expect(+ matchUrlPattern(+ "/api/dashboard/:dashId/params/:paramId/values",+ "/api/dashboard/789/params/456/values",+ ),+ ).toBe(true);+ });++ it("should match dashboard parameter search pattern", () => {+ expect(+ matchUrlPattern(+ "/api/dashboard/:dashId/params/:paramId/search/:query",+ "/api/dashboard/789/params/456/search/test",+ ),+ ).toBe(true);+ });++ it("should match dashboard parameter remapping pattern", () => {+ expect(+ matchUrlPattern(+ "/api/dashboard/:dashId/params/:paramId/remapping",+ "/api/dashboard/789/params/456/remapping",+ ),+ ).toBe(true);+ });+});diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.tsindex 307903aa991..e3d68e2f5d9 100644--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts@@ -1,5 +1,10 @@import _ from "underscore";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";+import type {+ SdkDispatch,+ SdkStoreState,+} from "embedding-sdk-bundle/store/types";import type {LoadSdkQuestionParams,SdkQuestionState,@@ -9,28 +14,35 @@ import { getParameterValuesForQuestion } from "metabase/query_builder/actions/coimport { loadMetadataForCard } from "metabase/questions/actions";import { getMetadata } from "metabase/selectors/metadata";import Question from "metabase-lib/v1/Question";-import type { Dispatch, GetState } from "metabase-types/store";++type LoadQuestionSdkParams = LoadSdkQuestionParams & {+ token: string | null | undefined;+};export const loadQuestionSdk =({options = {},deserializedCard,questionId: initQuestionId,+ token,initialSqlParameters,targetDashboardId,- }: LoadSdkQuestionParams) =>+ }: LoadQuestionSdkParams) =>async (- dispatch: Dispatch,- getState: GetState,+ dispatch: SdkDispatch,+ getState: () => SdkStoreState,): Promise<Required<Pick<SdkQuestionState, "question">> &Pick<SdkQuestionState, "originalQuestion" | "parameterValues">> => {+ const isGuestEmbed = getIsGuestEmbed(getState());+const isNewQuestion = initQuestionId === "new";const questionId = isNewQuestion ? undefined : initQuestionId;const { card: resolvedCard, originalCard } = await resolveCards({cardId: questionId ?? undefined,+ token,options,dispatch,getState,@@ -41,7 +53,11 @@ export const loadQuestionSdk =? { ...resolvedCard, creationType: "custom_question" }: resolvedCard;- await dispatch(loadMetadataForCard(card));+ if (!isGuestEmbed) {+ // We don't have a `metadata` endpoint for static/guest embeds+ await dispatch(loadMetadataForCard(card, { token }));+ }+const metadata = getMetadata(getState());const originalQuestion =@@ -52,7 +68,11 @@ export const loadQuestionSdk =question = question.setDashboardId(targetDashboardId);}- question = question.applyTemplateTagParameters();+ // In Legacy Static Embedding we didn't have this logic,+ // it breaks behavior when a parameter is disabled.+ if (!isGuestEmbed) {+ question = question.applyTemplateTagParameters();+ }const queryParams = initialSqlParameters? _.mapObject(initialSqlParameters, String)diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.tsindex 367f986ab23..614ae1a56d0 100644--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts@@ -9,10 +9,14 @@ import { getMetadata } from "metabase/selectors/metadata";import { getCardAfterVisualizationClick } from "metabase/visualizations/lib/utils";import Question from "metabase-lib/v1/Question";import { cardIsEquivalent } from "metabase-lib/v1/queries/utils/card";+import type { ParameterValuesMap } from "metabase-types/api";import type { Dispatch, GetState } from "metabase-types/store";interface RunQuestionOnNavigateParams extends NavigateToNewCardParams {originalQuestion?: Question;+ parameterValues?: ParameterValuesMap;+ isGuestEmbed: boolean;+ token: string | null | undefined;onQuestionChange: (question: Question) => void;onClearQueryResults: () => void;}@@ -24,9 +28,12 @@ export const runQuestionOnNavigateSdk =getState: GetState,): Promise<SdkQuestionState | null> => {let {+ isGuestEmbed,+ token,nextCard,previousCard,originalQuestion,+ parameterValues,cancelDeferred,onQuestionChange,onClearQueryResults,@@ -39,7 +46,10 @@ export const runQuestionOnNavigateSdk =// Fallback when a visualization legend is clickedif (cardIsEquivalent(previousCard, nextCard)) {- nextCard = await loadCard(nextCard.id, { dispatch, getState });+ nextCard = await loadCard(+ { cardId: nextCard.id },+ { dispatch, getState },+ );} else {nextCard = getCardAfterVisualizationClick(nextCard, previousCard);onClearQueryResults();@@ -48,12 +58,15 @@ export const runQuestionOnNavigateSdk =// Optimistic update the UI before we re-fetch the query metadata.onQuestionChange(new Question(nextCard, getMetadata(getState())));- await dispatch(loadMetadataForCard(nextCard));+ await dispatch(loadMetadataForCard(nextCard, { token }));const state = await runQuestionQuerySdk({question: new Question(nextCard, getMetadata(getState())),originalQuestion,+ parameterValues,cancelDeferred,+ isGuestEmbed,+ token,});return state as SdkQuestionState;diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.tsindex d25067a69b8..b9c322a68f3 100644--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts@@ -1,20 +1,32 @@+import { getGuestEmbedFilteredParameters } from "embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters";import type { SdkQuestionState } from "embedding-sdk-bundle/types/question";import type { Deferred } from "metabase/lib/promise";import { runQuestionQuery } from "metabase/services";import { getSensibleDisplays } from "metabase/visualizations";import * as Lib from "metabase-lib";import type Question from "metabase-lib/v1/Question";+import type { ParameterValuesMap } from "metabase-types/api";interface RunQuestionQueryParams {question: Question;+ isGuestEmbed: boolean;+ token: string | null | undefined;originalQuestion?: Question;+ parameterValues?: ParameterValuesMap;cancelDeferred?: Deferred;}export async function runQuestionQuerySdk(params: RunQuestionQueryParams,): Promise<SdkQuestionState> {- let { question, originalQuestion, cancelDeferred } = params;+ let {+ question,+ isGuestEmbed,+ token,+ originalQuestion,+ parameterValues,+ cancelDeferred,+ } = params;if (question.isSaved()) {const type = question.type();@@ -30,14 +42,28 @@ export async function runQuestionQuerySdk(let queryResults;- if (shouldRunCardQuery(question)) {+ if (shouldRunCardQuery({ question, isGuestEmbed })) {+ const filteredParameters = getGuestEmbedFilteredParameters(+ question,+ parameterValues,+ );+queryResults = await runQuestionQuery(question, {cancelDeferred,ignoreCache: false,isDirty: isQueryDirty,+ token,+ ...(isGuestEmbed && {+ queryParamsOverride: {+ parameters: JSON.stringify(filteredParameters),+ },+ }),});- const [{ data }] = queryResults;+ // Default values for rows/cols are needed because the `data` is missing in the case of Guest Embed+ const [{ data = isGuestEmbed ? { rows: [], cols: [] } : undefined }] =+ queryResults;+const sensibleDisplays = getSensibleDisplays(data);question = question.maybeResetDisplay(data, sensibleDisplays, undefined);}@@ -50,7 +76,19 @@ export async function runQuestionQuerySdk(return { question, queryResults };}-export function shouldRunCardQuery(question: Question): boolean {+export function shouldRunCardQuery({+ question,+ isGuestEmbed,+}: {+ question: Question;+ isGuestEmbed: boolean | null;+}): boolean {+ // Questions fetched from `/api/embed/*` endpoints have some fields missing, and it forces the this.legacyNativeQuery().canRun() to return `false`+ // To avoid it we just force-return true+ if (isGuestEmbed) {+ return true;+ }+const query = question.query();const { isNative } = Lib.queryDisplayInfo(query);diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.tsindex 0781a99e8bc..0d354645d9c 100644--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts@@ -34,6 +34,8 @@ interface UpdateQuestionParams {queryResults?: any[];cancelDeferred?: Deferred;+ isGuestEmbed: boolean;+ token: string | null | undefined;/** Optimistic update the question in the query builder UI */optimisticUpdateQuestion: (question: Question) => void;@@ -55,6 +57,8 @@ export const updateQuestionSdk =queryResults,optimisticUpdateQuestion: onQuestionChange,shouldRunQueryOnQuestionChange = false,+ isGuestEmbed,+ token,} = params;nextQuestion = getAdHocQuestionWithVizSettings({@@ -63,7 +67,7 @@ export const updateQuestionSdk =shouldStartAdHocQuestion,});- if (!nextQuestion.canAutoRun()) {+ if (!isGuestEmbed && !nextQuestion.canAutoRun()) {shouldRunQueryOnQuestionChange = false;}@@ -107,7 +111,7 @@ export const updateQuestionSdk =);if (!_.isEqual(currentDependencies, nextDependencies)) {- await dispatch(loadMetadataForCard(nextQuestion.card()));+ await dispatch(loadMetadataForCard(nextQuestion.card(), { token }));}const metadata = getMetadata(getState());@@ -122,7 +126,10 @@ export const updateQuestionSdk =if (shouldRunQueryOnQuestionChange) {return runQuestionQuerySdk({question: nextQuestion,+ isGuestEmbed,+ token,originalQuestion,+ parameterValues: nextParameterValues,cancelDeferred,});}diff --git a/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts b/frontend/src/embedding-sdk-bundle/lib/usage-problem.tsindex 2280c22dac6..c45ea865ec5 100644--- a/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts+++ b/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts@@ -13,6 +13,7 @@ import { getIsLocalhost } from "./get-is-localhost";interface SdkProblemOptions {authConfig: MetabaseAuthConfig;isEnabled: boolean;+ isGuestEmbed: boolean | null;hasTokenFeature: boolean;isDevelopmentMode?: boolean;session: MetabaseEmbeddingSessionToken | null;@@ -67,6 +68,7 @@ export function getSdkUsageProblem(): SdkUsageProblem | null {const {isEnabled,+ isGuestEmbed,hasTokenFeature,authConfig,isDevelopmentMode,@@ -83,6 +85,14 @@ export function getSdkUsageProblem(// in case of a local app running a distant MB instanceconst isLocalhost = isLocalHost ?? getIsLocalhost();+ if (isDevelopmentMode) {+ return toWarning("DEVELOPMENT_MODE_CLOUD_INSTANCE");+ }++ if (isGuestEmbed === null || isGuestEmbed) {+ return null;+ }+/*** TODO: these checks for non-localhost environments are pending on* the "allowing CORS for /api/session/properties" PR to be merged@@ -98,12 +108,8 @@ export function getSdkUsageProblem(isApiKey,isLocalhost,isEnabled,- isDevelopmentMode,session,})- .with({ isDevelopmentMode: true }, () =>- toWarning("DEVELOPMENT_MODE_CLOUD_INSTANCE"),- ).with({ isSSO: true, hasTokenFeature: false, isLocalhost: true }, () =>toError("SSO_WITHOUT_LICENSE"),)diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.tsnew file mode 100644index 00000000000..f9e6e35a519--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts@@ -0,0 +1,11 @@+import { overrideRequestsForGuestEmbeds } from "embedding-sdk-bundle/lib/override-requests-for-guest-embeds";+import { createAsyncThunk } from "metabase/lib/redux";+import { refreshSiteSettings } from "metabase/redux/settings";++export const initGuestEmbed = createAsyncThunk<void, undefined>(+ "sdk/token/INIT_GUEST_EMBED",+ async (_: any, { dispatch }) => {+ overrideRequestsForGuestEmbeds();+ await dispatch(refreshSiteSettings());+ },+);diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/index.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/index.tsnew file mode 100644index 00000000000..ee73c896209--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/index.ts@@ -0,0 +1 @@+export * from "./guest-embed";diff --git a/frontend/src/embedding-sdk-bundle/store/reducer.ts b/frontend/src/embedding-sdk-bundle/store/reducer.tsindex ec2571133e8..313e6f4e270 100644--- a/frontend/src/embedding-sdk-bundle/store/reducer.ts+++ b/frontend/src/embedding-sdk-bundle/store/reducer.ts@@ -11,6 +11,8 @@ import type { SdkUsageProblem } from "embedding-sdk-bundle/types/usage-problem";import type { MetabaseFetchRequestTokenFn } from "metabase/embedding-sdk/types/refresh-token";import { initAuth, refreshTokenAsync } from "./auth";+import { initGuestEmbed } from "./guest-embed";+const SET_IS_GUEST_EMBED = "sdk/SET_IS_GUEST_EMBED";const SET_METABASE_INSTANCE_VERSION = "sdk/SET_METABASE_INSTANCE_VERSION";const SET_METABASE_CLIENT_URL = "sdk/SET_METABASE_CLIENT_URL";const SET_LOADER_COMPONENT = "sdk/SET_LOADER_COMPONENT";@@ -18,6 +20,7 @@ const SET_ERROR_COMPONENT = "sdk/SET_ERROR_COMPONENT";const SET_ERROR = "sdk/SET_ERROR";const SET_FETCH_REQUEST_TOKEN_FN = "sdk/SET_FETCH_REQUEST_TOKEN_FN";+export const setIsGuestEmbed = createAction<boolean>(SET_IS_GUEST_EMBED);export const setMetabaseInstanceVersion = createAction<string>(SET_METABASE_INSTANCE_VERSION,);@@ -50,6 +53,7 @@ export const setUsageProblem = createAction<SdkUsageProblem | null>();const initialState: SdkState = {+ isGuestEmbed: null,metabaseInstanceUrl: "",metabaseInstanceVersion: null,token: {@@ -57,7 +61,7 @@ const initialState: SdkState = {loading: false,error: null,},- loginStatus: { status: "uninitialized" },+ initStatus: { status: "uninitialized" },error: null,plugins: null,eventHandlers: null,@@ -82,26 +86,43 @@ export const sdk = createReducer(initialState, (builder) => {builder.addCase(refreshTokenAsync.rejected, (state, action) => {const error = action.error as Error;- state.loginStatus = { status: "error", error };+ state.initStatus = { status: "error", error };});builder.addCase(initAuth.pending, (state) => {- state.loginStatus = { status: "loading" };+ state.initStatus = { status: "loading" };});builder.addCase(initAuth.fulfilled, (state) => {- state.loginStatus = { status: "success" };+ state.initStatus = { status: "success" };});builder.addCase(initAuth.rejected, (state, action) => {const error = action.error as Error;- state.loginStatus = { status: "error", error };+ state.initStatus = { status: "error", error };+ });++ builder.addCase(initGuestEmbed.pending, (state) => {+ state.initStatus = { status: "loading" };+ });++ builder.addCase(initGuestEmbed.fulfilled, (state) => {+ state.initStatus = { status: "success" };+ });++ builder.addCase(initGuestEmbed.rejected, (state, action) => {+ const error = action.error as Error;+ state.initStatus = { status: "error", error };});builder.addCase(setLoaderComponent, (state, action) => {state.loaderComponent = action.payload;});+ builder.addCase(setIsGuestEmbed, (state, action) => {+ state.isGuestEmbed = action.payload;+ });+builder.addCase(setPlugins, (state, action) => {// At the time of writing, doing `this.state.plugins = action.payload` causes// `Type instantiation is excessively deep and possibly infinite.` fordiff --git a/frontend/src/embedding-sdk-bundle/store/selectors.ts b/frontend/src/embedding-sdk-bundle/store/selectors.tsindex fe24885544a..219c7ebd754 100644--- a/frontend/src/embedding-sdk-bundle/store/selectors.ts+++ b/frontend/src/embedding-sdk-bundle/store/selectors.ts@@ -1,11 +1,21 @@import type { SdkStoreState } from "embedding-sdk-bundle/store/types";+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import { getSetting } from "metabase/selectors/settings";+import { getTokenFeature } from "metabase/setup";import type { State } from "metabase-types/store";-export const getLoginStatus = (state: SdkStoreState) => state.sdk?.loginStatus;+export const getIsGuestEmbedRaw = (state: SdkStoreState) =>+ state.sdk?.isGuestEmbed;++export const getIsGuestEmbed = (state: SdkStoreState) =>+ Boolean(state.sdk?.isGuestEmbed);++export const getInitStatus = (state: SdkStoreState) => state.sdk?.initStatus;++export const getLoginStatus = (state: SdkStoreState) => state.sdk?.initStatus;export const getIsInitialized = (state: SdkStoreState) =>- getLoginStatus(state).status !== "uninitialized";+ getInitStatus(state).status !== "uninitialized";export const getIsLoggedIn = (state: SdkStoreState) =>getLoginStatus(state).status === "success";@@ -38,3 +48,13 @@ export const getFetchRefreshTokenFn = (state: SdkStoreState) =>export const getAvailableFonts = (state: SdkStoreState) =>getSetting(state, "available-fonts");++export const getHasTokenFeature = (state: SdkStoreState) => {+ // When the setting haven't been loaded or failed to query, we assume that the+ // feature is _enabled_ first.+ if (!state.settings.values?.["token-features"]) {+ return true;+ }++ return getTokenFeature(state, EMBEDDING_SDK_CONFIG.tokenFeatureKey);+};diff --git a/frontend/src/embedding-sdk-bundle/store/types.ts b/frontend/src/embedding-sdk-bundle/store/types.tsindex 5bffa13cddc..d5417689b45 100644--- a/frontend/src/embedding-sdk-bundle/store/types.ts+++ b/frontend/src/embedding-sdk-bundle/store/types.ts@@ -11,11 +11,11 @@ import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config"import type { SdkEventHandlersConfig } from "embedding-sdk-bundle/types/events";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";import type {+ InitializationStatus,SdkErrorComponent,SdkLoadingError,} from "embedding-sdk-bundle/types/ui";import type { SdkUsageProblem } from "embedding-sdk-bundle/types/usage-problem";-import type { LoginStatus } from "embedding-sdk-bundle/types/user";import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";import type { State } from "metabase-types/store";@@ -32,10 +32,11 @@ export type SdkStore = Omit<Store<SdkStoreState, Action>, "dispatch"> & {export type SdkDispatch = ThunkDispatch<SdkStoreState, void, AnyAction>;export type SdkState = {+ isGuestEmbed: boolean | null;metabaseInstanceUrl: MetabaseAuthConfig["metabaseInstanceUrl"];metabaseInstanceVersion: string | null;token: EmbeddingSessionTokenState;- loginStatus: LoginStatus;+ initStatus: InitializationStatus;error: SdkLoadingError | null;plugins: null | MetabasePluginsConfig;eventHandlers: null | SdkEventHandlersConfig;diff --git a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts b/frontend/src/embedding-sdk-bundle/test/mocks/state.tsindex 911197dc9c2..6afde43256e 100644--- a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts+++ b/frontend/src/embedding-sdk-bundle/test/mocks/state.ts@@ -29,7 +29,8 @@ export const createMockSdkState = ({return {metabaseInstanceUrl: "",metabaseInstanceVersion: null,- loginStatus: createMockLoginStatusState(),+ isGuestEmbed: false,+ initStatus: createMockLoginStatusState(),token: createMockTokenState(),usageProblem: null,plugins: {},diff --git a/frontend/src/embedding-sdk-bundle/test/server-mocks/sdk-init.ts b/frontend/src/embedding-sdk-bundle/test/server-mocks/sdk-init.tsindex b356ebc165c..ced01360bdd 100644--- a/frontend/src/embedding-sdk-bundle/test/server-mocks/sdk-init.ts+++ b/frontend/src/embedding-sdk-bundle/test/server-mocks/sdk-init.ts@@ -31,7 +31,7 @@ export const setupSdkState = ({tokenFeatures = createMockTokenFeatures({ embedding_sdk: true }),settingDefinitions = [],sdkState = createMockSdkState({- loginStatus: createMockLoginStatusState({ status: "success" }),+ initStatus: createMockLoginStatusState({ status: "success" }),}),...stateOpts}: {diff --git a/frontend/src/embedding-sdk-bundle/types/auth-config.ts b/frontend/src/embedding-sdk-bundle/types/auth-config.tsindex a66ab81fb7d..edba7cacc70 100644--- a/frontend/src/embedding-sdk-bundle/types/auth-config.ts+++ b/frontend/src/embedding-sdk-bundle/types/auth-config.ts@@ -24,6 +24,7 @@ export type MetabaseAuthConfigWithJwt = BaseMetabaseAuthConfig & {*/fetchRequestToken?: MetabaseFetchRequestTokenFn;+ isGuest?: false;apiKey?: never;};@@ -37,6 +38,7 @@ export type MetabaseAuthConfigWithSaml = BaseMetabaseAuthConfig & {* it defaults to SAML unless the preferredAuthMethod is specified.*/preferredAuthMethod?: "saml";+ isGuest?: false;apiKey?: never;fetchRequestToken?: never;};@@ -46,6 +48,20 @@ export type MetabaseAuthConfigWithSaml = BaseMetabaseAuthConfig & {*/export type MetabaseAuthConfigWithApiKey = BaseMetabaseAuthConfig & {apiKey: string;+ isGuest?: false;+ preferredAuthMethod?: never;+ fetchRequestToken?: never;+};++/**+ * @category MetabaseProvider+ */+export type MetabaseIsGuestAuthConfig = BaseMetabaseAuthConfig & {+ /**+ * Defines if SDK should work in a Guest Embed mode+ */+ isGuest: true;+ apiKey?: never;preferredAuthMethod?: never;fetchRequestToken?: never;};@@ -56,7 +72,8 @@ export type MetabaseAuthConfigWithApiKey = BaseMetabaseAuthConfig & {export type MetabaseAuthConfig =| MetabaseAuthConfigWithApiKey| MetabaseAuthConfigWithJwt- | MetabaseAuthConfigWithSaml;+ | MetabaseAuthConfigWithSaml+ | MetabaseIsGuestAuthConfig;export type MetabaseAuthMethod = Exclude<MetabaseAuthConfig["preferredAuthMethod"],diff --git a/frontend/src/embedding-sdk-bundle/types/dashboard.ts b/frontend/src/embedding-sdk-bundle/types/dashboard.tsindex 1c5e1b0f391..41dd42a262e 100644--- a/frontend/src/embedding-sdk-bundle/types/dashboard.ts+++ b/frontend/src/embedding-sdk-bundle/types/dashboard.ts@@ -5,10 +5,32 @@ import type {import type { CreateDashboardProperties } from "metabase/dashboard/containers/CreateDashboardForm";import type { CardDisplayType } from "metabase-types/api";-import type { SdkEntityId } from "./entity";+import type { SdkEntityId, SdkEntityToken } from "./entity";export type SdkDashboardId = number | string | SdkEntityId;+export type SdkDashboardEntityPublicProps =+ | {+ /**+ * The ID of the dashboard.+ * <br/>+ * This is either:+ * <br/>+ * - the numerical ID when accessing a dashboard link, i.e. `http://localhost:3000/dashboard/1-my-dashboard` where the ID is `1`+ * <br/>+ * - the string ID found in the `entity_id` key of the dashboard object when using the API directly or using the SDK Collection Browser to return data+ */+ dashboardId: SdkDashboardId | null;+ token?: never;+ }+ | {+ dashboardId?: never;+ /**+ * A valid JWT token for the guest embed.+ */+ token: SdkEntityToken | null;+ };+/*** The Dashboard entity*/diff --git a/frontend/src/embedding-sdk-bundle/types/entity.ts b/frontend/src/embedding-sdk-bundle/types/entity.tsindex 991d428015b..a168f314cf3 100644--- a/frontend/src/embedding-sdk-bundle/types/entity.ts+++ b/frontend/src/embedding-sdk-bundle/types/entity.ts@@ -1,2 +1,4 @@// eslint-disable-next-line @typescript-eslint/ban-types -- allows for other string literal types in other ID typesexport type SdkEntityId = string & {};++export type SdkEntityToken = string;diff --git a/frontend/src/embedding-sdk-bundle/types/question.ts b/frontend/src/embedding-sdk-bundle/types/question.tsindex 4014e508a33..62dbf20dba8 100644--- a/frontend/src/embedding-sdk-bundle/types/question.ts+++ b/frontend/src/embedding-sdk-bundle/types/question.ts@@ -7,15 +7,38 @@ import type InternalQuestion from "metabase-lib/v1/Question";import type { Card, ParameterValuesMap } from "metabase-types/api";import type { SdkDashboardId } from "./dashboard";-import type { SdkEntityId } from "./entity";+import type { SdkEntityId, SdkEntityToken } from "./entity";export type { MetabaseQuestion } from "metabase/embedding-sdk/types/question";export type SdkQuestionId = number | "new" | SdkEntityId;+export type SdkQuestionEntityPublicProps =+ | {+ /**+ * The ID of the question.+ * <br/>+ * This is either:+ * <br/>+ * - the numerical ID when accessing a question link, i.e. `http://localhost:3000/question/1-my-question` where the ID is `1`+ * <br/>+ * - the string ID found in the `entity_id` key of the question object when using the API directly or using the SDK Collection Browser to return data+ */+ questionId: SdkQuestionId | null;+ token?: never;+ }+ | {+ questionId?: never;+ /**+ * A valid JWT token for the guest embed.+ */+ token: SdkEntityToken | null;+ };+export interface SdkQuestionState {question?: InternalQuestion;originalQuestion?: InternalQuestion;+ token?: string | null;queryResults?: any[];parameterValues?: ParameterValuesMap;}diff --git a/frontend/src/embedding-sdk-bundle/types/ui.ts b/frontend/src/embedding-sdk-bundle/types/ui.tsindex 7284ed03266..ace9ebf398c 100644--- a/frontend/src/embedding-sdk-bundle/types/ui.ts+++ b/frontend/src/embedding-sdk-bundle/types/ui.ts@@ -1,5 +1,40 @@import type { JSX, ReactNode } from "react";+/**+ * @inline+ */+export type InitializationStatusUninitialized = {+ status: "uninitialized";+};++/**+ * @inline+ */+export type InitializationStatusSuccess = {+ status: "success";+};++/**+ * @inline+ */+export type InitializationStatusLoading = {+ status: "loading";+};++/**+ * @inline+ */+export type InitializationStatusError = {+ status: "error";+ error: Error;+};++export type InitializationStatus =+ | InitializationStatusUninitialized+ | InitializationStatusSuccess+ | InitializationStatusLoading+ | InitializationStatusError;+export type { ButtonProps } from "metabase/ui";export type {ChartColor,diff --git a/frontend/src/embedding-sdk-bundle/types/user.ts b/frontend/src/embedding-sdk-bundle/types/user.tsindex 5c350e9090f..f61c75469a9 100644--- a/frontend/src/embedding-sdk-bundle/types/user.ts+++ b/frontend/src/embedding-sdk-bundle/types/user.ts@@ -1,3 +1,5 @@+import type { InitializationStatus, InitializationStatusError } from "./ui";+export type SdkUserId = number;/**@@ -18,34 +20,6 @@ export type MetabaseUser = {/*** @inline*/-type LoginStatusUninitialized = {- status: "uninitialized";-};--/**- * @inline- */-type LoginStatusSuccess = {- status: "success";-};--/**- * @inline- */-type LoginStatusLoading = {- status: "loading";-};--/**- * @inline- */-export type LoginStatusError = {- status: "error";- error: Error;-};+export type LoginStatusError = InitializationStatusError;-export type LoginStatus =- | LoginStatusUninitialized- | LoginStatusSuccess- | LoginStatusLoading- | LoginStatusError;+export type LoginStatus = InitializationStatus;diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.tsindex f5a179546df..8c48c90a415 100644--- a/frontend/src/metabase-types/analytics/event.ts+++ b/frontend/src/metabase-types/analytics/event.ts@@ -218,7 +218,7 @@ export type EmbedWizardExperienceCompletedEvent = ValidateEvent<{export type EmbedWizardResourceSelectionCompletedEvent = ValidateEvent<{event: "embed_wizard_resource_selection_completed";- event_detail: "default" | "custom";+ event_detail: string;}>;export type EmbedWizardOptionsCompletedEvent = ValidateEvent<{@@ -228,7 +228,7 @@ export type EmbedWizardOptionsCompletedEvent = ValidateEvent<{export type EmbedWizardCodeCopiedEvent = ValidateEvent<{event: "embed_wizard_code_copied";- event_detail: "sso" | "user_session";+ event_detail: string;}>;export type TableEditingSettingsToggledEvent = ValidateEvent<{diff --git a/frontend/src/metabase-types/store/modal.ts b/frontend/src/metabase-types/store/modal.tsindex 03b7bbfbf6b..0412f9c50cc 100644--- a/frontend/src/metabase-types/store/modal.ts+++ b/frontend/src/metabase-types/store/modal.ts@@ -1,10 +1,13 @@+import type { STATIC_LEGACY_EMBEDDING_TYPE } from "metabase/embedding/constants";+export type ModalName =| null| "collection"| "dashboard"| "action"| "help"- | "embed";+ | "embed"+ | typeof STATIC_LEGACY_EMBEDDING_TYPE;export type ModalState<TProps = Record<string, unknown>> = {id: ModalName | null;diff --git a/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.ts b/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.tsindex 3bb7066b32a..dfa71f4e77c 100644--- a/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.ts+++ b/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.ts@@ -10,61 +10,11 @@ export interface RelatedSettingItem {export const getModularEmbeddingRelatedSettingItems =(): RelatedSettingItem[] => [- // TODO: enable this once we've added the "Security" tab to Embedding Settings.- // {- // icon: "shield_outline",- // name: t`Security`,- // to: "/admin/embedding/security",- // },{- icon: "lock",- name: t`Authentication`,- to: "/admin/settings/authentication",- },- {- icon: "database",- name: t`Databases`,- to: "/admin/databases",- },- {- icon: "person",- name: t`People`,- to: "/admin/people",- },- {- icon: "group",- name: t`Permissions`,- to: "/admin/permissions",- },- {- icon: "palette",- name: t`Appearance`,- to: "/admin/settings/appearance",+ icon: "shield_outline",+ name: t`Security`,+ to: "/admin/embedding/security",},- ];--export const getStaticEmbeddingRelatedSettingItems =- (): RelatedSettingItem[] => [- {- icon: "database",- name: t`Databases`,- to: "/admin/databases",- },- {- icon: "palette",- name: t`Appearance`,- to: "/admin/settings/appearance",- },- ];--export const getInteractiveEmbeddingRelatedSettingItems =- (): RelatedSettingItem[] => [- // TODO: enable this once we've added the "Security" tab to Embedding Settings.- // {- // icon: "shield_outline",- // name: t`Security`,- // to: "/admin/embedding/security",- // },{icon: "lock",name: t`Authentication`,@@ -85,14 +35,37 @@ export const getInteractiveEmbeddingRelatedSettingItems =name: t`Permissions`,to: "/admin/permissions",},- {- icon: "metabot",- name: t`Embedded Metabot`,- to: "/admin/metabot/2",- },{icon: "palette",name: t`Appearance`,to: "/admin/settings/appearance",},];++export const getGuestEmbedsRelatedSettingItems = (): RelatedSettingItem[] => [+ {+ icon: "shield_outline",+ name: t`Security`,+ to: "/admin/embedding/security",+ },+ {+ icon: "database",+ name: t`Databases`,+ to: "/admin/databases",+ },+ {+ icon: "person",+ name: t`People`,+ to: "/admin/people",+ },+ {+ icon: "group",+ name: t`Permissions`,+ to: "/admin/permissions",+ },+ {+ icon: "palette",+ name: t`Appearance`,+ to: "/admin/settings/appearance",+ },+];diff --git a/frontend/src/metabase/admin/components/RelatedSettingsSection/index.ts b/frontend/src/metabase/admin/components/RelatedSettingsSection/index.tsindex 5d7a3e57a18..6bc1f0926da 100644--- a/frontend/src/metabase/admin/components/RelatedSettingsSection/index.ts+++ b/frontend/src/metabase/admin/components/RelatedSettingsSection/index.ts@@ -2,6 +2,5 @@ export { RelatedSettingsSection } from "./RelatedSettingsSection";export {getModularEmbeddingRelatedSettingItems,- getStaticEmbeddingRelatedSettingItems,- getInteractiveEmbeddingRelatedSettingItems,+ getGuestEmbedsRelatedSettingItems,} from "./constants";diff --git a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsxindex 5566ac41ced..917043235f1 100644--- a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx+++ b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx@@ -5,17 +5,14 @@ import {type AdminNavItemProps,AdminNavWrapper,} from "metabase/admin/components/AdminNav";-import { UpsellGem } from "metabase/admin/upsells/components/UpsellGem";import { useHasTokenFeature } from "metabase/common/hooks";import { useSelector } from "metabase/lib/redux";-import { PLUGIN_EMBEDDING } from "metabase/plugins";+import { isEEBuild } from "metabase/lib/utils";import { getLocation } from "metabase/selectors/routing";import { Divider, Flex, Stack } from "metabase/ui";export function EmbeddingNav() {const hasSimpleEmbedding = useHasTokenFeature("embedding_simple");- const hasInteractiveEmbedding = PLUGIN_EMBEDDING.isEnabled();- const hasSdkEmbedding = useHasTokenFeature("embedding_sdk");return (<AdminNavWrapper>@@ -33,40 +30,30 @@ export function EmbeddingNav() {)}<EmbeddingNavItem- path="/admin/embedding/modular"+ path="/admin/embedding"label={<Flex gap="sm" align="center">- <span>{t`Modular`}</span>- {(!hasSdkEmbedding || !hasSimpleEmbedding) && <UpsellGem />}+ <span>{t`Settings`}</span></Flex>}- icon="embed_modular"+ icon="gear"/>- <EmbeddingNavItem- path="/admin/embedding/interactive"- label={- <Flex gap="sm" align="center">- <span>{t`Interactive`}</span>- {!hasInteractiveEmbedding && <UpsellGem />}- </Flex>- }- icon="embed_interactive"- />-- <EmbeddingNavItem- path="/admin/embedding/static"- label={t`Static`}- icon="embed_static"- />-- <Divider mb="sm" />+ {isEEBuild() && (+ <>+ <EmbeddingNavItem+ path="/admin/embedding/guest"+ label={t`Guest embeds`}+ icon="ghost"+ />- <EmbeddingNavItem- path="/admin/embedding/security"- label={t`Security`}- icon="shield_outline"- />+ <EmbeddingNavItem+ path="/admin/embedding/security"+ label={t`Security`}+ icon="shield_outline"+ />+ </>+ )}</Stack></AdminNavWrapper>);diff --git a/frontend/src/metabase/admin/routes.jsx b/frontend/src/metabase/admin/routes.jsxindex 478ae07d91c..78707fef2de 100644--- a/frontend/src/metabase/admin/routes.jsx+++ b/frontend/src/metabase/admin/routes.jsx@@ -22,9 +22,9 @@ import { UserSuccessModal } from "metabase/admin/people/containers/UserSuccessMoimport { PerformanceApp } from "metabase/admin/performance/components/PerformanceApp";import getAdminPermissionsRoutes from "metabase/admin/permissions/routes";import {- EmbeddingSdkSettings,EmbeddingSecuritySettings,- StaticEmbeddingSettings,+ EmbeddingSettings,+ GuestEmbedsSettings,} from "metabase/admin/settings/components/EmbeddingSettings";import { Help } from "metabase/admin/tools/components/Help";import { JobInfoApp } from "metabase/admin/tools/components/JobInfoApp";@@ -40,9 +40,9 @@ import { TasksApp } from "metabase/admin/tools/components/TasksApp";import { ToolsApp } from "metabase/admin/tools/components/ToolsApp";import { EmbeddingHubAdminSettingsPage } from "metabase/embedding/embedding-hub";import { ModalRoute } from "metabase/hoc/ModalRoute";+import { isEEBuild } from "metabase/lib/utils";import { DataModelV1 } from "metabase/metadata/pages/DataModelV1";import {- PLUGIN_ADMIN_SETTINGS,PLUGIN_ADMIN_TOOLS,PLUGIN_ADMIN_USER_MENU_ROUTES,PLUGIN_CACHING,@@ -55,7 +55,6 @@ import {import { ModelPersistenceConfiguration } from "./performance/components/ModelPersistenceConfiguration";import { StrategyEditorForDatabases } from "./performance/components/StrategyEditorForDatabases";import { PerformanceTabId } from "./performance/types";-import { InteractiveEmbeddingUpsellPage } from "./settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage";import { getSettingsRoutes } from "./settingsRoutes";import { ToolsUpsell } from "./tools/components/ToolsUpsell";import { RedirectToAllowedSettings, createAdminRouteGuard } from "./utils";@@ -146,57 +145,59 @@ const getRoutes = (store, CanAccessSettings, IsAdmin) => ({/* EMBEDDING */}<Route path="embedding" component={createAdminRouteGuard("embedding")}><Route title={t`Embedding`} component={AdminEmbeddingApp}>- <IndexRedirect to="modular" />+ <IndexRoute component={EmbeddingSettings} />+<Routepath="setup-guide"title={t`Setup guide`}component={EmbeddingHubAdminSettingsPage}/>- <Route- path="modular"- title={t`Modular`}- component={EmbeddingSdkSettings}- />- <Route- path="interactive"- title={t`Interactive`}- component={() => {- if (PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettings) {- return <PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettings />;- }- return <InteractiveEmbeddingUpsellPage />;- }}- />- <Route- path="static"- title={t`Static`}- component={StaticEmbeddingSettings}- />- <Route- path="security"- title={t`Security`}- component={EmbeddingSecuritySettings}- />+ {isEEBuild() && (+ <>+ <Route+ path="guest"+ title={t`Unauthenticated embeds`}+ component={GuestEmbedsSettings}+ />++ <Route+ path="security"+ title={t`Security`}+ component={EmbeddingSecuritySettings}+ />+ </>+ )}</Route></Route>+ {/* EE has all embedding settings on the same page */}+ {!isEEBuild() && (+ <>+ <Redirect from="/admin/embedding/guest" to="/admin/embedding" />++ <Redirect from="/admin/embedding/security" to="/admin/embedding" />+ </>+ )}+{/* Backwards compatibility for embedding settings */}+ <Redirect from="/admin/embedding/modular" to="/admin/embedding" />+ <Redirect from="/admin/embedding/interactive" to="/admin/embedding" /><Redirectfrom="/admin/settings/embedding-in-other-applications"- to="/admin/embedding/modular"+ to="/admin/embedding"/><Redirectfrom="/admin/settings/embedding-in-other-applications/full-app"- to="/admin/embedding/interactive"+ to="/admin/embedding"/><Redirectfrom="/admin/settings/embedding-in-other-applications/standalone"- to="/admin/embedding/static"+ to="/admin/embedding/guest"/><Redirectfrom="/admin/settings/embedding-in-other-applications/sdk"- to="/admin/embedding/modular"+ to="/admin/embedding"/>{/* SETTINGS */}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsxindex c6c63b26d75..9b4f1dc9ea9 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/EmbeddingSdkSettings.tsx@@ -1,29 +1,14 @@import cx from "classnames";import { match } from "ts-pattern";-import { c, jt, t } from "ttag";+import { c, t } from "ttag";-import {- RelatedSettingsSection,- getModularEmbeddingRelatedSettingItems,-} from "metabase/admin/components/RelatedSettingsSection";-import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";-import { UpsellDevInstances } from "metabase/admin/upsells";-import { UpsellEmbeddingButton } from "metabase/admin/upsells/UpsellEmbeddingButton";import { UpsellSdkLink } from "metabase/admin/upsells/UpsellSdkLink";import ExternalLink from "metabase/common/components/ExternalLink";-import { useDocsUrl, useSetting, useUrlWithUtm } from "metabase/common/hooks";+import { useDocsUrl, 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 { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";-import { AdminSettingInput } from "../../widgets/AdminSettingInput";-import S from "../EmbeddingSettings.module.css";import { EmbeddingSettingsCard } from "../EmbeddingSettingsCard";const utmTags = {@@ -33,31 +18,9 @@ const utmTags = {utm_content: "embedding-sdk-admin",};-export function EmbeddingSdkSettings() {- const dispatch = useDispatch();+export const EmbeddingSdkSettings = () => {const isEE = isEEBuild();-- const isReactSdkEnabled = useSetting("enable-embedding-sdk");const isReactSdkFeatureAvailable = PLUGIN_EMBEDDING_SDK.isEnabled();- const isLocalhostCorsDisabled = useSetting("disable-cors-on-localhost");-- const isSimpleEmbedEnabled = useSetting("enable-embedding-simple");- const isSimpleEmbedFeatureAvailable =- PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled();-- const isEmbeddingAvailable =- isReactSdkFeatureAvailable || isSimpleEmbedFeatureAvailable;-- const canEditSdkOrigins =- (isReactSdkFeatureAvailable && isReactSdkEnabled) ||- (isSimpleEmbedFeatureAvailable && isSimpleEmbedEnabled);-- const isHosted = useSetting("is-hosted?");-- const { url: switchMetabaseBinariesUrl } = useDocsUrl(- "paid-features/activating-the-enterprise-edition",- { utm: utmTags },- );const implementJwtUrl = useDocsUrl("embedding/sdk/authentication", {utm: utmTags,@@ -73,19 +36,6 @@ export function EmbeddingSdkSettings() {utmTags,);- // The quickstart is part of the documentation page, unlike the SDK, so we only need a single docs link.- const embedJsDocumentationUrl = useDocsUrl("embedding/embedded-analytics-js");-- const SwitchBinariesLink = (- <ExternalLink- key="switch-metabase-binaries"- href={switchMetabaseBinariesUrl}- className={cx(CS.link, CS.textBold)}- >- {t`switch Metabase binaries`}- </ExternalLink>- );-const ImplementJwtLink = (<ExternalLinkkey="implement-jwt"@@ -97,18 +47,9 @@ export function EmbeddingSdkSettings() {);const apiKeyBannerText = match({- needsToSwitchBinaries: !isEE,- needsToUpgrade: !isEmbeddingAvailable,- needsToImplementJwt: isEmbeddingAvailable,+ needsToUpgrade: !isReactSdkFeatureAvailable,+ needsToImplementJwt: isReactSdkFeatureAvailable,})- .with(- { needsToSwitchBinaries: true },- () =>- c(- "{0} is the link to switch binaries. {1} is the link to upsell the SDK. {2} is the link to implement JWT or SAML authentication.",- )- .jt`You can test Embedded analytics SDK on localhost quickly by using API keys. To use the SDK on other sites, ${SwitchBinariesLink}, ${(<UpsellSdkLink key="upsell-sdk-link" />)} and ${ImplementJwtLink}.`,- ).with({ needsToUpgrade: true },() =>@@ -125,137 +66,29 @@ export function EmbeddingSdkSettings() {).otherwise(() => null);- const corsHintText = isLocalhostCorsDisabled- ? t`Separate values with a space. Localhost is not allowed. Changes will take effect within one minute.`- : t`Separate values with a space. Localhost is automatically included. Changes will take effect within one minute.`;+ if (!isEE) {+ return null;+ }return (- <SettingsPageWrapper title={t`Modular embedding`}>- <EmbeddingSettingsCard- title={t`Embedded Analytics JS`}- description={t`An easy-to-use library that lets you embed Metabase entities like charts, dashboards, or even the query builder into your own application using customizable components.`}- settingKey="enable-embedding-simple"- isFeatureEnabled={isSimpleEmbedFeatureAvailable}- links={[- {- icon: "reference",- title: t`Documentation`,- href: embedJsDocumentationUrl?.url,- },- ]}- rightSideContent={- !isSimpleEmbedFeatureAvailable ? (- <UpsellEmbeddingButton- url="https://www.metabase.com/product/embedded-analytics"- campaign="embedded-analytics-js"- location="embedding-page"- size="default"- />- ) : undefined- }- actionButton={- isSimpleEmbedFeatureAvailable && (- <Button- variant="brand"- size="sm"- onClick={() => {- dispatch(setOpenModalWithProps({ id: "embed" }));- }}- >- {t`New embed`}- </Button>- )- }- testId="sdk-setting-card"- />-- <EmbeddingSettingsCard- title={t`SDK for React`}- description={t`Embed the full power of Metabase into your application to build a custom analytics experience and programmatically manage dashboards and data.`}- settingKey="enable-embedding-sdk"- links={[- {- icon: "bolt",- title: t`Quick start`,- href: sdkQuickStartUrl,- },- {- icon: "reference",- title: t`Documentation`,- href: sdkDocumentationUrl,- },- ]}- alertInfoText={apiKeyBannerText}- testId="sdk-setting-card"- />-- <Box py="lg" px="xl" className={S.SectionCard}>- <AdminSettingInput- title={t`Cross-Origin Resource Sharing (CORS)`}- description={- <Group align="center" gap="sm">- <Text c="text-medium" fz="md">- {isEmbeddingAvailable- ? t`Enter the origins for the websites or apps where you want to allow SDK embedding.`- : jt`Try out the SDK on localhost. To enable other sites, ${(<UpsellSdkLink key="upsell-sdk-link" />)} and enter the origins for the websites or apps where you want to allow SDK and Embedded Analytics JS.`}- </Text>-- {isEmbeddingAvailable && (- <HoverCard position="bottom">- <HoverCard.Target>- <Icon name="info" c="text-medium" cursor="pointer" />- </HoverCard.Target>-- <HoverCard.Dropdown>- <Box p="md" w={270} bg="white">- <Text lh="lg" c="text-medium">- {corsHintText}- </Text>- </Box>- </HoverCard.Dropdown>- </HoverCard>- )}- </Group>- }- name="embedding-app-origins-sdk"- placeholder="https://*.example.com"- inputType="text"- disabled={!canEditSdkOrigins}- />- </Box>-- {isEmbeddingAvailable && isHosted && (- <Box py="lg" px="xl" className={S.SectionCard}>- <Stack gap="xs">- <Text- htmlFor="version-pinning"- component="label"- c="text-primary"- fw="bold"- fz="lg"- >- {t`Version pinning`}- </Text>-- <Text c="text-secondary" lh="lg" mb="sm">- {t`Metabase Cloud instances are automatically upgraded to new releases. SDK packages are strictly compatible with specific version of Metabase. You can request to pin your Metabase to a major version and upgrade your Metabase and SDK dependency in a coordinated fashion.`}- </Text>-- <ExternalLink href="mailto:[email protected]">- <Group gap="sm" fw="bold" w="fit-content">- <Icon name="mail" size={14} aria-hidden />- <span>{t`Request version pinning`}</span>- </Group>- </ExternalLink>- </Stack>- </Box>- )}-- <RelatedSettingsSection- items={getModularEmbeddingRelatedSettingItems()}- />-- <UpsellDevInstances location="embedding-page" />- </SettingsPageWrapper>+ <EmbeddingSettingsCard+ title={t`Enable SDK for React`}+ description={t`Embed the full power of Metabase into your application to build a custom analytics experience and programmatically manage dashboards and data.`}+ settingKey="enable-embedding-sdk"+ links={[+ {+ icon: "bolt",+ title: t`Quick start`,+ href: sdkQuickStartUrl,+ },+ {+ icon: "reference",+ title: t`Documentation`,+ href: sdkDocumentationUrl,+ },+ ]}+ alertInfoText={apiKeyBannerText}+ testId="sdk-setting-card"+ />);-}+};diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/index.ts b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/index.tsdeleted file mode 100644index fa7a99790d2..00000000000--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./EmbeddingSdkSettings";diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/common.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/common.unit.spec.tsxdeleted file mode 100644index 660aa0defc3..00000000000--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/common.unit.spec.tsx+++ /dev/null@@ -1,196 +0,0 @@-import userEvent from "@testing-library/user-event";--import { findRequests } from "__support__/server-mocks";-import { screen, within } from "__support__/ui";--import { setup } from "./setup";--describe("EmbeddingSdkSettings (OSS)", () => {- describe("banner text when user is self-hosted or cloud", () => {- it("should tell users to use localhost and API keys to test the SDK", async () => {- await setup({- isEmbeddingSdkEnabled: true,- showSdkEmbedTerms: false,- });- expect(- screen.getByText(- /You can test Embedded analytics SDK on localhost quickly by using API keys/i,- ),- ).toBeInTheDocument();-- const alertInfo = within(screen.getByTestId("sdk-settings-alert-info"));- expect(- alertInfo.getByText("switch Metabase binaries"),- ).toBeInTheDocument();- expect(- alertInfo.getByText("upgrade to Metabase Pro"),- ).toBeInTheDocument();- expect(- alertInfo.getByText("implement JWT or SAML SSO"),- ).toBeInTheDocument();- });- });-- describe("Modal behavior based on enable-embedding-sdk and show-sdk-embed-terms", () => {- describe("when enable-embedding-sdk=false & show-sdk-embed-terms=true", () => {- it("should update settings when user accepts the SDK terms", async () => {- await setup({- isEmbeddingSdkEnabled: false,- showSdkEmbedTerms: true,- });-- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();- await userEvent.click(- screen.getByRole("switch", { name: "SDK for React toggle" }),- );- assertLegaleseModal();-- await userEvent.click(screen.getByText("Agree and continue"));-- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();-- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- const [{ body }] = puts;- expect(body).toEqual({- "enable-embedding-sdk": true,- "show-sdk-embed-terms": false,- });- });-- it("should not update settings when user declines the SDK terms", async () => {- await setup({- isEmbeddingSdkEnabled: false,- showSdkEmbedTerms: true,- });-- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();- await userEvent.click(- screen.getByRole("switch", { name: "SDK for React toggle" }),- );- assertLegaleseModal();-- await userEvent.click(screen.getByText("Decline and go back"));-- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();-- const puts = await findRequests("PUT");- expect(puts).toHaveLength(0);- });- });-- describe("when enable-embedding-sdk=false & show-sdk-embed-terms=false", () => {- it("should not show the modal when the user clicks the toggle", async () => {- await setup({- isEmbeddingSdkEnabled: false,- showSdkEmbedTerms: false,- });-- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();- await userEvent.click(- screen.getByRole("switch", { name: "SDK for React toggle" }),- );- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();-- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- const [{ url, body }] = puts;- expect(url).toContain("api/setting/enable-embedding-sdk");- expect(body).toEqual({- value: true,- });- });- });- });-- it("should not show version pinning section", async () => {- await setup({- isEmbeddingSdkEnabled: true,- showSdkEmbedTerms: false,- });- expect(screen.queryByText("Version pinning")).not.toBeInTheDocument();- expect(- screen.queryByText(- "Metabase Cloud instances are automatically upgraded to new releases. SDK packages are strictly compatible with specific version of Metabase. You can request to pin your Metabase to a major version and upgrade your Metabase and SDK dependency in a coordinated fashion.",- ),- ).not.toBeInTheDocument();- expect(- screen.queryByRole("link", { name: "Request version pinning" }),- ).not.toBeInTheDocument();- });-- it("should show cards with related settings", async () => {- await setup({- isEmbeddingSdkEnabled: true,- showSdkEmbedTerms: false,- });-- const relatedSettingCards = await screen.findAllByTestId(- "related-setting-card",- );- expect(relatedSettingCards).toHaveLength(5);-- expect(await screen.findByText("Authentication")).toBeInTheDocument();- expect(await screen.findByText("Databases")).toBeInTheDocument();- expect(await screen.findByText("People")).toBeInTheDocument();- expect(await screen.findByText("Permissions")).toBeInTheDocument();- expect(await screen.findByText("Appearance")).toBeInTheDocument();- });-- it("shows the Embedded Analytics JS toggle is Disabled when token features are missing (EMB-801)", () => {- setup({ tokenFeatures: { embedding_simple: false } });-- const toggle = screen.getByRole("switch", {- name: "Embedded Analytics JS toggle",- });-- expect(toggle).toBeDisabled();-- const toggleContainer = screen- .getAllByTestId("switch-with-env-var")- .find((toggleElement) =>- within(toggleElement).queryByRole("switch", {- name: "Embedded Analytics JS toggle",- }),- );-- expect(within(toggleContainer!).getByText("Disabled")).toBeInTheDocument();- });-- it("should not show embed button and docs when Embedded Analytics JS is not available", async () => {- setup({ tokenFeatures: { embedding_simple: false } });-- const card = screen- .getAllByTestId("sdk-setting-card")- .find((card) => card.textContent?.includes("Embedded Analytics JS"));-- // Upsell and documentation should be shown- expect(card).toHaveTextContent("Try for free");- expect(card).toHaveTextContent("Documentation");-- // Call-to-action should not be shown- expect(card).not.toHaveTextContent("New embed");- });-- it("should not show embed button on oss even if simple embedding is enabled", async () => {- await setup({- isEmbeddingSimpleEnabled: true,- tokenFeatures: { embedding_simple: false },- });-- const card = screen- .getAllByTestId("sdk-setting-card")- .find((card) => card.textContent?.includes("Embedded Analytics JS"));-- expect(card).not.toHaveTextContent("New embed");- expect(card).toHaveTextContent("Documentation");- });-});--function assertLegaleseModal() {- expect(screen.getByRole("dialog")).toBeInTheDocument();-- expect(screen.getByText("First, some legalese")).toBeInTheDocument();- expect(screen.getByText("Decline and go back")).toBeInTheDocument();- expect(screen.getByText("Agree and continue")).toBeInTheDocument();-}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/CorsInputWidget.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/CorsInputWidget.tsxnew file mode 100644index 00000000000..c82eb0e53bb--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/CorsInputWidget.tsx@@ -0,0 +1,58 @@+import { jt, t } from "ttag";++import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";+import { useSetting } from "metabase/common/hooks";+import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";+import { Box, Group, HoverCard, Icon, Text } from "metabase/ui";++export const CorsInputWidget = () => {+ const isReactSdkEnabled = useSetting("enable-embedding-sdk");+ const isReactSdkFeatureAvailable = PLUGIN_EMBEDDING_SDK.isEnabled();+ const isLocalhostCorsDisabled = useSetting("disable-cors-on-localhost");++ const isSimpleEmbedEnabled = useSetting("enable-embedding-simple");++ const corsHintText = isLocalhostCorsDisabled+ ? t`Separate values with a space. Localhost is not allowed. Changes will take effect within one minute.`+ : t`Separate values with a space. Localhost is automatically included. Changes will take effect within one minute.`;++ const canEditSdkOrigins =+ (isReactSdkFeatureAvailable && isReactSdkEnabled) || isSimpleEmbedEnabled;++ return (+ <AdminSettingInput+ title={t`Cross-Origin Resource Sharing (CORS)`}+ description={+ <Group align="center" gap="sm">+ <Text c="text-medium" fz="md">+ {jt`Add the website domains where you want to allow Embedded Analytics JS and SDK. SDK using API keys can only run on localhost.. ${(+ <HoverCard key="embedding-cors-hint" position="bottom">+ <HoverCard.Target>+ <Icon+ name="info"+ c="text-medium"+ cursor="pointer"+ ml="sm"+ style={{ verticalAlign: "middle" }}+ />+ </HoverCard.Target>++ <HoverCard.Dropdown>+ <Box p="md" w={270} bg="white">+ <Text lh="lg" c="text-medium">+ {corsHintText}+ </Text>+ </Box>+ </HoverCard.Dropdown>+ </HoverCard>+ )}`}+ </Text>+ </Group>+ }+ name="embedding-app-origins-sdk"+ placeholder="https://*.example.com"+ inputType="text"+ disabled={!canEditSdkOrigins}+ />+ );+};diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.tsxindex 991bae1e907..5c9d278e95f 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.tsx@@ -5,11 +5,16 @@ import {SettingsSection,} from "metabase/admin/components/SettingsSection";+import { CorsInputWidget } from "./CorsInputWidget";import { SameSiteSelectWidget } from "./SameSiteSelectWidget";export function EmbeddingSecuritySettings() {return (<SettingsPageWrapper title={t`Security`}>+ <SettingsSection>+ <CorsInputWidget />+ </SettingsSection>+<SettingsSection><SameSiteSelectWidget /></SettingsSection>diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/common.unit.spec.tsxsimilarity index 56%rename from frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.unit.spec.tsxrename to frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/common.unit.spec.tsxindex 0f105ec3860..f19010cb03f 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/EmbeddingSecuritySettings.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/common.unit.spec.tsx@@ -1,32 +1,26 @@import userEvent from "@testing-library/user-event";-import {- findRequests,- setupPropertiesEndpoints,- setupSettingsEndpoints,- setupUpdateSettingEndpoint,-} from "__support__/server-mocks";+import { findRequests } from "__support__/server-mocks";import { renderWithProviders, screen } from "__support__/ui";-import { createMockSettings } from "metabase-types/api/mocks";-import { EmbeddingSecuritySettings } from "./EmbeddingSecuritySettings";+import { setup as baseSetup } from "../../tests/setup";+import { EmbeddingSecuritySettings } from "../EmbeddingSecuritySettings";const setup = async () => {- const settings = createMockSettings();-- setupPropertiesEndpoints(settings);- setupSettingsEndpoints([]);- setupUpdateSettingEndpoint();+ await baseSetup({+ renderCallback: ({ state }) =>+ renderWithProviders(<EmbeddingSecuritySettings />, {+ storeInitialState: state,+ }),+ });- renderWithProviders(<EmbeddingSecuritySettings />);+ expect(await screen.findByText("Security")).toBeInTheDocument();};-describe("EmbeddingSecuritySettings", () => {+describe("EmbeddingSecuritySettings => common", () => {it("should allow changing samesite cookie setting", async () => {await setup();- expect(await screen.findByText("Security")).toBeInTheDocument();-expect(await screen.findByText("SameSite cookie setting"),).toBeInTheDocument();diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/enterprise.unit.spec.tsxnew file mode 100644index 00000000000..16430c906f7--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/enterprise.unit.spec.tsx@@ -0,0 +1,57 @@+import userEvent from "@testing-library/user-event";++import { findRequests } from "__support__/server-mocks";+import { fireEvent, renderWithProviders, screen, within } from "__support__/ui";++import { setup as baseSetup } from "../../tests/setup";+import { EmbeddingSecuritySettings } from "../EmbeddingSecuritySettings";++const setup = async ({+ showSdkEmbedTerms,+ isEmbeddingSdkEnabled,+}: {+ showSdkEmbedTerms?: boolean;+ isEmbeddingSdkEnabled?: boolean;+} = {}) => {+ await baseSetup({+ renderCallback: ({ state }) =>+ renderWithProviders(<EmbeddingSecuritySettings />, {+ storeInitialState: state,+ }),+ showSdkEmbedTerms,+ isEmbeddingSdkEnabled,+ hasEnterprisePlugins: isEmbeddingSdkEnabled,+ tokenFeatures: {+ embedding_sdk: isEmbeddingSdkEnabled,+ },+ });++ expect(await screen.findByText("Security")).toBeInTheDocument();+};++describe("EmbeddingSecuritySettings => enterprise", () => {+ it("should allow users to update CORS settings", async () => {+ await setup({+ isEmbeddingSdkEnabled: true,+ showSdkEmbedTerms: false,+ });++ const input = within(+ await screen.findByTestId("embedding-app-origins-sdk-setting"),+ ).getByRole("textbox");++ expect(input).toBeEnabled();+ await userEvent.clear(input);+ await userEvent.type(input, "fast.limos");+ await fireEvent.blur(input);+ await screen.findByDisplayValue("fast.limos");++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ const [{ url, body }] = puts;+ expect(url).toContain("api/setting/embedding-app-origins-sdk");+ expect(body).toEqual({+ value: "fast.limos",+ });+ });+});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/simple-embedding.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/simple-embedding.unit.spec.tsxnew file mode 100644index 00000000000..73e6edb445a--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecuritySettings/tests/simple-embedding.unit.spec.tsx@@ -0,0 +1,85 @@+import { renderWithProviders, screen } from "__support__/ui";++import { setup as baseSetup } from "../../tests/setup";+import { EmbeddingSecuritySettings } from "../EmbeddingSecuritySettings";++const setup = async ({+ showSdkEmbedTerms,+ isEmbeddingSdkEnabled,+ isEmbeddingSimpleEnabled,+}: {+ showSdkEmbedTerms?: boolean;+ isEmbeddingSdkEnabled?: boolean;+ isEmbeddingSimpleEnabled?: boolean;+} = {}) => {+ await baseSetup({+ renderCallback: ({ state }) =>+ renderWithProviders(<EmbeddingSecuritySettings />, {+ storeInitialState: state,+ }),+ showSdkEmbedTerms,+ isEmbeddingSdkEnabled,+ isEmbeddingSimpleEnabled,+ hasEnterprisePlugins: true,+ tokenFeatures: {+ embedding_sdk: true,+ embedding_simple: true,+ },+ });++ expect(await screen.findByText("Security")).toBeInTheDocument();+};++describe("EmbeddingSecuritySettings", () => {+ describe("Authorized Origins input field", () => {+ it("should be disabled when both SDK and simple embedding are disabled", async () => {+ await setup({+ isEmbeddingSdkEnabled: false,+ isEmbeddingSimpleEnabled: false,+ showSdkEmbedTerms: false,+ });++ expect(+ screen.getByText("Cross-Origin Resource Sharing (CORS)"),+ ).toBeInTheDocument();++ const originInput = screen.getByPlaceholderText("https://*.example.com");+ expect(originInput).toBeDisabled();+ });++ it.each([+ {+ description:+ "should be enabled when SDK is enabled and simple embedding is disabled",+ isEmbeddingSdkEnabled: true,+ isEmbeddingSimpleEnabled: false,+ },+ {+ description:+ "should be enabled when simple embedding is enabled and SDK is disabled",+ isEmbeddingSdkEnabled: false,+ isEmbeddingSimpleEnabled: true,+ },+ {+ description:+ "should be enabled when both SDK and simple embedding are enabled",+ isEmbeddingSdkEnabled: true,+ isEmbeddingSimpleEnabled: true,+ },+ ])(+ "$description",+ async ({ isEmbeddingSdkEnabled, isEmbeddingSimpleEnabled }) => {+ await setup({+ isEmbeddingSdkEnabled,+ isEmbeddingSimpleEnabled,+ showSdkEmbedTerms: false,+ });++ const originInput = screen.getByPlaceholderText(+ "https://*.example.com",+ );+ expect(originInput).toBeEnabled();+ },+ );+ });+});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsxnew file mode 100644index 00000000000..b5ff9ea1b32--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsx@@ -0,0 +1,130 @@+import type { PropsWithChildren } from "react";+import { t } from "ttag";++import {+ RelatedSettingsSection,+ getModularEmbeddingRelatedSettingItems,+} from "metabase/admin/components/RelatedSettingsSection";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";+import { NewEmbedButton } from "metabase/admin/settings/components/EmbeddingSettings/NewEmbedButton/NewEmbedButton";+import { UpsellDevInstances } from "metabase/admin/upsells";+import ExternalLink from "metabase/common/components/ExternalLink";+import { useDocsUrl, useSetting } from "metabase/common/hooks";+import { isEEBuild } from "metabase/lib/utils";+import {+ PLUGIN_ADMIN_SETTINGS,+ PLUGIN_CONTENT_TRANSLATION,+ PLUGIN_EMBEDDING_SDK,+} from "metabase/plugins";+import { Box, Group, Icon, Stack, Text } from "metabase/ui";++import { EmbeddingSdkSettings } from "../EmbeddingSdkSettings/EmbeddingSdkSettings";+import S from "../EmbeddingSettings.module.css";+import { EmbeddingSettingsCard } from "../EmbeddingSettingsCard";+import { SharedCombinedEmbeddingSettings } from "../SharedCombinedEmbeddingSettings";++function EmbeddingSettingsPageWrapper({ children }: PropsWithChildren) {+ const isEE = isEEBuild();++ return (+ <SettingsPageWrapper title={t`Embedding settings`}>+ {children}++ <RelatedSettingsSection+ items={getModularEmbeddingRelatedSettingItems()}+ />++ {isEE && <UpsellDevInstances location="embedding-page" />}+ </SettingsPageWrapper>+ );+}++function EmbeddingSettingsEE() {+ const isReactSdkFeatureAvailable = PLUGIN_EMBEDDING_SDK.isEnabled();++ const isHosted = useSetting("is-hosted?");++ // The quickstart is part of the documentation page, unlike the SDK, so we only need a single docs link.+ const embedJsDocumentationUrl = useDocsUrl("embedding/embedded-analytics-js");++ return (+ <>+ <Text size="lg" fw="bold" lh="xs">+ {t`Embedding methods`}+ </Text>++ <EmbeddingSettingsCard+ title={t`Enable Embedded Analytics JS`}+ description={t`An easy-to-use library that lets you embed Metabase entities like charts, dashboards, or even the query builder into your own application using customizable components.`}+ settingKey="enable-embedding-simple"+ links={[+ {+ icon: "reference",+ title: t`Documentation`,+ href: embedJsDocumentationUrl?.url,+ },+ ]}+ actionButton={<NewEmbedButton />}+ testId="sdk-setting-card"+ />++ <EmbeddingSdkSettings />++ {PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettingsCard && (+ <PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettingsCard />+ )}++ <Text size="lg" fw="bold" lh="xs">+ {t`Settings`}+ </Text>++ <PLUGIN_CONTENT_TRANSLATION.ContentTranslationConfiguration />++ {isReactSdkFeatureAvailable && isHosted && (+ <Box py="lg" px="xl" className={S.SectionCard}>+ <Stack gap="xs">+ <Text+ htmlFor="version-pinning"+ component="label"+ c="text-primary"+ fw="bold"+ fz="lg"+ >+ {t`Version pinning`}+ </Text>++ <Text c="text-secondary" lh="lg" mb="sm">+ {t`Metabase Cloud instances are automatically upgraded to new releases. SDK packages are strictly compatible with specific version of Metabase. You can request to pin your Metabase to a major version and upgrade your Metabase and SDK dependency in a coordinated fashion.`}+ </Text>++ <ExternalLink href="mailto:[email protected]">+ <Group gap="sm" fw="bold" w="fit-content">+ <Icon name="mail" size={14} aria-hidden />+ <span>{t`Request version pinning`}</span>+ </Group>+ </ExternalLink>+ </Stack>+ </Box>+ )}+ </>+ );+}++function EmbeddingSettingsOSS() {+ return (+ <SharedCombinedEmbeddingSettings+ showCorsSettings+ showContentTranslationSettings+ />+ );+}++export const EmbeddingSettings = () => {+ const isEE = isEEBuild();++ return (+ <EmbeddingSettingsPageWrapper>+ {isEE ? <EmbeddingSettingsEE /> : <EmbeddingSettingsOSS />}+ </EmbeddingSettingsPageWrapper>+ );+};diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/index.ts b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/index.tsnew file mode 100644index 00000000000..68d9dd94d91--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/index.ts@@ -0,0 +1 @@+export * from "./EmbeddingSettings";diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/common.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/common.unit.spec.tsxnew file mode 100644index 00000000000..658a3cd3855--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/common.unit.spec.tsx@@ -0,0 +1,66 @@+import { screen } from "__support__/ui";++import { setup } from "./setup";++describe("EmbeddingSdkSettings (OSS)", () => {+ describe("SDK card", () => {+ it("should not show SDK card in OSS", async () => {+ await setup({+ isEmbeddingSdkEnabled: false,+ showSdkEmbedTerms: false,+ });+ expect(+ screen.queryByText(/Enable SDK for React/i),+ ).not.toBeInTheDocument();+ });+ });++ it("should not show version pinning section", async () => {+ await setup({+ isEmbeddingSdkEnabled: true,+ showSdkEmbedTerms: false,+ });+ expect(screen.queryByText("Version pinning")).not.toBeInTheDocument();+ expect(+ screen.queryByText(+ "Metabase Cloud instances are automatically upgraded to new releases. SDK packages are strictly compatible with specific version of Metabase. You can request to pin your Metabase to a major version and upgrade your Metabase and SDK dependency in a coordinated fashion.",+ ),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("link", { name: "Request version pinning" }),+ ).not.toBeInTheDocument();+ });++ it("should show cards with related settings", async () => {+ await setup({+ isEmbeddingSdkEnabled: true,+ showSdkEmbedTerms: false,+ });++ const relatedSettingCards = await screen.findAllByTestId(+ "related-setting-card",+ );+ expect(relatedSettingCards).toHaveLength(6);++ expect(await screen.findByText("Security")).toBeInTheDocument();+ expect(await screen.findByText("Authentication")).toBeInTheDocument();+ expect(await screen.findByText("Databases")).toBeInTheDocument();+ expect(await screen.findByText("People")).toBeInTheDocument();+ expect(await screen.findByText("Permissions")).toBeInTheDocument();+ expect(await screen.findByText("Appearance")).toBeInTheDocument();+ });++ it("does not show the Embedded Analytics JS toggle when token features are missing", () => {+ setup({ tokenFeatures: { embedding_simple: false } });++ expect(+ screen.queryByText("Enable Embedded Analytics JS"),+ ).not.toBeInTheDocument();+ });++ it("shows the Guest Embeds toggle when token features are missing", () => {+ setup({ tokenFeatures: { embedding_simple: false } });++ expect(screen.getByText("Guest embeds")).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/enterprise.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/enterprise.unit.spec.tsxrename to frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/enterprise.unit.spec.tsxdiff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/premium.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/premium.unit.spec.tsxsimilarity index 67%rename from frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/premium.unit.spec.tsxrename to frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/premium.unit.spec.tsxindex 1c47883aa3c..e6792e616d3 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/premium.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/premium.unit.spec.tsx@@ -1,7 +1,4 @@-import userEvent from "@testing-library/user-event";--import { findRequests } from "__support__/server-mocks";-import { fireEvent, screen, within } from "__support__/ui";+import { screen, within } from "__support__/ui";import { type SetupOpts, setup as baseSetup } from "./setup";@@ -37,31 +34,6 @@ describe("EmbeddingSdkSettings (EE with Embedding SDK token)", () => {).toBeInTheDocument();});- it("should allow users to update CORS settings", async () => {- await setup({- isEmbeddingSdkEnabled: true,- showSdkEmbedTerms: false,- });-- const input = within(- await screen.findByTestId("embedding-app-origins-sdk-setting"),- ).getByRole("textbox");-- expect(input).toBeEnabled();- await userEvent.clear(input);- await userEvent.type(input, "fast.limos");- await fireEvent.blur(input);- await screen.findByDisplayValue("fast.limos");-- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- const [{ url, body }] = puts;- expect(url).toContain("api/setting/embedding-app-origins-sdk");- expect(body).toEqual({- value: "fast.limos",- });- });-describe("Version pinning", () => {it("should offer users version pinning when they have a cloud instance", async () => {await setup({ isHosted: true });diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/setup.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/setup.tsxnew file mode 100644index 00000000000..43c75a94f98--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/setup.tsx@@ -0,0 +1,19 @@+import { renderWithProviders, screen } from "__support__/ui";++import {+ type SetupOpts as BaseSetupOpts,+ setup as baseSetup,+} from "../../tests/setup";+import { EmbeddingSettings } from "../EmbeddingSettings";++export type SetupOpts = Omit<BaseSetupOpts, "renderCallback">;++export async function setup(setupOptions: SetupOpts = {}) {+ baseSetup({+ ...setupOptions,+ renderCallback: ({ state }) =>+ renderWithProviders(<EmbeddingSettings />, { storeInitialState: state }),+ });++ await screen.findByText("Embedding settings");+}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/simple-embedding.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/simple-embedding.unit.spec.tsxsimilarity index 59%rename from frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/simple-embedding.unit.spec.tsxrename to frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/simple-embedding.unit.spec.tsxindex 5d1086ae8b0..de069aa9dbb 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/simple-embedding.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/simple-embedding.unit.spec.tsx@@ -27,11 +27,13 @@ describe("EmbeddingSdkSettings (EE with Simple Embedding feature)", () => {expect(toggles).toHaveLength(2);expect(- screen.getByRole("switch", { name: "SDK for React toggle" }),+ screen.getByRole("switch", { name: "Enable SDK for React toggle" }),).toBeInTheDocument();expect(- screen.getByRole("switch", { name: "Embedded Analytics JS toggle" }),+ screen.getByRole("switch", {+ name: "Enable Embedded Analytics JS toggle",+ }),).toBeInTheDocument();});@@ -46,7 +48,7 @@ describe("EmbeddingSdkSettings (EE with Simple Embedding feature)", () => {// Enable Embedded Analytics JSconst toggle = await screen.findByRole("switch", {- name: "Embedded Analytics JS toggle",+ name: "Enable Embedded Analytics JS toggle",});await userEvent.click(toggle);@@ -66,7 +68,7 @@ describe("EmbeddingSdkSettings (EE with Simple Embedding feature)", () => {});const toggle = await screen.findByRole("switch", {- name: "Embedded Analytics JS toggle",+ name: "Enable Embedded Analytics JS toggle",});await userEvent.click(toggle);@@ -92,61 +94,11 @@ describe("EmbeddingSdkSettings (EE with Simple Embedding feature)", () => {const card = screen.getAllByTestId("sdk-setting-card")- .find((card) => card.textContent?.includes("Embedded Analytics JS"));+ .find((card) =>+ card.textContent?.includes("Enable Embedded Analytics JS"),+ );expect(card).toHaveTextContent("New embed");expect(card).toHaveTextContent("Documentation");});-- describe("Authorized Origins input field", () => {- it("should be disabled when both SDK and simple embedding are disabled", async () => {- await setup({- isEmbeddingSdkEnabled: false,- isEmbeddingSimpleEnabled: false,- showSdkEmbedTerms: false,- });-- expect(- screen.getByText("Cross-Origin Resource Sharing (CORS)"),- ).toBeInTheDocument();-- const originInput = screen.getByPlaceholderText("https://*.example.com");- expect(originInput).toBeDisabled();- });-- it.each([- {- description:- "should be enabled when SDK is enabled and simple embedding is disabled",- isEmbeddingSdkEnabled: true,- isEmbeddingSimpleEnabled: false,- },- {- description:- "should be enabled when simple embedding is enabled and SDK is disabled",- isEmbeddingSdkEnabled: false,- isEmbeddingSimpleEnabled: true,- },- {- description:- "should be enabled when both SDK and simple embedding are enabled",- isEmbeddingSdkEnabled: true,- isEmbeddingSimpleEnabled: true,- },- ])(- "$description",- async ({ isEmbeddingSdkEnabled, isEmbeddingSimpleEnabled }) => {- await setup({- isEmbeddingSdkEnabled,- isEmbeddingSimpleEnabled,- showSdkEmbedTerms: false,- });-- const originInput = screen.getByPlaceholderText(- "https://*.example.com",- );- expect(originInput).toBeEnabled();- },- );- });});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettingsCard.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettingsCard.tsxindex 834d741cd6a..6e9f3a4df49 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettingsCard.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettingsCard.tsx@@ -1,3 +1,5 @@+import type { PropsWithChildren } from "react";+import ExternalLink from "metabase/common/components/ExternalLink";import {Alert,@@ -11,35 +13,34 @@ import {} from "metabase/ui";import S from "./EmbeddingSettings.module.css";-import { EmbeddingToggle } from "./EmbeddingToggle";+import { type EmbeddingSettingKey, EmbeddingToggle } from "./EmbeddingToggle";type LinkItem = { icon: IconName; title: string; href: string };export function EmbeddingSettingsCard({+ children,title,description,settingKey,+ dependentSettingKeys,isFeatureEnabled = true,links,rightSideContent,alertInfoText,actionButton,testId,-}: {+}: PropsWithChildren<{title: string;description: string;- settingKey:- | "enable-embedding-sdk"- | "enable-embedding-simple"- | "enable-embedding-static"- | "enable-embedding-interactive";+ settingKey: EmbeddingSettingKey;+ dependentSettingKeys?: EmbeddingSettingKey[];isFeatureEnabled?: boolean;links?: LinkItem[];rightSideContent?: React.ReactNode;alertInfoText?: React.ReactNode;actionButton?: React.ReactNode;testId?: string;-}) {+}>) {const hasLinksContent = links && links.length > 0;return (@@ -56,6 +57,7 @@ export function EmbeddingSettingsCard({<Group justify="space-between" align="center"><EmbeddingTogglesettingKey={settingKey}+ dependentSettingKeys={dependentSettingKeys}labelPosition="right"disabled={!isFeatureEnabled}aria-label={`${title} toggle`}@@ -87,6 +89,8 @@ export function EmbeddingSettingsCard({)}</Stack>+ {children}+{(hasLinksContent || actionButton) && (<Grouppx="xl"diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.tsxindex 73745b656a9..b84ac4cd7b3 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.tsx@@ -2,26 +2,33 @@ import { useDisclosure } from "@mantine/hooks";import type { ChangeEvent } from "react";import { t } from "ttag";-import { useAdminSetting } from "metabase/api/utils";+import { useAdminSetting, useAdminSettings } from "metabase/api/utils";import { useSetting } from "metabase/common/hooks";import { Switch, type SwitchProps, Text } from "metabase/ui";import { EmbeddingLegaleseModal } from "../EmbeddingLegaleseModal";+export type EmbeddingSettingKey =+ | "enable-embedding-static"+ | "enable-embedding-sdk"+ | "enable-embedding-interactive"+ | "enable-embedding-simple";+export type EmbeddingToggleProps = {- settingKey:- | "enable-embedding-static"- | "enable-embedding-sdk"- | "enable-embedding-interactive"- | "enable-embedding-simple";+ settingKey: EmbeddingSettingKey;+ dependentSettingKeys?: EmbeddingSettingKey[];} & Omit<SwitchProps, "onChange">;export function EmbeddingToggle({settingKey,+ dependentSettingKeys = [],labelPosition = "left",...switchProps}: EmbeddingToggleProps) {- const { value, settingDetails, updateSetting } = useAdminSetting(settingKey);+ const { value, settingDetails } = useAdminSetting(settingKey);+ const { values: dependentSettingsValues, updateSettings } =+ useAdminSettings(dependentSettingKeys);+const showSdkEmbedTerms = useSetting("show-sdk-embed-terms");const showSimpleEmbedTerms = useSetting("show-simple-embed-terms");@@ -36,26 +43,28 @@ export function EmbeddingToggle({);}- const isEnabled = Boolean(value);+ const isEnabled =+ Boolean(value) && Object.values(dependentSettingsValues).every(Boolean);const isEmbeddingToggle =settingKey === "enable-embedding-sdk" ||settingKey === "enable-embedding-simple";- const handleChange = (newValue: boolean) => {+ const handleChange = (checked: boolean) => {const shouldShowEmbedTerms =(settingKey === "enable-embedding-sdk" && showSdkEmbedTerms) ||(settingKey === "enable-embedding-simple" && showSimpleEmbedTerms);- if (shouldShowEmbedTerms && isEmbeddingToggle && newValue) {+ if (shouldShowEmbedTerms && isEmbeddingToggle && checked) {openLegaleseModal();return;}- updateSetting({- key: settingKey,- value: newValue,- });+ const settingKeys = [settingKey, ...dependentSettingKeys];++ updateSettings(+ Object.fromEntries(settingKeys.map((key) => [key, checked])),+ );};return (diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsxindex b3bb5c0066d..f4b8151df28 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsx@@ -4,7 +4,7 @@ import {findRequests,setupPropertiesEndpoints,setupSettingsEndpoints,- setupUpdateSettingEndpoint,+ setupUpdateSettingsEndpoint,} from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";import type { SettingDefinition } from "metabase-types/api";@@ -40,7 +40,7 @@ const setup = async ({setupSettingsEndpoints(settings);setupPropertiesEndpoints(settingValues);- setupUpdateSettingEndpoint();+ setupUpdateSettingsEndpoint();renderWithProviders(<EmbeddingToggle@@ -91,7 +91,7 @@ describe("EmbeddingToggle", () => {const puts = await findRequests("PUT");expect(puts).toHaveLength(1);const [{ body }] = puts;- expect(body).toEqual({ value: true });+ expect(body).toEqual({ "enable-embedding-static": true });});it("should send a PUT request with value=false when setting is on", async () => {@@ -103,7 +103,7 @@ describe("EmbeddingToggle", () => {const puts = await findRequests("PUT");expect(puts).toHaveLength(1);const [{ body }] = puts;- expect(body).toEqual({ value: false });+ expect(body).toEqual({ "enable-embedding-static": false });});});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.tsxnew file mode 100644index 00000000000..7e187ffaae9--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.tsx@@ -0,0 +1,18 @@+import { t } from "ttag";++import {+ RelatedSettingsSection,+ getGuestEmbedsRelatedSettingItems,+} from "metabase/admin/components/RelatedSettingsSection";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";+import { SharedCombinedEmbeddingSettings } from "metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings";++export function GuestEmbedsSettings() {+ return (+ <SettingsPageWrapper title={t`Guest embeds`}>+ <SharedCombinedEmbeddingSettings />++ <RelatedSettingsSection items={getGuestEmbedsRelatedSettingItems()} />+ </SettingsPageWrapper>+ );+}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsxnew file mode 100644index 00000000000..099f8d1f4b0--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsx@@ -0,0 +1,59 @@+import fetchMock from "fetch-mock";++import {+ setupEmbeddableEntitiesEndpoints,+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+ setupUpdateSettingEndpoint,+ setupUserKeyValueEndpoints,+} from "__support__/server-mocks";+import { renderWithProviders, screen } from "__support__/ui";+import {+ createMockCard,+ createMockDashboard,+ createMockSettings,+} from "metabase-types/api/mocks";++import { GuestEmbedsSettings } from "./GuestEmbedsSettings";++const setup = async ({ enabled }: { enabled: boolean }) => {+ const settings = createMockSettings({ "enable-embedding-static": enabled });++ setupPropertiesEndpoints(settings);+ setupSettingsEndpoints([]);+ setupUpdateSettingEndpoint();+ setupEmbeddableEntitiesEndpoints({+ dashboards: [createMockDashboard({ name: "My cool dashboard" })],+ cards: [createMockCard({ name: "My cool card" })],+ });++ fetchMock.get("path:/api/util/random_token", {+ token: "fake-token",+ });+ setupUserKeyValueEndpoints({+ namespace: "user_acknowledgement",+ key: "upsell-embedded-analytics-js",+ value: true,+ });++ renderWithProviders(<GuestEmbedsSettings />);++ expect(await screen.findAllByText("Guest embeds")).toHaveLength(2); // Title + Card+};++describe("GuestEmbedsSettings", () => {+ it("should show cards with related settings", async () => {+ await setup({ enabled: true });++ const relatedSettingCards = await screen.findAllByTestId(+ "related-setting-card",+ );+ expect(relatedSettingCards).toHaveLength(5);++ expect(await screen.findByText("Security")).toBeInTheDocument();+ expect(await screen.findByText("Databases")).toBeInTheDocument();+ expect(await screen.findByText("People")).toBeInTheDocument();+ expect(await screen.findByText("Permissions")).toBeInTheDocument();+ expect(await screen.findByText("Appearance")).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage/InteractiveEmbeddingUpsellPage.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage/InteractiveEmbeddingUpsellPage.tsxdeleted file mode 100644index fc95274065a..00000000000--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage/InteractiveEmbeddingUpsellPage.tsx+++ /dev/null@@ -1,81 +0,0 @@-import { jt, t } from "ttag";--import { SettingsSection } from "metabase/admin/components/SettingsSection";-import { UpsellEmbeddingButton } from "metabase/admin/upsells/UpsellEmbeddingButton";-import { UpsellGem } from "metabase/admin/upsells/components";-import ExternalLink from "metabase/common/components/ExternalLink";-import { getPlan } from "metabase/common/utils/plan";-import { useSelector } from "metabase/lib/redux";-import { getDocsUrl, getSetting } from "metabase/selectors/settings";-import { Box, Flex, Group, Icon, Text, Title } from "metabase/ui";--export const InteractiveEmbeddingUpsellPage = () => {- const plan = useSelector((state) =>- getPlan(getSetting(state, "token-features")),- );-- const quickStartUrl = useSelector((state) =>- getDocsUrl(state, {- page: "embedding/interactive-embedding-quick-start-guide",- utm: interactiveEmbeddingUtmTags,- }),- );-- return (- <SettingsSection>- <article>- <Flex gap="md" mb="sm" direction="row" align="center">- <Group gap="sm">- <UpsellGem />-- <Title order={3}>{t`Interactive embedding`}</Title>- </Group>- </Flex>-- <Text lh="1.25rem" mb="lg">- {jt`Use interactive embedding when you want to ${(- <ExternalLink- href={`https://www.metabase.com/blog/why-full-app-embedding?utm_source=${plan}&utm_media=embed-settings`}- key="why-full-app-embedding"- >- {t`offer multi-tenant, self-service analytics`}- </ExternalLink>- )} and people want to create their own questions, dashboards, models, and more, all in their own data sandbox.`}- </Text>-- <Flex gap="lg" direction="column" align="flex-start">- <Text- fw="bold"- c="brand"- component="a"- pos="relative"- href={quickStartUrl}- target="_blank"- rel="noreferrer"- >- {t`Check out our Quickstart`}{" "}- <Box ml="sm" top="2.5px" pos="absolute" component="span">- <Icon name="share" aria-hidden />- </Box>- </Text>-- <Group justify="space-between" align="center" w="100%">- <UpsellEmbeddingButton- url="https://www.metabase.com/product/embedded-analytics"- campaign="embedding-interactive"- location="embedding-page"- size="large"- />- </Group>- </Flex>- </article>- </SettingsSection>- );-};--const interactiveEmbeddingUtmTags = {- utm_source: "product",- utm_medium: "docs",- utm_campaign: "embedding-interactive",- utm_content: "embedding-admin",-};diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage/index.ts b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage/index.tsdeleted file mode 100644index 4dcbce7d452..00000000000--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/InteractiveEmbeddingUpsellPage/index.ts+++ /dev/null@@ -1 +0,0 @@-export { InteractiveEmbeddingUpsellPage } from "./InteractiveEmbeddingUpsellPage";diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/NewEmbedButton/NewEmbedButton.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/NewEmbedButton/NewEmbedButton.tsxnew file mode 100644index 00000000000..9e557e7d2bf--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/NewEmbedButton/NewEmbedButton.tsx@@ -0,0 +1,30 @@+import { t } from "ttag";++import { useDispatch } from "metabase/lib/redux";+import type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";+import { setOpenModalWithProps } from "metabase/redux/ui";+import { Button } from "metabase/ui";++export const NewEmbedButton = () => {+ const dispatch = useDispatch();++ return (+ <Button+ variant="brand"+ size="sm"+ onClick={() => {+ const modalProps: Pick<SdkIframeEmbedSetupModalProps, "initialState"> =+ {+ initialState: {+ isGuest: true,+ useExistingUserSession: true,+ },+ };++ dispatch(setOpenModalWithProps({ id: "embed", props: modalProps }));+ }}+ >+ {t`New embed`}+ </Button>+ );+};diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.tsxnew file mode 100644index 00000000000..4340bb71265--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.tsx@@ -0,0 +1,103 @@+import { useMemo } from "react";+import { t } from "ttag";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import { EmbeddingSettingsCard } from "metabase/admin/settings/components/EmbeddingSettings";+import type { EmbeddingSettingKey } from "metabase/admin/settings/components/EmbeddingSettings/EmbeddingToggle";+import { NewEmbedButton } from "metabase/admin/settings/components/EmbeddingSettings/NewEmbedButton/NewEmbedButton";+import { UpsellBanner } from "metabase/admin/upsells/components";+import { useSetting } from "metabase/common/hooks";+import { useSelector } from "metabase/lib/redux";+import {+ PLUGIN_CONTENT_TRANSLATION,+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,+} from "metabase/plugins";+import { getUpgradeUrl } from "metabase/selectors/settings";+import { Box, Text } from "metabase/ui";++import { SettingTitle } from "../../SettingHeader";+import { EmbeddedResources } from "../../widgets/PublicLinksListing/EmbeddedResources";+import { EmbeddingSecretKeyWidget } from "../EmbeddingSecretKeyWidget";+import { CorsInputWidget } from "../EmbeddingSecuritySettings/CorsInputWidget";++type Props = {+ showEmbeddingSdkSettings?: boolean;+ showCorsSettings?: boolean;+ showContentTranslationSettings?: boolean;+};++export function SharedCombinedEmbeddingSettings({+ showCorsSettings,+ showContentTranslationSettings,+}: Props) {+ const isSimpleEmbedFeatureAvailable =+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled();+ const isGuestEmbedsEnabled = useSetting("enable-embedding-static");++ const upgradeUrl = useSelector((state) =>+ getUpgradeUrl(state, { utm_content: "embedding-settings" }),+ );++ const dependentSettingKeys: EmbeddingSettingKey[] = useMemo(+ // When the simple embed feature is not available (oss), we toggle both guest and simple embeds+ () => (isSimpleEmbedFeatureAvailable ? [] : ["enable-embedding-simple"]),+ [isSimpleEmbedFeatureAvailable],+ );++ return (+ <>+ <EmbeddingSettingsCard+ title={t`Guest embeds`}+ description={t`A secure way to embed charts and dashboards when you don’t want to offer ad-hoc querying or chart drill-through.`}+ settingKey="enable-embedding-static"+ actionButton={<NewEmbedButton />}+ dependentSettingKeys={dependentSettingKeys}+ sdk-setting-card+ testId="guest-embeds-setting-card"+ />++ {!isSimpleEmbedFeatureAvailable && (+ <UpsellBanner+ title={t`Upgrade to Metabase Pro for more powerful embedding methods`}+ campaign="embedded-analytics-js"+ location="embedding-page"+ buttonText={t`Upgrade`}+ buttonLink={upgradeUrl}+ dismissible+ >+ <Text c="text-medium" lh="md">+ {t`Embed charts, dashboards with drill-throughs, or even the query builder into your own application using customizable components. Secure your embeds with single sign-on.`}+ </Text>+ </UpsellBanner>+ )}++ <SettingsSection>+ <EmbeddingSecretKeyWidget />+ </SettingsSection>++ {isGuestEmbedsEnabled && (+ <SettingsSection>+ <Box data-testid="embedded-resources">+ <SettingTitle+ id="static-embeds"+ fz="lg"+ mb="md"+ >{t`Published embeds`}</SettingTitle>++ <EmbeddedResources />+ </Box>+ </SettingsSection>+ )}++ {showCorsSettings && (+ <SettingsSection>+ <CorsInputWidget />+ </SettingsSection>+ )}++ {showContentTranslationSettings && (+ <PLUGIN_CONTENT_TRANSLATION.ContentTranslationConfiguration />+ )}+ </>+ );+}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/StaticEmbeddingSettings.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsxsimilarity index 69%rename from frontend/src/metabase/admin/settings/components/EmbeddingSettings/StaticEmbeddingSettings.unit.spec.tsxrename to frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsxindex 799b6af9c7c..e31c2caee56 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/StaticEmbeddingSettings.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsx@@ -7,6 +7,7 @@ import {setupPropertiesEndpoints,setupSettingsEndpoints,setupUpdateSettingEndpoint,+ setupUpdateSettingsEndpoint,setupUserKeyValueEndpoints,} from "__support__/server-mocks";import { renderWithProviders, screen } from "__support__/ui";@@ -16,7 +17,7 @@ import {createMockSettings,} from "metabase-types/api/mocks";-import { StaticEmbeddingSettings } from "./StaticEmbeddingSettings";+import { SharedCombinedEmbeddingSettings } from "./SharedCombinedEmbeddingSettings";const setup = async ({ enabled }: { enabled: boolean }) => {const settings = createMockSettings({ "enable-embedding-static": enabled });@@ -24,6 +25,7 @@ const setup = async ({ enabled }: { enabled: boolean }) => {setupPropertiesEndpoints(settings);setupSettingsEndpoints([]);setupUpdateSettingEndpoint();+ setupUpdateSettingsEndpoint();setupEmbeddableEntitiesEndpoints({dashboards: [createMockDashboard({ name: "My cool dashboard" })],cards: [createMockCard({ name: "My cool card" })],@@ -34,31 +36,21 @@ const setup = async ({ enabled }: { enabled: boolean }) => {});setupUserKeyValueEndpoints({namespace: "user_acknowledgement",- key: "upsell-dev_instances",+ key: "upsell-embedded-analytics-js",value: true,});- renderWithProviders(<StaticEmbeddingSettings />);-- await screen.findByText("Static embedding"); // breadcrumb+ renderWithProviders(<SharedCombinedEmbeddingSettings />);};-describe("StaticEmbeddingSettings", () => {- it("should show embedding toggle", async () => {- await setup({ enabled: true });-- expect(- await screen.findByText("Enable static embedding"),- ).toBeInTheDocument();- });-+describe("SharedCombinedEmbeddingSettings", () => {it("should toggle static embedding on", async () => {await setup({ enabled: false });- await screen.findByText("Enable static embedding");+ await screen.findByText("Guest embeds");const toggle = screen.getByRole("switch", {- name: /Enable static embedding toggle/i,+ name: /Guest embeds toggle/i,});await userEvent.click(toggle);@@ -66,8 +58,11 @@ describe("StaticEmbeddingSettings", () => {const puts = await findRequests("PUT");expect(puts).toHaveLength(1);const [{ url, body }] = puts;- expect(url).toContain("/setting/enable-embedding-static");- expect(body).toEqual({ value: true });+ expect(url).toContain("/setting");+ expect(body).toEqual({+ "enable-embedding-simple": true,+ "enable-embedding-static": true,+ });});it("should show embeddable dashboards and cards when embedding is enabled", async () => {@@ -79,9 +74,7 @@ describe("StaticEmbeddingSettings", () => {it("should hide embeddable dashboards and cards when embedding is disabled", async () => {await setup({ enabled: false });- expect(- await screen.findByText("Enable static embedding"),- ).toBeInTheDocument();+ expect(await screen.findByText("Guest embeds")).toBeInTheDocument();expect(screen.queryByText("Manage embeds")).not.toBeInTheDocument();});@@ -104,16 +97,4 @@ describe("StaticEmbeddingSettings", () => {expect(url).toContain("/setting/embedding-secret-key");expect(body).toEqual({ value: "fake-token" }); // we got this from the mock api});-- it("should show cards with related settings", async () => {- await setup({ enabled: true });-- const relatedSettingCards = await screen.findAllByTestId(- "related-setting-card",- );- expect(relatedSettingCards).toHaveLength(2);-- expect(await screen.findByText("Databases")).toBeInTheDocument();- expect(await screen.findByText("Appearance")).toBeInTheDocument();- });});diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/index.ts b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/index.tsnew file mode 100644index 00000000000..e886cd67484--- /dev/null+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/index.ts@@ -0,0 +1 @@+export * from "./SharedCombinedEmbeddingSettings";diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/StaticEmbeddingSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/StaticEmbeddingSettings.tsxdeleted file mode 100644index 9620e11d959..00000000000--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/StaticEmbeddingSettings.tsx+++ /dev/null@@ -1,57 +0,0 @@-import { t } from "ttag";--import {- RelatedSettingsSection,- getStaticEmbeddingRelatedSettingItems,-} from "metabase/admin/components/RelatedSettingsSection";-import {- SettingsPageWrapper,- SettingsSection,-} from "metabase/admin/components/SettingsSection";-import { UpsellDevInstances } from "metabase/admin/upsells";-import { useSetting } from "metabase/common/hooks";-import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";-import { Box } from "metabase/ui";--import { SettingTitle } from "../SettingHeader";-import { EmbeddedResources } from "../widgets/PublicLinksListing/EmbeddedResources";--import { EmbeddingSecretKeyWidget } from "./EmbeddingSecretKeyWidget";-import { EmbeddingSettingsCard } from "./EmbeddingSettingsCard";--export function StaticEmbeddingSettings() {- const isStaticEmbeddingEnabled = useSetting("enable-embedding-static");-- return (- <SettingsPageWrapper title={t`Static embedding`}>- <EmbeddingSettingsCard- title={t`Enable static embedding`}- description={t`A secure way to embed charts and dashboards when you don’t want to offer ad-hoc querying or chart drill-through.`}- settingKey="enable-embedding-static"- />-- <SettingsSection>- <EmbeddingSecretKeyWidget />- </SettingsSection>-- {isStaticEmbeddingEnabled && (- <SettingsSection>- <Box data-testid="embedded-resources">- <SettingTitle- id="static-embeds"- fz="lg"- mb="md"- >{t`Published embeds`}</SettingTitle>-- <EmbeddedResources />- </Box>- </SettingsSection>- )}-- <PLUGIN_CONTENT_TRANSLATION.ContentTranslationConfiguration />-- <RelatedSettingsSection items={getStaticEmbeddingRelatedSettingItems()} />- <UpsellDevInstances location="embedding-page" />- </SettingsPageWrapper>- );-}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/index.ts b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/index.tsindex 8f994457931..4fd00073c52 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/index.ts+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/index.ts@@ -1,5 +1,5 @@-export { StaticEmbeddingSettings } from "./StaticEmbeddingSettings";-export { EmbeddingSdkSettings } from "./EmbeddingSdkSettings/EmbeddingSdkSettings";+export { GuestEmbedsSettings } from "metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings";+export { EmbeddingSettings } from "metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings";export { EmbeddingSecuritySettings } from "./EmbeddingSecuritySettings";export { EmbeddingSettingsCard } from "./EmbeddingSettingsCard";export { EmbeddingToggle } from "./EmbeddingToggle";diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/setup.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/tests/setup.tsxsimilarity index 86%rename from frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/setup.tsxrename to frontend/src/metabase/admin/settings/components/EmbeddingSettings/tests/setup.tsxindex 6a335dfa643..ab36c4bf6f3 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSdkSettings/tests/setup.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/tests/setup.tsx@@ -9,17 +9,17 @@ import {setupUserKeyValueEndpoints,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { waitFor } from "__support__/ui";import type { Settings, TokenFeatures } from "metabase-types/api";import {createMockSettings,createMockTokenFeatures,} from "metabase-types/api/mocks";+import type { State } from "metabase-types/store";import { createMockState } from "metabase-types/store/mocks";-import { EmbeddingSdkSettings } from "../EmbeddingSdkSettings";-export interface SetupOpts {+ renderCallback: (data: { state: Partial<State> }) => void;showSdkEmbedTerms?: Settings["show-sdk-embed-terms"];isEmbeddingSdkEnabled?: Settings["enable-embedding-sdk"];isEmbeddingSimpleEnabled?: Settings["enable-embedding-simple"];@@ -29,13 +29,14 @@ export interface SetupOpts {}export async function setup({+ renderCallback,showSdkEmbedTerms = true,isEmbeddingSdkEnabled = false,isEmbeddingSimpleEnabled = false,isHosted = false,hasEnterprisePlugins = false,tokenFeatures = {},-}: SetupOpts = {}) {+}: SetupOpts) {const settings = createMockSettings({"show-sdk-embed-terms": showSdkEmbedTerms,"enable-embedding-sdk": isEmbeddingSdkEnabled,@@ -62,11 +63,14 @@ export async function setup({key: "upsell-dev_instances",value: true,});-- renderWithProviders(<EmbeddingSdkSettings />, {- storeInitialState: state,+ setupUserKeyValueEndpoints({+ namespace: "user_acknowledgement",+ key: "upsell-embedded-analytics-js",+ value: true,});+ renderCallback({ state });+await waitFor(async () => {const gets = await findRequests("GET");expect(gets).toEqual(@@ -80,6 +84,4 @@ export async function setup({]),);});-- await screen.findByText("SDK for React");}diff --git a/frontend/src/metabase/admin/upsells/UpsellCacheConfig.tsx b/frontend/src/metabase/admin/upsells/UpsellCacheConfig.tsxindex 8bd7b43005b..3839cf48e85 100644--- a/frontend/src/metabase/admin/upsells/UpsellCacheConfig.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellCacheConfig.tsx@@ -1,10 +1,10 @@import { jt, t } from "ttag";+import { UpsellCard } from "metabase/common/components/UpsellCard";import { useHasTokenFeature } from "metabase/common/hooks/use-has-token-feature";import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";import { Box } from "metabase/ui";-import { UpsellCard } from "./components";import { UPGRADE_URL } from "./constants";export const UpsellCacheConfig = ({ location }: { location: string }) => {diff --git a/frontend/src/metabase/admin/upsells/UpsellEmbedHomepage.tsx b/frontend/src/metabase/admin/upsells/UpsellEmbedHomepage.tsxindex a72090eda2a..fd12429d945 100644--- a/frontend/src/metabase/admin/upsells/UpsellEmbedHomepage.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellEmbedHomepage.tsx@@ -1,8 +1,8 @@import { t } from "ttag";+import { UpsellCard } from "metabase/common/components/UpsellCard";import { Text } from "metabase/ui";-import { UpsellCard } from "./components";import { UPGRADE_URL } from "./constants";const campaign = "advanced-embeds";diff --git a/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsx b/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsxdeleted file mode 100644index 55034591c95..00000000000--- a/frontend/src/metabase/admin/upsells/UpsellEmbedJsCta.tsx+++ /dev/null@@ -1,114 +0,0 @@-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,- 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";-import { trackUpsellClicked } from "./components/analytics";-import { useUpsellLink } from "./components/use-upsell-link";--export function useUpsellEmbedJsCta({- resource,- resourceType,- closeModal,-}: {- resource: EmbedResource;- resourceType: EmbedResourceType;- closeModal: () => void;-}) {- const dispatch = useDispatch();-- const campaign = "embedded-analytics-js";- const location = "static-embed-popover";-- const isEmbedJsEnabled = useHasTokenFeature("embedding_simple");-- const { triggerUpsellFlow } = PLUGIN_ADMIN_SETTINGS.useUpsellFlow({- campaign,- location,- });-- const trackUpsell = () => trackUpsellClicked({ location, campaign });-- const url = useUpsellLink({- url: `https://www.metabase.com/product/embedded-analytics`,- campaign,- location,- });-- if (isEmbedJsEnabled) {- return {- openEmbedFlow: () => {- const modalProps: Pick<SdkIframeEmbedSetupModalProps, "initialState"> =- {- initialState: {- resourceType,- resourceId: resource.id,- },- };-- closeModal();-- dispatch(- setOpenModalWithProps({- id: "embed",- props: modalProps,- }),- );- },- };- }-- return {- url,- triggerUpsellFlow,- trackUpsell,- };-}--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;- }-- return (- <Box>- <UpsellCta- onClick={() => {- if (triggerUpsellFlow) {- triggerUpsellFlow();- } else if (openEmbedFlow) {- openEmbedFlow();- }- }}- internalLink={undefined}- buttonText={t`Try for free`}- url={url}- onClickCapture={() => trackUpsell?.()}- size="large"- />- </Box>- );-}diff --git a/frontend/src/metabase/admin/upsells/UpsellEmbeddingButton.tsx b/frontend/src/metabase/admin/upsells/UpsellEmbeddingButton.tsxdeleted file mode 100644index ea3eb41a616..00000000000--- a/frontend/src/metabase/admin/upsells/UpsellEmbeddingButton.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { t } from "ttag";--import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";--import { UpsellCta } from "./components/UpsellCta";-import { useUpsellLink } from "./components/use-upsell-link";--export const UpsellEmbeddingButton = ({- url,- campaign,- location,- size = "default",-}: {- url: string;- campaign: string;- location: string;- size?: "default" | "large";-}) => {- const upsellLink = useUpsellLink({- url,- campaign,- location,- });-- const { triggerUpsellFlow } = PLUGIN_ADMIN_SETTINGS.useUpsellFlow({- campaign,- location,- });-- return (- <UpsellCta- onClick={triggerUpsellFlow}- buttonText={t`Try for free`}- url={upsellLink}- internalLink={undefined}- onClickCapture={() => {}}- size={size}- />- );-};diff --git a/frontend/src/metabase/admin/upsells/UpsellHosting.tsx b/frontend/src/metabase/admin/upsells/UpsellHosting.tsxindex c35302a2679..39d38746b09 100644--- a/frontend/src/metabase/admin/upsells/UpsellHosting.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellHosting.tsx@@ -1,10 +1,11 @@import { jt, t } from "ttag";const RocketGlobeIllustrationSrc = "app/assets/img/rocket-globe.svg";+import { UpsellCard } from "metabase/common/components/UpsellCard";import { useSelector } from "metabase/lib/redux";import { getIsHosted } from "metabase/setup/selectors";-import { UpsellBanner, UpsellCard } from "./components";+import { UpsellBanner } from "./components";// the default 200px width will break the title into two linesconst UPSELL_CARD_WIDTH = 202;diff --git a/frontend/src/metabase/admin/upsells/UpsellMetabaseBanner.tsx b/frontend/src/metabase/admin/upsells/UpsellMetabaseBanner.tsxindex 416a22d2269..1767b24fa51 100644--- a/frontend/src/metabase/admin/upsells/UpsellMetabaseBanner.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellMetabaseBanner.tsx@@ -1,6 +1,6 @@import { t } from "ttag";-import { UpsellCard } from "metabase/admin/upsells/components";+import { UpsellCard } from "metabase/common/components/UpsellCard";import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";import { UPGRADE_URL } from "./constants";@@ -22,7 +22,7 @@ export function UpsellMetabaseBanner() {fullWidthonClick={triggerUpsellFlow}>- {t`The “Powered by Metabase” banner appears on all static embeds created with your current version. Upgrade to remove it (and customize a lot more)`}+ {t`The “Powered by Metabase” banner appears on all guest embeds created with your current version. Upgrade to remove it (and customize a lot more)`}</UpsellCard>);}diff --git a/frontend/src/metabase/admin/upsells/UpsellSSO.tsx b/frontend/src/metabase/admin/upsells/UpsellSSO.tsxindex d02dc56adba..c48cd9f697d 100644--- a/frontend/src/metabase/admin/upsells/UpsellSSO.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellSSO.tsx@@ -1,12 +1,12 @@import { t } from "ttag";+import { UpsellCard } from "metabase/common/components/UpsellCard";import { hasAnySsoFeature } from "metabase/common/utils/plan";import { useSelector } from "metabase/lib/redux";import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";import { getSetting } from "metabase/selectors/settings";import { Box, List } from "metabase/ui";-import { UpsellCard } from "./components";import { UPGRADE_URL } from "./constants";export const UpsellSSO = ({ location }: { location: string }) => {diff --git a/frontend/src/metabase/admin/upsells/UpsellUploads.tsx b/frontend/src/metabase/admin/upsells/UpsellUploads.tsxindex c31e8f6ec08..6b58a810c43 100644--- a/frontend/src/metabase/admin/upsells/UpsellUploads.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellUploads.tsx@@ -1,11 +1,11 @@import { c, t } from "ttag";+import { UpsellCard } from "metabase/common/components/UpsellCard";import { getPlan } from "metabase/common/utils/plan";import { useSelector } from "metabase/lib/redux";import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";import { getSetting } from "metabase/selectors/settings";-import { UpsellCard } from "./components";import { UPGRADE_URL } from "./constants";export const UpsellUploads = ({ location }: { location: string }) => {diff --git a/frontend/src/metabase/admin/upsells/UpsellUsageAnalytics.tsx b/frontend/src/metabase/admin/upsells/UpsellUsageAnalytics.tsxindex 9a1d0f45773..02b710f6825 100644--- a/frontend/src/metabase/admin/upsells/UpsellUsageAnalytics.tsx+++ b/frontend/src/metabase/admin/upsells/UpsellUsageAnalytics.tsx@@ -1,12 +1,15 @@import { t } from "ttag";import ExternalLink from "metabase/common/components/ExternalLink";+import {+ UpsellCard,+ type UpsellCardProps,+} from "metabase/common/components/UpsellCard";import { useSelector } from "metabase/lib/redux";import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";import { getDocsUrl } from "metabase/selectors/settings";import { Box, type BoxProps, Text } from "metabase/ui";-import { UpsellCard, type UpsellCardProps } from "./components";import { UPGRADE_URL } from "./constants";const usageAnalyticsIllustrationSource = "app/assets/img/usage-analytics.png";diff --git a/frontend/src/metabase/admin/upsells/components/UpsellGem.tsx b/frontend/src/metabase/admin/upsells/components/UpsellGem.tsxindex fc59e739f3e..922910f2353 100644--- a/frontend/src/metabase/admin/upsells/components/UpsellGem.tsx+++ b/frontend/src/metabase/admin/upsells/components/UpsellGem.tsx@@ -3,5 +3,11 @@ import { Icon, type IconProps } from "metabase/ui";import S from "./UpsellGem.module.css";export const UpsellGem = (props: Omit<IconProps, "name" | "color">) => (- <Icon size={16} name="gem" className={S.UpsellGem} {...props} />+ <Icon+ data-testid="upsell-gem"+ size={16}+ name="gem"+ className={S.UpsellGem}+ {...props}+ />);diff --git a/frontend/src/metabase/admin/upsells/components/index.ts b/frontend/src/metabase/admin/upsells/components/index.tsindex 9ed9238a204..ae3ec947250 100644--- a/frontend/src/metabase/admin/upsells/components/index.ts+++ b/frontend/src/metabase/admin/upsells/components/index.ts@@ -1,5 +1,4 @@export * from "./UpsellBanner";export * from "./UpsellBigCard";-export * from "./UpsellCard";export * from "./UpsellPill";export { UpsellGem } from "./UpsellGem";diff --git a/frontend/src/metabase/api/session.ts b/frontend/src/metabase/api/session.tsindex f95045cdf7f..577b14e9906 100644--- a/frontend/src/metabase/api/session.ts+++ b/frontend/src/metabase/api/session.ts@@ -8,6 +8,8 @@ import type {import { Api } from "./api";import { handleQueryFulfilled } from "./utils/lifecycle";+export const sessionPropertiesPath = "/api/session/properties";+export const sessionApi = Api.injectEndpoints({endpoints: (builder) => ({getPasswordResetTokenStatus: builder.query<@@ -30,7 +32,7 @@ export const sessionApi = Api.injectEndpoints({getSessionProperties: builder.query<EnterpriseSettings, void>({query: () => ({method: "GET",- url: "/api/session/properties",+ url: sessionPropertiesPath,}),providesTags: ["session-properties"],onQueryStarted: (_, { queryFulfilled, dispatch }) =>diff --git a/frontend/src/metabase/api/utils/settings.ts b/frontend/src/metabase/api/utils/settings.tsindex a63aa19ab9a..cc73db8c368 100644--- a/frontend/src/metabase/api/utils/settings.ts+++ b/frontend/src/metabase/api/utils/settings.ts@@ -1,4 +1,4 @@-import { useCallback } from "react";+import { useCallback, useMemo } from "react";import { t } from "ttag";import { useToast } from "metabase/common/hooks";@@ -6,6 +6,7 @@ import type {EnterpriseSettingKey,EnterpriseSettingValue,EnterpriseSettings,+ SettingDefinition,} from "metabase-types/api";import { useGetSettingsQuery } from "../session";@@ -106,3 +107,87 @@ export const useAdminSetting = <SettingName extends EnterpriseSettingKey>(...apiProps,};};++/**+ * Hook to get setting values and mutators for multiple settings+ */+export const useAdminSettings = <+ SettingNames extends readonly EnterpriseSettingKey[],+>(+ settingNames: SettingNames,+) => {+ const {+ data: settings,+ isLoading: settingsLoading,+ ...apiProps+ } = useGetSettingsQuery();+ const { data: settingsDetails, isLoading: detailsLoading } =+ useGetAdminSettingsDetailsQuery();+ const [updateSettings, updateSettingsResult] = useUpdateSettingsMutation();++ const [sendToast] = useToast();++ const handleUpdateSettings = useCallback(+ async ({+ toast = true,+ ...settings+ }: {+ toast?: boolean;+ } & Partial<EnterpriseSettings>) => {+ const response = await updateSettings(settings);++ if (!toast) {+ return response;+ }++ if (response.error) {+ const message =+ (response.error as { data?: { message: string } })?.data?.message ||+ t`Error saving settings`;++ sendToast({ message, icon: "warning", toastColor: "danger" });+ } else {+ sendToast({ message: t`Changes saved`, icon: "check_filled" });+ }+ return response;+ },+ [updateSettings, sendToast],+ );++ const values = useMemo(() => {+ if (!settings) {+ return {} as Record<SettingNames[number], boolean>;+ }++ return settingNames.reduce(+ (acc, key) => {+ acc[key as SettingNames[number]] = !!settings[key];+ return acc;+ },+ {} as Record<SettingNames[number], boolean>,+ );+ }, [settings, settingNames]);++ const details = useMemo(() => {+ if (!settingsDetails) {+ return {} as Record<SettingNames[number], SettingDefinition>;+ }++ return settingNames.reduce(+ (acc, key) => {+ acc[key as SettingNames[number]] = settingsDetails[key];+ return acc;+ },+ {} as Record<SettingNames[number], SettingDefinition>,+ );+ }, [settingsDetails, settingNames]);++ return {+ values,+ details,+ updateSettings: handleUpdateSettings,+ updateSettingsResult,+ isLoading: settingsLoading || detailsLoading,+ ...apiProps,+ };+};diff --git a/frontend/src/metabase/api/utils/settings.unit.spec.tsx b/frontend/src/metabase/api/utils/settings.unit.spec.tsxindex b68885d5b5e..cb890709ee7 100644--- a/frontend/src/metabase/api/utils/settings.unit.spec.tsx+++ b/frontend/src/metabase/api/utils/settings.unit.spec.tsx@@ -5,6 +5,7 @@ import {setupPropertiesEndpoints,setupSettingsEndpoints,setupUpdateSettingEndpoint,+ setupUpdateSettingsEndpoint,} from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";import {@@ -12,7 +13,7 @@ import {createMockSettings,} from "metabase-types/api/mocks";-import { useAdminSetting } from "./settings";+import { useAdminSetting, useAdminSettings } from "./settings";const TestComponent = () => {const { value, settingDetails, updateSetting, isLoading } =@@ -39,6 +40,53 @@ const TestComponent = () => {);};+const TestMultipleSettingsComponent = () => {+ const { values, details, updateSettings, isLoading } = useAdminSettings([+ "site-name",+ "site-url",+ ] as const);++ if (isLoading) {+ return <div>Loading...</div>;+ }++ return (+ <div>+ <div data-testid="values">{JSON.stringify(values)}</div>+ <div data-testid="details">{JSON.stringify(details)}</div>+ <button+ onClick={async () => {+ await updateSettings({ "site-name": "Updated Site Name" });+ }}+ >+ change site name+ </button>+ </div>+ );+};++const setupMultipleSettings = async () => {+ setupPropertiesEndpoints(+ createMockSettings({+ "site-name": "Metabased",+ "site-url": "https://metabase.com",+ }),+ );+ setupSettingsEndpoints([+ createMockSettingDefinition({+ key: "site-name",+ is_env_setting: true,+ env_name: "MB_SPECIAL_SITE_NAME",+ }),+ createMockSettingDefinition({+ key: "site-url",+ is_env_setting: false,+ }),+ ]);+ setupUpdateSettingsEndpoint();+ renderWithProviders(<TestMultipleSettingsComponent />);+};+const setup = async () => {setupPropertiesEndpoints(createMockSettings({ "site-name": "Metabased" }));setupSettingsEndpoints([@@ -95,3 +143,46 @@ describe("useAdminSetting", () => {expect(putCall?.request?.url).toContain("/api/setting/site-name");});});++describe("useAdminSettings", () => {+ it("should have loading state", async () => {+ await setupMultipleSettings();++ expect(screen.getByText("Loading...")).toBeInTheDocument();++ await waitFor(async () => {+ expect(screen.queryByText("Loading...")).not.toBeInTheDocument();+ });+ });++ it("should get multiple setting values", async () => {+ await setupMultipleSettings();++ const valuesElement = await screen.findByTestId("values");++ expect(valuesElement).toHaveTextContent(+ JSON.stringify({ "site-name": true, "site-url": true }),+ );+ });++ it("should get multiple setting details", async () => {+ await setupMultipleSettings();++ const detailsElement = await screen.findByTestId("details");++ expect(detailsElement).toHaveTextContent(/site\-name/);+ expect(detailsElement).toHaveTextContent(/site\-url/);+ expect(detailsElement).toHaveTextContent(/MB_SPECIAL_SITE_NAME/);+ });++ it("should allow setting mutation", async () => {+ await setupMultipleSettings();+ const updateButton = await screen.findByText("change site name");++ await userEvent.click(updateButton);++ const apiCalls = fetchMock.callHistory.calls();+ const putCall = apiCalls.find((call) => call.request?.method === "PUT");+ expect(putCall?.request?.url).toMatch(/\/api\/setting/);+ });+});diff --git a/frontend/src/metabase/app-embed-sdk.tsx b/frontend/src/metabase/app-embed-sdk.tsxindex 19f93d46f18..41e3895ef1c 100644--- a/frontend/src/metabase/app-embed-sdk.tsx+++ b/frontend/src/metabase/app-embed-sdk.tsx@@ -5,7 +5,7 @@ import "metabase/lib/csp";// Import the embedding SDK vendors side-effectsimport "metabase/embedding-sdk/vendors-side-effects";-+// eslint-disable-next-line import/orderimport {EMBEDDING_SDK_CONFIG,EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG,@@ -23,7 +23,9 @@ EMBEDDING_SDK_CONFIG.tokenFeatureKey = "embedding_simple";// load the embedding_iframe_sdk EE pluginimport "sdk-iframe-embedding-ee-plugins";-import { PLUGIN_EMBEDDING_IFRAME_SDK } from "./plugins";+// Must be imported after the EE plugins are loaded+// eslint-disable-next-line import/order+import { SdkIframeEmbedRoute } from "metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute";function _init() {document.body.style.margin = "0";@@ -36,9 +38,7 @@ function _init() {return;}- createRoot(rootElement).render(- <PLUGIN_EMBEDDING_IFRAME_SDK.SdkIframeEmbedRoute />,- );+ createRoot(rootElement).render(<SdkIframeEmbedRoute />);}if (document.readyState !== "loading") {diff --git a/frontend/src/metabase/admin/upsells/components/UpsellCard.mdx b/frontend/src/metabase/common/components/UpsellCard/UpsellCard.mdxsimilarity index 100%rename from frontend/src/metabase/admin/upsells/components/UpsellCard.mdxrename to frontend/src/metabase/common/components/UpsellCard/UpsellCard.mdxdiff --git a/frontend/src/metabase/admin/upsells/components/UpsellCard.module.css b/frontend/src/metabase/common/components/UpsellCard/UpsellCard.module.csssimilarity index 82%rename from frontend/src/metabase/admin/upsells/components/UpsellCard.module.cssrename to frontend/src/metabase/common/components/UpsellCard/UpsellCard.module.cssindex 436cb0713a2..90d8d6c788d 100644--- a/frontend/src/metabase/admin/upsells/components/UpsellCard.module.css+++ b/frontend/src/metabase/common/components/UpsellCard/UpsellCard.module.css@@ -1,4 +1,4 @@-@import "./Upsells.base.module.css";+@import "../../../admin/upsells/components/Upsells.base.module.css";.UpsellCardComponent {border-radius: 0.5rem;diff --git a/frontend/src/metabase/admin/upsells/components/UpsellCard.stories.tsx b/frontend/src/metabase/common/components/UpsellCard/UpsellCard.stories.tsxsimilarity index 100%rename from frontend/src/metabase/admin/upsells/components/UpsellCard.stories.tsxrename to frontend/src/metabase/common/components/UpsellCard/UpsellCard.stories.tsxdiff --git a/frontend/src/metabase/admin/upsells/components/UpsellCard.tsx b/frontend/src/metabase/common/components/UpsellCard/UpsellCard.tsxsimilarity index 83%rename from frontend/src/metabase/admin/upsells/components/UpsellCard.tsxrename to frontend/src/metabase/common/components/UpsellCard/UpsellCard.tsxindex 356bf246f0e..35c922f6c9f 100644--- a/frontend/src/metabase/admin/upsells/components/UpsellCard.tsx+++ b/frontend/src/metabase/common/components/UpsellCard/UpsellCard.tsx@@ -3,14 +3,17 @@ import { useMount } from "react-use";import { Box, Flex, Image, Stack, Text, Title } from "metabase/ui";-import { UPGRADE_URL } from "../constants";+import { UpsellCta } from "../../../admin/upsells/components/UpsellCta";+import { UpsellGem } from "../../../admin/upsells/components/UpsellGem";+import { UpsellWrapper } from "../../../admin/upsells/components/UpsellWrapper";+import {+ trackUpsellClicked,+ trackUpsellViewed,+} from "../../../admin/upsells/components/analytics";+import { useUpsellLink } from "../../../admin/upsells/components/use-upsell-link";+import { UPGRADE_URL } from "../../../admin/upsells/constants";import S from "./UpsellCard.module.css";-import { UpsellCta } from "./UpsellCta";-import { UpsellGem } from "./UpsellGem";-import { UpsellWrapper } from "./UpsellWrapper";-import { trackUpsellClicked, trackUpsellViewed } from "./analytics";-import { useUpsellLink } from "./use-upsell-link";type CardWidthProps =| {diff --git a/frontend/src/metabase/common/components/UpsellCard/index.ts b/frontend/src/metabase/common/components/UpsellCard/index.tsnew file mode 100644index 00000000000..c58ccdcf18b--- /dev/null+++ b/frontend/src/metabase/common/components/UpsellCard/index.ts@@ -0,0 +1 @@+export * from "./UpsellCard";diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsxindex 89b096b2c0f..d88a08a1b03 100644--- a/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx@@ -115,6 +115,7 @@ function DashCardInner({isEditingParameter,navigateToNewCardFromDashboard,reportAutoScrolledToDashcard,+ isGuestEmbed,} = useDashboardContext();const dashcardData = useSelector((state) =>@@ -206,7 +207,10 @@ function DashCardInner({return { expectedDuration, isSlow };}, [series, isLoading]);- const error = useMemo(() => getDashcardResultsError(series), [series]);+ const error = useMemo(+ () => getDashcardResultsError(series, !!isGuestEmbed),+ [series, isGuestEmbed],+ );const hasError = !!error;const gridSize = useMemo(diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsxindex f01d9da8b71..4808c04c750 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx@@ -35,9 +35,12 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {const [modalOpened, { open: openModal, close: closeModal }] = useDisclosure();const dispatch = useDispatch();+ const { isGuestEmbed } = useDashboardContext();useMount(() => {- dispatch(fetchPulseFormInput());+ if (!isGuestEmbed) {+ dispatch(fetchPulseFormInput());+ }});const isEditing = useSelector(getIsEditing);@@ -54,7 +57,12 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {);const { data: collection, isLoading: isLoadingCollection } =- useGetCollectionQuery({ id: dashboard.collection_id || "root" });+ useGetCollectionQuery(+ { id: dashboard.collection_id || "root" },+ {+ skip: isGuestEmbed,+ },+ );const onRequestCancel = () => {if (isDirty && isEditing) {@@ -103,12 +111,15 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {];};- if (isLoadingCollection || !collection) {- return (- <Flex justify="center" py="1.5rem">- <Loader size={29} />- </Flex>- );+ // We don't fetch collection info for static embedding+ if (!isGuestEmbed) {+ if (isLoadingCollection || !collection) {+ return (+ <Flex justify="center" py="1.5rem">+ <Loader size={29} />+ </Flex>+ );+ }}const hasLastEditInfo = dashboard["last-edit-info"] != null;diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderView.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderView.tsxindex 8585f4054aa..0e87170b681 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderView.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderView.tsx@@ -41,7 +41,7 @@ type DashboardHeaderViewProps = {editingButtons?: JSX.Element[];editWarning?: string;dashboard: IDashboard;- collection: Collection;+ collection: Collection | undefined;isBadgeVisible: boolean;isLastEditInfoVisible: boolean;onLastEditInfoClick?: () => void;@@ -159,11 +159,13 @@ export function DashboardHeaderView({<PLUGIN_MODERATION.EntityModerationIconmoderationReviews={dashboard.moderation_reviews}/>- <PLUGIN_COLLECTION_COMPONENTS.CollectionInstanceAnalyticsIcon- color="brand"- collection={collection}- entity="dashboard"- />+ {!!collection && (+ <PLUGIN_COLLECTION_COMPONENTS.CollectionInstanceAnalyticsIcon+ color="brand"+ collection={collection}+ entity="dashboard"+ />+ )}</Flex></Flex><Flex className={S.HeaderBadges}>diff --git a/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsx b/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsxindex 5b92b5a85f0..3d1e5ef1d41 100644--- a/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsx@@ -52,6 +52,7 @@ export const DashboardParameterList = forwardRef<hideParameters,parameters: dashboardParameters,parameterValues,+ token,} = useDashboardContext();const linkedFilterParameters = useMemo(@@ -72,6 +73,7 @@ export const DashboardParameterList = forwardRef<editingParameter={editingParameter}hideParameters={hideParameters}dashboardId={dashboard?.id}+ token={token}isSortable={isSortable}isFullscreen={isFullscreen}isEditing={isEditing}diff --git a/frontend/src/metabase/dashboard/components/DashboardTitle/DashboardTitle.tsx b/frontend/src/metabase/dashboard/components/DashboardTitle/DashboardTitle.tsxindex 9669c29a08a..489ee5c8ef6 100644--- a/frontend/src/metabase/dashboard/components/DashboardTitle/DashboardTitle.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardTitle/DashboardTitle.tsx@@ -4,10 +4,12 @@ import EditableText from "metabase/common/components/EditableText";import { DASHBOARD_NAME_MAX_LENGTH } from "metabase/dashboard/constants";import { useDashboardContext } from "metabase/dashboard/context";import { useDashboardTitle } from "metabase/dashboard/hooks/use-dashboard-title";+import { useTranslateContent } from "metabase/i18n/hooks";export const DashboardTitle = ({ className }: { className?: string }) => {const [title, setTitle] = useDashboardTitle();const { dashboard, isEditableDashboard } = useDashboardContext();+ const tc = useTranslateContent();if (!dashboard) {return null;@@ -17,7 +19,7 @@ export const DashboardTitle = ({ className }: { className?: string }) => {<EditableTextclassName={className}key={title}- initialValue={title}+ initialValue={tc(title)}placeholder={t`Add title`}isDisabled={!isEditableDashboard}data-testid="dashboard-name-heading"diff --git a/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx b/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsxindex 32f9ffa427a..d7eeca45f5e 100644--- a/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx+++ b/frontend/src/metabase/dashboard/containers/DashboardSharingEmbeddingModal/DashboardSharingEmbeddingModal.tsx@@ -1,79 +1,57 @@import {- useCreateDashboardPublicLinkMutation,- useDeleteDashboardPublicLinkMutation,useUpdateDashboardEmbeddingParamsMutation,useUpdateDashboardEnableEmbeddingMutation,} from "metabase/api";import { getParameters } from "metabase/dashboard/selectors";import { STATIC_LEGACY_EMBEDDING_TYPE } from "metabase/embedding/constants";import { useSelector } from "metabase/lib/redux";-import * as Urls from "metabase/lib/urls";-import {- EmbedModal,- EmbedModalContent,-} from "metabase/public/components/EmbedModal";+import { EmbedModal } from "metabase/public/components/EmbedModal";import type { Dashboard } from "metabase-types/api";export type DashboardSharingEmbeddingModalProps = {- className?: string;dashboard: Dashboard;isOpen: boolean;+ onBack?: () => void;onClose: () => void;};export const DashboardSharingEmbeddingModal = ({- className,dashboard,isOpen,+ onBack,onClose,}: DashboardSharingEmbeddingModalProps) => {const parameters = useSelector(getParameters);- const [createPublicDashboardLink] = useCreateDashboardPublicLinkMutation();- const [deletePublicDashboardLink] = useDeleteDashboardPublicLinkMutation();const [updateDashboardEmbeddingParams] =useUpdateDashboardEmbeddingParamsMutation();const [updateDashboardEnableEmbedding] =useUpdateDashboardEnableEmbeddingMutation();- const getPublicUrl = (publicUuid: string) => Urls.publicDashboard(publicUuid);-return (- <EmbedModal isOpen={isOpen} onClose={onClose}>- {({ embedType, goToNextStep }) => (- <EmbedModalContent- embedType={embedType}- goToNextStep={goToNextStep}- className={className}- resource={dashboard}- resourceParameters={parameters}- resourceType="dashboard"- onCreatePublicLink={() =>- createPublicDashboardLink({ id: dashboard.id })- }- onDeletePublicLink={() =>- deletePublicDashboardLink({ id: dashboard.id })- }- onUpdateEnableEmbedding={(enable_embedding) =>- updateDashboardEnableEmbedding({- id: dashboard.id,- enable_embedding,- embedding_type: enable_embedding- ? STATIC_LEGACY_EMBEDDING_TYPE- : null,- })- }- onUpdateEmbeddingParams={(embedding_params) =>- updateDashboardEmbeddingParams({- id: dashboard.id,- embedding_params,- embedding_type: STATIC_LEGACY_EMBEDDING_TYPE,- })- }- getPublicUrl={getPublicUrl}- onClose={onClose}- />- )}- </EmbedModal>+ <EmbedModal+ isOpen={isOpen}+ resource={dashboard}+ resourceParameters={parameters}+ resourceType="dashboard"+ onUpdateEnableEmbedding={(enable_embedding) =>+ updateDashboardEnableEmbedding({+ id: dashboard.id,+ enable_embedding,+ embedding_type: enable_embedding+ ? STATIC_LEGACY_EMBEDDING_TYPE+ : null,+ })+ }+ onUpdateEmbeddingParams={(embedding_params) =>+ updateDashboardEmbeddingParams({+ id: dashboard.id,+ embedding_params,+ embedding_type: STATIC_LEGACY_EMBEDDING_TYPE,+ })+ }+ onBack={onBack}+ onClose={onClose}+ />);};diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsxindex 71daf494ffc..67cc766c93b 100644--- a/frontend/src/metabase/dashboard/context/context.tsx+++ b/frontend/src/metabase/dashboard/context/context.tsx@@ -51,6 +51,7 @@ type DashboardActionButtonList = DashboardActionKey[] | null;export type DashboardContextOwnProps = {dashboardId: DashboardId;+ token?: string | null;parameterQueryParams?: ParameterValuesMap;onLoad?: (dashboard: Dashboard) => void;onError?: (error: unknown) => void;@@ -70,6 +71,7 @@ export type DashboardContextOwnProps = {"isEditing" | "downloadsEnabled">) => DashboardActionButtonList);isDashcardVisible?: (dc: DashboardCard) => boolean;+ isGuestEmbed?: boolean;/*** I want this to be optional, and error out when it's not passed, so it's obvious we need to pass it.* Forcing passing it isn't ideal since we only need to do this in a couple of places@@ -117,6 +119,7 @@ const DashboardContextProviderInner = forwardRef(function DashboardContextProviderInner({dashboardId,+ token,parameterQueryParams = {},onLoad,onLoadWithoutCards,@@ -151,6 +154,7 @@ const DashboardContextProviderInner = forwardRef(isLoadingWithoutCards,parameters,isEmbeddingIframe,+ isGuestEmbed,// redux actionsaddCardToDashboard,@@ -199,7 +203,16 @@ const DashboardContextProviderInner = forwardRef();const fetchData = useCallback(- async (dashboardId: DashboardId, option: FetchOption = {}) => {+ async (+ {+ dashboardId,+ token,+ }: {+ dashboardId: DashboardId;+ token: string | null | undefined;+ },+ option: FetchOption = {},+ ) => {const hasDashboardChanged = dashboardId !== previousDashboardId;const { forceRefetch } = option;// When forcing a refetch, we want to clear the cache@@ -210,7 +223,7 @@ const DashboardContextProviderInner = forwardRef(initialize({ clearCache: !effectiveIsNavigatingBackToDashboard });fetchDashboard({- dashId: dashboardId,+ dashId: token ?? dashboardId,queryParams: parameterQueryParams,options: {clearCache: !effectiveIsNavigatingBackToDashboard,@@ -266,20 +279,26 @@ const DashboardContextProviderInner = forwardRef(return {refetchDashboard() {if (dashboardId) {- fetchData(dashboardId, {- forceRefetch: true,- });+ fetchData(+ {+ dashboardId,+ token,+ },+ {+ forceRefetch: true,+ },+ );}},};- }, [dashboardId, fetchData]);+ }, [dashboardId, token, fetchData]);useEffect(() => {if (dashboardId && dashboardId !== previousDashboardId) {reset();- fetchData(dashboardId);+ fetchData({ dashboardId, token });}- }, [dashboardId, fetchData, previousDashboardId, reset]);+ }, [dashboardId, token, fetchData, previousDashboardId, reset]);useEffect(() => {if (dashboard) {@@ -370,6 +389,7 @@ const DashboardContextProviderInner = forwardRef(<DashboardContext.Providervalue={{dashboardId,+ token,dashboard: dashboardWithFilteredCards,parameterQueryParams,onLoad,@@ -410,6 +430,7 @@ const DashboardContextProviderInner = forwardRef(parameters,parameterValues,isEmbeddingIframe,+ isGuestEmbed,// redux actionsaddCardToDashboard,diff --git a/frontend/src/metabase/dashboard/utils.ts b/frontend/src/metabase/dashboard/utils.tsindex 7563a4a4fb8..87b3939982d 100644--- a/frontend/src/metabase/dashboard/utils.ts+++ b/frontend/src/metabase/dashboard/utils.ts@@ -2,6 +2,8 @@ import type { Location } from "history";import _ from "underscore";import { SERVER_ERROR_TYPES } from "metabase/lib/errors";+import { isStaticEmbeddingEntityLoadingError } from "metabase/lib/errors/is-static-embedding-entity-loading-error";+import type { StaticEmbeddingEntityError } from "metabase/lib/errors/types";import { isJWT } from "metabase/lib/utils";import { isUuid } from "metabase/lib/uuid";import {@@ -284,7 +286,10 @@ export function isDashcardLoading(return cardData.length === 0 || cardData.some((data) => data == null);}-export function getDashcardResultsError(datasets: Dataset[]) {+export function getDashcardResultsError(+ datasets: Dataset[],+ isGuestEmbed: boolean,+) {const isAccessRestricted = datasets.some((s) =>s.error_type === SERVER_ERROR_TYPES.missingPermissions ||@@ -298,6 +303,19 @@ export function getDashcardResultsError(datasets: Dataset[]) {};}+ const staticEntityLoadingError = datasets.find((dataset) =>+ isStaticEmbeddingEntityLoadingError(dataset.error, {+ isGuestEmbed,+ }),+ )?.error as StaticEmbeddingEntityError | undefined;++ if (staticEntityLoadingError) {+ return {+ message: staticEntityLoadingError.data,+ icon: "warning" as const,+ };+ }+if (datasets.some((dataset) => dataset.error)) {const curatedErrorDataset = datasets.find((dataset) => dataset.error && dataset.error_is_curated,@@ -357,7 +375,7 @@ const shouldHideCard = (return (!hasRows(dashcardData) &&- !getDashcardResultsError(Object.values(dashcardData))+ !getDashcardResultsError(Object.values(dashcardData), false));};diff --git a/frontend/src/metabase/dashboard/utils.unit.spec.ts b/frontend/src/metabase/dashboard/utils.unit.spec.tsindex 82325a545f6..4752e652715 100644--- a/frontend/src/metabase/dashboard/utils.unit.spec.ts+++ b/frontend/src/metabase/dashboard/utils.unit.spec.ts@@ -196,6 +196,8 @@ describe("Dashboard utils", () => {});describe("getDashcardResultsError", () => {+ const isGuestEmbed = false;+const expectedPermissionError = {icon: "key",message: "Sorry, you don't have permission to see this card.",@@ -207,48 +209,60 @@ describe("Dashboard utils", () => {};it("should return the access restricted error when the error type is missing-required-permissions", () => {- const error = getDashcardResultsError([- createMockDataset({- error_type: SERVER_ERROR_TYPES.missingPermissions,- }),- ]);+ const error = getDashcardResultsError(+ [+ createMockDataset({+ error_type: SERVER_ERROR_TYPES.missingPermissions,+ }),+ ],+ isGuestEmbed,+ );expect(error).toStrictEqual(expectedPermissionError);});it("should return the access restricted error when the status code is 403", () => {- const error = getDashcardResultsError([- createMockDataset({- error: {- status: 403,- },- }),- ]);+ const error = getDashcardResultsError(+ [+ createMockDataset({+ error: {+ status: 403,+ },+ }),+ ],+ isGuestEmbed,+ );expect(error).toStrictEqual(expectedPermissionError);});it("should return a generic error if a dataset has an error", () => {- const error = getDashcardResultsError([- createMockDataset({}),- createMockDataset({- error: {- status: 401,- },- }),- ]);+ const error = getDashcardResultsError(+ [+ createMockDataset({}),+ createMockDataset({+ error: {+ status: 401,+ },+ }),+ ],+ isGuestEmbed,+ );expect(error).toStrictEqual(expectedGenericError);});it("should return a curated error in case it is set in the response", () => {- const error = getDashcardResultsError([- createMockDataset({}),- createMockDataset({- error: "Wrong query",- error_is_curated: true,- }),- ]);+ const error = getDashcardResultsError(+ [+ createMockDataset({}),+ createMockDataset({+ error: "Wrong query",+ error_is_curated: true,+ }),+ ],+ isGuestEmbed,+ );expect(error).toEqual({icon: "warning",@@ -257,30 +271,39 @@ describe("Dashboard utils", () => {});it("should return a generic error in case the error is curated but is not a string", () => {- const error = getDashcardResultsError([- createMockDataset({}),- createMockDataset({- error: { status: 500 },- error_is_curated: true,- }),- ]);+ const error = getDashcardResultsError(+ [+ createMockDataset({}),+ createMockDataset({+ error: { status: 500 },+ error_is_curated: true,+ }),+ ],+ isGuestEmbed,+ );expect(error).toEqual(expectedGenericError);});it("should not return any errors if there are no any errors", () => {- const error = getDashcardResultsError([createMockDataset({})]);+ const error = getDashcardResultsError(+ [createMockDataset({})],+ isGuestEmbed,+ );expect(error).toBeUndefined();});it("should not return any errors if the error is curated but there is no error message or object set", () => {- const error = getDashcardResultsError([- createMockDataset({- error: undefined,- error_is_curated: true,- }),- ]);+ const error = getDashcardResultsError(+ [+ createMockDataset({+ error: undefined,+ error_is_curated: true,+ }),+ ],+ isGuestEmbed,+ );expect(error).toBeUndefined();});diff --git a/frontend/src/metabase/embedding/components/EmbeddingFooter/EmbeddingFooter.module.css b/frontend/src/metabase/embedding/components/EmbeddingFooter/EmbeddingFooter.module.cssnew file mode 100644index 00000000000..e8c591ce39b--- /dev/null+++ b/frontend/src/metabase/embedding/components/EmbeddingFooter/EmbeddingFooter.module.css@@ -0,0 +1,5 @@+.EmbeddingFooter {+ color: var(--mb-color-text-primary);+ background-color: transparent;+ transition: var(--transition-theme-change);+}diff --git a/frontend/src/metabase/embedding/components/EmbeddingFooter/EmbeddingFooter.tsx b/frontend/src/metabase/embedding/components/EmbeddingFooter/EmbeddingFooter.tsxnew file mode 100644index 00000000000..16172fb5c09--- /dev/null+++ b/frontend/src/metabase/embedding/components/EmbeddingFooter/EmbeddingFooter.tsx@@ -0,0 +1,34 @@+import type { PropsWithChildren } from "react";++import {+ Footer,+ type FooterVariant,+} from "metabase/public/components/EmbedFrame/EmbedFrame.styled";+import { LogoBadge } from "metabase/public/components/EmbedFrame/LogoBadge";++import EmbeddingFooterS from "./EmbeddingFooter.module.css";++type Props = {+ hasEmbedBranding: boolean;+ variant: FooterVariant;+ isDarkMode?: boolean;+};++export const EmbeddingFooter = ({+ children,+ hasEmbedBranding,+ variant,+ isDarkMode,+}: PropsWithChildren<Props>) => {+ return (+ <Footer+ data-testid="embedding-footer"+ className={EmbeddingFooterS.EmbeddingFooter}+ variant={variant}+ >+ {hasEmbedBranding && <LogoBadge dark={!!isDarkMode} />}++ {children}+ </Footer>+ );+};diff --git a/frontend/src/metabase/embedding/components/MoreServerSnippetExamplesLink/MoreServerSnippetExamplesLink.tsx b/frontend/src/metabase/embedding/components/MoreServerSnippetExamplesLink/MoreServerSnippetExamplesLink.tsxnew file mode 100644index 00000000000..bcccd21cd50--- /dev/null+++ b/frontend/src/metabase/embedding/components/MoreServerSnippetExamplesLink/MoreServerSnippetExamplesLink.tsx@@ -0,0 +1,19 @@+import { jt, t } from "ttag";++import ExternalLink from "metabase/common/components/ExternalLink";+import { Box, Center } from "metabase/ui";++export const MoreServerSnippetExamplesLink = () => (+ <Box my="1rem">+ <Center>+ <h4>{jt`More ${(+ <ExternalLink+ key="examples"+ href="https://github.com/metabase/embedding-reference-apps"+ >+ {t`examples on GitHub`}+ </ExternalLink>+ )}`}</h4>+ </Center>+ </Box>+);diff --git a/frontend/src/metabase/embedding/components/SharingMenu/DashboardSharingMenu.tsx b/frontend/src/metabase/embedding/components/SharingMenu/DashboardSharingMenu.tsxindex 74ff6508461..b89aab5ecc3 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/DashboardSharingMenu.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/DashboardSharingMenu.tsx@@ -1,18 +1,19 @@-import { useState } from "react";-import { isInstanceAnalyticsCollection } from "metabase/collections/utils";import { setSharing as setDashboardSubscriptionSidebarOpen } from "metabase/dashboard/actions";import { getIsSharing as getIsDashboardSubscriptionSidebarOpen } from "metabase/dashboard/selectors";+import { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";import { useDispatch, useSelector } from "metabase/lib/redux";import { DashboardSubscriptionMenuItem } from "metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem";import { Flex, Menu } from "metabase/ui";import type { Dashboard } from "metabase-types/api";+import { useSharingModal } from "../../hooks/use-sharing-modal";+import { EmbedMenuItem } from "./MenuItems/EmbedMenuItem";import { ExportPdfMenuItem } from "./MenuItems/ExportPdfMenuItem";import { PublicLinkMenuItem } from "./MenuItems/PublicLinkMenuItem";+import { PublicLinkModals } from "./PublicLinkModals";import { SharingMenu } from "./SharingMenu";-import { SharingModals } from "./SharingModals";import type { DashboardSharingModalType } from "./types";export function DashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {@@ -26,9 +27,11 @@ export function DashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {setDashboardSubscriptionSidebarOpen(!isDashboardSubscriptionSidebarOpen),);- const [modalType, setModalType] = useState<DashboardSharingModalType | null>(- null,- );+ const { modalType, setModalType } =+ useSharingModal<DashboardSharingModalType>({+ resource: dashboard,+ resourceType: "dashboard",+ });const hasPublicLink = !!dashboard?.public_uuid;const isArchived = dashboard.archived;@@ -56,11 +59,13 @@ export function DashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {hasPublicLink={hasPublicLink}onClick={() => setModalType("dashboard-public-link")}/>- <EmbedMenuItem onClick={() => setModalType("dashboard-embed")} />+ <EmbedMenuItem+ onClick={() => setModalType(GUEST_EMBED_EMBEDDING_TYPE)}+ /></>)}</SharingMenu>- <SharingModals+ <PublicLinkModalsmodalType={modalType}dashboard={dashboard}onClose={() => setModalType(null)}diff --git a/frontend/src/metabase/embedding/components/SharingMenu/SharingModals.tsx b/frontend/src/metabase/embedding/components/SharingMenu/PublicLinkModals.tsxsimilarity index 71%rename from frontend/src/metabase/embedding/components/SharingMenu/SharingModals.tsxrename to frontend/src/metabase/embedding/components/SharingMenu/PublicLinkModals.tsxindex 6e78f262d15..8c689647792 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/SharingModals.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/PublicLinkModals.tsx@@ -1,7 +1,5 @@import { type Ref, forwardRef } from "react";-import { DashboardSharingEmbeddingModal } from "metabase/dashboard/containers/DashboardSharingEmbeddingModal";-import { QuestionEmbedWidget } from "metabase/query_builder/components/QuestionEmbedWidget";import { Box } from "metabase/ui";import type Question from "metabase-lib/v1/Question";import type { Dashboard } from "metabase-types/api";@@ -46,7 +44,7 @@ type SharingModalProps = BaseSharingModalProps &});-export const SharingModals = ({+export const PublicLinkModals = ({modalType,onClose,question,@@ -63,10 +61,6 @@ export const SharingModals = ({);}- if (modalType === "question-embed" && question) {- return <QuestionEmbedWidget card={question._card} onClose={onClose} />;- }-if (modalType === "dashboard-public-link") {return (<DashboardPublicLinkPopover@@ -78,16 +72,5 @@ export const SharingModals = ({);}- if (modalType === "dashboard-embed" && dashboard) {- return (- <DashboardSharingEmbeddingModal- key="dashboard-embed"- dashboard={dashboard}- onClose={onClose}- isOpen- />- );- }-return null;};diff --git a/frontend/src/metabase/embedding/components/SharingMenu/QuestionSharingMenu.tsx b/frontend/src/metabase/embedding/components/SharingMenu/QuestionSharingMenu.tsxindex 13f68e14f64..9d29f24c67c 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/QuestionSharingMenu.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/QuestionSharingMenu.tsx@@ -1,8 +1,8 @@-import { useState } from "react";import { t } from "ttag";import { isInstanceAnalyticsCollection } from "metabase/collections/utils";import { useSetting } from "metabase/common/hooks";+import { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";import { useDispatch, useSelector } from "metabase/lib/redux";import { setUIControls } from "metabase/query_builder/actions";import { MODAL_TYPES } from "metabase/query_builder/constants";@@ -13,16 +13,21 @@ import {import { Flex } from "metabase/ui";import type Question from "metabase-lib/v1/Question";+import { useSharingModal } from "../../hooks/use-sharing-modal";+import { EmbedMenuItem } from "./MenuItems/EmbedMenuItem";import { PublicLinkMenuItem } from "./MenuItems/PublicLinkMenuItem";+import { PublicLinkModals } from "./PublicLinkModals";import { SharingButton, SharingMenu } from "./SharingMenu";-import { SharingModals } from "./SharingModals";import type { QuestionSharingModalType } from "./types";export function QuestionSharingMenu({ question }: { question: Question }) {const dispatch = useDispatch();- const [modalType, setModalType] = useState<QuestionSharingModalType | null>(- null,+ const { modalType, setModalType } = useSharingModal<QuestionSharingModalType>(+ {+ resource: question.card(),+ resourceType: "question",+ },);const hasPublicLink = !!question?.publicUUID?.();const isModel = question.type() === "model";@@ -72,7 +77,7 @@ export function QuestionSharingMenu({ question }: { question: Question }) {tooltip={t`Public link`}onClick={() => setModalType("question-public-link")}/>- <SharingModals+ <PublicLinkModalsmodalType={modalType}question={question}onClose={() => setModalType(null)}@@ -88,9 +93,11 @@ export function QuestionSharingMenu({ question }: { question: Question }) {hasPublicLink={hasPublicLink}onClick={() => setModalType("question-public-link")}/>- <EmbedMenuItem onClick={() => setModalType("question-embed")} />+ <EmbedMenuItem+ onClick={() => setModalType(GUEST_EMBED_EMBEDDING_TYPE)}+ /></SharingMenu>- <SharingModals+ <PublicLinkModalsmodalType={modalType}question={question}onClose={() => setModalType(null)}diff --git a/frontend/src/metabase/embedding/components/SharingMenu/test/QuestionSharingMenu.unit.spec.tsx b/frontend/src/metabase/embedding/components/SharingMenu/test/QuestionSharingMenu.unit.spec.tsxindex 6ee359e5c5f..9fe49d281da 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/test/QuestionSharingMenu.unit.spec.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/test/QuestionSharingMenu.unit.spec.tsx@@ -126,32 +126,6 @@ describe("QuestionSharingMenu", () => {});describe("embedding", () => {- describe("admins", () => {- describe("when embedding is disabled", () => {- it("should open the embed modal when the 'Embed' menu item is clicked", async () => {- setupQuestionSharingMenu({- isAdmin: true,- isEmbeddingEnabled: false,- });- await openMenu();- await userEvent.click(screen.getByText("Embed"));- expect(await screen.findByText("Embed Metabase")).toBeInTheDocument();- });- });-- describe("when embedding is enabled", () => {- it("should open the embed modal when the 'Embed' menu item is clicked", async () => {- setupQuestionSharingMenu({- isAdmin: true,- isEmbeddingEnabled: true,- });- await openMenu();- await userEvent.click(screen.getByText("Embed"));- expect(await screen.findByText("Embed Metabase")).toBeInTheDocument();- });- });- });-describe("non-admins", () => {it("should not show the 'Embed' menu item if embedding is enabled", async () => {setupQuestionSharingMenu({diff --git a/frontend/src/metabase/embedding/components/SharingMenu/types.ts b/frontend/src/metabase/embedding/components/SharingMenu/types.tsindex 674cefdac4a..76d8c10a370 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/types.ts+++ b/frontend/src/metabase/embedding/components/SharingMenu/types.ts@@ -1,3 +1,5 @@+import type { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";+export type EmbedModalType = "question-embed" | "dashboard-embed";export type PublicLinkModalType =| "question-public-link"@@ -5,10 +7,10 @@ export type PublicLinkModalType =export type QuestionSharingModalType =| "question-public-link"- | "question-embed";+ | typeof GUEST_EMBED_EMBEDDING_TYPE;export type DashboardSharingModalType =| "dashboard-public-link"- | "dashboard-embed";+ | typeof GUEST_EMBED_EMBEDDING_TYPE;export type SharingModalType = PublicLinkModalType | EmbedModalType;diff --git a/frontend/src/metabase/embedding/constants.ts b/frontend/src/metabase/embedding/constants.tsindex b520bce1ce4..f3583dc42d0 100644--- a/frontend/src/metabase/embedding/constants.ts+++ b/frontend/src/metabase/embedding/constants.ts@@ -1,3 +1,4 @@import type { EmbeddingType } from "metabase/public/lib/types";export const STATIC_LEGACY_EMBEDDING_TYPE: EmbeddingType = "static-legacy";+export const GUEST_EMBED_EMBEDDING_TYPE: EmbeddingType = "guest-embed";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.tsindex f22efa6de4b..aade80c0de2 100644--- 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@@ -33,7 +33,10 @@ export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {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 },+ initialState: {+ isGuest: true,+ useExistingUserSession: true,+ },});},variant: "outline",@@ -130,7 +133,10 @@ export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {description: t`Deploy your embedded dashboard to a production environment and share with your users.`,onClick: () => {openEmbedModal({- initialState: { useExistingUserSession: false },+ initialState: {+ isGuest: false,+ useExistingUserSession: false,+ },});},variant: "outline",diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.tsindex ee139b7db07..df111a3d015 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts@@ -4,7 +4,12 @@ import type {SdkIframeEmbedSettingKey,SdkIframeEmbedSettings,} from "metabase/embedding/embedding-iframe-sdk/types/embed";+import { getAuthTypeForSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-auth-type-for-settings";+import { countEmbeddingParameterOptions } from "metabase/embedding/lib/count-embedding-parameter-options";import { trackSimpleEvent } from "metabase/lib/analytics";+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";+import type { EmbeddingParameters } from "metabase/public/lib/types";+import type { Card, Dashboard } from "metabase-types/api";import type {SdkIframeEmbedSetupExperience,@@ -15,6 +20,10 @@ import {getResourceIdFromSettings,} from "./utils/get-default-sdk-iframe-embed-setting";+export const UPSELL_CAMPAIGN_EXPERIENCE = "embedding_experience";+export const UPSELL_CAMPAIGN_AUTH = "embedding_auth";+export const UPSELL_CAMPAIGN_BEHAVIOR = "embedding_behavior";+/*** Tracking every embed settings would bloat Snowplow, so we only track* the most relevant options that reveal usage patterns.@@ -36,6 +45,8 @@ const EMBED_SETTINGS_TO_IGNORE: SdkIframeEmbedSettingKey[] = ["dashboardId","questionId","targetCollection",+ "hiddenParameters",+ "lockedParameters",];export const trackEmbedWizardOpened = () =>@@ -51,30 +62,53 @@ export const trackEmbedWizardExperienceCompleted = (experience === defaultExperience ? "default" : `custom=${experience}`,});-export const trackEmbedWizardResourceSelectionCompleted = (- currentSettings: SdkIframeEmbedSetupSettings,- defaultResourceId: string | number,-) => {+export const trackEmbedWizardResourceSelectionCompleted = ({+ experience,+ currentSettings,+ defaultResourceId,+}: {+ experience: SdkIframeEmbedSetupExperience;+ currentSettings: SdkIframeEmbedSetupSettings;+ defaultResourceId: string | number;+}) => {const currentResourceId = getResourceIdFromSettings(currentSettings) ?? "";- const isDefault = currentResourceId === defaultResourceId;+ const isDefaultResource = currentResourceId === defaultResourceId;++ const eventDetailsParts: string[] = [+ `isDefaultResource=${isDefaultResource}`,+ `experience=${experience}`,+ ];trackSimpleEvent({event: "embed_wizard_resource_selection_completed",- event_detail: isDefault ? "default" : "custom",+ event_detail: buildEventDetails(eventDetailsParts),});};const getEmbedSettingsToCompare = (settings: Partial<SdkIframeEmbedSettings>) =>_.omit(_.omit(settings, ...EMBED_SETTINGS_TO_IGNORE), _.isUndefined);-export const trackEmbedWizardOptionsCompleted = (- settings: Partial<SdkIframeEmbedSettings>,- experience: SdkIframeEmbedSetupExperience,-) => {+export const trackEmbedWizardOptionsCompleted = ({+ initialState,+ experience,+ resource,+ settings,+ isGuestEmbedsEnabled,+ embeddingParameters,+}: {+ initialState: SdkIframeEmbedSetupModalInitialState | undefined;+ experience: SdkIframeEmbedSetupExperience;+ resource: Dashboard | Card | null;+ settings: Partial<SdkIframeEmbedSetupSettings>;+ isGuestEmbedsEnabled: boolean;+ embeddingParameters: EmbeddingParameters;+}) => {// Get defaults for this experience type (with a dummy resource ID)const defaultSettings = getDefaultSdkIframeEmbedSettings({+ initialState,experience,resourceId: 0,+ isGuestEmbedsEnabled,});// Does the embed settings diverge from the experience defaults?@@ -83,46 +117,101 @@ export const trackEmbedWizardOptionsCompleted = (getEmbedSettingsToCompare(defaultSettings),);- let options: string[] = [+ const eventDetailsParts: (string | null)[] = [`settings=${hasCustomOptions ? "custom" : "default"}`,];if (hasCustomOptions) {+ const authType = getAuthTypeForSettings(settings);+ const params = countEmbeddingParameterOptions(embeddingParameters);const hasCustomTheme = settings.theme?.colors !== undefined;- options = [- ...options,- `theme=${hasCustomTheme ? "custom" : "default"}`,- `auth=${settings.useExistingUserSession ? "user_session" : "sso"}`,- ];-- for (const _optionKey in settings) {- const optionKey = _optionKey as keyof SdkIframeEmbedSettings;-- if (!EMBED_SETTINGS_TO_TRACK.includes(optionKey)) {- continue;- }-- const value = settings[optionKey];-- if (value === undefined) {- continue;- }-- options.push(`${optionKey}=${value.toString()}`);- }+ eventDetailsParts.push(+ ...[+ `experience=${experience}`,+ ...buldEventDetailsPartsForGuestEmbedResource({ resource, settings }),+ `auth=${authType}`,+ ...buildEventDetailsPartsForSettings(settings),+ ...(settings.isGuest ? [`params=${JSON.stringify(params)}`] : []),+ `theme=${hasCustomTheme ? "custom" : "default"}`,+ ],+ );}trackSimpleEvent({event: "embed_wizard_options_completed",- event_detail: options.join(","),+ event_detail: buildEventDetails(eventDetailsParts),});};-export const trackEmbedWizardCodeCopied = (- authMethod: "sso" | "user_session",-) =>+export const trackEmbedWizardCodeCopied = ({+ experience,+ resource,+ snippetType,+ settings,+}: {+ experience: SdkIframeEmbedSetupExperience;+ resource: Dashboard | Card | null;+ snippetType: "frontend" | "server";+ settings: SdkIframeEmbedSetupSettings;+}) => {+ const authType = getAuthTypeForSettings(settings);++ const eventDetailsParts: (string | null)[] = [+ `experience=${experience}`,+ `snippetType=${snippetType}`,+ ...buldEventDetailsPartsForGuestEmbedResource({ resource, settings }),+ `auth=${authType}`,+ ];+trackSimpleEvent({event: "embed_wizard_code_copied",- event_detail: authMethod,+ event_detail: buildEventDetails(eventDetailsParts),});+};++const buldEventDetailsPartsForGuestEmbedResource = ({+ resource,+ settings,+}: {+ resource: Dashboard | Card | null;+ settings: Partial<SdkIframeEmbedSetupSettings>;+}) => [+ ...(settings.isGuest+ ? [+ resource?.enable_embedding !== undefined+ ? `guestEmbedEnabled=${resource.enable_embedding}`+ : null,+ resource?.embedding_type+ ? `guestEmbedType=${resource.embedding_type}`+ : null,+ ]+ : []),+];++const buildEventDetailsPartsForSettings = (+ settings: Partial<SdkIframeEmbedSettings>,+) => {+ const options: string[] = [];++ for (const _optionKey in settings) {+ const optionKey = _optionKey as keyof SdkIframeEmbedSettings;++ if (!EMBED_SETTINGS_TO_TRACK.includes(optionKey)) {+ continue;+ }++ const value = settings[optionKey];++ if (value === undefined) {+ continue;+ }++ options.push(`${optionKey}=${value.toString()}`);+ }++ return options;+};++const buildEventDetails = (eventDetailsParts: (string | null)[]): string =>+ eventDetailsParts.filter(Boolean).join(",");diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/CodeSnippet/CopyCodeSnippetButton.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/CodeSnippet/CopyCodeSnippetButton.tsxnew file mode 100644index 00000000000..437104e19a6--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/CodeSnippet/CopyCodeSnippetButton.tsx@@ -0,0 +1,24 @@+import { t } from "ttag";++import { Button, CopyButton, Icon } from "metabase/ui";++type Props = {+ snippet: string;+ onCopy?: () => void;+};++export const CopyCodeSnippetButton = ({ snippet, onCopy }: Props) => (+ <CopyButton value={snippet}>+ {({ copied, copy }: { copied: boolean; copy: () => void }) => (+ <Button+ leftSection={<Icon name="copy" size={16} />}+ onClick={() => {+ copy();+ onCopy?.();+ }}+ >+ {copied ? t`Copied!` : t`Copy code`}+ </Button>+ )}+ </CopyButton>+);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ColorCustomizationSection.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ColorCustomizationSection.tsxindex 0004196ebb3..a5f917d6c36 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ColorCustomizationSection.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ColorCustomizationSection.tsx@@ -1,11 +1,21 @@-import { useCallback, useState } from "react";+import cx from "classnames";+import { type ReactNode, useCallback, useState } from "react";import { t } from "ttag";import { ColorPillPicker } from "metabase/common/components/ColorPicker";import { useSetting } from "metabase/common/hooks";+import CS from "metabase/css/core/index.css";import type { MetabaseColors } from "metabase/embedding-sdk/theme";import { originalColors, staticVizOverrides } from "metabase/lib/colors";-import { ActionIcon, Group, Icon, Stack, Text, Tooltip } from "metabase/ui";+import {+ ActionIcon,+ Flex,+ Group,+ Icon,+ Stack,+ Text,+ Tooltip,+} from "metabase/ui";import { getConfigurableThemeColors } from "../utils/theme-colors";@@ -16,12 +26,16 @@ const defaultMetabaseColorsWithoutAlpha = {interface ColorCustomizationSectionProps {theme?: { colors?: Partial<MetabaseColors> };+ disabled: boolean;+ hoverCard: ReactNode;onColorChange: (colors: Partial<MetabaseColors>) => void;onColorReset?: () => void;}export const ColorCustomizationSection = ({theme,+ disabled,+ hoverCard,onColorChange,onColorReset,}: ColorCustomizationSectionProps) => {@@ -43,26 +57,40 @@ export const ColorCustomizationSection = ({return (<>- <Group justify="space-between" align="center" mb="lg">+ <Group+ justify="space-between"+ align="center"+ mb="lg"+ data-testid="appearance-section"+ ><Text size="lg" fw="bold">{t`Appearance`}</Text>- {hasColorChanged && (- <Tooltip label={t`Reset colors`}>- <ActionIcon- variant="subtle"- size="sm"- onClick={resetColors}- aria-label={t`Reset colors`}- >- <Icon name="revert" c="brand" />- </ActionIcon>- </Tooltip>- )}+ <Flex gap="md" align="center">+ {hasColorChanged && (+ <Tooltip label={t`Reset colors`}>+ <ActionIcon+ variant="subtle"+ size="sm"+ onClick={resetColors}+ aria-label={t`Reset colors`}+ >+ <Icon name="revert" c="brand" />+ </ActionIcon>+ </Tooltip>+ )}++ {hoverCard}+ </Flex></Group>- <Group align="start" gap="xl">+ <Group+ align="start"+ gap="xl"+ opacity={!disabled ? 1 : 0.5}+ className={cx(disabled && CS.pointerEventsNone)}+ >{getConfigurableThemeColors().map(({ key, name, originalColorKey }) => {// Use the default from appearance settings. If not set, use the default Metabase color.const originalColor =diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddedAnalyticsCard.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddedAnalyticsCard.tsxindex a32c8641f51..86665a7244c 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddedAnalyticsCard.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddedAnalyticsCard.tsx@@ -1,102 +1,32 @@-import { useState } from "react";import { t } from "ttag";-import { useUpdateSettingsMutation } from "metabase/api";-import { useSetting, useToast } from "metabase/common/hooks";-import {- Box,- Button,- Card,- Group,- HoverCard,- Icon,- Stack,- Text,-} from "metabase/ui";+import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";-export const EnableEmbeddedAnalyticsCard = () => {- const isSimpleEmbeddingEnabled = useSetting("enable-embedding-simple");- const [updateSettings] = useUpdateSettingsMutation();- const [sendToast] = useToast();-- // Freeze the card visibility to show even when we enabled the embedding setting.- // This allows us to show the "Enabled" button state and not hide the card.- const [showSimpleEmbedding] = useState(!isSimpleEmbeddingEnabled);-- const handleEnableEmbedding = async () => {- try {- await updateSettings({- "enable-embedding-simple": true,-- // accept the terms for Embedded Analytics JS- "show-simple-embed-terms": false,- });- } catch (error) {- sendToast({ message: t`Failed to enable Embedded Analytics JS` });- }- };-- // eslint-disable-next-line no-literal-metabase-strings -- admin only- const tooltip1 = t`When using the Embedded analytics SDK, each end user should have their own Metabase account.`;+import { EnableEmbeddingCard } from "./EnableEmbeddingCard";- // eslint-disable-next-line no-literal-metabase-strings -- admin only- const tooltip2 = t`Sharing Metabase accounts is a security risk. Even if you filter data on the client side, each user could use their token to view any data visible to that shared user account. That, and we consider shared accounts to be unfair usage of our terms.`;-- // eslint-disable-next-line no-literal-metabase-strings -- admin only- const tooltip3 = t`Fair usage of the SDK involves giving each end-user of the embedded analytics their own Metabase account.`;+export const EnableEmbeddedAnalyticsCard = () => {+ const { isSimpleEmbeddingEnabled, isSimpleEmbeddingTermsAccepted } =+ useSdkIframeEmbedSetupContext();- if (!showSimpleEmbedding) {+ // Not yet fetched+ if (isSimpleEmbeddingEnabled === undefined) {return null;}return (- <Card p="md" mb="md">- <Stack gap={0}>- <Text fz="md" c="text-dark">- {t`Enable Embedded Analytics JS to get started.`}- </Text>-- <Group gap="xs">- <Text size="sm" c="text-medium">- {t`By continuing, you agree to the fair usage conditions.`}- </Text>-- <HoverCard position="right-start" withArrow>- <HoverCard.Target>- <Box>- <Icon name="info" size={14} c="text-medium" />- </Box>- </HoverCard.Target>-- <HoverCard.Dropdown>- <Stack maw={340} p="md" gap="md">- <Text fz="sm" lh="lg">- {tooltip1}- </Text>-- <Text fz="sm" lh="lg">- {tooltip2}- </Text>-- <Text fz="sm" lh="lg">- {tooltip3}- </Text>- </Stack>- </HoverCard.Dropdown>- </HoverCard>- </Group>-- <Group justify="flex-end" mt="md">- <Button- variant={isSimpleEmbeddingEnabled ? "default" : "filled"}- onClick={handleEnableEmbedding}- disabled={isSimpleEmbeddingEnabled}- leftSection={isSimpleEmbeddingEnabled && <Icon name="check" />}- >- {isSimpleEmbeddingEnabled ? t`Enabled` : t`Enable to continue`}- </Button>- </Group>- </Stack>- </Card>+ <EnableEmbeddingCard+ embeddingType="Embedded Analytics JS"+ isEnabled={isSimpleEmbeddingEnabled}+ termsAccepted={isSimpleEmbeddingTermsAccepted}+ settingsToUpdate={{+ "enable-embedding-simple": true,+ // accept the terms for Embedded Analytics JS+ "show-simple-embed-terms": false,+ ...(!isSimpleEmbeddingTermsAccepted && {+ "show-simple-embed-terms": false,+ }),+ }}+ errorMessage={t`Failed to enable Embedded Analytics JS`}+ />);};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddingCard.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddingCard.tsxnew file mode 100644index 00000000000..acef8c1cb9d--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddingCard.tsx@@ -0,0 +1,137 @@+import { useRef, useState } from "react";+import { match } from "ts-pattern";+import { t } from "ttag";++import { useUpdateSettingsMutation } from "metabase/api";+import { useToast } from "metabase/common/hooks";+import { Button, Card, Group, HoverCard, Icon, Stack, Text } from "metabase/ui";+import type { EnterpriseSettings } from "metabase-types/api";++interface EmbeddingControlCardProps {+ embeddingType: string;+ isEnabled: boolean;+ termsAccepted: boolean;+ settingsToUpdate: Partial<EnterpriseSettings>;+ errorMessage: string;+}++export const EnableEmbeddingCard = ({+ embeddingType,+ isEnabled,+ termsAccepted,+ settingsToUpdate,+ errorMessage,+}: EmbeddingControlCardProps) => {+ const [updateSettings] = useUpdateSettingsMutation();+ const [sendToast] = useToast();++ const isAccepted = isEnabled && termsAccepted;++ // Freeze the card visibility to show even when we enabled the embedding setting.+ // This allows us to show the "Enabled" button state and not hide the card.+ const [showCard] = useState(!isAccepted);++ const handleEnableEmbedding = async () => {+ try {+ await updateSettings(settingsToUpdate);+ } catch (error) {+ sendToast({ message: errorMessage });+ }+ };++ const initialDataRef = useRef({ isEnabled, termsAccepted });++ if (!showCard) {+ return null;+ }++ const data = match(initialDataRef.current)+ .with(+ {+ isEnabled: false,+ termsAccepted: false,+ },+ () => ({+ title: t`To continue, enable ${embeddingType} and agree to the usage conditions.`,+ buttonCaption: t`Agree and enable`,+ }),+ )+ .with(+ {+ isEnabled: true,+ termsAccepted: false,+ },+ () => ({+ title: t`Agree to the usage conditions to continue.`,+ buttonCaption: t`Agree and continue`,+ }),+ )+ .with(+ {+ isEnabled: false,+ termsAccepted: true,+ },+ () => ({+ title: t`Enable ${embeddingType} to get started.`,+ buttonCaption: t`Enable and continue`,+ }),+ )+ .otherwise(() => null);++ if (!data) {+ return null;+ }++ const { title, buttonCaption } = data;++ return (+ <Card p="md" mb="md" data-testid="enable-embedding-card">+ <Stack gap={0}>+ <Text fz="md" c="text-dark">+ {title}+ {!termsAccepted && (+ <HoverCard position="bottom" withArrow>+ <HoverCard.Target>+ <Icon+ name="info"+ size={14}+ c="text-medium"+ ml="sm"+ style={{ verticalAlign: "middle" }}+ />+ </HoverCard.Target>++ <HoverCard.Dropdown>+ <Stack maw={340} p="md" gap="md">+ <Text fz="sm" lh="lg">+ {/* eslint-disable-next-line no-literal-metabase-strings -- User facing text */}+ {t`When you embed charts or dashboards from Metabase in your+ own application that application isn't subject to the Affero+ General Public License that covers the rest of Metabase,+ provided you keep the Metabase logo and the "Powered by+ Metabase" visible on those embeds.`}+ </Text>++ <Text fz="sm" lh="lg">+ {t`You should, however, read the license text linked above as that is the actual license that you will be agreeing to by enabling this feature.`}+ </Text>+ </Stack>+ </HoverCard.Dropdown>+ </HoverCard>+ )}+ </Text>++ <Group justify="flex-end" mt="md">+ <Button+ variant={isAccepted ? "default" : "filled"}+ onClick={handleEnableEmbedding}+ disabled={isAccepted}+ leftSection={isAccepted && <Icon name="check" />}+ >+ {isAccepted ? "Enabled" : buttonCaption}+ </Button>+ </Group>+ </Stack>+ </Card>+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableGuestEmbedsCard.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableGuestEmbedsCard.tsxnew file mode 100644index 00000000000..aa0f60efd5e--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/EnableGuestEmbedsCard.tsx@@ -0,0 +1,41 @@+import { t } from "ttag";++import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";++import { EnableEmbeddingCard } from "./EnableEmbeddingCard";++export const EnableGuestEmbedsCard = () => {+ const {+ isSimpleEmbedFeatureAvailable,+ isGuestEmbedsEnabled,+ isGuestEmbedsTermsAccepted,+ } = useSdkIframeEmbedSetupContext();++ if (isSimpleEmbedFeatureAvailable) {+ return null;+ }++ // Not yet fetched+ if (isGuestEmbedsEnabled === undefined) {+ return null;+ }++ return (+ <EnableEmbeddingCard+ embeddingType="Guest embeds"+ isEnabled={isGuestEmbedsEnabled}+ termsAccepted={isGuestEmbedsTermsAccepted}+ settingsToUpdate={{+ "enable-embedding-static": true,+ // When the simple embed feature is not available (oss), we toggle both static and simple embedding+ ...(!isSimpleEmbedFeatureAvailable && {+ "enable-embedding-simple": true,+ }),+ ...(!isGuestEmbedsTermsAccepted && {+ "show-static-embed-terms": false,+ }),+ }}+ errorMessage={t`Failed to enable Guest embeds`}+ />+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/GetCodeStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/GetCodeStep.tsxindex bc788d0bdcc..5600179d6e5 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/GetCodeStep.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/GetCodeStep.tsx@@ -2,18 +2,11 @@ import { t } from "ttag";import { useUpdateSettingsMutation } from "metabase/api";import { CodeEditor } from "metabase/common/components/CodeEditor";-import { useSetting } from "metabase/common/hooks";-import {- Button,- Card,- CopyButton,- Flex,- HoverCard,- Icon,- Radio,- Stack,- Text,-} from "metabase/ui";+import { MoreServerSnippetExamplesLink } from "metabase/embedding/components/MoreServerSnippetExamplesLink/MoreServerSnippetExamplesLink";+import { CopyCodeSnippetButton } from "metabase/embedding/embedding-iframe-sdk-setup/components/CodeSnippet/CopyCodeSnippetButton";+import { useSdkIframeEmbedServerSnippet } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-server-snippet";+import { EmbedServerSnippetLanguageSelect } from "metabase/public/components/EmbedServerSnippetLanguageSelect/EmbedServerSnippetLanguageSelect";+import { Card, Flex, Stack, Text } from "metabase/ui";import type { SettingKey } from "metabase-types/api";import { trackEmbedWizardCodeCopied } from "../analytics";@@ -21,26 +14,23 @@ import { useSdkIframeEmbedSetupContext } from "../context";import { useSdkIframeEmbedSnippet } from "../hooks/use-sdk-iframe-embed-snippet";export const GetCodeStep = () => {- const { settings, updateSettings } = useSdkIframeEmbedSetupContext();+ const { experience, resource, settings } = useSdkIframeEmbedSetupContext();const [updateInstanceSettings] = useUpdateSettingsMutation();- const isJwtEnabled = useSetting("jwt-enabled");- const isSamlEnabled = useSetting("saml-enabled");- const isJwtConfigured = useSetting("jwt-configured");- const isSamlConfigured = useSetting("saml-configured");-- const isSsoEnabledAndConfigured =- (isJwtEnabled && isJwtConfigured) || (isSamlEnabled && isSamlConfigured);-+ const serverSnippetData = useSdkIframeEmbedServerSnippet();const snippet = useSdkIframeEmbedSnippet();- const authType = settings.useExistingUserSession ? "user-session" : "sso";+ const trackSnippetCopied = (snippetType: "frontend" | "server") => {+ trackEmbedWizardCodeCopied({+ experience,+ resource,+ snippetType,+ settings,+ });+ };- const handleCodeSnippetCopied = () => {- // Embed Flow: track code copied- trackEmbedWizardCodeCopied(- settings.useExistingUserSession ? "user_session" : "sso",- );+ const handleFrontendSnippetCopied = () => {+ trackSnippetCopied("frontend");// Embedding Hub: track step completionconst settingKey: SettingKey = settings.useExistingUserSession@@ -50,76 +40,17 @@ export const GetCodeStep = () => {updateInstanceSettings({ [settingKey]: true });};+ const handleServerSnippetCopied = () => trackSnippetCopied("server");+return (<Stack gap="md">- <Card p="md">- <Stack gap="md" p="xs">- <Text size="lg" fw="bold">- {t`Authentication`}- </Text>-- <Text size="sm" c="text-medium">- {t`Choose the authentication method for embedding:`}- </Text>-- <Radio.Group- value={authType}- onChange={(value) =>- updateSettings({- useExistingUserSession: value === "user-session",- })- }- >- <Stack gap="sm">- <Radio- value="user-session"- label={- <Flex align="center" gap="xs">- {/* eslint-disable-next-line no-literal-metabase-strings -- this string is only shown for admins. */}- <Text>{t`Existing Metabase session`}</Text>- <HoverCard position="bottom">- <HoverCard.Target>- <Icon- name="info"- size={14}- c="text-medium"- cursor="pointer"- />- </HoverCard.Target>- <HoverCard.Dropdown>- <Text lh="md" p="md" style={{ width: 300 }}>- {/* eslint-disable-next-line no-literal-metabase-strings -- this string is only shown for admins. */}- {t`This option lets you test Embedded Analytics JS locally using your existing Metabase session cookie. This only works for testing locally, using your admin account and on this browser. This may not work on Safari and Firefox. We recommend testing this in Chrome.`}- </Text>- </HoverCard.Dropdown>- </HoverCard>- </Flex>- }- />-- <Radio- value="sso"- label={t`Single sign-on (SSO)`}- disabled={!isSsoEnabledAndConfigured}- />- </Stack>- </Radio.Group>-- {authType === "sso" && (- <Text size="sm" c="text-medium">- {t`Select this option if you have already set up SSO. This option relies on SSO to sign in your application users into the embedded iframe, and groups and permissions to enforce limits on what users can access. `}- </Text>- )}- </Stack>- </Card>-<Card p="md"><Text size="lg" fw="bold" mb="md">{t`Embed code`}</Text><Stack gap="sm">- <div onCopy={handleCodeSnippetCopied}>+ <div onCopy={handleFrontendSnippetCopied}><CodeEditorlanguage="html"value={snippet}@@ -128,21 +59,44 @@ export const GetCodeStep = () => {/></div>- <CopyButton value={snippet}>- {({ copied, copy }: { copied: boolean; copy: () => void }) => (- <Button- leftSection={<Icon name="copy" size={16} />}- onClick={() => {- copy();- handleCodeSnippetCopied();- }}- >- {copied ? t`Copied!` : t`Copy code`}- </Button>- )}- </CopyButton>+ <CopyCodeSnippetButton+ snippet={snippet}+ onCopy={handleFrontendSnippetCopied}+ /></Stack></Card>++ {!!serverSnippetData && (+ <Card p="md">+ <Flex align="baseline" justify="space-between">+ <Text size="lg" fw="bold" mb="md">+ {t`Server code`}+ </Text>++ <EmbedServerSnippetLanguageSelect+ languageOptions={serverSnippetData.serverSnippetOptions}+ selectedOptionId={serverSnippetData.selectedServerSnippetId}+ onChangeOption={serverSnippetData.setSelectedServerSnippetId}+ />+ </Flex>++ <Stack gap="sm">+ <CodeEditor+ language={serverSnippetData.serverSnippetOption.language}+ value={serverSnippetData.serverSnippetOption.source}+ readOnly+ lineNumbers={false}+ />++ <CopyCodeSnippetButton+ snippet={serverSnippetData.serverSnippetOption.source}+ onCopy={handleServerSnippetCopied}+ />++ <MoreServerSnippetExamplesLink />+ </Stack>+ </Card>+ )}</Stack>);};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingAlert.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingAlert.tsxnew file mode 100644index 00000000000..70894b96eb0--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingAlert.tsx@@ -0,0 +1,88 @@+import { c, t } from "ttag";++import { STATIC_LEGACY_EMBEDDING_TYPE } from "metabase/embedding/constants";+import type { LegacyStaticEmbeddingModalProps } from "metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal";+import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import { getResourceTypeFromExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience";+import { useDispatch } from "metabase/lib/redux";+import { setOpenModalWithProps } from "metabase/redux/ui";+import { Alert, Anchor, Box, Flex, Icon, Stack, Text } from "metabase/ui";++export const LegacyStaticEmbeddingAlert = () => {+ const { isGuestEmbedsEnabled, settings, resource, experience, onClose } =+ useSdkIframeEmbedSetupContext();++ const dispatch = useDispatch();++ const isGuestEmbed = !!settings.isGuest;+ const useExistingUserSession = !!settings.useExistingUserSession;++ const resourceType = getResourceTypeFromExperience(experience);+ const shouldShowForResource =+ resourceType === "dashboard" || resourceType === "question";++ if (+ !isGuestEmbedsEnabled ||+ !isGuestEmbed ||+ !resource ||+ !resourceType ||+ !shouldShowForResource+ ) {+ return null;+ }++ const shouldShowLegacyStaticEmbeddingAlert =+ resource.enable_embedding && resource.embedding_type === "static-legacy";++ if (!shouldShowLegacyStaticEmbeddingAlert) {+ return null;+ }++ return (+ <Alert color="info" variant="outline">+ <Flex gap="sm">+ <Box>+ <Icon color="var(--mb-color-text-secondary)" name="info" mt="2px" />+ </Box>++ <Stack>+ <Text c="text-primary" lh="lg">+ {t`This embed uses the legacy static embedding method. The controls shown are for the new embedding method, which is recommended.`}+ </Text>++ <Anchor+ key="anchor"+ fw="bold"+ lh="lg"+ data-testid="legacy-static-embedding-button"+ onClick={() => {+ onClose();++ const modalProps: LegacyStaticEmbeddingModalProps = {+ experience,+ dashboardId: settings.dashboardId,+ questionId: settings.questionId,+ parentInitialState: {+ resourceId: resource.id,+ resourceType,+ isGuest: isGuestEmbed,+ useExistingUserSession,+ },+ };++ dispatch(+ setOpenModalWithProps({+ id: STATIC_LEGACY_EMBEDDING_TYPE,+ props: modalProps,+ }),+ );+ }}+ >+ {c("A link that toggles the legacy static embedding wizard.")+ .t`Use legacy static embedding (not recommended)`}+ </Anchor>+ </Stack>+ </Flex>+ </Alert>+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal.tsxnew file mode 100644index 00000000000..e204008501d--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal.tsx@@ -0,0 +1,75 @@+import { t } from "ttag";++import { DashboardSharingEmbeddingModal } from "metabase/dashboard/containers/DashboardSharingEmbeddingModal";+import { useGetCurrentResource } from "metabase/embedding/embedding-iframe-sdk-setup/hooks";+import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";+import { useOpenEmbedJsWizard } from "metabase/embedding/hooks/use-open-embed-js-wizard";+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";+import { LoadingAndErrorWrapper } from "metabase/public/containers/PublicAction/PublicAction.styled";+import { QuestionEmbedWidget } from "metabase/query_builder/components/QuestionEmbedWidget";+import type { Card, Dashboard, DashboardId } from "metabase-types/api";++export type LegacyStaticEmbeddingModalProps = {+ experience: SdkIframeEmbedSetupExperience;+ dashboardId?: DashboardId;+ questionId?: string | number;+ parentInitialState: SdkIframeEmbedSetupModalInitialState | undefined;+};++export type InternalProps = LegacyStaticEmbeddingModalProps & {+ onClose: () => void;+};++export const LegacyStaticEmbeddingModal = ({+ experience,+ dashboardId,+ questionId,+ parentInitialState,+ onClose,+}: InternalProps) => {+ const { resource, isError, isLoading } = useGetCurrentResource({+ experience,+ dashboardId,+ questionId,+ });++ const openEmbedJsWizard = useOpenEmbedJsWizard({+ initialState: parentInitialState,+ });++ if (isLoading || isError) {+ return (+ <LoadingAndErrorWrapper+ loading={isLoading}+ error={isError ? t`Something’s gone wrong` : undefined}+ />+ );+ }++ const handleBack = () => {+ openEmbedJsWizard({ onBeforeOpen: () => onClose() });+ };++ if (experience === "chart") {+ return (+ <QuestionEmbedWidget+ card={resource as Card}+ onBack={handleBack}+ onClose={onClose}+ />+ );+ }++ if (experience === "dashboard") {+ return (+ <DashboardSharingEmbeddingModal+ dashboard={resource as Dashboard}+ onBack={handleBack}+ onClose={onClose}+ isOpen+ />+ );+ }++ return null;+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/ParameterSettings.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/ParameterSettings.tsxindex a6723cc9550..46cd20f5f90 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/ParameterSettings.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/ParameterSettings.tsx@@ -1,19 +1,21 @@-import { useDebouncedCallback } from "@mantine/hooks";-import { useCallback, useMemo } from "react";+import { useMemo } from "react";import { t } from "ttag";import CS from "metabase/css/core/index.css";-import { SET_INITIAL_PARAMETER_DEBOUNCE_MS } from "metabase/embedding/embedding-iframe-sdk-setup/constants";+import { getResourceTypeFromExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience";+import { isQuestionOrDashboardSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings";import { ParameterWidget } from "metabase/parameters/components/ParameterWidget";+import { ParametersSettings } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/ParametersSettings";+import { getLockedPreviewParameters } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-locked-preview-parameters";import { Group, Stack, Text } from "metabase/ui";import type { UiParameter } from "metabase-lib/v1/parameters/types";import { getValuePopulatedParameters } from "metabase-lib/v1/parameters/utils/parameter-values";-import type { ParameterValueOrArray } from "metabase-types/api";import { useSdkIframeEmbedSetupContext } from "../../context";+import { useInitialParameterValues } from "../../hooks/use-initial-parameter-values";+import { useParameterVisibility } from "../../hooks/use-parameter-visibility";import { ParameterVisibilityToggle } from "./ParameterVisibilityToggle";-import { useHideParameter } from "./hooks/use-hide-parameter";export const ParameterSettings = () => {const {@@ -22,39 +24,27 @@ export const ParameterSettings = () => {updateSettings,availableParameters,parametersValuesById,+ embeddingParameters,isLoading,+ onEmbeddingParametersChange,} = useSdkIframeEmbedSetupContext();- const { isParameterHidden, toggleParameterVisibility } = useHideParameter({- settings,- updateSettings,- });+ const { isHiddenParameter, toggleParameterVisibility } =+ useParameterVisibility({+ settings,+ updateSettings,+ });- const isQuestionOrDashboardEmbed =- !!settings.questionId || !!settings.dashboardId;+ const { updateInitialParameterValue, removeInitialParameterValue } =+ useInitialParameterValues({+ settings,+ updateSettings,+ });- const updateInitialParameterValue = useDebouncedCallback(- useCallback(- (slug: string, value: ParameterValueOrArray | null | undefined) => {- if (settings.dashboardId) {- updateSettings({- initialParameters: {- ...settings.initialParameters,- [slug]: value,- },- });- } else if (settings.questionId) {- updateSettings({- initialSqlParameters: {- ...settings.initialSqlParameters,- [slug]: value,- },- });- }- },- [settings, updateSettings],- ),- SET_INITIAL_PARAMETER_DEBOUNCE_MS,+ const isGuestEmbed = !!settings.isGuest;+ const isQuestionOrDashboardEmbed = isQuestionOrDashboardSettings(+ experience,+ settings,);const uiParameters = useMemo(@@ -80,6 +70,34 @@ export const ParameterSettings = () => {);}+ if (isGuestEmbed) {+ const lockedParameters = getLockedPreviewParameters(+ availableParameters,+ embeddingParameters,+ );+ const resourceType = getResourceTypeFromExperience(experience);++ if (!resourceType) {+ return null;+ }++ return (+ <ParametersSettings+ resourceType={resourceType}+ resourceParameters={availableParameters}+ embeddingParams={embeddingParameters}+ lockedParameters={lockedParameters}+ parameterValues={parametersValuesById}+ withInitialValues+ onChangeEmbeddingParameters={onEmbeddingParametersChange}+ onChangeParameterValue={({ slug, value }) =>+ updateInitialParameterValue(slug, value)+ }+ onRemoveParameterValue={({ slug }) => removeInitialParameterValue(slug)}+ />+ );+ }+if (availableParameters.length > 0) {return (<Stack>@@ -100,7 +118,7 @@ export const ParameterSettings = () => {<ParameterVisibilityToggleparameterName={parameter.slug}experience={experience}- isHidden={isParameterHidden(parameter.slug)}+ isHidden={isHiddenParameter(parameter.slug)}onToggle={toggleParameterVisibility}/></Group>diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/hooks/use-hide-parameter.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/hooks/use-hide-parameter.tsdeleted file mode 100644index a5ad7f768cd..00000000000--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/ParameterSettings/hooks/use-hide-parameter.ts+++ /dev/null@@ -1,41 +0,0 @@-import { useCallback } from "react";--import type { SdkIframeEmbedSetupContextType } from "metabase/embedding/embedding-iframe-sdk-setup/context";--export function useHideParameter({- settings,- updateSettings,-}: Pick<SdkIframeEmbedSetupContextType, "settings" | "updateSettings">) {- const toggleParameterVisibility = useCallback(- (parameterName: string) => {- if (!settings.dashboardId && !settings.questionId) {- return;- }-- const hiddenParameters = settings?.hiddenParameters ?? [];-- const nextHiddenParameters = hiddenParameters.includes(parameterName)- ? hiddenParameters.filter((name) => name !== parameterName)- : [...hiddenParameters, parameterName];-- updateSettings({ hiddenParameters: nextHiddenParameters });- },- [settings, updateSettings],- );-- const isParameterHidden = useCallback(- (parameterName: string) => {- if (!settings.dashboardId && !settings.questionId) {- return true;- }-- return (settings.hiddenParameters ?? []).includes(parameterName);- },- [settings],- );-- return {- isParameterHidden,- toggleParameterVisibility,- };-}diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsxindex 48c209ac757..b6d0828bc9d 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsx@@ -10,13 +10,14 @@ import { match } from "ts-pattern";import { useSetting } from "metabase/common/hooks";import { METABASE_CONFIG_IS_PROXY_FIELD_NAME } from "metabase/embedding/embedding-iframe-sdk/constants";+// we import the equivalent of embed.js so that we don't add extra loading time+// by appending the scriptimport { setupConfigWatcher } from "metabase/embedding/embedding-iframe-sdk/embed";import type { SdkIframeEmbedBaseSettings } from "metabase/embedding/embedding-iframe-sdk/types/embed";+import { buildEmbedAttributes } from "metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes";import type { MetabaseTheme } from "metabase/embedding-sdk/theme";import { colors as defaultMetabaseColors } from "metabase/lib/colors";import { Card } from "metabase/ui";-// we import the equivalent of embed.js so that we don't add extra loading time-// by appending the scriptimport { useSdkIframeEmbedSetupContext } from "../context";import { getDerivedDefaultColorsForEmbedFlow } from "../utils/derived-colors-for-embed-flow";@@ -33,8 +34,9 @@ declare global {}}-export const SdkIframeEmbedPreview = () => {- const { settings } = useSdkIframeEmbedSetupContext();+const SdkIframeEmbedPreviewInner = () => {+ const { experience, settings, guestEmbedSignedTokenForPreview } =+ useSdkIframeEmbedSetupContext();const [isLoading, setIsLoading] = useState(true);const instanceUrl = useSetting("site-url");@@ -83,8 +85,9 @@ export const SdkIframeEmbedPreview = () => {instanceUrl,theme: derivedTheme,useExistingUserSession: true,+ isGuest: settings.isGuest,}),- [instanceUrl, derivedTheme],+ [instanceUrl, derivedTheme, settings.isGuest],);// initial configuration, needed so that the element finds the config on first render@@ -121,6 +124,13 @@ export const SdkIframeEmbedPreview = () => {}}, [settings.componentName]);+ const attributes = buildEmbedAttributes({+ experience,+ settings,+ token: guestEmbedSignedTokenForPreview,+ wrapWithQuotes: false,+ });+return (<CardclassName={S.EmbedPreviewIframe}@@ -133,60 +143,19 @@ export const SdkIframeEmbedPreview = () => {{match(settings).with({ componentName: "metabase-question", template: "exploration" },- (s) =>- createElement("metabase-question", {- "question-id": "new",- "is-save-enabled": s.isSaveEnabled,- "target-collection": s.targetCollection,- "entity-types": s.entityTypes- ? JSON.stringify(s.entityTypes)- : undefined,- }),+ () => createElement("metabase-question", attributes),)- .with({ componentName: "metabase-question" }, (s) =>- createElement("metabase-question", {- "question-id": s.questionId,- drills: s.drills,- "with-title": s.withTitle,- "with-downloads": s.withDownloads,- "is-save-enabled": s.isSaveEnabled,- "target-collection": s.targetCollection,- "entity-types": s.entityTypes- ? JSON.stringify(s.entityTypes)- : undefined,- "initial-sql-parameters": s.initialSqlParameters- ? JSON.stringify(s.initialSqlParameters)- : undefined,- "hidden-parameters": s.hiddenParameters- ? JSON.stringify(s.hiddenParameters)- : undefined,- }),+ .with({ componentName: "metabase-question" }, () =>+ createElement("metabase-question", attributes),)- .with({ componentName: "metabase-dashboard" }, (s) =>- createElement("metabase-dashboard", {- "dashboard-id": s.dashboardId,- drills: s.drills,- "with-title": s.withTitle,- "with-downloads": s.withDownloads,- "initial-parameters": s.initialParameters- ? JSON.stringify(s.initialParameters)- : undefined,- "hidden-parameters": s.hiddenParameters- ? JSON.stringify(s.hiddenParameters)- : undefined,- }),+ .with({ componentName: "metabase-dashboard" }, () =>+ createElement("metabase-dashboard", attributes),)- .with({ componentName: "metabase-browser" }, (s) =>- createElement("metabase-browser", {- "read-only": s.readOnly,- "initial-collection": s.initialCollection,- "collection-visible-columns": s.collectionVisibleColumns- ? JSON.stringify(s.collectionVisibleColumns)- : undefined,- }),+ .with({ componentName: "metabase-browser" }, () =>+ createElement("metabase-browser", attributes),)- .with({ componentName: "metabase-metabot" }, (s) =>- createElement("metabase-metabot", { layout: s.layout }),+ .with({ componentName: "metabase-metabot" }, () =>+ createElement("metabase-metabot", attributes),).exhaustive()}@@ -197,3 +166,19 @@ export const SdkIframeEmbedPreview = () => {</Card>);};++export const SdkIframeEmbedPreview = () => {+ const { settings } = useSdkIframeEmbedSetupContext();++ const remountKey = useMemo(+ () =>+ JSON.stringify({+ // We must re-mount preview when `isGuest` setting is changed+ // to force its change for embed.js+ isGuest: settings.isGuest,+ }),+ [settings.isGuest],+ );++ return <SdkIframeEmbedPreviewInner key={remountKey} />;+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal.tsxindex 365d82dcb14..8cfe1334c06 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal.tsx@@ -1,3 +1,4 @@+import cx from "classnames";import { useState } from "react";import { ResizableBox } from "react-resizable";import { match } from "ts-pattern";@@ -7,7 +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 CS from "metabase/css/core/index.css";+import { SdkIframeGuestEmbedStatusBar } from "metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeGuestEmbedStatusBar";+import { SdkIframeStepHeader } from "metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeStepHeader";import { useDispatch } from "metabase/lib/redux";import type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";import { closeModal } from "metabase/redux/ui";@@ -34,9 +37,15 @@ import { SdkIframeEmbedSetupProvider } from "./SdkIframeEmbedSetupProvider";export const SdkIframeEmbedSetupContent = () => {const dispatch = useDispatch();const [updateSettings] = useUpdateSettingsMutation();- const { currentStep, settings } = useSdkIframeEmbedSetupContext();-- const isSimpleEmbeddingEnabled = useSetting("enable-embedding-simple");+ const {+ isSimpleEmbedFeatureAvailable,+ isSimpleEmbeddingEnabled,+ isSimpleEmbeddingTermsAccepted,+ isGuestEmbedsEnabled,+ isGuestEmbedsTermsAccepted,+ currentStep,+ settings,+ } = useSdkIframeEmbedSetupContext();const { handleNext, handleBack, canGoBack, StepContent } =useSdkIframeEmbedNavigation();@@ -52,6 +61,10 @@ export const SdkIframeEmbedSetupContent = () => {dispatch(closeModal());}+ const allowPreviewAndNavigation = isSimpleEmbedFeatureAvailable+ ? isSimpleEmbeddingEnabled && isSimpleEmbeddingTermsAccepted+ : isGuestEmbedsEnabled && isGuestEmbedsTermsAccepted;+const nextStepButton = match(currentStep).with("get-code", () => (<Button@@ -63,7 +76,11 @@ export const SdkIframeEmbedSetupContent = () => {</Button>)).with("select-embed-options", () => (- <Button variant="filled" onClick={handleNext}>+ <Button+ variant="filled"+ disabled={!allowPreviewAndNavigation}+ onClick={handleNext}+ >{t`Get code`}</Button>))@@ -71,25 +88,40 @@ export const SdkIframeEmbedSetupContent = () => {<Buttonvariant="filled"onClick={handleNext}- disabled={!isSimpleEmbeddingEnabled}+ disabled={!allowPreviewAndNavigation}>{t`Next`}</Button>));return (- <Box className={S.Container}>+ <Box+ className={S.Container}+ data-testid="sdk-iframe-embed-setup-modal-content"+ ><SidebarResizer><Box className={S.Sidebar} component="aside">- <Box className={S.SidebarContent}>- <StepContent />- </Box>+ <Stack className={S.SidebarContent} gap="md">+ <Stack gap="md">+ <SdkIframeStepHeader />++ <Stack+ gap="md"+ opacity={allowPreviewAndNavigation ? 1 : 0.5}+ className={cx(+ !allowPreviewAndNavigation && CS.pointerEventsNone,+ )}+ >+ <StepContent />+ </Stack>+ </Stack>+ </Stack><Group className={S.Navigation} justify="space-between"><Buttonvariant="default"onClick={handleBack}- disabled={!canGoBack || !isSimpleEmbeddingEnabled}+ disabled={!canGoBack || !allowPreviewAndNavigation}>{t`Back`}</Button>@@ -103,7 +135,9 @@ export const SdkIframeEmbedSetupContent = () => {<Stack h="100%"><Modal.CloseButton />- {isSimpleEmbeddingEnabled ? (+ <SdkIframeGuestEmbedStatusBar />++ {allowPreviewAndNavigation ? (<SdkIframeEmbedPreview />) : (<Card h="100%">@@ -149,7 +183,10 @@ export const SdkIframeEmbedSetupModal = ({onClose={onClose}><Modal.Content style={{ overflow: "hidden" }}>- <SdkIframeEmbedSetupProvider initialState={initialState}>+ <SdkIframeEmbedSetupProvider+ initialState={initialState}+ onClose={onClose}+ ><SdkIframeEmbedSetupContent /></SdkIframeEmbedSetupProvider></Modal.Content>diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupProvider.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupProvider.tsxindex 7366e63f614..3d75880a216 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupProvider.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupProvider.tsx@@ -1,15 +1,23 @@import { type ReactNode, useMemo, useState } from "react";+import { useMount } from "react-use";import { useSearchQuery } from "metabase/api";-import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";+import { useSetting } from "metabase/common/hooks";+import { trackEmbedWizardOpened } from "metabase/embedding/embedding-iframe-sdk-setup/analytics";+import { useEmbeddingParameters } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters";+import { useGetGuestEmbedSignedToken } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token";+import {+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP,+ type SdkIframeEmbedSetupModalInitialState,+} from "metabase/plugins";import {SdkIframeEmbedSetupContext,type SdkIframeEmbedSetupContextType,} from "../context";import {+ useAvailableParameters,useGetCurrentResource,- useParameters,useParametersValues,useRecentItems,} from "../hooks";@@ -20,12 +28,27 @@ import { getExperienceFromSettings } from "../utils/get-default-sdk-iframe-embedinterface SdkIframeEmbedSetupProviderProps {children: ReactNode;initialState: SdkIframeEmbedSetupModalInitialState | undefined;+ onClose: () => void;}export const SdkIframeEmbedSetupProvider = ({children,initialState,+ onClose,}: SdkIframeEmbedSetupProviderProps) => {+ const isSimpleEmbedFeatureAvailable =+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled();++ const isSimpleEmbeddingEnabled = useSetting("enable-embedding-simple");+ const isSimpleEmbeddingTermsAccepted = !useSetting("show-simple-embed-terms");++ const isGuestEmbedsEnabled = useSetting("enable-embedding-static");+ const isGuestEmbedsTermsAccepted = !useSetting("show-static-embed-terms");++ useMount(() => {+ trackEmbedWizardOpened();+ });+// 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 {@@ -67,6 +90,8 @@ export const SdkIframeEmbedSetupProvider = ({recentDashboards,isRecentsLoading,modelCount,+ isSimpleEmbedFeatureAvailable,+ isGuestEmbedsEnabled,});// Which embed experience are we setting up?@@ -77,20 +102,51 @@ export const SdkIframeEmbedSetupProvider = ({const { resource, isError, isLoading, isFetching } = useGetCurrentResource({experience,- settings,+ dashboardId: settings.dashboardId,+ questionId: settings.questionId,});- const { availableParameters } = useParameters({- experience,+ const { availableParameters, initialAvailableParameters } =+ useAvailableParameters({+ experience,+ resource,+ });++ const {+ embeddingParameters,+ initialEmbeddingParameters,+ onEmbeddingParametersChange,+ } = useEmbeddingParameters({+ settings,+ updateSettings,resource,+ availableParameters,+ initialAvailableParameters,});- const { parametersValuesById } = useParametersValues({+ const { parametersValuesById, previewParameterValuesBySlug } =+ useParametersValues({+ settings,+ availableParameters,+ embeddingParameters,+ });++ const {+ signedTokenForSnippet: guestEmbedSignedTokenForSnippet,+ signedTokenForPreview: guestEmbedSignedTokenForPreview,+ } = useGetGuestEmbedSignedToken({settings,- availableParameters,+ experience,+ previewParameterValuesBySlug,+ embeddingParameters,});const value: SdkIframeEmbedSetupContextType = {+ isSimpleEmbedFeatureAvailable,+ isSimpleEmbeddingEnabled,+ isSimpleEmbeddingTermsAccepted,+ isGuestEmbedsEnabled,+ isGuestEmbedsTermsAccepted,currentStep,setCurrentStep,initialState,@@ -109,7 +165,14 @@ export const SdkIframeEmbedSetupProvider = ({addRecentItem,isEmbedSettingsLoaded,availableParameters,+ initialEmbeddingParameters,parametersValuesById,+ previewParameterValuesBySlug,+ embeddingParameters,+ onEmbeddingParametersChange,+ guestEmbedSignedTokenForSnippet,+ guestEmbedSignedTokenForPreview,+ onClose,};return (diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeGuestEmbedStatusBar.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeGuestEmbedStatusBar.tsxnew file mode 100644index 00000000000..73295c3a96c--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeGuestEmbedStatusBar.tsx@@ -0,0 +1,135 @@+import {+ useUpdateCardEmbeddingParamsMutation,+ useUpdateCardEnableEmbeddingMutation,+ useUpdateDashboardEmbeddingParamsMutation,+ useUpdateDashboardEnableEmbeddingMutation,+} from "metabase/api";+import { useSetting } from "metabase/common/hooks";+import { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";+import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import { getResourceTypeFromExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience";+import { isStepWithResource } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-step-with-resource";+import { EmbedModalContentStatusBar } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/EmbedModalContentStatusBar";+import type { StaticEmbedSetupPaneProps } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/StaticEmbedSetupPane";+import { getHasParamsChanged } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-has-params-changed";+import { getStaticEmbedSetupPublishHandlers } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-static-embed-setup-publish-handlers";+import type { EmbeddingParameters } from "metabase/public/lib/types";+import { Card } from "metabase/ui";++type Props = Pick<StaticEmbedSetupPaneProps, "resource" | "resourceType"> & {+ initialEmbeddingParameters: EmbeddingParameters;+};++const SdkIframeGuestEmbedStatusBarInner = ({+ resource,+ resourceType,+ initialEmbeddingParameters,+}: Props) => {+ const exampleDashboardId = useSetting("example-dashboard-id");+ const {+ availableParameters: resourceParameters,+ embeddingParameters,+ isFetching,+ onEmbeddingParametersChange,+ } = useSdkIframeEmbedSetupContext();++ const [updateDashboardEmbeddingParams] =+ useUpdateDashboardEmbeddingParamsMutation();+ const [updateDashboardEnableEmbedding] =+ useUpdateDashboardEnableEmbeddingMutation();+ const [updateCardEmbeddingParams] = useUpdateCardEmbeddingParamsMutation();+ const [updateCardEnableEmbedding] = useUpdateCardEnableEmbeddingMutation();++ const handleEnableEmbedding = async (enableEmbedding: boolean) => {+ const handlersMap = {+ dashboard: updateDashboardEnableEmbedding,+ question: updateCardEnableEmbedding,+ } as const;++ await handlersMap[resourceType]?.({+ id: resource.id as number,+ enable_embedding: enableEmbedding,+ embedding_type: enableEmbedding ? GUEST_EMBED_EMBEDDING_TYPE : null,+ });+ };++ const handleUpdateEmbeddingParams = async (+ embeddingParams: EmbeddingParameters,+ ) => {+ const handlersMap = {+ dashboard: updateDashboardEmbeddingParams,+ question: updateCardEmbeddingParams,+ } as const;++ await handlersMap[resourceType]?.({+ id: resource.id as number,+ embedding_params: embeddingParams,+ embedding_type: GUEST_EMBED_EMBEDDING_TYPE,+ });+ };++ const hasParamsChanged = getHasParamsChanged({+ initialEmbeddingParams: initialEmbeddingParameters,+ embeddingParams: embeddingParameters,+ });++ const { handleSave, handleUnpublish, handleDiscard } =+ getStaticEmbedSetupPublishHandlers({+ resource,+ resourceType,+ resourceParameters,+ onUpdateEnableEmbedding: handleEnableEmbedding,+ onUpdateEmbeddingParams: handleUpdateEmbeddingParams,+ embeddingParams: embeddingParameters,+ setEmbeddingParams: onEmbeddingParametersChange,+ exampleDashboardId,+ });++ return (+ <Card>+ <EmbedModalContentStatusBar+ resourceType={resourceType}+ isPublished={resource.enable_embedding}+ isFetching={isFetching}+ hasSettingsChanges={hasParamsChanged}+ onSave={handleSave}+ onUnpublish={handleUnpublish}+ onDiscard={handleDiscard}+ />+ </Card>+ );+};++export const SdkIframeGuestEmbedStatusBar = () => {+ const {+ currentStep,+ settings,+ resource,+ experience,+ initialEmbeddingParameters,+ } = useSdkIframeEmbedSetupContext();++ const isGuestEmbed = !!settings.isGuest;++ const resourceType = getResourceTypeFromExperience(experience);++ const shouldShowForStep = isStepWithResource(currentStep);+ const shouldShowForResource =+ resourceType === "dashboard" || resourceType === "question";++ if (!isGuestEmbed || !shouldShowForStep || !shouldShowForResource) {+ return null;+ }++ if (!resource || !resourceType || !initialEmbeddingParameters) {+ return null;+ }++ return (+ <SdkIframeGuestEmbedStatusBarInner+ resource={resource}+ resourceType={resourceType}+ initialEmbeddingParameters={initialEmbeddingParameters}+ />+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeStepHeader.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeStepHeader.tsxnew file mode 100644index 00000000000..4142d538afd--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeStepHeader.tsx@@ -0,0 +1,16 @@+import { EnableEmbeddedAnalyticsCard } from "metabase/embedding/embedding-iframe-sdk-setup/components/EnableEmbeddedAnalyticsCard";+import { EnableGuestEmbedsCard } from "metabase/embedding/embedding-iframe-sdk-setup/components/EnableGuestEmbedsCard";+import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";++export const SdkIframeStepHeader = () => {+ const { isSimpleEmbedFeatureAvailable, currentStep } =+ useSdkIframeEmbedSetupContext();++ const rerenderKey = currentStep;++ return isSimpleEmbedFeatureAvailable ? (+ <EnableEmbeddedAnalyticsCard key={rerenderKey} />+ ) : (+ <EnableGuestEmbedsCard key={rerenderKey} />+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedExperienceStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedExperienceStep.tsxindex 8c48674b050..f7ddbba01d2 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedExperienceStep.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedExperienceStep.tsx@@ -1,13 +1,12 @@-import cx from "classnames";import { P, match } from "ts-pattern";import { t } from "ttag";import _ from "underscore";-import { useSetting } from "metabase/common/hooks";-import CS from "metabase/css/core/index.css";import { ALLOWED_EMBED_SETTING_KEYS_MAP } from "metabase/embedding/embedding-iframe-sdk/constants";+import { UPSELL_CAMPAIGN_EXPERIENCE } from "metabase/embedding/embedding-iframe-sdk-setup/analytics";+import { WithSimpleEmbeddingFeatureUpsellTooltip } from "metabase/embedding/embedding-iframe-sdk-setup/components/warnings/WithSimpleEmbeddingFeatureUpsellTooltip";import { PLUGIN_METABOT } from "metabase/plugins";-import { Card, Radio, Stack, Text } from "metabase/ui";+import { Card, Flex, Radio, Stack, Text } from "metabase/ui";import {EMBED_FALLBACK_DASHBOARD_ID,@@ -18,10 +17,11 @@ import { useSdkIframeEmbedSetupContext } from "../context";import type { SdkIframeEmbedSetupExperience } from "../types";import { getDefaultSdkIframeEmbedSettings } from "../utils/get-default-sdk-iframe-embed-setting";-import { EnableEmbeddedAnalyticsCard } from "./EnableEmbeddedAnalyticsCard";-export const SelectEmbedExperienceStep = () => {const {+ isSimpleEmbedFeatureAvailable,+ isGuestEmbedsEnabled,+ initialState,experience,settings,replaceSettings,@@ -29,7 +29,6 @@ export const SelectEmbedExperienceStep = () => {recentQuestions,} = useSdkIframeEmbedSetupContext();- const isSimpleEmbeddingEnabled = useSetting("enable-embedding-simple");const isMetabotAvailable = PLUGIN_METABOT.isEnabled();const handleEmbedExperienceChange = (@@ -57,48 +56,58 @@ export const SelectEmbedExperienceStep = () => {// these settings are overridden when the embed type changes...getDefaultSdkIframeEmbedSettings({+ initialState,experience,resourceId: defaultResourceId,+ isGuestEmbedsEnabled,}),});};- const experiences = getEmbedExperiences({ isMetabotAvailable });+ const experiences = getEmbedExperiences({+ isSimpleEmbedFeatureAvailable,+ isMetabotAvailable,+ });return (- <>- <EnableEmbeddedAnalyticsCard />+ <Card p="md" mb="md">+ <Text size="lg" fw="bold" mb="md">+ {t`Select your embed experience`}+ </Text>- <Card- p="md"- mb="md"- opacity={isSimpleEmbeddingEnabled ? 1 : 0.5}- className={cx(!isSimpleEmbeddingEnabled && CS.pointerEventsNone)}+ <Radio.Group+ value={experience}+ onChange={(experience) =>+ handleEmbedExperienceChange(+ experience as SdkIframeEmbedSetupExperience,+ )+ }>- <Text size="lg" fw="bold" mb="md">- {t`Select your embed experience`}- </Text>-- <Radio.Group- value={experience}- onChange={(experience) =>- handleEmbedExperienceChange(- experience as SdkIframeEmbedSetupExperience,- )- }- >- <Stack gap="md">- {experiences.map((experience) => (- <Radio- key={experience.value}- value={experience.value}- label={experience.title}- description={experience.description}- />- ))}- </Stack>- </Radio.Group>- </Card>- </>+ <Stack gap="md">+ {experiences.map((experience) => (+ <WithSimpleEmbeddingFeatureUpsellTooltip+ key={experience.value}+ mode="custom"+ enableTooltip={experience.showUpsell === true}+ campaign={UPSELL_CAMPAIGN_EXPERIENCE}+ >+ {({ disabled, hoverCard }) => (+ <Radio+ value={experience.value}+ label={+ <Flex gap="xs" align="center">+ {experience.title}+ {hoverCard}+ </Flex>+ }+ description={experience.description}+ disabled={disabled}+ />+ )}+ </WithSimpleEmbeddingFeatureUpsellTooltip>+ ))}+ </Stack>+ </Radio.Group>+ </Card>);};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsxindex b166a0ebb86..0c5cd362665 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx@@ -1,23 +1,166 @@-import { useCallback, useMemo } from "react";+import { type ReactNode, useCallback, useMemo } from "react";import { P, match } from "ts-pattern";import { t } from "ttag";+import { useSetting } from "metabase/common/hooks";+import {+ UPSELL_CAMPAIGN_AUTH,+ UPSELL_CAMPAIGN_BEHAVIOR,+} from "metabase/embedding/embedding-iframe-sdk-setup/analytics";+import { getAuthTypeForSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-auth-type-for-settings";+import { isQuestionOrDashboardSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings";import type { MetabaseColors } from "metabase/embedding-sdk/theme";-import { Card, Checkbox, Divider, Stack, Text } from "metabase/ui";+import {+ Card,+ Checkbox,+ Divider,+ Flex,+ HoverCard,+ Icon,+ Radio,+ Stack,+ Text,+} from "metabase/ui";import { useSdkIframeEmbedSetupContext } from "../context";import { ColorCustomizationSection } from "./ColorCustomizationSection";+import { LegacyStaticEmbeddingAlert } from "./LegacyStaticEmbeddingAlert";import { MetabotLayoutSetting } from "./MetabotLayoutSetting";import { ParameterSettings } from "./ParameterSettings";+import {+ TooltipWarning,+ type TooltipWarningMode,+} from "./warnings/TooltipWarning";+import { WithSimpleEmbeddingFeatureUpsellTooltip } from "./warnings/WithSimpleEmbeddingFeatureUpsellTooltip";++export const SelectEmbedOptionsStep = () => (+ <Stack gap="md">+ <AuthenticationSection />+ <BehaviorSection />+ <ParametersSection />+ <AppearanceSection />+ <LegacyStaticEmbeddingAlert />+ </Stack>+);++const AuthenticationSection = () => {+ const {+ isSimpleEmbedFeatureAvailable,+ experience,+ settings,+ updateSettings,+ } = useSdkIframeEmbedSetupContext();++ const isQuestionOrDashboardEmbed = isQuestionOrDashboardSettings(+ experience,+ settings,+ );++ const isJwtEnabled = useSetting("jwt-enabled");+ const isSamlEnabled = useSetting("saml-enabled");+ const isJwtConfigured = useSetting("jwt-configured");+ const isSamlConfigured = useSetting("saml-configured");++ const isSsoEnabledAndConfigured =+ (isJwtEnabled && isJwtConfigured) || (isSamlEnabled && isSamlConfigured);++ const authType = getAuthTypeForSettings(settings);++ const handleAuthTypeChange = (value: string) => {+ const isGuest = value === "guest-embed";+ const useExistingUserSession = value === "user-session";++ updateSettings({+ isGuest,+ useExistingUserSession,+ });+ };++ /* eslint-disable-next-line no-literal-metabase-strings -- this string is only shown for admins. */+ const existingMetabaseSessionLabel = t`Existing Metabase session`;-export const SelectEmbedOptionsStep = () => {return (- <Stack gap="md">- <BehaviorSection />- <ParametersSection />- <AppearanceSection />- </Stack>+ <Card p="md">+ <Stack gap="md" p="xs">+ <Text size="lg" fw="bold">+ {t`Authentication`}+ </Text>++ <Radio.Group value={authType} onChange={handleAuthTypeChange}>+ <Stack gap="sm">+ {isQuestionOrDashboardEmbed && (+ <WithGuestEmbedsDisabledWarning>+ {({ disabled }) => (+ <Radio+ disabled={disabled}+ value="guest-embed"+ label={t`Guest`}+ />+ )}+ </WithGuestEmbedsDisabledWarning>+ )}++ <WithSimpleEmbeddingFeatureUpsellTooltip+ enableTooltip={!isSimpleEmbedFeatureAvailable}+ campaign={UPSELL_CAMPAIGN_AUTH}+ >+ {({ disabled }) => (+ <Radio+ value="user-session"+ label={+ disabled ? (+ existingMetabaseSessionLabel+ ) : (+ <Flex align="center" gap="xs">+ <Text>{existingMetabaseSessionLabel}</Text>+ <HoverCard position="bottom">+ <HoverCard.Target>+ <Icon+ name="info"+ size={14}+ c="text-medium"+ cursor="pointer"+ style={{ flexShrink: 0 }}+ />+ </HoverCard.Target>+ <HoverCard.Dropdown>+ <Text lh="md" p="md" style={{ width: 300 }}>+ {/* eslint-disable-next-line no-literal-metabase-strings -- this string is only shown for admins. */}+ {t`This option lets you test Embedded Analytics JS locally using your existing Metabase session cookie. This only works for testing locally, using your admin account and on this browser. This may not work on Safari and Firefox. We recommend testing this in Chrome.`}+ </Text>+ </HoverCard.Dropdown>+ </HoverCard>+ </Flex>+ )+ }+ disabled={disabled}+ />+ )}+ </WithSimpleEmbeddingFeatureUpsellTooltip>++ <WithSimpleEmbeddingFeatureUpsellTooltip+ enableTooltip={!isSimpleEmbedFeatureAvailable}+ campaign={UPSELL_CAMPAIGN_AUTH}+ >+ {({ disabled }) => (+ <Radio+ value="sso"+ label={t`Single sign-on (SSO)`}+ disabled={disabled || !isSsoEnabledAndConfigured}+ />+ )}+ </WithSimpleEmbeddingFeatureUpsellTooltip>+ </Stack>+ </Radio.Group>++ {authType === "sso" && (+ <Text size="sm" c="text-medium">+ {t`Select this option if you have already set up SSO. This option relies on SSO to sign in your application users into the embedded iframe, and groups and permissions to enforce limits on what users can access. `}+ </Text>+ )}+ </Stack>+ </Card>);};@@ -26,38 +169,65 @@ const BehaviorSection = () => {const behaviorSection = useMemo(() => {return match(settings)- .with({ template: "exploration" }, (settings) => (- <Checkbox- label={t`Allow people to save new questions`}- checked={settings.isSaveEnabled}- onChange={(e) => updateSettings({ isSaveEnabled: e.target.checked })}- />- ))+ .with(+ { template: "exploration", isGuest: P.optional(false) },+ (settings) => (+ <Checkbox+ label={t`Allow people to save new questions`}+ disabled={settings.isGuest}+ checked={settings.isSaveEnabled}+ onChange={(e) =>+ updateSettings({ isSaveEnabled: e.target.checked })+ }+ />+ ),+ ).with({ componentName: "metabase-question", questionId: P.nonNullable },(settings) => (<Stack gap="md">- <Checkbox- label={t`Allow people to drill through on data points`}- checked={settings.drills}- onChange={(e) => updateSettings({ drills: e.target.checked })}- />-- <Checkbox- label={t`Allow downloads`}- checked={settings.withDownloads}- onChange={(e) =>- updateSettings({ withDownloads: e.target.checked })- }- />-- <Checkbox- label={t`Allow people to save new questions`}- checked={settings.isSaveEnabled}- onChange={(e) =>- updateSettings({ isSaveEnabled: e.target.checked })- }- />+ <WithNotAvailableForGuestEmbedsWarning+ campaign={UPSELL_CAMPAIGN_BEHAVIOR}+ >+ {({ disabled }) => (+ <Checkbox+ label={t`Allow people to drill through on data points`}+ disabled={disabled}+ checked={settings.drills}+ onChange={(e) => updateSettings({ drills: e.target.checked })}+ />+ )}+ </WithNotAvailableForGuestEmbedsWarning>++ <WithNotAvailableWithoutSimpleEmbeddingFeatureWarning+ campaign={UPSELL_CAMPAIGN_BEHAVIOR}+ >+ {({ disabled }) => (+ <Checkbox+ label={t`Allow downloads`}+ disabled={disabled}+ checked={settings.withDownloads}+ onChange={(e) =>+ updateSettings({ withDownloads: e.target.checked })+ }+ />+ )}+ </WithNotAvailableWithoutSimpleEmbeddingFeatureWarning>++ <WithNotAvailableForGuestEmbedsWarning+ campaign={UPSELL_CAMPAIGN_BEHAVIOR}+ >+ {({ disabled }) => (+ <Checkbox+ label={t`Allow people to save new questions`}+ disabled={disabled}+ checked={settings.isSaveEnabled}+ onChange={(e) =>+ updateSettings({ isSaveEnabled: e.target.checked })+ }+ />+ )}+ </WithNotAvailableForGuestEmbedsWarning></Stack>),)@@ -65,29 +235,47 @@ const BehaviorSection = () => {{ componentName: "metabase-dashboard", dashboardId: P.nonNullable },(settings) => (<Stack gap="md">- <Checkbox- label={t`Allow people to drill through on data points`}- checked={settings.drills}- onChange={(e) => updateSettings({ drills: e.target.checked })}- />-- <Checkbox- label={t`Allow downloads`}- checked={settings.withDownloads}- onChange={(e) =>- updateSettings({ withDownloads: e.target.checked })- }- />+ <WithNotAvailableForGuestEmbedsWarning+ campaign={UPSELL_CAMPAIGN_BEHAVIOR}+ >+ {({ disabled }) => (+ <Checkbox+ label={t`Allow people to drill through on data points`}+ disabled={disabled}+ checked={settings.drills}+ onChange={(e) => updateSettings({ drills: e.target.checked })}+ />+ )}+ </WithNotAvailableForGuestEmbedsWarning>++ <WithNotAvailableWithoutSimpleEmbeddingFeatureWarning+ campaign={UPSELL_CAMPAIGN_BEHAVIOR}+ >+ {({ disabled }) => (+ <Checkbox+ label={t`Allow downloads`}+ disabled={disabled}+ checked={settings.withDownloads}+ onChange={(e) =>+ updateSettings({ withDownloads: e.target.checked })+ }+ />+ )}+ </WithNotAvailableWithoutSimpleEmbeddingFeatureWarning></Stack>),)- .with({ componentName: "metabase-browser" }, (settings) => (- <Checkbox- label={t`Allow editing dashboards and questions`}- checked={!settings.readOnly}- onChange={(e) => updateSettings({ readOnly: !e.target.checked })}- />- ))+ .with(+ { componentName: "metabase-browser", isGuest: P.optional(false) },+ (settings) => (+ <Checkbox+ label={t`Allow editing dashboards and questions`}+ disabled={settings.isGuest}+ checked={!settings.readOnly}+ onChange={(e) => updateSettings({ readOnly: !e.target.checked })}+ />+ ),+ ).otherwise(() => null);}, [settings, updateSettings]);@@ -168,14 +356,110 @@ const AppearanceSection = () => {return (<Card p="md">- <ColorCustomizationSection- theme={theme}- onColorChange={updateColors}- onColorReset={() => updateSettings({ theme: undefined })}- />+ <WithNotAvailableWithoutSimpleEmbeddingFeatureWarning+ mode="custom"+ campaign={UPSELL_CAMPAIGN_BEHAVIOR}+ >+ {({ disabled, hoverCard }) => (+ <ColorCustomizationSection+ theme={theme}+ disabled={disabled}+ hoverCard={hoverCard}+ onColorChange={updateColors}+ onColorReset={() => updateSettings({ theme: undefined })}+ />+ )}+ </WithNotAvailableWithoutSimpleEmbeddingFeatureWarning>{appearanceSection && <Divider mt="lg" mb="md" />}{appearanceSection}</Card>);};++const WithGuestEmbedsDisabledWarning = ({+ children,+}: {+ children: (data: { disabled: boolean }) => ReactNode;+}) => {+ const { isGuestEmbedsEnabled } = useSdkIframeEmbedSetupContext();++ const disabled = !isGuestEmbedsEnabled;++ return (+ <TooltipWarning+ warning={+ <Text lh="md" p="md">+ {t`Disabled in the admin settings`}+ </Text>+ }+ disabled={disabled}+ >+ {children}+ </TooltipWarning>+ );+};++const WithNotAvailableWithoutSimpleEmbeddingFeatureWarning = ({+ mode,+ children,+ campaign,+}: {+ mode?: TooltipWarningMode;+ children: (data: { disabled: boolean; hoverCard: ReactNode }) => ReactNode;+ campaign: string;+}) => {+ const { isSimpleEmbedFeatureAvailable } = useSdkIframeEmbedSetupContext();++ return (+ <WithSimpleEmbeddingFeatureUpsellTooltip+ mode={mode}+ enableTooltip={!isSimpleEmbedFeatureAvailable}+ campaign={campaign}+ >+ {({ disabled, hoverCard }) => children({ disabled, hoverCard })}+ </WithSimpleEmbeddingFeatureUpsellTooltip>+ );+};++const WithNotAvailableForGuestEmbedsWarning = ({+ mode,+ children,+ campaign,+}: {+ mode?: TooltipWarningMode;+ children: (data: { disabled: boolean; hoverCard: ReactNode }) => ReactNode;+ campaign: string;+}) => {+ const { settings } = useSdkIframeEmbedSetupContext();++ return (+ <WithNotAvailableWithoutSimpleEmbeddingFeatureWarning+ mode={mode}+ campaign={campaign}+ >+ {({ disabled: disabledForOss, hoverCard: disabledForOssHoverCard }) => (+ <TooltipWarning+ enableTooltip={!disabledForOss}+ warning={+ <Text lh="md" p="md">+ {t`Not available if Guest Mode is selected`}+ </Text>+ }+ disabled={!!settings.isGuest}+ >+ {({+ disabled: disabledForGuestEmbeds,+ hoverCard: disabledForGuestEmbedsHoverCard,+ }) =>+ children({+ disabled: disabledForOss || disabledForGuestEmbeds,+ hoverCard:+ disabledForOssHoverCard || disabledForGuestEmbedsHoverCard,+ })+ }+ </TooltipWarning>+ )}+ </WithNotAvailableWithoutSimpleEmbeddingFeatureWarning>+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsxindex d84fdd06dc0..20ede1c18a7 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsx@@ -68,6 +68,7 @@ export const SelectEmbedResourceStep = () => {// Clear parametersinitialParameters: {},hiddenParameters: [],+ lockedParameters: [],});} else if (experience === "chart") {updateSettings({@@ -76,6 +77,7 @@ export const SelectEmbedResourceStep = () => {// Clear parametersinitialSqlParameters: {},hiddenParameters: [],+ lockedParameters: [],});} else if (experience === "browser") {updateSettings({diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsxindex 04d1d447b72..a12f9a476d5 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup-embedding-hub.unit.spec.tsx@@ -1,10 +1,19 @@import userEvent from "@testing-library/user-event";import { screen } from "__support__/ui";+import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";import { setup, waitForUpdateSetting } from "./test-setup";describe("Embed flow > embedding hub step completion tracking", () => {+ beforeEach(() => {+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = jest.fn(() => true);+ });++ afterEach(() => {+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = () => false;+ });+afterEach(() => {jest.clearAllMocks();});@@ -20,6 +29,7 @@ describe("Embed flow > embedding hub step completion tracking", () => {setup({jwtReady: !useExistingUserSession,simpleEmbeddingEnabled: true,+ showSimpleEmbedTerms: false,initialState: {useExistingUserSession,},@@ -27,7 +37,6 @@ describe("Embed flow > embedding hub step completion tracking", () => {await userEvent.click(screen.getByRole("button", { name: "Next" }));await userEvent.click(screen.getByRole("button", { name: "Next" }));- await userEvent.click(screen.getByRole("button", { name: "Get code" }));const authRadio = screen.getByDisplayValue(useExistingUserSession ? "user-session" : "sso",@@ -36,6 +45,8 @@ describe("Embed flow > embedding hub step completion tracking", () => {await userEvent.click(authRadio);expect(authRadio).toBeChecked();+ await userEvent.click(screen.getByRole("button", { name: "Get code" }));+const actionButton = screen.getByRole("button", {name: trigger === "copy" ? /Copy code/ : /Done/,});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsxindex 4e04240c210..eb90eeda024 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx@@ -5,6 +5,7 @@ import {setupCardQueryMetadataEndpoint,} from "__support__/server-mocks";import { screen } from "__support__/ui";+import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";import {createMockCard,createMockCardQueryMetadata,@@ -31,6 +32,14 @@ describe("Embed flow > initial setup", () => {});describe("Embed flow > forward and backward navigation", () => {+ beforeEach(() => {+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = jest.fn(() => true);+ });++ afterEach(() => {+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = () => false;+ });+it("navigates forward through the embed flow", async () => {setup({ simpleEmbeddingEnabled: true });@@ -43,6 +52,8 @@ describe("Embed flow > forward and backward navigation", () => {expect(screen.getByRole("button", { name: "Back" })).toBeEnabled();await userEvent.click(screen.getByRole("button", { name: "Next" }));++ expect(screen.getByText("Authentication")).toBeInTheDocument();expect(screen.getByText("Behavior")).toBeInTheDocument();expect(screen.getByText("Appearance")).toBeInTheDocument();expect(@@ -50,9 +61,7 @@ describe("Embed flow > forward and backward navigation", () => {).toBeInTheDocument();await userEvent.click(screen.getByRole("button", { name: "Get code" }));- expect(- screen.getByText("Choose the authentication method for embedding:"),- ).toBeInTheDocument();+expect(screen.queryByRole("button", { name: "Next" }),).not.toBeInTheDocument();@@ -103,10 +112,8 @@ describe("Embed flow > forward and backward navigation", () => {expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();expect(screen.getByRole("button", { name: "Back" })).toBeDisabled();});-});-describe("Embed flow > pre-selection via url parameter", () => {- it("pre-selects question when resource_type=question is in URL", async () => {+ it("pre-selects question when resourceType: question is the initial state", async () => {const mockDatabase = createMockDatabase();const mockCard = createMockCard({ id: 456 });diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsxindex 9d9f03ee985..ea89bc56ed8 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx@@ -1,3 +1,4 @@+import { setupEnterprisePlugins } from "__support__/enterprise";import {findRequests,setupDashboardEndpoints,@@ -7,27 +8,47 @@ import {setupUpdateSettingEndpoint,setupUpdateSettingsEndpoint,} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";import { renderWithProviders, waitFor } from "__support__/ui";import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";import {createMockDashboard,createMockDashboardQueryMetadata,createMockDatabase,+ createMockSettings,+ createMockTokenFeatures,} from "metabase-types/api/mocks";-import {- createMockSettingsState,- createMockState,-} from "metabase-types/store/mocks";+import { createMockState } from "metabase-types/store/mocks";import { SdkIframeEmbedSetupModal } from "../SdkIframeEmbedSetupModal";export const setup = (options?: {+ hasEnterprisePlugins?: boolean;simpleEmbeddingEnabled?: boolean;+ showSimpleEmbedTerms?: boolean;jwtReady?: boolean;initialState?: SdkIframeEmbedSetupModalInitialState;}) => {+ const { hasEnterprisePlugins = true } = options ?? {};+const mockDatabase = createMockDatabase();const mockDashboard = createMockDashboard();++ if (hasEnterprisePlugins) {+ setupEnterprisePlugins();+ }++ const tokenFeatures = createMockTokenFeatures({+ embedding_simple: options?.simpleEmbeddingEnabled ?? false,+ });+ const settingValues = createMockSettings({+ "token-features": tokenFeatures,+ "show-simple-embed-terms": options?.showSimpleEmbedTerms ?? false,+ "enable-embedding-simple": options?.simpleEmbeddingEnabled ?? false,+ "jwt-enabled": options?.jwtReady ?? false,+ "jwt-configured": options?.jwtReady ?? false,+ });+setupRecentViewsAndSelectionsEndpoints([], ["selections", "views"]);setupSearchEndpoints([]);setupDashboardEndpoints(mockDashboard);@@ -44,6 +65,7 @@ export const setup = (options?: {<SdkIframeEmbedSetupModalopenedinitialState={{+ isGuest: false,useExistingUserSession: true,...options?.initialState,}}@@ -51,24 +73,12 @@ export const setup = (options?: {/>,{storeInitialState: createMockState({- settings: createMockSettingsState({- "enable-embedding-simple": options?.simpleEmbeddingEnabled ?? false,- "jwt-enabled": options?.jwtReady ?? false,- "jwt-configured": options?.jwtReady ?? false,- }),+ settings: mockSettings(settingValues),}),},);};-export async function waitForPutRequests() {- return waitFor(async () => {- const puts = await findRequests("PUT");- expect(puts.length).toBeGreaterThan(0);- return puts;- });-}-export async function waitForUpdateSetting(settingKey: string, value: any) {return waitFor(async () => {const puts = await findRequests("PUT");diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/warnings/TooltipWarning.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/warnings/TooltipWarning.tsxnew file mode 100644index 00000000000..9bbf310ea6b--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/warnings/TooltipWarning.tsx@@ -0,0 +1,71 @@+import type { ReactNode } from "react";++import CS from "metabase/css/core/index.css";+import { Box, Flex, HoverCard, Icon } from "metabase/ui";++export type TooltipWarningMode = "default" | "custom";++export const TooltipWarning = ({+ children,+ mode = "default",+ enableTooltip = true,+ icon,+ warning,+ disabled,+}: {+ mode?: TooltipWarningMode;+ children: (data: {+ disabled: boolean;+ hoverCard: ReactNode | null;+ }) => ReactNode;+ enableTooltip?: boolean;+ icon?: ReactNode;+ warning: ReactNode;+ disabled: boolean;+}) => {+ if (!enableTooltip) {+ return children({ disabled: false, hoverCard: null });+ }++ const iconElement = (+ <Box>+ {icon ?? (+ <Icon+ name={"info"}+ size={14}+ c="text-medium"+ cursor="pointer"+ style={{ flexShrink: 0 }}+ />+ )}+ </Box>+ );+ const hoverCard = disabled ? (+ <HoverCard position="bottom">+ <HoverCard.Target>+ <Box className={CS.cursorPointer}>{iconElement}</Box>+ </HoverCard.Target>+ <HoverCard.Dropdown>{warning}</HoverCard.Dropdown>+ </HoverCard>+ ) : null;++ const isCustomMode = mode === "custom";++ if (isCustomMode) {+ return children({+ disabled,+ hoverCard,+ });+ }++ return (+ <Flex align="center" gap="xs" data-testid="tooltip-warning">+ {children({+ disabled,+ hoverCard: null,+ })}++ {hoverCard}+ </Flex>+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/warnings/WithSimpleEmbeddingFeatureUpsellTooltip.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/warnings/WithSimpleEmbeddingFeatureUpsellTooltip.tsxnew file mode 100644index 00000000000..7ae5f22f895--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/warnings/WithSimpleEmbeddingFeatureUpsellTooltip.tsx@@ -0,0 +1,56 @@+import type { ReactNode } from "react";+import { t } from "ttag";++import { UpsellGem } from "metabase/admin/upsells/components";+import { UpsellCard } from "metabase/common/components/UpsellCard";+import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import { useSelector } from "metabase/lib/redux";+import { getUpgradeUrl } from "metabase/selectors/settings";++import { TooltipWarning, type TooltipWarningMode } from "./TooltipWarning";++const UPSELL_CARD_WIDTH = 252;++export const WithSimpleEmbeddingFeatureUpsellTooltip = ({+ mode,+ children,+ enableTooltip,+ campaign,+}: {+ mode?: TooltipWarningMode;+ children: (data: { disabled: boolean; hoverCard: ReactNode }) => ReactNode;+ enableTooltip: boolean;+ campaign: string;+}) => {+ const { settings } = useSdkIframeEmbedSetupContext();++ const disabled = !!settings.isGuest;++ const upgradeUrl = useSelector((state) =>+ getUpgradeUrl(state, { utm_content: "embedding-page" }),+ );++ return (+ <TooltipWarning+ mode={mode}+ enableTooltip={enableTooltip}+ icon={<UpsellGem />}+ warning={+ <UpsellCard+ title={t`Get more powerful embedding`}+ buttonLink={upgradeUrl}+ campaign={campaign}+ location="embedded_analytics_js_wizard"+ /* eslint-disable-next-line no-literal-metabase-strings -- Button text */+ buttonText={t`Upgrade to Metabase Pro`}+ maxWidth={UPSELL_CARD_WIDTH}+ >+ {t`Upgrade to get access to embeds with single sign-on, drill through, the SDK for React, and more.`}+ </UpsellCard>+ }+ disabled={disabled}+ >+ {children}+ </TooltipWarning>+ );+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/constants.tsindex 9b260fa4c1a..10f1845166a 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/constants.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/constants.ts@@ -13,8 +13,10 @@ import type {export const EMBED_RESOURCE_LIST_MAX_RECENTS = 6;export const getEmbedExperiences = ({+ isSimpleEmbedFeatureAvailable,isMetabotAvailable,}: {+ isSimpleEmbedFeatureAvailable: boolean;isMetabotAvailable: boolean;}) =>[@@ -32,11 +34,13 @@ export const getEmbedExperiences = ({value: "exploration",title: t`Exploration`,description: t`Embed an interactive data exploration experience`,+ showUpsell: !isSimpleEmbedFeatureAvailable,},{value: "browser",title: t`Browser`,description: t`Embed a browser to manage dashboards and charts`,+ showUpsell: !isSimpleEmbedFeatureAvailable,},...(isMetabotAvailable? [@@ -44,6 +48,7 @@ export const getEmbedExperiences = ({value: "metabot" as const,title: t`Metabot`,description: t`Embed a Metabot chat interface`,+ showUpsell: !isSimpleEmbedFeatureAvailable,},]: []),@@ -51,6 +56,7 @@ export const getEmbedExperiences = ({title: string;description: string;value: SdkIframeEmbedSetupExperience;+ showUpsell?: boolean;}[];type EmbedStepConfig = {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/context.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/context.tsindex 470dabf67ba..db2241e3eb0 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/context.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/context.ts@@ -1,7 +1,10 @@import { createContext, useContext } from "react";import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";-import type { EmbeddingParametersValues } from "metabase/public/lib/types";+import type {+ EmbeddingParameters,+ EmbeddingParametersValues,+} from "metabase/public/lib/types";import type { Card, Dashboard, Parameter } from "metabase-types/api";import type {@@ -13,6 +16,16 @@ import type {} from "./types";export interface SdkIframeEmbedSetupContextType {+ // User features+ isSimpleEmbedFeatureAvailable: boolean;++ // User settings+ isSimpleEmbeddingEnabled: boolean;+ isSimpleEmbeddingTermsAccepted: boolean;++ isGuestEmbedsEnabled: boolean;+ isGuestEmbedsTermsAccepted: boolean;+// NavigationcurrentStep: SdkIframeEmbedSetupStep;setCurrentStep: (step: SdkIframeEmbedSetupStep) => void;@@ -48,9 +61,22 @@ export interface SdkIframeEmbedSetupContextType {// Parameters for dashboards and questionsavailableParameters: Parameter[];+ initialEmbeddingParameters: EmbeddingParameters | null;parametersValuesById: EmbeddingParametersValues;+ previewParameterValuesBySlug: EmbeddingParametersValues;+ embeddingParameters: EmbeddingParameters;+ onEmbeddingParametersChange: (+ embeddingParameters: EmbeddingParameters,+ ) => void;isEmbedSettingsLoaded: boolean;++ // guest embed+ guestEmbedSignedTokenForSnippet: string | null;+ guestEmbedSignedTokenForPreview: string | null;++ // modal handlers+ onClose: () => void;}export const SdkIframeEmbedSetupContext =diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/index.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/index.tsindex c1227e0acda..76b217f3b72 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/index.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/index.ts@@ -1,6 +1,6 @@export { useGetCurrentResource } from "./use-get-current-resource";export { useRecentItems } from "./use-recent-items";-export { useParameters } from "./use-parameters";+export { useAvailableParameters } from "./use-available-parameters";export { useParametersValues } from "./use-parameters-values";export { useSdkIframeEmbedSnippet } from "./use-sdk-iframe-embed-snippet";export { useSdkIframeEmbedNavigation } from "./use-sdk-iframe-embed-navigation";diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.tssimilarity index 72%rename from frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters.tsrename to frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.tsindex 169d6cb1293..f6c970aa696 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts@@ -1,5 +1,5 @@-import { useEffect, useMemo } from "react";-import { useLatest } from "react-use";+import { useEffect, useMemo, useRef } from "react";+import { useLatest, usePrevious } from "react-use";import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";import { useDispatch, useSelector } from "metabase/lib/redux";@@ -14,13 +14,18 @@ type UseParameterListProps = {resource: Dashboard | Card | null;};-export const useParameters = ({+export const useAvailableParameters = ({experience,resource,}: UseParameterListProps) => {const dispatch = useDispatch();const metadata = useSelector(getMetadata);+ // We need initial available parameters to display the `discard changes` button+ // and reset user selected parameters back to initial parameters+ const initialAvailableParametersRef = useRef<Parameter[] | null>(null);+ const prevResourceId = usePrevious(resource?.id);+// This prevents `availableParameters` from being updated on every metadata change,// which would cause unnecessary re-renders in the component using this hook.// See [PublicOrEmbeddedQuestion.tsx] for reference.@@ -48,6 +53,15 @@ export const useParameters = ({return [];}, [resource, experience, metadata, metadataRef]);+ // Reset initial parameters when the resource changes+ if (resource?.id !== prevResourceId) {+ initialAvailableParametersRef.current = null;+ }++ if (resource && initialAvailableParametersRef.current === null) {+ initialAvailableParametersRef.current = availableParameters;+ }+useEffect(() => {if (resource && "param_fields" in resource && resource.param_fields) {// This is needed to make some parameter widget populate the dropdown list@@ -58,5 +72,6 @@ export const useParameters = ({return {availableParameters,+ initialAvailableParameters: initialAvailableParametersRef.current,};};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.tsnew file mode 100644index 00000000000..05140470ca6--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.ts@@ -0,0 +1,330 @@+import { renderHook } from "@testing-library/react";++import { useAvailableParameters } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters";+import type { Card, Dashboard } from "metabase-types/api";+import {+ createMockCard,+ createMockDashboard,+ createMockParameter,+} from "metabase-types/api/mocks";++const mockDispatch = jest.fn();++jest.mock("metabase/lib/redux", () => ({+ useDispatch: () => mockDispatch,+ useSelector: jest.fn(),+}));++jest.mock("metabase/parameters/utils/dashboards", () => ({+ getSavedDashboardUiParameters: jest.fn(),+}));++jest.mock("metabase-lib/v1/parameters/utils/cards", () => ({+ getCardUiParameters: jest.fn(),+}));++jest.mock("metabase/redux/metadata", () => ({+ addFields: jest.fn((fields) => ({ type: "ADD_FIELDS", payload: fields })),+}));++jest.mock("metabase/selectors/metadata", () => ({+ getMetadata: jest.fn(),+}));++const mockUseSelector = jest.requireMock("metabase/lib/redux").useSelector;+const mockGetSavedDashboardUiParameters = jest.requireMock(+ "metabase/parameters/utils/dashboards",+).getSavedDashboardUiParameters;+const mockGetCardUiParameters = jest.requireMock(+ "metabase-lib/v1/parameters/utils/cards",+).getCardUiParameters;++const mockParameter1 = createMockParameter({+ id: "param1",+ slug: "category",+ name: "Category",+});++const mockParameter2 = createMockParameter({+ id: "param2",+ slug: "status",+ name: "Status",+});++const mockDashboard = createMockDashboard({+ id: 1,+ name: "Test Dashboard",+ parameters: [mockParameter1, mockParameter2],+});++const mockCard = createMockCard({+ id: 1,+ name: "Test Question",+});++describe("useAvailableParameters", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockUseSelector.mockReturnValue({});+ mockGetSavedDashboardUiParameters.mockReturnValue([+ mockParameter1,+ mockParameter2,+ ]);+ mockGetCardUiParameters.mockReturnValue([mockParameter1]);+ });++ describe("with null resource", () => {+ it("should return empty arrays when resource is null", () => {+ const { result } = renderHook(() =>+ useAvailableParameters({+ experience: "dashboard",+ resource: null,+ }),+ );++ expect(result.current.availableParameters).toEqual([]);+ expect(result.current.initialAvailableParameters).toBeNull();+ });+ });++ describe("with dashboard experience", () => {+ it("should return expected parameters", () => {+ const { result } = renderHook(() =>+ useAvailableParameters({+ experience: "dashboard",+ resource: mockDashboard,+ }),+ );++ expect(result.current.availableParameters).toEqual([+ mockParameter1,+ mockParameter2,+ ]);+ });++ it("should set initialAvailableParameters on first resource load", () => {+ const { result } = renderHook(() =>+ useAvailableParameters({+ experience: "dashboard",+ resource: mockDashboard,+ }),+ );++ expect(result.current.initialAvailableParameters).toEqual([+ mockParameter1,+ mockParameter2,+ ]);+ });+ });++ describe("with chart experience", () => {+ it("should return expected parameters", () => {+ const { result } = renderHook(() =>+ useAvailableParameters({+ experience: "chart",+ resource: mockCard,+ }),+ );++ expect(result.current.availableParameters).toEqual([mockParameter1]);+ });++ it("should handle null return from getCardUiParameters", () => {+ mockGetCardUiParameters.mockReturnValue(null);++ const { result } = renderHook(() =>+ useAvailableParameters({+ experience: "chart",+ resource: mockCard,+ }),+ );++ expect(result.current.availableParameters).toEqual([]);+ });+ });++ describe("resource change handling", () => {+ it("should reinitialize initialAvailableParameters when resource id changes", () => {+ const firstDashboard = createMockDashboard({+ id: 1,+ name: "Dashboard 1",+ });+ const secondDashboard = createMockDashboard({+ id: 2,+ name: "Dashboard 2",+ });++ const firstParameters = [mockParameter1];+ const secondParameters = [mockParameter2];++ mockGetSavedDashboardUiParameters+ .mockReturnValueOnce(firstParameters)+ .mockReturnValueOnce(secondParameters);++ const { result, rerender } = renderHook(+ ({ resource }: { resource: Dashboard | Card | null }) =>+ useAvailableParameters({+ experience: "dashboard",+ resource,+ }),+ {+ initialProps: { resource: firstDashboard as Dashboard | Card | null },+ },+ );++ expect(result.current.initialAvailableParameters).toEqual(+ firstParameters,+ );++ rerender({ resource: secondDashboard });++ expect(result.current.initialAvailableParameters).toEqual(+ secondParameters,+ );+ });++ it("should not change initialAvailableParameters when resource id stays the same", () => {+ const dashboard = createMockDashboard({ id: 1, name: "Dashboard 1" });++ const firstParameters = [mockParameter1];+ const updatedParameters = [mockParameter1, mockParameter2];++ mockGetSavedDashboardUiParameters+ .mockReturnValueOnce(firstParameters)+ .mockReturnValueOnce(updatedParameters);++ const { result, rerender } = renderHook(+ ({ resource }: { resource: Dashboard | Card | null }) =>+ useAvailableParameters({+ experience: "dashboard",+ resource,+ }),+ {+ initialProps: { resource: dashboard as Dashboard | Card | null },+ },+ );++ expect(result.current.initialAvailableParameters).toEqual(+ firstParameters,+ );++ // Rerender with same resource (simulating metadata update)+ rerender({ resource: { ...dashboard } as Dashboard | Card | null });++ // initialAvailableParameters should remain unchanged+ expect(result.current.initialAvailableParameters).toEqual(+ firstParameters,+ );+ // But availableParameters should update+ expect(result.current.availableParameters).toEqual(updatedParameters);+ });++ it("should reset initialAvailableParameters when switching from dashboard to card", () => {+ const dashboard = createMockDashboard({ id: 1 });+ const card = createMockCard({ id: 2 });++ const dashboardParameters = [mockParameter1, mockParameter2];+ const cardParameters = [mockParameter1];++ mockGetSavedDashboardUiParameters.mockReturnValue(dashboardParameters);+ mockGetCardUiParameters.mockReturnValue(cardParameters);++ const { result, rerender } = renderHook(+ ({+ experience,+ resource,+ }: {+ experience: "dashboard" | "chart";+ resource: Dashboard | Card | null;+ }) =>+ useAvailableParameters({+ experience,+ resource,+ }),+ {+ initialProps: {+ experience: "dashboard" as "dashboard" | "chart",+ resource: dashboard as Dashboard | Card | null,+ },+ },+ );++ expect(result.current.initialAvailableParameters).toEqual(+ dashboardParameters,+ );++ rerender({+ experience: "chart",+ resource: card,+ });++ expect(result.current.initialAvailableParameters).toEqual(cardParameters);+ });++ it("should handle transition from null to resource", () => {+ const { result, rerender } = renderHook(+ ({ resource }: { resource: Dashboard | Card | null }) =>+ useAvailableParameters({+ experience: "dashboard",+ resource,+ }),+ {+ initialProps: { resource: null as Dashboard | Card | null },+ },+ );++ expect(result.current.initialAvailableParameters).toBeNull();++ rerender({ resource: mockDashboard });++ expect(result.current.initialAvailableParameters).toEqual([+ mockParameter1,+ mockParameter2,+ ]);+ });++ it("should handle transition from resource to null", () => {+ const { result, rerender } = renderHook(+ ({ resource }: { resource: Dashboard | Card | null }) =>+ useAvailableParameters({+ experience: "dashboard",+ resource,+ }),+ {+ initialProps: { resource: mockDashboard as Dashboard | Card | null },+ },+ );++ expect(result.current.initialAvailableParameters).toEqual([+ mockParameter1,+ mockParameter2,+ ]);++ rerender({ resource: null });++ // initialAvailableParameters should be reset to null when resource becomes null+ expect(result.current.initialAvailableParameters).toBeNull();+ });+ });++ describe("param_fields handling", () => {+ it("should dispatch addFields when resource has param_fields", () => {+ const dashboardWithParamFields = {+ ...mockDashboard,+ param_fields: {+ field1: [{ id: 1, name: "Field 1" }],+ field2: [{ id: 2, name: "Field 2" }],+ },+ };++ renderHook(() =>+ useAvailableParameters({+ experience: "dashboard",+ resource: dashboardWithParamFields as unknown as Dashboard,+ }),+ );++ expect(mockDispatch).toHaveBeenCalled();+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion.tsnew file mode 100644index 00000000000..2489c5c7cb0--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion.ts@@ -0,0 +1,64 @@+import { useCallback } from "react";++import type { SdkIframeEmbedSetupSettings } from "metabase/embedding/embedding-iframe-sdk-setup/types";+import type { EmbeddingParameters } from "metabase/public/lib/types";+import type { Parameter } from "metabase-types/api";++export const useEmbeddingParametersConversion = () => {+ const convertToEmbedSettings = useCallback(+ (+ embeddingParameters: EmbeddingParameters,+ ): Partial<SdkIframeEmbedSetupSettings> => {+ const { hiddenParameters, lockedParameters } = Object.entries(+ embeddingParameters,+ ).reduce(+ (acc, [slug, state]) => {+ if (state === "locked") {+ acc.lockedParameters.push(slug);+ }++ if (state === "disabled") {+ acc.hiddenParameters.push(slug);+ }++ return acc;+ },+ {+ hiddenParameters: [] as string[],+ lockedParameters: [] as string[],+ },+ );++ return {+ hiddenParameters,+ lockedParameters,+ };+ },+ [],+ );++ const convertToEmbeddingParameters = useCallback(+ (+ parameters: Parameter[],+ hiddenParameters: string[] = [],+ lockedParameters: string[] = [],+ ): EmbeddingParameters => {+ return parameters.reduce<EmbeddingParameters>((acc, { slug }) => {+ if (lockedParameters.includes(slug)) {+ acc[slug] = "locked";+ } else if (hiddenParameters.includes(slug)) {+ acc[slug] = "disabled";+ } else {+ acc[slug] = "enabled";+ }+ return acc;+ }, {});+ },+ [],+ );++ return {+ convertToEmbedSettings,+ convertToEmbeddingParameters,+ };+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion.unit.spec.tsnew file mode 100644index 00000000000..a247bb903ee--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion.unit.spec.ts@@ -0,0 +1,287 @@+import { renderHook } from "@testing-library/react";++import { useEmbeddingParametersConversion } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion";+import type { EmbeddingParameters } from "metabase/public/lib/types";+import type { Parameter } from "metabase-types/api";+import { createMockParameter } from "metabase-types/api/mocks";++describe("useEmbeddingParametersConversion", () => {+ const mockParameter1 = createMockParameter({+ id: "param1",+ slug: "category",+ name: "Category",+ });++ const mockParameter2 = createMockParameter({+ id: "param2",+ slug: "status",+ name: "Status",+ });++ const mockParameter3 = createMockParameter({+ id: "param3",+ slug: "region",+ name: "Region",+ });++ describe("convertToEmbedSettings", () => {+ it("should convert enabled parameters correctly", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams: EmbeddingParameters = {+ category: "enabled",+ status: "enabled",+ };++ const sdkSettings =+ result.current.convertToEmbedSettings(embeddingParams);++ expect(sdkSettings).toEqual({+ hiddenParameters: [],+ lockedParameters: [],+ });+ });++ it("should convert disabled parameters to hiddenParameters", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams: EmbeddingParameters = {+ category: "disabled",+ status: "enabled",+ };++ const sdkSettings =+ result.current.convertToEmbedSettings(embeddingParams);++ expect(sdkSettings).toEqual({+ hiddenParameters: ["category"],+ lockedParameters: [],+ });+ });++ it("should convert locked parameters to lockedParameters", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams: EmbeddingParameters = {+ category: "locked",+ status: "enabled",+ };++ const sdkSettings =+ result.current.convertToEmbedSettings(embeddingParams);++ expect(sdkSettings).toEqual({+ hiddenParameters: [],+ lockedParameters: ["category"],+ });+ });++ it("should handle mixed parameter states", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams: EmbeddingParameters = {+ category: "locked",+ status: "disabled",+ region: "enabled",+ };++ const sdkSettings =+ result.current.convertToEmbedSettings(embeddingParams);++ expect(sdkSettings).toEqual({+ hiddenParameters: ["status"],+ lockedParameters: ["category"],+ });+ });++ it("should handle empty embedding parameters", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams: EmbeddingParameters = {};++ const sdkSettings =+ result.current.convertToEmbedSettings(embeddingParams);++ expect(sdkSettings).toEqual({+ hiddenParameters: [],+ lockedParameters: [],+ });+ });++ it("should handle parameters with special characters", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams: EmbeddingParameters = {+ "param-with-dash": "disabled",+ param_with_underscore: "locked",+ };++ const sdkSettings =+ result.current.convertToEmbedSettings(embeddingParams);++ expect(sdkSettings).toEqual({+ hiddenParameters: ["param-with-dash"],+ lockedParameters: ["param_with_underscore"],+ });+ });+ });++ describe("convertToEmbeddingParameters", () => {+ it("should convert parameters with no hidden or locked to enabled", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const parameters: Parameter[] = [mockParameter1, mockParameter2];++ const embeddingParams = result.current.convertToEmbeddingParameters(+ parameters,+ [],+ [],+ );++ expect(embeddingParams).toEqual({+ category: "enabled",+ status: "enabled",+ });+ });++ it("should convert hidden parameters to disabled", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const parameters: Parameter[] = [mockParameter1, mockParameter2];++ const embeddingParams = result.current.convertToEmbeddingParameters(+ parameters,+ ["category"],+ [],+ );++ expect(embeddingParams).toEqual({+ category: "disabled",+ status: "enabled",+ });+ });++ it("should convert locked parameters to locked", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const parameters: Parameter[] = [mockParameter1, mockParameter2];++ const embeddingParams = result.current.convertToEmbeddingParameters(+ parameters,+ [],+ ["category"],+ );++ expect(embeddingParams).toEqual({+ category: "locked",+ status: "enabled",+ });+ });++ it("should prioritize locked over hidden", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const parameters: Parameter[] = [mockParameter1];++ const embeddingParams = result.current.convertToEmbeddingParameters(+ parameters,+ ["category"],+ ["category"],+ );++ expect(embeddingParams).toEqual({+ category: "locked",+ });+ });++ it("should handle mixed parameter states", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const parameters: Parameter[] = [+ mockParameter1,+ mockParameter2,+ mockParameter3,+ ];++ const embeddingParams = result.current.convertToEmbeddingParameters(+ parameters,+ ["status"],+ ["category"],+ );++ expect(embeddingParams).toEqual({+ category: "locked",+ status: "disabled",+ region: "enabled",+ });+ });++ it("should handle empty parameters list", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const embeddingParams = result.current.convertToEmbeddingParameters(+ [],+ [],+ [],+ );++ expect(embeddingParams).toEqual({});+ });++ it("should handle undefined hidden and locked parameters", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const parameters: Parameter[] = [mockParameter1, mockParameter2];++ const embeddingParams = result.current.convertToEmbeddingParameters(+ parameters,+ undefined,+ undefined,+ );++ expect(embeddingParams).toEqual({+ category: "enabled",+ status: "enabled",+ });+ });+ });++ describe("round-trip conversion", () => {+ it("should correctly convert back and forth", () => {+ const { result } = renderHook(() => useEmbeddingParametersConversion());++ const originalEmbeddingParams: EmbeddingParameters = {+ category: "locked",+ status: "disabled",+ region: "enabled",+ };++ const sdkSettings = result.current.convertToEmbedSettings(+ originalEmbeddingParams,+ );++ const parameters: Parameter[] = [+ mockParameter1,+ mockParameter2,+ mockParameter3,+ ];++ const hiddenParams =+ "hiddenParameters" in sdkSettings+ ? sdkSettings.hiddenParameters+ : undefined;+ const lockedParams =+ "lockedParameters" in sdkSettings+ ? sdkSettings.lockedParameters+ : undefined;++ const convertedBack = result.current.convertToEmbeddingParameters(+ parameters,+ hiddenParams,+ lockedParams,+ );++ expect(convertedBack).toEqual(originalEmbeddingParams);+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters.tsnew file mode 100644index 00000000000..259cf582926--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters.ts@@ -0,0 +1,91 @@+import { useCallback, useEffect, useMemo, useRef } from "react";+import { usePrevious } from "react-use";++import type { SdkIframeEmbedSetupContextType } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import { useEmbeddingParametersConversion } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion";+import { getDefaultEmbeddingParams } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-default-embedding-params";+import type { EmbeddingParameters } from "metabase/public/lib/types";+import type { Card, Dashboard, Parameter } from "metabase-types/api";++export const useEmbeddingParameters = ({+ settings,+ updateSettings,+ resource,+ initialAvailableParameters,+ availableParameters,+}: Pick<SdkIframeEmbedSetupContextType, "settings" | "updateSettings"> & {+ resource: Dashboard | Card | null;+ initialAvailableParameters: Parameter[] | null;+ availableParameters: Parameter[];+}) => {+ const { convertToEmbedSettings, convertToEmbeddingParameters } =+ useEmbeddingParametersConversion();++ const hasInitializedRef = useRef(false);+ const prevResourceId = usePrevious(resource?.id);++ // Reset initialization flag when the resource changes+ if (resource?.id !== prevResourceId) {+ hasInitializedRef.current = false;+ }++ const areEmbeddingParametersInitialized =+ (!!settings.dashboardId || !!settings.questionId) &&+ (("hiddenParameters" in settings && !!settings.hiddenParameters) ||+ ("lockedParameters" in settings && !!settings.lockedParameters));++ const initialEmbeddingParameters = useMemo(() => {+ if (!resource || !initialAvailableParameters) {+ return null;+ }++ return getDefaultEmbeddingParams(resource, initialAvailableParameters);+ }, [initialAvailableParameters, resource]);++ const embeddingParameters = useMemo(() => {+ const hiddenParameters =+ "hiddenParameters" in settings ? settings.hiddenParameters : undefined;+ const lockedParameters =+ "lockedParameters" in settings ? settings.lockedParameters : undefined;++ return convertToEmbeddingParameters(+ availableParameters,+ hiddenParameters,+ lockedParameters,+ );+ }, [availableParameters, convertToEmbeddingParameters, settings]);++ const onEmbeddingParametersChange = useCallback(+ (embeddingParameters: EmbeddingParameters) => {+ updateSettings(convertToEmbedSettings(embeddingParameters));+ },+ [convertToEmbedSettings, updateSettings],+ );++ // Call onEmbeddingParametersChange ONLY ONCE per resource when initialEmbeddingParameters+ // changes from null to a non-null value (for guest embeds only).+ // The resource?.id dependency ensures this re-runs when switching resources.+ useEffect(() => {+ if (+ resource?.id &&+ !hasInitializedRef.current &&+ settings.isGuest &&+ initialEmbeddingParameters !== null+ ) {+ hasInitializedRef.current = true;+ onEmbeddingParametersChange(initialEmbeddingParameters);+ }+ }, [+ initialEmbeddingParameters,+ onEmbeddingParametersChange,+ settings.isGuest,+ resource?.id,+ ]);++ return {+ areEmbeddingParametersInitialized,+ initialEmbeddingParameters,+ embeddingParameters,+ onEmbeddingParametersChange,+ };+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters.unit.spec.tsnew file mode 100644index 00000000000..ebad96bd95b--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters.unit.spec.ts@@ -0,0 +1,590 @@+import { renderHook } from "@testing-library/react";++import { useEmbeddingParameters } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters";+import type { SdkIframeEmbedSetupSettings } from "metabase/embedding/embedding-iframe-sdk-setup/types";+import type { EmbeddingParameters } from "metabase/public/lib/types";+import type { Card, Dashboard, Parameter } from "metabase-types/api";+import {+ createMockCard,+ createMockDashboard,+ createMockParameter,+} from "metabase-types/api/mocks";++jest.mock(+ "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion",+);+jest.mock(+ "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-default-embedding-params",+);++const mockUseEmbeddingParametersConversion = jest.requireMock(+ "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-embedding-parameters-conversion",+).useEmbeddingParametersConversion;++const mockGetDefaultEmbeddingParams = jest.requireMock(+ "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-default-embedding-params",+).getDefaultEmbeddingParams;++const mockUpdateSettings = jest.fn();+const mockConvertToEmbedSettings = jest.fn();+const mockConvertToEmbeddingParameters = jest.fn();++const mockParameter1 = createMockParameter({+ id: "param1",+ slug: "category",+ name: "Category",+});++const mockParameter2 = createMockParameter({+ id: "param2",+ slug: "status",+ name: "Status",+});++const mockDashboard = createMockDashboard({+ id: 1,+ name: "Test Dashboard",+});++const mockCard = createMockCard({+ id: 1,+ name: "Test Question",+});++const defaultSettings: any = {+ dashboardId: 1,+ hiddenParameters: ["category"],+ lockedParameters: ["status"],+ isGuest: true,+} as SdkIframeEmbedSetupSettings;++describe("useEmbeddingParameters", () => {+ beforeEach(() => {+ jest.clearAllMocks();++ mockUseEmbeddingParametersConversion.mockReturnValue({+ convertToEmbedSettings: mockConvertToEmbedSettings,+ convertToEmbeddingParameters: mockConvertToEmbeddingParameters,+ });++ mockConvertToEmbeddingParameters.mockImplementation(+ (+ parameters: Parameter[],+ hiddenParameters: string[] = [],+ lockedParameters: string[] = [],+ ) => {+ return parameters.reduce<EmbeddingParameters>((acc, { slug }) => {+ if (lockedParameters.includes(slug)) {+ acc[slug] = "locked";+ } else if (hiddenParameters.includes(slug)) {+ acc[slug] = "disabled";+ } else {+ acc[slug] = "enabled";+ }+ return acc;+ }, {});+ },+ );++ mockConvertToEmbedSettings.mockImplementation(+ (params: EmbeddingParameters) => ({+ hiddenParameters: Object.keys(params).filter(+ (key) => params[key] === "disabled",+ ),+ lockedParameters: Object.keys(params).filter(+ (key) => params[key] === "locked",+ ),+ }),+ );++ mockGetDefaultEmbeddingParams.mockReturnValue({+ category: "enabled",+ status: "enabled",+ });+ });++ describe("areEmbeddingParametersInitialized", () => {+ it("should return true when dashboardId and hiddenParameters are present", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.areEmbeddingParametersInitialized).toBe(true);+ });++ it("should return true when dashboardId and lockedParameters are present", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ dashboardId: 1,+ lockedParameters: ["status"],+ isGuest: true,+ } as SdkIframeEmbedSetupSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.areEmbeddingParametersInitialized).toBe(true);+ });++ it("should return false when no resource id is present", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ hiddenParameters: ["category"],+ isGuest: true,+ } as SdkIframeEmbedSetupSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.areEmbeddingParametersInitialized).toBe(false);+ });++ it("should return false when no parameters are initialized", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ dashboardId: 1,+ isGuest: true,+ } as SdkIframeEmbedSetupSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.areEmbeddingParametersInitialized).toBe(false);+ });++ it("should work with questionId instead of dashboardId", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ questionId: 1,+ lockedParameters: ["status"],+ isGuest: true,+ } as SdkIframeEmbedSetupSettings,+ updateSettings: mockUpdateSettings,+ resource: mockCard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.areEmbeddingParametersInitialized).toBe(true);+ });+ });++ describe("initialEmbeddingParameters", () => {+ it("should return null when resource is null", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: null,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.initialEmbeddingParameters).toBeNull();+ });++ it("should return null when initialAvailableParameters is null", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: null,+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.initialEmbeddingParameters).toBeNull();+ });+ });++ describe("embeddingParameters", () => {+ it("should build embedding parameters from settings correctly", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(result.current.embeddingParameters).toEqual({+ category: "disabled",+ status: "locked",+ });+ });++ it("should mark parameter as enabled when not hidden or locked", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ dashboardId: 1,+ hiddenParameters: [],+ lockedParameters: [],+ isGuest: true,+ } as any,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1],+ availableParameters: [mockParameter1],+ }),+ );++ expect(result.current.embeddingParameters).toEqual({+ category: "enabled",+ });+ });++ it("should prioritize locked over hidden", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ dashboardId: 1,+ hiddenParameters: ["category"],+ lockedParameters: ["category"],+ isGuest: true,+ } as any,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1],+ availableParameters: [mockParameter1],+ }),+ );++ expect(result.current.embeddingParameters).toEqual({+ category: "locked",+ });+ });++ it("should handle empty parameters list", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [],+ availableParameters: [],+ }),+ );++ expect(result.current.embeddingParameters).toEqual({});+ });+ });++ describe("onEmbeddingParametersChange", () => {+ it("should call updateSettings with correct values", () => {+ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ const newParams: EmbeddingParameters = {+ category: "locked",+ status: "enabled",+ };++ result.current.onEmbeddingParametersChange(newParams);++ expect(mockConvertToEmbedSettings).toHaveBeenCalledWith(newParams);+ expect(mockUpdateSettings).toHaveBeenCalled();+ });+ });++ describe("initialization with initial parameters", () => {+ it("should call onEmbeddingParametersChange once when initialEmbeddingParameters changes from null to value for guest embeds", () => {+ const mockInitialParams = { category: "enabled", status: "enabled" };+ mockGetDefaultEmbeddingParams.mockReturnValue(mockInitialParams);++ const { rerender } = renderHook(+ ({+ resource,+ initialAvailableParameters,+ }: {+ resource: Dashboard | Card | null;+ initialAvailableParameters: Parameter[] | null;+ }) =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource,+ initialAvailableParameters,+ availableParameters: [mockParameter1, mockParameter2],+ }),+ {+ initialProps: {+ resource: null,+ initialAvailableParameters: null,+ },+ },+ );++ expect(mockUpdateSettings).not.toHaveBeenCalled();++ rerender({+ resource: mockDashboard as any,+ initialAvailableParameters: [mockParameter1, mockParameter2] as any,+ });++ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);++ rerender({+ resource: mockDashboard as any,+ initialAvailableParameters: [mockParameter1, mockParameter2] as any,+ });++ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);+ });++ it("should not call onEmbeddingParametersChange when not a guest embed", () => {+ const mockInitialParams = { category: "enabled", status: "enabled" };+ mockGetDefaultEmbeddingParams.mockReturnValue(mockInitialParams);++ const { rerender } = renderHook(+ ({+ resource,+ initialAvailableParameters,+ }: {+ resource: Dashboard | Card | null;+ initialAvailableParameters: Parameter[] | null;+ }) =>+ useEmbeddingParameters({+ settings: {+ ...defaultSettings,+ isGuest: false,+ },+ updateSettings: mockUpdateSettings,+ resource,+ initialAvailableParameters,+ availableParameters: [mockParameter1, mockParameter2],+ }),+ {+ initialProps: {+ resource: null,+ initialAvailableParameters: null,+ },+ },+ );++ rerender({+ resource: mockDashboard as any,+ initialAvailableParameters: [mockParameter1, mockParameter2] as any,+ });++ expect(mockUpdateSettings).not.toHaveBeenCalled();+ });++ it("should not call onEmbeddingParametersChange when initialEmbeddingParameters is null", () => {+ mockGetDefaultEmbeddingParams.mockReturnValue(null);++ renderHook(() =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: null,+ availableParameters: [mockParameter1, mockParameter2],+ }),+ );++ expect(mockUpdateSettings).not.toHaveBeenCalled();+ });++ it("should handle initialization with Card resource", () => {+ const mockInitialParams = { category: "enabled" };+ mockGetDefaultEmbeddingParams.mockReturnValue(mockInitialParams);++ const { rerender } = renderHook(+ ({+ resource,+ initialAvailableParameters,+ }: {+ resource: Dashboard | Card | null;+ initialAvailableParameters: Parameter[] | null;+ }) =>+ useEmbeddingParameters({+ settings: {+ questionId: 1,+ isGuest: true,+ hiddenParameters: [],+ } as unknown as SdkIframeEmbedSetupSettings,+ updateSettings: mockUpdateSettings,+ resource,+ initialAvailableParameters,+ availableParameters: [mockParameter1],+ }),+ {+ initialProps: {+ resource: null,+ initialAvailableParameters: null,+ },+ },+ );++ rerender({+ resource: mockCard as any,+ initialAvailableParameters: [mockParameter1] as any,+ });++ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);+ });++ it("should only initialize once even when other dependencies change", () => {+ const mockInitialParams = { category: "enabled", status: "enabled" };+ mockGetDefaultEmbeddingParams.mockReturnValue(mockInitialParams);++ const { rerender } = renderHook(+ ({ settings }: { settings: any }) =>+ useEmbeddingParameters({+ settings,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [mockParameter1, mockParameter2],+ availableParameters: [mockParameter1, mockParameter2],+ }),+ {+ initialProps: {+ settings: defaultSettings,+ },+ },+ );++ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);++ rerender({+ settings: {+ ...defaultSettings,+ hiddenParameters: ["different"],+ },+ });++ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);+ });+ });++ describe("edge cases", () => {+ it("should handle parameters with special characters in slugs", () => {+ const specialParam = createMockParameter({+ id: "special",+ slug: "param-with-dash_and_underscore",+ name: "Special Param",+ });++ const { result } = renderHook(() =>+ useEmbeddingParameters({+ settings: {+ dashboardId: 1,+ hiddenParameters: ["param-with-dash_and_underscore"],+ lockedParameters: [],+ isGuest: true,+ } as any,+ updateSettings: mockUpdateSettings,+ resource: mockDashboard,+ initialAvailableParameters: [specialParam],+ availableParameters: [specialParam],+ }),+ );++ expect(result.current.embeddingParameters).toEqual({+ "param-with-dash_and_underscore": "disabled",+ });+ });++ it("should handle switching between Dashboard and Card resources", () => {+ const { rerender, result } = renderHook(+ ({ resource }: { resource: Dashboard | Card }) =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource,+ initialAvailableParameters: [mockParameter1],+ availableParameters: [mockParameter1],+ }),+ {+ initialProps: {+ resource: mockDashboard as Dashboard | Card,+ },+ },+ );++ expect(result.current.initialEmbeddingParameters).toBeTruthy();++ rerender({ resource: mockCard });++ expect(result.current.initialEmbeddingParameters).toBeTruthy();+ expect(mockGetDefaultEmbeddingParams).toHaveBeenCalledWith(mockCard, [+ mockParameter1,+ ]);+ });++ it("should reinitialize embedding parameters when resource id changes for guest embeds", () => {+ const firstDashboard = createMockDashboard({ id: 1 });+ const secondDashboard = createMockDashboard({ id: 2 });++ const mockInitialParams = { category: "enabled" };+ mockGetDefaultEmbeddingParams.mockReturnValue(mockInitialParams);++ const { rerender } = renderHook(+ ({+ resource,+ initialAvailableParameters,+ }: {+ resource: Dashboard | Card | null;+ initialAvailableParameters: Parameter[] | null;+ }) =>+ useEmbeddingParameters({+ settings: defaultSettings,+ updateSettings: mockUpdateSettings,+ resource,+ initialAvailableParameters,+ availableParameters: [mockParameter1],+ }),+ {+ initialProps: {+ resource: firstDashboard as Dashboard | Card | null,+ initialAvailableParameters: [mockParameter1] as Parameter[] | null,+ },+ },+ );++ // First initialization+ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);++ // Change to a different resource+ rerender({+ resource: secondDashboard,+ initialAvailableParameters: [mockParameter1],+ });++ // Should reinitialize for the new resource+ expect(mockUpdateSettings).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-current-resource.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-current-resource.tsindex d836d970774..f4a99c7abfd 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-current-resource.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-current-resource.ts@@ -3,12 +3,9 @@ import { useAsync } from "react-use";import { skipToken, useGetCardQuery } from "metabase/api";import { fetchDashboard } from "metabase/dashboard/actions";import { getDashboardComplete } from "metabase/dashboard/selectors";-import type {- SdkIframeEmbedSetupExperience,- SdkIframeEmbedSetupSettings,-} from "metabase/embedding/embedding-iframe-sdk-setup/types";+import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";import { useDispatch, useSelector } from "metabase/lib/redux";-import type { Card, Dashboard } from "metabase-types/api";+import type { Card, Dashboard, DashboardId } from "metabase-types/api";const getResource = ({experience,@@ -32,26 +29,28 @@ const getResource = ({export const useGetCurrentResource = ({experience,- settings,+ dashboardId,+ questionId,}: {experience: SdkIframeEmbedSetupExperience;- settings: SdkIframeEmbedSetupSettings;+ dashboardId?: DashboardId;+ questionId?: string | number;}) => {const dispatch = useDispatch();const { loading: isDashboardLoading, error: dashboardLoadingError } =useAsync(async () => {- if (!settings.dashboardId) {+ if (!dashboardId) {return;}await dispatch(fetchDashboard({- dashId: settings.dashboardId as number,+ dashId: dashboardId as number,queryParams: {},}),);- }, [settings.dashboardId, dispatch]);+ }, [dashboardId, dispatch]);const dashboard = useSelector(getDashboardComplete);const {@@ -59,9 +58,9 @@ export const useGetCurrentResource = ({error: cardLoadingError,isLoading: isCardLoading,isFetching: isCardFetching,- } = useGetCardQuery(- settings.questionId ? { id: settings.questionId as number } : skipToken,- );+ } = useGetCardQuery(questionId ? { id: questionId as number } : skipToken, {+ refetchOnMountOrArgChange: true,+ });const isLoading = isDashboardLoading || isCardLoading;const isFetching = isCardFetching;diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.tsnew file mode 100644index 00000000000..ec5dfefff2b--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.ts@@ -0,0 +1,90 @@+import { useState } from "react";+import { useDeepCompareEffect } from "react-use";++import { useSetting } from "metabase/common/hooks";+import type { SdkIframeEmbedSetupContextType } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import { getResourceTypeFromExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience";+import { isQuestionOrDashboardSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings";+import { getSignedToken } from "metabase/public/lib/embed";++const SIGNED_TOKEN_FOR_SNIPPET_EXPIRATION_MINUTES = 10;+const SIGNED_TOKEN_FOR_PREVIEW_EXPIRATION_MINUTES = 60;++export const useGetGuestEmbedSignedToken = ({+ settings,+ experience,+ previewParameterValuesBySlug,+ embeddingParameters,+}: Pick<+ SdkIframeEmbedSetupContextType,+ | "settings"+ | "experience"+ | "previewParameterValuesBySlug"+ | "embeddingParameters"+>) => {+ const secretKey = useSetting("embedding-secret-key");++ const [{ signedTokenForSnippet, signedTokenForPreview }, setSignedTokens] =+ useState<{+ signedTokenForSnippet: string | null;+ signedTokenForPreview: string | null;+ }>({+ signedTokenForSnippet: null,+ signedTokenForPreview: null,+ });++ const isGuestEmbed = !!settings.isGuest;+ const isQuestionOrDashboard = isQuestionOrDashboardSettings(+ experience,+ settings,+ );++ useDeepCompareEffect(() => {+ if (!isGuestEmbed || !isQuestionOrDashboard || !secretKey) {+ return;+ }++ const generate = async () => {+ const resourceType = getResourceTypeFromExperience(experience);++ const signedTokenForSnippet = resourceType+ ? await getSignedToken(+ resourceType,+ settings.dashboardId ?? settings.questionId ?? "",+ previewParameterValuesBySlug,+ secretKey,+ embeddingParameters,+ SIGNED_TOKEN_FOR_SNIPPET_EXPIRATION_MINUTES,+ )+ : "";+ const signedTokenForPreview = resourceType+ ? await getSignedToken(+ resourceType,+ settings.dashboardId ?? settings.questionId ?? "",+ previewParameterValuesBySlug,+ secretKey,+ embeddingParameters,+ SIGNED_TOKEN_FOR_PREVIEW_EXPIRATION_MINUTES,+ )+ : "";++ setSignedTokens({+ signedTokenForSnippet,+ signedTokenForPreview,+ });+ };++ generate();+ }, [+ isGuestEmbed,+ isQuestionOrDashboard,+ previewParameterValuesBySlug,+ experience,+ settings.dashboardId,+ settings.questionId,+ secretKey,+ embeddingParameters,+ ]);++ return { signedTokenForSnippet, signedTokenForPreview };+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values.tsnew file mode 100644index 00000000000..d1d639d5736--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values.ts@@ -0,0 +1,93 @@+import { useDebouncedCallback } from "@mantine/hooks";+import { useCallback, useMemo } from "react";++import { SET_INITIAL_PARAMETER_DEBOUNCE_MS } from "metabase/embedding/embedding-iframe-sdk-setup/constants";+import type { SdkIframeEmbedSetupContextType } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";+import type { ParameterValueOrArray } from "metabase-types/api";++type ParameterValuesKey = "initialParameters" | "initialSqlParameters";++export const useInitialParameterValues = ({+ settings,+ updateSettings,+}: Pick<SdkIframeEmbedSetupContextType, "settings" | "updateSettings">) => {+ const parameterValuesKey: ParameterValuesKey | null = useMemo(() => {+ if (settings.dashboardId) {+ return "initialParameters";+ }++ if (settings.questionId) {+ return "initialSqlParameters";+ }++ return null;+ }, [settings.dashboardId, settings.questionId]);++ const currentParameterValues = useMemo((): ParameterValues => {+ if (parameterValuesKey === "initialParameters") {+ return (+ ("initialParameters" in settings+ ? settings.initialParameters+ : undefined) || {}+ );+ }++ if (parameterValuesKey === "initialSqlParameters") {+ return (+ ("initialSqlParameters" in settings+ ? settings.initialSqlParameters+ : undefined) || {}+ );+ }++ return {};+ }, [parameterValuesKey, settings]);++ const updateInitialParameterValue = useDebouncedCallback(+ useCallback(+ (slug: string, value: ParameterValueOrArray | null | undefined) => {+ if (parameterValuesKey === "initialParameters") {+ updateSettings({+ initialParameters: {+ ...currentParameterValues,+ [slug]: value,+ },+ });+ } else if (parameterValuesKey === "initialSqlParameters") {+ updateSettings({+ initialSqlParameters: {+ ...currentParameterValues,+ [slug]: value,+ },+ });+ }+ },+ [parameterValuesKey, currentParameterValues, updateSettings],+ ),+ SET_INITIAL_PARAMETER_DEBOUNCE_MS,+ );++ const removeInitialParameterValue = useCallback(+ (slug: string) => {+ const nextParameterValues = { ...currentParameterValues };+ delete nextParameterValues[slug];++ if (parameterValuesKey === "initialParameters") {+ updateSettings({+ initialParameters: nextParameterValues,+ });+ } else if (parameterValuesKey === "initialSqlParameters") {+ updateSettings({+ initialSqlParameters: nextParameterValues,+ });+ }+ },+ [parameterValuesKey, currentParameterValues, updateSettings],+ );++ return {+ updateInitialParameterValue,+ removeInitialParameterValue,+ };+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values.unit.spec.tsnew file mode 100644index 00000000000..b893d975869--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values.unit.spec.ts@@ -0,0 +1,365 @@+import { act, renderHook, waitFor } from "@testing-library/react";++import { useInitialParameterValues } from "metabase/embedding/embedding-iframe-sdk-setup/hooks/use-initial-parameter-values";++describe("useInitialParameterValues", () => {+ const mockUpdateSettings = jest.fn();++ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("with dashboard settings", () => {+ it("should update initialParameters for dashboard", async () => {+ const settings: any = {+ dashboardId: 1,+ initialParameters: { category: "electronics" },+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("status", "active");+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: "electronics",+ status: "active",+ },+ });+ });+ });++ it("should remove parameter from initialParameters for dashboard", () => {+ const settings: any = {+ dashboardId: 1,+ initialParameters: { category: "electronics", status: "active" },+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.removeInitialParameterValue("status");+ });++ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: "electronics",+ },+ });+ });++ it("should handle undefined initialParameters for dashboard", async () => {+ const settings: any = {+ dashboardId: 1,+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("category", "electronics");+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: "electronics",+ },+ });+ });+ });+ });++ describe("with question settings", () => {+ it("should update initialSqlParameters for question", async () => {+ const settings: any = {+ questionId: 1,+ initialSqlParameters: { param1: "value1" },+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("param2", "value2");+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialSqlParameters: {+ param1: "value1",+ param2: "value2",+ },+ });+ });+ });++ it("should remove parameter from initialSqlParameters for question", () => {+ const settings: any = {+ questionId: 1,+ initialSqlParameters: { param1: "value1", param2: "value2" },+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.removeInitialParameterValue("param2");+ });++ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialSqlParameters: {+ param1: "value1",+ },+ });+ });++ it("should handle undefined initialSqlParameters for question", async () => {+ const settings: any = {+ questionId: 1,+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("param1", "value1");+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialSqlParameters: {+ param1: "value1",+ },+ });+ });+ });+ });++ describe("with neither dashboard nor question", () => {+ it("should not call updateSettings when updating", async () => {+ const settings: any = {};++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("param1", "value1");+ });++ await waitFor(+ () => {+ expect(mockUpdateSettings).not.toHaveBeenCalled();+ },+ { timeout: 1000 },+ );+ });++ it("should not call updateSettings when removing", () => {+ const settings: any = {};++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.removeInitialParameterValue("param1");+ });++ expect(mockUpdateSettings).not.toHaveBeenCalled();+ });+ });++ describe("parameter value types", () => {+ it("should handle string values", async () => {+ const settings: any = { dashboardId: 1, initialParameters: {} };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("category", "electronics");+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: "electronics",+ },+ });+ });+ });++ it("should handle number values", async () => {+ const settings: any = { dashboardId: 1, initialParameters: {} };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("count", 42);+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ count: 42,+ },+ });+ });+ });++ it("should handle array values", async () => {+ const settings: any = { dashboardId: 1, initialParameters: {} };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("categories", [+ "electronics",+ "books",+ ]);+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ categories: ["electronics", "books"],+ },+ });+ });+ });++ it("should handle null values", async () => {+ const settings: any = {+ dashboardId: 1,+ initialParameters: { category: "electronics" },+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("category", null);+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: null,+ },+ });+ });+ });++ it("should handle undefined values", async () => {+ const settings: any = {+ dashboardId: 1,+ initialParameters: { category: "electronics" },+ };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("category", undefined);+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: undefined,+ },+ });+ });+ });+ });++ describe("debouncing", () => {+ it("should debounce updateInitialParameterValue calls", async () => {+ const settings: any = { dashboardId: 1, initialParameters: {} };++ const { result } = renderHook(() =>+ useInitialParameterValues({+ settings,+ updateSettings: mockUpdateSettings,+ }),+ );++ act(() => {+ result.current.updateInitialParameterValue("category", "electronics");+ result.current.updateInitialParameterValue("category", "books");+ result.current.updateInitialParameterValue("category", "toys");+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledTimes(1);+ });++ await waitFor(() => {+ expect(mockUpdateSettings).toHaveBeenCalledWith({+ initialParameters: {+ category: "toys",+ },+ });+ });+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameter-visibility.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameter-visibility.tsnew file mode 100644index 00000000000..b6f16d36e33--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameter-visibility.ts@@ -0,0 +1,66 @@+import { useCallback } from "react";++import type { SdkIframeEmbedSetupContextType } from "metabase/embedding/embedding-iframe-sdk-setup/context";++interface UseParameterVisibilityProps+ extends Pick<SdkIframeEmbedSetupContextType, "settings" | "updateSettings"> {}++/**+ * Manages parameter visibility state (hidden/locked).+ * Provides checks and toggles for parameter visibility in the SDK iframe embed setup.+ */+export const useParameterVisibility = ({+ settings,+ updateSettings,+}: UseParameterVisibilityProps) => {+ const hasResource = !!settings.dashboardId || !!settings.questionId;++ const isHiddenParameter = useCallback(+ (parameterName: string) => {+ if (!hasResource) {+ return true;+ }++ const hiddenParameters =+ "hiddenParameters" in settings ? settings.hiddenParameters : undefined;+ return (hiddenParameters ?? []).includes(parameterName);+ },+ [settings, hasResource],+ );++ const isLockedParameter = useCallback(+ (parameterName: string) => {+ if (!hasResource) {+ return false;+ }++ const lockedParameters =+ "lockedParameters" in settings ? settings.lockedParameters : undefined;+ return (lockedParameters ?? []).includes(parameterName);+ },+ [settings, hasResource],+ );++ const toggleParameterVisibility = useCallback(+ (parameterName: string) => {+ if (!hasResource) {+ return;+ }++ const hiddenParameters =+ "hiddenParameters" in settings ? (settings.hiddenParameters ?? []) : [];+ const nextHiddenParameters = hiddenParameters.includes(parameterName)+ ? hiddenParameters.filter((name) => name !== parameterName)+ : [...hiddenParameters, parameterName];++ updateSettings({ hiddenParameters: nextHiddenParameters });+ },+ [settings, hasResource, updateSettings],+ );++ return {+ isHiddenParameter,+ isLockedParameter,+ toggleParameterVisibility,+ };+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters-values.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters-values.tsindex 4cd22172305..73121e7b4d3 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters-values.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-parameters-values.ts@@ -1,38 +1,59 @@import { useMemo } from "react";-import { P, match } from "ts-pattern";import type { SdkIframeEmbedSetupSettings } from "metabase/embedding/embedding-iframe-sdk-setup/types";import { convertParameterValuesBySlugToById } from "metabase/embedding/embedding-iframe-sdk-setup/utils/convert-parameter-values-by-slug-to-by-id";-import type { EmbeddingParametersValues } from "metabase/public/lib/types";+import { getPreviewParamsBySlug } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-preview-params-by-slug";+import type { EmbeddingParameters } from "metabase/public/lib/types";import type { Parameter } from "metabase-types/api";+interface UseParametersValuesProps {+ settings: SdkIframeEmbedSetupSettings;+ availableParameters: Parameter[];+ embeddingParameters: EmbeddingParameters;+}++const getParameterValuesBySlug = (settings: SdkIframeEmbedSetupSettings) => {+ if (settings.dashboardId) {+ return settings.initialParameters ?? {};+ }++ if (settings.questionId) {+ return settings.initialSqlParameters ?? {};+ }++ return {};+};++/**+ * Converts parameter values between slug-based and id-based formats.+ * Widgets expect values keyed by parameter.id, but embed settings store them by parameter.slug.+ */export const useParametersValues = ({settings,availableParameters,-}: {- settings: SdkIframeEmbedSetupSettings;- availableParameters: Parameter[];-}) => {- /**- * 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 parametersValuesById: EmbeddingParametersValues = useMemo(() => {- const valuesBySlug = match(settings)- .with({ dashboardId: P.nonNullable }, (s) => s.initialParameters ?? {})- .with({ questionId: P.nonNullable }, (s) => s.initialSqlParameters ?? {})- .otherwise(() => ({}));+ embeddingParameters,+}: UseParametersValuesProps) => {+ const parametersValuesById = useMemo(() => {+ const valuesBySlug = getParameterValuesBySlug(settings);return convertParameterValuesBySlugToById(valuesBySlug,availableParameters,);- }, [availableParameters, settings]);+ }, [settings, availableParameters]);++ const previewParameterValuesBySlug = useMemo(+ () =>+ getPreviewParamsBySlug({+ resourceParameters: availableParameters,+ embeddingParams: embeddingParameters,+ parameterValues: parametersValuesById,+ }),+ [availableParameters, embeddingParameters, parametersValuesById],+ );return {parametersValuesById,+ previewParameterValuesBySlug,};};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-navigation.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-navigation.tsindex 706f596083f..cc91ed51a60 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-navigation.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-navigation.ts@@ -10,8 +10,17 @@ import { EMBED_STEPS } from "../constants";import { useSdkIframeEmbedSetupContext } from "../context";export function useSdkIframeEmbedNavigation() {- const { experience, currentStep, setCurrentStep, settings, defaultSettings } =- useSdkIframeEmbedSetupContext();+ const {+ isGuestEmbedsEnabled,+ initialState,+ experience,+ resource,+ currentStep,+ setCurrentStep,+ settings,+ defaultSettings,+ embeddingParameters,+ } = useSdkIframeEmbedSetupContext();const availableSteps = useMemo(() => {// Exclude non-applicable steps for the current embed type@@ -33,13 +42,21 @@ export function useSdkIframeEmbedNavigation() {);}).with("select-embed-resource", () => {- trackEmbedWizardResourceSelectionCompleted(- settings,- defaultSettings.resourceId,- );+ trackEmbedWizardResourceSelectionCompleted({+ experience,+ currentSettings: settings,+ defaultResourceId: defaultSettings.resourceId,+ });}).with("select-embed-options", () => {- trackEmbedWizardOptionsCompleted(settings, experience);+ trackEmbedWizardOptionsCompleted({+ initialState,+ experience,+ resource,+ settings,+ isGuestEmbedsEnabled,+ embeddingParameters,+ });});if (nextStep) {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-server-snippet.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-server-snippet.tsnew file mode 100644index 00000000000..9f1a16c0890--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-server-snippet.ts@@ -0,0 +1,104 @@+import { useMemo, useState } from "react";++import { useSetting } from "metabase/common/hooks";+import { useSdkIframeEmbedSetupContext } from "metabase/embedding/embedding-iframe-sdk-setup/context";+import { getResourceTypeFromExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience";+import { isQuestionOrDashboardSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings";+import {+ clojure,+ node,+ python,+ ruby,+} from "metabase/public/lib/code-templates";+import type {+ CodeSampleParameters,+ ServerCodeSampleConfig,+} from "metabase/public/lib/types";++const getEmbedServerCodeExampleOptions = (+ codeSampleParameters: Omit<CodeSampleParameters, "displayOptions">,+): Omit<ServerCodeSampleConfig, "getIframeQuerySource">[] => [+ {+ id: "node",+ name: "Node.js",+ source: node.getServerSource(codeSampleParameters),+ parametersSource: node.getParametersSource(codeSampleParameters.params),+ language: "typescript",+ embedOption: "pug",+ },+ {+ id: "ruby",+ name: "Ruby",+ source: ruby.getServerSource(codeSampleParameters),+ parametersSource: ruby.getParametersSource(codeSampleParameters.params),+ language: "ruby",+ embedOption: "erb",+ },+ {+ id: "python",+ name: "Python",+ source: python.getServerSource(codeSampleParameters),+ parametersSource: python.getParametersSource(codeSampleParameters.params),+ language: "python",+ embedOption: "pug",+ },+ {+ id: "clojure",+ name: "Clojure",+ source: clojure.getServerSource(codeSampleParameters),+ parametersSource: clojure.getParametersSource(codeSampleParameters.params),+ language: "clojure",+ embedOption: "pug",+ },+];++export function useSdkIframeEmbedServerSnippet() {+ const { experience, resource, previewParameterValuesBySlug, settings } =+ useSdkIframeEmbedSetupContext();++ const isGuestEmbed = !!settings.isGuest;+ const isQuestionOrDashboardEmbed = isQuestionOrDashboardSettings(+ experience,+ settings,+ );++ const siteUrl = useSetting("site-url");+ const secretKey = useSetting("embedding-secret-key");++ const resourceType = getResourceTypeFromExperience(experience);++ const serverSnippetOptions = useMemo(+ () =>+ resource && resourceType && secretKey+ ? getEmbedServerCodeExampleOptions({+ siteUrl,+ secretKey,+ resourceType,+ resourceId: resource.id,+ params: previewParameterValuesBySlug,+ // We don't need an iframe snippet, because we use EmbedJS snippet for frontent snippet+ withIframeSnippet: false,+ })+ : [],+ [previewParameterValuesBySlug, resource, resourceType, secretKey, siteUrl],+ );++ const [selectedServerSnippetId, setSelectedServerSnippetId] = useState(+ serverSnippetOptions[0]?.id,+ );++ const serverSnippetOption =+ serverSnippetOptions.find(({ id }) => id === selectedServerSnippetId) ??+ null;++ if (!isGuestEmbed || !isQuestionOrDashboardEmbed || !serverSnippetOption) {+ return null;+ }++ return {+ serverSnippetOptions,+ serverSnippetOption,+ selectedServerSnippetId,+ setSelectedServerSnippetId,+ };+}diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.tsindex 3e44134ca72..4c04ccee6e7 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts@@ -13,35 +13,56 @@ import type {} from "metabase/embedding/embedding-iframe-sdk-setup/types";import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";-import { trackEmbedWizardOpened } from "../analytics";+import { getAdjustedSdkIframeEmbedSetting } from "../utils/get-adjusted-sdk-iframe-embed-setting";import {getDefaultSdkIframeEmbedSettings,getExperienceFromSettings,getResourceIdFromSettings,} from "../utils/get-default-sdk-iframe-embed-setting";-const getSettingsToPersist = (- settings: Partial<SdkIframeEmbedSetupSettings>,-) => {- return _.pick(settings, ["theme", "useExistingUserSession"]);+const getSettingsToPersist = ({+ isSimpleEmbedFeatureAvailable,+ settings,+}: {+ isSimpleEmbedFeatureAvailable: boolean;+ settings: Partial<SdkIframeEmbedSetupSettings>;+}): Partial<Pick<SdkIframeEmbedSetupSettings, "theme">> => {+ const keys = [];++ // We don't allow theme change when `simple embedding` feature is not available.+ if (isSimpleEmbedFeatureAvailable) {+ keys.push("theme");+ }++ return _.pick(settings, keys);};-const usePersistedSettings = () => {+const usePersistedSettings = ({+ isSimpleEmbedFeatureAvailable,+}: {+ isSimpleEmbedFeatureAvailable: boolean;+}) => {const [rawPersisted, rawPersistSettings] = useUserSetting("sdk-iframe-embed-setup-settings",{ debounceTimeout: USER_SETTINGS_DEBOUNCE_MS },);const persistedSettings = useMemo(- () => getSettingsToPersist(rawPersisted || {}),- [rawPersisted],+ () =>+ getSettingsToPersist({+ isSimpleEmbedFeatureAvailable,+ settings: rawPersisted || {},+ }),+ [isSimpleEmbedFeatureAvailable, rawPersisted],);const persistSettings = useCallback((settings: Partial<SdkIframeEmbedSetupSettings>) => {- rawPersistSettings(getSettingsToPersist(settings));+ rawPersistSettings(+ getSettingsToPersist({ isSimpleEmbedFeatureAvailable, settings }),+ );},- [rawPersistSettings],+ [isSimpleEmbedFeatureAvailable, rawPersistSettings],);return [persistedSettings, persistSettings] as const;@@ -52,14 +73,20 @@ export const useSdkIframeEmbedSettings = ({recentDashboards,isRecentsLoading,modelCount,+ isSimpleEmbedFeatureAvailable,+ isGuestEmbedsEnabled,}: {initialState: SdkIframeEmbedSetupModalInitialState | undefined;recentDashboards: SdkIframeEmbedSetupRecentItem[];isRecentsLoading: boolean;modelCount: number;+ isSimpleEmbedFeatureAvailable: boolean;+ isGuestEmbedsEnabled: boolean;}) => {const [isEmbedSettingsLoaded, setEmbedSettingsLoaded] = useState(false);- const [persistedSettings, persistSettings] = usePersistedSettings();+ const [persistedSettings, persistSettings] = usePersistedSettings({+ isSimpleEmbedFeatureAvailable,+ });const defaultSettings = useMemo(() => {return match(initialState)@@ -67,25 +94,31 @@ export const useSdkIframeEmbedSettings = ({{ resourceType: "dashboard", resourceId: P.nonNullable },(initialState) =>getDefaultSdkIframeEmbedSettings({+ initialState,experience: "dashboard",resourceId: initialState.resourceId,+ isGuestEmbedsEnabled,}),).with({ resourceType: "question", resourceId: P.nonNullable },(initialState) =>getDefaultSdkIframeEmbedSettings({+ initialState,experience: "chart",resourceId: initialState.resourceId,+ isGuestEmbedsEnabled,}),)- .otherwise(() =>+ .otherwise((initialState) =>getDefaultSdkIframeEmbedSettings({+ initialState,experience: "dashboard",resourceId: recentDashboards[0]?.id ?? EMBED_FALLBACK_DASHBOARD_ID,+ isGuestEmbedsEnabled,}),);- }, [recentDashboards, initialState]);+ }, [recentDashboards, initialState, isGuestEmbedsEnabled]);const [rawSettings, setRawSettings] = useState<SdkIframeEmbedSetupSettings>();@@ -118,11 +151,18 @@ export const useSdkIframeEmbedSettings = ({...nextSettings,} as SdkIframeEmbedSetupSettings;- persistSettings(mergedSettings);+ const adjustedSettings = getAdjustedSdkIframeEmbedSetting({+ defaultSettings: defaultSettings,+ prevSettings: prevSettings ?? defaultSettings,+ settings: mergedSettings,+ isGuestEmbedsEnabled,+ });++ persistSettings(adjustedSettings);- return mergedSettings;+ return adjustedSettings;}),- [defaultSettings, persistSettings],+ [defaultSettings, persistSettings, isGuestEmbedsEnabled],);const replaceSettings = useCallback(@@ -137,20 +177,23 @@ export const useSdkIframeEmbedSettings = ({// If they are, set them as the current settings.useEffect(() => {if (!isEmbedSettingsLoaded && !isRecentsLoading) {- setRawSettings({- ...settings,- ...persistedSettings,-- // Override the persisted settings if `useExistingUserSession` is specified.- // This is used for Embedding Hub.- ...(initialState?.useExistingUserSession !== undefined && {- useExistingUserSession: initialState.useExistingUserSession,- }),+ setRawSettings((prevSettings) => {+ const mergedSettings = {+ ...settings,+ ...persistedSettings,+ };++ const adjustedSettings = getAdjustedSdkIframeEmbedSetting({+ defaultSettings,+ prevSettings: prevSettings ?? defaultSettings,+ settings: mergedSettings,+ isGuestEmbedsEnabled,+ });++ return adjustedSettings;});setEmbedSettingsLoaded(true);-- trackEmbedWizardOpened();}}, [persistedSettings,@@ -158,6 +201,8 @@ export const useSdkIframeEmbedSettings = ({settings,isRecentsLoading,initialState,+ defaultSettings,+ isGuestEmbedsEnabled,]);return {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.tsindex 758c5429431..a3b03f232a6 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts@@ -9,7 +9,8 @@ import { getEmbedSnippet } from "../utils/embed-snippet";export function useSdkIframeEmbedSnippet() {const instanceUrl = useSetting("site-url");const applicationColors = useSetting("application-colors");- const { settings, experience } = useSdkIframeEmbedSetupContext();+ const { settings, experience, guestEmbedSignedTokenForSnippet } =+ useSdkIframeEmbedSetupContext();return useMemo(() => {// Apply derived colors to the settings for the code snippet@@ -24,6 +25,13 @@ export function useSdkIframeEmbedSnippet() {settings: { ...settings, theme: derivedTheme },instanceUrl,experience,+ guestEmbedSignedTokenForSnippet,});- }, [settings, applicationColors, instanceUrl, experience]);+ }, [+ settings,+ applicationColors,+ instanceUrl,+ experience,+ guestEmbedSignedTokenForSnippet,+ ]);}diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.tsindex 4942217d737..08c53440fe8 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts@@ -5,6 +5,7 @@ import type {MetabotEmbedOptions,QuestionEmbedOptions,SdkIframeEmbedBaseSettings,+ SdkIframeEmbedGuestEmbedSettings,} from "metabase/embedding/embedding-iframe-sdk/types/embed";import type { BaseRecentItem } from "metabase-types/api";@@ -31,9 +32,16 @@ export type SdkIframeEmbedSetupRecentItem = Pick<"name" | "description"> & { id: string | number };-export type SdkIframeDashboardEmbedSettings = DashboardEmbedOptions;+export type SdkIframeEmbedSetupGuestEmbedSettings =+ SdkIframeEmbedGuestEmbedSettings;-export type SdkIframeQuestionEmbedSettings = QuestionEmbedOptions;+export type SdkIframeDashboardEmbedSettings = DashboardEmbedOptions & {+ lockedParameters?: string[];+};++export type SdkIframeQuestionEmbedSettings = QuestionEmbedOptions & {+ lockedParameters?: string[];+};export type SdkIframeEmbedSetupTemplateSettings =| SdkIframeDashboardEmbedSettings@@ -50,4 +58,5 @@ export type SdkIframeEmbedSetupSettings = Omit<SdkIframeEmbedBaseSettings,"instanceUrl"> &+ Partial<SdkIframeEmbedSetupGuestEmbedSettings> &SdkIframeEmbedSetupTemplateSettings;diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes.tsnew file mode 100644index 00000000000..25858733dc8--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes.ts@@ -0,0 +1,144 @@+import { match } from "ts-pattern";++import {+ ALLOWED_EMBED_SETTING_KEYS_MAP,+ ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP,+ type AllowedEmbedSettingKey,+} from "metabase/embedding/embedding-iframe-sdk/constants";+import type {+ DashboardEmbedOptions,+ ExplorationEmbedOptions,+ QuestionEmbedOptions,+ SdkIframeEmbedBaseSettings,+} from "metabase/embedding/embedding-iframe-sdk/types/embed";+import type {+ SdkIframeDashboardEmbedSettings,+ SdkIframeEmbedSetupExperience,+ SdkIframeEmbedSetupSettings,+ SdkIframeQuestionEmbedSettings,+} from "metabase/embedding/embedding-iframe-sdk-setup/types";+import { getVisibleParameters } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters";++export const buildEmbedAttributes = ({+ settings,+ experience,+ token,+ wrapWithQuotes,+}: {+ settings: SdkIframeEmbedSetupSettings;+ experience: SdkIframeEmbedSetupExperience;+ token: string | null;+ wrapWithQuotes: boolean;+}) => {+ const isGuestEmbed = !!settings.isGuest;++ const settingsWithOverrides = match(experience)+ .with("chart", () => {+ const questionSettings = settings as SdkIframeQuestionEmbedSettings;++ return {+ ...questionSettings,+ token,+ initialSqlParameters: getVisibleParameters(+ questionSettings.initialSqlParameters,+ questionSettings.lockedParameters,+ ),+ hiddenParameters: questionSettings.hiddenParameters?.length+ ? questionSettings.hiddenParameters+ : undefined,+ entityTypes: questionSettings.entityTypes?.length+ ? questionSettings.entityTypes+ : undefined,+ } as QuestionEmbedOptions;+ })+ .with("exploration", () => {+ const explorationSettings = settings as ExplorationEmbedOptions;++ return {+ ...explorationSettings,+ questionId: "new" as const,+ entityTypes: explorationSettings.entityTypes?.length+ ? explorationSettings.entityTypes+ : undefined,+ template: undefined,+ } as unknown as ExplorationEmbedOptions;+ })+ .with("dashboard", () => {+ const dashboardSettings = settings as SdkIframeDashboardEmbedSettings;++ return {+ ...dashboardSettings,+ token,+ initialParameters: getVisibleParameters(+ dashboardSettings.initialParameters,+ dashboardSettings.lockedParameters,+ ),+ hiddenParameters: dashboardSettings.hiddenParameters?.length+ ? dashboardSettings.hiddenParameters+ : undefined,+ } as DashboardEmbedOptions;+ })+ .otherwise(() => settings);++ return transformEmbedSettingsToAttributes({+ settings: settingsWithOverrides,+ keysToProcess: isGuestEmbed+ ? ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP[experience]+ : ALLOWED_EMBED_SETTING_KEYS_MAP[experience],+ wrapWithQuotes,+ });+};++// Convert camelCase keys to lower-dash-case for web components+const toDashCase = (str: string): string =>+ str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);++// Convert values to string attributes+export const formatAttributeValue = (+ value: unknown,+ wrapWithQuotes: boolean = true,+): string => {+ if (Array.isArray(value) || typeof value === "object") {+ const jsonString = JSON.stringify(value);+ const escapedString = jsonString.replace(/'/g, "'");+ return wrapWithQuotes ? `'${escapedString}'` : escapedString;+ }++ return wrapWithQuotes ? `"${value}"` : String(value);+};++type SettingKey = Exclude<keyof SdkIframeEmbedBaseSettings, "_isLocalhost">;++function transformEmbedSettingsToAttributes({+ settings,+ keysToProcess,+ wrapWithQuotes,+}: {+ settings: Partial<SdkIframeEmbedSetupSettings>;+ keysToProcess: AllowedEmbedSettingKey[];+ wrapWithQuotes: boolean;+}): Record<string, string> {+ const attributes: [string, string][] = [];++ for (const key of keysToProcess) {+ const value = (settings as any)[key];++ if (value === undefined || value === null) {+ continue;+ }++ // Skip base configuration keys that go into defineMetabaseConfig+ if (ALLOWED_EMBED_SETTING_KEYS_MAP.base.includes(key as SettingKey)) {+ continue;+ }++ const attributeName = toDashCase(key);++ attributes.push([+ attributeName,+ formatAttributeValue(value, wrapWithQuotes),+ ]);+ }++ return Object.fromEntries(attributes);+}diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes.unit.spec.tsnew file mode 100644index 00000000000..f9b8dab5d90--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes.unit.spec.ts@@ -0,0 +1,539 @@+import type {+ SdkIframeEmbedSetupExperience,+ SdkIframeEmbedSetupSettings,+} from "metabase/embedding/embedding-iframe-sdk-setup/types";++import {+ buildEmbedAttributes,+ formatAttributeValue,+} from "./build-embed-attributes";++// Mock getVisibleParameters+jest.mock("./get-visible-parameters", () => ({+ getVisibleParameters: jest.fn((params, locked) => {+ if (!params || !locked?.length) {+ return params;+ }+ const filtered = Object.fromEntries(+ Object.entries(params).filter(([key]) => !locked.includes(key)),+ );+ return Object.keys(filtered).length > 0 ? filtered : undefined;+ }),+}));++describe("buildEmbedAttributes", () => {+ describe("chart experience", () => {+ it("should build attributes for chart with guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ isGuest: true,+ withTitle: true,+ withDownloads: false,+ drills: true,+ initialSqlParameters: { param1: "value1", param2: "value2" },+ lockedParameters: ["param2"],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: "test-token",+ wrapWithQuotes: true,+ });++ // Note: drills is not in ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP for chart+ expect(result).toEqual({+ token: '"test-token"',+ "initial-sql-parameters": `'{"param1":"value1"}'`,+ "with-title": '"true"',+ "with-downloads": '"false"',+ });+ });++ it("should build attributes for chart without guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ isGuest: false,+ withTitle: false,+ withDownloads: true,+ drills: false,+ initialSqlParameters: { param1: "value1" },+ hiddenParameters: ["param2"],+ isSaveEnabled: true,+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "question-id": '"123"',+ "is-save-enabled": '"true"',+ "initial-sql-parameters": `'{"param1":"value1"}'`,+ "hidden-parameters": `'["param2"]'`,+ "with-title": '"false"',+ drills: '"false"',+ "with-downloads": '"true"',+ });+ });++ it("should handle chart with entityTypes", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ isGuest: false,+ entityTypes: ["model", "table"],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "question-id": '"123"',+ "entity-types": `'["model","table"]'`,+ });+ });++ it("should handle chart with targetCollection", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ isGuest: false,+ targetCollection: 456,+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ // Note: template is not in ALLOWED_EMBED_SETTING_KEYS_MAP for chart+ expect(result).toEqual({+ "question-id": '"123"',+ });+ });++ it("should omit hiddenParameters if empty array for chart", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ isGuest: false,+ hiddenParameters: [],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "question-id": '"123"',+ });+ });++ it("should filter locked parameters from initialSqlParameters for guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ isGuest: true,+ initialSqlParameters: {+ param1: "value1",+ param2: "value2",+ param3: "value3",+ },+ lockedParameters: ["param2", "param3"],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: "test-token",+ wrapWithQuotes: true,+ });++ expect(result["initial-sql-parameters"]).toBe(`'{"param1":"value1"}'`);+ });+ });++ describe("dashboard experience", () => {+ it("should build attributes for dashboard with guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-dashboard",+ dashboardId: 456,+ isGuest: true,+ withTitle: true,+ withDownloads: true,+ drills: false,+ initialParameters: { filter1: "value1", filter2: "value2" },+ lockedParameters: ["filter2"],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "dashboard" as SdkIframeEmbedSetupExperience,+ token: "test-token",+ wrapWithQuotes: true,+ });++ // Note: drills is not in ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP for dashboard+ expect(result).toEqual({+ token: '"test-token"',+ "initial-parameters": `'{"filter1":"value1"}'`,+ "with-title": '"true"',+ "with-downloads": '"true"',+ });+ });++ it("should build attributes for dashboard without guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-dashboard",+ dashboardId: 456,+ isGuest: false,+ withTitle: false,+ withDownloads: false,+ drills: true,+ initialParameters: { filter1: "value1" },+ hiddenParameters: ["filter2"],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "dashboard" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "dashboard-id": '"456"',+ "initial-parameters": `'{"filter1":"value1"}'`,+ "hidden-parameters": `'["filter2"]'`,+ "with-title": '"false"',+ drills: '"true"',+ "with-downloads": '"false"',+ });+ });++ it("should omit hiddenParameters if empty array for dashboard", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-dashboard",+ dashboardId: 456,+ isGuest: false,+ hiddenParameters: [],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "dashboard" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "dashboard-id": '"456"',+ });+ });++ it("should filter locked parameters from initialParameters for guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-dashboard",+ dashboardId: 456,+ isGuest: true,+ initialParameters: {+ filter1: "value1",+ filter2: "value2",+ filter3: "value3",+ },+ lockedParameters: ["filter1", "filter3"],+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "dashboard" as SdkIframeEmbedSetupExperience,+ token: "test-token",+ wrapWithQuotes: true,+ });++ expect(result["initial-parameters"]).toBe(`'{"filter2":"value2"}'`);+ });+ });++ describe("exploration experience", () => {+ it("should build attributes for exploration without guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ targetCollection: 789,+ entityTypes: ["model", "table"],+ isSaveEnabled: true,+ apiKey: "test-api-key",+ template: "exploration",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "exploration" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "question-id": '"new"',+ "target-collection": '"789"',+ "entity-types": `'["model","table"]'`,+ "is-save-enabled": '"true"',+ });+ });++ it("should build attributes for exploration with guest embed", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ isGuest: true,+ targetCollection: 789,+ entityTypes: ["model"],+ apiKey: "test-api-key",+ template: "exploration",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "exploration" as SdkIframeEmbedSetupExperience,+ token: "test-token",+ wrapWithQuotes: true,+ });++ // Note: ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.exploration is empty+ expect(result).toEqual({});+ });++ it("should omit isSaveEnabled for guest embed exploration", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ isGuest: true,+ targetCollection: 789,+ isSaveEnabled: true,+ apiKey: "test-api-key",+ template: "exploration",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "exploration" as SdkIframeEmbedSetupExperience,+ token: "test-token",+ wrapWithQuotes: true,+ });++ expect(result).not.toHaveProperty("is-save-enabled");+ });+ });++ describe("base settings exclusion", () => {+ it("should exclude base configuration keys from attributes", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ apiKey: "test-api-key",+ theme: { colors: { primary: "#000" } },+ locale: "en",+ preferredAuthMethod: "jwt",+ isGuest: false,+ } as SdkIframeEmbedSetupSettings;++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).not.toHaveProperty("api-key");+ expect(result).not.toHaveProperty("theme");+ expect(result).not.toHaveProperty("locale");+ expect(result).not.toHaveProperty("preferred-auth-method");+ expect(result).not.toHaveProperty("is-guest-embed");+ });+ });++ describe("wrapWithQuotes parameter", () => {+ it("should not wrap values with quotes when wrapWithQuotes is false", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ componentName: "metabase-question",+ questionId: 123,+ withTitle: true,+ initialSqlParameters: { param1: "value1" },+ apiKey: "test-api-key",+ };++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: false,+ });++ expect(result).toEqual({+ "question-id": "123",+ "initial-sql-parameters": `{"param1":"value1"}`,+ "with-title": "true",+ });+ });+ });++ describe("undefined and null values", () => {+ it("should omit undefined values from attributes", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ questionId: 123,+ withTitle: undefined,+ drills: undefined,+ apiKey: "test-api-key",+ } as SdkIframeEmbedSetupSettings;++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "question-id": '"123"',+ });+ });++ it("should omit null values from attributes", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ questionId: 123,+ withTitle: null as any,+ drills: null as any,+ apiKey: "test-api-key",+ } as SdkIframeEmbedSetupSettings;++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toEqual({+ "question-id": '"123"',+ });+ });+ });++ describe("camelCase to dash-case conversion", () => {+ it("should convert camelCase keys to dash-case", () => {+ const settings: SdkIframeEmbedSetupSettings = {+ questionId: 123,+ isSaveEnabled: true,+ initialSqlParameters: { param: "value" },+ hiddenParameters: ["param"],+ apiKey: "test-api-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = buildEmbedAttributes({+ settings,+ experience: "chart" as SdkIframeEmbedSetupExperience,+ token: null,+ wrapWithQuotes: true,+ });++ expect(result).toHaveProperty("question-id");+ expect(result).toHaveProperty("is-save-enabled");+ expect(result).toHaveProperty("initial-sql-parameters");+ expect(result).toHaveProperty("hidden-parameters");+ expect(result).not.toHaveProperty("questionId");+ expect(result).not.toHaveProperty("isSaveEnabled");+ });+ });+});++describe("formatAttributeValue", () => {+ it("should format string values correctly", () => {+ expect(formatAttributeValue("hello")).toBe('"hello"');+ });++ it("should format number values correctly", () => {+ expect(formatAttributeValue(42)).toBe('"42"');+ expect(formatAttributeValue(3.14)).toBe('"3.14"');+ });++ it("should format boolean values correctly", () => {+ expect(formatAttributeValue(true)).toBe('"true"');+ expect(formatAttributeValue(false)).toBe('"false"');+ });++ it("should format array values correctly", () => {+ expect(formatAttributeValue([1, 2, 3])).toBe("'[1,2,3]'");+ expect(formatAttributeValue(["a", "b", "c"])).toBe('\'["a","b","c"]\'');+ expect(formatAttributeValue([1, "b", true])).toBe("'[1,\"b\",true]'");+ });++ it("should HTML escape single quotes in array and objects", () => {+ expect(formatAttributeValue(["O'Reilly", "D'Angelo"])).toBe(+ `'["O'Reilly","D'Angelo"]'`,+ );+ expect(formatAttributeValue({ quote: "It's a test" })).toBe(+ `'{"quote":"It's a test"}'`,+ );+ });++ it("should HTML escape single quotes in nested arrays and objects", () => {+ expect(+ formatAttributeValue([{ name: "O'Reilly" }, { name: "D'Angelo" }]),+ ).toBe(`'[{"name":"O'Reilly"},{"name":"D'Angelo"}]'`);+ expect(formatAttributeValue({ nested: { quote: "It's a test" } })).toBe(+ `'{"nested":{"quote":"It's a test"}}'`,+ );+ });++ it("should format object values correctly", () => {+ expect(formatAttributeValue({ key: "value" })).toBe(`'{"key":"value"}'`);+ expect(formatAttributeValue({ a: 1, b: true })).toBe(`'{"a":1,"b":true}'`);+ });++ it("should handle nested arrays and objects", () => {+ expect(formatAttributeValue([{ a: 1 }, { b: 2 }])).toBe(+ `'[{"a":1},{"b":2}]'`,+ );+ expect(+ formatAttributeValue([+ [1, 2],+ [3, 4],+ ]),+ ).toBe("'[[1,2],[3,4]]'");+ });++ it("should handle null and undefined values", () => {+ expect(formatAttributeValue(null)).toBe("'null'");+ expect(formatAttributeValue(undefined)).toBe('"undefined"');+ });++ it("should not wrap with quotes if flag is passed to `false`", () => {+ expect(formatAttributeValue(42, false)).toBe("42");+ expect(formatAttributeValue({ a: 1, b: true }, false)).toBe(+ `{"a":1,"b":true}`,+ );+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.tsindex c9e7a59d315..6cfe98e3e9c 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.ts@@ -3,33 +3,27 @@ import _ from "underscore";import {ALLOWED_EMBED_SETTING_KEYS_MAP,- type AllowedEmbedSettingKey,+ ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP,} from "metabase/embedding/embedding-iframe-sdk/constants";-import type {- DashboardEmbedOptions,- QuestionEmbedOptions,- SdkIframeEmbedBaseSettings,-} from "metabase/embedding/embedding-iframe-sdk/types/embed";+import { buildEmbedAttributes } from "metabase/embedding/embedding-iframe-sdk-setup/utils/build-embed-attributes";import type {- SdkIframeDashboardEmbedSettings,SdkIframeEmbedSetupExperience,SdkIframeEmbedSetupSettings,- SdkIframeQuestionEmbedSettings,} from "../types";import { filterEmptySettings } from "./filter-empty-settings";-type SettingKey = Exclude<keyof SdkIframeEmbedBaseSettings, "_isLocalhost">;-export function getEmbedSnippet({settings,instanceUrl,experience,+ guestEmbedSignedTokenForSnippet,}: {settings: SdkIframeEmbedSetupSettings;instanceUrl: string;experience: SdkIframeEmbedSetupExperience;+ guestEmbedSignedTokenForSnippet: string | null;}): string {// eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins.return `<script defer src="${instanceUrl}/app/embed.js"></script>@@ -51,16 +45,21 @@ function defineMetabaseConfig(config) {${getEmbedCustomElementSnippet({settings,experience,+ guestEmbedSignedTokenForSnippet,})}`;}export function getEmbedCustomElementSnippet({settings,experience,+ guestEmbedSignedTokenForSnippet,}: {settings: SdkIframeEmbedSetupSettings;experience: SdkIframeEmbedSetupExperience;+ guestEmbedSignedTokenForSnippet: string | null;}): string {+ const isGuestEmbed = !!settings.isGuest;+const elementName = match(experience).with("dashboard", () => "metabase-dashboard").with("chart", () => "metabase-question")@@ -69,84 +68,25 @@ export function getEmbedCustomElementSnippet({.with("metabot", () => "metabase-metabot").exhaustive();- const settingsWithOverrides = match(experience)- .with("chart", () => {- const questionSettings = settings as SdkIframeQuestionEmbedSettings;-- return {- ...settings,- hiddenParameters: questionSettings.hiddenParameters?.length- ? questionSettings.hiddenParameters- : undefined,- } as QuestionEmbedOptions;- })- .with(- "exploration",- () =>- ({- ...settings,- questionId: "new" as const,- template: undefined,- }) as QuestionEmbedOptions,- )- .with("dashboard", () => {- const dashboardSettings = settings as SdkIframeDashboardEmbedSettings;-- return {- ...settings,- hiddenParameters: dashboardSettings.hiddenParameters?.length- ? dashboardSettings.hiddenParameters- : undefined,- } as DashboardEmbedOptions;- })- .otherwise(() => settings);-- const attributes = transformEmbedSettingsToAttributes(- settingsWithOverrides,- ALLOWED_EMBED_SETTING_KEYS_MAP[experience],- );-- return `<${elementName}${attributes ? ` ${attributes}` : ""}></${elementName}>`;-}--// Convert camelCase keys to lower-dash-case for web components-const toDashCase = (str: string): string =>- str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);--// Convert values to string attributes-export const formatAttributeValue = (value: unknown): string => {- if (Array.isArray(value) || typeof value === "object") {- const jsonString = JSON.stringify(value);- const escapedString = jsonString.replace(/'/g, "'");- return `'${escapedString}'`;- }-- return `"${value}"`;-};--export function transformEmbedSettingsToAttributes(- settings: Partial<SdkIframeEmbedSetupSettings>,- keysToProcess: AllowedEmbedSettingKey[],-): string {- const attributes: string[] = [];-- for (const key of keysToProcess) {- const value = (settings as any)[key];-- if (value === undefined || value === null) {- continue;- }+ const attributes = buildEmbedAttributes({+ experience,+ settings,+ token: guestEmbedSignedTokenForSnippet,+ wrapWithQuotes: true,+ });- // Skip base configuration keys that go into defineMetabaseConfig- if (ALLOWED_EMBED_SETTING_KEYS_MAP.base.includes(key as SettingKey)) {- continue;- }+ const attributesString = Object.entries(attributes)+ .map(([key, value]) => `${key}=${value}`)+ .join(" ");- const attributeName = toDashCase(key);- attributes.push(`${attributeName}=${formatAttributeValue(value)}`);- }+ const customElementSnippetParts = [+ isGuestEmbed && guestEmbedSignedTokenForSnippet+ ? `<!--\nTHIS IS THE EXAMPLE!\nNEVER HARDCODE THIS JWT TOKEN DIRECTLY IN YOUR HTML!\n\nFetch the JWT token from your backend and programmatically pass it to the '${elementName}'.\n-->`+ : "",+ `<${elementName}${attributesString.trim() ? ` ${attributesString}` : ""}></${elementName}>`,+ ].filter(Boolean);- return attributes.join(" ");+ return customElementSnippetParts.join("\n");}export function getMetabaseConfigSnippet({@@ -156,13 +96,21 @@ export function getMetabaseConfigSnippet({settings: Partial<SdkIframeEmbedSetupSettings>;instanceUrl: string;}): string {- const config = _.pick(settings, ALLOWED_EMBED_SETTING_KEYS_MAP.base);+ const isGuestEmbed = !!settings.isGuest;++ const config = _.pick(+ settings,+ isGuestEmbed+ ? ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.base+ : ALLOWED_EMBED_SETTING_KEYS_MAP.base,+ );const cleanedConfig = {- ..._.omit(config, ["useExistingUserSession"]),+ ..._.omit(config, ["isGuest", "useExistingUserSession"]),- // Only include useExistingUserSession if it is true.+ // Only include settings below when they are true....(config.useExistingUserSession ? { useExistingUserSession: true } : {}),+ ...(isGuestEmbed ? { isGuest: true } : {}),// Append these settings that can't be controlled by users.instanceUrl,diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.unit.spec.tsdeleted file mode 100644index ae7a0ea3623..00000000000--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/embed-snippet.unit.spec.ts+++ /dev/null@@ -1,63 +0,0 @@-import { formatAttributeValue } from "./embed-snippet";--describe("formatAttributeValue", () => {- it("should format string values correctly", () => {- expect(formatAttributeValue("hello")).toBe('"hello"');- });-- it("should format number values correctly", () => {- expect(formatAttributeValue(42)).toBe('"42"');- expect(formatAttributeValue(3.14)).toBe('"3.14"');- });-- it("should format boolean values correctly", () => {- expect(formatAttributeValue(true)).toBe('"true"');- expect(formatAttributeValue(false)).toBe('"false"');- });-- it("should format array values correctly", () => {- expect(formatAttributeValue([1, 2, 3])).toBe("'[1,2,3]'");- expect(formatAttributeValue(["a", "b", "c"])).toBe('\'["a","b","c"]\'');- expect(formatAttributeValue([1, "b", true])).toBe("'[1,\"b\",true]'");- });-- it("should HTML escape single quotes in array and objects", () => {- expect(formatAttributeValue(["O'Reilly", "D'Angelo"])).toBe(- `'["O'Reilly","D'Angelo"]'`,- );- expect(formatAttributeValue({ quote: "It's a test" })).toBe(- `'{"quote":"It's a test"}'`,- );- });-- it("should HTML escape single quotes in nested arrays and objects", () => {- expect(- formatAttributeValue([{ name: "O'Reilly" }, { name: "D'Angelo" }]),- ).toBe(`'[{"name":"O'Reilly"},{"name":"D'Angelo"}]'`);- expect(formatAttributeValue({ nested: { quote: "It's a test" } })).toBe(- `'{"nested":{"quote":"It's a test"}}'`,- );- });-- it("should format object values correctly", () => {- expect(formatAttributeValue({ key: "value" })).toBe(`'{"key":"value"}'`);- expect(formatAttributeValue({ a: 1, b: true })).toBe(`'{"a":1,"b":true}'`);- });-- it("should handle nested arrays and objects", () => {- expect(formatAttributeValue([{ a: 1 }, { b: 2 }])).toBe(- `'[{"a":1},{"b":2}]'`,- );- expect(- formatAttributeValue([- [1, 2],- [3, 4],- ]),- ).toBe("'[[1,2],[3,4]]'");- });-- it("should handle null and undefined values", () => {- expect(formatAttributeValue(null)).toBe("'null'");- expect(formatAttributeValue(undefined)).toBe('"undefined"');- });-});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-adjusted-sdk-iframe-embed-setting.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-adjusted-sdk-iframe-embed-setting.tsnew file mode 100644index 00000000000..10376140007--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-adjusted-sdk-iframe-embed-setting.ts@@ -0,0 +1,62 @@+import { match } from "ts-pattern";++import { getCommonEmbedSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings";++import type { SdkIframeEmbedSetupSettings } from "../types";++import { getExperienceFromSettings } from "./get-default-sdk-iframe-embed-setting";++export const getAdjustedSdkIframeEmbedSetting = ({+ defaultSettings,+ prevSettings,+ settings,+ isGuestEmbedsEnabled,+}: {+ defaultSettings: SdkIframeEmbedSetupSettings;+ prevSettings: SdkIframeEmbedSetupSettings;+ settings: SdkIframeEmbedSetupSettings;+ isGuestEmbedsEnabled: boolean;+}): SdkIframeEmbedSetupSettings => {+ const experience = getExperienceFromSettings(settings);++ return match({ prevSettings, settings })+ .with(+ {+ prevSettings: { isGuest: false },+ settings: { isGuest: true },+ },+ ({ settings }) => ({+ ...settings,+ ...getCommonEmbedSettings({+ state: {+ isGuest: settings.isGuest,+ useExistingUserSession: settings.useExistingUserSession,+ },+ experience,+ isGuestEmbedsEnabled,+ }),+ }),+ )+ .with(+ {+ prevSettings: { isGuest: true },+ settings: { isGuest: false },+ },+ ({ settings }) => ({+ ...settings,+ drills: "drills" in defaultSettings && defaultSettings.drills,+ isSaveEnabled:+ "isSaveEnabled" in defaultSettings && defaultSettings.isSaveEnabled,+ ...getCommonEmbedSettings({+ state: {+ isGuest: settings.isGuest,+ useExistingUserSession: settings.useExistingUserSession,+ },+ experience,+ isGuestEmbedsEnabled,+ }),+ useExistingUserSession: settings.useExistingUserSession,+ }),+ )+ .otherwise(({ settings }) => settings);+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-auth-type-for-settings.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-auth-type-for-settings.tsnew file mode 100644index 00000000000..fc3a18c1213--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-auth-type-for-settings.ts@@ -0,0 +1,10 @@+import type { SdkIframeEmbedSetupSettings } from "metabase/embedding/embedding-iframe-sdk-setup/types";++export const getAuthTypeForSettings = (+ settings: Partial<SdkIframeEmbedSetupSettings>,+) =>+ settings.isGuest+ ? "guest-embed"+ : settings.useExistingUserSession+ ? "user-session"+ : "sso";diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings.tsnew file mode 100644index 00000000000..921749c2f55--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings.ts@@ -0,0 +1,104 @@+import { isQuestionOrDashboardExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-experience";+import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";++import type {+ SdkIframeDashboardEmbedSettings,+ SdkIframeEmbedSetupExperience,+ SdkIframeEmbedSetupGuestEmbedSettings,+ SdkIframeEmbedSetupSettings,+ SdkIframeQuestionEmbedSettings,+} from "../types";++const GET_ENABLE_GUEST_EMBED_SETTINGS: (data: {+ isSimpleEmbedFeatureAvailable: boolean;+ experience: SdkIframeEmbedSetupExperience;+}) => SdkIframeEmbedSetupGuestEmbedSettings &+ Pick<SdkIframeEmbedSetupSettings, "useExistingUserSession"> = ({+ isSimpleEmbedFeatureAvailable,+ experience,+}) => {+ const isQuestionOrDashboardEmbed =+ isQuestionOrDashboardExperience(experience);++ return {+ ...(isQuestionOrDashboardEmbed+ ? {+ isGuest: true,+ useExistingUserSession: false,+ ...(isQuestionOrDashboardEmbed && {+ drills: false,+ // We force set `downloads` to `true` when the `simple embedding` feature is not enabled (OSS)+ ...(!isSimpleEmbedFeatureAvailable && {+ withDownloads: true,+ }),+ }),+ }+ : {+ isGuest: false,+ useExistingUserSession: true,+ }),+ hiddenParameters: [],+ };+};++const GET_DISABLE_GUEST_EMBED_SETTINGS: (data: {+ state:+ | Pick<SdkIframeEmbedSetupSettings, "isGuest" | "useExistingUserSession">+ | undefined;+ experience: SdkIframeEmbedSetupExperience;+}) => SdkIframeEmbedSetupGuestEmbedSettings &+ Pick<SdkIframeEmbedSetupSettings, "useExistingUserSession"> &+ Pick<+ SdkIframeDashboardEmbedSettings | SdkIframeQuestionEmbedSettings,+ "lockedParameters"+ > = ({ state, experience }) => {+ const isQuestionOrDashboardEmbed =+ isQuestionOrDashboardExperience(experience);+ const isQuestionEmbed = experience === "chart";++ return {+ ...(isQuestionOrDashboardEmbed+ ? {+ isGuest: false,+ useExistingUserSession: state?.useExistingUserSession,+ drills: true,+ }+ : {+ isGuest: false,+ useExistingUserSession: state?.useExistingUserSession,+ }),+ ...(isQuestionEmbed && {+ // Currently, a chart should not have hidden parameters in non-guest embed mode+ hiddenParameters: [],+ }),+ };+};++export const getCommonEmbedSettings = ({+ state,+ experience,+ isGuestEmbedsEnabled,+}: {+ state:+ | Pick<SdkIframeEmbedSetupSettings, "isGuest" | "useExistingUserSession">+ | undefined;+ experience: SdkIframeEmbedSetupExperience;+ isGuestEmbedsEnabled: boolean;+}) => {+ const isSimpleEmbedFeatureAvailable =+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled();++ if (isSimpleEmbedFeatureAvailable) {+ return isGuestEmbedsEnabled && state?.isGuest+ ? GET_ENABLE_GUEST_EMBED_SETTINGS({+ experience,+ isSimpleEmbedFeatureAvailable,+ })+ : GET_DISABLE_GUEST_EMBED_SETTINGS({ state, experience });+ } else {+ return GET_ENABLE_GUEST_EMBED_SETTINGS({+ experience,+ isSimpleEmbedFeatureAvailable,+ });+ }+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings.unit.spec.tsnew file mode 100644index 00000000000..0b5bfbb243c--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-common-embed-settings.unit.spec.ts@@ -0,0 +1,326 @@+import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";+import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";++import { getCommonEmbedSettings } from "./get-common-embed-settings";++jest.mock("metabase/plugins", () => ({+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP: {+ isFeatureEnabled: jest.fn(),+ },+}));++const mockIsFeatureEnabled = (enabled: boolean) => {+ (+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled as jest.Mock+ ).mockReturnValue(enabled);+};++describe("getCommonEmbedSettings", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("when simple embed feature is available (Enterprise)", () => {+ beforeEach(() => {+ mockIsFeatureEnabled(true);+ });++ describe("with guest embeds enabled and state.isGuest is true", () => {+ it.each<{+ experience: SdkIframeEmbedSetupExperience;+ useExistingUserSession: boolean;+ expected: Record<string, unknown>;+ }>([+ {+ experience: "dashboard",+ useExistingUserSession: false,+ expected: {+ isGuest: true,+ useExistingUserSession: false,+ drills: false,+ hiddenParameters: [],+ },+ },+ {+ experience: "chart",+ useExistingUserSession: false,+ expected: {+ isGuest: true,+ useExistingUserSession: false,+ drills: false,+ hiddenParameters: [],+ },+ },+ {+ experience: "exploration",+ useExistingUserSession: true,+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "browser",+ useExistingUserSession: true,+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "metabot",+ useExistingUserSession: true,+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ hiddenParameters: [],+ },+ },+ ])(+ "should return correct settings for $experience experience",+ ({ experience, useExistingUserSession, expected }) => {+ const result = getCommonEmbedSettings({+ state: { isGuest: true, useExistingUserSession },+ experience,+ isGuestEmbedsEnabled: true,+ });++ expect(result).toEqual(expected);+ },+ );+ });++ describe("with guest embeds disabled", () => {+ it.each<{+ experience: SdkIframeEmbedSetupExperience;+ useExistingUserSession: boolean;+ expected: Record<string, unknown>;+ }>([+ {+ experience: "dashboard",+ useExistingUserSession: true,+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ drills: true,+ },+ },+ {+ experience: "chart",+ useExistingUserSession: false,+ expected: {+ isGuest: false,+ useExistingUserSession: false,+ drills: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "exploration",+ useExistingUserSession: true,+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ },+ },+ ])(+ "should return non-guest settings for $experience experience",+ ({ experience, useExistingUserSession, expected }) => {+ const result = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession },+ experience,+ isGuestEmbedsEnabled: false,+ });++ expect(result).toEqual(expected);+ },+ );++ it("should reset hiddenParameters for chart but not for dashboard in non-guest mode", () => {+ const chartResult = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession: true },+ experience: "chart",+ isGuestEmbedsEnabled: false,+ });++ const dashboardResult = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession: true },+ experience: "dashboard",+ isGuestEmbedsEnabled: false,+ });++ expect(chartResult).toHaveProperty("hiddenParameters", []);+ expect(dashboardResult).not.toHaveProperty("hiddenParameters");+ });++ it("should handle undefined state", () => {+ const result = getCommonEmbedSettings({+ state: undefined,+ experience: "dashboard",+ isGuestEmbedsEnabled: false,+ });++ expect(result).toEqual({+ isGuest: false,+ useExistingUserSession: undefined,+ drills: true,+ });+ });+ });++ describe("with guest embeds enabled but state.isGuest is false", () => {+ it.each<{+ experience: SdkIframeEmbedSetupExperience;+ useExistingUserSession: boolean;+ expected: Record<string, unknown>;+ }>([+ {+ experience: "dashboard",+ useExistingUserSession: true,+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ drills: true,+ },+ },+ {+ experience: "exploration",+ useExistingUserSession: false,+ expected: {+ isGuest: false,+ useExistingUserSession: false,+ },+ },+ ])(+ "should return non-guest settings for $experience experience",+ ({ experience, useExistingUserSession, expected }) => {+ const result = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession },+ experience,+ isGuestEmbedsEnabled: true,+ });++ expect(result).toEqual(expected);+ },+ );+ });+ });++ describe("when simple embed feature is not available (OSS)", () => {+ beforeEach(() => {+ mockIsFeatureEnabled(false);+ });++ it.each<{+ experience: SdkIframeEmbedSetupExperience;+ expected: Record<string, unknown>;+ }>([+ {+ experience: "dashboard",+ expected: {+ isGuest: true,+ useExistingUserSession: false,+ drills: false,+ withDownloads: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "chart",+ expected: {+ isGuest: true,+ useExistingUserSession: false,+ drills: false,+ withDownloads: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "exploration",+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "browser",+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ hiddenParameters: [],+ },+ },+ {+ experience: "metabot",+ expected: {+ isGuest: false,+ useExistingUserSession: true,+ hiddenParameters: [],+ },+ },+ ])(+ "should return correct settings for $experience experience",+ ({ experience, expected }) => {+ const result = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession: false },+ experience,+ isGuestEmbedsEnabled: false,+ });++ expect(result).toEqual(expected);+ },+ );++ it("should ignore isGuestEmbedsEnabled parameter for dashboard/chart", () => {+ const resultWithTrue = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession: false },+ experience: "dashboard",+ isGuestEmbedsEnabled: true,+ });++ const resultWithFalse = getCommonEmbedSettings({+ state: { isGuest: false, useExistingUserSession: false },+ experience: "dashboard",+ isGuestEmbedsEnabled: false,+ });++ expect(resultWithTrue).toEqual(resultWithFalse);+ expect(resultWithTrue).toEqual({+ isGuest: true,+ useExistingUserSession: false,+ drills: false,+ withDownloads: true,+ hiddenParameters: [],+ });+ });++ it("should force withDownloads=true for dashboard/chart", () => {+ const result = getCommonEmbedSettings({+ state: undefined,+ experience: "dashboard",+ isGuestEmbedsEnabled: true,+ });++ expect(result).toHaveProperty("withDownloads", true);+ });++ it("should handle undefined state", () => {+ const result = getCommonEmbedSettings({+ state: undefined,+ experience: "chart",+ isGuestEmbedsEnabled: false,+ });++ expect(result).toEqual({+ isGuest: true,+ useExistingUserSession: false,+ drills: false,+ withDownloads: true,+ hiddenParameters: [],+ });+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.tsindex 17889ead285..95e68cf3d86 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts@@ -8,20 +8,27 @@ import type {MetabotEmbedOptions,QuestionEmbedOptions,} from "metabase/embedding/embedding-iframe-sdk/types/embed";+import type { SdkIframeEmbedSetupModalInitialState } from "metabase/plugins";import type {SdkIframeEmbedSetupExperience,SdkIframeEmbedSetupSettings,} from "../types";+import { getCommonEmbedSettings } from "./get-common-embed-settings";+export const getDefaultSdkIframeEmbedSettings = ({+ initialState,experience,resourceId,+ isGuestEmbedsEnabled,}: {+ initialState: SdkIframeEmbedSetupModalInitialState | undefined;experience: SdkIframeEmbedSetupExperience;resourceId: SdkDashboardId | SdkQuestionId;+ isGuestEmbedsEnabled: boolean;}): SdkIframeEmbedSetupSettings => {- const templateDefaults = match(experience)+ const defaults = match(experience).with("dashboard",(): DashboardEmbedOptions => ({@@ -68,8 +75,13 @@ export const getDefaultSdkIframeEmbedSettings = ({.exhaustive();return {- ...templateDefaults,useExistingUserSession: true,+ ...defaults,+ ...getCommonEmbedSettings({+ state: initialState,+ experience,+ isGuestEmbedsEnabled,+ }),};};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience.tsnew file mode 100644index 00000000000..e9b5dd8290f--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience.ts@@ -0,0 +1,15 @@+import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";+import type { GuestEmbedResourceType } from "metabase/public/lib/types";++export const getResourceTypeFromExperience = (+ experience: SdkIframeEmbedSetupExperience,+): GuestEmbedResourceType | null => {+ switch (experience) {+ case "dashboard":+ return "dashboard";+ case "chart":+ return "question";+ default:+ return null;+ }+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters.tsnew file mode 100644index 00000000000..fdbecd3fb80--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters.ts@@ -0,0 +1,31 @@+import type { SqlParameterValues } from "embedding-sdk-bundle/types";+import type { ParameterValues } from "metabase-types/api";++const getNormalizedParameters = <+ TParameters extends ParameterValues | SqlParameterValues,+>(+ parameters: TParameters,+) => (Object.keys(parameters).length > 0 ? parameters : undefined);++export const getVisibleParameters = <+ TParameters extends ParameterValues | SqlParameterValues,+>(+ parameters: TParameters | undefined,+ lockedParameters: string[] | undefined,+): TParameters | undefined => {+ if (!parameters) {+ return parameters;+ }++ if (!lockedParameters?.length) {+ return getNormalizedParameters(parameters);+ }++ const filteredParameters = Object.fromEntries(+ Object.entries(parameters).filter(+ ([key]) => !lockedParameters.includes(key),+ ),+ ) as TParameters;++ return getNormalizedParameters(filteredParameters);+};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters.unit.spec.tsnew file mode 100644index 00000000000..396fb7049e7--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-visible-parameters.unit.spec.ts@@ -0,0 +1,74 @@+import { getVisibleParameters } from "./get-visible-parameters";++describe("getVisibleParameters", () => {+ describe("when lockedParameters is undefined or empty", () => {+ it.each([+ {+ parameters: { param1: "value1", param2: "value2" },+ lockedParameters: undefined,+ description: "undefined locked parameters",+ expected: { param1: "value1", param2: "value2" },+ },+ {+ parameters: { param1: "value1", param2: "value2" },+ lockedParameters: [],+ description: "empty locked parameters array",+ expected: { param1: "value1", param2: "value2" },+ },+ ])(+ "should return original parameters when $description",+ ({ parameters, lockedParameters, expected }) => {+ const result = getVisibleParameters(parameters, lockedParameters);++ expect(result).toEqual(expected);+ },+ );+ });++ describe("when filtering parameters", () => {+ it.each([+ {+ parameters: { param1: "value1", param2: "value2", param3: "value3" },+ lockedParameters: ["param2"],+ description: "one locked parameter out of three",+ expected: { param1: "value1", param3: "value3" },+ },+ {+ parameters: { param1: "value1", param2: "value2", param3: "value3" },+ lockedParameters: ["param1", "param3"],+ description: "two locked parameters out of three",+ expected: { param2: "value2" },+ },+ {+ parameters: { param1: "value1", param2: "value2" },+ lockedParameters: ["param3"],+ description: "locked parameter not in parameters",+ expected: { param1: "value1", param2: "value2" },+ },+ {+ parameters: { param1: "value1", param2: "value2" },+ lockedParameters: ["param3", "param4"],+ description: "multiple locked parameters not in parameters",+ expected: { param1: "value1", param2: "value2" },+ },+ ])(+ "should return filtered parameters when $description",+ ({ parameters, lockedParameters, expected }) => {+ const result = getVisibleParameters(parameters, lockedParameters);++ expect(result).toEqual(expected);+ },+ );+ });++ describe("when all parameters are locked", () => {+ it("should return undefined when all parameters are locked", () => {+ const parameters = { param1: "value1", param2: "value2" };+ const lockedParameters = ["param1", "param2"];++ const result = getVisibleParameters(parameters, lockedParameters);++ expect(result).toBeUndefined();+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-experience.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-experience.tsnew file mode 100644index 00000000000..a043febb032--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-experience.ts@@ -0,0 +1,6 @@+import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";++export const isQuestionOrDashboardExperience = (+ experience: SdkIframeEmbedSetupExperience,+): experience is "dashboard" | "chart" =>+ ["dashboard", "chart"].includes(experience);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings.tsnew file mode 100644index 00000000000..175968e1829--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings.ts@@ -0,0 +1,19 @@+import type {+ SdkIframeDashboardEmbedSettings,+ SdkIframeEmbedSetupExperience,+ SdkIframeEmbedSetupSettings,+ SdkIframeQuestionEmbedSettings,+} from "metabase/embedding/embedding-iframe-sdk-setup/types";++export const isQuestionOrDashboardSettings = (+ experience: SdkIframeEmbedSetupExperience,+ settings: SdkIframeEmbedSetupSettings,+): settings is+ | SdkIframeDashboardEmbedSettings+ | SdkIframeQuestionEmbedSettings =>+ (experience === "dashboard" &&+ settings.dashboardId !== null &&+ settings.dashboardId !== undefined) ||+ (experience === "chart" &&+ settings.questionId !== null &&+ settings.questionId !== undefined);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings.unit.spec.tsnew file mode 100644index 00000000000..776d0f7e4eb--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings.unit.spec.ts@@ -0,0 +1,190 @@+import type {+ SdkIframeEmbedSetupExperience,+ SdkIframeEmbedSetupSettings,+} from "metabase/embedding/embedding-iframe-sdk-setup/types";++import { isQuestionOrDashboardSettings } from "./is-question-or-dashboard-settings";++describe("isQuestionOrDashboardSettings", () => {+ describe("dashboard experience", () => {+ it.each([+ { dashboardId: 123, description: "positive number", expected: true },+ { dashboardId: 0, description: "0", expected: true },+ { dashboardId: "123", description: "string", expected: true },+ { dashboardId: "", description: "empty string", expected: true },+ { dashboardId: false, description: "false", expected: true },+ { dashboardId: null, description: "null", expected: false },+ { dashboardId: undefined, description: "undefined", expected: false },+ ])(+ "should return $expected when dashboardId is $description",+ ({ dashboardId, expected }) => {+ const settings = {+ dashboardId,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings("dashboard", settings);++ expect(result).toBe(expected);+ },+ );++ it("should return false when questionId is provided instead of dashboardId", () => {+ const settings = {+ questionId: 123,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings("dashboard", settings);++ expect(result).toBe(false);+ });+ });++ describe("chart experience", () => {+ it.each([+ { questionId: 456, description: "positive number", expected: true },+ { questionId: 0, description: "0", expected: true },+ { questionId: "456", description: "string", expected: true },+ { questionId: "", description: "empty string", expected: true },+ { questionId: false, description: "false", expected: true },+ { questionId: null, description: "null", expected: false },+ { questionId: undefined, description: "undefined", expected: false },+ ])(+ "should return $expected when questionId is $description",+ ({ questionId, expected }) => {+ const settings = {+ questionId,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings("chart", settings);++ expect(result).toBe(expected);+ },+ );++ it("should return false when dashboardId is provided instead of questionId", () => {+ const settings = {+ dashboardId: 456,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings("chart", settings);++ expect(result).toBe(false);+ });+ });++ describe("other experiences", () => {+ it.each([+ {+ experience: "exploration" as SdkIframeEmbedSetupExperience,+ settings: { questionId: 123 },+ description: "exploration with questionId",+ expected: false,+ },+ {+ experience: "exploration" as SdkIframeEmbedSetupExperience,+ settings: { dashboardId: 123 },+ description: "exploration with dashboardId",+ expected: false,+ },+ {+ experience: "browser" as SdkIframeEmbedSetupExperience,+ settings: { questionId: 123, dashboardId: 456 },+ description: "browser with both IDs",+ expected: false,+ },+ {+ experience: "metabot" as SdkIframeEmbedSetupExperience,+ settings: { questionId: 123, dashboardId: 456 },+ description: "metabot with both IDs",+ expected: false,+ },+ ])(+ "should return $expected for $description",+ ({ experience, settings, expected }) => {+ const result = isQuestionOrDashboardSettings(+ experience,+ settings as unknown as SdkIframeEmbedSetupSettings,+ );++ expect(result).toBe(expected);+ },+ );+ });++ describe("edge cases", () => {+ it.each([+ {+ experience: "dashboard" as const,+ description: "dashboard",+ expected: true,+ },+ { experience: "chart" as const, description: "chart", expected: true },+ ])(+ "should return $expected when both IDs are present for $description experience",+ ({ experience, expected }) => {+ const settings = {+ dashboardId: 123,+ questionId: 456,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings(experience, settings);++ expect(result).toBe(expected);+ },+ );++ it.each([+ { settings: {}, description: "empty settings", expected: false },+ {+ settings: { apiKey: "test-key", withTitle: true },+ description: "settings without IDs",+ expected: false,+ },+ ])(+ "should return $expected for dashboard with $description",+ ({ settings, expected }) => {+ const result = isQuestionOrDashboardSettings(+ "dashboard",+ settings as SdkIframeEmbedSetupSettings,+ );++ expect(result).toBe(expected);+ },+ );+ });++ describe("type guard behavior", () => {+ it("should narrow type to SdkIframeDashboardEmbedSettings for dashboard", () => {+ const settings = {+ dashboardId: 123,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings("dashboard", settings);++ // Type guard should return true and narrow the type+ expect(result).toBe(true);+ // TypeScript should allow accessing dashboardId due to type narrowing+ expect(settings.dashboardId).toBe(123);+ });++ it("should narrow type to SdkIframeQuestionEmbedSettings for chart", () => {+ const settings = {+ questionId: 456,+ apiKey: "test-key",+ } as unknown as SdkIframeEmbedSetupSettings;++ const result = isQuestionOrDashboardSettings("chart", settings);++ // Type guard should return true and narrow the type+ expect(result).toBe(true);+ // TypeScript should allow accessing questionId due to type narrowing+ expect(settings.questionId).toBe(456);+ });+ });+});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-step-with-resource.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-step-with-resource.tsnew file mode 100644index 00000000000..c19038b1d61--- /dev/null+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/is-step-with-resource.ts@@ -0,0 +1,4 @@+import type { SdkIframeEmbedSetupStep } from "metabase/embedding/embedding-iframe-sdk-setup/types";++export const isStepWithResource = (step: SdkIframeEmbedSetupStep) =>+ step === "select-embed-options" || step === "get-code";diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsxindex 257a98dee49..ffa3812cc6c 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx@@ -15,10 +15,15 @@ import {import { getSdkStore, useSdkSelector } from "embedding-sdk-bundle/store";import { getLoginStatus } from "embedding-sdk-bundle/store/selectors";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";+import type { SdkDashboardEntityPublicProps } from "embedding-sdk-bundle/types/dashboard";+import type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";+import { EmbeddingFooter } from "metabase/embedding/components/EmbeddingFooter/EmbeddingFooter";import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";import { createTracker } from "metabase/lib/analytics-untyped";+import { useSelector } from "metabase/lib/redux";import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";-import { Box } from "metabase/ui";+import { getSetting } from "metabase/selectors/settings";+import { Stack } from "metabase/ui";import { useParamRerenderKey } from "../hooks/use-param-rerender-key";import { useSdkIframeEmbedEventBus } from "../hooks/use-sdk-iframe-embed-event-bus";@@ -53,11 +58,12 @@ export const SdkIframeEmbedRoute = () => {const hasEmbedTokenFeature = PLUGIN_EMBEDDING_IFRAME_SDK.hasValidLicense();+ const { isGuest, theme, locale } = embedSettings;const isProduction = !embedSettings._isLocalhost;- // If the parent page is not running on localhost and+ // If the parent page is not running on localhost, it's not the unauthenticated embedding, and// the token feature is not present, we show an error message- if (isProduction && !hasEmbedTokenFeature) {+ if (isProduction && !isGuest && !hasEmbedTokenFeature) {return <SdkIframeInvalidLicenseError />;}@@ -71,12 +77,11 @@ export const SdkIframeEmbedRoute = () => {return <SdkIframeExistingUserSessionInProductionError />;}- const { theme, locale } = embedSettings;-- const authConfig: MetabaseAuthConfig = {+ const authConfig = {+ isGuest: embedSettings.isGuest,metabaseInstanceUrl: embedSettings.instanceUrl,apiKey: embedSettings.apiKey,- };+ } as MetabaseAuthConfig;return (<ComponentProvider@@ -86,9 +91,20 @@ export const SdkIframeEmbedRoute = () => {reduxStore={store}isLocalHost={embedSettings._isLocalhost}>- <Box h="100vh" bg={theme?.colors?.background}>+ <Stack+ mih="100vh"+ bg={theme?.colors?.background}+ style={{+ display: "grid",+ width: "100%",+ gridTemplateColumns: "1fr",+ gridTemplateRows: "1fr auto",+ }}+ ><SdkIframeEmbedView settings={embedSettings} />- </Box>++ {isGuest && <EmbedBrandingFooter />}+ </Stack></ComponentProvider>);};@@ -112,90 +128,158 @@ const SdkIframeEmbedView = ({);}- return match(settings)- .with(- {- componentName: "metabase-browser",- },- (settings) => (- // re-mount breadcrumbs when initial collection changes- <SdkBreadcrumbsProvider key={settings.initialCollection}>- <MetabaseBrowser settings={settings} />- </SdkBreadcrumbsProvider>- ),- )- .with(- {- componentName: "metabase-dashboard",- dashboardId: P.nonNullable,- drills: false,- },- (settings) => (- <StaticDashboard- dashboardId={settings.dashboardId}- withTitle={settings.withTitle}- withDownloads={settings.withDownloads}- initialParameters={settings.initialParameters}- hiddenParameters={settings.hiddenParameters}- key={rerenderKey}- />- ),- )- .with(- {- componentName: "metabase-dashboard",- dashboardId: P.nonNullable,- drills: P.optional(true),- },- (settings) => (- <InteractiveDashboard- dashboardId={settings.dashboardId}- withTitle={settings.withTitle}- withDownloads={settings.withDownloads}- initialParameters={settings.initialParameters}- hiddenParameters={settings.hiddenParameters}- drillThroughQuestionHeight="100%"- drillThroughQuestionProps={{ isSaveEnabled: false }}- key={rerenderKey}- />- ),- )- .with(- {- componentName: "metabase-question",- questionId: P.nonNullable,- },- (settings) => {- const commonProps = {- questionId: settings.questionId,- withDownloads: settings.withDownloads,- height: "100%",- initialSqlParameters: settings.initialSqlParameters,- title: settings.withTitle ?? true, // defaulting title to true even if in the sdk it defaults to false for static- };-- // note: to create a new question we need to render InteractiveQuestion- if (settings.drills === false && settings.questionId !== "new") {- // note: this disable drills but also removes the top toolbar- return <StaticQuestion {...commonProps} key={rerenderKey} />;- }-- return (+ return (+ match(settings)+ .with(+ {+ componentName: "metabase-browser",+ },+ (settings) => (+ // re-mount breadcrumbs when initial collection changes+ <SdkBreadcrumbsProvider key={settings.initialCollection}>+ <MetabaseBrowser settings={settings} />+ </SdkBreadcrumbsProvider>+ ),+ )+ .with(+ // Embedding based on a dashboardId (Metabase Account auth type) with disabled drills+ {+ componentName: "metabase-dashboard",+ dashboardId: P.nonNullable,+ drills: false,+ },+ // Embedding based on a token (Guest Embed auth type) with default/disabled drills+ {+ componentName: "metabase-dashboard",+ token: P.nonNullable,+ },+ (settings) => {+ const entityProps: SdkDashboardEntityPublicProps = settings.token+ ? {+ token: settings.token,+ }+ : {+ dashboardId: settings.dashboardId ?? null,+ };++ return (+ <StaticDashboard+ key={rerenderKey}+ {...entityProps}+ withTitle={settings.withTitle}+ withDownloads={settings.withDownloads}+ initialParameters={settings.initialParameters}+ hiddenParameters={settings.hiddenParameters}+ />+ );+ },+ )+ .with(+ // Embedding based on a dashboardId (Metabase Account auth type) with default/enabled drills+ {+ componentName: "metabase-dashboard",+ dashboardId: P.nonNullable,+ drills: P.optional(true),+ },+ (settings) => (+ <InteractiveDashboard+ key={rerenderKey}+ dashboardId={settings.dashboardId ?? null}+ token={settings.token}+ withTitle={settings.withTitle}+ withDownloads={settings.withDownloads}+ initialParameters={settings.initialParameters}+ hiddenParameters={settings.hiddenParameters}+ drillThroughQuestionHeight="100%"+ drillThroughQuestionProps={{ isSaveEnabled: false }}+ />+ ),+ )+ .with(+ // Embedding based on a questionId (Metabase Account auth type) with disabled drills+ {+ componentName: "metabase-question",+ questionId: P.intersection(P.nonNullable, P.not("new")),+ drills: false,+ },+ // Embedding based on a token (Guest Embed auth type) with default/disabled drills+ {+ componentName: "metabase-question",+ token: P.nonNullable,+ },+ (settings) => {+ const entityProps: SdkQuestionEntityPublicProps = settings.token+ ? {+ token: settings.token,+ }+ : {+ questionId: settings.questionId ?? null,+ };++ return (+ <StaticQuestion+ key={rerenderKey}+ {...entityProps}+ withDownloads={settings.withDownloads}+ height="100%"+ initialSqlParameters={settings.initialSqlParameters}+ hiddenParameters={settings.hiddenParameters}+ title={settings.withTitle ?? true}+ />+ );+ },+ )+ // Guest Embed of a question+ .with(+ // Embedding based on a questionId (Metabase Account auth type) with default/enabled drills+ {+ componentName: "metabase-question",+ questionId: P.nonNullable,+ },+ (settings) => (<SdkQuestion- {...commonProps}- isSaveEnabled={settings.isSaveEnabled ?? false}key={rerenderKey}+ questionId={settings.questionId ?? null}+ token={settings.token}+ withDownloads={settings.withDownloads}+ height="100%"+ initialSqlParameters={settings.initialSqlParameters}+ hiddenParameters={settings.hiddenParameters}+ title={settings.withTitle ?? true}+ isSaveEnabled={settings.isSaveEnabled ?? false}targetCollection={settings.targetCollection}entityTypes={settings.entityTypes}/>- );- },- )- .with(- {- componentName: "metabase-metabot",- },- (settings) => <MetabotQuestion layout={settings.layout} height="100%" />,- )- .otherwise(() => null);+ ),+ )+ .with(+ {+ componentName: "metabase-metabot",+ },+ (settings) => (+ <MetabotQuestion+ key={rerenderKey}+ layout={settings.layout}+ height="100%"+ />+ ),+ )+ .otherwise(() => null)+ );+};++const EmbedBrandingFooter = () => {+ const hasEmbedBranding = useSelector(+ (state) => !getSetting(state, "hide-embed-branding?"),+ );++ if (!hasEmbedBranding) {+ return null;+ }++ return (+ <PublicComponentStylesWrapper>+ <EmbeddingFooter variant="default" hasEmbedBranding />+ </PublicComponentStylesWrapper>+ );};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.tsindex 8ac7f5145e3..cf60ba907a2 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts@@ -25,6 +25,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"preferredAuthMethod","fetchRequestToken","useExistingUserSession",+ "isGuest",] satisfies (keyof SdkIframeEmbedBaseSettings)[],dashboard: ["dashboardId",@@ -63,6 +64,31 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {] satisfies (keyof BrowserEmbedOptions)[],metabot: ["layout"] satisfies (keyof MetabotEmbedOptions)[],} as const;+export const ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP = {+ base: [+ "apiKey",+ "instanceUrl",+ "theme",+ "locale",+ "isGuest",+ ] satisfies (keyof SdkIframeEmbedBaseSettings)[],+ dashboard: [+ "token",+ "withTitle",+ "withDownloads",+ "initialParameters",+ ] satisfies (keyof DashboardEmbedOptions)[],+ chart: [+ "token",+ "withTitle",+ "withDownloads",+ "entityTypes",+ "initialSqlParameters",+ ] satisfies (keyof QuestionEmbedOptions)[],+ exploration: [] satisfies (keyof ExplorationEmbedOptions)[],+ browser: [] satisfies (keyof BrowserEmbedOptions)[],+ metabot: [] satisfies (keyof MetabotEmbedOptions)[],+} as const;// This file is used by embed.js, so we shouldn't import external dependencies.const uniq = <T>(list: T[]): T[] => Array.from(new Set(list));@@ -76,14 +102,25 @@ export const ALLOWED_EMBED_SETTING_KEYS = uniq([...ALLOWED_EMBED_SETTING_KEYS_MAP.metabot,]) satisfies SdkIframeEmbedSettingKey[];-export type AllowedEmbedSettingKey =- (typeof ALLOWED_EMBED_SETTING_KEYS)[number];+export const ALLOWED_GUEST_EMBED_SETTING_KEYS = uniq([+ ...ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.base,+ ...ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.dashboard,+ ...ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.chart,+ ...ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.exploration,+ ...ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP.browser,+]) satisfies SdkIframeEmbedSettingKey[];++export type AllowedEmbedSettingKey = (+ | typeof ALLOWED_EMBED_SETTING_KEYS+ | typeof ALLOWED_GUEST_EMBED_SETTING_KEYS+)[number];/** Prevent updating these fields with `embed.updateSettings()` after the embed is created. */export const DISABLE_UPDATE_FOR_KEYS = ["instanceUrl","useExistingUserSession","fetchRequestToken",+ "isGuest",] as const satisfies AllowedEmbedSettingKey[];export const METABASE_CONFIG_IS_PROXY_FIELD_NAME = "__isProxy";diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.tsindex d705fa2f21f..0bc88bd1062 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts@@ -486,6 +486,7 @@ function createCustomElement<Arr extends readonly string[]>(const MetabaseDashboardElement = createCustomElement("metabase-dashboard", ["dashboard-id",+ "token","with-title","with-downloads","drills",@@ -495,6 +496,7 @@ const MetabaseDashboardElement = createCustomElement("metabase-dashboard", [const MetabaseQuestionElement = createCustomElement("metabase-question", ["question-id",+ "token","with-title","with-downloads","drills",diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-param-rerender-key.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-param-rerender-key.tsindex 0e7cc03d725..f5a083fc4a8 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-param-rerender-key.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-param-rerender-key.ts@@ -9,19 +9,32 @@ import type { SdkIframeEmbedSettings } from "../types/embed";* Forces a re-render when the initial parameter changes.*/export const useParamRerenderKey = (settings: SdkIframeEmbedSettings) =>- useMemo(- () =>- match(settings)- .with(- { dashboardId: P.nonNullable },- (settings) =>- `dashboard-${stableStringify(settings.initialParameters)}`,- )- .with(- { questionId: P.nonNullable },- (settings) =>- `question-${stableStringify(settings.initialSqlParameters)}`,- )- .otherwise(() => null),- [settings],- );+ useMemo(() => {+ const { entity, dependencies } = match(settings)+ .with({ componentName: "metabase-dashboard" }, (settings) => ({+ entity: "dashboard",+ dependencies: {+ initialParameters: settings.initialParameters,+ hiddenParameters: settings.hiddenParameters,+ token: settings.token,+ },+ }))+ .with(+ { componentName: "metabase-question", questionId: P.nonNullable },+ { componentName: "metabase-question", token: P.nonNullable },+ (settings) => ({+ entity: "question",+ dependencies: {+ initialParameters: settings.initialSqlParameters,+ hiddenParameters: settings.hiddenParameters,+ token: settings.token,+ },+ }),+ )+ .otherwise(() => ({ entity: "entity", dependencies: {} }));++ return `${entity}-${stableStringify({+ isGuest: settings.isGuest,+ ...dependencies,+ })}`;+ }, [settings]);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.tsindex 9f5e1824307..f2b387d0926 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts@@ -7,52 +7,70 @@ import type {MetabaseTheme,SqlParameterValues,} from "embedding-sdk-bundle/types";+import type {+ SdkIframeDashboardEmbedSettings,+ SdkIframeQuestionEmbedSettings,+} from "metabase/embedding/embedding-iframe-sdk-setup/types";import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";import type {MetabaseEmbeddingSessionToken,MetabaseFetchRequestTokenFn,} from "metabase/embedding-sdk/types/refresh-token";+import type { StrictUnion } from "metabase/embedding-sdk/types/utils";import type { EmbeddedAnalyticsJsEventSchema } from "metabase-types/analytics/embedded-analytics-js";import type { CollectionId } from "metabase-types/api";import type { EmbeddingEntityType } from "metabase-types/store/embedding-data-picker";/** Events that the embed.js script listens for */export type SdkIframeEmbedTagMessage =- | { type: "metabase.embed.iframeReady" }- | { type: "metabase.embed.requestSessionToken" };+ | SdkIframeEmbedTagIframeReadyMessage+ | SdkIframeEmbedTagRequestSessionTokenMessage;++export type SdkIframeEmbedTagIframeReadyMessage = {+ type: "metabase.embed.iframeReady";+};+export type SdkIframeEmbedTagRequestSessionTokenMessage = {+ type: "metabase.embed.requestSessionToken";+};/** Events that the sdk embed route listens for */export type SdkIframeEmbedMessage =- | {- type: "metabase.embed.setSettings";- data: SdkIframeEmbedSettings;- }- | {- type: "metabase.embed.submitSessionToken";- data: {- authMethod: MetabaseAuthMethod;- sessionToken: MetabaseEmbeddingSessionToken;- };- }- | {- type: "metabase.embed.reportAuthenticationError";- data: {- error: MetabaseError<MetabaseErrorCode, unknown>;- };- }- | {- type: "metabase.embed.reportAnalytics";- data: {- usageAnalytics: EmbeddedAnalyticsJsEventSchema;- embedHostUrl: string;- };- };+ | SdkIframeEmbedSetSettingsMessage+ | SdkIframeEmbedSubmitSessionTokenMessage+ | SdkIframeEmbedReportAuthenticationError+ | SdkIframeEmbedReportAnalytics;++export type SdkIframeEmbedSetSettingsMessage = {+ type: "metabase.embed.setSettings";+ data: SdkIframeEmbedSettings;+};+export type SdkIframeEmbedSubmitSessionTokenMessage = {+ type: "metabase.embed.submitSessionToken";+ data: {+ authMethod: MetabaseAuthMethod;+ sessionToken: MetabaseEmbeddingSessionToken;+ };+};+export type SdkIframeEmbedReportAuthenticationError = {+ type: "metabase.embed.reportAuthenticationError";+ data: {+ error: MetabaseError<MetabaseErrorCode, unknown>;+ };+};+export type SdkIframeEmbedReportAnalytics = {+ type: "metabase.embed.reportAnalytics";+ data: {+ usageAnalytics: EmbeddedAnalyticsJsEventSchema;+ embedHostUrl: string;+ };+};// --- Embed Option Interfaces ----export interface DashboardEmbedOptions {+export type DashboardEmbedOptions = StrictUnion<+ { dashboardId: number | string } | { token: string }+> & {componentName: "metabase-dashboard";- dashboardId: number | string;drills?: boolean;withTitle?: boolean;@@ -65,11 +83,12 @@ export interface DashboardEmbedOptions {// incompatible optionstemplate?: never;questionId?: never;-}+};-export interface QuestionEmbedOptions {+export type QuestionEmbedOptions = StrictUnion<+ { questionId: number | string } | { token: string }+> & {componentName: "metabase-question";- questionId: number | string;drills?: boolean;withTitle?: boolean;@@ -85,7 +104,7 @@ export interface QuestionEmbedOptions {// incompatible optionstemplate?: never;dashboardId?: never;-}+};export interface ExplorationEmbedOptions {componentName: "metabase-question";@@ -98,6 +117,7 @@ export interface ExplorationEmbedOptions {// incompatible optionsdashboardId?: never;questionId?: never;+ token?: never;}export interface BrowserEmbedOptions {@@ -130,6 +150,7 @@ export interface BrowserEmbedOptions {template?: never;questionId?: never;dashboardId?: never;+ token?: never;}export interface MetabotEmbedOptions {@@ -142,6 +163,7 @@ export interface MetabotEmbedOptions {template?: never;questionId?: never;dashboardId?: never;+ token?: never;}type CollectionBrowserEntityTypes =@@ -151,6 +173,7 @@ type CollectionBrowserEntityTypes =| "model";export type SdkIframeEmbedBaseSettings = {+ isGuest?: boolean;apiKey?: string;instanceUrl: string;theme?: MetabaseTheme;@@ -165,6 +188,10 @@ export type SdkIframeEmbedBaseSettings = {_isLocalhost?: boolean;};+export type SdkIframeEmbedGuestEmbedSettings = {+ isGuest: boolean;+};+export type SdkIframeEmbedTemplateSettings =| DashboardEmbedOptions| QuestionEmbedOptions@@ -195,8 +222,8 @@ export type SdkIframeEmbedEventHandler = () => void;/** Keys that can be used to update the embed settings */export type SdkIframeEmbedSettingKey =| keyof SdkIframeEmbedBaseSettings- | keyof DashboardEmbedOptions- | keyof QuestionEmbedOptions+ | keyof SdkIframeDashboardEmbedSettings+ | keyof SdkIframeQuestionEmbedSettings| keyof ExplorationEmbedOptions| keyof BrowserEmbedOptions| keyof MetabotEmbedOptions;diff --git a/frontend/src/metabase/embedding/hooks/use-open-embed-js-wizard.ts b/frontend/src/metabase/embedding/hooks/use-open-embed-js-wizard.tsnew file mode 100644index 00000000000..f838f31b0b6--- /dev/null+++ b/frontend/src/metabase/embedding/hooks/use-open-embed-js-wizard.ts@@ -0,0 +1,31 @@+import { useCallback } from "react";++import { useDispatch } from "metabase/lib/redux";+import type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";+import { setOpenModalWithProps } from "metabase/redux/ui";++export const useOpenEmbedJsWizard = ({+ initialState,+}: {+ initialState: SdkIframeEmbedSetupModalProps["initialState"];+}) => {+ const dispatch = useDispatch();++ return useCallback(+ ({ onBeforeOpen }: { onBeforeOpen?: () => void }) => {+ const modalProps: Pick<SdkIframeEmbedSetupModalProps, "initialState"> = {+ initialState,+ };++ onBeforeOpen?.();++ dispatch(+ setOpenModalWithProps({+ id: "embed",+ props: modalProps,+ }),+ );+ },+ [dispatch, initialState],+ );+};diff --git a/frontend/src/metabase/embedding/hooks/use-sharing-modal.ts b/frontend/src/metabase/embedding/hooks/use-sharing-modal.tsnew file mode 100644index 00000000000..32136cf149e--- /dev/null+++ b/frontend/src/metabase/embedding/hooks/use-sharing-modal.ts@@ -0,0 +1,57 @@+import { useCallback, useState } from "react";++import type {+ DashboardSharingModalType,+ QuestionSharingModalType,+} from "metabase/embedding/components/SharingMenu/types";+import { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";+import { useOpenEmbedJsWizard } from "metabase/embedding/hooks/use-open-embed-js-wizard";+import { useDispatch } from "metabase/lib/redux";+import type {+ EmbedResource,+ EmbedResourceType,+} from "metabase/public/lib/types";+import { setOpenModal } from "metabase/redux/ui";++export const useSharingModal = <+ TModalType extends DashboardSharingModalType | QuestionSharingModalType,+>({+ resource,+ resourceType,+}: {+ resource: EmbedResource;+ resourceType: EmbedResourceType;+}) => {+ const dispatch = useDispatch();++ const [modalType, setModalType] = useState<TModalType | null>(null);++ const openEmbedJsWizard = useOpenEmbedJsWizard({+ initialState: {+ resourceId: resource.id,+ resourceType,+ isGuest: true,+ useExistingUserSession: true,+ },+ });++ const handleSetModalType = useCallback(+ (modalType: TModalType | null) => {+ if (!modalType) {+ dispatch(setOpenModal(null));+ }++ switch (modalType) {+ case GUEST_EMBED_EMBEDDING_TYPE:+ openEmbedJsWizard({ onBeforeOpen: () => setModalType(null) });+ break;++ default:+ setModalType(modalType);+ }+ },+ [dispatch, openEmbedJsWizard],+ );++ return { modalType, setModalType: handleSetModalType };+};diff --git a/frontend/src/metabase/embedding/hooks/use-sharing-modal.unit.spec.tsx b/frontend/src/metabase/embedding/hooks/use-sharing-modal.unit.spec.tsxnew file mode 100644index 00000000000..9986dc3768a--- /dev/null+++ b/frontend/src/metabase/embedding/hooks/use-sharing-modal.unit.spec.tsx@@ -0,0 +1,144 @@+import { act, renderHook } from "@testing-library/react";++import type { DashboardSharingModalType } from "metabase/embedding/components/SharingMenu/types";+import {+ GUEST_EMBED_EMBEDDING_TYPE,+ STATIC_LEGACY_EMBEDDING_TYPE,+} from "metabase/embedding/constants";+import { setOpenModal } from "metabase/redux/ui";+import type { Dashboard } from "metabase-types/api";++import { useSharingModal } from "./use-sharing-modal";++const mockDispatch = jest.fn();+const mockOpenEmbedJsWizard = jest.fn();++jest.mock("metabase/lib/redux", () => ({+ useDispatch: () => mockDispatch,+}));++jest.mock("metabase/embedding/hooks/use-open-embed-js-wizard", () => ({+ useOpenEmbedJsWizard: () => mockOpenEmbedJsWizard,+}));++const mockResource = { id: 1 } as Dashboard;+const mockResourceType = "dashboard" as const;++describe("useSharingModal", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("should initialize with null modalType", () => {+ const { result } = renderHook(() =>+ useSharingModal<DashboardSharingModalType>({+ resource: mockResource,+ resourceType: mockResourceType,+ }),+ );++ expect(result.current.modalType).toBeNull();+ });++ it("should set modalType for STATIC_LEGACY_EMBEDDING_TYPE", () => {+ const { result } = renderHook(() =>+ useSharingModal<DashboardSharingModalType>({+ resource: mockResource,+ resourceType: mockResourceType,+ }),+ );++ act(() => {+ result.current.setModalType(STATIC_LEGACY_EMBEDDING_TYPE);+ });++ expect(result.current.modalType).toBe(STATIC_LEGACY_EMBEDDING_TYPE);+ });++ it("should dispatch setOpenModal(null) when clearing modalType", () => {+ const { result } = renderHook(() =>+ useSharingModal<DashboardSharingModalType>({+ resource: mockResource,+ resourceType: mockResourceType,+ }),+ );++ act(() => {+ result.current.setModalType(STATIC_LEGACY_EMBEDDING_TYPE);+ });++ act(() => {+ result.current.setModalType(null);+ });++ expect(result.current.modalType).toBeNull();+ expect(mockDispatch).toHaveBeenCalledWith(setOpenModal(null));+ });++ it("should call openEmbedJsWizard when setting GUEST_EMBED_EMBEDDING_TYPE", () => {+ const { result } = renderHook(() =>+ useSharingModal<DashboardSharingModalType>({+ resource: mockResource,+ resourceType: mockResourceType,+ }),+ );++ act(() => {+ result.current.setModalType(GUEST_EMBED_EMBEDDING_TYPE);+ });++ expect(mockOpenEmbedJsWizard).toHaveBeenCalledWith({+ onBeforeOpen: expect.any(Function),+ });+ });++ it("should clear modalType before opening EmbedJS wizard", () => {+ const { result } = renderHook(() =>+ useSharingModal<DashboardSharingModalType>({+ resource: mockResource,+ resourceType: mockResourceType,+ }),+ );++ act(() => {+ result.current.setModalType(STATIC_LEGACY_EMBEDDING_TYPE);+ });++ expect(result.current.modalType).toBe(STATIC_LEGACY_EMBEDDING_TYPE);++ act(() => {+ result.current.setModalType(GUEST_EMBED_EMBEDDING_TYPE);+ });++ // Extract and call the onBeforeOpen callback+ const onBeforeOpenCallback = mockOpenEmbedJsWizard.mock.calls[0][0]+ .onBeforeOpen as () => void;++ act(() => {+ onBeforeOpenCallback();+ });++ expect(result.current.modalType).toBeNull();+ });++ it("should update modalType when switching between different modal types", () => {+ const { result } = renderHook(() =>+ useSharingModal<DashboardSharingModalType>({+ resource: mockResource,+ resourceType: mockResourceType,+ }),+ );++ act(() => {+ result.current.setModalType(STATIC_LEGACY_EMBEDDING_TYPE);+ });++ expect(result.current.modalType).toBe(STATIC_LEGACY_EMBEDDING_TYPE);++ act(() => {+ result.current.setModalType("public-link" as DashboardSharingModalType);+ });++ expect(result.current.modalType).toBe("public-link");+ });+});diff --git a/frontend/src/metabase/embedding/lib/count-embedding-parameter-options.ts b/frontend/src/metabase/embedding/lib/count-embedding-parameter-options.tsnew file mode 100644index 00000000000..4c2bbb0b83d--- /dev/null+++ b/frontend/src/metabase/embedding/lib/count-embedding-parameter-options.ts@@ -0,0 +1,18 @@+import type {+ EmbeddingParameterVisibility,+ EmbeddingParameters,+} from "metabase/public/lib/types";++export const countEmbeddingParameterOptions = (+ embeddingParams: EmbeddingParameters,+): Record<EmbeddingParameterVisibility, number> =>+ Object.values(embeddingParams).reduce(+ (acc, value) => {+ acc[value] += 1;+ return acc;+ },+ { disabled: 0, locked: 0, enabled: 0 } as Record<+ EmbeddingParameterVisibility,+ number+ >,+ );diff --git a/frontend/src/metabase/lib/api.js b/frontend/src/metabase/lib/api.jsindex b9e87d10b20..25dd872da73 100644--- a/frontend/src/metabase/lib/api.js+++ b/frontend/src/metabase/lib/api.js@@ -378,25 +378,8 @@ export class Api extends EventEmitter {}/**- /**- * @typedef {{- * method: "GET" | "POST";- * url: string;- * options: {- * headers?: Record<string, string>;- * hasBody: boolean;- * } & Record<string, unknown>;- * }} OnBeforeRequestHandlerData- *- * @typedef {(data: OnBeforeRequestHandlerData) => (Promise<void | OnBeforeRequestHandlerData>)} OnBeforeRequestHandler- *- * @typedef {{- * key: string;- * handler: OnBeforeRequestHandler- * }} OnBeforeRequestHandlerDescriptor- *- * @param data {OnBeforeRequestHandlerData}- * @return data {Promise<OnBeforeRequestHandlerData>}+ * @param data {import('metabase/plugins').OnBeforeRequestHandlerData}+ * @return data {Promise<import('metabase/plugins').OnBeforeRequestHandlerData>}*/async apiRequestManipulationMiddleware(data) {let { method, url, options } = data;@@ -404,20 +387,19 @@ export class Api extends EventEmitter {/*** Handlers order is important.* Handlers are executed in order and each handler uses the data returned by a previous handler.- * @type {OnBeforeRequestHandler[]}+ * @type {import('metabase/plugins').OnBeforeRequestHandler[]}*/const handlers = [];if (isEmbeddingSdk()) {- if (- PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler- ) {- // A handler that set's `getOrRefreshSession` logic for SDK- handlers.push(+ handlers.push(+ ...[PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler,- );- }+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers+ .overrideRequestsForGuestEmbeds,+ ],+ );}if (handlers.length) {diff --git a/frontend/src/metabase/lib/errors/is-static-embedding-entity-loading-error.ts b/frontend/src/metabase/lib/errors/is-static-embedding-entity-loading-error.tsnew file mode 100644index 00000000000..a37d9791593--- /dev/null+++ b/frontend/src/metabase/lib/errors/is-static-embedding-entity-loading-error.ts@@ -0,0 +1,18 @@+import type { StaticEmbeddingEntityError } from "metabase/lib/errors/types";++export const isStaticEmbeddingEntityLoadingError = (+ error: unknown,+ { isGuestEmbed }: { isGuestEmbed: boolean },+): error is StaticEmbeddingEntityError => {+ if (!isGuestEmbed) {+ return false;+ }++ return (+ !!error &&+ typeof error === "object" &&+ "status" in error &&+ "data" in error &&+ typeof error.data === "string"+ );+};diff --git a/frontend/src/metabase/lib/errors/types.ts b/frontend/src/metabase/lib/errors/types.tsindex 317f7fc95a3..6bf5836dc88 100644--- a/frontend/src/metabase/lib/errors/types.ts+++ b/frontend/src/metabase/lib/errors/types.ts@@ -16,3 +16,8 @@ export interface MaxLengthParams {export interface LengthParams {length: number;}++export type StaticEmbeddingEntityError = {+ status: number;+ data: string;+};diff --git a/frontend/src/metabase/lib/utils.ts b/frontend/src/metabase/lib/utils.tsindex 540782503de..66be2d6fc2c 100644--- a/frontend/src/metabase/lib/utils.ts+++ b/frontend/src/metabase/lib/utils.ts@@ -32,7 +32,7 @@ export function numberToWord(num: number) {}}-export function isJWT(string: unknown) {+export function isJWT(string: unknown): string is string {return (typeof string === "string" &&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(string)@@ -161,3 +161,35 @@ export function versionIsLatest({}export const isEEBuild = () => PLUGIN_IS_EE_BUILD.isEEBuild();++// Extract resource id from signed JWT token used in Static Embedding+export const extractResourceIdFromJwtToken = (jwtToken: string) => {+ try {+ const parts = jwtToken.split(".");+ const payloadPart = parts[1];++ let base64 = payloadPart.replace(/-/g, "+").replace(/_/g, "/");+ const padding = base64.length % 4;++ if (padding === 2) {+ base64 += "==";+ } else if (padding === 3) {+ base64 += "=";+ } else if (padding !== 0) {+ throw new Error("Invalid base64url payload");+ }++ const jsonString = decodeURIComponent(+ Array.from(window.atob(base64))+ .map((c) => "%" + c.charCodeAt(0).toString(16).padStart(2, "0"))+ .join(""),+ );+ const payload = JSON.parse(jsonString);+ const resource = payload.resource;+ const entityId = resource.dashboard || resource.question;++ return entityId;+ } catch {+ return null;+ }+};diff --git a/frontend/src/metabase/lib/utils.unit.spec.ts b/frontend/src/metabase/lib/utils.unit.spec.tsnew file mode 100644index 00000000000..7ad60f5b6de--- /dev/null+++ b/frontend/src/metabase/lib/utils.unit.spec.ts@@ -0,0 +1,81 @@+import { SignJWT } from "jose";++import { extractResourceIdFromJwtToken } from "metabase/lib/utils";++const SECRET = new TextEncoder().encode("test-secret-key-for-jwt-signing");++const createJwtToken = async (payload: object): Promise<string> => {+ return new SignJWT(payload as Record<string, unknown>)+ .setProtectedHeader({ alg: "HS256" })+ .sign(SECRET);+};++describe("extractResourceIdFromJwtToken", () => {+ it("should extract dashboard id from JWT token", async () => {+ const token = await createJwtToken({+ resource: { dashboard: 123 },+ });++ expect(extractResourceIdFromJwtToken(token)).toBe(123);+ });++ it("should extract question id from JWT token", async () => {+ const token = await createJwtToken({+ resource: { question: 456 },+ });++ expect(extractResourceIdFromJwtToken(token)).toBe(456);+ });++ it("should prefer dashboard over question when both are present", async () => {+ const token = await createJwtToken({+ resource: { dashboard: 123, question: 456 },+ });++ expect(extractResourceIdFromJwtToken(token)).toBe(123);+ });++ it("should return null for invalid JWT format", () => {+ expect(extractResourceIdFromJwtToken("not-a-jwt")).toBeNull();+ expect(extractResourceIdFromJwtToken("only.two")).toBeNull();+ expect(extractResourceIdFromJwtToken("")).toBeNull();+ });++ it("should return null when resource is missing", async () => {+ const token = await createJwtToken({+ someOtherField: "value",+ });++ expect(extractResourceIdFromJwtToken(token)).toBeNull();+ });++ it("should return null when resource has neither dashboard nor question", async () => {+ const token = await createJwtToken({+ resource: { other: "value" },+ });++ expect(extractResourceIdFromJwtToken(token)).toBeUndefined();+ });++ it("should return null for invalid base64 payload", () => {+ const token = "header.!!!invalid-base64!!!.signature";++ expect(extractResourceIdFromJwtToken(token)).toBeNull();+ });++ it("should return null for invalid JSON in payload", () => {+ const header = btoa(JSON.stringify({ alg: "HS256" }));+ const invalidJsonPayload = btoa("not valid json");+ const token = `${header}.${invalidJsonPayload}.signature`;++ expect(extractResourceIdFromJwtToken(token)).toBeNull();+ });++ it("should handle string entity ids", async () => {+ const token = await createJwtToken({+ resource: { dashboard: "abc-123" },+ });++ expect(extractResourceIdFromJwtToken(token)).toBe("abc-123");+ });+});diff --git a/frontend/src/metabase/new/components/NewModals/NewModals.tsx b/frontend/src/metabase/new/components/NewModals/NewModals.tsxindex 8a8ee032ba6..65fac387b95 100644--- a/frontend/src/metabase/new/components/NewModals/NewModals.tsx+++ b/frontend/src/metabase/new/components/NewModals/NewModals.tsx@@ -8,15 +8,18 @@ import ActionCreator from "metabase/actions/containers/ActionCreator";import CreateCollectionModal from "metabase/collections/containers/CreateCollectionModal";import Modal from "metabase/common/components/Modal";import { CreateDashboardModal } from "metabase/dashboard/containers/CreateDashboardModal";+import { STATIC_LEGACY_EMBEDDING_TYPE } from "metabase/embedding/constants";+import {+ LegacyStaticEmbeddingModal,+ type LegacyStaticEmbeddingModalProps,+} from "metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal";+import { SdkIframeEmbedSetupModal } from "metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal";import Collections from "metabase/entities/collections/collections";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 type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";import { closeModal, setOpenModal } from "metabase/redux/ui";import { getCurrentOpenModalState } from "metabase/selectors/ui";import type { WritebackAction } from "metabase-types/api";@@ -24,7 +27,7 @@ import type { WritebackAction } from "metabase-types/api";export const NewModals = withRouter((props: WithRouterProps) => {const { pathname } = useLocation();const { id: currentNewModalId, props: currentNewModalProps } = useSelector(- getCurrentOpenModalState<SdkIframeEmbedSetupModalProps>,+ getCurrentOpenModalState,);const dispatch = useDispatch();const collectionId = useSelector((state) =>@@ -91,10 +94,24 @@ export const NewModals = withRouter((props: WithRouterProps) => {</Modal>);case "embed": {+ const props = currentNewModalProps as SdkIframeEmbedSetupModalProps;return (- <PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetupModal+ <SdkIframeEmbedSetupModalopened- initialState={currentNewModalProps?.initialState}+ initialState={props?.initialState}+ onClose={handleModalClose}+ />+ );+ }+ case STATIC_LEGACY_EMBEDDING_TYPE: {+ const props = currentNewModalProps as LegacyStaticEmbeddingModalProps;++ return (+ <LegacyStaticEmbeddingModal+ experience={props?.experience}+ dashboardId={props?.dashboardId}+ questionId={props?.questionId}+ parentInitialState={props?.parentInitialState}onClose={handleModalClose}/>);diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsxindex 5071b969103..1b83e978716 100644--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx@@ -254,7 +254,12 @@ export const useCommandPaletteBasicActions = ({perform: () =>openNewModalWithProps<Pick<SdkIframeEmbedSetupModalProps, "initialState">- >("embed"),+ >("embed", {+ initialState: {+ isGuest: true,+ useExistingUserSession: true,+ },+ }),});}diff --git a/frontend/src/metabase/parameters/actions.ts b/frontend/src/metabase/parameters/actions.tsindex 107cee35660..050bf1f5f6a 100644--- a/frontend/src/metabase/parameters/actions.ts+++ b/frontend/src/metabase/parameters/actions.ts@@ -49,15 +49,16 @@ export const fetchParameterValues =export interface FetchCardParameterValuesOpts {cardId: CardId;+ token?: string | null;parameter: Parameter;query?: string;}export const fetchCardParameterValues =- ({ cardId, parameter, query }: FetchCardParameterValuesOpts) =>+ ({ cardId, token, parameter, query }: FetchCardParameterValuesOpts) =>(dispatch: Dispatch, getState: GetState) => {- const request = {- cardId,+ const request: CardParameterValuesRequest = {+ ...(token ? { token } : { cardId }),paramId: parameter.id,query,};@@ -72,6 +73,7 @@ export const fetchCardParameterValues =export interface FetchDashboardParameterValuesOpts {dashboardId: DashboardId;+ token?: string | null;parameter: Parameter;parameters: Parameter[];query?: string;@@ -80,14 +82,15 @@ export interface FetchDashboardParameterValuesOpts {export const fetchDashboardParameterValues =({dashboardId,+ token,parameter,parameters,query,}: FetchDashboardParameterValuesOpts) =>(dispatch: Dispatch, getState: GetState) => {- const request = {+ const request: DashboardParameterValuesRequest = {+ ...(token ? { token } : { dashId: dashboardId }),paramId: parameter.id,- dashId: dashboardId,query,...getFilteringParameterValuesMap(parameter, parameters),};@@ -118,7 +121,8 @@ const loadParameterValues = async (request: ParameterValuesRequest) => {};interface CardParameterValuesRequest {- cardId: CardId;+ cardId?: CardId;+ token?: string | null;paramId: ParameterId;query?: string;}@@ -135,7 +139,8 @@ const loadCardParameterValues = async (request: CardParameterValuesRequest) => {};interface DashboardParameterValuesRequest {- dashId: DashboardId;+ dashId?: DashboardId;+ token?: string | null;paramId: ParameterId;query?: string;}diff --git a/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsx b/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsxindex aa757a31e59..60ede6e135a 100644--- a/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsx+++ b/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsx@@ -48,6 +48,7 @@ export const ParameterDropdownWidget = ({parameters,cardId,dashboardId,+ token,enableRequiredBehavior,}: ParameterDropdownWidgetProps) => {const normalizedValue = Array.isArray(value)@@ -153,6 +154,7 @@ export const ParameterDropdownWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}+ token={token}value={normalizedValue}fields={parameter.fields}setValue={setValueOrDefault}diff --git a/frontend/src/metabase/parameters/components/ParameterValueWidget.tsx b/frontend/src/metabase/parameters/components/ParameterValueWidget.tsxindex 6b3d7f84d42..9bccbf04be8 100644--- a/frontend/src/metabase/parameters/components/ParameterValueWidget.tsx+++ b/frontend/src/metabase/parameters/components/ParameterValueWidget.tsx@@ -44,6 +44,7 @@ export type ParameterValueWidgetProps = {parameters?: UiParameter[];cardId?: CardId;dashboardId?: DashboardId;+ token?: string | null;setParameterValueToDefault?: (parameterId: ParameterId) => void;// This means the widget will take care of the default value.// Should be used for dashboards and native questions in the parameter bar,@@ -68,6 +69,7 @@ export const ParameterValueWidget = ({placeholder,cardId,dashboardId,+ token,setParameterValueToDefault,setValue,value,@@ -220,6 +222,7 @@ export const ParameterValueWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}+ token={token}value={value}setValue={setValue}isEditing={isEditing}@@ -307,6 +310,7 @@ export const ParameterValueWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}+ token={token}value={value}setValue={setValue}isEditing={isEditing}diff --git a/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsx b/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsxindex 0e75171a504..059d8008849 100644--- a/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsx+++ b/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsx@@ -34,6 +34,7 @@ export type ParameterWidgetProps = PropsWithChildren<setValue: (value: any) => void;cardId?: CardId;dashboardId?: DashboardId;+ token?: string | null;editingParameter: Parameter | null;commitImmediately: boolean;@@ -57,6 +58,7 @@ export type ParameterWidgetProps = PropsWithChildren<export const ParameterWidget = ({cardId,dashboardId,+ token,parameter,editingParameter,commitImmediately = false,@@ -153,6 +155,7 @@ export const ParameterWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}+ token={token}value={parameter.value}setValue={(value) => setValue?.(value)}isEditing={isEditingParameter}diff --git a/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsx b/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsxindex 48cef44da66..25430803e2e 100644--- a/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsx+++ b/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsx@@ -27,6 +27,7 @@ export const ParametersList = forwardRef<HTMLDivElement, ParametersListProps>(linkedFilterParameters = parameters,cardId,dashboardId,+ token,editingParameter,isSortable = true,@@ -82,6 +83,7 @@ export const ParametersList = forwardRef<HTMLDivElement, ParametersListProps>(parameters={linkedFilterParameters}cardId={cardId}dashboardId={dashboardId}+ token={token}editingParameter={editingParameter}setEditingParameter={setEditingParameter}setValue={diff --git a/frontend/src/metabase/parameters/components/ParametersList/types.ts b/frontend/src/metabase/parameters/components/ParametersList/types.tsindex 10328422141..c032337b0b8 100644--- a/frontend/src/metabase/parameters/components/ParametersList/types.ts+++ b/frontend/src/metabase/parameters/components/ParametersList/types.ts@@ -19,6 +19,7 @@ export type ParametersListProps = {cardId?: CardId;dashboardId?: DashboardId;+ token?: string | null;editingParameter: Parameter | null | undefined;linkedFilterParameters: Parameter[];diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsxindex 9303e236eb0..c7f9cd044fc 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx@@ -113,6 +113,7 @@ export interface IFieldValuesWidgetProps {fields: Field[];dashboardId?: DashboardId;cardId?: CardId;+ token?: string | null;value: RowValue[];onChange: (value: RowValue[]) => void;@@ -151,6 +152,7 @@ export const FieldValuesWidgetInner = forwardRef<fields,dashboardId,cardId,+ token,value,onChange,multi,@@ -248,6 +250,7 @@ export const FieldValuesWidgetInner = forwardRef<return dispatch(fetchCardParameterValues({cardId,+ token,parameter,query,}),@@ -262,6 +265,7 @@ export const FieldValuesWidgetInner = forwardRef<return dispatch(fetchDashboardParameterValues({dashboardId,+ token,parameter,parameters,query,diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsxindex 60048d6a556..2ac232d6949 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx@@ -34,6 +34,7 @@ interface ParameterFieldWidgetProps {value?: string | string[];cardId?: CardId;dashboardId?: DashboardId;+ token?: string | null;}export function ParameterFieldWidget({@@ -45,6 +46,7 @@ export function ParameterFieldWidget({parameters,cardId,dashboardId,+ token,}: ParameterFieldWidgetProps) {const [unsavedValue, setUnsavedValue] = useState<RowValue[]>(() =>normalizeValue(value),@@ -104,6 +106,7 @@ export function ParameterFieldWidget({parameters={parameters}cardId={cardId}dashboardId={dashboardId}+ token={token}onChange={onValueChange}placeholder={isEditing ? t`Enter a default value…` : undefined}fields={fields}diff --git a/frontend/src/metabase/plugins/oss/api.ts b/frontend/src/metabase/plugins/oss/api.tsindex b793a580743..bfaf75389a5 100644--- a/frontend/src/metabase/plugins/oss/api.ts+++ b/frontend/src/metabase/plugins/oss/api.ts@@ -1,11 +1,11 @@-import type { DashboardId, ParameterId } from "metabase-types/api";+import type { CardId, DashboardId, ParameterId } from "metabase-types/api";const getDefaultPluginApi = () => ({getRemappedCardParameterValueUrl: (- dashboardId: DashboardId,+ cardId: CardId,parameterId: ParameterId,) =>- `/api/card/${dashboardId}/params/${encodeURIComponent(parameterId)}/remapping`,+ `/api/card/${cardId}/params/${encodeURIComponent(parameterId)}/remapping`,getRemappedDashboardParameterValueUrl: (dashboardId: DashboardId,parameterId: ParameterId,diff --git a/frontend/src/metabase/plugins/oss/content-translation.ts b/frontend/src/metabase/plugins/oss/content-translation.tsindex 944d79467b3..d84545e75ce 100644--- a/frontend/src/metabase/plugins/oss/content-translation.ts+++ b/frontend/src/metabase/plugins/oss/content-translation.ts@@ -7,6 +7,7 @@ import type { Series } from "metabase-types/api";const getDefaultPluginContentTranslation = () => ({isEnabled: false,+ getDictionaryBasePath: null as string | null,setEndpointsForStaticEmbedding: (_encodedToken: string) => {},ContentTranslationConfiguration: PluginPlaceholder,useTranslateContent: <diff --git a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk-setup.ts b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk-setup.tsindex 59a43906796..49ef37da53f 100644--- a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk-setup.ts+++ b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk-setup.ts@@ -1,5 +1,3 @@-import type { ReactNode } from "react";-export type SdkIframeEmbedSetupModalProps = {opened: boolean;onClose: () => void;@@ -9,15 +7,12 @@ export type SdkIframeEmbedSetupModalProps = {export type SdkIframeEmbedSetupModalInitialState = {resourceType?: string | null;resourceId?: string | number | null;+ isGuest?: boolean;useExistingUserSession?: boolean;};const getDefaultPluginEmbeddingIframeSdkSetup = () => ({isFeatureEnabled: () => false,- shouldShowEmbedInNewItemMenu: () => false,- SdkIframeEmbedSetupModal: (- _props: SdkIframeEmbedSetupModalProps,- ): ReactNode => null,});export const PLUGIN_EMBEDDING_IFRAME_SDK_SETUP =diff --git a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.tsindex 3a9e6c21a91..190f9ba864a 100644--- a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts+++ b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts@@ -1,8 +1,5 @@-import type { ReactNode } from "react";-const getDefaultPluginEmbeddingIframeSdk = () => ({hasValidLicense: () => false,- SdkIframeEmbedRoute: (): ReactNode => null,});export const PLUGIN_EMBEDDING_IFRAME_SDK = getDefaultPluginEmbeddingIframeSdk();diff --git a/frontend/src/metabase/plugins/oss/embedding-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-sdk.tsindex 6ce4f4343d0..a0cde686f9c 100644--- a/frontend/src/metabase/plugins/oss/embedding-sdk.ts+++ b/frontend/src/metabase/plugins/oss/embedding-sdk.ts@@ -1,7 +1,23 @@+export type OnBeforeRequestHandlerData = {+ method: "GET" | "POST";+ url: string;+ options: {+ headers?: Record<string, string>;+ hasBody: boolean;+ } & Record<string, unknown>;+};++export type OnBeforeRequestHandler = (+ data: OnBeforeRequestHandlerData,+) => Promise<void | OnBeforeRequestHandlerData>;+const getDefaultPluginEmbeddingSdk = () => ({isEnabled: () => false,onBeforeRequestHandlers: {getOrRefreshSessionHandler: async () => {},+ overrideRequestsForGuestEmbeds: async (+ _data: OnBeforeRequestHandlerData,+ ): Promise<OnBeforeRequestHandlerData | void> => {},},});diff --git a/frontend/src/metabase/plugins/oss/settings.ts b/frontend/src/metabase/plugins/oss/settings.tsindex abe59af9478..c490fccccf5 100644--- a/frontend/src/metabase/plugins/oss/settings.ts+++ b/frontend/src/metabase/plugins/oss/settings.ts@@ -3,7 +3,7 @@ import type { ComponentType } from "react";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";const getDefaultPluginAdminSettings = () => ({- InteractiveEmbeddingSettings: null,+ InteractiveEmbeddingSettingsCard: null,LicenseAndBillingSettings: PluginPlaceholder,useUpsellFlow: (_props: {campaign: string;@@ -16,7 +16,7 @@ const getDefaultPluginAdminSettings = () => ({});export const PLUGIN_ADMIN_SETTINGS: {- InteractiveEmbeddingSettings: ComponentType | null;+ InteractiveEmbeddingSettingsCard: ComponentType | null;LicenseAndBillingSettings: ComponentType;useUpsellFlow: (props: { campaign: string; location: string }) => {triggerUpsellFlow: (() => void) | undefined;diff --git a/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx b/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsxindex 236eae24dbf..6c314c2c821 100644--- a/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx+++ b/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx@@ -15,6 +15,7 @@ import {} from "metabase/dashboard/constants";import { useIsParameterPanelSticky } from "metabase/dashboard/hooks/use-is-parameter-panel-sticky";import { getDashboardType } from "metabase/dashboard/utils";+import { EmbeddingFooter } from "metabase/embedding/components/EmbeddingFooter/EmbeddingFooter";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { initializeIframeResizer, isSmallScreen } from "metabase/lib/dom";import { useSelector } from "metabase/lib/redux";@@ -45,14 +46,12 @@ import {Body,ContentContainer,DashboardTabsContainer,- Footer,Header,Root,Separator,TitleAndButtonsContainer,TitleAndDescriptionContainer,} from "./EmbedFrame.styled";-import { LogoBadge } from "./LogoBadge";import { useGlobalTheme } from "./useGlobalTheme";export type EmbedFrameBaseProps = Partial<{@@ -290,16 +289,15 @@ export const EmbedFrame = ({{dashboard && <FilterApplyToast position="fixed" />}{isFooterEnabled && (- <Footer- data-testid="embed-frame-footer"- className={EmbedFrameS.EmbedFrameFooter}+ <EmbeddingFootervariant={footerVariant}+ isDarkMode={theme === "night"}+ hasEmbedBranding={hasEmbedBranding}>- {hasEmbedBranding && <LogoBadge dark={theme === "night"} />}{actionButtons && (<ActionButtonsContainer>{actionButtons}</ActionButtonsContainer>)}- </Footer>+ </EmbeddingFooter>)}</Root>);diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModal.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModal.tsxindex 08d426aa883..4cc6af579e9 100644--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModal.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/EmbedModal.tsx@@ -1,92 +1,56 @@-import { useMemo, useState } from "react";-import { Link } from "react-router";import { t } from "ttag";import Modal from "metabase/common/components/Modal";-import CS from "metabase/css/core/index.css";-import { useSelector } from "metabase/lib/redux";-import type { EmbedModalStep } from "metabase/public/lib/types";-import { getSetting } from "metabase/selectors/settings";-import { getApplicationName } from "metabase/selectors/whitelabel";-import { Group, Icon, Stack, Text } from "metabase/ui";+import { StaticEmbedSetupPane } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane";+import type {+ EmbedResource,+ EmbedResourceParameter,+ EmbeddingParameters,+ GuestEmbedResourceType,+} from "metabase/public/lib/types";import { EmbedModalHeader } from "./EmbedModal.styled";interface EmbedModalProps {isOpen?: boolean;+ resource: EmbedResource;+ resourceType: GuestEmbedResourceType;+ resourceParameters: EmbedResourceParameter[];++ onUpdateEnableEmbedding: (enableEmbedding: boolean) => void;+ onUpdateEmbeddingParams: (embeddingParams: EmbeddingParameters) => void;+ onBack?: () => void;onClose: () => void;- children: ({- embedType,- goToNextStep,- goBackToEmbedModal,- }: {- embedType: EmbedModalStep;- goToNextStep: () => void;- goBackToEmbedModal: () => void;- }) => JSX.Element;}-export const EmbedModal = ({ children, isOpen, onClose }: EmbedModalProps) => {- const shouldShowEmbedTerms = useSelector((state) =>- getSetting(state, "show-static-embed-terms"),- );- const [embedType, setEmbedType] = useState<EmbedModalStep>(null);- const applicationName = useSelector(getApplicationName);-- const isEmbeddingSetupStage = embedType === null;-- const goToNextStep = () => {- if (embedType === null && shouldShowEmbedTerms) {- setEmbedType("legalese");- } else {- setEmbedType("application");- }- };-- const goBackToEmbedModal = () => {- setEmbedType(null);- };-- const onEmbedClose = () => {- onClose();- setEmbedType(null);- };-- const modalTitle = useMemo(() => {- if (isEmbeddingSetupStage) {- return <EmbedModalTitle applicationName={applicationName} />;- }- }, [isEmbeddingSetupStage, applicationName]);-- return (- <Modal- isOpen={isOpen}- onClose={onEmbedClose}- title={modalTitle}- fit- formModal={false}- // needed to allow selecting with the mouse on the code samples- enableMouseEvents- >- {!isEmbeddingSetupStage && (- <EmbedModalHeader onClose={onEmbedClose} onBack={goBackToEmbedModal}>- {t`Static embedding`}- </EmbedModalHeader>- )}- {children({ embedType, goToNextStep, goBackToEmbedModal })}- </Modal>- );-};--const EmbedModalTitle = ({ applicationName }: { applicationName: string }) => (- <Stack gap="sm">- <Text fw="bold" fz="h2">{t`Embed ${applicationName}`}</Text>-- <Link to="/admin/embedding/modular" className={CS.link} target="_blank">- <Group gap="xs">- <Text c="brand">{t`Embedding settings`}</Text>- <Icon c="brand" name="external" />- </Group>- </Link>- </Stack>+export const EmbedModal = ({+ isOpen,+ resource,+ resourceType,+ resourceParameters,+ onUpdateEnableEmbedding,+ onUpdateEmbeddingParams,+ onBack,+ onClose,+}: EmbedModalProps) => (+ <Modal+ isOpen={isOpen}+ onClose={onClose}+ fit+ formModal={false}+ // needed to allow selecting with the mouse on the code samples+ enableMouseEvents+ >+ <EmbedModalHeader onClose={onClose} onBack={onBack}>+ {t`Static embedding`}+ </EmbedModalHeader>++ <StaticEmbedSetupPane+ resource={resource}+ resourceType={resourceType}+ resourceParameters={resourceParameters}+ onUpdateEnableEmbedding={onUpdateEnableEmbedding}+ onUpdateEmbeddingParams={onUpdateEmbeddingParams}+ />+ </Modal>);diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModal.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModal.unit.spec.tsxdeleted file mode 100644index 8f2609d5f7e..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModal.unit.spec.tsx+++ /dev/null@@ -1,119 +0,0 @@-import userEvent from "@testing-library/user-event";-import { Route } from "react-router";--import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen, within } from "__support__/ui";-import { Button, Group, Text } from "metabase/ui";-import { createMockState } from "metabase-types/store/mocks";--import { EmbedModal } from "./EmbedModal";--const TestEmbedModal = ({- onClose,- isOpen,-}: {- onClose: () => void;- isOpen?: boolean;-}): JSX.Element => {- return (- <EmbedModal isOpen={isOpen} onClose={onClose}>- {({ embedType, goToNextStep, goBackToEmbedModal }) => (- <Group data-testid="test-embed-modal-content">- <Button onClick={goBackToEmbedModal}>Previous</Button>- <Text data-testid="test-embed-step">- {embedType ?? "Embed Landing"}- </Text>- <Button onClick={goToNextStep}>Next</Button>- </Group>- )}- </EmbedModal>- );-};--const setup = ({ isOpen = true, showStaticEmbedTerms = true } = {}) => {- const onClose = jest.fn();-- renderWithProviders(- <Route- path="*"- component={() => <TestEmbedModal isOpen={isOpen} onClose={onClose} />}- ></Route>,- {- storeInitialState: createMockState({- settings: mockSettings({- "application-name": "Embed Metabase",- "show-static-embed-terms": showStaticEmbedTerms,- }),- }),- initialRoute: "*",- withRouter: true,- },- );-- return { onClose };-};--describe("EmbedModal", () => {- it("should render header and content", () => {- setup();-- expect(- within(screen.getByTestId("modal-header")).getByText("Embed Metabase"),- ).toBeInTheDocument();-- expect(screen.getByTestId("test-embed-modal-content")).toBeInTheDocument();-- expect(screen.getByTestId("test-embed-step")).toHaveTextContent(- "Embed Landing",- );- });-- it("should go to the legalese step when `Next` is clicked", async () => {- setup();-- await userEvent.click(screen.getByText("Next"));-- expect(screen.getByTestId("test-embed-step")).toHaveTextContent("legalese");- });-- it("should go to the legalese step then the static embedding step if the user has not accepted the embedding terms", async () => {- setup({ showStaticEmbedTerms: true });- await userEvent.click(screen.getByText("Next"));- expect(screen.getByTestId("test-embed-step")).toHaveTextContent("legalese");-- await userEvent.click(screen.getByText("Next"));- expect(screen.getByTestId("test-embed-step")).toHaveTextContent(- "application",- );- });-- it("should immediately go to the static embedding step if the user has accepted the terms", async () => {- setup({ showStaticEmbedTerms: false });-- await userEvent.click(screen.getByText("Next"));- expect(- within(screen.getByTestId("modal-header")).getByText("Static embedding"),- ).toBeInTheDocument();- expect(screen.getByTestId("test-embed-step")).toHaveTextContent(- "application",- );- });-- it("returns to the initial embed modal landing when the user clicks the modal title", async () => {- setup();-- await userEvent.click(screen.getByText("Next"));- expect(screen.getByTestId("test-embed-step")).toHaveTextContent("legalese");-- await userEvent.click(screen.getByText("Static embedding"));- expect(screen.getByTestId("test-embed-step")).toHaveTextContent(- "Embed Landing",- );- });-- it("calls onClose when the modal is closed", async () => {- const { onClose } = setup();- await userEvent.click(screen.getByLabelText("close icon"));- expect(onClose).toHaveBeenCalled();- });-});diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsxdeleted file mode 100644index 487d68d4674..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/EmbedModalContent.tsx+++ /dev/null@@ -1,78 +0,0 @@-import type { ExportFormatType } from "metabase/embedding/components/PublicLinkPopover/types";-import { LegaleseStep } from "metabase/public/components/widgets/LegaleseStep/LegaleseStep";-import type {- EmbedModalStep,- EmbedResource,- EmbedResourceParameter,- EmbedResourceType,- EmbeddingParameters,-} from "metabase/public/lib/types";--import { SelectEmbedTypePane } from "../SelectEmbedTypePane";-import { StaticEmbedSetupPane } from "../StaticEmbedSetupPane";--export interface EmbedModalContentProps {- embedType: EmbedModalStep;- goToNextStep: () => void;-- resource: EmbedResource;- resourceType: EmbedResourceType;- resourceParameters: EmbedResourceParameter[];-- onUpdateEnableEmbedding: (enableEmbedding: boolean) => void;- onUpdateEmbeddingParams: (embeddingParams: EmbeddingParameters) => void;-- onCreatePublicLink: () => void;- onDeletePublicLink: () => void;- getPublicUrl: (publicUuid: string, extension?: ExportFormatType) => string;-- onClose: () => void;-- className?: string;-}--export const EmbedModalContent = (- props: EmbedModalContentProps,-): JSX.Element => {- const {- embedType,- goToNextStep,- resource,- resourceType,- resourceParameters,- onUpdateEnableEmbedding,- onUpdateEmbeddingParams,- onCreatePublicLink,- onDeletePublicLink,- getPublicUrl,- onClose,- } = props;-- if (embedType == null) {- return (- <SelectEmbedTypePane- resource={resource}- resourceType={resourceType}- onCreatePublicLink={onCreatePublicLink}- onDeletePublicLink={onDeletePublicLink}- getPublicUrl={getPublicUrl}- goToNextStep={goToNextStep}- closeModal={onClose}- />- );- }-- if (embedType === "legalese") {- return <LegaleseStep goToNextStep={goToNextStep} />;- }-- return (- <StaticEmbedSetupPane- resource={resource}- resourceType={resourceType}- resourceParameters={resourceParameters}- onUpdateEmbeddingParams={onUpdateEmbeddingParams}- onUpdateEnableEmbedding={onUpdateEnableEmbedding}- />- );-};diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/index.ts b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/index.tsdeleted file mode 100644index c0b2fbac64f..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/index.ts+++ /dev/null@@ -1 +0,0 @@-export { EmbedModalContent } from "./EmbedModalContent";diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.common.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.common.unit.spec.tsxdeleted file mode 100644index baa499e142c..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.common.unit.spec.tsx+++ /dev/null@@ -1,187 +0,0 @@-import { screen, within } from "@testing-library/react";-import userEvent from "@testing-library/user-event";--import { createMockTokenFeatures } from "metabase-types/api/mocks";--import { setup } from "./setup";--describe("EmbedModalContent", () => {- describe("Static Embedding", () => {- describe("Select Embed Type phase", () => {- it("should render", () => {- setup();-- expect(screen.getByText("Static embedding")).toBeInTheDocument();- expect(screen.getByText("Embedded Analytics JS")).toBeInTheDocument();- expect(screen.getByText("SDK for React")).toBeInTheDocument();- });- });-- describe("when Static Embedding is disabled", () => {- const STATIC_EMBEDDING_TITLE = "Static embedding";-- it("should mention Static Embedding and tell admin to enable Static Embedding in the setting", () => {- setup();-- // The card is not clickable- expect(- screen.queryByRole("link", { name: STATIC_EMBEDDING_TITLE }),- ).not.toBeInTheDocument();-- // We show the link at the bottom of the card- const withinStaticEmbeddingCard = within(- screen.getByRole("article", { name: STATIC_EMBEDDING_TITLE }),- );- expect(- withinStaticEmbeddingCard.getByText("Disabled."),- ).toBeInTheDocument();- expect(- withinStaticEmbeddingCard.getByRole("link", {- name: "Enable in admin settings",- }),- ).toHaveAttribute("href", "/admin/embedding/static");- });- });-- describe("when Static Embedding is enabled", () => {- it("should switch to StaticEmbedSetupPane", async () => {- const { goToNextStep } = setup({- enableEmbedding: {- static: true,- },- });-- expect(goToNextStep).toHaveBeenCalledTimes(0);-- await userEvent.click(screen.getByText("Static embedding"));-- expect(goToNextStep).toHaveBeenCalledTimes(1);- });-- it("should render StaticEmbedSetupPane when embedType=application", () => {- setup({- props: {- embedType: "application",- },- });-- expect(- screen.getByText("Setting up a static embed"),- ).toBeInTheDocument();- });- });- });-- describe("Interactive Embedding", () => {- const INTERACTIVE_EMBEDDING_TITLE = "Embedded Analytics JS";-- describe("when Interactive Embedding is disabled", () => {- it("should mention Interactive Embedding and lead users to learn more link", () => {- setup();-- // The card is clickable- expect(- screen.queryByRole("link", { name: INTERACTIVE_EMBEDDING_TITLE }),- ).toHaveProperty(- "href",- "https://www.metabase.com/product/embedded-analytics?utm_source=product&utm_medium=upsell&utm_campaign=embedded-analytics-js&utm_content=static-embed-popover&source_plan=oss",- );-- // We show the learn more link- const withinInteractiveEmbeddingCard = within(- screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),- );- expect(- withinInteractiveEmbeddingCard.getByText("Learn more"),- ).toBeInTheDocument();- expect(- withinInteractiveEmbeddingCard.queryByText("Disabled."),- ).not.toBeInTheDocument();- expect(- withinInteractiveEmbeddingCard.queryByText(- "Enable in admin settings",- ),- ).not.toBeInTheDocument();- });- });-- describe("when Interactive Embedding is enabled", () => {- it("should mention Interactive Embedding and lead users to learn more link", () => {- setup({- enableEmbedding: {- interactive: true,- },- });-- // The card is clickable- expect(- screen.queryByRole("link", { name: INTERACTIVE_EMBEDDING_TITLE }),- ).toHaveProperty(- "href",- "https://www.metabase.com/product/embedded-analytics?utm_source=product&utm_medium=upsell&utm_campaign=embedded-analytics-js&utm_content=static-embed-popover&source_plan=oss",- );-- // We show the learn more link- const withinInteractiveEmbedCard = within(- screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),- );- expect(- withinInteractiveEmbedCard.getByText("Learn more"),- ).toBeInTheDocument();- });- });- });-- describe("Embedding SDK", () => {- const SDK_TITLE = "SDK for React";-- describe("when the SDK is disabled", () => {- it("should mention the sdk and tell admin to enable the SDK in the setting", () => {- setup({- tokenFeatures: createMockTokenFeatures(),- });-- expect(- screen.getByRole("link", { name: SDK_TITLE }),- ).toBeInTheDocument();-- // We show the link at the bottom of the card- const withinSdkCard = within(- screen.getByRole("article", { name: SDK_TITLE }),- );- expect(withinSdkCard.getByText("Disabled.")).toBeInTheDocument();- expect(- withinSdkCard.getByRole("link", {- name: "Enable in admin settings",- }),- ).toHaveAttribute("href", "/admin/embedding/modular");- });- });-- describe("when the SDK is enabled", () => {- it("should mention the sdk and link to its admin settings page", () => {- setup({- enableEmbedding: {- sdk: true,- },- });-- expect(screen.getByRole("link", { name: SDK_TITLE })).toHaveProperty(- "href",- "https://www.metabase.com/docs/latest/embedding/sdk/introduction.html?utm_source=product&utm_medium=docs&utm_content=embed-modal&source_plan=oss",- );-- // We don't show the link at the bottom of the card- const withinSdkCard = within(- screen.getByRole("article", { name: SDK_TITLE }),- );- expect(withinSdkCard.queryByText("Disabled.")).not.toBeInTheDocument();- expect(- withinSdkCard.queryByRole("link", {- name: "Enabled in admin settings",- }),- ).not.toBeInTheDocument();- });- });- });-});diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.enterprise.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.enterprise.unit.spec.tsxdeleted file mode 100644index bd2433be1b1..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.enterprise.unit.spec.tsx+++ /dev/null@@ -1,73 +0,0 @@-import { screen, within } from "@testing-library/react";--import { type SetupOpts, setup } from "./setup";--function setupEnterprise(opts?: Partial<SetupOpts>) {- setup({- ...opts,- hasEnterprisePlugins: true,- isHosted: false,- });-}--describe("EmbedModalContent", () => {- describe("Interactive Embedding", () => {- const INTERACTIVE_EMBEDDING_TITLE = "Embedded Analytics JS";-- describe("when Interactive Embedding is disabled", () => {- it("should mention Interactive Embedding and lead users to learn more link", () => {- setupEnterprise();-- // The card is clickable- expect(- screen.queryByRole("link", { name: "Learn more" }),- ).toHaveProperty(- "href",- "https://www.metabase.com/product/embedded-analytics?utm_source=product&utm_medium=upsell&utm_campaign=embedded-analytics-js&utm_content=static-embed-popover&source_plan=oss",- );-- // We show the learn more link- const withinInteractiveEmbeddingCard = within(- screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),- );- expect(- withinInteractiveEmbeddingCard.getByText("Learn more"),- ).toBeInTheDocument();- expect(- withinInteractiveEmbeddingCard.queryByText("Disabled."),- ).not.toBeInTheDocument();- expect(- withinInteractiveEmbeddingCard.queryByText(- "Enable in admin settings",- ),- ).not.toBeInTheDocument();-- expect(- screen.getByRole("button", { name: "Try for free" }),- ).toBeInTheDocument();- });- });-- describe("when Interactive Embedding is enabled", () => {- it("should mention Interactive Embedding and lead users to learn more link", () => {- setupEnterprise();-- // The card is clickable- expect(- screen.queryByRole("link", { name: "Learn more" }),- ).toHaveProperty(- "href",- "https://www.metabase.com/product/embedded-analytics?utm_source=product&utm_medium=upsell&utm_campaign=embedded-analytics-js&utm_content=static-embed-popover&source_plan=oss",- );-- // We show the learn more link- const withinInteractiveEmbeddingCard = within(- screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),- );- expect(- withinInteractiveEmbeddingCard.getByText("Learn more"),- ).toBeInTheDocument();- });- });- });-});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.tsxdeleted file mode 100644index 7b172393171..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/EmbedModalContent.premium.unit.spec.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { screen, within } from "@testing-library/react";--import { createMockTokenFeatures } from "metabase-types/api/mocks";--import { type SetupOpts, setup } from "./setup";--function setupPremium(opts?: Partial<SetupOpts>) {- setup({- ...opts,- hasEnterprisePlugins: true,- tokenFeatures: createMockTokenFeatures({ embedding_simple: true }),- isHosted: true,- });-}--describe("EmbedModalContent", () => {- describe("Interactive Embedding", () => {- const INTERACTIVE_EMBEDDING_TITLE = "Embedded Analytics JS";-- describe("when Interactive Embedding is disabled", () => {- it("should mention Interactive Embedding and tell admin to enable Interactive Embedding in the setting", () => {- setupPremium();-- // The card is not clickable- expect(- screen.queryByRole("link", { name: INTERACTIVE_EMBEDDING_TITLE }),- ).not.toBeInTheDocument();-- // We show the link at the bottom of the card- const withinInteractiveEmbeddingCard = within(- screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),- );- expect(- withinInteractiveEmbeddingCard.getByText("Disabled."),- ).toBeInTheDocument();- expect(- withinInteractiveEmbeddingCard.getByRole("link", {- name: "Enable in admin settings",- }),- ).toHaveAttribute("href", "/admin/embedding/modular");- });- });-- describe("when Interactive Embedding is enabled", () => {- it("should mention Interactive Embedding and link to its admin settings page", () => {- setupPremium({- enableEmbedding: {- interactive: true,- },- });-- // We don't show the link at the bottom of the card- const withinInteractiveEmbeddingCard = within(- screen.getByRole("article", { name: INTERACTIVE_EMBEDDING_TITLE }),- );- expect(- withinInteractiveEmbeddingCard.queryByText("Disabled."),- ).not.toBeInTheDocument();- expect(- withinInteractiveEmbeddingCard.queryByRole("link", {- name: "Enabled in admin settings",- }),- ).not.toBeInTheDocument();- });- });- });-});diff --git a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsx b/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsxdeleted file mode 100644index 72bbf63f905..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/EmbedModalContent/tests/setup.tsx+++ /dev/null@@ -1,119 +0,0 @@-import { Route } from "react-router";--import { setupEnterprisePlugins } from "__support__/enterprise";-import { setupTokenStatusEndpoint } from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import { renderWithProviders } from "__support__/ui";-import type { EmbedResource } from "metabase/public/lib/types";-import type { TokenFeatures } from "metabase-types/api";-import {- createMockTokenFeatures,- createMockUser,-} from "metabase-types/api/mocks";--import type { EmbedModalContentProps } from "../EmbedModalContent";-import { EmbedModalContent } from "../EmbedModalContent";--type EnableEmbedding = {- static?: boolean;- interactive?: boolean;- sdk?: boolean;-};--export interface SetupOpts {- enableEmbedding?: EnableEmbedding;- props?: Partial<EmbedModalContentProps>;- hasEnterprisePlugins?: boolean;- tokenFeatures?: TokenFeatures;- isHosted?: boolean;-}--export function setup(- {- enableEmbedding: {- static: enableEmbeddingStatic = false,- interactive: enableEmbeddingInteractive = false,- sdk: enableEmbeddingSdk = false,- } = {- static: false,- interactive: false,- sdk: false,- },- props: {- embedType = null,- resource = {} as EmbedResource,- resourceType = "dashboard",- resourceParameters = [],- goToNextStep = jest.fn(),- getPublicUrl = jest.fn((_resource) => "some URL"),- onUpdateEmbeddingParams = jest.fn(),- onUpdateEnableEmbedding = jest.fn(),- onCreatePublicLink = jest.fn(),- onDeletePublicLink = jest.fn(),- onClose = jest.fn(),- } = {},- hasEnterprisePlugins,- tokenFeatures = createMockTokenFeatures(),- isHosted,- }: SetupOpts = {- props: {},- },-) {- const settings = mockSettings({- "token-features": tokenFeatures,- "enable-embedding-static": enableEmbeddingStatic,- "enable-embedding-interactive": enableEmbeddingInteractive,- "enable-embedding-simple": enableEmbeddingInteractive,- "enable-embedding-sdk": enableEmbeddingSdk,- "embedding-secret-key": "my_super_secret_key",- "is-hosted?": isHosted ?? false,- });-- if (hasEnterprisePlugins) {- setupEnterprisePlugins();- }-- setupTokenStatusEndpoint({- valid: true,- });-- const view = renderWithProviders(- <Route- path="*"- component={() => {- return (- <EmbedModalContent- embedType={embedType}- goToNextStep={goToNextStep}- resource={resource}- resourceType={resourceType}- resourceParameters={resourceParameters}- getPublicUrl={getPublicUrl}- onUpdateEmbeddingParams={onUpdateEmbeddingParams}- onUpdateEnableEmbedding={onUpdateEnableEmbedding}- onCreatePublicLink={onCreatePublicLink}- onDeletePublicLink={onDeletePublicLink}- onClose={onClose}- />- );- }}- />,- {- storeInitialState: {- currentUser: createMockUser({ is_superuser: true }),- settings,- },- withRouter: true,- },- );-- return {- ...view,- goToNextStep,- getPublicUrl,- onUpdateEmbeddingParams,- onUpdateEnableEmbedding,- onCreatePublicLink,- onDeletePublicLink,- };-}diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/PublicEmbedCard.tsx b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/PublicEmbedCard.tsxdeleted file mode 100644index fb258889b45..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/PublicEmbedCard.tsx+++ /dev/null@@ -1,86 +0,0 @@-import { useState } from "react";-import { useAsync } from "react-use";-import { jt, t } from "ttag";--import { PublicLinkCopyPanel } from "metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel";-import { trackPublicEmbedCodeCopied } from "metabase/public/lib/analytics";-import {- Button,- Center,- Group,- Loader,- Popover,- Stack,- Text,-} from "metabase/ui";--export const PublicEmbedCard = ({- publicEmbedCode,- createPublicLink,- deletePublicLink,- resourceType,-}: any) => {- const [isOpen, setIsOpen] = useState(false);-- const { loading } = useAsync(async () => {- if (isOpen && !publicEmbedCode) {- return createPublicLink();- }- return null;- }, [publicEmbedCode, isOpen]);-- return (- <Group gap="xs">- <Text>- {jt`Use ${(- <Text component="span" fw="bold" key="bold">- {t`public embedding`}- </Text>- )} to add a publicly-visible iframe embed to your web page or blog- post.`}- </Text>- <Popover- position="bottom"- withArrow- shadow="md"- opened={isOpen}- // onClose is still needed to close the popover when the user clicks outside of it- // even if it we're using Popover as controlled- onClose={() => setIsOpen(false)}- >- <Popover.Target>- <Button- variant="subtle"- p={0}- onClick={() => setIsOpen((value) => !value)}- >{t`Get embedding code`}</Button>- </Popover.Target>- <Popover.Dropdown>- <Stack p="lg" w="28rem" mih="7.5rem">- {loading ? (- <Center>- <Loader />- </Center>- ) : (- <PublicLinkCopyPanel- url={publicEmbedCode}- onRemoveLink={(e) => {- setIsOpen(false);- deletePublicLink(e);- }}- removeButtonLabel={t`Remove public link`}- removeTooltipLabel={t`Affects both public link and embed URL for this dashboard`}- onCopy={() =>- trackPublicEmbedCodeCopied({- artifact: resourceType,- source: "public-embed",- })- }- />- )}- </Stack>- </Popover.Dropdown>- </Popover>- </Group>- );-};diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsx b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsxdeleted file mode 100644index 11badd8dac5..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.tsx+++ /dev/null@@ -1,293 +0,0 @@-import cx from "classnames";-import type React from "react";-import { useState } from "react";-import { t } from "ttag";--import {- UpsellEmbedJsCta,- useUpsellEmbedJsCta,-} from "metabase/admin/upsells/UpsellEmbedJsCta";-import { UpsellGem } from "metabase/admin/upsells/components";-import ExternalLink from "metabase/common/components/ExternalLink";-import Link from "metabase/common/components/Link";-import {- useDocsUrl,- useHasTokenFeature,- useSetting,-} from "metabase/common/hooks";-import CS from "metabase/css/core/index.css";-import type { ExportFormatType } from "metabase/embedding/components/PublicLinkPopover/types";-import { useSelector } from "metabase/lib/redux";-import { trackPublicLinkRemoved } from "metabase/public/lib/analytics";-import { getPublicEmbedHTML } from "metabase/public/lib/code";-import type {- EmbedResource,- EmbedResourceType,-} from "metabase/public/lib/types";-import { getSetting } from "metabase/selectors/settings";-import { Group, Icon, List, Stack, Text, UnstyledButton } from "metabase/ui";--import { PublicEmbedCard } from "./PublicEmbedCard";-import { SharingPaneButton } from "./SharingPaneButton/SharingPaneButton";-import EmbeddedJsIllustration from "./illustrations/embedded-analytics-js.svg?component";-import SdkIllustration from "./illustrations/embedding-sdk.svg?component";-import StaticEmbeddingIllustration from "./illustrations/static-embedding.svg?component";--interface SelectEmbedTypePaneProps {- resource: EmbedResource;- resourceType: EmbedResourceType;- onCreatePublicLink: () => void;- onDeletePublicLink: () => void;- getPublicUrl: (publicUuid: string, extension?: ExportFormatType) => string;- goToNextStep: () => void;- closeModal: () => void;-}--export function SelectEmbedTypePane({- resource,- resourceType,- onCreatePublicLink,- onDeletePublicLink,- getPublicUrl,- goToNextStep,- closeModal,-}: SelectEmbedTypePaneProps) {- const { url } = useUpsellEmbedJsCta({ resource, resourceType, closeModal });- const hasPublicLink = resource.public_uuid != null;-- const utmTags = {- utm_content: "embed-modal",- };-- // eslint-disable-next-line no-unconditional-metabase-links-render -- only visible to admins- const { url: embeddingUrl } = useDocsUrl("embedding/introduction", {- anchor: "comparison-of-embedding-types",- utm: utmTags,- });-- // eslint-disable-next-line no-unconditional-metabase-links-render -- only visible to admins- const { url: sdkDocsUrl } = useDocsUrl("embedding/sdk/introduction", {- utm: utmTags,- });-- const isPublicSharingEnabled = useSelector((state) =>- getSetting(state, "enable-public-sharing"),- );-- const [isLoadingLink, setIsLoadingLink] = useState(false);-- const publicEmbedCode =- resource.public_uuid &&- getPublicEmbedHTML(getPublicUrl(resource.public_uuid));-- const createPublicLink = async () => {- if (!isLoadingLink && !hasPublicLink) {- setIsLoadingLink(true);- await onCreatePublicLink();- setIsLoadingLink(false);- }- };-- const deletePublicLink = async () => {- if (!isLoadingLink && hasPublicLink) {- setIsLoadingLink(true);-- trackPublicLinkRemoved({- artifact: resourceType,- source: "public-embed",- });-- await onDeletePublicLink();- setIsLoadingLink(false);- }- };-- const isEmbedJsAvailable = useHasTokenFeature("embedding_simple");- const isEmbeddingSdkAvailable = useHasTokenFeature("embedding_sdk");- const isStaticEmbeddingEnabled = useSetting("enable-embedding-static");- const isEmbedJsEnabled = useSetting("enable-embedding-simple");- const isEmbeddingSdkEnabled = useSetting("enable-embedding-sdk");-- return (- <Stack- display="inline-flex"- p="lg"- gap="lg"- data-testid="sharing-pane-container"- align="stretch"- >- <Group gap="lg" maw="100%" align="stretch">- {/* Static Embedding */}- <SharingPaneButton- title={t`Static embedding`}- illustration={<StaticEmbeddingIllustration />}- onClick={isStaticEmbeddingEnabled ? goToNextStep : undefined}- isDisabled={!isStaticEmbeddingEnabled}- disabledLink="/admin/embedding/static"- >- <List>- <List.Item>{t`Embedded, signed charts in iframes.`}</List.Item>- <List.Item>{t`No query builder or row-level data access.`}</List.Item>- <List.Item>{t`Data restriction with locked parameters.`}</List.Item>- </List>- </SharingPaneButton>-- {/* Embedded Analytics JS: render either upsell or embed flow link */}- <MaybeLinkEmbedJs- resource={resource}- resourceType={resourceType}- shouldRenderLink={!isEmbedJsAvailable || isEmbedJsEnabled}- closeModal={closeModal}- >- <SharingPaneButton- title={t`Embedded Analytics JS`}- badge={!isEmbedJsAvailable && <UpsellGem />}- illustration={<EmbeddedJsIllustration />}- isDisabled={isEmbedJsAvailable && !isEmbedJsEnabled}- disabledLink="/admin/embedding/modular"- actionHint={- !isEmbedJsAvailable ? (- <UpsellEmbedJsCta- resource={resource}- resourceType={resourceType}- closeModal={closeModal}- />- ) : undefined- }- >- <List>- <List.Item>{t`A simple way to embed using plain JavaScript`}</List.Item>- <List.Item>{t`Embed static or interactive dashboards and charts with drill-down, the query builder or let people browse and manage collections.`}</List.Item>- <List.Item>- {t`Advanced customizations for styling.`} <br />{" "}- {!isEmbedJsAvailable && <LearnMore url={url} />}- </List.Item>- </List>- </SharingPaneButton>- </MaybeLinkEmbedJs>-- {/* SDK for React */}- <ExternalLink href={sdkDocsUrl} className={CS.noDecoration}>- <SharingPaneButton- title={t`SDK for React`}- badge={!isEmbeddingSdkAvailable && <UpsellGem />}- illustration={<SdkIllustration />}- isDisabled={!isEmbeddingSdkEnabled}- disabledLink={"/admin/embedding/modular"}- actionHint={- <Group gap="xs">- <Text c="brand" fw="bold">- {t`Go to quick start`}- </Text>-- <Icon name="external" c="brand" aria-hidden />- </Group>- }- >- <List>- {/* eslint-disable-next-line no-literal-metabase-strings -- visible only to admin */}- <List.Item>{t`Embed Metabase components with React (like standalone charts, dashboards, the query builder, and more)`}</List.Item>- <List.Item>{t`Manage access and interactivity per component`}</List.Item>- <List.Item>{t`Advanced customization options for styling`}</List.Item>- </List>- </SharingPaneButton>- </ExternalLink>- </Group>-- <Group justify="space-between">- {/* PUBLIC EMBEDDING */}- {isPublicSharingEnabled ? (- <PublicEmbedCard- publicEmbedCode={publicEmbedCode}- createPublicLink={createPublicLink}- deletePublicLink={deletePublicLink}- resourceType={resourceType}- />- ) : (- <Text>- {t`Public embeds and links are disabled.`}{" "}- <Link- variant="brand"- to="/admin/settings/public-sharing"- >{t`Settings`}</Link>- </Text>- )}- <ExternalLink- className={cx(CS.link, CS.textBold)}- style={{ display: "flex", alignItems: "center", gap: 4 }}- href={embeddingUrl}- >- {t`Compare options`} <Icon name="share" aria-hidden />- </ExternalLink>- </Group>- </Stack>- );-}--function LearnMore({ url }: { url: string | undefined }) {- if (!url) {- return null;- }-- return (- <ExternalLink- href={url}- style={{ fontWeight: "bold" }}- >{t`Learn more`}</ExternalLink>- );-}--function MaybeLinkEmbedJs({- resource,- resourceType,- shouldRenderLink,- closeModal,- ...props-}: {- children: React.ReactNode;- resource: EmbedResource;- resourceType: EmbedResourceType;- shouldRenderLink?: boolean;- closeModal: () => void;-}) {- const { openEmbedFlow, url, triggerUpsellFlow } = useUpsellEmbedJsCta({- resource,- resourceType,- closeModal,- });-- if (!shouldRenderLink) {- return props.children;- }-- if (openEmbedFlow || triggerUpsellFlow) {- return (- <UnstyledButton- onClick={() => {- if (triggerUpsellFlow) {- triggerUpsellFlow();- } else if (openEmbedFlow) {- openEmbedFlow();- }- }}- type="button"- aria-label={t`Embedded Analytics JS`}- >- {props.children}- </UnstyledButton>- );- }-- if (url) {- return (- <ExternalLink- {...props}- href={url}- target="_blank"- 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.tsxdeleted file mode 100644index 1f3406e9ec0..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SelectEmbedTypePane.unit.spec.tsx+++ /dev/null@@ -1,181 +0,0 @@-import userEvent from "@testing-library/user-event";-import { Route } from "react-router";--import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen } from "__support__/ui";-import { checkNotNull } from "metabase/lib/types";-import { createMockDashboard, createMockUser } from "metabase-types/api/mocks";-import { createMockState } from "metabase-types/store/mocks";--import { SelectEmbedTypePane } from "./SelectEmbedTypePane";--const setup = ({- isAdmin = false,- hasPublicLink = false,- isResourcePublished = false,- isStaticEmbeddingEnabled = false,- isPublicSharingEnabled = false,-}: {- isAdmin?: boolean;- hasPublicLink?: boolean;- isResourcePublished?: boolean;- isStaticEmbeddingEnabled?: boolean;- isPublicSharingEnabled?: boolean;-} = {}) => {- const TEST_DASHBOARD = createMockDashboard({- public_uuid: hasPublicLink ? "mock-uuid" : undefined,- enable_embedding: isResourcePublished,- });-- const onCreatePublicLink = jest.fn();- const onDeletePublicLink = jest.fn();- const getPublicUrl = jest.fn((uuid) => uuid);- const goToNextStep = jest.fn();- const closeModal = jest.fn();-- const { history } = renderWithProviders(- <Route- path="*"- component={() => (- <SelectEmbedTypePane- resource={TEST_DASHBOARD}- resourceType="dashboard"- onCreatePublicLink={onCreatePublicLink}- onDeletePublicLink={onDeletePublicLink}- getPublicUrl={getPublicUrl}- goToNextStep={goToNextStep}- closeModal={closeModal}- />- )}- ></Route>,- {- storeInitialState: createMockState({- currentUser: createMockUser({ is_superuser: isAdmin }),- settings: mockSettings({- "enable-public-sharing": isPublicSharingEnabled,- "enable-embedding-static": isStaticEmbeddingEnabled,- }),- }),- withRouter: true,- },- );-- return {- goToNextStep,- onCreatePublicLink,- onDeletePublicLink,- getPublicUrl,- history: checkNotNull(history),- };-};--describe("SelectEmbedTypePane", () => {- describe("static embed button", () => {- describe("when the resource is published", () => {- it("should call `goToNextStep` with `application` when the static embedding option is clicked", async () => {- const { goToNextStep } = setup({- isResourcePublished: true,- isStaticEmbeddingEnabled: true,- });-- await userEvent.click(screen.getByText("Static embedding"));-- expect(goToNextStep).toHaveBeenCalled();- });- });-- describe("when the resource is not published", () => {- it("should call `goToNextStep` with `application` when the static embedding option is clicked", async () => {- const { goToNextStep } = setup({- isResourcePublished: false,- isStaticEmbeddingEnabled: true,- });-- await userEvent.click(screen.getByText("Static embedding"));-- expect(goToNextStep).toHaveBeenCalled();- });- });- });-- describe("public embed button", () => {- describe("when public sharing is disabled", () => {- it("should redirect to settings when public sharing is disabled and `Settings` is clicked", async () => {- const { history } = setup({- isPublicSharingEnabled: false,- });-- await userEvent.click(screen.getByRole("link", { name: "Settings" }));-- expect(history.getCurrentLocation().pathname).toEqual(- "/admin/settings/public-sharing",- );- });- });-- describe("when a public link exists", () => {- it("should render iframe link, copy button, `Copy snippet` description, and `Affects public url and link` tooltip", async () => {- setup({ hasPublicLink: true, isPublicSharingEnabled: true });-- await userEvent.click(screen.getByText("Get embedding code"));-- expect(screen.getByTestId("public-link-input")).toHaveDisplayValue(- /<iframe(\s+)src="mock-uuid".*<\/iframe>/s,- );-- expect(screen.getByTestId("copy-button")).toBeInTheDocument();- expect(screen.getByText("Remove public link")).toBeInTheDocument();-- await userEvent.hover(screen.getByText("Remove public link"));- expect(- await screen.findByText(- "Affects both public link and embed URL for this dashboard",- ),- ).toBeInTheDocument();- });-- it("should call `onDeletePublicLink` when `Remove public link` is clicked", async () => {- const { onDeletePublicLink } = setup({- hasPublicLink: true,- isPublicSharingEnabled: true,- });-- await userEvent.click(screen.getByText("Get embedding code"));-- await userEvent.click(screen.getByText("Remove public link"));-- expect(onDeletePublicLink).toHaveBeenCalled();- });- });-- describe("when a public link doesn't exist", () => {- it("should render `Get embedding code`", () => {- setup({ hasPublicLink: false, isPublicSharingEnabled: true });-- expect(screen.getByText("Get embedding code")).toBeInTheDocument();- });-- it("should call `onCreatePublicLink` when `Get embedding code` is clicked", async () => {- const { onCreatePublicLink } = setup({ isPublicSharingEnabled: true });-- await userEvent.click(- screen.getByRole("button", { name: "Get embedding code" }),- );-- expect(onCreatePublicLink).toHaveBeenCalled();- });- });- });-- describe('"Compare options" button', () => {- it("should open in a new tab", () => {- setup();-- const compareOptionsButton = screen.getByRole("link", {- name: "Compare options",- });-- expect(compareOptionsButton).toHaveAttribute("target", "_blank");- });- });-});diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SharingPaneButton/SharingPaneButton.module.css b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SharingPaneButton/SharingPaneButton.module.cssdeleted file mode 100644index 3650e3af5c8..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SharingPaneButton/SharingPaneButton.module.css+++ /dev/null@@ -1,21 +0,0 @@-.Container:not([data-css-specificity-hack="🤷"]) {- cursor: pointer;- overflow: hidden;-- --external-link-icon-color: var(--mb-color-text-light);-- &:hover {- border-color: var(--mb-color-brand);- background-color: var(--mb-color-bg-light);-- --external-link-icon-color: var(--mb-color-brand);- }-}--.Disabled.Container:not([data-css-specificity-hack="🤷"]) {- --mb-color-text-primary: var(--mb-color-text-tertiary);-- cursor: not-allowed;- border-color: var(--mb-color-border);- background-color: var(--mb-color-bg-light);-}diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SharingPaneButton/SharingPaneButton.tsx b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SharingPaneButton/SharingPaneButton.tsxdeleted file mode 100644index 6a38b6db857..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/SharingPaneButton/SharingPaneButton.tsx+++ /dev/null@@ -1,88 +0,0 @@-import cx from "classnames";-import type { MouseEventHandler, ReactNode } from "react";-import { t } from "ttag";--import Link from "metabase/common/components/Link";-import { Box, Center, Group, Paper, Stack, Text, Title } from "metabase/ui";--import S from "./SharingPaneButton.module.css";--type SharingOptionProps = {- illustration: JSX.Element;- children: ReactNode;- title: string;- badge?: ReactNode;- onClick?: MouseEventHandler;- "data-testid"?: string;- isDisabled?: boolean;- disabledLink: string;- actionHint?: ReactNode;-};--export const SharingPaneButton = ({- illustration,- children,- title,- onClick,- badge,- "data-testid": dataTestId,- isDisabled,- disabledLink,- actionHint,-}: SharingOptionProps) => {- return (- <Paper- component="article"- className={cx(S.Container, { [S.Disabled]: isDisabled })}- p="lg"- pt="3.25rem"- withBorder- data-testid={dataTestId}- onClick={onClick}- mih="100%"- pos="relative"- w="22rem"- aria-label={title}- >- <Stack justify="space-between" h="100%">- <Stack pb={isDisabled ? "md" : undefined}>- <Center mb={32}>{illustration}</Center>- <Group align="center" gap="sm">- {badge}- <Title order={2}>{title}</Title>- </Group>- {children}- </Stack>-- {!isDisabled && (- <Stack mt="lg" w="100%" align="flex-end">- {actionHint ?? (- <Text c="brand" fw="bold">- {t`Embed`}- </Text>- )}- </Stack>- )}- </Stack>-- {isDisabled && (- <Box- pos="absolute"- bottom={0}- left={0}- w="100%"- bg="var(--mb-color-background-disabled)"- >- <Text c="text-secondary" fw="bold" ta="center" py="sm" lh="normal">- {t`Disabled.`}{" "}- <Box- component={Link}- c="brand"- to={disabledLink}- >{t`Enable in admin settings`}</Box>- </Text>- </Box>- )}- </Paper>- );-};diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/embedded-analytics-js.svg b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/embedded-analytics-js.svgdeleted file mode 100644index f327c79f0a3..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/embedded-analytics-js.svg+++ /dev/null@@ -1,16 +0,0 @@-<svg width="121" height="96" viewBox="0 0 121 96" fill="none" xmlns="http://www.w3.org/2000/svg">-<g clip-path="url(#clip0_17201_1069)">-<rect x="4.08398" y="3.75" width="112.5" height="88.5" rx="8.25" stroke="#EEEEEE" stroke-width="7.5"/>-<g clip-path="url(#clip1_17201_1069)">-<path d="M33.8695 68.9095C32.7775 68.9485 31.9195 68.656 31.2955 68.032C30.6715 67.408 30.3595 66.6085 30.3595 65.6335C30.3595 64.8925 30.5935 64.249 31.0615 63.703C31.4905 63.118 32.134 62.806 32.992 62.767L34.747 62.65C36.463 62.533 37.75 62.0065 38.608 61.0705C39.505 60.0955 39.9535 58.711 39.9535 56.917V30.592C39.9535 29.344 40.2655 28.408 40.8895 27.784C41.5525 27.121 42.4885 26.7895 43.6975 26.7895C44.9065 26.7895 45.823 27.121 46.447 27.784C47.11 28.408 47.4415 29.344 47.4415 30.592V56.8585C47.4415 59.3155 46.993 61.402 46.096 63.118C45.238 64.834 43.951 66.1795 42.235 67.1545C40.519 68.0905 38.3935 68.6365 35.8585 68.7925L33.8695 68.9095ZM70.6363 69.085C68.9203 69.085 67.2043 68.9485 65.4883 68.6755C63.7723 68.4415 62.1538 68.071 60.6328 67.564C59.1118 67.018 57.7468 66.355 56.5378 65.575C55.8358 65.107 55.3483 64.5415 55.0753 63.8785C54.8023 63.2155 54.7048 62.572 54.7828 61.948C54.8998 61.285 55.1533 60.7195 55.5433 60.2515C55.9723 59.7445 56.4988 59.4325 57.1228 59.3155C57.7468 59.1985 58.4293 59.374 59.1703 59.842C60.8863 60.856 62.6998 61.597 64.6108 62.065C66.5218 62.533 68.5303 62.767 70.6363 62.767C73.7173 62.767 75.9598 62.26 77.3638 61.246C78.7678 60.193 79.4698 58.8475 79.4698 57.2095C79.4698 55.8445 78.9628 54.772 77.9488 53.992C76.9738 53.212 75.2773 52.5685 72.8593 52.0615L66.4243 50.716C62.7193 49.936 59.9503 48.6295 58.1173 46.7965C56.3233 44.9245 55.4263 42.4675 55.4263 39.4255C55.4263 37.5145 55.8163 35.779 56.5963 34.219C57.3763 32.659 58.4683 31.3135 59.8723 30.1825C61.3153 29.0515 63.0118 28.1935 64.9618 27.6085C66.9508 26.9845 69.1348 26.6725 71.5138 26.6725C73.8538 26.6725 76.0768 26.965 78.1828 27.55C80.2888 28.135 82.1803 28.993 83.8573 30.124C84.4813 30.553 84.8908 31.0795 85.0858 31.7035C85.3198 32.3275 85.3783 32.9515 85.2613 33.5755C85.1443 34.1605 84.8713 34.6675 84.4423 35.0965C84.0133 35.5255 83.4673 35.779 82.8043 35.857C82.1803 35.935 81.4588 35.74 80.6398 35.272C79.1968 34.453 77.7343 33.868 76.2523 33.517C74.7703 33.166 73.1713 32.9905 71.4553 32.9905C69.6613 32.9905 68.1208 33.244 66.8338 33.751C65.5468 34.258 64.5523 34.9795 63.8503 35.9155C63.1873 36.8125 62.8558 37.885 62.8558 39.133C62.8558 40.537 63.3238 41.668 64.2598 42.526C65.1958 43.345 66.7948 43.9885 69.0568 44.4565L75.4333 45.802C79.2943 46.621 82.1608 47.908 84.0328 49.663C85.9438 51.418 86.8993 53.758 86.8993 56.683C86.8993 58.555 86.5093 60.2515 85.7293 61.7725C84.9883 63.2935 83.8963 64.6 82.4533 65.692C81.0493 66.784 79.3528 67.6225 77.3638 68.2075C75.3748 68.7925 73.1323 69.085 70.6363 69.085Z" fill="#C5C7D0"/>-</g>-</g>-<defs>-<clipPath id="clip0_17201_1069">-<rect width="120" height="96" fill="white" transform="translate(0.333984)"/>-</clipPath>-<clipPath id="clip1_17201_1069">-<rect width="72" height="72" fill="white" transform="translate(24.334 12)"/>-</clipPath>-</defs>-</svg>diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/embedding-sdk.svg b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/embedding-sdk.svgdeleted file mode 100644index 90603b02c8e..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/embedding-sdk.svg+++ /dev/null@@ -1,11 +0,0 @@-<svg width="121" height="96" fill="none" xmlns="http://www.w3.org/2000/svg">- <g clip-path="url(#a)">- <rect x="4.084" y="3.75" width="112.5" height="88.5" rx="8.25" stroke="#EEE" stroke-width="7.5"/>- <path d="M60.334 42.332c3.09 0 5.61 2.52 5.61 5.67 0 3-2.52 5.55-5.61 5.55-3.09 0-5.61-2.55-5.61-5.55 0-3.15 2.52-5.67 5.61-5.67Zm-13.89 29.67c1.89 1.14 6.03-.6 10.8-5.1a72.673 72.673 0 0 1-4.53-5.7 68.977 68.977 0 0 1-7.2-1.08c-1.53 6.42-.96 10.83.93 11.88Zm2.13-17.22-.87-1.53c-.33.87-.66 1.74-.87 2.58.81.18 1.71.33 2.64.48l-.9-1.53Zm19.62-2.28 2.43-4.5-2.43-4.5c-.9-1.59-1.86-3-2.73-4.41-1.62-.09-3.33-.09-5.13-.09-1.8 0-3.51 0-5.13.09-.87 1.41-1.83 2.82-2.73 4.41l-2.43 4.5 2.43 4.5c.9 1.59 1.86 3 2.73 4.41 1.62.09 3.33.09 5.13.09 1.8 0 3.51 0 5.13-.09.87-1.41 1.83-2.82 2.73-4.41Zm-7.86-20.16c-.57.66-1.17 1.35-1.77 2.16h3.54c-.6-.81-1.2-1.5-1.77-2.16Zm0 31.32c.57-.66 1.17-1.35 1.77-2.16h-3.54c.6.81 1.2 1.5 1.77 2.16Zm13.86-39.66c-1.86-1.14-6 .6-10.77 5.1 1.56 1.77 3.09 3.69 4.53 5.7 2.46.24 4.89.6 7.2 1.08 1.53-6.42.96-10.83-.96-11.88Zm-2.1 17.22.87 1.53c.33-.87.66-1.74.87-2.58-.81-.18-1.71-.33-2.64-.48l.9 1.53Zm4.35-21.15c4.41 2.52 4.89 9.15 3.03 16.89 7.62 2.25 13.11 5.97 13.11 11.04 0 5.07-5.49 8.79-13.11 11.04 1.86 7.74 1.38 14.37-3.03 16.89-4.38 2.52-10.35-.36-16.11-5.85-5.76 5.49-11.73 8.37-16.14 5.85-4.38-2.52-4.86-9.15-3-16.89-7.62-2.25-13.11-5.97-13.11-11.04 0-5.07 5.49-8.79 13.11-11.04-1.86-7.74-1.38-14.37 3-16.89 4.41-2.52 10.38.36 16.14 5.85 5.76-5.49 11.73-8.37 16.11-5.85Zm-.87 27.93c1.02 2.25 1.92 4.5 2.67 6.78 6.3-1.89 9.84-4.59 9.84-6.78 0-2.19-3.54-4.89-9.84-6.78-.75 2.28-1.65 4.53-2.67 6.78Zm-30.48 0c-1.02-2.25-1.92-4.5-2.67-6.78-6.3 1.89-9.84 4.59-9.84 6.78 0 2.19 3.54 4.89 9.84 6.78.75-2.28 1.65-4.53 2.67-6.78Zm27 6.78-.9 1.53c.93-.15 1.83-.3 2.64-.48-.21-.84-.54-1.71-.87-2.58l-.87 1.53Zm-8.67 12.12c4.77 4.5 8.91 6.24 10.77 5.1 1.92-1.05 2.49-5.46.96-11.88-2.31.48-4.74.84-7.2 1.08a72.673 72.673 0 0 1-4.53 5.7Zm-14.85-25.68.9-1.53c-.93.15-1.83.3-2.64.48.21.84.54 1.71.87 2.58l.87-1.53Zm8.67-12.12c-4.77-4.5-8.91-6.24-10.8-5.1-1.89 1.05-2.46 5.46-.93 11.88a69.03 69.03 0 0 1 7.2-1.08c1.44-2.01 2.97-3.93 4.53-5.7Z" fill="#C5C7D0"/>- </g>- <defs>- <clipPath id="a">- <path fill="#fff" d="M.334 0h120v96h-120z"/>- </clipPath>- </defs>-</svg>diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/interactive-embedding.svg b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/interactive-embedding.svgdeleted file mode 100644index 37e4fff8df8..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/interactive-embedding.svg+++ /dev/null@@ -1,11 +0,0 @@-<svg width="120" height="96" fill="none" xmlns="http://www.w3.org/2000/svg">- <g clip-path="url(#a)">- <rect x="3.75" y="3.75" width="112.5" height="88.5" rx="8.25" stroke="#F1F1F1" stroke-width="7.5"/>- <path d="M60.445 67.868c.61 0 1.055-.446 1.172-1.079C63.281 53.946 65.086 52 77.789 50.594c.656-.07 1.102-.562 1.102-1.172 0-.61-.446-1.078-1.102-1.172-12.703-1.406-14.508-3.351-16.172-16.195C61.5 31.422 61.055 31 60.445 31c-.61 0-1.054.422-1.148 1.055-1.664 12.844-3.492 14.789-16.172 16.195-.68.094-1.125.563-1.125 1.172 0 .61.445 1.102 1.125 1.172 12.656 1.664 14.414 3.375 16.172 16.195.094.633.539 1.079 1.148 1.079ZM90 34c.264 0 .457-.194.508-.468.722-5.574 1.505-6.418 7.014-7.029.285-.03.478-.244.478-.508 0-.265-.193-.468-.478-.509-5.51-.61-6.292-1.454-7.014-7.028-.05-.275-.244-.458-.508-.458-.265 0-.457.183-.498.458-.722 5.574-1.515 6.418-7.014 7.028-.295.041-.488.244-.488.509 0 .264.193.478.488.508 5.489.723 6.251 1.465 7.014 7.029.04.274.234.468.498.468ZM92 77c.198 0 .343-.145.381-.351.541-4.18 1.129-4.814 5.26-5.271a.383.383 0 0 0 .359-.382c0-.198-.145-.35-.359-.381-4.132-.458-4.719-1.091-5.26-5.272-.038-.206-.183-.343-.381-.343-.199 0-.343.137-.374.343-.54 4.18-1.136 4.814-5.26 5.272-.221.03-.366.183-.366.381 0 .199.145.359.366.382 4.117.541 4.689 1.098 5.26 5.27.031.207.176.352.374.352ZM28 39c.198 0 .343-.145.381-.351.541-4.18 1.128-4.814 5.26-5.271a.383.383 0 0 0 .359-.382c0-.199-.145-.35-.358-.381-4.133-.458-4.72-1.091-5.26-5.272-.039-.206-.184-.343-.382-.343-.199 0-.343.137-.374.343-.54 4.18-1.136 4.814-5.26 5.272-.221.03-.366.183-.366.381 0 .199.145.359.366.382 4.117.541 4.689 1.098 5.26 5.27.031.207.176.352.374.352Z" fill="#C5C7D0"/>- </g>- <defs>- <clipPath id="a">- <path fill="#fff" d="M0 0h120v96H0z"/>- </clipPath>- </defs>-</svg>diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/static-embedding.svg b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/static-embedding.svgdeleted file mode 100644index 7768bde3f30..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/illustrations/static-embedding.svg+++ /dev/null@@ -1,12 +0,0 @@-<svg width="120" height="96" fill="none" xmlns="http://www.w3.org/2000/svg">- <g clip-path="url(#a)">- <rect x="3.75" y="3.75" width="112.5" height="88.5" rx="8.25" stroke="#F1F1F1" stroke-width="7.5"/>- <path d="M42 57h27v27H48a6 6 0 0 1-6-6V57ZM75 57h30v21a6 6 0 0 1-6 6H75V57ZM42 36a6 6 0 0 1 6-6h51a6 6 0 0 1 6 6v15H42V36Z" fill="#D0D0D0"/>- <path d="M15 18a6 6 0 0 1 6-6h78a6 6 0 0 1 6 6v6H15v-6ZM15 30h18v54H21a6 6 0 0 1-6-6V30Z" fill="#F1F1F1"/>- </g>- <defs>- <clipPath id="a">- <path fill="#fff" d="M0 0h120v96H0z"/>- </clipPath>- </defs>-</svg>diff --git a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/index.ts b/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/index.tsdeleted file mode 100644index e3475519acb..00000000000--- a/frontend/src/metabase/public/components/EmbedModal/SelectEmbedTypePane/index.ts+++ /dev/null@@ -1 +0,0 @@-export { SelectEmbedTypePane } from "./SelectEmbedTypePane";diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/EmbedModalContentStatusBar.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/EmbedModalContentStatusBar.tsxindex bbe8e4de318..916e40b8108 100644--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/EmbedModalContentStatusBar.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/EmbedModalContentStatusBar.tsx@@ -3,12 +3,13 @@ import { t } from "ttag";import CS from "metabase/css/core/index.css";import type { EmbedResourceType } from "metabase/public/lib/types";-import { Button, Flex, Group, Paper, Text } from "metabase/ui";+import { Button, Flex, Group, Text } from "metabase/ui";interface EmbedModalContentStatusBarProps {isPublished: boolean;resourceType: EmbedResourceType;hasSettingsChanges: boolean;+ isFetching?: boolean;onDiscard: () => void;onUnpublish: () => Promise<void>;onSave: () => Promise<void>;@@ -18,6 +19,7 @@ export const EmbedModalContentStatusBar = ({isPublished,resourceType,hasSettingsChanges,+ isFetching,onDiscard,onUnpublish,onSave,@@ -26,54 +28,56 @@ export const EmbedModalContentStatusBar = ({const [isUnpublishing, setIsUnpublishing] = useState(false);return (- <Paper- withBorder- shadow="sm"- m="1.5rem 2rem"- p="0.75rem 1rem"- data-testid="embed-modal-content-status-bar"+ <Flex+ w="100%"+ justify="space-between"+ direction="row"+ align="center"+ gap="0.5rem">- <Flex w="100%" justify="space-between" align="center" gap="0.5rem">- <Text fw="bold">- {!isPublished- ? t`You will need to publish this ${resourceType} before you can embed it in another application.`- : hasSettingsChanges- ? t`You’ve made changes that need to be published before they will be reflected in your application embed.`- : t`This ${resourceType} is published and ready to be embedded.`}- </Text>+ <Text>+ {!isPublished+ ? t`You will need to publish this ${resourceType} before you can embed it in another application.`+ : hasSettingsChanges+ ? t`You’ve made changes that need to be published before they will be reflected in your application embed.`+ : t`This ${resourceType} is published and ready to be embedded.`}+ </Text>- <Group gap="1rem" className={CS.flexNoShrink}>- {isPublished &&- (hasSettingsChanges ? (- <Button onClick={onDiscard}>{t`Discard changes`}</Button>- ) : (- <Button- variant="subtle"- color="error"- loading={isUnpublishing}- onClick={() => {- setIsUnpublishing(true);- onUnpublish().finally(() => setIsUnpublishing(false));- }}- >{t`Unpublish`}</Button>- ))}-- {(!isPublished || hasSettingsChanges) && (+ <Group+ gap="1rem"+ className={CS.flexNoShrink}+ style={{ alignSelf: "flex-end", justifyContent: "flex-end" }}+ >+ {isPublished &&+ (hasSettingsChanges ? (+ <Button onClick={onDiscard}>{t`Discard changes`}</Button>+ ) : (<Button- variant="filled"- loading={isPublishing}+ variant="subtle"+ color="error"+ loading={isUnpublishing || isFetching}onClick={() => {- setIsPublishing(true);- onSave().finally(() => setIsPublishing(false));+ setIsUnpublishing(true);+ onUnpublish().finally(() => setIsUnpublishing(false));}}- >- {hasSettingsChanges && isPublished- ? t`Publish changes`- : t`Publish`}- </Button>- )}- </Group>- </Flex>- </Paper>+ >{t`Unpublish`}</Button>+ ))}++ {(!isPublished || hasSettingsChanges) && (+ <Button+ variant="filled"+ loading={isPublishing || isFetching}+ onClick={() => {+ setIsPublishing(true);+ onSave().finally(() => setIsPublishing(false));+ }}+ >+ {hasSettingsChanges && isPublished+ ? t`Publish changes`+ : t`Publish`}+ </Button>+ )}+ </Group>+ </Flex>);};diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/OverviewSettings.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/OverviewSettings.tsxindex 2dbf70ce3fa..f30f203a268 100644--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/OverviewSettings.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/OverviewSettings.tsx@@ -6,12 +6,13 @@ import { jt, t } from "ttag";import ExternalLink from "metabase/common/components/ExternalLink";import { useDocsUrl } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";+import { MoreServerSnippetExamplesLink } from "metabase/embedding/components/MoreServerSnippetExamplesLink/MoreServerSnippetExamplesLink";import { getEmbedClientCodeExampleOptions } from "metabase/public/lib/code";import type {EmbedResourceType,ServerCodeSampleConfig,} from "metabase/public/lib/types";-import { Box, Center, Stack, Text } from "metabase/ui";+import { Stack, Text } from "metabase/ui";import { ClientEmbedCodePane } from "./ClientEmbedCodePane";import { SettingsTabLayout } from "./StaticEmbedSetupPane.styled";@@ -92,18 +93,7 @@ export const OverviewSettings = ({onCopy={() => onClientCodeCopy(selectedClientCodeOptionId)}/>- <Box my="1rem">- <Center>- <h4>{jt`More ${(- <ExternalLink- key="examples"- href="https://github.com/metabase/embedding-reference-apps"- >- {t`examples on GitHub`}- </ExternalLink>- )}`}</h4>- </Center>- </Box>+ <MoreServerSnippetExamplesLink /></Stack>}/>diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/ParametersSettings.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/ParametersSettings.tsxindex 67727d8ad90..7c24e80c897 100644--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/ParametersSettings.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/ParametersSettings.tsx@@ -24,23 +24,44 @@ export interface ParametersSettingsProps {resourceType: EmbedResourceType;resourceParameters: EmbedResourceParameter[];+ withInitialValues: boolean;+embeddingParams: EmbeddingParameters;lockedParameters: EmbedResourceParameter[];parameterValues: EmbeddingParametersValues;onChangeEmbeddingParameters: (parameters: EmbeddingParameters) => void;- onChangeParameterValue: (id: string, value: string) => void;+ onChangeParameterValue: (data: {+ id: string;+ slug: string;+ value: string | null;+ }) => void;+ onRemoveParameterValue: (data: { id: string; slug: string }) => void;}export const ParametersSettings = ({resourceType,resourceParameters,+ withInitialValues,embeddingParams,lockedParameters,parameterValues,onChangeEmbeddingParameters,onChangeParameterValue,+ onRemoveParameterValue,}: ParametersSettingsProps): JSX.Element => {+ const valuePopulatedEditableParameters = useMemo(+ () =>+ getValuePopulatedParameters({+ parameters: resourceParameters,+ values: parameterValues,+ defaultRequired: true,+ }).filter((parameter) => {+ const visibility = embeddingParams[parameter.slug] || "disabled";+ return visibility === "enabled";+ }) as EmbedResourceParameterWithValue[],+ [resourceParameters, parameterValues, embeddingParams],+ );const valuePopulatedLockedParameters = useMemo(() =>getValuePopulatedParameters({@@ -63,41 +84,57 @@ export const ParametersSettings = ({<Stack gap="1rem"><Text>{t`Parameters are disabled by default, which also makes them hidden from end-users. Make them editable so that end-users can see and modify them. Make them locked so that they are hidden from end-users but you can set their values from your app.`}</Text>- {resourceParameters.map((parameter) => (- <div key={parameter.id} className={cx(CS.flex, CS.alignCenter)}>- <Icon name={getParameterIconName(parameter)} className={CS.mr2} />- <h3>- {parameter.name}- {parameter.required && (- <Text color="error" component="span">- *- </Text>- )}- </h3>- <Select- buttonProps={{- "aria-label": parameter.name,- }}- className={cx(CS.mlAuto, CS.bgWhite)}- value={embeddingParams[parameter.slug] || "disabled"}- onChange={(e: ChangeEvent<HTMLSelectElement>) =>- onChangeEmbeddingParameters({- ...embeddingParams,- [parameter.slug]: e.target- .value as EmbeddingParameterVisibility,- })- }- >- <Option- icon="close"- value="disabled"- disabled={parameter.required}- >{t`Disabled`}</Option>- <Option icon="pencil" value="enabled">{t`Editable`}</Option>- <Option icon="lock" value="locked">{t`Locked`}</Option>- </Select>- </div>- ))}+ {resourceParameters.map((parameter) => {+ const visibility = embeddingParams[parameter.slug] || "disabled";++ return (+ <div key={parameter.id} className={cx(CS.flex, CS.alignCenter)}>+ <Icon+ name={getParameterIconName(parameter)}+ className={CS.mr2}+ />+ <h3>+ {parameter.name}+ {parameter.required && (+ <Text color="error" component="span">+ *+ </Text>+ )}+ </h3>+ <Select+ buttonProps={{+ "aria-label": parameter.name,+ }}+ className={cx(CS.mlAuto, CS.bgWhite)}+ value={visibility}+ onChange={(e: ChangeEvent<HTMLSelectElement>) => {+ const nextVisibility = e.target+ .value as EmbeddingParameterVisibility;++ onChangeEmbeddingParameters({+ ...embeddingParams,+ [parameter.slug]: nextVisibility,+ });++ if (nextVisibility === "disabled") {+ onRemoveParameterValue({+ id: parameter.id,+ slug: parameter.slug,+ });+ }+ }}+ >+ <Option+ icon="close"+ value="disabled"+ disabled={parameter.required}+ >{t`Disabled`}</Option>+ <Option icon="lock" value="locked">{t`Locked`}</Option>+ <Option icon="pencil" value="enabled">{t`Editable`}</Option>+ </Select>+ </div>+ );+ })}{hasRequiredParameters && (<Text size="xm">@@ -124,13 +161,60 @@ export const ParametersSettings = ({parameter={parameter}parameters={valuePopulatedLockedParameters}setValue={(value: string) =>- onChangeParameterValue(parameter.id, value)+ onChangeParameterValue({+ id: parameter.id,+ slug: parameter.slug,+ value,+ })}setParameterValueToDefault={() => {- onChangeParameterValue(- parameter.id,- parameter.default as any,- );+ onChangeParameterValue({+ id: parameter.id,+ slug: parameter.slug,+ value: parameter.default as any,+ });+ }}+ enableParameterRequiredBehavior+ />+ ))}+ </Stack>+ </StaticEmbedSetupPaneSettingsContentSection>+ </>+ )}++ {withInitialValues && valuePopulatedEditableParameters.length > 0 && (+ <>+ <Divider my="2rem" />+ <StaticEmbedSetupPaneSettingsContentSection+ title={t`Set initial values for parameters`}+ >+ <Stack gap="1rem">+ {valuePopulatedEditableParameters.map((parameter) => (+ <StaticParameterWidget+ key={parameter.id}+ className={CS.m0}+ parameter={parameter}+ parameters={valuePopulatedEditableParameters}+ setValue={(value: string) => {+ if (value) {+ onChangeParameterValue({+ id: parameter.id,+ slug: parameter.slug,+ value,+ });+ } else {+ onRemoveParameterValue({+ id: parameter.id,+ slug: parameter.slug,+ });+ }+ }}+ setParameterValueToDefault={() => {+ onChangeParameterValue({+ id: parameter.id,+ slug: parameter.slug,+ value: parameter.default as any,+ });}}enableParameterRequiredBehavior/>diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/StaticEmbedSetupPane.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/StaticEmbedSetupPane.tsxindex b1d1aa407e7..040b4f073e5 100644--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/StaticEmbedSetupPane.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/StaticEmbedSetupPane.tsx@@ -2,33 +2,27 @@ import cx from "classnames";import { useMemo, useState } from "react";import { useAsync } from "react-use";import { t } from "ttag";-import _ from "underscore";import { useSetting } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";import { useSelector } from "metabase/lib/redux";import { checkNotNull } from "metabase/lib/types";-import {- trackStaticEmbedCodeCopied,- trackStaticEmbedDiscarded,- trackStaticEmbedPublished,- trackStaticEmbedUnpublished,-} from "metabase/public/lib/analytics";+import { getPreviewParamsBySlug } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-preview-params-by-slug";+import { getStaticEmbedSetupPublishHandlers } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-static-embed-setup-publish-handlers";+import { trackStaticEmbedCodeCopied } from "metabase/public/lib/analytics";import { getEmbedServerCodeExampleOptions } from "metabase/public/lib/code";import { getIframeQueryWithoutDefaults } from "metabase/public/lib/code-templates";import { getSignedPreviewUrlWithoutHash } from "metabase/public/lib/embed";import type {EmbedResource,EmbedResourceParameter,- EmbedResourceType,EmbeddingDisplayOptions,- EmbeddingParameterVisibility,EmbeddingParameters,EmbeddingParametersValues,+ GuestEmbedResourceType,} from "metabase/public/lib/types";import { getCanWhitelabel } from "metabase/selectors/whitelabel";-import { Stack, Tabs } from "metabase/ui";-import { getParameterValue } from "metabase-lib/v1/parameters/utils/parameter-values";+import { Paper, Stack, Tabs } from "metabase/ui";import { EmbedModalContentStatusBar } from "./EmbedModalContentStatusBar";import { LookAndFeelSettings } from "./LookAndFeelSettings";@@ -39,32 +33,19 @@ import { type PreviewBackgroundType, PreviewPane } from "./PreviewPane";import { ServerEmbedCodePane } from "./ServerEmbedCodePane";import { SettingsTabLayout } from "./StaticEmbedSetupPane.styled";import { getDefaultDisplayOptions } from "./config";+import { getDefaultEmbeddingParams } from "./lib/get-default-embedding-params";+import { getHasParamsChanged } from "./lib/get-has-params-changed";+import { getLockedPreviewParameters } from "./lib/get-locked-preview-parameters";import { EMBED_MODAL_TABS } from "./tabs";import type { ActivePreviewPane, EmbedCodePaneVariant } from "./types";-const countEmbeddingParameterOptions = (- embeddingParams: EmbeddingParameters,-): Record<EmbeddingParameterVisibility, number> =>- Object.values(embeddingParams).reduce(- (acc, value) => {- acc[value] += 1;- return acc;- },- { disabled: 0, locked: 0, enabled: 0 } as Record<- EmbeddingParameterVisibility,- number- >,- );-export interface StaticEmbedSetupPaneProps {resource: EmbedResource;- resourceType: EmbedResourceType;+ resourceType: GuestEmbedResourceType;resourceParameters: EmbedResourceParameter[];- onUpdateEnableEmbedding: (enableEmbedding: boolean) => void | Promise<void>;- onUpdateEmbeddingParams: (- embeddingParams: EmbeddingParameters,- ) => void | Promise<void>;+ onUpdateEnableEmbedding: (enableEmbedding: boolean) => void;+ onUpdateEmbeddingParams: (embeddingParams: EmbeddingParameters) => void;}export const StaticEmbedSetupPane = ({@@ -132,7 +113,7 @@ export const StaticEmbedSetupPane = ({({ id }) => id === selectedServerCodeOptionId,);- const hasSettingsChanges = getHasSettingsChanges({+ const hasParamsChanged = getHasParamsChanged({initialEmbeddingParams,embeddingParams,});@@ -161,36 +142,17 @@ export const StaticEmbedSetupPane = ({? iframeUrlWithoutHash + getIframeQueryWithoutDefaults(displayOptions): null;- const handleSave = async () => {- if (!resource.enable_embedding) {- await onUpdateEnableEmbedding(true);- }- await onUpdateEmbeddingParams(embeddingParams);- trackStaticEmbedPublished({- artifact: resourceType,+ const { handleSave, handleUnpublish, handleDiscard } =+ getStaticEmbedSetupPublishHandlers({resource,- isExampleDashboard: exampleDashboardId === resource.id,- params: countEmbeddingParameterOptions({- ...convertResourceParametersToEmbeddingParams(resourceParameters),- ...embeddingParams,- }),- });- };-- const handleUnpublish = async () => {- await onUpdateEnableEmbedding(false);- trackStaticEmbedUnpublished({- artifact: resourceType,- resource,- });- };-- const handleDiscard = () => {- setEmbeddingParams(getDefaultEmbeddingParams(resource, resourceParameters));- trackStaticEmbedDiscarded({- artifact: resourceType,+ resourceType,+ resourceParameters,+ onUpdateEnableEmbedding,+ onUpdateEmbeddingParams,+ embeddingParams,+ setEmbeddingParams,+ exampleDashboardId,});- };const getServerEmbedCodePane = (variant: EmbedCodePaneVariant) => {return (@@ -247,14 +209,22 @@ export const StaticEmbedSetupPane = ({return (<Stack gap={0}>- <EmbedModalContentStatusBar- resourceType={resourceType}- isPublished={resource.enable_embedding}- hasSettingsChanges={hasSettingsChanges}- onSave={handleSave}- onUnpublish={handleUnpublish}- onDiscard={handleDiscard}- />+ <Paper+ withBorder+ shadow="sm"+ m="1.5rem 2rem"+ p="0.75rem 1rem"+ data-testid="embed-modal-content-status-bar"+ >+ <EmbedModalContentStatusBar+ resourceType={resourceType}+ isPublished={resource.enable_embedding}+ hasSettingsChanges={hasParamsChanged}+ onSave={handleSave}+ onUnpublish={handleUnpublish}+ onDiscard={handleDiscard}+ />+ </Paper><TabsdefaultValue={EMBED_MODAL_TABS.Overview}@@ -305,16 +275,24 @@ export const StaticEmbedSetupPane = ({<ParametersSettingsresourceType={resourceType}resourceParameters={resourceParameters}+ withInitialValues={false}embeddingParams={embeddingParams}lockedParameters={lockedParameters}parameterValues={parameterValues}onChangeEmbeddingParameters={setEmbeddingParams}- onChangeParameterValue={(id: string, value: string) =>+ onChangeParameterValue={({ id, value }) =>setParameterValues((state) => ({...state,[id]: value,}))}+ onRemoveParameterValue={({ id }) =>+ setParameterValues((state) => {+ const nextState = { ...state };+ delete nextState[id];+ return nextState;+ })+ }/>}previewSlot={@@ -373,109 +351,6 @@ export const StaticEmbedSetupPane = ({);};-function getDefaultEmbeddingParams(- resource: EmbedResource,- resourceParameters: EmbedResourceParameter[],-): EmbeddingParameters {- const validSlugs = resourceParameters.map((param) => param.slug);- // We first pick only dashboard parameters with valid slugs- const defaultParams = _.pick(resource.embedding_params || {}, validSlugs);- // Then pick valid required dashboard parameters- const validRequiredParams = resourceParameters.filter(- (param) => param.slug && param.required,- );-- // And for each required parameter set its value to "enabled"- // (Editable) because this is the default for a required parameter.- // This is needed to save embedding_params when a user clicks- // "Publish" without changing parameter visibility.- return validRequiredParams.reduce((acc, param) => {- if (!acc[param.slug] || acc[param.slug] === "disabled") {- acc[param.slug] = "enabled";- }- return acc;- }, defaultParams);-}--function getPreviewParamsBySlug({- resourceParameters,- embeddingParams,- parameterValues,-}: {- resourceParameters: EmbedResourceParameter[];- embeddingParams: EmbeddingParameters;- parameterValues: EmbeddingParametersValues;-}) {- const lockedParameters = getLockedPreviewParameters(- resourceParameters,- embeddingParams,- );-- return Object.fromEntries(- lockedParameters.map((parameter) => {- const value = getParameterValue({- parameter,- values: parameterValues,- defaultRequired: true,- });- // metabase#47570- const valueWithDefaultLockedParameterValue = value === null ? [] : value;- return [parameter.slug, valueWithDefaultLockedParameterValue];- }),- );-}--function getLockedPreviewParameters(- resourceParameters: EmbedResourceParameter[],- embeddingParams: EmbeddingParameters,-) {- return resourceParameters.filter(- (parameter) => embeddingParams[parameter.slug] === "locked",- );-}--function getHasSettingsChanges({- initialEmbeddingParams,- embeddingParams,-}: {- initialEmbeddingParams: EmbeddingParameters;- embeddingParams: EmbeddingParameters;-}): boolean {- const nonDisabledInitialEmbeddingParams = getNonDisabledEmbeddingParams(- initialEmbeddingParams,- );- const nonDisabledEmbeddingParams =- getNonDisabledEmbeddingParams(embeddingParams);-- return !_.isEqual(- nonDisabledInitialEmbeddingParams,- nonDisabledEmbeddingParams,- );-}--function getNonDisabledEmbeddingParams(- embeddingParams: EmbeddingParameters,-): EmbeddingParameters {- return Object.keys(embeddingParams).reduce((result, key) => {- if (embeddingParams[key] !== "disabled") {- result[key] = embeddingParams[key];- }-- return result;- }, {} as EmbeddingParameters);-}--function convertResourceParametersToEmbeddingParams(- resourceParameters: EmbedResourceParameter[],-) {- const embeddingParams: EmbeddingParameters = {};- for (const parameter of resourceParameters) {- embeddingParams[parameter.slug] = "disabled";- }-- return embeddingParams;-}-function getBackgroundType(displayOptions: Pick<EmbeddingDisplayOptions, "background" | "theme">,): PreviewBackgroundType {diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-default-embedding-params.ts b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-default-embedding-params.tsnew file mode 100644index 00000000000..6313921b963--- /dev/null+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-default-embedding-params.ts@@ -0,0 +1,41 @@+import _ from "underscore";++import type {+ EmbedResource,+ EmbedResourceParameter,+ EmbeddingParameters,+} from "metabase/public/lib/types";++export function getDefaultEmbeddingParams(+ resource: EmbedResource,+ resourceParameters: EmbedResourceParameter[],+): EmbeddingParameters {+ const validSlugs = resourceParameters.map((param) => param.slug);+ const validSlugsAsDisabledParams = validSlugs.reduce((acc, slug) => {+ acc[slug] = "disabled";++ return acc;+ }, {} as EmbeddingParameters);++ const resourceEmbeddingParams = {+ ...validSlugsAsDisabledParams,+ ...(resource.embedding_params || {}),+ };+ // We first pick only dashboard parameters with valid slugs+ const defaultParams = _.pick(resourceEmbeddingParams, validSlugs);+ // Then pick valid required dashboard parameters+ const validRequiredParams = resourceParameters.filter(+ (param) => param.slug && param.required,+ );++ // And for each parameter set its value to "enabled"+ // (Editable) because this is the default for a required parameter.+ // This is needed to save embedding_params when a user clicks+ // "Publish" without changing parameter visibility.+ return validRequiredParams.reduce((acc, param) => {+ if (!acc[param.slug] || acc[param.slug] === "disabled") {+ acc[param.slug] = "enabled";+ }+ return acc;+ }, defaultParams);+}diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-has-params-changed.ts b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-has-params-changed.tsnew file mode 100644index 00000000000..d0f9e704f98--- /dev/null+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-has-params-changed.ts@@ -0,0 +1,34 @@+import _ from "underscore";++import type { EmbeddingParameters } from "metabase/public/lib/types";++function getNonDisabledEmbeddingParams(+ embeddingParams: EmbeddingParameters,+): EmbeddingParameters {+ return Object.keys(embeddingParams).reduce((result, key) => {+ if (embeddingParams[key] !== "disabled") {+ result[key] = embeddingParams[key];+ }++ return result;+ }, {} as EmbeddingParameters);+}++export function getHasParamsChanged({+ initialEmbeddingParams,+ embeddingParams,+}: {+ initialEmbeddingParams: EmbeddingParameters;+ embeddingParams: EmbeddingParameters;+}): boolean {+ const nonDisabledInitialEmbeddingParams = getNonDisabledEmbeddingParams(+ initialEmbeddingParams,+ );+ const nonDisabledEmbeddingParams =+ getNonDisabledEmbeddingParams(embeddingParams);++ return !_.isEqual(+ nonDisabledInitialEmbeddingParams,+ nonDisabledEmbeddingParams,+ );+}diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-locked-preview-parameters.ts b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-locked-preview-parameters.tsnew file mode 100644index 00000000000..77181399a6a--- /dev/null+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-locked-preview-parameters.ts@@ -0,0 +1,13 @@+import type {+ EmbedResourceParameter,+ EmbeddingParameters,+} from "metabase/public/lib/types";++export function getLockedPreviewParameters(+ resourceParameters: EmbedResourceParameter[],+ embeddingParams: EmbeddingParameters,+) {+ return resourceParameters.filter(+ (parameter) => embeddingParams[parameter.slug] === "locked",+ );+}diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-preview-params-by-slug.ts b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-preview-params-by-slug.tsnew file mode 100644index 00000000000..1ec54aa9f83--- /dev/null+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-preview-params-by-slug.ts@@ -0,0 +1,35 @@+import { getLockedPreviewParameters } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-locked-preview-parameters";+import type {+ EmbedResourceParameter,+ EmbeddingParameters,+ EmbeddingParametersValues,+} from "metabase/public/lib/types";+import { getParameterValue } from "metabase-lib/v1/parameters/utils/parameter-values";++export function getPreviewParamsBySlug({+ resourceParameters,+ embeddingParams,+ parameterValues,+}: {+ resourceParameters: EmbedResourceParameter[];+ embeddingParams: EmbeddingParameters;+ parameterValues: EmbeddingParametersValues;+}) {+ const lockedParameters = getLockedPreviewParameters(+ resourceParameters,+ embeddingParams,+ );++ return Object.fromEntries(+ lockedParameters.map((parameter) => {+ const value = getParameterValue({+ parameter,+ values: parameterValues,+ defaultRequired: true,+ });+ // metabase#47570+ const valueWithDefaultLockedParameterValue = value === null ? [] : value;+ return [parameter.slug, valueWithDefaultLockedParameterValue];+ }),+ );+}diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-static-embed-setup-publish-handlers.ts b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-static-embed-setup-publish-handlers.tsnew file mode 100644index 00000000000..9aced763de1--- /dev/null+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/lib/get-static-embed-setup-publish-handlers.ts@@ -0,0 +1,79 @@+import { countEmbeddingParameterOptions } from "metabase/embedding/lib/count-embedding-parameter-options";+import type { StaticEmbedSetupPaneProps } from "metabase/public/components/EmbedModal/StaticEmbedSetupPane/StaticEmbedSetupPane";+import {+ trackStaticEmbedDiscarded,+ trackStaticEmbedPublished,+ trackStaticEmbedUnpublished,+} from "metabase/public/lib/analytics";+import type {+ EmbedResourceParameter,+ EmbeddingParameters,+} from "metabase/public/lib/types";++import { getDefaultEmbeddingParams } from "./get-default-embedding-params";++function convertResourceParametersToEmbeddingParams(+ resourceParameters: EmbedResourceParameter[],+) {+ const embeddingParams: EmbeddingParameters = {};+ for (const parameter of resourceParameters) {+ embeddingParams[parameter.slug] = "disabled";+ }++ return embeddingParams;+}++export const getStaticEmbedSetupPublishHandlers = ({+ resource,+ resourceType,+ resourceParameters,+ onUpdateEnableEmbedding,+ onUpdateEmbeddingParams,++ embeddingParams,+ setEmbeddingParams,++ exampleDashboardId,+}: StaticEmbedSetupPaneProps & {+ embeddingParams: EmbeddingParameters;+ setEmbeddingParams: (embeddingParams: EmbeddingParameters) => void;++ exampleDashboardId: number | null;+}) => {+ const handleSave = async () => {+ if (!resource.enable_embedding) {+ await onUpdateEnableEmbedding(true);+ }+ await onUpdateEmbeddingParams(embeddingParams);+ trackStaticEmbedPublished({+ artifact: resourceType,+ resource,+ isExampleDashboard: exampleDashboardId === resource.id,+ params: countEmbeddingParameterOptions({+ ...convertResourceParametersToEmbeddingParams(resourceParameters),+ ...embeddingParams,+ }),+ });+ };++ const handleUnpublish = async () => {+ await onUpdateEnableEmbedding(false);+ trackStaticEmbedUnpublished({+ artifact: resourceType,+ resource,+ });+ };++ const handleDiscard = () => {+ setEmbeddingParams(getDefaultEmbeddingParams(resource, resourceParameters));+ trackStaticEmbedDiscarded({+ artifact: resourceType,+ });+ };++ return {+ handleSave,+ handleUnpublish,+ handleDiscard,+ };+};diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsxindex f6bebe4e0ff..b221cb2a95d 100644--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsx@@ -500,7 +500,7 @@ describe("Static Embed Setup phase", () => {expect(screen.getByText(- "The “Powered by Metabase” banner appears on all static embeds created with your current version. Upgrade to remove it (and customize a lot more)",+ "The “Powered by Metabase” banner appears on all guest embeds created with your current version. Upgrade to remove it (and customize a lot more)",),).toBeVisible();diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/enterprise.unit.spec.tsxindex 6fe03ecbe62..3f7cd9bf460 100644--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/tests/enterprise.unit.spec.tsx@@ -39,7 +39,7 @@ describe("Static Embed Setup phase - EE, no token", () => {expect(screen.getByText(- "The “Powered by Metabase” banner appears on all static embeds created with your current version. Upgrade to remove it (and customize a lot more)",+ "The “Powered by Metabase” banner appears on all guest embeds created with your current version. Upgrade to remove it (and customize a lot more)",),).toBeVisible();});diff --git a/frontend/src/metabase/public/components/EmbedModal/index.ts b/frontend/src/metabase/public/components/EmbedModal/index.tsindex f7bd68bc33c..c92323d595b 100644--- a/frontend/src/metabase/public/components/EmbedModal/index.ts+++ b/frontend/src/metabase/public/components/EmbedModal/index.ts@@ -1,2 +1 @@export { EmbedModal } from "./EmbedModal";-export { EmbedModalContent } from "./EmbedModalContent";diff --git a/frontend/src/metabase/public/lib/code-templates.ts b/frontend/src/metabase/public/lib/code-templates.tsindex f1a6dde79ca..ef58fbaafe5 100644--- a/frontend/src/metabase/public/lib/code-templates.ts+++ b/frontend/src/metabase/public/lib/code-templates.ts@@ -75,7 +75,7 @@ export const node = {const jwt = require("jsonwebtoken");-const METABASE_SITE_URL = ${JSON.stringify(siteUrl)};+${withIframeSnippet ? `const METABASE_SITE_URL = ${JSON.stringify(siteUrl)};` : ""}const METABASE_SECRET_KEY = ${JSON.stringify(secretKey)};const payload = {@@ -118,7 +118,7 @@ export const python = {import jwtimport time-METABASE_SITE_URL = ${JSON.stringify(siteUrl)}+${withIframeSnippet ? `METABASE_SITE_URL = ${JSON.stringify(siteUrl)}` : ""}METABASE_SECRET_KEY = ${JSON.stringify(secretKey)}payload = {@@ -160,7 +160,7 @@ export const ruby = {require 'jwt'-METABASE_SITE_URL = ${JSON.stringify(siteUrl)}+${withIframeSnippet ? `METABASE_SITE_URL = ${JSON.stringify(siteUrl)}` : ""}METABASE_SECRET_KEY = ${JSON.stringify(secretKey)}payload = {@@ -198,7 +198,7 @@ export const clojure = {}: CodeSampleParameters) =>`(require '[buddy.sign.jwt :as jwt])-(def metabase-site-url ${JSON.stringify(siteUrl)})+${withIframeSnippet ? `(def metabase-site-url ${JSON.stringify(siteUrl)})` : ""}(def metabase-secret-key ${JSON.stringify(secretKey)})(def payloaddiff --git a/frontend/src/metabase/public/lib/embed.ts b/frontend/src/metabase/public/lib/embed.tsindex 600f559b72f..dc5fd5a015a 100644--- a/frontend/src/metabase/public/lib/embed.ts+++ b/frontend/src/metabase/public/lib/embed.ts@@ -7,18 +7,26 @@ import type {EmbeddingParametersValues,} from "./types";+const DEFAULT_SIGNED_TOKEN_EXPIRATION_MINUTES = 10;+export async function getSignedToken(resourceType: EmbedResourceType,rawResourceId: EmbedResource["id"],params: EmbeddingParametersValues = {},secretKey: string,previewEmbeddingParams: EmbeddingParametersValues,+ expirationMinutes: number = DEFAULT_SIGNED_TOKEN_EXPIRATION_MINUTES,) {const normalizedResourceId = parseInt(rawResourceId as string, 10);++ const iat = Math.round(new Date().getTime() / 1000);+ const exp = iat + 60 * expirationMinutes;+const unsignedToken: Record<string, any> = {resource: { [resourceType]: normalizedResourceId },params: params,- iat: Math.round(new Date().getTime() / 1000),+ iat,+ exp,};// include the `embedding_params` settings inline in the token for previewsif (previewEmbeddingParams) {diff --git a/frontend/src/metabase/public/lib/types.ts b/frontend/src/metabase/public/lib/types.tsindex fa43031bbfc..0462958fd11 100644--- a/frontend/src/metabase/public/lib/types.ts+++ b/frontend/src/metabase/public/lib/types.ts@@ -7,13 +7,12 @@ import type {export type DisplayTheme = "light" | "night" | "transparent";-export type EmbedModalStep = "application" | "legalese" | null;-export type EmbedResource = (Card | Dashboard) & {embedding_params?: EmbeddingParameters | null;};export type EmbedResourceType = "dashboard" | "question" | "document";+export type GuestEmbedResourceType = "dashboard" | "question";export type EmbedResourceParameter = {id: string;@@ -29,7 +28,7 @@ export type EmbedResourceDownloadOptions = {results?: boolean;};-export type EmbeddingType = "static-legacy";+export type EmbeddingType = "static-legacy" | "guest-embed";export type EmbeddingParameterVisibility = "disabled" | "enabled" | "locked";diff --git a/frontend/src/metabase/query_builder/actions/core/card.ts b/frontend/src/metabase/query_builder/actions/core/card.tsindex 0b381760902..e6decd3adb0 100644--- a/frontend/src/metabase/query_builder/actions/core/card.ts+++ b/frontend/src/metabase/query_builder/actions/core/card.ts@@ -3,13 +3,19 @@ import type { Dispatch, GetState } from "metabase-types/store";// load a card either by ID or from a base64 serialization. if both are present then they are merged, which the serialized version taking precedenceexport async function loadCard(- cardId: string | number,+ {+ cardId,+ token,+ }: {+ cardId: string | number;+ token?: string | null;+ },{ dispatch, getState }: { dispatch: Dispatch; getState: GetState },) {try {await dispatch(Questions.actions.fetch(- { id: cardId },+ { id: token ?? cardId },{properties: ["id",diff --git a/frontend/src/metabase/query_builder/actions/core/core.ts b/frontend/src/metabase/query_builder/actions/core/core.tsindex 98921316bf9..de60b52370b 100644--- a/frontend/src/metabase/query_builder/actions/core/core.ts+++ b/frontend/src/metabase/query_builder/actions/core/core.ts@@ -116,7 +116,10 @@ export const setCardAndRun = (const originalCard = card.original_card_id? // If the original card id is present, dynamically load its information for showing lineage- await loadCard(card.original_card_id, { dispatch, getState })+ await loadCard(+ { cardId: card.original_card_id },+ { dispatch, getState },+ ): // Otherwise, use a current card as the original card if the card has been saved// This is needed for checking whether the card is in dirty state or notcard.id@@ -153,7 +156,7 @@ export const navigateToNewCardInsideQB = createThunkAction(// This is mainly a fallback for scenarios where a visualization legend is clicked inside QBdispatch(setCardAndRun(- await loadCard(nextCard.id, { dispatch, getState }),+ await loadCard({ cardId: nextCard.id }, { dispatch, getState }),{},),);diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.tsindex bfd41f0bdb2..40e963bacec 100644--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts@@ -117,11 +117,17 @@ export function deserializeCard(serializedCard: string) {}async function fetchAndPrepareSavedQuestionCards(- cardId: string | number,+ {+ cardId,+ token,+ }: {+ cardId: string | number;+ token?: string | null;+ },dispatch: Dispatch,getState: GetState,) {- const card = await loadCard(cardId, { dispatch, getState });+ const card = await loadCard({ cardId, token }, { dispatch, getState });const originalCard = { ...card };// for showing the "started from" lineage correctly when adding filters/breakouts and when going back and forth@@ -141,10 +147,13 @@ async function fetchAndPrepareAdHocQuestionCards(};}- const originalCard = await loadCard(deserializedCard.original_card_id, {- dispatch,- getState,- });+ const originalCard = await loadCard(+ { cardId: deserializedCard.original_card_id },+ {+ dispatch,+ getState,+ },+ );if (cardIsEquivalent(deserializedCard, originalCard)) {return {@@ -166,12 +175,14 @@ type ResolveCardsResult = {export async function resolveCards({cardId,+ token,deserializedCard,options,dispatch,getState,}: {cardId?: string | number;+ token?: string | null;deserializedCard?: Card;options: BlankQueryOptions;dispatch: Dispatch;@@ -185,7 +196,7 @@ export async function resolveCards({};}return cardId- ? fetchAndPrepareSavedQuestionCards(cardId, dispatch, getState)+ ? fetchAndPrepareSavedQuestionCards({ cardId, token }, dispatch, getState): fetchAndPrepareAdHocQuestionCards(deserializedCard as Card,dispatch,diff --git a/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx b/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsxindex 0aa74f3127d..68a1c32e4d8 100644--- a/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx+++ b/frontend/src/metabase/query_builder/components/QuestionEmbedWidget/QuestionEmbedWidget.tsx@@ -1,73 +1,50 @@import {- useCreateCardPublicLinkMutation,- useDeleteCardPublicLinkMutation,useUpdateCardEmbeddingParamsMutation,useUpdateCardEnableEmbeddingMutation,} from "metabase/api";-import type { ExportFormatType } from "metabase/embedding/components/PublicLinkPopover/types";import { STATIC_LEGACY_EMBEDDING_TYPE } from "metabase/embedding/constants";import { useSelector } from "metabase/lib/redux";-import { publicQuestion } from "metabase/lib/urls";-import {- EmbedModal,- EmbedModalContent,-} from "metabase/public/components/EmbedModal";+import { EmbedModal } from "metabase/public/components/EmbedModal";import { getMetadata } from "metabase/selectors/metadata";import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";import type { Card } from "metabase-types/api";type QuestionEmbedWidgetProps = {- className?: string;card: Card;+ onBack?: () => void;onClose: () => void;};export const QuestionEmbedWidget = (props: QuestionEmbedWidgetProps) => {- const { className, card, onClose } = props;+ const { card, onBack, onClose } = props;const metadata = useSelector(getMetadata);const [updateEnableEmbedding] = useUpdateCardEnableEmbeddingMutation();const [updateEmbeddingParams] = useUpdateCardEmbeddingParamsMutation();- const [createPublicQuestionLink] = useCreateCardPublicLinkMutation();- const [deletePublicQuestionLink] = useDeleteCardPublicLinkMutation();-- const getPublicQuestionUrl = (- publicUuid: string,- extension?: ExportFormatType,- ) => publicQuestion({ uuid: publicUuid, type: extension });return (- <EmbedModal onClose={onClose}>- {({ embedType, goToNextStep }) => (- <EmbedModalContent- embedType={embedType}- goToNextStep={goToNextStep}- className={className}- resource={card}- resourceType="question"- resourceParameters={getCardUiParameters(card, metadata)}- onCreatePublicLink={() => createPublicQuestionLink({ id: card.id })}- onDeletePublicLink={() => deletePublicQuestionLink({ id: card.id })}- onUpdateEnableEmbedding={(enable_embedding) =>- updateEnableEmbedding({- id: card.id,- enable_embedding,- embedding_type: enable_embedding- ? STATIC_LEGACY_EMBEDDING_TYPE- : null,- })- }- onUpdateEmbeddingParams={(embedding_params) =>- updateEmbeddingParams({- id: card.id,- embedding_params,- embedding_type: STATIC_LEGACY_EMBEDDING_TYPE,- })- }- getPublicUrl={getPublicQuestionUrl}- onClose={onClose}- />- )}- </EmbedModal>+ <EmbedModal+ resource={card}+ resourceType="question"+ resourceParameters={getCardUiParameters(card, metadata)}+ onUpdateEnableEmbedding={(enable_embedding) =>+ updateEnableEmbedding({+ id: card.id,+ enable_embedding,+ embedding_type: enable_embedding+ ? STATIC_LEGACY_EMBEDDING_TYPE+ : null,+ })+ }+ onUpdateEmbeddingParams={(embedding_params) =>+ updateEmbeddingParams({+ id: card.id,+ embedding_params,+ embedding_type: STATIC_LEGACY_EMBEDDING_TYPE,+ })+ }+ onBack={onBack}+ onClose={onClose}+ />);};diff --git a/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsx b/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsxindex 66c01da3e96..008f7ccb4a4 100644--- a/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsx+++ b/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsx@@ -16,6 +16,7 @@ interface ResponsiveParametersListProps {parametersList?: string;};cardId?: CardId;+ token?: string | null;dashboardId?: DashboardId;parameters: Parameter[];setParameterValue: (parameterId: string, value: string) => void;@@ -28,6 +29,7 @@ interface ResponsiveParametersListProps {export const ResponsiveParametersList = ({classNames,cardId,+ token,dashboardId,parameters,setParameterValue,@@ -99,6 +101,7 @@ export const ResponsiveParametersList = ({)}cardId={cardId}dashboardId={dashboardId}+ token={token}parameters={parameters}setParameterValue={setParameterValue}setParameterIndex={setParameterIndex}diff --git a/frontend/src/metabase/query_builder/components/SyncedParametersList.tsx b/frontend/src/metabase/query_builder/components/SyncedParametersList.tsxindex 542cf90076b..b97a7159732 100644--- a/frontend/src/metabase/query_builder/components/SyncedParametersList.tsx+++ b/frontend/src/metabase/query_builder/components/SyncedParametersList.tsx@@ -15,6 +15,7 @@ export const SyncedParametersList = ({editingParameter,cardId,dashboardId,+ token,className,hideParameters,@@ -46,6 +47,7 @@ export const SyncedParametersList = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}+ token={token}editingParameter={editingParameter}isFullscreen={isFullscreen}isSortable={isSortable}diff --git a/frontend/src/metabase/questions/actions.ts b/frontend/src/metabase/questions/actions.tsindex 076ff885b88..7f0cd673d2c 100644--- a/frontend/src/metabase/questions/actions.ts+++ b/frontend/src/metabase/questions/actions.ts@@ -15,17 +15,21 @@ export const loadMetadataForTable =};export const loadMetadataForCard =- (card: Card | UnsavedCard) => async (dispatch: Dispatch) => {+ (card: Card | UnsavedCard, { token }: { token?: string | null } = {}) =>+ async (dispatch: Dispatch) => {if (isSavedCard(card)) {return entityCompatibleQuery(- card.id,+ token ?? card.id,dispatch,cardApi.endpoints.getCardQueryMetadata,{ forceRefetch: false },);} else if (card.dataset_query.database != null) {return entityCompatibleQuery(- card.dataset_query,+ {+ ...card.dataset_query,+ ...(!!token && { token }),+ },dispatch,datasetApi.endpoints.getAdhocQueryMetadata,{ forceRefetch: false },diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.jsindex d4c14908746..43aa8d66287 100644--- a/frontend/src/metabase/services.js+++ b/frontend/src/metabase/services.js@@ -8,9 +8,10 @@ import { normalizeParameters } from "metabase-lib/v1/parameters/utils/parameter-import { isNative } from "metabase-lib/v1/queries/utils/card";import { getPivotOptions } from "metabase-lib/v1/queries/utils/pivot";-const publicBase = "/api/public";+export const internalBase = "/api";+export const publicBase = "/api/public";// use different endpoints for embed previews-const embedBase = IS_EMBED_PREVIEW ? "/api/preview_embed" : "/api/embed";+export const embedBase = IS_EMBED_PREVIEW ? "/api/preview_embed" : "/api/embed";export const ActivityApi = {most_recently_viewed_dashboard: GET(@@ -90,6 +91,7 @@ export async function runQuestionQuery({cancelDeferred,isDirty = false,+ token,ignoreCache = false,collectionPreview = false,// Ability to override or add extra query params to the request, used by Embedding SDK@@ -106,7 +108,7 @@ export async function runQuestionQuery(const { dashboardId, dashcardId } = question.getDashboardProps();const queryParams = {- cardId: question.id(),+ ...(token ? { token } : { cardId: question.id() }),dashboardId,dashcardId,ignore_cache: ignoreCache,@@ -368,7 +370,7 @@ function setCardEndpoints({ base, encodedUuid, encodedToken }) {const prefix = `${base}/card/${encodedUuid ?? encodedToken}`;// RTK query- PLUGIN_API.getRemappedCardParameterValueUrl = (_dashboardId, parameterId) =>+ PLUGIN_API.getRemappedCardParameterValueUrl = (_cardId, parameterId) =>`${prefix}/params/${encodeURIComponent(parameterId)}/remapping`;// legacy APIdiff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/ghost.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/ghost.svgnew file mode 100644index 00000000000..726ab86804b--- /dev/null+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/ghost.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none">+ <path d="M6.00033 6.66146H6.00699M10.0003 6.66146H10.007M8.00033 1.32812C6.58584 1.32813 5.22928 1.89003 4.22909 2.89022C3.2289 3.89042 2.66699 5.24697 2.66699 6.66146V14.6615L4.66699 12.6615L6.33366 14.3281L8.00033 12.6615L9.66699 14.3281L11.3337 12.6615L13.3337 14.6615V6.66146C13.3337 5.24697 12.7718 3.89042 11.7716 2.89022C10.7714 1.89003 9.41481 1.32813 8.00033 1.32812Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.tsindex 680bdc3ab20..dbb1a7cec6f 100644--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts@@ -204,6 +204,8 @@ import gear_settings_filled_component from "./gear_settings_filled.svg?componentimport gear_settings_filled_source from "./gear_settings_filled.svg?source";import gem_component from "./gem.svg?component";import gem_source from "./gem.svg?source";+import ghost_component from "./ghost.svg?component";+import ghost_source from "./ghost.svg?source";import git_branch_component from "./git_branch.svg?component";import git_branch_source from "./git_branch.svg?source";import globe_component from "./globe.svg?component";@@ -911,6 +913,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =component: gem_component,source: gem_source,},+ ghost: {+ component: ghost_component,+ source: ghost_source,+ },git_branch: {component: git_branch_component,source: git_branch_source,@@ -1683,6 +1689,7 @@ export type IconName =| "gear"| "gear_settings_filled"| "gem"+ | "ghost"| "globe"| "git_branch"| "grabber"diff --git a/frontend/src/metabase/visualizations/click-actions/lib/modes.ts b/frontend/src/metabase/visualizations/click-actions/lib/modes.tsindex d07dcc0476b..e5bb4fc7126 100644--- a/frontend/src/metabase/visualizations/click-actions/lib/modes.ts+++ b/frontend/src/metabase/visualizations/click-actions/lib/modes.ts@@ -5,7 +5,6 @@ import type Question from "metabase-lib/v1/Question";import { Mode } from "../Mode";import { ArchivedMode } from "../modes/ArchivedMode";import { DefaultMode } from "../modes/DefaultMode";-import { EmbeddingSdkMode } from "../modes/EmbeddingSdkMode";import { ListMode } from "../modes/ListMode";export function getMode(question: Question): Mode | null {@@ -18,11 +17,11 @@ export function getMode(question: Question): Mode | null {export function getEmbeddingMode({question,- queryMode = EmbeddingSdkMode,+ queryMode,plugins,}: {question: Question;- queryMode?: QueryClickActionsMode;+ queryMode: QueryClickActionsMode;plugins?: MetabasePluginsConfig;}): Mode {return new Mode(question, queryMode, plugins);diff --git a/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode.ts b/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode.tsnew file mode 100644index 00000000000..c4796393665--- /dev/null+++ b/frontend/src/metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode.ts@@ -0,0 +1,8 @@+import { DashboardClickAction } from "metabase/visualizations/click-actions/actions/DashboardClickAction";+import type { QueryClickActionsMode } from "metabase/visualizations/types";++export const EmbeddingSdkStaticMode: QueryClickActionsMode = {+ name: "embedding-sdk-static",+ hasDrills: false,+ clickActions: [DashboardClickAction],+};diff --git a/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsx b/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsxindex 76f9d3112ab..27bfbf38325 100644--- a/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsx+++ b/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsx@@ -104,8 +104,15 @@ export default class LeafletGridHeatMap extends LeafletMap {const {series: [{ card }],metadata,+ token,} = this.props;+ const isStaticEmbedding = !!token;++ if (isStaticEmbedding) {+ return false;+ }+const question = new Question(card, metadata);const { isNative } = Lib.queryDisplayInfo(question.query());return !isNative;diff --git a/frontend/src/metabase/visualizations/components/LeafletMap.jsx b/frontend/src/metabase/visualizations/components/LeafletMap.jsxindex 17ed113cc71..a8aed5336cd 100644--- a/frontend/src/metabase/visualizations/components/LeafletMap.jsx+++ b/frontend/src/metabase/visualizations/components/LeafletMap.jsx@@ -140,8 +140,15 @@ export default class LeafletMap extends Component {const {series: [{ card }],metadata,+ token,} = this.props;+ const isStaticEmbedding = !!token;++ if (isStaticEmbedding) {+ return false;+ }+const question = new Question(card, metadata);const { isNative } = Lib.queryDisplayInfo(question.query());return !isNative || question.isSaved();diff --git a/frontend/src/metabase/visualizations/components/PinMap.jsx b/frontend/src/metabase/visualizations/components/PinMap.jsxindex 405171f4b04..25781b9b12f 100644--- a/frontend/src/metabase/visualizations/components/PinMap.jsx+++ b/frontend/src/metabase/visualizations/components/PinMap.jsx@@ -179,8 +179,11 @@ export default class PinMap extends Component {}render() {- const { className, settings, isEditing, isDashboard } = this.props;+ const { className, settings, isEditing, isDashboard, token } = this.props;const { lat, lng, zoom } = this.state;++ const isStaticEmbedding = !!token;+const disableUpdateButton = lat == null && lng == null && zoom == null;const Map = MAP_COMPONENTS_BY_TYPE[settings["map.pin_type"]];@@ -190,6 +193,10 @@ export default class PinMap extends Component {const mapProps = { ...this.props };mapProps.series[0].data.rows = rows;+ // For static embedding we hide the button+ const shouldShowDefaultViewChangeButton =+ !isStaticEmbedding && (isEditing || !isDashboard);+return (<divdata-element-id="pin-map"@@ -247,7 +254,7 @@ export default class PinMap extends Component {CS.hoverChild,)}>- {isEditing || !isDashboard ? (+ {shouldShowDefaultViewChangeButton ? (<divclassName={cx("PinMapUpdateButton",diff --git a/rspack.config.js b/rspack.config.jsindex 6284e6be568..9d223aef321 100644--- a/rspack.config.js+++ b/rspack.config.js@@ -4,11 +4,14 @@const configs = [require("./rspack.main.config")];-if (process.env.MB_EDITION === "ee" && process.env.SKIP_EMBEDDING_SDK !== "true") {- // Build the embed.js script for the sdk iframe embedding.+if (process.env.SKIP_EMBEDDING_SDK !== "true") {+ // Build the embed.js script for the sdk iframe embeddingconfigs.push(require("./rspack.iframe-sdk-embed.config"));- // Build the Embedding SDK npm package.- configs.push(require("./rspack.embedding-sdk-bundle.config"));++ if (process.env.MB_EDITION === "ee") {+ // Build the Embedding SDK npm package.+ configs.push(require("./rspack.embedding-sdk-bundle.config"));+ }}module.exports = configs;