Skip to content

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

refactor(simple-embed): drop MetabaseEmbed and pass to the iframe the component name (#61967)

Nicolò Pretto13835ef1006c
diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
index 99566a458c2..5e60ab04964 100644
--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
@@ -315,7 +315,7 @@ export const visitCustomHtmlPage = (
* This function checks if the rspack dev server is available and if so, it mocks the embed.js file
* to point it to the rspack dev server.
*/
-const mockEmbedJsToDevServer = () => {
+export const mockEmbedJsToDevServer = () => {
if (Cypress.env("CI")) {
// we don't need this logic in CI, let's skip the check to avoid slowing down the tests
return;
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/auto-enable-embedding.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/auto-enable-embedding.cy.spec.ts
index 54de96b62f6..2b57e8ce174 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/auto-enable-embedding.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/auto-enable-embedding.cy.spec.ts
@@ -13,6 +13,7 @@ describe(suiteTitle, () => {
cy.intercept("GET", "/api/dashboard/*").as("dashboard");
cy.intercept("POST", "/api/card/*/query").as("cardQuery");
cy.intercept("GET", "/api/activity/recents?*").as("recentActivity");
+ H.mockEmbedJsToDevServer();
});
it("auto-enables the enable-embedding-simple settings", () => {
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.ts
index 293d4d006cd..22c9ead6d20 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 @@ H.describeWithSnowplow(suiteTitle, () => {
H.activateToken("bleeding-edge");
H.enableTracking();
H.updateSetting("enable-embedding-simple", true);
+ H.mockEmbedJsToDevServer();
});
afterEach(() => {
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.ts
index a0748a02b8d..261c0d385bc 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
@@ -27,6 +27,8 @@ H.describeWithSnowplow(suiteTitle, () => {
cy.intercept("GET", "/api/dashboard/**").as("dashboard");
cy.intercept("POST", "/api/card/*/query").as("cardQuery");
cy.intercept("GET", "/api/activity/recents?*").as("recentActivity");
+
+ H.mockEmbedJsToDevServer();
});
afterEach(() => {
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts
index cf1622e5971..58462a941e8 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
@@ -48,10 +48,7 @@ export const visitNewEmbedPage = ({
cy.wait("@dashboard");
- cy.get("#iframe-embed-container", {
- // we are loading lots of JS, so on a slow connection it will take a long while.
- timeout: 20000,
- }).should("have.attr", "data-iframe-loaded", "true");
+ 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.ts
index 0081a8b1fd4..8c86abbfb07 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
@@ -3,6 +3,7 @@ import {
ORDERS_COUNT_QUESTION_ID,
ORDERS_DASHBOARD_ID,
} from "e2e/support/cypress_sample_instance_data";
+import { mockEmbedJsToDevServer } from "e2e/support/helpers";
import {
getEmbedSidebar,
@@ -32,6 +33,8 @@ H.describeWithSnowplow(suiteTitle, () => {
cy.intercept("GET", "/api/dashboard/**").as("dashboard");
cy.intercept("POST", "/api/card/*/query").as("cardQuery");
cy.intercept("GET", "/api/activity/recents?*").as("recentActivity");
+
+ mockEmbedJsToDevServer();
});
afterEach(() => {
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.ts
index c186fae0a9d..d5245995ab4 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,3 +1,5 @@
+import { mockEmbedJsToDevServer } from "e2e/support/helpers";
+
import {
codeBlock,
getEmbedSidebar,
@@ -23,6 +25,8 @@ H.describeWithSnowplow(suiteTitle, () => {
cy.intercept("GET", "/api/dashboard/**").as("dashboard");
cy.intercept("POST", "/api/card/*/query").as("cardQuery");
+
+ mockEmbedJsToDevServer();
});
afterEach(() => {
@@ -310,7 +314,6 @@ H.describeWithSnowplow(suiteTitle, () => {
});
H.getSimpleEmbedIframeContent().within(() => {
- cy.findByText("Orders").click();
cy.findByText("Save").should("be.visible");
});
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx
index 41def0f4a1d..f05eff9734f 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx
@@ -3,7 +3,6 @@ import { P, match } from "ts-pattern";
import {
InteractiveDashboard,
- InteractiveQuestion,
MetabaseProvider,
StaticDashboard,
StaticQuestion,
@@ -82,84 +81,77 @@ const SdkIframeEmbedView = ({
}): ReactNode => {
const rerenderKey = useParamRerenderKey(settings);
- return match(settings)
- .with(
- P.union({ template: "exploration" }, { questionId: "new" }),
- (settings) => (
- <InteractiveQuestion
- questionId="new"
- height="100%"
- isSaveEnabled={settings.isSaveEnabled ?? false}
- targetCollection={settings.targetCollection}
- entityTypes={settings.entityTypes}
- key={rerenderKey}
- />
- ),
- )
- .with({ template: "curate-content" }, (_settings) => null)
- .with({ template: "view-content" }, (_settings) => null)
- .with(
- {
- 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(
- {
- 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(
- {
- 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
- };
-
- if (settings.drills === false) {
- // note: this disable drills but also removes the top toolbar
- return <StaticQuestion {...commonProps} key={rerenderKey} />;
- }
-
- return (
- <SdkQuestion
- {...commonProps}
- isSaveEnabled={settings.isSaveEnabled ?? false}
+ return (
+ match(settings)
+ // .with({ template: "curate-content" }, (_settings) => null)
+ // .with({ template: "view-content" }, (_settings) => null)
+ .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}
- targetCollection={settings.targetCollection}
- entityTypes={settings.entityTypes}
/>
- );
- },
- )
- .otherwise(() => null);
+ ),
+ )
+ .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 (
+ <SdkQuestion
+ {...commonProps}
+ isSaveEnabled={settings.isSaveEnabled ?? false}
+ key={rerenderKey}
+ targetCollection={settings.targetCollection}
+ entityTypes={settings.entityTypes}
+ />
+ );
+ },
+ )
+ .otherwise(() => null)
+ );
};
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts
index b0accdd637b..4e30f1730c1 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts
@@ -6,18 +6,13 @@ import {
} from "embedding/auth-common";
import { INVALID_AUTH_METHOD, MetabaseError } from "embedding-sdk/errors";
-import {
- ALLOWED_EMBED_SETTING_KEYS,
- type AllowedEmbedSettingKey,
- DISABLE_UPDATE_FOR_KEYS,
-} from "./constants";
+import { DISABLE_UPDATE_FOR_KEYS } from "./constants";
import type {
SdkIframeEmbedEvent,
SdkIframeEmbedEventHandler,
SdkIframeEmbedMessage,
SdkIframeEmbedSettings,
SdkIframeEmbedTagMessage,
- SdkIframeEmbedTagSettings,
} from "./types/embed";
import { attributeToSettingKey, parseAttributeValue } from "./webcomponents";
@@ -26,12 +21,6 @@ const EMBEDDING_ROUTE = "embed/sdk/v1";
/** list of active embeds, used to know which embeds to update when the global config changes */
const _activeEmbeds: Set<MetabaseEmbedElement> = new Set();
-// Stub of MetabaseEmbedElement to satisfy type requirements of helper utilities below.
-// The full custom elements are declared later in this file.
-export class MetabaseEmbedElement extends HTMLElement {
- updateSettings(_settings: Partial<SdkIframeEmbedSettings>) {}
-}
-
// Setup a proxy to watch for changes to window.metabaseConfig and update all
// active embeds when the config changes. It also setups a setter for
// window.metabaseConfig to re-create the proxy if the whole object is replaced,
@@ -40,12 +29,9 @@ export class MetabaseEmbedElement extends HTMLElement {
const setupConfigWatcher = () => {
const createProxy = (target: Record<string, unknown>) =>
new Proxy(target, {
- set(obj, prop, value) {
- obj[prop as string] = value;
-
- _activeEmbeds.forEach((embedElement) => {
- embedElement.updateSettings({ [prop as string]: value });
- });
+ set(metabaseConfig, prop, newValue) {
+ metabaseConfig[prop as string] = newValue;
+ updateAllEmbeds({ [prop]: newValue });
return true;
},
});
@@ -60,21 +46,25 @@ const setupConfigWatcher = () => {
return proxyConfig;
},
set(newVal: Record<string, unknown>) {
- currentConfig = newVal || {};
+ assertFieldCanBeUpdated(newVal);
+
+ currentConfig = { ...currentConfig, ...newVal };
proxyConfig = createProxy(currentConfig);
- updateAllEmbeds(currentConfig as Partial<SdkIframeEmbedSettings>);
+ updateAllEmbeds(currentConfig);
},
});
// Trigger initial update if there was existing config
if (Object.keys(currentConfig).length > 0) {
- updateAllEmbeds(currentConfig as Partial<SdkIframeEmbedSettings>);
+ updateAllEmbeds(currentConfig);
}
};
export const updateAllEmbeds = (config: Partial<SdkIframeEmbedSettings>) => {
+ assertFieldCanBeUpdated(config);
+
_activeEmbeds.forEach((embedElement) => {
- embedElement.updateSettings(config);
+ embedElement._updateSettings(config);
});
};
@@ -90,106 +80,196 @@ if (typeof window !== "undefined") {
setupConfigWatcher();
}
-class MetabaseEmbed {
+const raiseError = (message: string) => {
+ throw new MetabaseError("EMBED_ERROR", message);
+};
+
+function assertFieldCanBeUpdated(newValues: Partial<SdkIframeEmbedSettings>) {
+ const currentConfig = (window as any).metabaseConfig || {};
+ for (const field of DISABLE_UPDATE_FOR_KEYS) {
+ if (
+ currentConfig[field] !== undefined &&
+ newValues[field] !== undefined && // we allow passing a partial update
+ currentConfig[field] !== newValues[field]
+ ) {
+ raiseError(`${field} cannot be updated after the embed is created`);
+ }
+ }
+}
+
+export abstract class MetabaseEmbedElement extends HTMLElement {
+ private _iframe: HTMLIFrameElement | null = null;
+ protected abstract _componentName: string;
+ protected abstract _attributeNames: readonly string[];
+
static readonly VERSION = "1.1.0";
- private _settings: SdkIframeEmbedTagSettings;
private _isEmbedReady: boolean = false;
- private iframe: HTMLIFrameElement | null = null;
-
private _eventHandlers: Map<
SdkIframeEmbedEvent["type"],
Set<SdkIframeEmbedEventHandler>
> = new Map();
- constructor(settings: SdkIframeEmbedTagSettings) {
- this._settings = settings;
- this._settings._isLocalhost = this._getIsLocalhost();
+ get globalSettings() {
+ return (window as any).metabaseConfig || {};
+ }
- this._setup();
+ // returns the attributes converted to camelCase + global settings
+ get properties(): SdkIframeEmbedSettings {
+ const attributesConverted = this._attributeNames.reduce(
+ (acc, attr) => {
+ const attrValue = this.getAttribute(attr as string);
+ if (attrValue !== null) {
+ const key = attributeToSettingKey(attr as string);
+ acc[key] = parseAttributeValue(attrValue);
+ }
+ return acc;
+ },
+ {} as Record<string, unknown>,
+ );
+
+ return {
+ ...this.globalSettings,
+ ...attributesConverted,
+ componentName: this._componentName,
+ _isLocalhost: this._getIsLocalhost(),
+ } as SdkIframeEmbedSettings;
}
- /**
- * Merge these settings with the current settings.
- */
- public updateSettings(settings: Partial<SdkIframeEmbedSettings>) {
- // The value of these fields must be the same as the initial value used to create an embed.
- // This allows users to pass a complete settings object that includes all their settings.
- for (const field of DISABLE_UPDATE_FOR_KEYS) {
- if (
- settings[field] !== undefined &&
- settings[field] !== this._settings[field]
- ) {
- raiseError(`${field} cannot be updated after the embed is created`);
+ addEventListener(
+ type: string,
+ listener: EventListenerOrEventListenerObject | SdkIframeEmbedEventHandler,
+ options?: boolean | AddEventListenerOptions,
+ ): void {
+ if (type === "ready") {
+ const eventType = type as SdkIframeEmbedEvent["type"];
+ const handler = listener as SdkIframeEmbedEventHandler;
+ if (!this._eventHandlers.has(eventType)) {
+ this._eventHandlers.set(eventType, new Set());
}
+
+ // For the ready event, invoke the handler immediately if the embed is already ready.
+ if (eventType === "ready" && this._isEmbedReady) {
+ handler();
+ return;
+ }
+
+ this._eventHandlers.get(eventType)!.add(handler);
+ return;
}
- // Merge incoming settings regardless of readiness so they're applied once the iframe signals ready.
- const allowedSettings = Object.fromEntries(
- Object.entries(settings).filter(([key]) =>
- ALLOWED_EMBED_SETTING_KEYS.includes(key as AllowedEmbedSettingKey),
- ),
+ // Fall back to the native HTMLElement event mechanism for all other events.
+ super.addEventListener(
+ type,
+ listener as EventListenerOrEventListenerObject,
+ options,
);
+ }
- // Update local cache first.
- this._settings = { ...this._settings, ...allowedSettings };
+ removeEventListener(
+ type: string,
+ listener: EventListenerOrEventListenerObject | SdkIframeEmbedEventHandler,
+ options?: boolean | EventListenerOptions,
+ ): void {
+ if (type === "ready") {
+ const eventType = type as SdkIframeEmbedEvent["type"];
+ const handler = listener as SdkIframeEmbedEventHandler;
+ const handlers = this._eventHandlers.get(eventType);
+
+ if (handlers) {
+ handlers.delete(handler);
+
+ if (handlers.size === 0) {
+ this._eventHandlers.delete(eventType);
+ }
+ }
+ return;
+ }
+
+ super.removeEventListener(
+ type,
+ listener as EventListenerOrEventListenerObject,
+ options,
+ );
+ }
+
+ /**
+ * Send a message with the new settings
+ */
+ _updateSettings(settings: Partial<SdkIframeEmbedSettings>) {
+ const newValues = {
+ ...this.properties,
+ ...settings,
+ } as SdkIframeEmbedSettings;
// If the iframe isn't ready yet, don't send the message now.
if (!this._isEmbedReady) {
return;
}
- // Iframe is ready – propagate only the delta (allowedSettings)
- if (Object.keys(allowedSettings).length > 0) {
- this._validateEmbedSettings(this._settings);
- this._sendMessage(
- "metabase.embed.setSettings",
- this._settings as SdkIframeEmbedSettings,
- );
- }
+ this._validateEmbedSettings(newValues);
+
+ // Iframe is ready – propagate the delta
+ this._sendMessage("metabase.embed.setSettings", newValues);
}
- public destroy() {
+ destroy() {
window.removeEventListener("message", this._handleMessage);
this._isEmbedReady = false;
this._eventHandlers.clear();
- if (this.iframe) {
- this.iframe.remove();
- this.iframe = null;
+ if (this._iframe) {
+ this._iframe.remove();
+ this._iframe = null;
}
}
- public addEventListener(
- eventType: SdkIframeEmbedEvent["type"],
- handler: SdkIframeEmbedEventHandler,
- ) {
- if (!this._eventHandlers.has(eventType)) {
- this._eventHandlers.set(eventType, new Set());
- }
+ connectedCallback() {
+ this.style.display = "block";
- // For the ready event, invoke the handler immediately if the embed is already ready.
- if (eventType === "ready" && this._isEmbedReady) {
- handler();
+ if (this._iframe) {
+ // already initialised
return;
}
- this._eventHandlers.get(eventType)!.add(handler);
+ if (!this.id) {
+ this.id = `metabase-embed-${Math.random().toString(36).slice(2)}`;
+ }
+
+ try {
+ this._setup();
+
+ registerEmbed(this);
+ } catch (error) {
+ console.error("[metabase.embed.error]", error);
+ }
}
- public removeEventListener(
- eventType: SdkIframeEmbedEvent["type"],
- handler: SdkIframeEmbedEventHandler,
- ) {
- const handlers = this._eventHandlers.get(eventType);
+ disconnectedCallback() {
+ this.destroy();
+ unregisterEmbed(this);
+ }
- if (handlers) {
- handlers.delete(handler);
+ attributeChangedCallback(
+ attrName: string,
+ oldVal: string | null,
+ newVal: string | null,
+ ) {
+ if (!this._iframe || oldVal === newVal) {
+ return;
+ }
- if (handlers.size === 0) {
- this._eventHandlers.delete(eventType);
- }
+ const key = attributeToSettingKey(attrName) as keyof SdkIframeEmbedSettings;
+ if (
+ (DISABLE_UPDATE_FOR_KEYS as readonly string[]).includes(key as string)
+ ) {
+ console.error(`${key} cannot be updated after the embed is created`);
+ return;
}
+
+ this._updateSettings({
+ [key]: parseAttributeValue(newVal),
+ } as Partial<SdkIframeEmbedSettings>);
}
private _emitEvent(event: SdkIframeEmbedEvent) {
@@ -200,59 +280,32 @@ class MetabaseEmbed {
}
}
- private _setEmbedSettings(settings: Partial<SdkIframeEmbedSettings>) {
- const allowedSettings = Object.fromEntries(
- Object.entries(settings).filter(([key]) =>
- ALLOWED_EMBED_SETTING_KEYS.includes(key as AllowedEmbedSettingKey),
- ),
- );
-
- this._settings = { ...this._settings, ...allowedSettings };
-
- this._validateEmbedSettings(this._settings);
- this._sendMessage("metabase.embed.setSettings", this._settings);
- }
-
private _setup() {
- this._validateEmbedSettings(this._settings);
+ this._validateEmbedSettings(this.properties);
- const { instanceUrl, target, iframeClassName } = this._settings;
+ this._iframe = document.createElement("iframe");
+ this._iframe.src = `${this.globalSettings.instanceUrl}/${EMBEDDING_ROUTE}`;
+ this._iframe.style.width = "100%";
+ this._iframe.style.height = "100%";
+ this._iframe.style.border = "none";
- this.iframe = document.createElement("iframe");
- this.iframe.src = `${instanceUrl}/${EMBEDDING_ROUTE}`;
- this.iframe.style.width = "100%";
- this.iframe.style.height = "100%";
- this.iframe.style.border = "none";
-
- this.iframe.setAttribute("data-metabase-embed", "true");
-
- if (iframeClassName) {
- this.iframe.classList.add(iframeClassName);
- }
+ this._iframe.setAttribute("data-metabase-embed", "true");
window.addEventListener("message", this._handleMessage);
- let parentContainer: HTMLElement | null = null;
-
- if (typeof target === "string") {
- parentContainer = document.querySelector(target);
- } else if (target instanceof HTMLElement) {
- parentContainer = target;
- }
-
- if (!parentContainer) {
- raiseError(`cannot find embed container "${target}"`);
- return;
- }
-
- parentContainer.appendChild(this.iframe);
+ this.appendChild(this._iframe);
}
private _getIsLocalhost() {
const { hostname } = window.location;
try {
- const instanceUrl = new URL(this._settings?.instanceUrl);
+ if (!this.globalSettings.instanceUrl) {
+ // if not configured yet, we return true to avoid throwing
+ return true;
+ }
+
+ const instanceUrl = new URL(this.globalSettings.instanceUrl);
if (hostname === instanceUrl.hostname) {
return true;
@@ -264,42 +317,11 @@ class MetabaseEmbed {
return hostname === "localhost" || hostname === "127.0.0.1";
}
- private _validateEmbedSettings(settings: SdkIframeEmbedTagSettings) {
+ private _validateEmbedSettings(settings: SdkIframeEmbedSettings) {
if (!settings.instanceUrl) {
raiseError("instanceUrl must be provided");
}
- if (!settings.dashboardId && !settings.questionId && !settings.template) {
- raiseError(
- "either dashboardId, questionId, or template must be provided",
- );
- }
-
- if (
- settings.template === "exploration" &&
- (settings.dashboardId || settings.questionId)
- ) {
- raiseError(
- "the exploration template can't be used with dashboardId or questionId",
- );
- }
-
- if (
- (settings.template === "view-content" ||
- settings.template === "curate-content") &&
- !settings.initialCollection
- ) {
- raiseError(
- `initialCollection must be provided for the ${settings.template} template`,
- );
- }
-
- if (settings.dashboardId && settings.questionId) {
- raiseError(
- "can't use both dashboardId and questionId at the same time. to change the question to a dashboard, set the questionId to null (and vice-versa)",
- );
- }
-
// Ensure auth methods are mutually exclusive
const authMethods = [
settings.apiKey,
@@ -314,16 +336,12 @@ class MetabaseEmbed {
"apiKey, useExistingUserSession, and preferredAuthMethod are mutually exclusive, only one can be specified.",
);
}
-
- if (!settings.target) {
- raiseError("target must be provided");
- }
}
private _handleMessage = async (
event: MessageEvent<SdkIframeEmbedTagMessage>,
) => {
- if (event.source !== this.iframe?.contentWindow) {
+ if (event.source !== this._iframe?.contentWindow) {
// ignore messages from other iframes
return;
}
@@ -338,11 +356,11 @@ class MetabaseEmbed {
}
this._isEmbedReady = true;
- if (this.iframe) {
+ if (this._iframe) {
// this is used from tests to await the loading of the iframe
- this.iframe.setAttribute("data-iframe-loaded", "true");
+ this._iframe.setAttribute("data-iframe-loaded", "true");
}
- this._setEmbedSettings(this._settings);
+ this._updateSettings(this.properties);
this._emitEvent({ type: "ready" });
}
@@ -355,14 +373,14 @@ class MetabaseEmbed {
type: Message["type"],
data: Message["data"],
) {
- if (this.iframe?.contentWindow) {
- this.iframe.contentWindow.postMessage({ type, data }, "*");
+ if (this._iframe?.contentWindow) {
+ this._iframe.contentWindow.postMessage({ type, data }, "*");
}
}
private async _authenticate() {
// If we are using an API key, we don't need to authenticate via SSO.
- if (this._settings.apiKey) {
+ if (this.properties.apiKey) {
return;
}
@@ -390,7 +408,7 @@ class MetabaseEmbed {
* @returns {{ method: "saml" | "jwt", sessionToken: {jwt: string} }}
*/
private async _getMetabaseSessionToken() {
- const { instanceUrl, preferredAuthMethod } = this._settings;
+ const { instanceUrl, preferredAuthMethod } = this.properties;
const urlResponseJson = await connectToInstanceAuthSso(instanceUrl, {
headers: this._getAuthRequestHeader(),
@@ -429,142 +447,21 @@ class MetabaseEmbed {
}
}
-const raiseError = (message: string) => {
- throw new MetabaseError("EMBED_ERROR", message);
-};
-
function createCustomElement<Arr extends readonly string[]>(
- tagName: string,
+ componentName: string,
attributeNames: Arr,
) {
- class CustomEmbedElement extends HTMLElement {
- private _embed: MetabaseEmbed | null = null;
+ const CustomEmbedElement = class extends MetabaseEmbedElement {
+ protected _componentName: string = componentName;
+ protected _attributeNames: readonly string[] = attributeNames;
static get observedAttributes() {
return attributeNames as readonly string[];
}
+ };
- addEventListener(
- type: string,
- listener: EventListenerOrEventListenerObject | SdkIframeEmbedEventHandler,
- options?: boolean | AddEventListenerOptions,
- ): void {
- if (type === "ready") {
- // Forward Metabase SDK specific events to the underlying embed instance.
- this._embed?.addEventListener(
- type as SdkIframeEmbedEvent["type"],
- listener as SdkIframeEmbedEventHandler,
- );
- return;
- }
-
- // Fall back to the native HTMLElement event mechanism for all other events.
- super.addEventListener(
- type,
- listener as EventListenerOrEventListenerObject,
- options,
- );
- }
-
- removeEventListener(
- type: string,
- listener: EventListenerOrEventListenerObject | SdkIframeEmbedEventHandler,
- options?: boolean | EventListenerOptions,
- ): void {
- if (type === "ready") {
- this._embed?.removeEventListener(
- type as SdkIframeEmbedEvent["type"],
- listener as SdkIframeEmbedEventHandler,
- );
- return;
- }
-
- super.removeEventListener(
- type,
- listener as EventListenerOrEventListenerObject,
- options,
- );
- }
-
- updateSettings(settings: Partial<SdkIframeEmbedSettings>) {
- this._embed?.updateSettings(settings);
- }
-
- connectedCallback() {
- this.style.display = "block";
-
- if (this._embed) {
- // already initialised
- return;
- }
-
- // we need to copy the settings, we don't want to accidentally mutate the shared object
- // TODO: do deep copy to be sure we're not sharing the theme
- const settings: Record<string, unknown> = {
- ...(window.metabaseConfig || {}),
- };
-
- // Read element-specific attributes
- attributeNames.forEach((attr) => {
- const attrValue = this.getAttribute(attr as string);
- if (attrValue !== null) {
- const key = attributeToSettingKey(attr as string);
- settings[key] = parseAttributeValue(attrValue);
- }
- });
-
- if (!this.id) {
- this.id = `metabase-embed-${Math.random().toString(36).slice(2)}`;
- }
- settings.target = `#${this.id}`;
-
- try {
- this._embed = new MetabaseEmbed(
- settings as unknown as SdkIframeEmbedTagSettings,
- );
- registerEmbed(this as unknown as MetabaseEmbedElement);
- } catch (error) {
- console.error("[metabase.embed.error]", error);
- }
- }
-
- disconnectedCallback() {
- this._embed?.destroy();
- this._embed = null;
- unregisterEmbed(this as unknown as MetabaseEmbedElement);
- }
-
- attributeChangedCallback(
- attrName: string,
- oldVal: string | null,
- newVal: string | null,
- ) {
- if (!this._embed || oldVal === newVal) {
- return;
- }
-
- const key = attributeToSettingKey(
- attrName,
- ) as keyof SdkIframeEmbedSettings;
- if (
- (DISABLE_UPDATE_FOR_KEYS as readonly string[]).includes(key as string)
- ) {
- return;
- }
-
- const value = parseAttributeValue(newVal);
- try {
- this._embed.updateSettings({
- [key]: value,
- } as Partial<SdkIframeEmbedSettings>);
- } catch (error) {
- console.error("[metabase.embed.error]", error);
- }
- }
- }
-
- if (typeof window !== "undefined" && !customElements.get(tagName)) {
- customElements.define(tagName, CustomEmbedElement);
+ if (typeof window !== "undefined" && !customElements.get(componentName)) {
+ customElements.define(componentName, CustomEmbedElement);
}
return CustomEmbedElement;
@@ -594,8 +491,7 @@ const MetabaseQuestionElement = createCustomElement("metabase-question", [
if (typeof window !== "undefined") {
(window as any)["metabase.embed"] = {
...(window as any)["metabase.embed"],
- MetabaseEmbed,
};
}
-export { MetabaseEmbed, MetabaseDashboardElement, MetabaseQuestionElement };
+export { MetabaseDashboardElement, MetabaseQuestionElement };
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.unit.spec.ts
index 328a462f03c..970cdd2631c 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.unit.spec.ts
@@ -1,183 +1,176 @@
-import _ from "underscore";
+import { act } from "react-dom/test-utils";
-import { MetabaseEmbed } from "./embed";
+import type { MetabaseEmbedElement } from "./embed";
+
+const defineMetabaseConfig = (config: unknown) => {
+ (window as any).metabaseConfig = config;
+};
describe("embed.js script tag for sdk iframe embedding", () => {
- const defaultSettings = {
- apiKey: "test-api-key",
- instanceUrl: "http://localhost:3000",
- target: document.createElement("div"),
- };
+ let consoleErrorSpy: jest.SpyInstance;
- it("throws when target element is not found", () => {
- expect(() => {
- new MetabaseEmbed({
- ...defaultSettings,
- dashboardId: 1,
- target: "#not-existent-target",
- });
- }).toThrow('cannot find embed container "#not-existent-target"');
- });
+ beforeEach(() => {
+ jest.resetModules();
+ // @ts-expect-error -- test cleanup
+ delete window.metabaseConfig;
+ require("./embed"); // we do things when the script is loaded
- it("throws when target element is undefined", () => {
- expect(() => {
- new MetabaseEmbed({
- ...defaultSettings,
- questionId: 1,
- // @ts-expect-error -- we are testing for incorrect configuration
- target: undefined,
- });
- }).toThrow("target must be provided");
+ document.body.innerHTML = "";
+ consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
});
- it("throws when instance url is not provided", () => {
- expect(() => {
- // @ts-expect-error -- we are testing for incorrect configuration
- new MetabaseEmbed({ ...defaultSettings, instanceUrl: undefined });
- }).toThrow("instanceUrl must be provided");
+ afterEach(() => {
+ consoleErrorSpy.mockRestore();
});
- it("throws when both question id and dashboard id are provided", () => {
- expect(() => {
- // @ts-expect-error -- we are testing for incorrect configuration
- new MetabaseEmbed({
- ...defaultSettings,
- questionId: 10,
- dashboardId: 10,
- });
- }).toThrow("can't use both dashboardId and questionId at the same time");
+ it("reports an error when instance url is not provided", () => {
+ const embed = document.createElement("metabase-question");
+ embed.setAttribute("question-id", "1");
+ document.body.appendChild(embed);
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ "[metabase.embed.error]",
+ expect.objectContaining({
+ message: "instanceUrl must be provided",
+ }),
+ );
});
- it("does not throw an error when instanceUrl is updated to be the same", () => {
- expect(() => {
- const embed = new MetabaseEmbed({
- ...defaultSettings,
- instanceUrl: "https://foo-bar-baz.com",
- questionId: 10,
- });
+ it("does not report an error when instanceUrl is updated to be the same", () => {
+ defineMetabaseConfig({
+ instanceUrl: "https://foo-bar-baz.com",
+ });
+ const embed = document.createElement("metabase-question");
+ embed.setAttribute("question-id", "10");
+ document.body.appendChild(embed);
- embed.updateSettings({ instanceUrl: "https://foo-bar-baz.com" });
- }).not.toThrow();
+ defineMetabaseConfig({
+ instanceUrl: "https://foo-bar-baz.com",
+ });
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
});
- it("throws an error when useExistingUserSession is updated to be a different value", () => {
- expect(() => {
- const embed = new MetabaseEmbed({
- ..._.omit(defaultSettings, "apiKey"),
- instanceUrl: "https://foo-bar-baz.com",
- questionId: 10,
- target: document.createElement("div"),
- useExistingUserSession: true,
- });
-
- embed.updateSettings({ useExistingUserSession: false });
- }).toThrow(
- "useExistingUserSession cannot be updated after the embed is created",
- );
- });
+ it("reports an error when useExistingUserSession is updated to be a different value", async () => {
+ defineMetabaseConfig({
+ instanceUrl: "https://foo-bar-baz.com",
+ useExistingUserSession: true,
+ });
+ const embed = document.createElement("metabase-question");
+ embed.setAttribute("question-id", "10");
- it("throws when question id is provided in the exploration template", () => {
- expect(() => {
- // @ts-expect-error -- we are testing for incorrect configuration
- new MetabaseEmbed({
- ...defaultSettings,
- template: "exploration",
- questionId: 10,
- });
- }).toThrow(
- "the exploration template can't be used with dashboardId or questionId",
- );
- });
+ await act(async () => {
+ document.body.appendChild(embed);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
- it("throws when dashboard id is provided in the exploration template", () => {
expect(() => {
- // @ts-expect-error -- we are testing for incorrect configuration
- new MetabaseEmbed({
- ...defaultSettings,
- template: "exploration",
- dashboardId: 10,
+ defineMetabaseConfig({
+ instanceUrl: "https://foo-bar-baz.com",
+ useExistingUserSession: false,
});
}).toThrow(
- "the exploration template can't be used with dashboardId or questionId",
+ "useExistingUserSession cannot be updated after the embed is created",
);
});
- it("throws when neither question id, dashboard id, or template are provided", () => {
- expect(() => {
- // @ts-expect-error -- we are testing for incorrect configuration
- new MetabaseEmbed({ ...defaultSettings });
- }).toThrow("either dashboardId, questionId, or template must be provided");
- });
-
- it.each([["view-content"], ["curate-content"]] as const)(
- "throws when initialCollection is not provided for the %s template",
- (template: "view-content" | "curate-content") => {
- expect(() => {
- // @ts-expect-error -- we are testing for incorrect configuration
- new MetabaseEmbed({
- ...defaultSettings,
- template,
- });
- }).toThrow(
- `initialCollection must be provided for the ${template} template`,
- );
- },
- );
-
it("fires ready event immediately when addEventListener is called when embed is ready", () => {
const readyHandler = jest.fn();
- const embed = new MetabaseEmbed({
- ...defaultSettings,
- dashboardId: 1,
+ defineMetabaseConfig({
+ instanceUrl: "http://localhost:3000",
});
+ const embed = document.createElement("metabase-dashboard");
+ embed.setAttribute("dashboard-id", "1");
+ document.body.appendChild(embed);
- // Simulate the embed being ready.
- (embed as any)._isEmbedReady = true;
+ // @ts-expect-error -- Simulate the embed being ready.
+ (embed as MetabaseEmbedElement)._isEmbedReady = true;
// The handler should be called immediately.
embed.addEventListener("ready", readyHandler);
expect(readyHandler).toHaveBeenCalledTimes(1);
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
});
- it.each([
- [{ apiKey: "test-key", useExistingUserSession: true }],
- [{ apiKey: "test-key", preferredAuthMethod: "jwt" }],
- [{ useExistingUserSession: true, preferredAuthMethod: "jwt" }],
- [
- {
- apiKey: "test-key",
- useExistingUserSession: true,
- preferredAuthMethod: "jwt",
- },
- ],
- ] as const)(
- "throws when auth methods are not mutually exclusive",
- (authConfig) => {
- const settings = {
- ..._.omit(defaultSettings, "apiKey"),
- dashboardId: 1,
+ const authErrorTestCases = [
+ { apiKey: "test-key", useExistingUserSession: true },
+ { apiKey: "test-key", preferredAuthMethod: "jwt" },
+ { useExistingUserSession: true, preferredAuthMethod: "jwt" },
+ {
+ apiKey: "test-key",
+ useExistingUserSession: true,
+ preferredAuthMethod: "jwt",
+ },
+ ].flatMap((authConfig) => [
+ { ...authConfig, dashboardId: 1 },
+ { ...authConfig, questionId: 1 },
+ ]);
+
+ it.each(authErrorTestCases)(
+ "reports an error when auth methods are not mutually exclusive for %p",
+ (settings) => {
+ const { questionId, dashboardId, ...config } = settings as Partial<
+ typeof settings
+ > & {
+ questionId?: number;
+ dashboardId?: number;
};
+ defineMetabaseConfig({
+ instanceUrl: "http://localhost:3000",
+ ...config,
+ });
- expect(() => {
- new MetabaseEmbed({ ...settings, ...authConfig });
- }).toThrow(
- "apiKey, useExistingUserSession, and preferredAuthMethod are mutually exclusive, only one can be specified.",
+ const tagName = questionId ? "metabase-question" : "metabase-dashboard";
+ const embed = document.createElement(tagName);
+ if (questionId) {
+ embed.setAttribute("question-id", String(questionId));
+ } else if (dashboardId) {
+ embed.setAttribute("dashboard-id", String(dashboardId));
+ }
+ document.body.appendChild(embed);
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ "[metabase.embed.error]",
+ expect.objectContaining({
+ message:
+ "apiKey, useExistingUserSession, and preferredAuthMethod are mutually exclusive, only one can be specified.",
+ }),
);
},
);
- it("does not throw when only one auth method is provided", () => {
- const settings = {
- ..._.omit(defaultSettings, "apiKey"),
- dashboardId: 1,
- target: document.createElement("div"),
- };
+ const singleAuthTestCases = [
+ { apiKey: "test-key" },
+ { useExistingUserSession: true },
+ { preferredAuthMethod: "jwt" },
+ ].flatMap((authConfig) => [
+ { ...authConfig, dashboardId: 1 },
+ { ...authConfig, questionId: 1 },
+ ]);
+
+ it.each(singleAuthTestCases)(
+ "does not report an error when only one auth method is provided for %p",
+ (settings) => {
+ const { questionId, dashboardId, ...config } = settings as Partial<
+ typeof settings
+ > & {
+ questionId?: number;
+ dashboardId?: number;
+ };
+ defineMetabaseConfig({
+ instanceUrl: "http://localhost:3000",
+ ...config,
+ });
+
+ const tagName = questionId ? "metabase-question" : "metabase-dashboard";
+ const embed = document.createElement(tagName);
+ if (questionId) {
+ embed.setAttribute("question-id", String(questionId));
+ } else if (dashboardId) {
+ embed.setAttribute("dashboard-id", String(dashboardId));
+ }
+ document.body.appendChild(embed);
- expect(() => {
- new MetabaseEmbed({ ...settings, apiKey: "test-key" });
- new MetabaseEmbed({ ...settings, useExistingUserSession: true });
- new MetabaseEmbed({ ...settings, preferredAuthMethod: "jwt" });
- }).not.toThrow();
- });
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
+ },
+ );
});
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts
index 9675476766b..ae342c08403 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts
@@ -37,6 +37,7 @@ export type SdkIframeEmbedMessage =
// --- Embed Option Interfaces ---
export interface DashboardEmbedOptions {
+ componentName: "metabase-dashboard";
dashboardId: number | string;
drills?: boolean;
@@ -53,6 +54,7 @@ export interface DashboardEmbedOptions {
}
export interface QuestionEmbedOptions {
+ componentName: "metabase-question";
questionId: number | string;
drills?: boolean;
@@ -71,6 +73,7 @@ export interface QuestionEmbedOptions {
}
export interface ExplorationEmbedOptions {
+ componentName: "metabase-question";
template: "exploration";
isSaveEnabled?: boolean;
@@ -125,20 +128,14 @@ export type SdkIframeEmbedBaseSettings = {
export type SdkIframeEmbedTemplateSettings =
| DashboardEmbedOptions
| QuestionEmbedOptions
- | ExplorationEmbedOptions
- | CurateContentEmbedOptions
- | ViewContentEmbedOptions;
+ | ExplorationEmbedOptions;
+// | CurateContentEmbedOptions
+// | ViewContentEmbedOptions;
/** Settings used by the sdk embed route */
export type SdkIframeEmbedSettings = SdkIframeEmbedBaseSettings &
SdkIframeEmbedTemplateSettings;
-/** Settings used by the embed.js constructor */
-export type SdkIframeEmbedTagSettings = SdkIframeEmbedSettings & {
- target: string | HTMLElement;
- iframeClassName?: string;
-};
-
export type SdkIframeEmbedEvent = { type: "ready" };
export type SdkIframeEmbedEventHandler = () => void;
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css
new file mode 100644
index 00000000000..378d46f8378
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.module.css
@@ -0,0 +1,4 @@
+.EmbedPreviewIframe > * {
+ /* makes the metabase-* elements full height */
+ height: 100%;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx
index daa36bd1e9b..7557b4aa974 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/SdkIframeEmbedPreview.tsx
@@ -1,18 +1,19 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+//
+import { createElement, useCallback, useEffect, useMemo, useRef } from "react";
import { useSearchParam } from "react-use";
-import _ from "underscore";
+import { match } from "ts-pattern";
-import type { MetabaseTheme } from "embedding-sdk";
import { useSetting } from "metabase/common/hooks";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
import { colors as defaultMetabaseColors } from "metabase/lib/colors";
import { Card } from "metabase/ui";
-import type { MetabaseEmbedElement } from "metabase-enterprise/embedding_iframe_sdk/embed";
import type { SdkIframeEmbedBaseSettings } from "metabase-enterprise/embedding_iframe_sdk/types/embed";
import { useSdkIframeEmbedSetupContext } from "../context";
-import { getEmbedCustomElementSnippet } from "../utils/embed-snippet";
import { getConfigurableThemeColors } from "../utils/theme-colors";
+import S from "./SdkIframeEmbedPreview.module.css";
+
declare global {
interface Window {
metabaseConfig: Partial<SdkIframeEmbedBaseSettings>;
@@ -20,77 +21,28 @@ declare global {
}
export const SdkIframeEmbedPreview = () => {
- const [isIframeLoaded, setIsIframeLoaded] = useState(false);
-
const { settings, isEmbedSettingsLoaded, experience } =
useSdkIframeEmbedSetupContext();
- const embedRef = useRef<MetabaseEmbedElement | null>(null);
const localeOverride = useSearchParam("locale");
const scriptRef = useRef<HTMLScriptElement | null>(null);
const instanceUrl = useSetting("site-url");
const applicationColors = useSetting("application-colors");
- // TODO(EMB-696): There is a bug in the SDK where if we set the theme back to undefined,
- // some color will not be reset to the default (e.g. text color, CSS variables).
- // We can remove this block once EMB-696 is fixed.
- const defaultTheme: MetabaseTheme = useMemo(() => {
- const colors = Object.fromEntries(
- getConfigurableThemeColors().map((color) => [
- color.key,
- applicationColors?.[color.originalColorKey] ??
- defaultMetabaseColors[color.originalColorKey],
- ]),
- );
-
- return { colors };
- }, [applicationColors]);
+ const defineMetabaseConfig = useCallback(
+ (metabaseConfig: SdkIframeEmbedBaseSettings) => {
+ window.metabaseConfig = metabaseConfig;
+ },
+ [],
+ );
useEffect(
() => {
if (isEmbedSettingsLoaded) {
const script = document.createElement("script");
-
script.src = `${instanceUrl}/app/embed.js`;
document.body.appendChild(script);
-
- const defineMetabaseConfig = (args: SdkIframeEmbedBaseSettings) => {
- window.metabaseConfig = args;
- };
-
- script.onload = () => {
- defineMetabaseConfig({
- instanceUrl,
- useExistingUserSession: true,
- theme: settings.theme,
- ...(localeOverride ? { locale: localeOverride } : {}),
- });
-
- const wrapperDiv = document.getElementById("iframe-embed-container");
- if (!wrapperDiv) {
- console.error("#iframe-embed-container not found");
- return;
- }
-
- wrapperDiv.innerHTML = getEmbedCustomElementSnippet({
- settings,
- experience,
- id: "custom-element-id",
- });
-
- const customElement = document.getElementById(
- "custom-element-id",
- ) as MetabaseEmbedElement;
- embedRef.current = customElement;
-
- customElement.style.height = "100%";
-
- embedRef.current.addEventListener("ready", () =>
- setIsIframeLoaded(true),
- );
- };
-
scriptRef.current = script;
}
@@ -103,31 +55,86 @@ export const SdkIframeEmbedPreview = () => {
[isEmbedSettingsLoaded, experience],
);
- useEffect(() => {
- if (embedRef.current) {
- embedRef.current.updateSettings({
- // Clear the existing experiences.
- // This is necessary as `updateSettings` merges new settings with existing ones.
- template: undefined,
- questionId: undefined,
- dashboardId: undefined,
-
- // We must always use user sessions in the preview.
- // We never use SSO in the preview as that adds complexity.
- ..._.omit(settings, ["useExistingUserSession"]),
+ // TODO(EMB-696): There is a bug in the SDK where if we set the theme back to undefined,
+ // some color will not be reset to the default (e.g. text color, CSS variables).
+ // We can remove this block once EMB-696 is fixed.
+ const defaultTheme: MetabaseTheme = useMemo(() => {
+ const colors = Object.fromEntries(
+ getConfigurableThemeColors().map((color) => [
+ color.key,
+ applicationColors?.[color.originalColorKey] ??
+ defaultMetabaseColors[color.originalColorKey],
+ ]),
+ );
+ return { colors };
+ }, [applicationColors]);
- // Fallback to the default theme if not set due to the bug mentioned above.
- theme: settings.theme ?? defaultTheme,
- });
- }
- }, [settings, isIframeLoaded, defaultTheme]);
+ useEffect(() => {
+ defineMetabaseConfig({
+ instanceUrl,
+ useExistingUserSession: true,
+ theme: settings.theme ?? defaultTheme,
+ ...(localeOverride ? { locale: localeOverride } : {}),
+ });
+ }, [
+ instanceUrl,
+ localeOverride,
+ settings.theme,
+ defineMetabaseConfig,
+ defaultTheme,
+ ]);
return (
<Card
+ className={S.EmbedPreviewIframe}
id="iframe-embed-container"
- data-iframe-loaded={isIframeLoaded}
bg={settings.theme?.colors?.background}
h="100%"
- />
+ >
+ {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,
+ }),
+ )
+ .with({ componentName: "metabase-question" }, (s) =>
+ createElement("metabase-question", {
+ "question-id": s.questionId,
+ drills: s.drills,
+ "with-title": s.withTitle,
+ "with-downloads": s.withDownloads,
+ "initial-sql-parameters": s.initialSqlParameters
+ ? JSON.stringify(s.initialSqlParameters)
+ : undefined,
+ "is-save-enabled": s.isSaveEnabled,
+ "target-collection": s.targetCollection,
+ "entity-types": s.entityTypes
+ ? JSON.stringify(s.entityTypes)
+ : undefined,
+ }),
+ )
+ .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,
+ }),
+ )
+ .exhaustive()}
+ </Card>
);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/utils/default-embed-setting.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/utils/default-embed-setting.ts
index 2cb81dbe05e..fb97bc1e60c 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/utils/default-embed-setting.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/utils/default-embed-setting.ts
@@ -19,6 +19,7 @@ export const getDefaultSdkIframeEmbedSettings = (
.with(
"dashboard",
(): DashboardEmbedOptions => ({
+ componentName: "metabase-dashboard",
dashboardId: defaultResourceId,
drills: true,
withDownloads: false,
@@ -28,6 +29,7 @@ export const getDefaultSdkIframeEmbedSettings = (
.with(
"chart",
(): QuestionEmbedOptions => ({
+ componentName: "metabase-question",
questionId: defaultResourceId,
drills: true,
withDownloads: false,
@@ -38,6 +40,7 @@ export const getDefaultSdkIframeEmbedSettings = (
.with(
"exploration",
(): ExplorationEmbedOptions => ({
+ componentName: "metabase-question",
template: "exploration",
isSaveEnabled: false,
}),