Skip to content

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

Clean up `metabase/utils/embed` (#72615)

Romeo Van Snickf78efe0f4b3f
diff --git a/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.ts
index b0df33b76d2..f99c7b982cd 100644
--- a/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.ts
+++ b/e2e/support/helpers/e2e-embedding-iframe-interactive-helpers.ts
@@ -47,7 +47,7 @@ export function postMessageToIframe(options: PostMessageOptions) {
const { messageData, iframeSelector } = options;
// this madness is necessary to simulate a real MessageEvent coming from the parent window
- // because in frontend/src/metabase/utils/embed.js we check e.source === window.parent
+ // because in frontend/src/metabase/embedding/interactive-embedding/initialize we check e.source === window.parent
cy.get(iframeSelector)
.should("be.visible")
.then(($iframe) => {
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index 31fa232528d..d89c0c8398e 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -33,13 +33,13 @@ import { initializePlugins } from "ee-plugins";
import { AppThemeProvider } from "metabase/AppThemeProvider";
import { ModifiedBackend } from "metabase/common/components/dnd/ModifiedBackend";
import registerDashboardVisualizations from "metabase/dashboard/visualizations/register";
+import { initializeInteractiveEmbedding } from "metabase/embedding/interactive-embedding";
import { MetabotProvider } from "metabase/metabot/context";
import { PLUGIN_APP_INIT_FUNCTIONS } from "metabase/plugins";
import { refreshSiteSettings } from "metabase/redux/settings";
import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles";
import { EmotionCacheProvider } from "metabase/ui/components/theme/EmotionCacheProvider";
import api from "metabase/utils/api";
-import { initializeEmbedding } from "metabase/utils/embed";
import { captureConsoleErrors } from "metabase/utils/errors";
import { initTracing, rotateTraceId } from "metabase/utils/otel";
import { MetabaseReduxProvider } from "metabase/utils/redux/custom-context";
@@ -79,7 +79,7 @@ function _init(reducers, getRoutes, callback) {
syncedHistory.listen(() => rotateTraceId());
}
- initializeEmbedding(store);
+ initializeInteractiveEmbedding(store.dispatch);
const root = createRoot(document.getElementById("root"));
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
index aa5955fa1e9..10c4a5c406e 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
@@ -6,8 +6,8 @@ import { usePrevious } from "react-use";
import _ from "underscore";
import { useSetting } from "metabase/common/hooks";
+import { isEmbedPreview } from "metabase/embedding/config";
import { selectTab } from "metabase/redux/dashboard";
-import { IS_EMBED_PREVIEW } from "metabase/utils/embed";
import { useDispatch, useSelector } from "metabase/utils/redux";
import * as Urls from "metabase/utils/urls";
import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";
@@ -57,7 +57,7 @@ export function useDashboardUrlQuery(
* This causes the iframe to reload when changing the preview hash from appearance
* settings because now the base URL (including the query string) is different.
*/
- if (IS_EMBED_PREVIEW || !dashboardId) {
+ if (isEmbedPreview() || !dashboardId) {
return;
}
diff --git a/frontend/src/metabase/embedding/config.ts b/frontend/src/metabase/embedding/config.ts
index fcb6117bbf8..160d5d7ff72 100644
--- a/frontend/src/metabase/embedding/config.ts
+++ b/frontend/src/metabase/embedding/config.ts
@@ -1,5 +1,5 @@
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import { isWithinIframe } from "metabase/utils/iframe";
+import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";
type InternalEmbeddingConfig = {
isPublicEmbedding: boolean;
@@ -30,3 +30,11 @@ export function isStaticEmbedding() {
export function isEmbedding() {
return isWithinIframe() || isEmbeddingSdk();
}
+
+/**
+ * Detect if this page is embedded in itself, i.e. it's an embed preview.
+ * It will need to do something different if we ever embed Metabase in itself for another reason.
+ */
+export function isEmbedPreview() {
+ return IFRAMED_IN_SELF;
+}
diff --git a/frontend/src/metabase/embedding/interactive-embedding/index.ts b/frontend/src/metabase/embedding/interactive-embedding/index.ts
new file mode 100644
index 00000000000..048cfe5bb93
--- /dev/null
+++ b/frontend/src/metabase/embedding/interactive-embedding/index.ts
@@ -0,0 +1 @@
+export * from "./initialize";
diff --git a/frontend/src/metabase/embedding/interactive-embedding/initialize.ts b/frontend/src/metabase/embedding/interactive-embedding/initialize.ts
new file mode 100644
index 00000000000..8ed2a7bbfb5
--- /dev/null
+++ b/frontend/src/metabase/embedding/interactive-embedding/initialize.ts
@@ -0,0 +1,112 @@
+import { push } from "react-router-redux";
+import _ from "underscore";
+
+import CS from "metabase/css/core/index.css";
+import { setInitialUrlOptions } from "metabase/redux/embed";
+import type { Dispatch } from "metabase/redux/store";
+import { isWithinIframe } from "metabase/utils/iframe";
+
+export type FrameSpec = {
+ mode: "normal" | "fit";
+ height: number;
+};
+
+export function initializeInteractiveEmbedding(dispatch: Dispatch) {
+ if (isWithinIframe()) {
+ let currentHref: string | undefined;
+ let currentFrame: FrameSpec | undefined;
+
+ // NOTE: history.listen and window's onhashchange + popstate events were not
+ // enough to catch all URL changes, so just poll for now :(
+ setInterval(() => {
+ const location = window.location;
+ if (currentHref !== location.href) {
+ sendMessage({
+ type: "location",
+ // extract just the string properties from window.location
+ location: _.pick(location, (v) => typeof v === "string"),
+ });
+ currentHref = location.href;
+ }
+ const frame = getFrameSpec();
+ if (!_.isEqual(currentFrame, frame)) {
+ sendMessage({ type: "frame", frame });
+ currentFrame = frame;
+ }
+ }, 100);
+ window.addEventListener("message", (e) => {
+ if (e.source === window.parent && e.data.metabase) {
+ if (e.data.metabase.type === "location") {
+ dispatch(push(e.data.metabase.location));
+ }
+ }
+ });
+ dispatch(setInitialUrlOptions(window.location));
+ }
+}
+
+type LocationMessage = {
+ type: "location";
+ location: Partial<Location>;
+};
+
+type FrameMessage = {
+ type: "frame";
+ frame: FrameSpec;
+};
+
+type Message = LocationMessage | FrameMessage;
+
+function sendMessage(message: Message) {
+ // Reason for using "*" (see #18824)
+ // 1) We cannot use MetabaseSettings.get("embedding-app-origin") because the format is different
+ // - the setting value can have multiple URLs but postMessage only supports one URL
+ // - the setting value support wildcard in subdomain but postMessage does not
+ // 2) The risk should be very low because
+ // - the data we sent is not sensitive data (frame size, current URL)
+ // - we are already using frame ancestor policy to limit domains that can embed metabase
+ window.parent.postMessage({ metabase: message }, "*");
+}
+
+function isFitViewportMode() {
+ const root = document.getElementById("root");
+
+ // get the first div, which may be preceded by style nodes
+ const firstChild = root?.querySelector("div");
+
+ if (firstChild) {
+ return firstChild.classList.contains(CS.spread);
+ }
+ return false;
+}
+
+function getFrameSpec(): FrameSpec {
+ if (isFitViewportMode()) {
+ return { mode: "fit", height: getScrollHeight() };
+ } else {
+ return { mode: "normal", height: document.body.scrollHeight };
+ }
+}
+
+function defaultGetScrollHeight() {
+ return document.body.scrollHeight;
+}
+
+function getScrollHeight() {
+ const appBarHeight =
+ document.getElementById("[data-element-id=app-bar]")?.offsetHeight ?? 0;
+ const dashboardHeaderHeight =
+ document.querySelector<HTMLElement>(
+ "[data-element-id=dashboard-header-container]",
+ )?.offsetHeight ?? 0;
+ const dashboardContentHeight =
+ document.querySelector("[data-element-id=dashboard-parameters-and-cards]")
+ ?.scrollHeight ?? 0;
+ const dashboardHeight = dashboardHeaderHeight + dashboardContentHeight;
+
+ if (dashboardHeight > 0) {
+ return appBarHeight + dashboardHeight;
+ }
+
+ return defaultGetScrollHeight();
+}
diff --git a/frontend/src/metabase/get-is-embed-preview.ts b/frontend/src/metabase/get-is-embed-preview.ts
deleted file mode 100644
index 4b67473a051..00000000000
--- a/frontend/src/metabase/get-is-embed-preview.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { IS_EMBED_PREVIEW } from "metabase/utils/embed";
-
-/**
- * The only point of putting this into its own function
- * is so we can mock it up in tests.
- * @internal
- */
-export const getIsEmbedPreview = (): boolean => {
- return IS_EMBED_PREVIEW;
-};
diff --git a/frontend/src/metabase/query_builder/hooks/use-sync-url-parameters.ts b/frontend/src/metabase/query_builder/hooks/use-sync-url-parameters.ts
index c11c96f90d5..a632b678544 100644
--- a/frontend/src/metabase/query_builder/hooks/use-sync-url-parameters.ts
+++ b/frontend/src/metabase/query_builder/hooks/use-sync-url-parameters.ts
@@ -2,7 +2,7 @@ import querystring from "querystring";
import { useEffect, useMemo } from "react";
-import { IS_EMBED_PREVIEW } from "metabase/utils/embed";
+import { isEmbedPreview } from "metabase/embedding/config";
import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";
import type { Parameter } from "metabase-types/api";
@@ -27,7 +27,7 @@ export function useSyncUrlParameters({
* This causes the iframe to reload when changing the preview hash from appearance
* settings because now the base URL (including the query string) is different.
*/
- if (IS_EMBED_PREVIEW || !enabled) {
+ if (isEmbedPreview() || !enabled) {
return;
}
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index 4ee88fbfb28..ab89d9fc140 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -1,16 +1,15 @@
+import { isEmbedPreview } from "metabase/embedding/config";
import api, { DELETE, GET, POST, PUT } from "metabase/utils/api";
import Question from "metabase-lib/v1/Question";
import { normalizeParameters } from "metabase-lib/v1/parameters/utils/parameter-values";
import { isNative } from "metabase-lib/v1/queries/utils/card";
import { getPivotOptions } from "metabase-lib/v1/queries/utils/pivot";
-import { getIsEmbedPreview } from "./get-is-embed-preview";
-
export const internalBase = "/api";
export const publicBase = "/api/public";
// use different endpoints for embed previews
export function getEmbedBase() {
- return getIsEmbedPreview() ? "/api/preview_embed" : "/api/embed";
+ return isEmbedPreview() ? "/api/preview_embed" : "/api/embed";
}
export const ActivityApi = {
diff --git a/frontend/src/metabase/visualizations/lib/map.ts b/frontend/src/metabase/visualizations/lib/map.ts
index b142b2b7285..a2b162dffc9 100644
--- a/frontend/src/metabase/visualizations/lib/map.ts
+++ b/frontend/src/metabase/visualizations/lib/map.ts
@@ -1,4 +1,4 @@
-import { IS_EMBED_PREVIEW } from "metabase/utils/embed";
+import { isEmbedPreview as getIsEmbedPreview } from "metabase/embedding/config";
import { isJWT } from "metabase/utils/jwt";
import { isUuid } from "metabase/utils/uuid";
import type { DashboardId, JsonQuery, Parameter } from "metabase-types/api";
@@ -23,8 +23,9 @@ interface TileUrlParams {
parameters?: Parameter[];
/**
* Indicates whether the tile URL is being generated for a preview embed context.
- * You probably don't need to set this manually as it defaults to `IS_EMBED_PREVIEW` (it's used for tests).
- * @default IS_EMBED_PREVIEW
+ * You probably don't need to set this manually; it defaults to `isEmbedPreview()`
+ * from `metabase/embedding/config`.
+ * @defaultValue isEmbedPreview()
*/
isEmbedPreview?: boolean;
}
@@ -42,7 +43,7 @@ export function getTileUrl(params: TileUrlParams): string {
uuid,
token,
parameters,
- isEmbedPreview = IS_EMBED_PREVIEW,
+ isEmbedPreview = getIsEmbedPreview(),
} = params;
const isDashboard = dashboardId && dashcardId && cardId;