Skip to content

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

fix: show confirmation on escape, clickoutside and browser's back actions for SidebarCacheForm (#66173)

Egor Grushin554ab26066d6
diff --git a/e2e/test/scenarios/admin/performance/helpers/modals-helpers.ts b/e2e/test/scenarios/admin/performance/helpers/modals-helpers.ts
new file mode 100644
index 00000000000..dc108eead5c
--- /dev/null
+++ b/e2e/test/scenarios/admin/performance/helpers/modals-helpers.ts
@@ -0,0 +1,7 @@
+export const confirmModal = () =>
+ cy.findByTestId("confirm-modal").should("be.visible");
+
+export const cancelConfirmationModal = () =>
+ confirmModal()
+ .findByRole("button", { name: /Cancel/ })
+ .click();
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
index 664d18cc087..dc81d8cbe1c 100644
--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
@@ -1,7 +1,6 @@
import { assoc } from "icepick";
import _ from "underscore";
-const { H } = cy;
import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
@@ -10,6 +9,7 @@ import {
ORDERS_DASHBOARD_ID,
ORDERS_QUESTION_ID,
} from "e2e/support/cypress_sample_instance_data";
+import { cancelConfirmationModal } from "e2e/test/scenarios/admin/performance/helpers/modals-helpers";
import { GRID_WIDTH } from "metabase/lib/dashboard_grid";
import {
createMockVirtualCard,
@@ -19,10 +19,13 @@ import {
import { interceptPerformanceRoutes } from "../admin/performance/helpers/e2e-performance-helpers";
import {
adaptiveRadioButton,
+ cacheStrategySidesheet,
durationRadioButton,
openSidebarCacheStrategyForm,
} from "../admin/performance/helpers/e2e-strategy-form-helpers";
+const { H } = cy;
+
const { ORDERS, ORDERS_ID, PRODUCTS, PEOPLE, PEOPLE_ID } = SAMPLE_DATABASE;
// There's a race condition when saving a dashboard
@@ -1688,6 +1691,46 @@ describe("scenarios > dashboard > caching", () => {
});
});
+ /**
+ * @note There is a similar test for closing the cache form when it's dirty
+ * It's in the Cypress describe block labeled "scenarios > question > caching"
+ */
+ it("should guard closing caching form if it's dirty on different actions", () => {
+ interceptPerformanceRoutes();
+ /**
+ * we need to populate the history via react router by clicking route's links
+ * in order to imitate a user who clicks "back" and "forward" button
+ */
+ cy.visit("/");
+ cy.findByTestId("main-navbar-root").findByText("Our analytics").click();
+ cy.findByTestId("collection-table")
+ .findByText("Orders in a dashboard")
+ .click();
+
+ openSidebarCacheStrategyForm("dashboard");
+
+ cacheStrategySidesheet().within(() => {
+ cy.findByText(/Caching settings/).should("be.visible");
+ durationRadioButton().click();
+ });
+ // Action 1: clicking on cross button
+ cacheStrategySidesheet().findByRole("button", { name: /Close/ }).click();
+ cancelConfirmationModal();
+ // Action 2: ESC button
+ cy.get("body").type("{esc}");
+ cancelConfirmationModal();
+ // Action 3: click outside
+ // When a user clicks somewhere outside he basically clicks on the top one
+ cy.findAllByTestId("modal-overlay")
+ .should("have.length.gte", 1)
+ .last()
+ .click();
+ cancelConfirmationModal();
+ // Action 4: browser's Back action
+ cy.go("back");
+ cancelConfirmationModal();
+ });
+
it("can click 'Clear cache' for a dashboard", () => {
interceptPerformanceRoutes();
H.visitDashboard(ORDERS_DASHBOARD_ID);
diff --git a/e2e/test/scenarios/question/caching.cy.spec.js b/e2e/test/scenarios/question/caching.cy.spec.js
index 4f3cd6e4a3b..3074cde6357 100644
--- a/e2e/test/scenarios/question/caching.cy.spec.js
+++ b/e2e/test/scenarios/question/caching.cy.spec.js
@@ -1,5 +1,5 @@
-const { H } = cy;
import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+import { cancelConfirmationModal } from "e2e/test/scenarios/admin/performance/helpers/modals-helpers";
import { interceptPerformanceRoutes } from "../admin/performance/helpers/e2e-performance-helpers";
import {
@@ -10,6 +10,8 @@ import {
questionSettingsSidesheet,
} from "../admin/performance/helpers/e2e-strategy-form-helpers";
+const { H } = cy;
+
describe("scenarios > question > caching", () => {
beforeEach(() => {
H.restore();
@@ -64,6 +66,44 @@ describe("scenarios > question > caching", () => {
});
});
+ /**
+ * @note There is a similar test for closing the cache form when it's dirty
+ * It's in the Cypress describe block labeled "scenarios > dashboard > caching"
+ */
+ it("should guard closing caching form if it's dirty on different actions", () => {
+ interceptPerformanceRoutes();
+ /**
+ * we need to populate the history via react router by clicking route's links
+ * in order to imitate a user who clicks "back" button
+ */
+ cy.visit("/");
+ cy.findByTestId("main-navbar-root").findByText("Our analytics").click();
+ cy.findByTestId("collection-table").findByText("Orders").click();
+
+ openSidebarCacheStrategyForm("question");
+
+ cacheStrategySidesheet().within(() => {
+ cy.findByText(/Caching settings/).should("be.visible");
+ durationRadioButton().click();
+ });
+ // Action 1: clicking on cross button
+ cacheStrategySidesheet().findByRole("button", { name: /Close/ }).click();
+ cancelConfirmationModal();
+ // Action 2: ESC button
+ cy.get("body").type("{esc}");
+ cancelConfirmationModal();
+ // Action 3: click outside
+ // When a user clicks somewhere outside he basically clicks on the top one
+ cy.findAllByTestId("modal-overlay")
+ .should("have.length.gte", 1)
+ .last()
+ .click();
+ cancelConfirmationModal();
+ // Action 4: browser's Back action
+ cy.go("back");
+ cancelConfirmationModal();
+ });
+
it("can click 'Clear cache' for a question", () => {
interceptPerformanceRoutes();
H.visitQuestion(ORDERS_QUESTION_ID);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx
index 63b8df0e6fa..b50acc6eded 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx
@@ -1,5 +1,4 @@
import { useCallback, useMemo } from "react";
-import { withRouter } from "react-router";
import { t } from "ttag";
import _ from "underscore";
@@ -15,13 +14,16 @@ import type { CacheStrategy } from "metabase-types/api";
import { getItemId, getItemName } from "./utils";
-const SidebarCacheForm_Base = ({
+export const SidebarCacheForm = ({
item,
model,
+ isOpen,
onClose,
+ withOverlay = true,
+ overlayProps,
onBack,
...stackProps
-}: SidebarCacheFormProps & { onBack: () => void }) => {
+}: SidebarCacheFormProps) => {
const configurableModels = useMemo(() => [model], [model]);
const id: number = getItemId(model, item);
const { configs, setConfigs, loading, error } = useCacheConfigs({
@@ -46,24 +48,26 @@ const SidebarCacheForm_Base = ({
);
const {
- askBeforeDiscardingChanges,
confirmationModal,
- isStrategyFormDirty,
setIsStrategyFormDirty,
+ isStrategyFormDirty,
+ askBeforeDiscardingChanges,
} = useConfirmIfFormIsDirty();
const headingId = `${model}-sidebar-caching-settings-heading`;
return (
<SidesheetSubPage
- isOpen
title={t`Caching settings`}
+ isOpen={isOpen}
+ onClose={() =>
+ isStrategyFormDirty ? askBeforeDiscardingChanges(onClose) : onClose()
+ }
+ withOverlay={withOverlay}
+ overlayProps={overlayProps}
onBack={() =>
isStrategyFormDirty ? askBeforeDiscardingChanges(onBack) : onBack()
}
- onClose={() => {
- isStrategyFormDirty ? askBeforeDiscardingChanges(onClose) : onClose();
- }}
>
<Stack
align="space-between"
@@ -92,5 +96,3 @@ const SidebarCacheForm_Base = ({
</SidesheetSubPage>
);
};
-
-export const SidebarCacheForm = withRouter(SidebarCacheForm_Base);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx
index 65ed3ff3e09..d5cc7704b96 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx
@@ -1,6 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from "react";
-import type { InjectedRouter, Route } from "react-router";
-import { withRouter } from "react-router";
import { t } from "ttag";
import _ from "underscore";
@@ -33,13 +31,7 @@ import { formatValueForSorting } from "./utils";
type CacheableItemResult = DashboardResult | QuestionResult;
-const _StrategyEditorForQuestionsAndDashboards = ({
- router,
- route,
-}: {
- router: InjectedRouter;
- route?: Route;
-}) => {
+export const StrategyEditorForQuestionsAndDashboards = () => {
const [
// The targetId is the id of the object that is currently being edited
targetId,
@@ -178,7 +170,7 @@ const _StrategyEditorForQuestionsAndDashboards = ({
confirmationModal,
isStrategyFormDirty,
setIsStrategyFormDirty,
- } = useConfirmIfFormIsDirty(router, route);
+ } = useConfirmIfFormIsDirty();
/** Change the target, but first confirm if the form is unsaved */
const updateTarget: UpdateTarget = useCallback(
@@ -305,10 +297,6 @@ const _StrategyEditorForQuestionsAndDashboards = ({
);
};
-export const StrategyEditorForQuestionsAndDashboards = withRouter(
- _StrategyEditorForQuestionsAndDashboards,
-);
-
const TableSkeleton = ({ columns }: { columns: ColumnItem[] }) => (
<ClientSortableTable<{ id: number }>
columns={columns}
diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx
index b76adaa6e57..1335953629b 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx
+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx
@@ -1,6 +1,4 @@
import { useEffect, useMemo, useState } from "react";
-import type { InjectedRouter, Route } from "react-router";
-import { withRouter } from "react-router";
import { t } from "ttag";
import { findWhere } from "underscore";
@@ -22,13 +20,7 @@ import type { UpdateTargetId } from "../types";
import { Panel, RoundedBox } from "./StrategyEditorForDatabases.styled";
import { StrategyForm } from "./StrategyForm";
-const StrategyEditorForDatabases_Base = ({
- router,
- route,
-}: {
- router: InjectedRouter;
- route?: Route;
-}) => {
+export const StrategyEditorForDatabases: React.FC = () => {
const { canOverrideRootStrategy } = PLUGIN_CACHING;
const [
@@ -75,7 +67,7 @@ const StrategyEditorForDatabases_Base = ({
confirmationModal,
isStrategyFormDirty,
setIsStrategyFormDirty,
- } = useConfirmIfFormIsDirty(router, route);
+ } = useConfirmIfFormIsDirty();
/** Update the targetId (the id of the currently edited model) but confirm if the form is unsaved */
const updateTargetId: UpdateTargetId = (newTargetId, isFormDirty) => {
@@ -169,7 +161,3 @@ const StrategyEditorForDatabases_Base = ({
</SettingsPageWrapper>
);
};
-
-export const StrategyEditorForDatabases = withRouter(
- StrategyEditorForDatabases_Base,
-);
diff --git a/frontend/src/metabase/admin/performance/components/test-utils.tsx b/frontend/src/metabase/admin/performance/components/test-utils.tsx
index 80376b94429..5f47ac80c01 100644
--- a/frontend/src/metabase/admin/performance/components/test-utils.tsx
+++ b/frontend/src/metabase/admin/performance/components/test-utils.tsx
@@ -1,3 +1,5 @@
+import { Route } from "react-router";
+
import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupDatabasesEndpoints,
@@ -67,9 +69,15 @@ export const setupStrategyEditorForDatabases = ({
);
setupDatabasesEndpoints(databases);
- return renderWithProviders(<StrategyEditorForDatabases />, {
- storeInitialState,
- });
+ const TestStrategyEditorForDatabases = () => <StrategyEditorForDatabases />;
+
+ return renderWithProviders(
+ <Route path="*" component={TestStrategyEditorForDatabases} />,
+ {
+ storeInitialState,
+ withRouter: true,
+ },
+ );
};
export const getSaveButton = async () =>
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx
index 8e94820b452..f7fb89eecdf 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx
@@ -1,5 +1,4 @@
import { useCallback, useState } from "react";
-import type { InjectedRouter, Route } from "react-router";
import { t } from "ttag";
import useBeforeUnload from "metabase/common/hooks/use-before-unload";
@@ -7,11 +6,7 @@ import { useConfirmation } from "metabase/common/hooks/use-confirmation";
import { useConfirmOnRouteLeave } from "./useConfirmOnRouteLeave";
-export const useConfirmIfFormIsDirty = (
- /** If not specified, no confirmation will occur on route leave */
- router?: InjectedRouter,
- route?: Route,
-) => {
+export const useConfirmIfFormIsDirty = () => {
const [isStrategyFormDirty, setIsStrategyFormDirty] = useState(false);
const { show: askConfirmation, modalContent: confirmationModal } =
@@ -29,8 +24,6 @@ export const useConfirmIfFormIsDirty = (
);
useConfirmOnRouteLeave({
- router,
- route,
shouldConfirm: isStrategyFormDirty,
confirm: askBeforeDiscardingChanges,
});
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
index 4c658462fc3..1c68cc5b921 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
@@ -1,45 +1,45 @@
-import type { Location } from "history";
-import { useEffect, useState } from "react";
-import type { InjectedRouter, Route } from "react-router";
+import { useEffect, useRef } from "react";
import { push } from "react-router-redux";
import { useDispatch } from "metabase/lib/redux";
+import { useRouter } from "metabase/router";
-export const useConfirmOnRouteLeave = ({
- router,
- route,
- shouldConfirm,
- confirm,
-}: {
- router?: InjectedRouter;
- route?: Route;
+type Props = {
shouldConfirm: boolean;
confirm: (onConfirm: () => void) => void;
-}) => {
- const [isConfirmed, setIsConfirmed] = useState(false);
- const [nextLocation, setNextLocation] = useState<Location>();
+};
+
+export const useConfirmOnRouteLeave = ({ shouldConfirm, confirm }: Props) => {
+ const dispatch = useDispatch();
+ const { router, routes } = useRouter();
+ /**
+ * to prevent endless loop
+ */
+ const confirmedRef = useRef<boolean>(false);
+ const currentRoute = routes.at(-1);
- useEffect(() => {
- if (!route || !router) {
- return;
- }
- const removeLeaveHook = router.setRouteLeaveHook(route, (location) => {
- if (shouldConfirm && !isConfirmed) {
+ useEffect(
+ () =>
+ router.setRouteLeaveHook(currentRoute, (nextLocation) => {
+ if (confirmedRef.current || !shouldConfirm) {
+ return true;
+ }
+ /**
+ * This will roll browser's URL back.
+ * Returning false from this function cancels routing on the redux level, but browser's URL changes anyway.
+ * So we need to roll this change back and then roll forward if user confirms.
+ *
+ * Unfortunately it won't work if user somewhere in the middle of history (e.g. has forward button available)
+ */
+ router.goForward();
confirm(() => {
- setIsConfirmed(true);
- setNextLocation(location);
+ confirmedRef.current = true;
+ if (nextLocation) {
+ dispatch(push(nextLocation));
+ }
});
return false;
- }
- });
- return removeLeaveHook;
- }, [router, route, isConfirmed, shouldConfirm, confirm]);
-
- const dispatch = useDispatch();
-
- useEffect(() => {
- if (nextLocation) {
- dispatch(push(nextLocation));
- }
- }, [dispatch, nextLocation]);
+ }),
+ [router, currentRoute, shouldConfirm, confirm, dispatch],
+ );
};
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
new file mode 100644
index 00000000000..07beca82f02
--- /dev/null
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
@@ -0,0 +1,81 @@
+import type { History } from "history";
+import { Route } from "react-router";
+
+import { act, renderWithProviders, screen } from "__support__/ui";
+import { checkNotNull } from "metabase/lib/types";
+
+import { useConfirmOnRouteLeave } from "./useConfirmOnRouteLeave";
+
+const confirmResult = jest.fn();
+
+const PageB = () => {
+ useConfirmOnRouteLeave({
+ shouldConfirm: true,
+ confirm: (onConfirm: () => void) => {
+ if (confirmResult()) {
+ onConfirm();
+ }
+ },
+ });
+
+ return <div>Page B</div>;
+};
+
+describe("useConfirmOnRouteLeave", () => {
+ const setup = () => {
+ const PageA = () => <div>Page A</div>;
+
+ const { history, ...rest } = renderWithProviders(
+ <div>
+ <Route path="/a" component={PageA} />
+ <Route path="/b" component={PageB} />
+ </div>,
+ { withRouter: true, initialRoute: "/a" },
+ );
+ const guardedHistory = checkNotNull(history);
+ return {
+ ...rest,
+ history: guardedHistory,
+ };
+ };
+
+ // Shared happy path for remaining on the /b route after an attempted exit
+ const navigateToBAndTriggerBack = (history: History) => {
+ // Navigate to /b to create a history entry to go back from
+ act(() => history.push("/b"));
+
+ // Ensure we're on /b
+ expect(screen.getByText("Page B")).toBeInTheDocument();
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+
+ // Simulate browser back, which should trigger confirmation and roll URL forward
+ act(() => history.goBack());
+ };
+
+ it("shows confirmation on browser back and stays on the same route when clicking 'No' (URL unchanged)", () => {
+ const { history } = setup();
+ // Do not confirm
+ confirmResult.mockReturnValue(false);
+
+ // try to leave a page
+ navigateToBAndTriggerBack(history);
+
+ // We must still be on the same route and URL
+ expect(screen.getByText("Page B")).toBeInTheDocument();
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+
+ it("navigates to the previous route when clicking 'Yes' in the confirmation", () => {
+ const { history } = setup();
+
+ // Do confirm
+ confirmResult.mockReturnValue(true);
+
+ // try to leave a page
+ navigateToBAndTriggerBack(history);
+
+ // We should navigate to /a
+ expect(screen.getByText("Page A")).toBeInTheDocument();
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ });
+});
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index d913ee7cb9d..3b61fbbe0de 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -24,14 +24,13 @@ import "metabase/plugins/builtin";
// This is conditionally aliased in the webpack config.
// If EE isn't enabled, it loads an empty file.
-
// Set nonce for mantine v6 deps
import "metabase/lib/csp";
import { createHistory } from "history";
import { DragDropContextProvider } from "react-dnd";
import { createRoot } from "react-dom/client";
-import { Router, useRouterHistory } from "react-router";
+import { useRouterHistory } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
import { initializePlugins } from "ee-plugins";
@@ -50,6 +49,8 @@ import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles
import { ThemeProvider } from "metabase/ui";
import registerVisualizations from "metabase/visualizations/register";
+import { HistoryProvider } from "./history";
+import { RouterProvider } from "./router";
import { getStore } from "./store";
// remove trailing slash
@@ -63,10 +64,11 @@ const browserHistory = useRouterHistory(createHistory)({
});
initializePlugins();
+
function _init(reducers, getRoutes, callback) {
const store = getStore(reducers, browserHistory);
const routes = getRoutes(store);
- const history = syncHistoryWithStore(browserHistory, store);
+ const syncedHistory = syncHistoryWithStore(browserHistory, store);
const MetabotProvider = PLUGIN_METABOT.getMetabotProvider();
createTracker(store);
@@ -82,7 +84,9 @@ function _init(reducers, getRoutes, callback) {
<ThemeProvider initialColorScheme={getUserColorScheme()}>
<GlobalStyles />
<MetabotProvider>
- <Router history={history}>{routes}</Router>
+ <HistoryProvider history={syncedHistory}>
+ <RouterProvider>{routes}</RouterProvider>
+ </HistoryProvider>
</MetabotProvider>
</ThemeProvider>
</DragDropContextProvider>
diff --git a/frontend/src/metabase/common/components/Sidesheet/Sidesheet.tsx b/frontend/src/metabase/common/components/Sidesheet/Sidesheet.tsx
index a22223ee748..0a2094f31d3 100644
--- a/frontend/src/metabase/common/components/Sidesheet/Sidesheet.tsx
+++ b/frontend/src/metabase/common/components/Sidesheet/Sidesheet.tsx
@@ -5,7 +5,7 @@ import { t } from "ttag";
import { uniqueId } from "underscore";
import Animation from "metabase/css/core/animation.module.css";
-import { Modal, Stack } from "metabase/ui";
+import { Modal, type ModalOverlayProps, Stack } from "metabase/ui";
import Styles from "./sidesheet.module.css";
@@ -20,6 +20,8 @@ interface SidesheetProps {
/** use this if you want to enable interior scrolling of tab panels */
removeBodyPadding?: boolean;
withOverlay?: boolean;
+ overlayProps?: ModalOverlayProps;
+ closeOnEscape?: boolean;
}
const sizes: Record<SidesheetSize, string> = {
@@ -39,6 +41,8 @@ export function Sidesheet({
children,
removeBodyPadding,
withOverlay = true,
+ overlayProps,
+ closeOnEscape = true,
}: SidesheetProps) {
const titleId = useMemo(() => uniqueId("sidesheet-title"), []);
return (
@@ -46,9 +50,12 @@ export function Sidesheet({
variant="sidesheet"
opened={isOpen}
onClose={onClose}
+ closeOnEscape={closeOnEscape}
h="100dvh"
>
- {withOverlay && <Modal.Overlay data-testid="modal-overlay" />}
+ {withOverlay && (
+ <Modal.Overlay {...overlayProps} data-testid="modal-overlay" />
+ )}
<Modal.Content
transitionProps={{ duration: 0 }}
px="none"
diff --git a/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx b/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx
index 7b076f80027..36d04074835 100644
--- a/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx
+++ b/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx
@@ -1,6 +1,6 @@
import type React from "react";
-import { Button, Flex, Icon, Title } from "metabase/ui";
+import { Button, Flex, Icon, type ModalOverlayProps, Title } from "metabase/ui";
import { Sidesheet, type SidesheetSize } from "./Sidesheet";
@@ -18,6 +18,7 @@ interface SidesheetSubPageProps {
size?: SidesheetSize;
/** Whether to show a translucent backdrop */
withOverlay?: boolean;
+ overlayProps?: ModalOverlayProps;
}
export const SidesheetSubPageTitle = ({
@@ -42,6 +43,7 @@ export const SidesheetSubPage = ({
isOpen,
size,
withOverlay = false,
+ overlayProps,
}: SidesheetSubPageProps) => (
<Sidesheet
isOpen={isOpen}
@@ -49,6 +51,7 @@ export const SidesheetSubPage = ({
onClose={onClose}
size={size}
withOverlay={withOverlay}
+ overlayProps={overlayProps}
>
{children}
</Sidesheet>
diff --git a/frontend/src/metabase/common/hooks/use-confirmation.tsx b/frontend/src/metabase/common/hooks/use-confirmation.tsx
index 2c7022853e4..04709a528e3 100644
--- a/frontend/src/metabase/common/hooks/use-confirmation.tsx
+++ b/frontend/src/metabase/common/hooks/use-confirmation.tsx
@@ -1,4 +1,4 @@
-import { type ReactNode, useState } from "react";
+import { type ReactNode, useCallback, useState } from "react";
import { t } from "ttag";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
@@ -43,26 +43,29 @@ export const useConfirmation = () => {
/>
) : null;
- const show = ({
- title,
- message,
- onConfirm,
- onCancel,
- confirmButtonText = t`Confirm`,
- cancelButtonText = t`Cancel`,
- confirmButtonProps,
- size,
- }: ConfirmationState) =>
- setConfirmationState({
+ const show = useCallback(
+ ({
title,
message,
onConfirm,
onCancel,
- confirmButtonText,
- cancelButtonText,
+ confirmButtonText = t`Confirm`,
+ cancelButtonText = t`Cancel`,
confirmButtonProps,
size,
- });
+ }: ConfirmationState) =>
+ setConfirmationState({
+ title,
+ message,
+ onConfirm,
+ onCancel,
+ confirmButtonText,
+ cancelButtonText,
+ confirmButtonProps,
+ size,
+ }),
+ [],
+ );
return { modalContent, show };
};
diff --git a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx
index 20a7e01f3ae..55008e3b3a2 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx
@@ -1,5 +1,4 @@
-import type { Dispatch, SetStateAction } from "react";
-import { useCallback, useState } from "react";
+import { useCallback } from "react";
import { useMount } from "react-use";
import { t } from "ttag";
@@ -11,32 +10,36 @@ import { useDashboardContext } from "metabase/dashboard/context";
import { isDashboardCacheable } from "metabase/dashboard/utils";
import { useDispatch } from "metabase/lib/redux";
import { PLUGIN_CACHING } from "metabase/plugins";
-import { Switch } from "metabase/ui";
+import { Switch, useModalsStack } from "metabase/ui";
import type { CacheableDashboard, Dashboard } from "metabase-types/api";
export function DashboardSettingsSidebar() {
const { dashboard, closeSidebar } = useDashboardContext();
- const [page, setPage] = useState<"default" | "caching">("default");
- const [isOpen, setIsOpen] = useState(false);
+ const { open, state, close } = useModalsStack(["default", "caching"]);
+
+ const currentModal: keyof typeof state = state.caching
+ ? "caching"
+ : "default";
useMount(() => {
- // this component is not rendered until it is "open"
- // but we want to set isOpen after it mounts to get
+ // the modal is not rendered until it is "open"
+ // but we want to set it open after it mounts to get
// pretty animations
- setIsOpen(true);
+ open("default");
});
if (!dashboard) {
return null;
}
- if (page === "caching") {
+ if (currentModal === "caching") {
return (
<PLUGIN_CACHING.SidebarCacheForm
item={dashboard as CacheableDashboard}
model="dashboard"
- onBack={() => setPage("default")}
+ isOpen={state.caching}
onClose={closeSidebar}
+ onBack={() => close("caching")}
pt="md"
/>
);
@@ -45,18 +48,13 @@ export function DashboardSettingsSidebar() {
return (
<ErrorBoundary>
<Sidesheet
- isOpen={isOpen}
- title={t`Dashboard settings`}
+ isOpen={state.default}
onClose={closeSidebar}
+ closeOnEscape={currentModal === "default"}
+ title={t`Dashboard settings`}
data-testid="dashboard-settings-sidebar"
>
- <DashboardSidesheetBody
- dashboard={dashboard}
- page={page}
- setPage={setPage}
- isOpen={isOpen}
- onClose={closeSidebar}
- />
+ <DashboardSidesheetBody dashboard={dashboard} openSidesheet={open} />
</Sidesheet>
</ErrorBoundary>
);
@@ -64,15 +62,12 @@ export function DashboardSettingsSidebar() {
export type DashboardSidebarPageProps = {
dashboard: Dashboard;
- page: "default" | "caching";
- setPage: Dispatch<SetStateAction<"default" | "caching">>;
- isOpen: boolean;
- onClose: () => void;
+ openSidesheet: (sidesheetKey: "caching") => void;
};
const DashboardSidesheetBody = ({
dashboard,
- setPage,
+ openSidesheet,
}: DashboardSidebarPageProps) => {
const dispatch = useDispatch();
@@ -112,7 +107,7 @@ const DashboardSidesheetBody = ({
<PLUGIN_CACHING.SidebarCacheSection
model="dashboard"
item={dashboard}
- setPage={setPage}
+ setPage={() => openSidesheet("caching")}
/>
</SidesheetCard>
)}
diff --git a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/setup.tsx b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/setup.tsx
index b4ca584fbcd..92c56b1f44e 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/setup.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/setup.tsx
@@ -1,3 +1,5 @@
+import { Route } from "react-router";
+
import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupDashboardEndpoints,
@@ -59,11 +61,16 @@ export async function setup({
setupEnterprisePlugins();
}
- renderWithProviders(
+ const TestDashboardSettingsSidebar = () => (
<MockDashboardContext dashboard={dashboard} closeSidebar={onClose}>
<DashboardSettingsSidebar />
- </MockDashboardContext>,
- { storeInitialState: state },
+ </MockDashboardContext>
+ );
+
+ renderWithProviders(
+ <Route path="*" component={TestDashboardSettingsSidebar} />,
+
+ { storeInitialState: state, withRouter: true },
);
await waitForLoaderToBeRemoved();
diff --git a/frontend/src/metabase/history/HistoryProvider.tsx b/frontend/src/metabase/history/HistoryProvider.tsx
new file mode 100644
index 00000000000..b9c6e28008b
--- /dev/null
+++ b/frontend/src/metabase/history/HistoryProvider.tsx
@@ -0,0 +1,23 @@
+import type { History } from "history";
+import { type PropsWithChildren, createContext } from "react";
+
+type HistoryContextType = {
+ history: History;
+};
+
+export const HistoryContext = createContext<HistoryContextType | null>(null);
+
+type Props = {
+ history: History;
+};
+
+export const HistoryProvider = ({
+ history,
+ children,
+}: PropsWithChildren<Props>) => {
+ return (
+ <HistoryContext.Provider value={{ history }}>
+ {children}
+ </HistoryContext.Provider>
+ );
+};
diff --git a/frontend/src/metabase/history/index.ts b/frontend/src/metabase/history/index.ts
new file mode 100644
index 00000000000..ea91d1e7664
--- /dev/null
+++ b/frontend/src/metabase/history/index.ts
@@ -0,0 +1,2 @@
+export * from "./HistoryProvider";
+export * from "./useHistory";
diff --git a/frontend/src/metabase/history/useHistory.ts b/frontend/src/metabase/history/useHistory.ts
new file mode 100644
index 00000000000..9b271ea76dc
--- /dev/null
+++ b/frontend/src/metabase/history/useHistory.ts
@@ -0,0 +1,11 @@
+import { useContext } from "react";
+
+import { HistoryContext } from "./HistoryProvider";
+
+export const useHistory = () => {
+ const history = useContext(HistoryContext);
+ if (!history) {
+ throw new Error("useHistory must be used inside <HistoryProvider>");
+ }
+ return history;
+};
diff --git a/frontend/src/metabase/plugins/oss/caching.ts b/frontend/src/metabase/plugins/oss/caching.ts
index 33aabb6b6e8..148dd7a7efa 100644
--- a/frontend/src/metabase/plugins/oss/caching.ts
+++ b/frontend/src/metabase/plugins/oss/caching.ts
@@ -6,7 +6,7 @@ import {
} from "metabase/admin/performance/constants/complex";
import type { ModelWithClearableCache } from "metabase/admin/performance/types";
import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";
-import type { StackProps } from "metabase/ui";
+import type { ModalOverlayProps, StackProps } from "metabase/ui";
import type Question from "metabase-lib/v1/Question";
import type { CacheableDashboard, CacheableModel } from "metabase-types/api";
@@ -26,7 +26,11 @@ export type SidebarCacheSectionProps = {
export type SidebarCacheFormProps = {
item: CacheableDashboard | Question;
model: CacheableModel;
+ isOpen: boolean;
+ withOverlay?: boolean;
+ overlayProps?: ModalOverlayProps;
onClose: () => void;
+ onBack: () => void;
} & StackProps;
export type PreemptiveCachingSwitchProps = {
@@ -39,9 +43,7 @@ const getDefaultPluginCaching = () => ({
GranularControlsExplanation: PluginPlaceholder as any,
SidebarCacheSection:
PluginPlaceholder as ComponentType<SidebarCacheSectionProps>,
- SidebarCacheForm: PluginPlaceholder as ComponentType<
- SidebarCacheFormProps & { onBack: () => void }
- >,
+ SidebarCacheForm: PluginPlaceholder as ComponentType<SidebarCacheFormProps>,
InvalidateNowButton:
PluginPlaceholder as ComponentType<InvalidateNowButtonProps>,
hasQuestionCacheSection: (_question: Question) => false,
diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx
index 661f1e98ac8..0085b0f054f 100644
--- a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx
+++ b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx
@@ -1,4 +1,3 @@
-import { useMemo, useState } from "react";
import { useMount } from "react-use";
import { match } from "ts-pattern";
import { t } from "ttag";
@@ -8,7 +7,7 @@ import { Sidesheet, SidesheetCard } from "metabase/common/components/Sidesheet";
import { useDispatch } from "metabase/lib/redux";
import { PLUGIN_CACHING, PLUGIN_MODEL_PERSISTENCE } from "metabase/plugins";
import { onCloseQuestionSettings } from "metabase/query_builder/actions";
-import { Stack } from "metabase/ui";
+import { Stack, useModalsStack } from "metabase/ui";
import type Question from "metabase-lib/v1/Question";
import { ModelCacheManagementSection } from "../ModelCacheManagementSection";
@@ -32,24 +31,26 @@ export const QuestionSettingsSidebar = ({
const dispatch = useDispatch();
const handleClose = () => dispatch(onCloseQuestionSettings());
- const [page, setPage] = useState<"default" | "caching">("default");
- const [isOpen, setIsOpen] = useState(false);
+ const { open, state, close } = useModalsStack(["default", "caching"]);
+
+ const currentModal: keyof typeof state = state.caching
+ ? "caching"
+ : "default";
useMount(() => {
- // this component is not rendered until it is "open"
- // but we want to set isOpen after it mounts to get
+ // the modal is not rendered until it is "open"
+ // but we want to set it open after it mounts to get
// pretty animations
- setIsOpen(true);
+ open("default");
});
- const title = useMemo(() => getTitle(question), [question]);
-
return (
<>
<Sidesheet
- title={title}
+ title={getTitle(question)}
+ isOpen={state.default}
onClose={handleClose}
- isOpen={isOpen}
+ closeOnEscape={currentModal === "default"}
data-testid="question-settings-sidebar"
>
{question.type() === "model" && (
@@ -64,19 +65,21 @@ export const QuestionSettingsSidebar = ({
<PLUGIN_CACHING.SidebarCacheSection
model="question"
item={question}
- setPage={setPage}
- key={page}
+ setPage={() => open("caching")}
+ key={currentModal}
/>
</Stack>
</SidesheetCard>
)}
</Sidesheet>
- {page === "caching" && (
+ {currentModal === "caching" && (
<PLUGIN_CACHING.SidebarCacheForm
item={question}
model="question"
- onBack={() => setPage("default")}
+ isOpen={state.caching}
onClose={handleClose}
+ overlayProps={{ bg: "transparent" }}
+ onBack={() => close("caching")}
pt="md"
/>
)}
diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsx
new file mode 100644
index 00000000000..c7af0721345
--- /dev/null
+++ b/frontend/src/metabase/router/RouterProvider.tsx
@@ -0,0 +1,46 @@
+import type { History } from "history";
+import { type PropsWithChildren, createContext } from "react";
+import { Route, Router, type WithRouterProps, withRouter } from "react-router";
+
+import { useHistory } from "metabase/history";
+
+type RouterContextType = WithRouterProps;
+
+export const RouterContext = createContext<RouterContextType | null>(null);
+
+const RouterContextProviderBase = ({
+ router,
+ location,
+ params,
+ routes,
+ children,
+}: PropsWithChildren<RouterContextType>) => {
+ return (
+ <RouterContext.Provider value={{ router, location, params, routes }}>
+ {children}
+ </RouterContext.Provider>
+ );
+};
+
+const RouterContextProvider = withRouter(RouterContextProviderBase);
+
+type RouterProviderProps = {
+ history?: History | undefined;
+};
+
+/**
+ * This provider encapsulates react-router initiation and puts router and routes references to the context
+ * This is v3's only solution to provide a router and routes.
+ * Without extra Route component it doesn't work.
+ * Additionally, it provides the history reference
+ */
+export const RouterProvider = ({
+ children,
+}: PropsWithChildren<RouterProviderProps>) => {
+ const { history } = useHistory();
+ return (
+ <Router history={history}>
+ <Route component={RouterContextProvider}>{children}</Route>
+ </Router>
+ );
+};
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
new file mode 100644
index 00000000000..d13f0355f5c
--- /dev/null
+++ b/frontend/src/metabase/router/index.ts
@@ -0,0 +1,2 @@
+export * from "./useRouter";
+export * from "./RouterProvider";
diff --git a/frontend/src/metabase/router/useRouter.tsx b/frontend/src/metabase/router/useRouter.tsx
new file mode 100644
index 00000000000..6e9d78e359d
--- /dev/null
+++ b/frontend/src/metabase/router/useRouter.tsx
@@ -0,0 +1,11 @@
+import { useContext } from "react";
+
+import { RouterContext } from "./RouterProvider";
+
+export const useRouter = () => {
+ const ctx = useContext(RouterContext);
+ if (!ctx) {
+ throw new Error("useRouter must be used inside <RouterProvider>");
+ }
+ return ctx;
+};
diff --git a/frontend/src/metabase/ui/components/overlays/Modal/index.tsx b/frontend/src/metabase/ui/components/overlays/Modal/index.tsx
index c2909e817f4..fb29aab7f36 100644
--- a/frontend/src/metabase/ui/components/overlays/Modal/index.tsx
+++ b/frontend/src/metabase/ui/components/overlays/Modal/index.tsx
@@ -8,6 +8,7 @@ import { useDisableCommandPalette } from "metabase/palette/hooks/useDisableComma
import { PreventEagerPortal } from "metabase/ui";
export type { ModalProps } from "@mantine/core";
+export { useModalsStack } from "@mantine/core";
export * from "./Modal.config";
diff --git a/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx b/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx
index 8881cdba7ed..20a1ee8a95d 100644
--- a/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx
+++ b/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx
@@ -6,7 +6,7 @@ import {
import { PreventEagerPortal } from "metabase/ui";
-export { type OverlayProps } from "@mantine/core";
+export type { OverlayProps, ModalOverlayProps } from "@mantine/core";
export { LoadingOverlay } from "@mantine/core";
export { overlayOverrides } from "./Overlay.config";
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 27f6e17e517..eb7f2049a4e 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -14,16 +14,18 @@ import { KBarProvider } from "kbar";
import type * as React from "react";
import { DragDropContextProvider } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
-import { Route, Router, useRouterHistory } from "react-router";
+import { Route, useRouterHistory } from "react-router";
import { routerMiddleware, routerReducer } from "react-router-redux";
import _ from "underscore";
import { Api } from "metabase/api";
import { UndoListing } from "metabase/common/components/UndoListing";
import { baseStyle } from "metabase/css/core/base.styled";
+import { HistoryProvider } from "metabase/history";
import { MetabaseReduxProvider } from "metabase/lib/redux";
import { makeMainReducers } from "metabase/reducers-main";
import { publicReducers } from "metabase/reducers-public";
+import { RouterProvider } from "metabase/router";
import type { MantineThemeOverride } from "metabase/ui";
import { ThemeProvider } from "metabase/ui";
import { ThemeProviderContext } from "metabase/ui/components/theme/ThemeProvider/context";
@@ -274,11 +276,14 @@ function MaybeRouter({
hasRouter: boolean;
history?: History;
}): JSX.Element {
- if (!hasRouter) {
+ if (!hasRouter || !history) {
return children;
}
-
- return <Router history={history}>{children}</Router>;
+ return (
+ <HistoryProvider history={history}>
+ <RouterProvider>{children}</RouterProvider>
+ </HistoryProvider>
+ );
}
function MaybeKBar({