Skip to content

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

Give the dashboard its own chunk (#79645)

Romeo Van Snick033ca3a31921
diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.ts
index cc22dc1e8f6..514d98bdca8 100644
--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.ts
+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-setup-helpers.ts
@@ -5,6 +5,12 @@ export const embedModalEnableEmbeddingCard = () =>
cy.findByTestId("enable-embedding-card");
export const embedModalEnableEmbedding = () => {
+ // Wait for the modal before reading the DOM below. That read is a snapshot
+ // and does not retry, so on an empty body it takes the early return and the
+ // terms are never accepted. The modal is code-split, so it mounts a moment
+ // after it is opened rather than in the same tick.
+ embedModalContent().should("exist");
+
cy.get("body").then(($body) => {
// No card mounted — terms were accepted in the test setup, the section
// bails early via `showSection` (see EnableModularEmbeddingSection /
diff --git a/frontend/src/metabase/app/nav/Navbar.tsx b/frontend/src/metabase/app/nav/Navbar.tsx
index c2068cb6407..98a96b48727 100644
--- a/frontend/src/metabase/app/nav/Navbar.tsx
+++ b/frontend/src/metabase/app/nav/Navbar.tsx
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { useListDatabasesQuery } from "metabase/api";
-import { getDashboard } from "metabase/dashboard/selectors";
+import { getDashboard } from "metabase/dashboard/shell-selectors";
import { AdminNavbar } from "metabase/nav/components/AdminNavbar";
import { MainNavbar } from "metabase/nav/containers/MainNavbar";
import { connect } from "metabase/redux";
diff --git a/frontend/src/metabase/app/selectors.ts b/frontend/src/metabase/app/selectors.ts
index 27d276cd298..f8460eb1875 100644
--- a/frontend/src/metabase/app/selectors.ts
+++ b/frontend/src/metabase/app/selectors.ts
@@ -4,7 +4,7 @@ import {
getDashboard,
getDashboardId,
getIsEditing as getIsEditingDashboard,
-} from "metabase/dashboard/selectors";
+} from "metabase/dashboard/shell-selectors";
import { getCurrentDocument } from "metabase/documents/selectors";
import { getEmbedOptions } from "metabase/embedding/interactive-embedding";
import { getCurrentExploration } from "metabase/explorations/selectors";
diff --git a/frontend/src/metabase/css/dashboard.module.css b/frontend/src/metabase/css/dashboard.module.css
index c222e306c64..6b4af6e2413 100644
--- a/frontend/src/metabase/css/dashboard.module.css
+++ b/frontend/src/metabase/css/dashboard.module.css
@@ -121,8 +121,16 @@
opacity: 0.01;
}
-/* .react-grid-placeholder is a global class from `react-grid-layout` */
-.DashEditing :global(.react-grid-placeholder) {
+/*
+ * .react-grid-placeholder is a global class from `react-grid-layout`.
+ *
+ * Match the library's own `.react-grid-item.react-grid-placeholder` and add a
+ * class, so this outranks it rather than merely following it. The library's
+ * stylesheet is imported by `GridLayout`, which now lives in the dashboard
+ * chunk, so it is injected after this one. At equal specificity that made its
+ * `z-index: 2` win and the placeholder covered the card being dragged.
+ */
+.DashEditing :global(.react-grid-item.react-grid-placeholder) {
z-index: 0;
background-color: var(--mb-color-background_page-secondary) !important;
transition: all 0.15s linear;
diff --git a/frontend/src/metabase/dashboard/actions/cards-typed.ts b/frontend/src/metabase/dashboard/actions/cards-typed.ts
index 4ef9e3f62b0..ec9730da8c1 100644
--- a/frontend/src/metabase/dashboard/actions/cards-typed.ts
+++ b/frontend/src/metabase/dashboard/actions/cards-typed.ts
@@ -1,4 +1,3 @@
-import { createAction } from "@reduxjs/toolkit";
import { t } from "ttag";
import _ from "underscore";
@@ -59,12 +58,14 @@ import {
import { showAutoWireToastNewCard } from "./auto-wire-parameters/actions";
import { closeAddCardAutoWireToasts } from "./auto-wire-parameters/toasts";
import {
- ADD_CARD_TO_DASH,
- ADD_MANY_CARDS_TO_DASH,
+ MARK_NEW_CARD_SEEN,
REMOVE_CARD_FROM_DASH,
TRASH_DASHBOARD_QUESTION_FROM_DASH,
UNDO_REMOVE_CARD_FROM_DASH,
UNDO_TRASH_DASHBOARD_QUESTION_FROM_DASH,
+ addCardToDash,
+ addManyCardsToDash,
+ markNewCardSeen,
setDashCardAttributes,
setDashboardAttributes,
} from "./core";
@@ -87,14 +88,6 @@ export type AddDashCardOpts = NewDashCardOpts & {
};
};
-export const MARK_NEW_CARD_SEEN = "metabase/dashboard/MARK_NEW_CARD_SEEN";
-export const markNewCardSeen = createAction<DashCardId>(MARK_NEW_CARD_SEEN);
-
-export const addCardToDash = createAction<NewDashboardCard>(ADD_CARD_TO_DASH);
-export const addManyCardsToDash = createAction<NewDashboardCard[]>(
- ADD_MANY_CARDS_TO_DASH,
-);
-
export const addDashCardToDashboard =
({ dashId, tabId, dashcardOverrides }: AddDashCardOpts) =>
(dispatch: Dispatch, getState: GetState) => {
@@ -604,3 +597,10 @@ const undoTrashDashboardQuestion = createThunkAction(
dispatch(undoRemoveCardFromDashboard({ dashcardId }));
},
);
+
+export {
+ MARK_NEW_CARD_SEEN,
+ addCardToDash,
+ addManyCardsToDash,
+ markNewCardSeen,
+};
diff --git a/frontend/src/metabase/dashboard/actions/core.ts b/frontend/src/metabase/dashboard/actions/core.ts
index 2cfd65859c7..6ba6f4f8db6 100644
--- a/frontend/src/metabase/dashboard/actions/core.ts
+++ b/frontend/src/metabase/dashboard/actions/core.ts
@@ -10,6 +10,10 @@ import type {
DashboardId,
} from "metabase-types/api";
+import type { NewDashboardCard } from "../utils";
+
+import type { fetchDashboard } from "./data-fetching";
+
export const SET_EDITING_DASHBOARD = "metabase/dashboard/SET_EDITING_DASHBOARD";
export const setEditingDashboard = (
dashboard: Dashboard | null,
@@ -75,6 +79,25 @@ export const ADD_CARD_TO_DASH = "metabase/dashboard/ADD_CARD_TO_DASH";
export const ADD_MANY_CARDS_TO_DASH =
"metabase/dashboard/ADD_MANY_CARDS_TO_DASH";
+// Declared beside their type constants rather than next to the thunks that
+// dispatch them. `reducers.ts` needs the creators, and the thunk modules reach
+// the visualization and parameter stacks, which would then be in the initial
+// bundle because the store imports the reducer on every page.
+export const addCardToDash = createAction<NewDashboardCard>(ADD_CARD_TO_DASH);
+export const addManyCardsToDash = createAction<NewDashboardCard[]>(
+ ADD_MANY_CARDS_TO_DASH,
+);
+
+export const MARK_NEW_CARD_SEEN = "metabase/dashboard/MARK_NEW_CARD_SEEN";
+export const markNewCardSeen = createAction<DashCardId>(MARK_NEW_CARD_SEEN);
+
+// The parameter action types live here rather than in `actions/parameters`, for
+// the same reason as the card ones above: `reducers.ts` names them, and that
+// module reaches the parameter editing UI.
+export const REMOVE_PARAMETER = "metabase/dashboard/REMOVE_PARAMETER";
+export const SET_PARAMETER_VALUE = "metabase/dashboard/SET_PARAMETER_VALUE";
+export const RESET_PARAMETERS = "metabase/dashboard/RESET_PARAMETERS";
+
export const REMOVE_CARD_FROM_DASH = "metabase/dashboard/REMOVE_CARD_FROM_DASH";
export const UNDO_REMOVE_CARD_FROM_DASH =
@@ -126,3 +149,18 @@ export const onReplaceAllDashCardVisualizationSettings = createAction(
},
}),
);
+
+/**
+ * The fulfilled action of the `fetchDashboard` thunk.
+ *
+ * `reducers.ts` only matches on it, and matching is by type string, so it does
+ * not need the thunk itself. Declaring it here keeps the store away from
+ * `actions/data-fetching`, which reaches the whole dashboard data layer. The
+ * payload type is derived from the thunk, so the two cannot drift.
+ */
+export const FETCH_DASHBOARD_FULFILLED =
+ "metabase/dashboard/FETCH_DASHBOARD/fulfilled";
+
+export const fetchDashboardFulfilled = createAction<
+ ReturnType<typeof fetchDashboard.fulfilled>["payload"]
+>(FETCH_DASHBOARD_FULFILLED);
diff --git a/frontend/src/metabase/dashboard/actions/core.unit.spec.ts b/frontend/src/metabase/dashboard/actions/core.unit.spec.ts
new file mode 100644
index 00000000000..e77b6be0a63
--- /dev/null
+++ b/frontend/src/metabase/dashboard/actions/core.unit.spec.ts
@@ -0,0 +1,11 @@
+import { fetchDashboardFulfilled } from "./core";
+import { fetchDashboard } from "./data-fetching";
+
+describe("fetchDashboardFulfilled", () => {
+ // It stands in for `fetchDashboard.fulfilled` so `reducers.ts` can match on it
+ // without importing the thunk. Matching is by type string, so if the two ever
+ // drift apart the reducer silently stops responding to a loaded dashboard.
+ it("has the same action type as the thunk it stands for", () => {
+ expect(fetchDashboardFulfilled.type).toBe(fetchDashboard.fulfilled.type);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/actions/index.ts b/frontend/src/metabase/dashboard/actions/index.ts
index dccba401536..d2bc502baae 100644
--- a/frontend/src/metabase/dashboard/actions/index.ts
+++ b/frontend/src/metabase/dashboard/actions/index.ts
@@ -10,4 +10,5 @@ export * from "./sharing";
export * from "./ui";
export * from "./actions";
export * from "./tabs";
+export * from "./tabs-thunks";
export * from "./trash";
diff --git a/frontend/src/metabase/dashboard/actions/parameters.tsx b/frontend/src/metabase/dashboard/actions/parameters.tsx
index 2dc6708378d..a04afc791a3 100644
--- a/frontend/src/metabase/dashboard/actions/parameters.tsx
+++ b/frontend/src/metabase/dashboard/actions/parameters.tsx
@@ -85,6 +85,9 @@ import {
} from "../utils";
import {
+ REMOVE_PARAMETER,
+ RESET_PARAMETERS,
+ SET_PARAMETER_VALUE,
type SetDashCardAttributesOpts,
setDashCardAttributes,
setDashboardAttributes,
@@ -381,7 +384,6 @@ export function removeParameterAndReferences(
});
}
-export const REMOVE_PARAMETER = "metabase/dashboard/REMOVE_PARAMETER";
export const removeParameter = createThunkAction(
REMOVE_PARAMETER,
(parameterId: ParameterId) => (dispatch, getState) => {
@@ -824,7 +826,6 @@ export const setParameterFilteringParameters = createThunkAction(
},
);
-export const SET_PARAMETER_VALUE = "metabase/dashboard/SET_PARAMETER_VALUE";
export const setParameterValue = createThunkAction(
SET_PARAMETER_VALUE,
(parameterId: ParameterId, value: unknown) => (_dispatch, getState) => {
@@ -879,7 +880,6 @@ export const setParameterValueToDefault = createThunkAction(
},
);
-export const RESET_PARAMETERS = "metabase/dashboard/RESET_PARAMETERS";
export const resetParameters = createThunkAction(
RESET_PARAMETERS,
() => (_dispatch, getState) => {
@@ -1141,3 +1141,5 @@ export const closeAutoApplyFiltersToast = createThunkAction(
}
},
);
+
+export { REMOVE_PARAMETER, RESET_PARAMETERS, SET_PARAMETER_VALUE };
diff --git a/frontend/src/metabase/dashboard/actions/tabs-thunks.ts b/frontend/src/metabase/dashboard/actions/tabs-thunks.ts
new file mode 100644
index 00000000000..0bcfaef8f8f
--- /dev/null
+++ b/frontend/src/metabase/dashboard/actions/tabs-thunks.ts
@@ -0,0 +1,83 @@
+import type { Dispatch, GetState } from "metabase/redux/store";
+import { addUndo } from "metabase/redux/undo";
+import { checkNotNull } from "metabase/utils/types";
+import type { DashboardTabId } from "metabase-types/api";
+
+import { trackCardMoved } from "../analytics";
+import { getDashCardById, getDashcards } from "../selectors";
+
+import { duplicateParameters } from "./parameters";
+import type { MoveDashCardToTabPayload } from "./tabs";
+import {
+ _moveDashCardToTab,
+ duplicateTabAction,
+ takeTempTabId,
+ undoMoveDashCardToTab,
+} from "./tabs";
+import { getDashCardMoveToTabUndoMessage } from "./utils";
+
+/**
+ * The tab thunks that read state or touch the parameter actions.
+ *
+ * They live apart from `tabs.ts` so that `tabsReducer` can stay in a module the
+ * store can import on its own. `tabs.ts` would otherwise reach the dashboard
+ * selectors and the parameter editing actions, and the store imports the
+ * dashboard reducer on every page.
+ */
+export const duplicateTab =
+ (sourceTabId: DashboardTabId | null) =>
+ (dispatch: Dispatch, getState: GetState) => {
+ const newTabId = takeTempTabId();
+
+ const sourceTabDashCards = Object.values(getDashcards(getState())).filter(
+ (dashcard) => dashcard.dashboard_tab_id === sourceTabId,
+ );
+ const sourceParameters = sourceTabDashCards.flatMap((dashcard) =>
+ "inline_parameters" in dashcard ? (dashcard.inline_parameters ?? []) : [],
+ );
+ const newParameters = duplicateParameters(
+ dispatch,
+ getState,
+ sourceParameters,
+ );
+ const sourceToNewParameterIdMap = Object.fromEntries(
+ sourceParameters.map((parameter, index) => [
+ parameter,
+ newParameters[index].id,
+ ]),
+ );
+
+ dispatch(
+ duplicateTabAction({ sourceTabId, newTabId, sourceToNewParameterIdMap }),
+ );
+ };
+
+export const moveDashCardToTab =
+ ({ destinationTabId, dashCardId }: MoveDashCardToTabPayload) =>
+ (dispatch: Dispatch, getState: GetState) => {
+ const dashCard = getDashCardById(getState(), dashCardId);
+
+ const originalCol = dashCard.col;
+ const originalRow = dashCard.row;
+ const originalTabId = checkNotNull(dashCard.dashboard_tab_id);
+
+ dispatch(_moveDashCardToTab({ destinationTabId, dashCardId }));
+
+ dispatch(
+ addUndo({
+ message: getDashCardMoveToTabUndoMessage(dashCard),
+ action: () => {
+ dispatch(
+ undoMoveDashCardToTab({
+ dashCardId,
+ originalCol,
+ originalRow,
+ originalTabId,
+ }),
+ );
+ },
+ }),
+ );
+
+ trackCardMoved(dashCard.dashboard_id);
+ };
diff --git a/frontend/src/metabase/dashboard/actions/tabs.ts b/frontend/src/metabase/dashboard/actions/tabs.ts
index a5d91fa0276..a9da083e9a3 100644
--- a/frontend/src/metabase/dashboard/actions/tabs.ts
+++ b/frontend/src/metabase/dashboard/actions/tabs.ts
@@ -8,14 +8,11 @@ import { CANCEL_EDITING_DASHBOARD } from "metabase/dashboard/actions/core";
import { INITIALIZE, selectTab } from "metabase/redux/dashboard";
import type {
DashboardState,
- Dispatch,
- GetState,
SelectedTabId,
StoreDashboard,
StoreDashcard,
TabDeletionId,
} from "metabase/redux/store";
-import { addUndo } from "metabase/redux/undo";
import { isVirtualDashCard } from "metabase/utils/dashboard";
import { getPositionForNewDashCard } from "metabase/utils/dashboard_grid";
import { checkNotNull } from "metabase/utils/types";
@@ -27,16 +24,13 @@ import type {
ParameterId,
} from "metabase-types/api";
-import { trackCardMoved } from "../analytics";
import { INITIAL_DASHBOARD_STATE } from "../constants";
-import { getDashCardById, getDashcards } from "../selectors";
import {
calculateDashCardRowAfterUndo,
generateTemporaryDashcardId,
} from "../utils";
-import { duplicateParameters } from "./parameters";
-import { getDashCardMoveToTabUndoMessage, getExistingDashCards } from "./utils";
+import { getExistingDashCards } from "./utils";
type CreateNewTabPayload = {
tabId: DashboardTabId;
@@ -61,7 +55,7 @@ type MoveTabPayload = {
sourceTabId: DashboardTabId;
destinationTabId: DashboardTabId;
};
-type MoveDashCardToTabPayload = {
+export type MoveDashCardToTabPayload = {
dashCardId: DashCardId;
destinationTabId: DashboardTabId;
};
@@ -132,45 +126,20 @@ function _createInitialTabs({
return { firstTabId, secondTabId };
}
-export function createNewTab() {
- // Decrement by 2 to leave space for two new tabs if dash doesn't have tabs already
+// Decrement by 2 to leave space for two new tabs if the dashboard has none yet.
+// Exported because `tabs-thunks` allocates ids from the same sequence.
+export function takeTempTabId() {
const tabId = tempTabId;
tempTabId -= 2;
-
- return createNewTabAction({ tabId });
+ return tabId;
}
-const duplicateTabAction = createAction<DuplicateTabPayload>(DUPLICATE_TAB);
-
-export const duplicateTab =
- (sourceTabId: DashboardTabId | null) =>
- (dispatch: Dispatch, getState: GetState) => {
- // Decrement by 2 to leave space for two new tabs if dash doesn't have tabs already
- const newTabId = tempTabId;
- tempTabId -= 2;
-
- const sourceTabDashCards = Object.values(getDashcards(getState())).filter(
- (dashcard) => dashcard.dashboard_tab_id === sourceTabId,
- );
- const sourceParameters = sourceTabDashCards.flatMap((dashcard) =>
- "inline_parameters" in dashcard ? (dashcard.inline_parameters ?? []) : [],
- );
- const newParameters = duplicateParameters(
- dispatch,
- getState,
- sourceParameters,
- );
- const sourceToNewParameterIdMap = Object.fromEntries(
- sourceParameters.map((parameter, index) => [
- parameter,
- newParameters[index].id,
- ]),
- );
+export function createNewTab() {
+ return createNewTabAction({ tabId: takeTempTabId() });
+}
- dispatch(
- duplicateTabAction({ sourceTabId, newTabId, sourceToNewParameterIdMap }),
- );
- };
+export const duplicateTabAction =
+ createAction<DuplicateTabPayload>(DUPLICATE_TAB);
function _selectTab({
state,
@@ -191,37 +160,7 @@ export const renameTab = createAction<RenameTabPayload>(RENAME_TAB);
export const moveTab = createAction<MoveTabPayload>(MOVE_TAB);
-export const moveDashCardToTab =
- ({ destinationTabId, dashCardId }: MoveDashCardToTabPayload) =>
- (dispatch: Dispatch, getState: GetState) => {
- const dashCard = getDashCardById(getState(), dashCardId);
-
- const originalCol = dashCard.col;
- const originalRow = dashCard.row;
- const originalTabId = checkNotNull(dashCard.dashboard_tab_id);
-
- dispatch(_moveDashCardToTab({ destinationTabId, dashCardId }));
-
- dispatch(
- addUndo({
- message: getDashCardMoveToTabUndoMessage(dashCard),
- action: () => {
- dispatch(
- undoMoveDashCardToTab({
- dashCardId,
- originalCol,
- originalRow,
- originalTabId,
- }),
- );
- },
- }),
- );
-
- trackCardMoved(dashCard.dashboard_id);
- };
-
-const _moveDashCardToTab =
+export const _moveDashCardToTab =
createAction<MoveDashCardToTabPayload>(MOVE_DASHCARD_TO_TAB);
export const undoMoveDashCardToTab = createAction<UndoMoveDashCardToTabPayload>(
diff --git a/frontend/src/metabase/dashboard/actions/tabs.unit.spec.ts b/frontend/src/metabase/dashboard/actions/tabs.unit.spec.ts
index e567ff28112..5fa674136ca 100644
--- a/frontend/src/metabase/dashboard/actions/tabs.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/tabs.unit.spec.ts
@@ -28,13 +28,8 @@ import { ORDERS, ORDERS_ID, PRODUCTS } from "metabase-types/api/mocks/presets";
import { TEST_DASHBOARD_STATE } from "../components/DashboardTabs/test-utils";
import { getDashboard, getDashcards } from "../selectors";
-import {
- duplicateTab,
- getIdFromSlug,
- moveTab,
- resetTempTabId,
- tabsReducer,
-} from "./tabs";
+import { getIdFromSlug, moveTab, resetTempTabId, tabsReducer } from "./tabs";
+import { duplicateTab } from "./tabs-thunks";
const ORDERS_CARD = createMockCard({
id: 1,
diff --git a/frontend/src/metabase/dashboard/context/context.redux.ts b/frontend/src/metabase/dashboard/context/context.redux.ts
index 0b13546829e..a629c890127 100644
--- a/frontend/src/metabase/dashboard/context/context.redux.ts
+++ b/frontend/src/metabase/dashboard/context/context.redux.ts
@@ -44,11 +44,11 @@ import {
import {
createNewTab,
deleteTab,
- duplicateTab,
moveTab,
renameTab,
undoDeleteTab,
} from "metabase/dashboard/actions/tabs";
+import { duplicateTab } from "metabase/dashboard/actions/tabs-thunks";
import { connect } from "metabase/redux";
import {
initialize,
diff --git a/frontend/src/metabase/dashboard/reducers.ts b/frontend/src/metabase/dashboard/reducers.ts
index 904eae94722..80fa5a68a9e 100644
--- a/frontend/src/metabase/dashboard/reducers.ts
+++ b/frontend/src/metabase/dashboard/reducers.ts
@@ -7,6 +7,13 @@ import { CARD_UPDATED } from "metabase/redux/cards";
import { SET_PARAMETER_VALUES, initialize } from "metabase/redux/dashboard";
import type { Card } from "metabase-types/api";
+import type {
+ removeCardFromDashboard,
+ removeParameter,
+ resetParameters,
+ setParameterValue,
+ undoRemoveCardFromDashboard,
+} from "./actions";
import {
REMOVE_CARD_FROM_DASH,
REMOVE_PARAMETER,
@@ -15,20 +22,15 @@ import {
UNDO_REMOVE_CARD_FROM_DASH,
addCardToDash,
addManyCardsToDash,
- fetchDashboard,
+ fetchDashboardFulfilled,
markNewCardSeen,
onReplaceAllDashCardVisualizationSettings,
onUpdateDashCardColumnSettings,
onUpdateDashCardVisualizationSettings,
- type removeCardFromDashboard,
- type removeParameter,
- type resetParameters,
setDashCardAttributes,
setMultipleDashCardAttributes,
- type setParameterValue,
- tabsReducer,
- type undoRemoveCardFromDashboard,
-} from "./actions";
+} from "./actions/core";
+import { tabsReducer } from "./actions/tabs";
import { INITIAL_DASHBOARD_STATE } from "./constants";
import {
autoApplyFilters,
@@ -61,7 +63,7 @@ const dashcards = createReducer(
INITIAL_DASHBOARD_STATE.dashcards,
(builder) => {
builder
- .addCase(fetchDashboard.fulfilled, (state, action) => ({
+ .addCase(fetchDashboardFulfilled, (state, action) => ({
...state,
...action.payload.entities.dashcard,
}))
@@ -215,7 +217,7 @@ const draftParameterValues = createReducer(
.addCase(initialize, (state, { payload: { clearCache = true } = {} }) => {
return clearCache ? {} : state;
})
- .addCase(fetchDashboard.fulfilled, (state, { payload }) =>
+ .addCase(fetchDashboardFulfilled, (state, { payload }) =>
payload.preserveParameters && !payload.dashboard.auto_apply_filters
? state
: payload.parameterValues,
diff --git a/frontend/src/metabase/dashboard/selectors.ts b/frontend/src/metabase/dashboard/selectors.ts
index 5bc8edeb272..c538672ce63 100644
--- a/frontend/src/metabase/dashboard/selectors.ts
+++ b/frontend/src/metabase/dashboard/selectors.ts
@@ -50,6 +50,13 @@ import type {
} from "metabase-types/api";
import { getNewCardUrl } from "./actions/getNewCardUrl";
+import {
+ getDashboard,
+ getDashboardBeforeEditing,
+ getDashboardId,
+ getDashboards,
+ getIsEditing,
+} from "./shell-selectors";
import {
canResetFilter,
findDashCardForInlineParameter,
@@ -73,19 +80,12 @@ function isEditParameterSidebar(
return sidebar.name === SIDEBAR_NAME.editParameter;
}
-export const getDashboardBeforeEditing = (state: State) =>
- state.dashboard.editingDashboard;
-
-export const getIsEditing = (state: State) =>
- Boolean(getDashboardBeforeEditing(state));
-
export const getClickBehaviorSidebarDashcard = (state: State) => {
const { sidebar, dashcards } = state.dashboard;
return isClickBehaviorSidebar(sidebar)
? dashcards[sidebar.props?.dashcardId]
: null;
};
-export const getDashboards = (state: State) => state.dashboard.dashboards;
export const getDashcardDataMap = (state: State) =>
state.dashboard.dashcardData;
@@ -159,14 +159,6 @@ export const getIsShowDashboardSettingsSidebar = createSelector(
(sidebar) => sidebar.name === SIDEBAR_NAME.settings,
);
-export const getDashboardId = (state: State) => state.dashboard.dashboardId;
-
-export const getDashboard = createSelector(
- [getDashboardId, getDashboards],
- (dashboardId, dashboards) =>
- dashboardId !== null ? dashboards[dashboardId] : undefined,
-);
-
export const getDashcards = (state: State) => state.dashboard.dashcards;
export const getDashCardById = (state: State, dashcardId: DashCardId) => {
@@ -721,3 +713,13 @@ export const getCanResetFilters = createSelector(
[getFiltersToReset],
(filtersToReset) => filtersToReset.length > 0,
);
+
+// Defined in a leaf module so the app shell can read them without pulling this
+// one in. Re-exported so every existing call site is unchanged.
+export {
+ getDashboard,
+ getDashboardBeforeEditing,
+ getDashboardId,
+ getDashboards,
+ getIsEditing,
+};
diff --git a/frontend/src/metabase/dashboard/shell-selectors.ts b/frontend/src/metabase/dashboard/shell-selectors.ts
new file mode 100644
index 00000000000..d98e7c7813f
--- /dev/null
+++ b/frontend/src/metabase/dashboard/shell-selectors.ts
@@ -0,0 +1,29 @@
+import { createSelector } from "@reduxjs/toolkit";
+
+import type { State, StoreDashboard } from "metabase/redux/store";
+
+/**
+ * The dashboard selectors the app shell reads on every page.
+ *
+ * They live here rather than in `dashboard/selectors` so that the nav bar and
+ * `app/selectors` can name them without importing that module. `selectors.ts`
+ * reaches metabase-lib, the parameter utilities and the visualization settings,
+ * so anything that imports it puts the dashboard feature in the initial bundle.
+ *
+ * `dashboard/selectors` re-exports all of these, so no other call site changes.
+ */
+export const getDashboardId = (state: State) => state.dashboard.dashboardId;
+
+export const getDashboards = (state: State) => state.dashboard.dashboards;
+
+export const getDashboardBeforeEditing = (state: State) =>
+ state.dashboard.editingDashboard;
+
+export const getIsEditing = (state: State) =>
+ Boolean(getDashboardBeforeEditing(state));
+
+export const getDashboard = createSelector(
+ [getDashboardId, getDashboards],
+ (dashboardId, dashboards): StoreDashboard | undefined =>
+ dashboardId !== null ? dashboards[dashboardId] : undefined,
+);
diff --git a/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.tsx b/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.tsx
index 6a5c818289a..04aae6a966a 100644
--- a/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.tsx
+++ b/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.tsx
@@ -1,12 +1,12 @@
import { useCallback, useEffect, useState } from "react";
-import { useNavigate } from "metabase/router";
+import { getIsNavigationPending, useNavigate } from "metabase/router";
import * as Urls from "metabase/urls";
import type { RouteParams } from "../../pages/DataModel/types";
import { TablePicker } from "./components";
-import type { TreePath } from "./types";
+import type { ChangeOptions, TreePath } from "./types";
type Props = TreePath & {
params: RouteParams;
@@ -27,8 +27,19 @@ export function RouterTablePicker({
} = props;
const onChange = useCallback(
- (value: TreePath) => {
+ (value: TreePath, options?: ChangeOptions) => {
setValue(value);
+
+ // The tree selects a lone database, and then its lone schema, once its
+ // data arrives. That mirrors into the URL long after the page opened, so
+ // it can land while the user is already on their way to another page. A
+ // `route.lazy` destination keeps this page mounted until its chunk
+ // resolves, and this replace would take that pending navigation's place.
+ // A pick the user made is theirs and still navigates.
+ if (options?.isAutomatic && getIsNavigationPending()) {
+ return;
+ }
+
navigate(Urls.dataStudioData(value), { replace: true });
},
[navigate],
diff --git a/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.unit.spec.tsx
new file mode 100644
index 00000000000..2ea4ae294f3
--- /dev/null
+++ b/frontend/src/metabase/data-studio/data-model/components/TablePicker/wrappers.unit.spec.tsx
@@ -0,0 +1,84 @@
+import userEvent from "@testing-library/user-event";
+
+import { render, screen } from "__support__/ui";
+import { getIsNavigationPending } from "metabase/router";
+
+import type { ChangeOptions, TreePath } from "./types";
+import { RouterTablePicker } from "./wrappers";
+
+const navigate = jest.fn();
+
+jest.mock("metabase/router", () => ({
+ ...jest.requireActual("metabase/router"),
+ useNavigate: () => navigate,
+ getIsNavigationPending: jest.fn(() => false),
+}));
+
+const PICKED: TreePath = { databaseId: 1, schemaName: "PUBLIC" };
+
+jest.mock("./components", () => ({
+ TablePicker: ({
+ onChange,
+ }: {
+ onChange: (path: TreePath, options?: ChangeOptions) => void;
+ }) => (
+ <>
+ <button onClick={() => onChange(PICKED, { isAutomatic: true })}>
+ automatic
+ </button>
+ <button onClick={() => onChange(PICKED)}>manual</button>
+ </>
+ ),
+}));
+
+function setup() {
+ render(<RouterTablePicker params={{}} setOnUpdateCallback={jest.fn()} />);
+}
+
+describe("RouterTablePicker", () => {
+ beforeEach(() => {
+ navigate.mockClear();
+ jest.mocked(getIsNavigationPending).mockReturnValue(false);
+ });
+
+ it("mirrors an automatic selection into the URL", async () => {
+ setup();
+
+ await userEvent.click(screen.getByText("automatic"));
+
+ expect(navigate).toHaveBeenCalledWith(
+ "/data-studio/data/database/1/schema/1:PUBLIC",
+ {
+ replace: true,
+ },
+ );
+ });
+
+ // The tree selects a lone database, and then its lone schema, once its data
+ // arrives, which can be long after the user asked to go somewhere else. A
+ // `route.lazy` destination keeps this page mounted until its chunk resolves,
+ // so this replace would take the pending navigation's place and strand the
+ // user here. See glossary.cy.spec.ts, which caught it.
+ it("skips an automatic selection while a navigation is pending", async () => {
+ jest.mocked(getIsNavigationPending).mockReturnValue(true);
+ setup();
+
+ await userEvent.click(screen.getByText("automatic"));
+
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("still follows a selection the user made", async () => {
+ jest.mocked(getIsNavigationPending).mockReturnValue(true);
+ setup();
+
+ await userEvent.click(screen.getByText("manual"));
+
+ expect(navigate).toHaveBeenCalledWith(
+ "/data-studio/data/database/1/schema/1:PUBLIC",
+ {
+ replace: true,
+ },
+ );
+ });
+});
diff --git a/frontend/src/metabase/new/components/NewModals/NewModals.tsx b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
index c86eb9fa3d3..7e4a8e5adf7 100644
--- a/frontend/src/metabase/new/components/NewModals/NewModals.tsx
+++ b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect } from "react";
+import { Suspense, lazy, useCallback, useEffect } from "react";
import ActionCreator from "metabase/actions/containers/ActionCreator";
import { CreateDashboardModal } from "metabase/common/CreateDashboard/CreateDashboardModal";
@@ -8,8 +8,6 @@ import CreateCollectionModal, {
import { useInitialCollectionId } from "metabase/common/collections/hooks";
import { UpgradeModal } from "metabase/common/components/upsells/components/UpgradeModal";
import { STATIC_LEGACY_EMBEDDING_TYPE } from "metabase/embedding/constants";
-import { LegacyStaticEmbeddingModal } from "metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal";
-import { SdkIframeEmbedSetupModal } from "metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal";
import { PaletteShortcutsModal } from "metabase/palette/components/PaletteShortcutsModal/PaletteShortcutsModal";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
import type {
@@ -25,6 +23,30 @@ import { Modal, PREVENT_AUTOCOMPLETE_CLIPPING_MODAL_PROPS } from "metabase/ui";
import * as Urls from "metabase/urls";
import type { WritebackAction } from "metabase-types/api";
+/**
+ * The embed setup modals, fetched when one is opened.
+ *
+ * `NewModals` is mounted for the whole session, so importing these directly put
+ * them in the initial bundle. They reach the dashboard actions and selectors,
+ * which is most of the dashboard feature. Nothing renders while they load: a
+ * modal that has just been asked for has no earlier state to preserve.
+ */
+const LegacyStaticEmbeddingModal = lazy(() =>
+ import("metabase/embedding/embedding-iframe-sdk-setup/components/LegacyStaticEmbeddingModal").then(
+ ({ LegacyStaticEmbeddingModal }) => ({
+ default: LegacyStaticEmbeddingModal,
+ }),
+ ),
+);
+
+const SdkIframeEmbedSetupModal = lazy(() =>
+ import("metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal").then(
+ ({ SdkIframeEmbedSetupModal }) => ({
+ default: SdkIframeEmbedSetupModal,
+ }),
+ ),
+);
+
const getCurrentOpenModalState = <TProps,>(state: State) =>
// Unjustified type cast. FIXME
state.modal as ModalState<TProps>;
@@ -115,11 +137,13 @@ export const NewModals = () => {
// Unjustified type cast. FIXME
const props = currentNewModalProps as SdkIframeEmbedSetupModalProps;
return (
- <SdkIframeEmbedSetupModal
- opened
- initialState={props?.initialState}
- onClose={handleModalClose}
- />
+ <Suspense fallback={null}>
+ <SdkIframeEmbedSetupModal
+ opened
+ initialState={props?.initialState}
+ onClose={handleModalClose}
+ />
+ </Suspense>
);
}
case STATIC_LEGACY_EMBEDDING_TYPE: {
@@ -127,13 +151,15 @@ export const NewModals = () => {
const props = currentNewModalProps as LegacyStaticEmbeddingModalProps;
return (
- <LegacyStaticEmbeddingModal
- experience={props?.experience}
- dashboardId={props?.dashboardId}
- questionId={props?.questionId}
- parentInitialState={props?.parentInitialState}
- onClose={handleModalClose}
- />
+ <Suspense fallback={null}>
+ <LegacyStaticEmbeddingModal
+ experience={props?.experience}
+ dashboardId={props?.dashboardId}
+ questionId={props?.questionId}
+ parentInitialState={props?.parentInitialState}
+ onClose={handleModalClose}
+ />
+ </Suspense>
);
}
case "upgrade":
diff --git a/frontend/src/metabase/query_builder/actions/url.ts b/frontend/src/metabase/query_builder/actions/url.ts
index 89b439811d2..fcf231b706c 100644
--- a/frontend/src/metabase/query_builder/actions/url.ts
+++ b/frontend/src/metabase/query_builder/actions/url.ts
@@ -3,7 +3,7 @@ import { parse as parseUrl } from "url";
import { isEqualCard } from "metabase/common/utils/card";
import { createThunkAction } from "metabase/redux";
import type { Path } from "metabase/router";
-import { navigate } from "metabase/router";
+import { getIsNavigationPending, navigate } from "metabase/router";
import { getBasename } from "metabase/utils/basename";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -129,6 +129,16 @@ export const updateUrl = createThunkAction(
return;
}
+ // Saving a card finishes asynchronously, so this can run after the user
+ // has already been sent somewhere else, for instance to the dashboard the
+ // question was just saved into. A `route.lazy` destination keeps the query
+ // builder mounted until its chunk resolves, and this navigation would
+ // replace that pending one. The URL only mirrors the card, so there is
+ // nothing to write if we are leaving.
+ if (getIsNavigationPending()) {
+ return;
+ }
+
if (replaceState == null) {
const isSameMode =
getQueryBuilderModeFromLocation(to).queryBuilderMode ===
diff --git a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
index 2f80b1dff0d..ad4e96ee12a 100644
--- a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
@@ -12,7 +12,12 @@ import {
createMockQueryBuilderUIControlsState,
createMockState,
} from "metabase/redux/store/mocks";
-import { type NavigateOptions, type To, navigate } from "metabase/router";
+import {
+ type NavigateOptions,
+ type To,
+ getIsNavigationPending,
+ navigate,
+} from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import * as Urls from "metabase/urls";
import { checkNotNull } from "metabase/utils/types";
@@ -34,6 +39,7 @@ registerVisualizations();
jest.mock("metabase/router", () => ({
...jest.requireActual("metabase/router"),
navigate: jest.fn(),
+ getIsNavigationPending: jest.fn(() => false),
}));
type UpdateUrlOptions = Parameters<typeof updateUrl>[1];
@@ -117,6 +123,9 @@ async function setup({
describe("QB Actions > updateUrl (navigation producer contract)", () => {
beforeEach(() => {
jest.mocked(navigate).mockClear();
+ // Reset here rather than at the end of the test that sets it, so a failing
+ // expectation cannot leak the pending state into the tests that follow.
+ jest.mocked(getIsNavigationPending).mockReturnValue(false);
jest.spyOn(console, "warn").mockImplementation(() => {});
window.history.replaceState({}, "", "/");
});
@@ -259,6 +268,22 @@ describe("QB Actions > updateUrl (navigation producer contract)", () => {
});
});
+ // Saving a card finishes asynchronously. A `route.lazy` destination keeps the
+ // query builder mounted while its chunk loads, so this can run after the user
+ // has been sent elsewhere, and a navigation here would replace that pending
+ // one. See dashboard-questions.cy.spec.js, which caught it.
+ it("does not navigate while the router has a navigation pending", async () => {
+ jest.mocked(getIsNavigationPending).mockReturnValue(true);
+
+ const card = createSavedStructuredCard();
+ await setup({
+ question: buildSavedQuestion(card),
+ options: { dirty: true },
+ });
+
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
it("flows objectId through onto location.state", async () => {
const card = createSavedStructuredCard();
const question = buildSavedQuestion(card);
diff --git a/frontend/src/metabase/router/create-router.tsx b/frontend/src/metabase/router/create-router.tsx
index 0c5b4ee6d90..86c60783be5 100644
--- a/frontend/src/metabase/router/create-router.tsx
+++ b/frontend/src/metabase/router/create-router.tsx
@@ -7,7 +7,7 @@ import {
} from "react-router";
import { AppShell } from "./AppShell";
-import { setRouterExpected } from "./navigator";
+import { setRouter, setRouterExpected } from "./navigator";
export type MemoryTestRouter = DataRouter;
@@ -47,14 +47,23 @@ function withAppShell(
];
}
+/**
+ * `getIsNavigationPending` reads the router's own navigation state, which
+ * react-router publishes nowhere else outside a component.
+ */
+function register(router: DataRouter): DataRouter {
+ setRouter(router);
+ return router;
+}
+
export function createAppRouter(
routes: RouteObject[],
basename?: string,
hydrateFallback?: ReactNode,
): DataRouter {
- return createBrowserRouter(withAppShell(routes, hydrateFallback), {
- basename,
- });
+ return register(
+ createBrowserRouter(withAppShell(routes, hydrateFallback), { basename }),
+ );
}
export function createMemoryAppRouter(
@@ -66,8 +75,10 @@ export function createMemoryAppRouter(
const entry = initialRoute.startsWith("/")
? initialRoute
: `/${initialRoute}`;
- return createMemoryRouter(withAppShell(routes, hydrateFallback), {
- basename,
- initialEntries: [entry],
- });
+ return register(
+ createMemoryRouter(withAppShell(routes, hydrateFallback), {
+ basename,
+ initialEntries: [entry],
+ }),
+ );
}
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 23461eb1531..78de6f81109 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -32,6 +32,7 @@ export {
export { queryToSearch, toFacadeLocation } from "./location";
export { createLocationMirror, type LocationMirror } from "./location-mirror";
export {
+ getIsNavigationPending,
navigate,
notifyLocationListeners,
subscribeLocation,
diff --git a/frontend/src/metabase/router/lazy-route.unit.spec.tsx b/frontend/src/metabase/router/lazy-route.unit.spec.tsx
index 192141ae680..b412dc50f9e 100644
--- a/frontend/src/metabase/router/lazy-route.unit.spec.tsx
+++ b/frontend/src/metabase/router/lazy-route.unit.spec.tsx
@@ -1,5 +1,11 @@
import { render, renderRoutes, screen } from "__support__/ui";
-import { type RouteObject, RouterProviderMemory } from "metabase/router";
+import {
+ type NavigateFunction,
+ type RouteObject,
+ RouterProviderMemory,
+ getIsNavigationPending,
+ useNavigate,
+} from "metabase/router";
function Home() {
return <span data-testid="home">home</span>;
@@ -88,6 +94,34 @@ describe("a lazy route", () => {
expect(screen.queryByTestId("split")).not.toBeInTheDocument();
});
+ // How a caller sits that window out. `getIsNavigationPending` reads it from
+ // the router, so it is already true on the line after the navigate rather than
+ // after the render that follows. A URL sync running in a promise callback gets
+ // no render in between, which is how the query builder came to replace the
+ // dashboard it had just saved a question into.
+ it("reports the window to a caller navigating in the same tick", async () => {
+ const { navigate } = setupCapturingNavigate();
+
+ navigate?.("/split");
+ expect(getIsNavigationPending()).toBe(true);
+
+ expect(await screen.findByTestId("split")).toBeInTheDocument();
+ expect(getIsNavigationPending()).toBe(false);
+ });
+
+ // The other half of the contract, and the more easily broken one. A route that
+ // is already loaded commits during the call, so there is no window to sit out
+ // and a URL sync that follows must still run. Reporting one here strands
+ // anything that mirrors state into the URL, which is most of the query
+ // builder. See QueryBuilder.unsaved-changes-warning.unit.spec.tsx.
+ it("reports no window for a navigation that commits during the call", () => {
+ const { navigate } = setupCapturingNavigate();
+
+ navigate?.("/plain");
+
+ expect(getIsNavigationPending()).toBe(false);
+ });
+
// What prefetching on hover buys, and what it does not. The module is already
// in hand, so the gap is a tick rather than a round trip, but the router still
// awaits `lazy` and still commits the location late.
@@ -129,3 +163,31 @@ describe("a lazy route", () => {
expect(router?.location.pathname).toBe("/split");
});
});
+
+/**
+ * Renders with a `useNavigate` handle, so a test can navigate and then read the
+ * pending state in the same tick, the way a promise callback does.
+ */
+function setupCapturingNavigate() {
+ let navigate: NavigateFunction | undefined;
+
+ function CaptureNavigate() {
+ navigate = useNavigate();
+ return <span data-testid="home">home</span>;
+ }
+
+ renderRoutes(
+ [
+ { path: "/", element: <CaptureNavigate /> },
+ { path: "/plain", element: <Split /> },
+ { path: "/split", lazy: async () => ({ Component: Split }) },
+ ],
+ { initialRoute: "/" },
+ );
+
+ return {
+ get navigate() {
+ return navigate;
+ },
+ };
+}
diff --git a/frontend/src/metabase/router/navigator.ts b/frontend/src/metabase/router/navigator.ts
index 12a7e070b93..a7ff176233e 100644
--- a/frontend/src/metabase/router/navigator.ts
+++ b/frontend/src/metabase/router/navigator.ts
@@ -1,4 +1,9 @@
-import type { NavigateFunction, NavigateOptions, To } from "react-router";
+import type {
+ DataRouter,
+ NavigateFunction,
+ NavigateOptions,
+ To,
+} from "react-router";
import type { Location as HistoryLocation } from "./types";
@@ -39,6 +44,42 @@ export function setRouterExpected(expected: boolean): void {
isRouterExpected = expected;
}
+/**
+ * The live router, registered as it is built. Only `getIsNavigationPending`
+ * reads it, and only for state react-router publishes nowhere else outside a
+ * component.
+ */
+let currentRouter: DataRouter | null = null;
+
+export function setRouter(router: DataRouter | null): void {
+ currentRouter = router;
+}
+
+/**
+ * Whether the router has accepted a navigation it has not committed yet.
+ *
+ * `useIsNavigating` answers the same question during a render. This is for the
+ * callers that cannot hold a hook, the same ones `navigate` below exists for.
+ *
+ * A `route.lazy` destination is what makes the window real: the router resolves
+ * the module before it commits the location, so the old page stays mounted at
+ * the old URL. Anything that navigates in that window replaces the pending
+ * navigation rather than queueing behind it, and the destination the user asked
+ * for is dropped. Effects that mirror state into the URL have to sit it out.
+ *
+ * Read from the router rather than tracked alongside it, because the router
+ * updates this synchronously and a React render does not: a caller navigating
+ * from a promise callback can run again before anything re-renders. It is
+ * precise in the other direction too. A navigation to a route that is already
+ * loaded commits during the call, so the window is never open for one, and a
+ * URL sync that follows it still runs.
+ */
+export function getIsNavigationPending(): boolean {
+ return (
+ currentRouter != null && currentRouter.state.navigation.state !== "idle"
+ );
+}
+
export function setRouterNavigate(navigate: NavigateFunction | null): void {
currentNavigate = navigate;
if (!navigate) {
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 46bdce7876e..222803bfaac 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -30,11 +30,6 @@ import { MoveQuestionsIntoDashboardsModal } from "metabase/common/components/Mov
import { NotFoundFallbackPage } from "metabase/common/components/NotFoundFallbackPage";
import { UnsubscribePage } from "metabase/common/components/Unsubscribe";
import { UserCollectionList } from "metabase/common/components/UserCollectionList";
-import { DashboardCopyModalConnected } from "metabase/dashboard/components/DashboardCopyModal";
-import { DashboardMoveModalConnected } from "metabase/dashboard/components/DashboardMoveModal";
-import { ArchiveDashboardModalConnected } from "metabase/dashboard/containers/ArchiveDashboardModal";
-import { AutomaticDashboardApp } from "metabase/dashboard/containers/AutomaticDashboardApp";
-import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";
import { getDataStudioRoutes } from "metabase/data-studio/routes";
import { TableDetailPage } from "metabase/detail-view/pages/TableDetailPage";
import { getRoutes as getExplorationsRoutes } from "metabase/explorations/routes";
@@ -123,6 +118,20 @@ const metabotQueryBuilder = () =>
* Documents, in their own chunk. It carries the rich text editing stack, which
* nothing outside the document page needs on first paint.
*/
+/**
+ * The dashboard, in its own chunk. Its three modal children defer separately, so
+ * opening one does not depend on the page chunk having arrived.
+ */
+const dashboardApp = () =>
+ import("metabase/dashboard/containers/DashboardApp/DashboardApp").then(
+ ({ DashboardApp }) => ({ Component: DashboardApp }),
+ );
+
+const automaticDashboardApp = () =>
+ import("metabase/dashboard/containers/AutomaticDashboardApp").then(
+ ({ AutomaticDashboardApp }) => ({ Component: AutomaticDashboardApp }),
+ );
+
const documentPage = () =>
import("metabase/documents/routes").then(({ DocumentPageOuter }) => ({
Component: DocumentPageOuter,
@@ -153,6 +162,8 @@ registerPagePrefetch("/document/", documentPage);
// against the document prefix instead: 15 kb fetched alongside a page of 337 kb,
// in exchange for the sidesheet already being there when it is opened.
registerPagePrefetch("/document/", commentsSidesheet);
+registerPagePrefetch("/dashboard/", dashboardApp);
+registerPagePrefetch("/auto/dashboard/", automaticDashboardApp);
export const getRoutes = (store: AppStore): RouteObject[] => [
{
@@ -311,20 +322,36 @@ export const getRoutes = (store: AppStore): RouteObject[] => [
{
path: "dashboard/:slug",
- element: <DashboardApp />,
- children: toRouteObjects(
- <>
- {modalRoute("move", DashboardMoveModalConnected, {
- noWrap: true,
- })}
- {modalRoute("copy", DashboardCopyModalConnected, {
- noWrap: true,
- })}
- {modalRoute("archive", ArchiveDashboardModalConnected, {
- noWrap: true,
- })}
- </>,
- ),
+ lazy: dashboardApp,
+ children: [
+ lazyModalRoute(
+ "move",
+ () =>
+ import("metabase/dashboard/components/DashboardMoveModal").then(
+ ({ DashboardMoveModalConnected }) =>
+ DashboardMoveModalConnected,
+ ),
+ { noWrap: true },
+ ),
+ lazyModalRoute(
+ "copy",
+ () =>
+ import("metabase/dashboard/components/DashboardCopyModal").then(
+ ({ DashboardCopyModalConnected }) =>
+ DashboardCopyModalConnected,
+ ),
+ { noWrap: true },
+ ),
+ lazyModalRoute(
+ "archive",
+ () =>
+ import("metabase/dashboard/containers/ArchiveDashboardModal").then(
+ ({ ArchiveDashboardModalConnected }) =>
+ ArchiveDashboardModalConnected,
+ ),
+ { noWrap: true },
+ ),
+ ],
},
{
@@ -421,7 +448,7 @@ export const getRoutes = (store: AppStore): RouteObject[] => [
},
// INDIVIDUAL DASHBOARDS
- { path: "/auto/dashboard/*", element: <AutomaticDashboardApp /> },
+ { path: "/auto/dashboard/*", lazy: automaticDashboardApp },
// REFERENCE
...getReferenceRoutes(),