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
Improve loader overlay for a data app (#78111)
Timofey Kachalov7c3311ba3521
diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.tsindex 981d108f00a..227c82b0c31 100644--- a/e2e/support/helpers/e2e-data-app-helpers.ts+++ b/e2e/support/helpers/e2e-data-app-helpers.ts@@ -73,6 +73,12 @@ type MockDataAppOptions<TestEnv> = {* type as `TestEnv` if it differs.*/testEnv?: TestEnv;+ /**+ * Hold the bundle response for this many ms, so the app's loading window is+ * long enough to assert on. Without it a small mocked bundle can render before+ * the test ever queries, making any "still loading" assertion racy.+ */+ bundleDelay?: number;};/**@@ -114,6 +120,7 @@ export const mockDataApp = <TestEnv = DataAppTestEnv>("X-Metabase-Data-App-Allowed-Hosts": JSON.stringify(allowedHosts),},body: prelude + bundleCode,+ ...(options.bundleDelay ? { delay: options.bundleDelay } : {}),},);diff --git a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts b/e2e/test/scenarios/data-apps/viewing.cy.spec.tsindex 7dce3a756c3..dcebe8f9114 100644--- a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/viewing.cy.spec.ts@@ -67,6 +67,29 @@ describe("scenarios > data apps > viewing & routing", () => {});});+ describe("loading state", () => {+ it("keeps the loader up until the app's bundle has actually rendered", () => {+ H.mockDataApp(APP_NAME, {+ displayName: APP_DISPLAY_NAME,+ testEnv: TEST_ENV,+ bundleDelay: 2000,+ });++ H.openDataApp(APP_NAME);++ cy.findByTestId("data-app-loading").should("be.visible");++ cy.findByTestId("data-app-loading", { timeout: 30000 }).should(+ "not.exist",+ );+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByRole("heading", { name: "Orders overview" }).should(+ "be.visible",+ );+ });+ });+ });+describe("internal routing", () => {it("mirrors internal route changes into the parent URL", () => {H.mockDataApp(APP_NAME, {diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsxindex 2a8f9bf9109..01048eff4b5 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx@@ -1,5 +1,5 @@import cx from "classnames";-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { t } from "ttag";import { EmptyState } from "metabase/common/components/EmptyState";@@ -13,11 +13,13 @@ import { useGetDataAppQuery } from "metabase-enterprise/api";import {DATA_APP_ERROR_MESSAGE_TYPE,+ DATA_APP_READY_MESSAGE_TYPE,type DataAppBundleErrorMessage,} from "../../constants";import { attachIframeUrlMirror } from "../../lib/attach-iframe-url-mirror";import { deriveIframeSrc } from "../../lib/derive-iframe-src";import { isCrossOriginError } from "../../lib/is-cross-origin-error";+import { isDataAppMessage } from "../../lib/is-data-app-message";import S from "./DataAppView.module.css";@@ -25,18 +27,6 @@ interface AppViewProps {params: { name: string };}-/** The iframe can post anything; only trust objects tagged with our error type. */-function isBundleErrorMessage(- data: unknown,-): data is Partial<DataAppBundleErrorMessage> {- return (- typeof data === "object" &&- data !== null &&- "type" in data &&- data.type === DATA_APP_ERROR_MESSAGE_TYPE- );-}-/*** /apps/:name(/*) — renders the requested data-app inside an isolated* iframe, mirroring the iframe's internal route into the parent's URL.@@ -56,27 +46,25 @@ function isBundleErrorMessage(export function DataAppView({ params }: AppViewProps) {const name = params.name;const validName = typeof name === "string" && name.length > 0;- // Callback ref (vs `useRef`) — fires when the iframe element actually- // mounts. The iframe is conditionally rendered (only after `meta`- // resolves), so a `useEffect` keyed on `[name, validName]` alone would- // run before the iframe exists and silently skip.- const [iframeEl, setIframeEl] = useState<HTMLIFrameElement | null>(null);-- // The iframe is blank until its document + bundles finish downloading (the- // in-iframe `BundleHost` loader only appears once its React app mounts), so we- // cover it with a loader here until its `load` event fires.- const [iframeLoaded, setIframeLoaded] = useState(false);-- // Errors that happen *inside* the iframe (bundle fetch failed, or the bundle- // crashed at runtime) are reported up to here via `postMessage` so we can- // render the failure screen in the host realm — where it matches the rest of- // the app's theme exactly, instead of fighting the SDK theme inside the frame.++ const iframeRef = useRef<HTMLIFrameElement | null>(null);+ const [iframeEl, setIframeElState] = useState<HTMLIFrameElement | null>(null);+ const setIframeEl = useCallback((el: HTMLIFrameElement | null) => {+ iframeRef.current = el;+ setIframeElState(el);+ }, []);++ const [appReady, setAppReady] = useState(false);const [bundleError, setBundleError] =useState<DataAppBundleErrorMessage | null>(null);- // Reset whenever we navigate to a different app so a stale error doesn't stick.+ // Reset whenever we navigate to a different app so a stale error/ready state+ // doesn't stick (the next app must re-earn the overlay being dropped).// Note: this currently is not possible, but may happen if we show apps in the left nav menu- useEffect(() => setBundleError(null), [name]);+ useEffect(() => {+ setBundleError(null);+ setAppReady(false);+ }, [name]);// Read parent path → iframe src ONCE; never re-derive on later renders.const src = useMemo(@@ -99,8 +87,6 @@ export function DataAppView({ params }: AppViewProps) {let detach: (() => void) | null = null;const onLoad = () => {- setIframeLoaded(true);-// The iframe can navigate cross-origin — a form submitting to an allowed// external host, or the chrome-error page from a blocked navigation — and a// cross-origin `contentWindow` throws on access. Mirroring only works@@ -138,32 +124,39 @@ export function DataAppView({ params }: AppViewProps) {}, [iframeEl, name, validName]);useEffect(() => {- if (!iframeEl) {- return undefined;- }-const onMessage = (event: MessageEvent) => {+ if (event.origin !== window.location.origin) {+ return;+ }++ const iframeWindow = iframeRef.current?.contentWindow;+// Only trust messages from our own iframe- if (event.source !== iframeEl.contentWindow) {+ if (!iframeWindow || event.source !== iframeWindow) {return;}const data: unknown = event.data;- if (isBundleErrorMessage(data)) {+ if (isDataAppMessage(data, DATA_APP_ERROR_MESSAGE_TYPE)) {setBundleError({type: DATA_APP_ERROR_MESSAGE_TYPE,notReady: Boolean(data.notReady),message: typeof data.message === "string" ? data.message : undefined,stack: typeof data.stack === "string" ? data.stack : undefined,});+ return;+ }++ if (isDataAppMessage(data, DATA_APP_READY_MESSAGE_TYPE)) {+ setAppReady(true);}};window.addEventListener("message", onMessage);return () => window.removeEventListener("message", onMessage);- }, [iframeEl]);+ }, []);if (!validName) {return (@@ -249,9 +242,13 @@ export function DataAppView({ params }: AppViewProps) {return (<Box pos="relative" h="100%">- {!iframeLoaded && (- <Box pos="absolute" style={{ inset: 0, zIndex: 1 }}>- <LoadingAndErrorWrapper loading />+ {!appReady && (+ <Box+ pos="absolute"+ bg="background-primary"+ style={{ inset: 0, zIndex: 1 }}+ >+ <LoadingAndErrorWrapper loading data-testid="data-app-loading" /></Box>)}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsxindex a2281566a92..d45a6a54957 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx@@ -4,7 +4,10 @@ import { renderWithProviders, screen } from "__support__/ui";import { useGetDataAppQuery } from "metabase-enterprise/api";import { createMockDataApp } from "metabase-types/api/mocks";-import { DATA_APP_ERROR_MESSAGE_TYPE } from "../../constants";+import {+ DATA_APP_ERROR_MESSAGE_TYPE,+ DATA_APP_READY_MESSAGE_TYPE,+} from "../../constants";import { DataAppView } from "./DataAppView";@@ -69,9 +72,15 @@ describe("DataAppView", () => {});/** Post a `message` event as if it came from `source`. */- function postMessage(source: MessageEventSource | null, data: unknown) {+ function postMessage(+ source: MessageEventSource | null,+ data: unknown,+ origin: string = window.location.origin,+ ) {act(() => {- window.dispatchEvent(new MessageEvent("message", { data, source }));+ window.dispatchEvent(+ new MessageEvent("message", { data, source, origin }),+ );});}@@ -119,4 +128,51 @@ describe("DataAppView", () => {).not.toBeInTheDocument();expect(screen.getByTitle("Sales")).toBeInTheDocument();});++ it("ignores messages from another origin, even sent through its own frame", () => {+ const iframe = setupIframe();++ postMessage(+ iframe.contentWindow,+ { type: DATA_APP_ERROR_MESSAGE_TYPE, notReady: true },+ "https://not-metabase.example.com",+ );++ expect(+ screen.queryByText("This data app isn’t ready yet"),+ ).not.toBeInTheDocument();+ });++ describe("loading overlay", () => {+ it("covers the frame until the app reports it's on screen", () => {+ const iframe = setupIframe();++ expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();++ postMessage(iframe.contentWindow, { type: DATA_APP_READY_MESSAGE_TYPE });++ expect(screen.queryByTestId("data-app-loading")).not.toBeInTheDocument();+ });++ it("stays up on the iframe's load event alone — that fires before the bundle renders", () => {+ const iframe = setupIframe();++ // The frame's document is parsed, but the bundle hasn't been fetched,+ // sandboxed or drawn yet. Lifting the overlay here is what caused the+ // white flash, so `load` must not dismiss it.+ act(() => {+ iframe.dispatchEvent(new Event("load"));+ });++ expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();+ });++ it("ignores a ready message that isn't from its own iframe", () => {+ setupIframe();++ postMessage(window, { type: DATA_APP_READY_MESSAGE_TYPE });++ expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();+ });+ });});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/constants.tsindex 0552f852cbf..49df2b1f754 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts@@ -1,8 +1,3 @@-/**- * `postMessage` type the iframe-top app (`DataAppIframeApp`) sends to the host- * (`AppView`) when the bundle can't be loaded or crashes at runtime, so the host- * can render the failure screen in its own (correctly themed) realm.- */export const DATA_APP_ERROR_MESSAGE_TYPE = "metabase.data-app.error" as const;export type DataAppBundleErrorMessage = {@@ -14,3 +9,5 @@ export type DataAppBundleErrorMessage = {/** The error's stack, when one could be read. */stack?: string;};++export const DATA_APP_READY_MESSAGE_TYPE = "metabase.data-app.ready" as const;diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.tsnew file mode 100644index 00000000000..5174073931e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.ts@@ -0,0 +1,11 @@+export function isDataAppMessage<Type extends string>(+ data: unknown,+ type: Type,+): data is { type: Type } & Record<string, unknown> {+ return (+ typeof data === "object" &&+ data !== null &&+ "type" in data &&+ data.type === type+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.unit.spec.tsnew file mode 100644index 00000000000..f3054c1c76b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.unit.spec.ts@@ -0,0 +1,49 @@+import {+ DATA_APP_ERROR_MESSAGE_TYPE,+ DATA_APP_READY_MESSAGE_TYPE,+} from "../constants";++import { isDataAppMessage } from "./is-data-app-message";++describe("isDataAppMessage", () => {+ it("accepts an object tagged with the given type, whatever else it carries", () => {+ expect(+ isDataAppMessage(+ { type: DATA_APP_ERROR_MESSAGE_TYPE, notReady: true },+ DATA_APP_ERROR_MESSAGE_TYPE,+ ),+ ).toBe(true);++ expect(+ isDataAppMessage(+ { type: DATA_APP_READY_MESSAGE_TYPE },+ DATA_APP_READY_MESSAGE_TYPE,+ ),+ ).toBe(true);+ });++ it("rejects a different message type, so the two handshakes can't be confused", () => {+ expect(+ isDataAppMessage(+ { type: DATA_APP_READY_MESSAGE_TYPE },+ DATA_APP_ERROR_MESSAGE_TYPE,+ ),+ ).toBe(false);+ });++ it.each([+ null,+ undefined,+ "metabase.data-app.ready",+ 42,+ [],+ {},+ { type: undefined },+ { notReady: true },+ ])(+ "rejects %p, which isn't a tagged object — the frame can post arbitrary data",+ (data) => {+ expect(isDataAppMessage(data, DATA_APP_READY_MESSAGE_TYPE)).toBe(false);+ },+ );+});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsxindex fe2cc446371..752eea53f84 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx@@ -1,4 +1,10 @@-import { Component, type ErrorInfo, type ReactNode, useMemo } from "react";+import {+ Component,+ type ErrorInfo,+ type ReactNode,+ useEffect,+ useMemo,+} from "react";import { t } from "ttag";import { Center, Loader } from "metabase/ui";@@ -7,6 +13,7 @@ import { color } from "metabase/ui/colors";import { type ErrorDetail, describeError } from "../../lib/describe-error";import { readNameFromUrl } from "../../lib/read-name-from-url";import { reportErrorToParent } from "../../lib/report-error-to-parent";+import { reportReadyToParent } from "../../lib/report-ready-to-parent";import { useDataAppBundle } from "../../lib/use-data-app-bundle";import { DataAppProvider } from "../DataAppProvider/DataAppProvider";@@ -65,6 +72,12 @@ class BundleErrorBoundary extends Component<function BundleHost({ name }: { name: string }) {const { data, failed } = useDataAppBundle(name);+ useEffect(() => {+ if (data && !failed) {+ reportReadyToParent();+ }+ }, [data, failed]);+// On failure we report the error up to the host `AppView` (see// `reportErrorToParent`), which renders the themed failure screen in its own// realm and unmounts this iframe. Until that handoff lands we show a neutraldiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.tsindex db4ac959457..59ec9095337 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts@@ -2,12 +2,6 @@ import { DATA_APP_ERROR_MESSAGE_TYPE } from "../../constants";import type { ErrorDetail } from "./describe-error";-/**- * Report a bundle failure up to the host `AppView` (the parent window) so it can- * render the failure screen in its own realm, where it's themed exactly like the- * rest of the app — instead of trying (and failing) to match the host's theme- * from inside the SDK-themed iframe.- */export function reportErrorToParent(notReady: boolean, detail?: ErrorDetail) {if (window.parent === window) {return;@@ -20,6 +14,6 @@ export function reportErrorToParent(notReady: boolean, detail?: ErrorDetail) {message: detail?.message,stack: detail?.stack,},- "*",+ window.location.origin,);}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-ready-to-parent.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-ready-to-parent.tsnew file mode 100644index 00000000000..c749bed26af--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-ready-to-parent.ts@@ -0,0 +1,12 @@+import { DATA_APP_READY_MESSAGE_TYPE } from "../../constants";++export function reportReadyToParent() {+ if (window.parent === window) {+ return;+ }++ window.parent.postMessage(+ { type: DATA_APP_READY_MESSAGE_TYPE },+ window.location.origin,+ );+}