Skip to content

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

Fixed InteractiveQuestion and StaticQuestion flashing the "run your code" empty state instead of a loader while `card.query` is still unresolved (#82693)

Timofey Kachalovd0ce86c19e5c
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx
index 44dc7023f74..13e0b1f275b 100644
--- a/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx
@@ -3,6 +3,7 @@ import {
type MetabaseCard,
StaticQuestion,
} from "@metabase/embedding-sdk-react";
+import { useState } from "react";
import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
@@ -11,6 +12,8 @@ import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-tes
import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+const { H } = cy;
+
const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
// What a data app actually passes: a `card` object built from a query (e.g. the
@@ -72,4 +75,101 @@ describe("scenarios > embedding-sdk > sdk-question card prop", () => {
cy.findByTestId("table-root").should("not.exist");
});
});
+
+ describe("card with a not-yet-resolved query (EMB-2390)", () => {
+ // Data apps mount the question as soon as `useMetabaseQueryObject` returns,
+ // whose `query` is null until it resolves. The SDK must keep showing its
+ // loader for that window and never fall through to the "run your code"
+ // empty state that belongs to a blank question.
+ const EMPTY_STATE_SELECTOR = 'img[alt="Code prompt icon"]';
+ const VISUALIZATION_SELECTOR = '[data-testid="visualization-root"]';
+ const PENDING_QUERY_HOLD_MS = 1500;
+
+ function assertEmptyStateNeverShownWhilePending() {
+ cy.window().then((win) => {
+ return new Cypress.Promise((resolve, reject) => {
+ const startedAt = Date.now();
+
+ const checkInterval = setInterval(() => {
+ if (win.document.querySelector(EMPTY_STATE_SELECTOR)) {
+ clearInterval(checkInterval);
+ reject(
+ new Error(
+ "the empty results state must not show while `card.query` is null",
+ ),
+ );
+ } else if (Date.now() - startedAt >= PENDING_QUERY_HOLD_MS) {
+ clearInterval(checkInterval);
+ resolve();
+ }
+ }, 20);
+ });
+ });
+ }
+
+ function assertEmptyStateNeverShownWhileResolving() {
+ H.assertElementNeverExists({
+ shouldNotExistSelector: EMPTY_STATE_SELECTOR,
+ successSelector: VISUALIZATION_SELECTOR,
+ rejectionMessage:
+ "the empty results state must not flash between the query resolving and the results rendering",
+ pollInterval: 20,
+ timeout: 15000,
+ });
+ }
+
+ function DeferredInteractiveQuestion() {
+ const [query, setQuery] = useState<MetabaseCard["query"]>(null);
+
+ return (
+ <div>
+ <InteractiveQuestion card={{ ...card, query }} />
+ <button onClick={() => setQuery(card.query)}>Resolve query</button>
+ </div>
+ );
+ }
+
+ function DeferredStaticQuestion() {
+ const [query, setQuery] = useState<MetabaseCard["query"]>(null);
+
+ return (
+ <div>
+ <StaticQuestion card={{ ...card, query }} />
+ <button onClick={() => setQuery(card.query)}>Resolve query</button>
+ </div>
+ );
+ }
+
+ it("InteractiveQuestion should show a loader instead of the empty results state until `card.query` resolves", () => {
+ mountSdkContent(<DeferredInteractiveQuestion />);
+
+ getSdkRoot().within(() => {
+ assertEmptyStateNeverShownWhilePending();
+ cy.findByTestId("loading-indicator").should("be.visible");
+ });
+
+ cy.findByRole("button", { name: "Resolve query" }).click();
+ assertEmptyStateNeverShownWhileResolving();
+
+ getSdkRoot().within(() => {
+ cy.findByTestId("visualization-root").should("be.visible");
+ });
+ });
+
+ it("StaticQuestion should show a loader instead of the empty results state until `card.query` resolves", () => {
+ mountSdkContent(<DeferredStaticQuestion />);
+
+ getSdkRoot().within(() => {
+ assertEmptyStateNeverShownWhilePending();
+ cy.findByTestId("loading-indicator").should("be.visible");
+ });
+
+ cy.findByRole("button", { name: "Resolve query" }).click();
+ assertEmptyStateNeverShownWhileResolving();
+
+ getSdkRoot().within(() => {
+ cy.findByTestId("visualization-root").should("be.visible");
+ });
+ });
+ });
});
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
index 8e9c541652b..755748f2548 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
@@ -12,6 +12,10 @@ import {
setupTableEndpoints,
setupUnauthorizedCardEndpoints,
} from "__support__/server-mocks";
+import {
+ setupAdhocQueryMetadataEndpoint,
+ setupCardDataset,
+} from "__support__/server-mocks/dataset";
import { setupEntityIdEndpoint } from "__support__/server-mocks/entity-id";
import {
act,
@@ -33,7 +37,7 @@ import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui
import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
import type { SdkQuestionTitleProps } from "embedding-sdk-bundle/types/question";
-import type { BaseEntityId, CardId } from "metabase-types/api";
+import type { BaseEntityId, CardId, UnsavedCard } from "metabase-types/api";
import {
createMockCard,
createMockCardQueryMetadata,
@@ -44,6 +48,7 @@ import {
createMockDatasetData,
createMockParameter,
createMockTable,
+ createMockUnsavedCard,
createMockUser,
} from "metabase-types/api/mocks";
import { createMockEntityId } from "metabase-types/api/mocks/entity-id";
@@ -124,6 +129,7 @@ const setup = async ({
withChartTypeSelector = false,
initialSqlParameters,
cardId = TEST_CARD_ID,
+ deserializedCard,
preventWaitForLoader = false,
mockNavigation,
}: Partial<
@@ -132,6 +138,7 @@ const setup = async ({
isValidCard?: boolean;
withCustomLayout?: boolean;
cardId: BaseEntityId | CardId | null;
+ deserializedCard?: UnsavedCard;
preventWaitForLoader?: boolean;
mockNavigation?: SdkInternalNavigationContextValue;
}
@@ -157,6 +164,10 @@ const setup = async ({
setupTableEndpoints(TEST_TABLE);
setupCardQueryEndpoints(TEST_CARD, TEST_DATASET);
+ setupCardDataset({ dataset: TEST_DATASET });
+ setupAdhocQueryMetadataEndpoint(
+ createMockCardQueryMetadata({ databases: [TEST_DB], tables: [TEST_TABLE] }),
+ );
setupEntityIdEndpoint({ card: { [TEST_ENTITY_ID]: TEST_CARD_ID } });
@@ -178,6 +189,7 @@ const setup = async ({
<SdkInternalNavigationContext.Provider value={mockNavigation ?? null}>
<SdkQuestion
questionId={cardId}
+ deserializedCard={deserializedCard}
title={title}
withChartTypeSelector={withChartTypeSelector}
initialSqlParameters={initialSqlParameters}
@@ -384,10 +396,24 @@ describe("InteractiveQuestion", () => {
expect(screen.getByTestId("query-visualization-root")).toBeInTheDocument();
});
+ it("should keep showing the loader while there is no question source yet (EMB-2390)", async () => {
+ await setup({ cardId: null, preventWaitForLoader: true });
+
+ expect(await screen.findByTestId("loading-indicator")).toBeInTheDocument();
+ expect(
+ screen.queryByText(/To run your code, click on the Run button/),
+ ).not.toBeInTheDocument();
+ expect(fetchMock.callHistory.calls("dataset-post")).toHaveLength(0);
+ });
+
describe("navigation stack initialization", () => {
it("should push a question entry with id=null for an ad-hoc question (questionId is null)", async () => {
const mockNavigation = makeMockNavigation();
- await setup({ cardId: null, mockNavigation });
+ await setup({
+ cardId: null,
+ deserializedCard: createMockUnsavedCard(),
+ mockNavigation,
+ });
expect(mockNavigation.push).toHaveBeenCalledWith({
type: "question",
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.ts
index 8c1a63c6fee..f9779f17af0 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
@@ -117,14 +117,17 @@ export function useLoadQuestion({
const sqlParameterKey = getParameterDependencyKey(initialSqlParameters);
const shouldLoadQuestion = questionId != null || deserializedCard != null;
- const [isQuestionLoading, setIsQuestionLoading] =
- useState(shouldLoadQuestion);
+ const [isLoadInFlight, setIsLoadInFlight] = useState(shouldLoadQuestion);
+
+ const isQuestionLoading = isLoadInFlight || !shouldLoadQuestion;
const [, loadAndQueryQuestion] = useAsyncFn(async () => {
- if (shouldLoadQuestion) {
- setIsQuestionLoading(true);
+ if (!shouldLoadQuestion) {
+ return {};
}
+ setIsLoadInFlight(true);
+
try {
const questionState = await dispatch(
loadQuestionSdk({
@@ -152,7 +155,7 @@ export function useLoadQuestion({
mergeQuestionState(results);
- setIsQuestionLoading(false);
+ setIsLoadInFlight(false);
return { ...results, originalQuestion };
} catch (err) {
// Ignore cancelled requests (e.g. when the component unmounts, or when a
@@ -160,7 +163,7 @@ export function useLoadQuestion({
// shared `controllerRef`). React simulates unmounting on strict mode,
// therefore "Question not found" will be shown without this.
if (isAbortError(err)) {
- setIsQuestionLoading(false);
+ setIsLoadInFlight(false);
return {};
}
@@ -180,7 +183,7 @@ export function useLoadQuestion({
parameterValues: undefined,
});
- setIsQuestionLoading(false);
+ setIsLoadInFlight(false);
return {};
}
}, [