Skip to content

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

Replace dashboard loading spinner with an instant skeleton (DSN-749) (#83288)

Maz Ameli30d6158ea13f
diff --git a/frontend/src/metabase/dashboard/actions/core.ts b/frontend/src/metabase/dashboard/actions/core.ts
index 6ba6f4f8db6..a964aa8d1cd 100644
--- a/frontend/src/metabase/dashboard/actions/core.ts
+++ b/frontend/src/metabase/dashboard/actions/core.ts
@@ -164,3 +164,13 @@ export const FETCH_DASHBOARD_FULFILLED =
export const fetchDashboardFulfilled = createAction<
ReturnType<typeof fetchDashboard.fulfilled>["payload"]
>(FETCH_DASHBOARD_FULFILLED);
+
+/**
+ * Dispatched by `fetchDashboard` as soon as the dashboard definition arrives,
+ * before the slower query-metadata request finishes. It carries the same
+ * normalized entities the fulfilled action will, so the loading skeleton can
+ * draw the dashboard's real card layout without waiting for the full load.
+ */
+export const dashboardLayoutFetched = createAction<
+ ReturnType<typeof fetchDashboard.fulfilled>["payload"]["entities"]
+>("metabase/dashboard/DASHBOARD_LAYOUT_FETCHED");
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index d31e1c8bd04..3a02beb6079 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -22,6 +22,7 @@ import {
getDashCardById,
getDashboardById,
getDashboardComplete,
+ getDashboardId,
getLinkTargetEntities,
getLoadingDashCards,
getParameterValues,
@@ -71,6 +72,8 @@ import type {
} from "metabase-types/api";
import { isVisualizerDashboardCard } from "metabase-types/guards/dashboard";
+import { dashboardLayoutFetched } from "./core";
+
export const FETCH_DASHBOARD_CARD_DATA =
"metabase/dashboard/FETCH_DASHBOARD_CARD_DATA";
export const fetchDashboardCardDataAction = createAction<{
@@ -678,6 +681,30 @@ const dashboardSchema = new schema.Entity("dashboard", {
dashcards: [dashcardSchema],
});
+/**
+ * Copies each virtual card's definition (headings, text, links, ...) from the
+ * dashcard's visualization settings onto its `card`, which the backend leaves
+ * empty for virtual cards. The dashboard can come straight from RTK Query,
+ * whose responses are deeply frozen, so this builds new objects rather than
+ * mutating in place.
+ */
+function copyVirtualCardsToCards(dashboard: Dashboard): Dashboard {
+ return {
+ ...dashboard,
+ dashcards: dashboard.dashcards.map((dashcard) =>
+ isVirtualDashCard(dashcard)
+ ? {
+ ...dashcard,
+ card: {
+ ...dashcard.card,
+ ...dashcard.visualization_settings.virtual_card,
+ },
+ }
+ : dashcard,
+ ),
+ };
+}
+
let fetchDashboardCancellation: AbortController | null;
const EMPTY_LINK_TARGETS: DashboardLinkTargets = {
@@ -849,19 +876,41 @@ export const fetchDashboard = createAsyncThunk(
);
result = prefetchedDashboard;
} else {
+ const dashboardRequest = runRtkEndpoint(
+ { id: dashId, dashboard_load_id: dashboardLoadId },
+ dispatch,
+ dashboardApi.endpoints.getDashboard,
+ { signal: fetchDashboardCancellation.signal },
+ );
+ const queryMetadataRequest = runRtkEndpoint(
+ { id: dashId, dashboard_load_id: dashboardLoadId },
+ dispatch,
+ dashboardApi.endpoints.getDashboardQueryMetadata,
+ { forceRefetch: false },
+ );
+
+ // The dashboard definition already holds the card layout and usually
+ // arrives well before the query metadata, so publish it right away for
+ // the loading skeleton. Only on a fresh open: a dashboard that is
+ // already on screen never shows the skeleton.
+ const isOpeningDashboard = getDashboardId(getState()) === null;
+ if (isOpeningDashboard) {
+ dashboardRequest.then(
+ (response) =>
+ dispatch(
+ dashboardLayoutFetched(
+ normalize(copyVirtualCardsToCards(response), dashboardSchema)
+ .entities,
+ ),
+ ),
+ // A failed request is surfaced by the `Promise.all` below.
+ () => {},
+ );
+ }
+
const [response, queryMetadata] = await Promise.all([
- runRtkEndpoint(
- { id: dashId, dashboard_load_id: dashboardLoadId },
- dispatch,
- dashboardApi.endpoints.getDashboard,
- { signal: fetchDashboardCancellation.signal },
- ),
- runRtkEndpoint(
- { id: dashId, dashboard_load_id: dashboardLoadId },
- dispatch,
- dashboardApi.endpoints.getDashboardQueryMetadata,
- { forceRefetch: false },
- ),
+ dashboardRequest,
+ queryMetadataRequest,
]);
linkTargets = toLinkTargets(queryMetadata);
result = response;
@@ -871,24 +920,7 @@ export const fetchDashboard = createAsyncThunk(
const isUsingCachedResults = entities != null;
if (!isUsingCachedResults) {
- // Copy over any virtual cards from the dashcard to the underlying
- // card/question. The result can come straight from RTK Query, whose
- // responses are deeply frozen, so build new objects rather than
- // mutating in place.
- result = {
- ...result,
- dashcards: result.dashcards.map((card: DashboardCard) =>
- card.visualization_settings?.virtual_card
- ? {
- ...card,
- card: {
- ...(card.card ?? {}),
- ...card.visualization_settings.virtual_card,
- },
- }
- : card,
- ),
- };
+ result = copyVirtualCardsToCards(result);
}
if (result.param_fields) {
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts b/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts
index e8ffe87023d..d8c545bdb96 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts
@@ -13,9 +13,11 @@ import {
createMockStoreDashboard,
} from "__support__/state";
import { createMockEntitiesState } from "__support__/store";
+import { waitFor } from "__support__/ui";
import { Api } from "metabase/api";
import type { DashboardState, State } from "metabase/redux/store";
import { isQuestionDashCard } from "metabase/utils/dashboard";
+import { defer } from "metabase/utils/promise";
import type { Dashboard } from "metabase-types/api";
import {
createMockCard,
@@ -29,6 +31,7 @@ import {
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
import { dashboardReducers } from "../reducers";
+import { getLastSeenTabDashcards } from "../selectors";
import {
fetchCardDataAction,
@@ -79,6 +82,79 @@ function setup({
}
describe("fetchDashboard", () => {
+ describe("while the query metadata is still loading (DSN-749)", () => {
+ let queryMetadataRequest = defer();
+
+ const setupDeferredQueryMetadata = (dashboardId: number) => {
+ queryMetadataRequest = defer();
+ fetchMock.get(`path:/api/dashboard/${dashboardId}/query_metadata`, () =>
+ queryMetadataRequest.promise.then(() =>
+ createMockDashboardQueryMetadata(),
+ ),
+ );
+ };
+
+ // Never leave the request pending, or teardown waits on it when a test fails.
+ afterEach(() => queryMetadataRequest.resolve());
+
+ it("publishes the dashboard layout before the fetch finishes", async () => {
+ const dashboard = createMockDashboard({
+ id: 1,
+ dashcards: [createMockDashboardCard({ id: 10, dashboard_id: 1 })],
+ });
+ const store = setup();
+ setupDashboardsEndpoints([dashboard]);
+ setupDeferredQueryMetadata(1);
+
+ const fetchResult = store.dispatch(
+ fetchDashboard({ dashId: 1, queryParams: {}, options: {} }),
+ );
+
+ // The skeleton can draw the real layout while the dashboard still loads.
+ await waitFor(() => {
+ expect(getLastSeenTabDashcards(store.getState(), 1)).toHaveLength(1);
+ });
+ expect(store.getState().dashboard.dashboardId).toBeNull();
+
+ queryMetadataRequest.resolve();
+ await expect(fetchResult).resolves.toHaveProperty(
+ "type",
+ "metabase/dashboard/FETCH_DASHBOARD/fulfilled",
+ );
+ expect(store.getState().dashboard.dashboardId).toBe(1);
+ });
+
+ it("does not publish the layout early when refetching a dashboard that is already on screen", async () => {
+ const store = setup({
+ dashboard: createMockDashboardState({
+ dashboardId: 1,
+ dashboards: {
+ 1: createMockStoreDashboard({ id: 1, name: "Old", dashcards: [] }),
+ },
+ }),
+ });
+ setupDashboardsEndpoints([createMockDashboard({ id: 1, name: "New" })]);
+ setupDeferredQueryMetadata(1);
+
+ const fetchResult = store.dispatch(
+ fetchDashboard({ dashId: 1, queryParams: {}, options: {} }),
+ );
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called("path:/api/dashboard/1/query_metadata"),
+ ).toBe(true);
+ });
+ // Let the dashboard GET resolve before checking nothing was merged early.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(store.getState().dashboard.dashboards[1].name).toBe("Old");
+
+ queryMetadataRequest.resolve();
+ await fetchResult;
+ expect(store.getState().dashboard.dashboards[1].name).toBe("New");
+ });
+ });
+
it("should cancel previous dashboard fetch when a new one is initiated (metabase#35959)", async () => {
const store = setup({
dashboards: [
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
index d6f352a279d..e7a9a845014 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
+++ b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
@@ -1,6 +1,5 @@
import cx from "classnames";
import { useMemo } from "react";
-import { t } from "ttag";
import DashboardS from "metabase/css/dashboard.module.css";
import { DashboardHeader } from "metabase/dashboard/components/DashboardHeader";
@@ -10,7 +9,7 @@ import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import EmbedFrameS from "metabase/embedding/theme.module.css";
import { useSelector } from "metabase/redux";
import { FullWidthContainer } from "metabase/styled-components/layout/FullWidthContainer";
-import { Box, Flex, Loader } from "metabase/ui";
+import { Box, Flex } from "metabase/ui";
import { DASHBOARD_PDF_EXPORT_ROOT_ID } from "metabase/visualizations/lib/save-dashboard-pdf";
import type { DashboardCard } from "metabase-types/api";
@@ -54,12 +53,10 @@ const DashboardDefaultView = ({ className }: { className?: string }) => {
const tabHasCards = currentTabDashcards.length > 0;
const dashboardHasCards = dashboard && dashboard.dashcards.length > 0;
- if (!dashboard) {
- return <Loader size="lg" label={t`Loading…`} />;
- }
-
- const isEmpty = !dashboardHasCards || (dashboardHasCards && !tabHasCards);
- const hasTabs = dashboard.tabs && dashboard.tabs.length > 1;
+ // While the dashboard loads, its header and grid render skeletons, so lay
+ // the page out as for a dashboard with cards.
+ const isEmpty = dashboard != null && (!dashboardHasCards || !tabHasCards);
+ const hasTabs = (dashboard?.tabs?.length ?? 0) > 1;
// Embedding SDK has parent containers that requires dashboard to be full height to avoid double scrollbars.
const isFullHeight = isEditing || isSharing || isEmbeddingSdk();
@@ -81,7 +78,7 @@ const DashboardDefaultView = ({ className }: { className?: string }) => {
flex="1 0 auto"
data-testid="dashboard"
>
- {dashboard.archived && <DashboardArchivedEntityBanner />}
+ {dashboard?.archived && <DashboardArchivedEntityBanner />}
<Box
component="header"
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx b/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx
index 23cc160e372..623af87a38a 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx
+++ b/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx
@@ -14,6 +14,7 @@ import {
DashboardGridConnected,
type DashboardGridProps,
} from "../../DashboardGrid";
+import { DashboardGridSkeleton } from "../../DashboardGridSkeleton";
import {
DashboardEmptyState,
DashboardEmptyStateWithoutAddPrompt,
@@ -26,6 +27,7 @@ export const Grid = ({
}: Pick<DashboardGridProps, "className" | "style" | "p">) => {
const {
dashboard,
+ dashboardId,
selectedTabId,
isEditing,
onRefreshPeriodChange,
@@ -71,6 +73,11 @@ export const Grid = ({
const isEmpty = !dashboardHasCards || (dashboardHasCards && !tabHasCards);
+ if (!dashboard) {
+ return <DashboardGridSkeleton dashboardId={dashboardId} />;
+ }
+
+ // Only a refetch of a dashboard that's already open gets here.
if (isLoadingWithoutCards) {
return <Loader size="lg" label={t`Loading…`} />;
}
diff --git a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx b/frontend/src/metabase/dashboard/components/DashboardGrid.tsx
index fda05452e3b..33e1529478e 100644
--- a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardGrid.tsx
@@ -28,6 +28,7 @@ import {
GRID_ASPECT_RATIO,
GRID_BREAKPOINTS,
GRID_COLUMNS,
+ GRID_MARGINS,
GRID_WIDTH,
MIN_ROW_HEIGHT,
} from "metabase/utils/dashboard_grid";
@@ -647,7 +648,7 @@ class DashboardGridInner extends Component<
breakpoints={GRID_BREAKPOINTS}
cols={GRID_COLUMNS}
width={width}
- margin={{ desktop: [6, 6], mobile: [6, 10] }}
+ margin={GRID_MARGINS}
containerPadding={[0, 0]}
rowHeight={rowHeight}
onLayoutChange={this.onLayoutChange}
diff --git a/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.module.css b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.module.css
new file mode 100644
index 00000000000..d78b72e0e58
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.module.css
@@ -0,0 +1,86 @@
+.root {
+ width: 100%;
+ container-type: inline-size;
+}
+
+/*
+ * Mirrors react-grid-layout's geometry (see DashboardGrid). The column count,
+ * aspect ratio, minimum row height and margins come in as custom properties,
+ * set from the same constants the real grid uses. Lengths are in
+ * container-query width units, so the skeleton cards land at the size and
+ * position the real cards will, at any width.
+ */
+.grid {
+ --skeleton-row-height: max(
+ calc(100cqw / var(--grid-columns) / var(--grid-aspect-ratio)),
+ var(--grid-min-row-height)
+ );
+ --skeleton-col-width: calc(
+ (100cqw - var(--grid-margin-x) * (var(--grid-columns) - 1)) /
+ var(--grid-columns)
+ );
+
+ position: relative;
+ width: 100%;
+ height: calc(
+ (var(--skeleton-row-height) + var(--grid-margin-y)) * var(--skeleton-rows)
+ );
+}
+
+.card {
+ position: absolute;
+ overflow: hidden;
+ background-color: var(--mb-color-bg-dashboard-card);
+ border: 1px solid var(--mb-color-border);
+ border-radius: 0.75rem;
+ left: calc(
+ (var(--skeleton-col-width) + var(--grid-margin-x)) * var(--skeleton-col)
+ );
+ top: calc(
+ (var(--skeleton-row-height) + var(--grid-margin-y)) * var(--skeleton-row)
+ );
+ width: calc(
+ var(--skeleton-col-width) * var(--skeleton-w) + (var(--skeleton-w) - 1) *
+ var(--grid-margin-x)
+ );
+ height: calc(
+ var(--skeleton-row-height) * var(--skeleton-h) + (var(--skeleton-h) - 1) *
+ var(--grid-margin-y)
+ );
+}
+
+/* Heading and text cards have no card chrome — just their text lines. */
+.transparent {
+ background-color: transparent;
+ border-color: transparent;
+}
+
+.textContent {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.5rem;
+ height: 100%;
+ padding: 0.5rem 0.75rem;
+ font-size: 0.875rem;
+}
+
+.textContentHeading {
+ font-size: 1.25rem;
+}
+
+/* The grid's mobile breakpoint, MOBILE_BREAKPOINT. A container query can't read a custom property. */
+@container (max-width: 752px) {
+ .grid {
+ display: flex;
+ flex-direction: column;
+ gap: var(--grid-mobile-margin-y);
+ height: auto;
+ }
+
+ .card {
+ position: static;
+ width: 100%;
+ height: calc(var(--skeleton-row-height) * var(--skeleton-h));
+ }
+}
diff --git a/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.tsx b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.tsx
new file mode 100644
index 00000000000..1cca85e91a3
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.tsx
@@ -0,0 +1,199 @@
+import cx from "classnames";
+import { t } from "ttag";
+
+import visuallyHidden from "metabase/css/core/visually-hidden.module.css";
+import {
+ getIsLastSeenDashboardFixedWidth,
+ getLastSeenTabDashcards,
+} from "metabase/dashboard/selectors";
+import { isHeadingDashCard, isTextDashCard } from "metabase/dashboard/utils";
+import { useSelector } from "metabase/redux";
+import type { StoreDashcard } from "metabase/redux/store";
+import { Box, Skeleton } from "metabase/ui";
+import {
+ GRID_ASPECT_RATIO,
+ GRID_MARGINS,
+ GRID_WIDTH,
+ MIN_ROW_HEIGHT,
+} from "metabase/utils/dashboard_grid";
+import ChartSkeleton from "metabase/visualizations/components/skeletons/ChartSkeleton";
+import type { CardDisplayType, DashboardId } from "metabase-types/api";
+import { isCardDisplayType } from "metabase-types/api";
+
+import { FixedWidthContainer } from "../Dashboard/DashboardComponents";
+
+import S from "./DashboardGridSkeleton.module.css";
+
+type SkeletonCardContent =
+ | { kind: "chart"; display: CardDisplayType | undefined }
+ | { kind: "text"; lines: string[]; isHeading: boolean };
+
+export type SkeletonCardPlacement = {
+ key: string;
+ content: SkeletonCardContent;
+ col: number;
+ row: number;
+ size_x: number;
+ size_y: number;
+};
+
+const MAX_TEXT_SKELETON_LINES = 12;
+const MIN_TEXT_LINE_CHARS = 3;
+const MAX_TEXT_LINE_CHARS = 40;
+
+/** The grid geometry react-grid-layout uses, handed to the CSS. */
+const GRID_GEOMETRY_STYLE = {
+ "--grid-columns": GRID_WIDTH,
+ "--grid-aspect-ratio": GRID_ASPECT_RATIO,
+ "--grid-min-row-height": `${MIN_ROW_HEIGHT}px`,
+ "--grid-margin-x": `${GRID_MARGINS.desktop[0]}px`,
+ "--grid-margin-y": `${GRID_MARGINS.desktop[1]}px`,
+ "--grid-mobile-margin-y": `${GRID_MARGINS.mobile[1]}px`,
+};
+
+const getTextLines = (text: string): string[] =>
+ text.split("\n").slice(0, MAX_TEXT_SKELETON_LINES);
+
+const getCardContent = (dc: StoreDashcard): SkeletonCardContent => {
+ if (isHeadingDashCard(dc) || isTextDashCard(dc)) {
+ return {
+ kind: "text",
+ lines: getTextLines(dc.visualization_settings.text ?? ""),
+ isHeading: isHeadingDashCard(dc),
+ };
+ }
+
+ return {
+ kind: "chart",
+ display: isCardDisplayType(dc.card.display) ? dc.card.display : undefined,
+ };
+};
+
+export const getPlacements = (
+ cards: readonly StoreDashcard[],
+): SkeletonCardPlacement[] =>
+ cards.map((dc) => ({
+ key: String(dc.id),
+ content: getCardContent(dc),
+ col: dc.col,
+ row: dc.row,
+ size_x: dc.size_x,
+ size_y: dc.size_y,
+ }));
+
+const getRowCount = (placements: readonly SkeletonCardPlacement[]): number =>
+ placements.reduce((rows, { row, size_y }) => Math.max(rows, row + size_y), 0);
+
+const getLineWidth = (chars: number): string => {
+ const clamped = Math.min(
+ Math.max(chars, MIN_TEXT_LINE_CHARS),
+ MAX_TEXT_LINE_CHARS,
+ );
+ return `min(${clamped}ch, 100%)`;
+};
+
+const TextCardSkeleton = ({
+ lines,
+ isHeading,
+}: {
+ lines: string[];
+ isHeading: boolean;
+}) => (
+ <div
+ className={cx(S.textContent, { [S.textContentHeading]: isHeading })}
+ data-testid="dashboard-skeleton-text"
+ >
+ {lines.map((line, index) => {
+ const trimmed = line.trim();
+ return trimmed.length === 0 ? (
+ <Box key={index} h="1.2em" />
+ ) : (
+ <Skeleton
+ key={index}
+ height="1.2em"
+ width={getLineWidth(trimmed.length)}
+ radius="sm"
+ />
+ );
+ })}
+ </div>
+);
+
+/**
+ * Draws card placements at the grid geometry the real cards will use, so the
+ * transition to the loaded dashboard is seamless. Heading and text cards render
+ * title-style line skeletons rather than a chart.
+ */
+export const CardLayoutSkeleton = ({
+ placements,
+}: {
+ placements: readonly SkeletonCardPlacement[];
+}) => (
+ <Box className={S.root}>
+ <Box
+ className={S.grid}
+ style={{
+ ...GRID_GEOMETRY_STYLE,
+ "--skeleton-rows": getRowCount(placements),
+ }}
+ data-testid="dashboard-grid-skeleton-cards"
+ >
+ {placements.map(({ key, content, col, row, size_x, size_y }) => (
+ <Box
+ key={key}
+ className={cx(S.card, { [S.transparent]: content.kind === "text" })}
+ style={{
+ "--skeleton-col": col,
+ "--skeleton-row": row,
+ "--skeleton-w": size_x,
+ "--skeleton-h": size_y,
+ }}
+ >
+ {content.kind === "text" ? (
+ <TextCardSkeleton
+ lines={content.lines}
+ isHeading={content.isHeading}
+ />
+ ) : (
+ <ChartSkeleton display={content.display} />
+ )}
+ </Box>
+ ))}
+ </Box>
+ </Box>
+);
+
+/**
+ * The dashboard's card grid as a skeleton, shown while the dashboard loads so
+ * that no spinner is needed. Cards are only drawn once the dashboard's real
+ * layout is known, from the in-memory Redux cache: the cards of the tab the
+ * user is landing on, at the dashboard's own width. Until then the grid stays
+ * empty rather than showing cards the dashboard may not have. Once the real
+ * grid mounts, its cards keep their own per-card content skeletons.
+ */
+export const DashboardGridSkeleton = ({
+ dashboardId,
+}: {
+ dashboardId: DashboardId | null;
+}) => {
+ const lastSeenTabDashcards = useSelector((state) =>
+ getLastSeenTabDashcards(state, dashboardId),
+ );
+ const isFixedWidth = useSelector((state) =>
+ getIsLastSeenDashboardFixedWidth(state, dashboardId),
+ );
+ const placements = getPlacements(lastSeenTabDashcards);
+
+ return (
+ <FixedWidthContainer
+ isFixedWidth={isFixedWidth}
+ aria-busy
+ data-testid="dashboard-grid-skeleton"
+ >
+ <span role="status" className={visuallyHidden.visuallyHidden}>
+ {t`Loading…`}
+ </span>
+ {placements.length > 0 && <CardLayoutSkeleton placements={placements} />}
+ </FixedWidthContainer>
+ );
+};
diff --git a/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.unit.spec.tsx
new file mode 100644
index 00000000000..5c38d8cd98c
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/DashboardGridSkeleton.unit.spec.tsx
@@ -0,0 +1,127 @@
+import {
+ createMockDashboardState,
+ createMockStoreDashboard,
+} from "__support__/state";
+import { renderWithProviders, screen, within } from "__support__/ui";
+import type { StoreDashboardTab, StoreDashcard } from "metabase/redux/store";
+import {
+ createMockDashboardCard,
+ createMockDashboardTab,
+ createMockHeadingDashboardCard,
+ createMockTextDashboardCard,
+} from "metabase-types/api/mocks";
+
+import { DashboardGridSkeleton } from "./DashboardGridSkeleton";
+
+type SetupOpts = {
+ dashcards?: StoreDashcard[];
+ tabs?: StoreDashboardTab[];
+ isCached?: boolean;
+};
+
+function setup({ dashcards = [], tabs = [], isCached = true }: SetupOpts = {}) {
+ renderWithProviders(<DashboardGridSkeleton dashboardId={1} />, {
+ storeInitialState: {
+ dashboard: createMockDashboardState({
+ dashboards: isCached
+ ? {
+ 1: createMockStoreDashboard({
+ id: 1,
+ dashcards: dashcards.map((dc) => dc.id),
+ tabs,
+ }),
+ }
+ : {},
+ dashcards: Object.fromEntries(dashcards.map((dc) => [dc.id, dc])),
+ }),
+ },
+ });
+}
+
+const getSkeletonCards = () =>
+ screen.getByTestId("dashboard-grid-skeleton-cards").children;
+
+describe("DashboardGridSkeleton", () => {
+ afterEach(() => {
+ window.history.replaceState({}, "", "/");
+ });
+
+ it("tells assistive technology the dashboard is loading, without a spinner", () => {
+ setup();
+
+ const skeleton = screen.getByTestId("dashboard-grid-skeleton");
+ expect(skeleton).toHaveAttribute("aria-busy", "true");
+ expect(within(skeleton).getByRole("status")).toHaveTextContent("Loading…");
+ expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
+ });
+
+ it("draws no cards until the dashboard's layout is known", () => {
+ setup({ isCached: false });
+
+ expect(screen.getByTestId("dashboard-grid-skeleton")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("dashboard-grid-skeleton-cards"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("draws exactly the cached dashboard's cards", () => {
+ setup({
+ dashcards: [
+ createMockDashboardCard({ id: 1, col: 0, row: 0, size_x: 12 }),
+ createMockDashboardCard({ id: 2, col: 12, row: 0, size_x: 12 }),
+ ],
+ });
+
+ expect(getSkeletonCards()).toHaveLength(2);
+ });
+
+ it("draws the cards of the tab the URL lands on", () => {
+ window.history.replaceState({}, "", "/dashboard/1?tab=200");
+ setup({
+ tabs: [
+ createMockDashboardTab({ id: 100 }),
+ createMockDashboardTab({ id: 200 }),
+ ],
+ dashcards: [
+ createMockDashboardCard({ id: 1, dashboard_tab_id: 100 }),
+ createMockDashboardCard({ id: 2, dashboard_tab_id: 200 }),
+ createMockDashboardCard({ id: 3, dashboard_tab_id: 200 }),
+ ],
+ });
+
+ expect(getSkeletonCards()).toHaveLength(2);
+ });
+
+ it("lands on the first tab that hasn't been removed", () => {
+ setup({
+ tabs: [
+ { ...createMockDashboardTab({ id: 100 }), isRemoved: true },
+ createMockDashboardTab({ id: 200 }),
+ ],
+ dashcards: [
+ createMockDashboardCard({ id: 1, dashboard_tab_id: 100 }),
+ createMockDashboardCard({ id: 2, dashboard_tab_id: 200 }),
+ createMockDashboardCard({ id: 3, dashboard_tab_id: 200 }),
+ ],
+ });
+
+ expect(getSkeletonCards()).toHaveLength(2);
+ });
+
+ it("renders one line skeleton per line of a heading or text card", () => {
+ setup({
+ dashcards: [
+ createMockHeadingDashboardCard({ id: 1, text: "One heading line" }),
+ createMockTextDashboardCard({
+ id: 2,
+ text: "Line one\nLine two\nLine three",
+ }),
+ ],
+ });
+
+ const textSkeletons = screen.getAllByTestId("dashboard-skeleton-text");
+ expect(textSkeletons).toHaveLength(2);
+ expect(textSkeletons[0].childElementCount).toBe(1);
+ expect(textSkeletons[1].childElementCount).toBe(3);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/index.ts b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/index.ts
new file mode 100644
index 00000000000..36149bb6515
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardGridSkeleton/index.ts
@@ -0,0 +1 @@
+export { DashboardGridSkeleton } from "./DashboardGridSkeleton";
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx
index 8038985a631..39f5aee9cf0 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx
@@ -21,11 +21,11 @@ import { fetchPulseFormInput } from "metabase/notifications/pulse/actions";
import { useDispatch, useSelector } from "metabase/redux";
import { useMaybeLocation } from "metabase/router";
import { getSetting } from "metabase/settings";
-import { Flex, Loader } from "metabase/ui";
import type { Dashboard } from "metabase-types/api";
import { SIDEBAR_NAME } from "../../constants";
+import { DashboardHeaderSkeleton } from "./DashboardHeaderSkeleton";
import { DashboardHeaderView } from "./DashboardHeaderView";
import { CancelEditButton, SaveEditButton } from "./buttons";
@@ -61,13 +61,12 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {
getSetting(state, "custom-homepage-dashboard") === dashboard?.id,
);
- const { data: collection, isLoading: isLoadingCollection } =
- useGetCollectionQuery(
- { id: dashboard.collection_id || "root" },
- {
- skip: isGuestEmbed,
- },
- );
+ const { data: collection } = useGetCollectionQuery(
+ { id: dashboard.collection_id || "root" },
+ {
+ skip: isGuestEmbed,
+ },
+ );
const onRequestCancel = () => {
if (isDirty && isEditing) {
@@ -116,17 +115,6 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {
];
};
- // 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;
const editingButtons = getEditingButtons();
@@ -164,10 +152,12 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {
};
export const DashboardHeader = () => {
- const { dashboard } = useDashboardContext();
+ const { dashboard, dashboardId, titled } = useDashboardContext();
if (!dashboard) {
- return null;
+ return (
+ <DashboardHeaderSkeleton dashboardId={dashboardId} titled={titled} />
+ );
}
return <DashboardHeaderInner dashboard={dashboard} />;
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderSkeleton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderSkeleton.tsx
new file mode 100644
index 00000000000..a9d597d6323
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderSkeleton.tsx
@@ -0,0 +1,184 @@
+import cx from "classnames";
+import type { ReactNode } from "react";
+
+import { EditableText } from "metabase/common/components/EditableText";
+import CS from "metabase/css/core/index.css";
+import {
+ getIsAdditionalInfoVisible,
+ getIsHeaderVisible,
+ getIsLastSeenDashboardFixedWidth,
+ getLastSeenDashboard,
+} from "metabase/dashboard/selectors";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import { useSelector } from "metabase/redux";
+import { FullWidthContainer } from "metabase/styled-components/layout/FullWidthContainer";
+import { Box, Flex, Skeleton, Text, UnstyledButton } from "metabase/ui";
+import type { DashboardId } from "metabase-types/api";
+
+import { FixedWidthContainer } from "../Dashboard/DashboardComponents";
+
+import S from "./DashboardHeaderView.module.css";
+
+// Dashboards render a fixed row of action-icon buttons in their header.
+const HEADER_ACTIONS = Array.from({ length: 6 });
+
+/**
+ * A skeleton bar laid over an invisible copy of the element it stands in for,
+ * so it takes up exactly the height the real element will.
+ */
+const SkeletonOver = ({
+ width,
+ height,
+ children,
+}: {
+ width: string;
+ height: string;
+ children: ReactNode;
+}) => (
+ <Box pos="relative" w={width}>
+ {/* A flex container, like the rows the real elements sit in. */}
+ <Flex style={{ visibility: "hidden" }} aria-hidden>
+ {children}
+ </Flex>
+ <Flex pos="absolute" top={0} bottom={0} left={0} right={0} align="center">
+ <Skeleton height={height} radius="sm" />
+ </Flex>
+ </Box>
+);
+
+/**
+ * The dashboard header as a skeleton, shown while the dashboard loads. It's
+ * built from the same layout pieces as `DashboardHeaderView` and follows the
+ * same visibility rules, and sizes its title area from the real title and
+ * last-edit label, so the header doesn't change height when the dashboard
+ * arrives. Tabs come from the dashboard as last seen in the in-memory Redux
+ * cache, so the tab row only appears when the dashboard has more than one tab.
+ */
+export const DashboardHeaderSkeleton = ({
+ dashboardId,
+ titled,
+}: {
+ dashboardId: DashboardId | null;
+ titled: boolean;
+}) => {
+ const isHeaderVisible = useSelector(getIsHeaderVisible);
+ const isAdditionalInfoVisible = useSelector(getIsAdditionalInfoVisible);
+ const lastSeenDashboard = useSelector((state) =>
+ getLastSeenDashboard(state, dashboardId),
+ );
+ const isFixedWidth = useSelector((state) =>
+ getIsLastSeenDashboardFixedWidth(state, dashboardId),
+ );
+ const tabs = lastSeenDashboard?.tabs?.filter((tab) => !tab.isRemoved) ?? [];
+ // Without the dashboard in the cache, assume it has an edit history, as
+ // nearly every dashboard does.
+ const hasLastEditInfo =
+ lastSeenDashboard == null || lastSeenDashboard["last-edit-info"] != null;
+ const isLastEditInfoVisible = hasLastEditInfo && isAdditionalInfoVisible;
+
+ return (
+ <div
+ className={S.DashboardHeader}
+ aria-busy
+ data-testid="dashboard-header-skeleton"
+ >
+ <div className={S.HeaderContainer}>
+ {isHeaderVisible && (
+ <FullWidthContainer className={cx(CS.wrapper, S.HeaderRow)}>
+ <FixedWidthContainer
+ className={S.HeaderFixedWidthContainer}
+ isFixedWidth={isFixedWidth}
+ >
+ {titled && (
+ // The real header mounts with its sub-header shown.
+ <Box
+ className={cx(S.HeaderContent, S.showSubHeader)}
+ data-testid="dashboard-header-skeleton-title"
+ >
+ <Flex className={S.HeaderCaptionContainer}>
+ <SkeletonOver width="14rem" height="1.5rem">
+ <EditableText
+ className={S.HeaderCaption}
+ initialValue=""
+ isDisabled
+ />
+ </SkeletonOver>
+ </Flex>
+ <Flex
+ className={S.HeaderBadges}
+ data-testid="dashboard-header-skeleton-badges"
+ >
+ {isLastEditInfoVisible && (
+ <SkeletonOver width="10rem" height="0.875rem">
+ <LastEditInfoLabelSizer />
+ </SkeletonOver>
+ )}
+ </Flex>
+ </Box>
+ )}
+ <Flex className={S.HeaderButtonsContainer}>
+ <Flex
+ className={S.HeaderButtonSection}
+ data-testid="dashboard-header-skeleton-actions"
+ >
+ {HEADER_ACTIONS.map((_, index) => (
+ <Skeleton
+ key={index}
+ height="2rem"
+ width="2rem"
+ radius="sm"
+ />
+ ))}
+ </Flex>
+ </Flex>
+ </FixedWidthContainer>
+ </FullWidthContainer>
+ )}
+ {tabs.length > 1 && (
+ <FullWidthContainer className={S.HeaderRow}>
+ <FixedWidthContainer
+ className={S.HeaderFixedWidthContainer}
+ isFixedWidth={isFixedWidth}
+ >
+ <Flex
+ align="center"
+ gap="lg"
+ h="2.5rem"
+ data-testid="dashboard-header-skeleton-tabs"
+ >
+ {tabs.map((tab) => (
+ <Skeleton
+ key={tab.id}
+ height="1rem"
+ width="4rem"
+ radius="sm"
+ />
+ ))}
+ </Flex>
+ </FixedWidthContainer>
+ </FullWidthContainer>
+ )}
+ </div>
+ </div>
+ );
+};
+
+/**
+ * An empty line of the dashboard's last-edit label, rendered as the same
+ * element `LastEditInfoLabel` uses in this context so it has the same height.
+ */
+const LastEditInfoLabelSizer = () =>
+ isEmbeddingSdk() ? (
+ <Text className={S.HeaderLastEditInfoLabel} size="sm" fw="bold">
+ {" "}
+ </Text>
+ ) : (
+ <UnstyledButton
+ className={S.HeaderLastEditInfoLabel}
+ fz="sm"
+ fw="bold"
+ tabIndex={-1}
+ >
+ {" "}
+ </UnstyledButton>
+ );
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderSkeleton.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderSkeleton.unit.spec.tsx
new file mode 100644
index 00000000000..aeedc250dfe
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderSkeleton.unit.spec.tsx
@@ -0,0 +1,102 @@
+import {
+ createMockDashboardState,
+ createMockStoreDashboard,
+} from "__support__/state";
+import { renderWithProviders, screen } from "__support__/ui";
+import type { StoreDashboardTab } from "metabase/redux/store";
+import { createMockDashboardTab } from "metabase-types/api/mocks";
+
+import { DashboardHeaderSkeleton } from "./DashboardHeaderSkeleton";
+
+type SetupOpts = {
+ tabs?: StoreDashboardTab[];
+ titled?: boolean;
+ isCached?: boolean;
+};
+
+function setup({ tabs = [], titled = true, isCached = true }: SetupOpts = {}) {
+ renderWithProviders(
+ <DashboardHeaderSkeleton dashboardId={1} titled={titled} />,
+ {
+ storeInitialState: {
+ dashboard: createMockDashboardState({
+ dashboards: isCached
+ ? { 1: createMockStoreDashboard({ id: 1, tabs }) }
+ : {},
+ }),
+ },
+ },
+ );
+}
+
+describe("DashboardHeaderSkeleton", () => {
+ it("draws the title and action buttons as a busy region", () => {
+ setup();
+
+ expect(screen.getByTestId("dashboard-header-skeleton")).toHaveAttribute(
+ "aria-busy",
+ "true",
+ );
+ expect(
+ screen.getByTestId("dashboard-header-skeleton-title"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("dashboard-header-skeleton-actions").childElementCount,
+ ).toBe(6);
+ });
+
+ it("reserves the last-edit label's row on a fresh page load", () => {
+ setup({ isCached: false });
+
+ expect(
+ screen.getByTestId("dashboard-header-skeleton-badges").childElementCount,
+ ).toBe(1);
+ });
+
+ it("reserves the last-edit label's row for a cached dashboard with an edit history", () => {
+ setup();
+
+ expect(
+ screen.getByTestId("dashboard-header-skeleton-badges").childElementCount,
+ ).toBe(1);
+ });
+
+ it("leaves out the title where the dashboard isn't titled", () => {
+ setup({ titled: false });
+
+ expect(
+ screen.queryByTestId("dashboard-header-skeleton-title"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("draws no tab row on a fresh page load", () => {
+ setup({ isCached: false });
+
+ expect(
+ screen.queryByTestId("dashboard-header-skeleton-tabs"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("draws no tab row for a dashboard with a single tab", () => {
+ setup({ tabs: [createMockDashboardTab({ id: 1 })] });
+
+ expect(
+ screen.queryByTestId("dashboard-header-skeleton-tabs"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("draws one placeholder per tab, skipping removed tabs", () => {
+ setup({
+ tabs: [
+ createMockDashboardTab({ id: 1 }),
+ createMockDashboardTab({ id: 2 }),
+ { ...createMockDashboardTab({ id: 3 }), isRemoved: true },
+ createMockDashboardTab({ id: 4 }),
+ ],
+ });
+
+ expect(
+ screen.getByTestId("dashboard-header-skeleton-tabs").childElementCount,
+ ).toBe(3);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanel.tsx b/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanel.tsx
index e50f8b37e8b..fe750d80f92 100644
--- a/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanel.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanel.tsx
@@ -16,11 +16,13 @@ import { FixedWidthContainer } from "../Dashboard/DashboardComponents";
import { ParametersList } from "../Dashboard/components";
import S from "./DashboardParameterPanel.module.css";
+import { DashboardParameterPanelSkeleton } from "./DashboardParameterPanelSkeleton";
export function DashboardParameterPanel() {
const parameters = useSelector(getDashboardHeaderValuePopulatedParameters);
- const { dashboard, hideParameters, isEditing } = useDashboardContext();
+ const { dashboard, dashboardId, hideParameters, isEditing } =
+ useDashboardContext();
const visibleParameters = getVisibleParameters(parameters, hideParameters);
const hasVisibleParameters = visibleParameters.length > 0;
@@ -34,6 +36,15 @@ export function DashboardParameterPanel() {
disabled: !allowSticky || !hasVisibleParameters,
});
+ if (!dashboard) {
+ return (
+ <DashboardParameterPanelSkeleton
+ dashboardId={dashboardId}
+ hideParameters={hideParameters}
+ />
+ );
+ }
+
if (!hasVisibleParameters) {
return null;
}
diff --git a/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanelSkeleton.tsx b/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanelSkeleton.tsx
new file mode 100644
index 00000000000..a65d3e42cea
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanelSkeleton.tsx
@@ -0,0 +1,70 @@
+import cx from "classnames";
+
+import {
+ getIsLastSeenDashboardFixedWidth,
+ getLastSeenDashboardHeaderParameters,
+} from "metabase/dashboard/selectors";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import { getVisibleParameters } from "metabase/parameters/utils/ui";
+import { useSelector } from "metabase/redux";
+import { FullWidthContainer } from "metabase/styled-components/layout/FullWidthContainer";
+import { Flex, Skeleton } from "metabase/ui";
+import type { DashboardId } from "metabase-types/api";
+
+import DashboardS from "../Dashboard/Dashboard.module.css";
+import { FixedWidthContainer } from "../Dashboard/DashboardComponents";
+
+import S from "./DashboardParameterPanel.module.css";
+
+/**
+ * The dashboard's filter widgets as skeletons, shown while the dashboard
+ * loads. They come from the dashboard as last seen in the in-memory Redux
+ * cache, so nothing is drawn on a fresh page load.
+ */
+export const DashboardParameterPanelSkeleton = ({
+ dashboardId,
+ hideParameters,
+}: {
+ dashboardId: DashboardId | null;
+ hideParameters?: string | null;
+}) => {
+ const isFixedWidth = useSelector((state) =>
+ getIsLastSeenDashboardFixedWidth(state, dashboardId),
+ );
+ const headerParameters = useSelector((state) =>
+ getLastSeenDashboardHeaderParameters(state, dashboardId),
+ );
+ const visibleParameters = getVisibleParameters(
+ headerParameters,
+ hideParameters,
+ );
+
+ if (visibleParameters.length === 0) {
+ return null;
+ }
+
+ return (
+ <FullWidthContainer
+ className={cx(S.ParametersWidgetContainer, {
+ [S.isEmbeddingSdk]: isEmbeddingSdk(),
+ })}
+ aria-busy
+ data-testid="dashboard-parameters-skeleton"
+ >
+ <FixedWidthContainer
+ className={DashboardS.ParametersFixedWidthContainer}
+ isFixedWidth={isFixedWidth}
+ >
+ <Flex
+ align="center"
+ gap="sm"
+ data-testid="dashboard-parameters-skeleton-filters"
+ >
+ {visibleParameters.map((parameter) => (
+ <Skeleton key={parameter.id} height={24} width={160} radius="sm" />
+ ))}
+ </Flex>
+ </FixedWidthContainer>
+ </FullWidthContainer>
+ );
+};
diff --git a/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanelSkeleton.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanelSkeleton.unit.spec.tsx
new file mode 100644
index 00000000000..c90d33753de
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardParameterPanel/DashboardParameterPanelSkeleton.unit.spec.tsx
@@ -0,0 +1,73 @@
+import {
+ createMockDashboardState,
+ createMockStoreDashboard,
+} from "__support__/state";
+import { renderWithProviders, screen } from "__support__/ui";
+import {
+ createMockDashboardCard,
+ createMockParameter,
+} from "metabase-types/api/mocks";
+
+import { DashboardParameterPanelSkeleton } from "./DashboardParameterPanelSkeleton";
+
+const PARAMETERS = [
+ createMockParameter({ id: "a", slug: "a" }),
+ createMockParameter({ id: "b", slug: "b" }),
+ createMockParameter({ id: "c", slug: "c" }),
+];
+
+// Parameter "c" sits inline on this card rather than in the header.
+const DASHCARD = createMockDashboardCard({ id: 10, inline_parameters: ["c"] });
+
+function setup({
+ isCached = true,
+ hideParameters,
+}: { isCached?: boolean; hideParameters?: string } = {}) {
+ renderWithProviders(
+ <DashboardParameterPanelSkeleton
+ dashboardId={1}
+ hideParameters={hideParameters}
+ />,
+ {
+ storeInitialState: {
+ dashboard: createMockDashboardState({
+ dashboards: isCached
+ ? {
+ 1: createMockStoreDashboard({
+ id: 1,
+ parameters: PARAMETERS,
+ dashcards: [DASHCARD.id],
+ }),
+ }
+ : {},
+ dashcards: { [DASHCARD.id]: DASHCARD },
+ }),
+ },
+ },
+ );
+}
+
+const getPlaceholders = () =>
+ screen.getByTestId("dashboard-parameters-skeleton-filters").children;
+
+describe("DashboardParameterPanelSkeleton", () => {
+ it("draws one placeholder per header filter, leaving out inline ones", () => {
+ setup();
+
+ expect(getPlaceholders()).toHaveLength(2);
+ });
+
+ it("leaves out filters the embedding hides", () => {
+ setup({ hideParameters: "b" });
+
+ expect(getPlaceholders()).toHaveLength(1);
+ });
+
+ it("draws nothing on a fresh page load", () => {
+ setup({ isCached: false });
+
+ expect(
+ screen.queryByTestId("dashboard-parameters-skeleton"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.unit.spec.tsx
index b33f4f4c6ab..203db331dfe 100644
--- a/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.unit.spec.tsx
@@ -9,7 +9,7 @@ import { createMockEntitiesState } from "__support__/store";
import {
renderWithProviders,
screen,
- waitForLoaderToBeRemoved,
+ waitForDashboardToLoad,
within,
} from "__support__/ui";
import { Route } from "metabase/router";
@@ -51,7 +51,7 @@ const setup = async () => {
},
);
- await waitForLoaderToBeRemoved();
+ await waitForDashboardToLoad();
return {
dashboardId,
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsx
index 96c74457987..7883ef6f424 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsx
@@ -16,7 +16,7 @@ import {
act,
renderWithProviders,
waitFor,
- waitForLoaderToBeRemoved,
+ waitForDashboardToLoad,
} from "__support__/ui";
import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";
import { Route } from "metabase/router";
@@ -80,7 +80,7 @@ async function setup({ hash = "" }: { hash?: string } = {}) {
},
);
- await waitForLoaderToBeRemoved();
+ await waitForDashboardToLoad();
const getTargetDashcard = () =>
checkNotNull(
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx
index 09434728a1d..b0a673e75f8 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx
@@ -22,11 +22,12 @@ import {
act,
renderWithProviders,
screen,
- waitForLoaderToBeRemoved,
+ waitForDashboardToLoad,
} from "__support__/ui";
import { getBeforeUnloadUnsavedMessage } from "metabase/common/hooks/use-before-unload";
import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";
import { Route } from "metabase/router";
+import { defer } from "metabase/utils/promise";
import { checkNotNull } from "metabase/utils/types";
import type { Dashboard } from "metabase-types/api";
import {
@@ -36,7 +37,9 @@ import {
createMockDashboard,
createMockDashboardQueryMetadata,
createMockDatabase,
+ createMockHeadingDashboardCard,
createMockTable,
+ createMockTextDashboardCard,
} from "metabase-types/api/mocks";
const TEST_COLLECTION = createMockCollection();
@@ -59,22 +62,33 @@ const TestHome = () => <div />;
interface Options {
dashboard?: Partial<Dashboard>;
slug?: string;
+ /** Holds the query metadata response until `resolveQueryMetadata` is called. */
+ deferQueryMetadata?: boolean;
}
-async function setup({ dashboard, slug }: Options = {}) {
+function renderDashboardApp({
+ dashboard,
+ slug,
+ deferQueryMetadata = false,
+}: Options = {}) {
const mockDashboard = createMockDashboard(dashboard);
const dashboardId = mockDashboard.id;
+ const queryMetadata = createMockDashboardQueryMetadata({
+ databases: [TEST_DATABASE_WITH_ACTIONS],
+ });
+ const queryMetadataRequest = defer();
setupNotificationChannelsEndpoints({});
setupDatabasesEndpoints([TEST_DATABASE_WITH_ACTIONS]);
setupDashboardEndpoints(mockDashboard);
- setupDashboardQueryMetadataEndpoint(
- mockDashboard,
- createMockDashboardQueryMetadata({
- databases: [TEST_DATABASE_WITH_ACTIONS],
- }),
- );
+ if (deferQueryMetadata) {
+ fetchMock.get(`path:/api/dashboard/${dashboardId}/query_metadata`, () =>
+ queryMetadataRequest.promise.then(() => queryMetadata),
+ );
+ } else {
+ setupDashboardQueryMetadataEndpoint(mockDashboard, queryMetadata);
+ }
setupCollectionsEndpoints({ collections: [] });
setupCollectionItemsEndpoint({
collection: TEST_COLLECTION,
@@ -116,16 +130,23 @@ async function setup({ dashboard, slug }: Options = {}) {
},
);
- await waitForLoaderToBeRemoved();
-
return {
dashboardId,
router: checkNotNull(router),
store,
mockEventListener,
+ resolveQueryMetadata: () => queryMetadataRequest.resolve(),
};
}
+async function setup(options: Options = {}) {
+ const view = renderDashboardApp(options);
+
+ await waitForDashboardToLoad();
+
+ return view;
+}
+
describe("DashboardApp", () => {
afterEach(() => {
jest.clearAllMocks();
@@ -169,7 +190,7 @@ describe("DashboardApp", () => {
router.navigate(`/dashboard/${dashboardId}`);
});
- await waitForLoaderToBeRemoved();
+ await waitForDashboardToLoad();
await userEvent.click(await screen.findByLabelText("Edit dashboard"));
@@ -190,7 +211,7 @@ describe("DashboardApp", () => {
router.navigate(`/dashboard/${dashboardId}`);
});
- await waitForLoaderToBeRemoved();
+ await waitForDashboardToLoad();
await userEvent.click(screen.getByLabelText("Edit dashboard"));
await userEvent.click(screen.getByTestId("dashboard-name-heading"));
@@ -285,6 +306,55 @@ describe("DashboardApp", () => {
expect(store.getState().app.errorPage).toMatchObject({ status: 404 });
});
+ describe("loading state (DSN-749)", () => {
+ it("renders the dashboard with skeletons, instead of a loading spinner, while it loads", async () => {
+ renderDashboardApp();
+
+ // The real dashboard page renders right away, with skeletons for its
+ // header and grid, and a loading spinner is never shown.
+ expect(screen.getByTestId("dashboard")).toBeInTheDocument();
+ expect(
+ screen.getByTestId("dashboard-header-skeleton"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("dashboard-grid-skeleton")).toBeInTheDocument();
+ expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
+
+ // Once the dashboard arrives, its real header and grid replace them.
+ await waitForDashboardToLoad();
+ expect(screen.getByTestId("dashboard-header")).toBeInTheDocument();
+ });
+
+ it("switches to the dashboard's real card layout as soon as it is known, before the load finishes", async () => {
+ const { resolveQueryMetadata } = renderDashboardApp({
+ dashboard: {
+ dashcards: [
+ createMockHeadingDashboardCard({ id: 1, text: "Heading" }),
+ createMockTextDashboardCard({
+ id: 2,
+ text: "First line\nSecond line",
+ }),
+ ],
+ },
+ deferQueryMetadata: true,
+ });
+
+ try {
+ // These can only come from the dashboard's own layout, drawn while
+ // its query metadata loads.
+ expect(
+ await screen.findAllByTestId("dashboard-skeleton-text"),
+ ).toHaveLength(2);
+ } finally {
+ resolveQueryMetadata();
+ }
+
+ await waitForDashboardToLoad();
+ expect(
+ screen.queryByTestId("dashboard-skeleton-text"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
it("should not allow to enter a dashboard name longer than 254 characters", async () => {
await setup();
diff --git a/frontend/src/metabase/dashboard/reducers-typed.ts b/frontend/src/metabase/dashboard/reducers-typed.ts
index 35d51348592..6609d20f0bb 100644
--- a/frontend/src/metabase/dashboard/reducers-typed.ts
+++ b/frontend/src/metabase/dashboard/reducers-typed.ts
@@ -54,6 +54,7 @@ import {
addManyCardsToDash,
cancelFetchCardData,
clearCardData,
+ dashboardLayoutFetched,
fetchCardDataAction,
fetchDashboard,
fetchDashboardCardDataAction,
@@ -320,6 +321,10 @@ export const dashboards = createReducer(
...state,
...payload.entities.dashboard,
}))
+ .addCase(dashboardLayoutFetched, (state, { payload }) => ({
+ ...state,
+ ...payload.dashboard,
+ }))
.addCase(
setDashboardAttributes,
(state, { payload: { id, attributes, isDirty = true } }) => {
diff --git a/frontend/src/metabase/dashboard/reducers.ts b/frontend/src/metabase/dashboard/reducers.ts
index 021fec4ffea..313f229ad73 100644
--- a/frontend/src/metabase/dashboard/reducers.ts
+++ b/frontend/src/metabase/dashboard/reducers.ts
@@ -22,6 +22,7 @@ import {
UNDO_REMOVE_CARD_FROM_DASH,
addCardToDash,
addManyCardsToDash,
+ dashboardLayoutFetched,
fetchDashboardFulfilled,
markNewCardSeen,
onReplaceAllDashCardVisualizationSettings,
@@ -68,6 +69,10 @@ const dashcards = createReducer(
...state,
...action.payload.entities.dashcard,
}))
+ .addCase(dashboardLayoutFetched, (state, { payload }) => ({
+ ...state,
+ ...payload.dashcard,
+ }))
.addCase(
setDashCardAttributes,
(state, { payload: { id, attributes } }) => {
diff --git a/frontend/src/metabase/dashboard/selectors.ts b/frontend/src/metabase/dashboard/selectors.ts
index d84238ee64c..ba82b7564af 100644
--- a/frontend/src/metabase/dashboard/selectors.ts
+++ b/frontend/src/metabase/dashboard/selectors.ts
@@ -26,6 +26,7 @@ import type {
EditParameterSidebarState,
State,
StoreDashboard,
+ StoreDashcard,
} from "metabase/redux/store";
import { getSetting } from "metabase/settings";
import * as Urls from "metabase/urls";
@@ -47,6 +48,7 @@ import type {
DashboardParameterMapping,
DashboardTabId,
EmbeddingParameterVisibility,
+ Parameter,
ParameterId,
VirtualCard,
} from "metabase-types/api";
@@ -181,6 +183,96 @@ export const getDashboardById = (state: State, dashboardId: DashboardId) => {
return dashboards[dashboardId];
};
+const EMPTY_DASHCARDS: StoreDashcard[] = [];
+const EMPTY_PARAMETERS: Parameter[] = [];
+
+/**
+ * The dashboard as we last saw it, looked up by id in the in-memory Redux
+ * cache. Unlike `getDashboard`, it survives the reset of the active
+ * `dashboardId` while a dashboard (re)loads, so a dashboard seen earlier in
+ * this session can draw its real layout as a skeleton. Undefined on any fresh
+ * page load.
+ */
+export const getLastSeenDashboard = (
+ state: State,
+ dashboardId: DashboardId | null,
+): StoreDashboard | undefined =>
+ dashboardId == null ? undefined : getDashboardById(state, dashboardId);
+
+/**
+ * Whether the dashboard as last seen is fixed width. Without it in the cache,
+ * assume it is, since fixed is the default width for dashboards.
+ */
+export const getIsLastSeenDashboardFixedWidth = (
+ state: State,
+ dashboardId: DashboardId | null,
+): boolean =>
+ (getLastSeenDashboard(state, dashboardId)?.width ?? "fixed") === "fixed";
+
+/**
+ * The dashcards of the tab the user is landing on, in the dashboard as last
+ * seen. The tab is chosen the way `getSelectedTabId` chooses it on load.
+ */
+export const getLastSeenTabDashcards = createSelector(
+ [
+ getLastSeenDashboard,
+ getDashcards,
+ getIsWebApp,
+ (state: State) => getSetting(state, "site-url"),
+ (state: State & Partial<SdkSharedStoreState>) =>
+ state.sdk?.initialDashboardTabId,
+ ],
+ (
+ dashboard,
+ dashcardMap,
+ isWebApp,
+ siteUrl,
+ sdkInitialDashboardTabId,
+ ): StoreDashcard[] => {
+ if (!dashboard) {
+ return EMPTY_DASHCARDS;
+ }
+
+ const dashboardWithVisibleTabs = {
+ ...dashboard,
+ tabs: dashboard.tabs?.filter((tab) => !tab.isRemoved),
+ };
+ const tabId = isEmbeddingSdk()
+ ? getSdkInitialDashboardTabId(
+ dashboardWithVisibleTabs,
+ sdkInitialDashboardTabId,
+ )
+ : getInitialSelectedTabId(dashboardWithVisibleTabs, siteUrl, isWebApp);
+
+ const dashcards = dashboard.dashcards
+ .map((id) => dashcardMap[id])
+ .filter((dc): dc is StoreDashcard => isNotNull(dc) && !dc.isRemoved);
+ return tabId == null
+ ? dashcards
+ : dashcards.filter((dc) => dc.dashboard_tab_id === tabId);
+ },
+);
+
+/**
+ * The filters shown in the header of the dashboard as last seen: its
+ * parameters except those placed inline on a dashcard.
+ */
+export const getLastSeenDashboardHeaderParameters = createSelector(
+ [getLastSeenDashboard, getDashcards],
+ (dashboard, dashcardMap): Parameter[] => {
+ if (!dashboard?.parameters) {
+ return EMPTY_PARAMETERS;
+ }
+
+ const dashcards = dashboard.dashcards
+ .map((id) => dashcardMap[id])
+ .filter(isNotNull);
+ return dashboard.parameters.filter(
+ (parameter) => !isDashcardInlineParameter(parameter.id, dashcards),
+ );
+ },
+);
+
export const getLinkTargetEntities = (state: State) =>
state.dashboard.linkTargets;
diff --git a/frontend/src/metabase/dashboard/selectors.unit.spec.ts b/frontend/src/metabase/dashboard/selectors.unit.spec.ts
index 977f6514c7a..5109c2d00f0 100644
--- a/frontend/src/metabase/dashboard/selectors.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/selectors.unit.spec.ts
@@ -13,7 +13,11 @@ import {
getDashboardHeaderParameters,
getEditingParameterId,
getIsEditingParameter,
+ getIsLastSeenDashboardFixedWidth,
getIsSharing,
+ getLastSeenDashboard,
+ getLastSeenDashboardHeaderParameters,
+ getLastSeenTabDashcards,
getParameters,
getQuestionByCard,
getSelectedTabId,
@@ -566,4 +570,110 @@ describe("getQuestionByCard", () => {
expect(question).toBe(second[index]);
});
});
+
+ describe("getLastSeenTabDashcards", () => {
+ // The active pointer is null, mimicking the window during a (re)fetch when
+ // the layout can only be read from the in-memory Redux cache by id.
+ const CACHED_STATE = createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: null,
+ dashboards: {
+ 5: createMockStoreDashboard({
+ id: 5,
+ dashcards: [10, 11, 12],
+ tabs: [
+ createMockDashboardTab({ id: 100 }),
+ createMockDashboardTab({ id: 200 }),
+ ],
+ }),
+ },
+ dashcards: {
+ 10: createMockDashboardCard({ id: 10, dashboard_tab_id: 100 }),
+ 11: createMockDashboardCard({ id: 11, dashboard_tab_id: 100 }),
+ 12: createMockDashboardCard({ id: 12, dashboard_tab_id: 200 }),
+ },
+ }),
+ });
+
+ it("returns the cached default-tab dashcards even when the active dashboard id is reset", () => {
+ const cards = getLastSeenTabDashcards(CACHED_STATE, 5);
+ expect(cards.map((dc) => dc.id)).toEqual([10, 11]);
+ });
+
+ it("returns an empty array for a dashboard that isn't cached", () => {
+ expect(getLastSeenTabDashcards(CACHED_STATE, 999)).toEqual([]);
+ expect(getLastSeenTabDashcards(CACHED_STATE, null)).toEqual([]);
+ });
+ });
+
+ describe("getLastSeenDashboard", () => {
+ const STATE = createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: null,
+ dashboards: { 5: createMockStoreDashboard({ id: 5 }) },
+ }),
+ });
+
+ it("returns the dashboard from the cache even when the active dashboard id is reset", () => {
+ expect(getLastSeenDashboard(STATE, 5)).toMatchObject({ id: 5 });
+ });
+
+ it("returns nothing for a dashboard that isn't cached", () => {
+ expect(getLastSeenDashboard(STATE, 999)).toBeUndefined();
+ expect(getLastSeenDashboard(STATE, null)).toBeUndefined();
+ });
+ });
+
+ describe("getIsLastSeenDashboardFixedWidth", () => {
+ const STATE = createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: null,
+ dashboards: {
+ 5: createMockStoreDashboard({ id: 5, width: "fixed" }),
+ 6: createMockStoreDashboard({ id: 6, width: "full" }),
+ },
+ }),
+ });
+
+ it("follows the cached dashboard's width", () => {
+ expect(getIsLastSeenDashboardFixedWidth(STATE, 5)).toBe(true);
+ expect(getIsLastSeenDashboardFixedWidth(STATE, 6)).toBe(false);
+ });
+
+ it("assumes the default fixed width for a dashboard that isn't cached", () => {
+ expect(getIsLastSeenDashboardFixedWidth(STATE, 999)).toBe(true);
+ expect(getIsLastSeenDashboardFixedWidth(STATE, null)).toBe(true);
+ });
+ });
+
+ describe("getLastSeenDashboardHeaderParameters", () => {
+ const STATE = createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: null,
+ dashboards: {
+ 5: createMockStoreDashboard({
+ id: 5,
+ dashcards: [10],
+ parameters: [
+ createMockParameter({ id: "a" }),
+ createMockParameter({ id: "b" }),
+ ],
+ }),
+ },
+ dashcards: {
+ 10: createMockDashboardCard({ id: 10, inline_parameters: ["b"] }),
+ },
+ }),
+ });
+
+ it("returns the cached dashboard's parameters except those inline on a dashcard", () => {
+ expect(
+ getLastSeenDashboardHeaderParameters(STATE, 5).map(({ id }) => id),
+ ).toEqual(["a"]);
+ });
+
+ it("returns no parameters for a dashboard that isn't cached", () => {
+ expect(getLastSeenDashboardHeaderParameters(STATE, 999)).toEqual([]);
+ });
+ });
});
diff --git a/frontend/src/metabase/dashboard/utils.ts b/frontend/src/metabase/dashboard/utils.ts
index 18759791d56..f51b00c2723 100644
--- a/frontend/src/metabase/dashboard/utils.ts
+++ b/frontend/src/metabase/dashboard/utils.ts
@@ -104,6 +104,12 @@ export function isHeadingDashCard(
return getVirtualCardType(dashcard) === "heading";
}
+export function isTextDashCard(
+ dashcard: BaseDashboardCard,
+): dashcard is VirtualDashboardCard {
+ return getVirtualCardType(dashcard) === "text";
+}
+
export function isLinkDashCard(
dashcard: BaseDashboardCard,
): dashcard is VirtualDashboardCard {
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.common.unit.spec.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.common.unit.spec.tsx
index 518df857cde..83b67d12998 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.common.unit.spec.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.common.unit.spec.tsx
@@ -17,6 +17,28 @@ describe("PublicOrEmbeddedDashboardPage", () => {
setupLastDownloadFormatEndpoints();
});
+ it("shows the grid skeleton, not the empty state, while the dashboard loads", async () => {
+ const { releaseDashboardRequest } = await setupCommon({
+ holdDashboardRequest: true,
+ });
+
+ try {
+ expect(
+ await screen.findByTestId("dashboard-grid-skeleton"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("This dashboard is empty"),
+ ).not.toBeInTheDocument();
+ } finally {
+ releaseDashboardRequest();
+ }
+
+ expect(await screen.findByTestId("dashboard-grid")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("dashboard-grid-skeleton"),
+ ).not.toBeInTheDocument();
+ });
+
it("should display dashboard tabs", async () => {
await setupCommon({ numberOfTabs: 2 });
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx
index 34d0961ae0d..1b49baab565 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx
@@ -1,3 +1,4 @@
+import fetchMock from "fetch-mock";
import _ from "underscore";
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
@@ -8,6 +9,7 @@ import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
import { Route } from "metabase/router";
import { registerStaticVisualizations } from "metabase/static-viz/register";
+import { defer } from "metabase/utils/promise";
import type {
DashboardCard,
DashboardTab,
@@ -36,6 +38,8 @@ export type SetupOpts = {
tokenFeatures?: TokenFeatures;
dashboardTitle: string;
enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
+ /** Holds the dashboard request until `releaseDashboardRequest` is called. */
+ holdDashboardRequest?: boolean;
};
export async function setup(
@@ -46,6 +50,7 @@ export async function setup(
tokenFeatures = createMockTokenFeatures(),
dashboardTitle,
enterprisePlugins,
+ holdDashboardRequest = false,
}: SetupOpts = { dashboardTitle: "" },
) {
mockSettings({
@@ -87,6 +92,14 @@ export async function setup(
tabs,
});
+ const dashboardRequest = defer();
+ if (holdDashboardRequest) {
+ // Registered first, so it answers the dashboard request instead of the
+ // route `setupEmbedDashboardEndpoints` adds.
+ fetchMock.get(`path:/api/embed/dashboard/${MOCK_TOKEN}`, () =>
+ dashboardRequest.promise.then(() => dashboard),
+ );
+ }
setupEmbedDashboardEndpoints(MOCK_TOKEN, dashboard, dashcards);
const pathname = `/embed/dashboard/${MOCK_TOKEN}`;
@@ -109,9 +122,12 @@ export async function setup(
},
);
- if (numberOfTabs > 0) {
+ if (numberOfTabs > 0 && !holdDashboardRequest) {
expect(await screen.findByTestId("dashboard-grid")).toBeInTheDocument();
}
- return view;
+ return {
+ ...view,
+ releaseDashboardRequest: () => dashboardRequest.resolve(),
+ };
}
diff --git a/frontend/src/metabase/utils/dashboard_grid.ts b/frontend/src/metabase/utils/dashboard_grid.ts
index e126e277010..b61257fe3bd 100644
--- a/frontend/src/metabase/utils/dashboard_grid.ts
+++ b/frontend/src/metabase/utils/dashboard_grid.ts
@@ -8,6 +8,8 @@ import { DEFAULT_CARD_SIZE_JSON } from "cljs/metabase.dashboards.constants";
export const GRID_WIDTH = 24;
export const GRID_ASPECT_RATIO = 10 / 9;
+// The dashboard grid skeleton's mobile container query repeats this value,
+// because CSS can't read it. Keep the two in sync.
const MOBILE_BREAKPOINT = 752;
export const GRID_BREAKPOINTS = {
@@ -20,6 +22,15 @@ export const GRID_COLUMNS = {
mobile: 1,
};
+/** The gaps between dashcards, as `[horizontal, vertical]` pixels. */
+export const GRID_MARGINS: Record<
+ keyof typeof GRID_BREAKPOINTS,
+ [number, number]
+> = {
+ desktop: [6, 6],
+ mobile: [6, 10],
+};
+
/** @type {{ width: number, height: number }} */
export const DEFAULT_CARD_SIZE = DEFAULT_CARD_SIZE_JSON;
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 550aae47a38..bdeb19a4ad8 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -579,6 +579,26 @@ export const waitForLoaderToBeRemoved = async () => {
});
};
+/**
+ * Waits for a dashboard to finish loading. While it loads, a dashboard renders
+ * skeletons rather than a loader, so `waitForLoaderToBeRemoved` alone returns
+ * before the dashboard is there.
+ */
+export const waitForDashboardToLoad = async () => {
+ await waitFor(
+ () => {
+ expect(
+ screen.queryByTestId("dashboard-grid-skeleton"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("dashboard-header-skeleton"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+};
+
/**
* jsdom doesn't have offsetHeight and offsetWidth, so we need to mock it
*/