Skip to content

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

Convert modal routes to a modalRoute factory and delete getParentPath (#77372)

Romeo Van Snick972c96b58d12
diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx
index a3dc214b4b4..243ebbb80cc 100644
--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx
@@ -1,4 +1,3 @@
-import type { Location } from "history";
import { useCallback } from "react";
import { useMount } from "react-use";
@@ -6,9 +5,7 @@ import { updateDataPermission } from "metabase/admin/permissions/permissions";
import { DataPermissionType } from "metabase/admin/permissions/types";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useDatabaseQuery } from "metabase/common/hooks";
-import { getParentPath } from "metabase/hoc/ModalRoute";
import { useDispatch } from "metabase/redux";
-import { push, withRouter } from "metabase/router";
import { updateImpersonation } from "metabase-enterprise/advanced_permissions/reducer";
import { getImpersonation } from "metabase-enterprise/advanced_permissions/selectors";
import type {
@@ -30,10 +27,7 @@ import { ImpersonationModalView } from "./ImpersonationModalView";
interface ImpersonationModalProps {
params: ImpersonationModalParams;
- location: Location;
- route: {
- path: string;
- };
+ onClose: () => void;
}
const parseParams = (params: ImpersonationModalParams): ImpersonationParams => {
@@ -46,10 +40,9 @@ const parseParams = (params: ImpersonationModalParams): ImpersonationParams => {
};
};
-const ImpersonationModalInner = ({
- route,
+export const ImpersonationModal = ({
params,
- location,
+ onClose,
}: ImpersonationModalProps) => {
const { groupId, databaseId } = parseParams(params);
@@ -80,10 +73,6 @@ const ImpersonationModalInner = ({
const dispatch = useDispatch();
- const close = useCallback(() => {
- dispatch(push(getParentPath(route, location)));
- }, [dispatch, route, location]);
-
const handleSave = useCallback(
(attribute: UserAttributeKey) => {
dispatch(
@@ -109,15 +98,11 @@ const ImpersonationModalInner = ({
);
}
- close();
+ onClose();
},
- [close, databaseId, dispatch, groupId, selectedAttribute],
+ [onClose, databaseId, dispatch, groupId, selectedAttribute],
);
- const handleCancel = useCallback(() => {
- dispatch(push(getParentPath(route, location)));
- }, [dispatch, route, location]);
-
useMount(() => {
dispatch(fetchUserAttributes());
});
@@ -140,9 +125,7 @@ const ImpersonationModalInner = ({
attributes={attributes}
database={database}
onSave={handleSave}
- onCancel={handleCancel}
+ onCancel={onClose}
/>
);
};
-
-export const ImpersonationModal = withRouter(ImpersonationModalInner);
diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx
index 4b50c2b8389..0783c320404 100644
--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx
@@ -14,6 +14,7 @@ import {
waitFor,
waitForLoaderToBeRemoved,
} from "__support__/ui";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { Route } from "metabase/router";
import { ImpersonationModal } from "metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal";
import { advancedPermissionsSlice } from "metabase-enterprise/advanced_permissions/reducer";
@@ -64,10 +65,13 @@ const setup = async ({
const { store } = renderWithProviders(
<>
<Route path="/" />
- <Route
- path="database/:databaseId/impersonated/group/:groupId"
- component={ImpersonationModal}
- />
+ <Route path="database/:databaseId">
+ {modalRoute(
+ "impersonated/group/:groupId",
+ // @ts-expect-error - params prop can't be inferred
+ ImpersonationModal,
+ )}
+ </Route>
</>,
{
initialRoute: `database/${databaseId}/impersonated/group/${groupId}`,
diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js
index 70c4600e277..c5514078e67 100644
--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js
@@ -4,7 +4,7 @@ import {
getDatabaseFocusPermissionsUrl,
getGroupFocusPermissionsUrl,
} from "metabase/admin/permissions/utils/urls";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import {
PLUGIN_ADMIN_PERMISSIONS_DATABASE_ACTIONS,
PLUGIN_ADMIN_PERMISSIONS_DATABASE_GROUP_ROUTES,
@@ -76,19 +76,14 @@ export function initializePlugin() {
];
PLUGIN_ADMIN_PERMISSIONS_DATABASE_ROUTES.push(
- <ModalRoute
- key="impersonated/group/:groupId"
- path="impersonated/group/:groupId"
- modal={ImpersonationModal}
- />,
+ modalRoute("impersonated/group/:groupId", ImpersonationModal),
);
PLUGIN_ADMIN_PERMISSIONS_DATABASE_GROUP_ROUTES.push(
- <ModalRoute
- key="impersonated/database/:impersonatedDatabaseId"
- path="impersonated/database/:impersonatedDatabaseId"
- modal={ImpersonationModal}
- />,
+ modalRoute(
+ "impersonated/database/:impersonatedDatabaseId",
+ ImpersonationModal,
+ ),
);
PLUGIN_ADVANCED_PERMISSIONS.isBlockPermission = (value) =>
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/routes.jsx b/enterprise/frontend/src/metabase-enterprise/audit_app/routes.jsx
index 24f8569f037..af2e8242472 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/routes.jsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/routes.jsx
@@ -1,7 +1,6 @@
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { UnsubscribeUserModal } from "./containers/UnsubscribeUserModal/UnsubscribeUserModal";
-export const getUserMenuRotes = () => (
- <ModalRoute path="unsubscribe" modal={UnsubscribeUserModal} noWrap />
-);
+export const getUserMenuRotes = () =>
+ modalRoute("unsubscribe", UnsubscribeUserModal, { noWrap: true });
diff --git a/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx b/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx
index 9f43ff34e53..ff6ec2d75a5 100644
--- a/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx
@@ -2,8 +2,8 @@ import { t } from "ttag";
import { skipToken, useListCollectionItemsQuery } from "metabase/api";
import { ForwardRefLink } from "metabase/common/components/Link";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { UserHasSeen } from "metabase/common/components/UserHasSeen/UserHasSeen";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
import { PLUGIN_COLLECTIONS } from "metabase/plugins";
import { Badge, Icon, Menu } from "metabase/ui";
import * as Urls from "metabase/urls";
@@ -79,8 +79,9 @@ export function initializePlugin() {
};
};
- PLUGIN_COLLECTIONS.cleanUpRoute = (
- <ModalRoute path="cleanup" modal={CleanupCollectionModal} />
+ PLUGIN_COLLECTIONS.cleanUpRoute = modalRoute(
+ "cleanup",
+ CleanupCollectionModal,
);
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx
index 960cf1e3535..1ad45322d6e 100644
--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx
@@ -1,4 +1,3 @@
-import type { Location } from "history";
import { t } from "ttag";
import {
@@ -7,9 +6,7 @@ import {
useListUserAttributesQuery,
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import { getParentPath } from "metabase/hoc/ModalRoute";
import { useDispatch, useSelector } from "metabase/redux";
-import { push } from "metabase/router";
import { parseIntParam } from "metabase/urls";
import { getGroupTableAccessPolicy } from "metabase-enterprise/sandboxes/selectors";
import type { GroupTableAccessPolicy } from "metabase-types/api";
@@ -20,14 +17,12 @@ import type { GroupTableAccessPolicyParams, SandboxesState } from "../types";
interface EditSandboxingModalContainerProps {
params: GroupTableAccessPolicyParams;
- location: Location;
- route: { path: string };
+ onClose: () => void;
}
const EditSandboxingModalContainer = ({
params,
- location,
- route,
+ onClose,
}: EditSandboxingModalContainerProps) => {
const dispatch = useDispatch();
@@ -77,14 +72,10 @@ const EditSandboxingModalContainer = ({
return <LoadingAndErrorWrapper loading />;
}
- const close = () => {
- return dispatch(push(getParentPath(route, location)));
- };
-
const handleSave = async (policy: GroupTableAccessPolicy) => {
dispatch(updatePolicy(policy));
dispatch(updateTableSandboxingPermission(params));
- close();
+ onClose();
};
return (
@@ -92,7 +83,7 @@ const EditSandboxingModalContainer = ({
policy={policy}
attributes={attributes || []}
params={params}
- onCancel={close}
+ onCancel={onClose}
onSave={handleSave}
/>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js b/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js
index 9cd99f25ede..92d0bfff372 100644
--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js
@@ -5,7 +5,7 @@ import {
getDatabaseFocusPermissionsUrl,
getGroupFocusPermissionsUrl,
} from "metabase/admin/permissions/utils/urls";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import {
PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_ACTIONS,
PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_CONFIRMATIONS,
@@ -64,18 +64,10 @@ export function initializePlugin() {
PLUGIN_ADMIN_USER_FORM_FIELDS.FormLoginAttributes = LoginAttributesWidget;
PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES.push(
- <ModalRoute
- key=":tableId/segmented"
- path=":tableId/segmented"
- modal={EditSandboxingModal}
- />,
+ modalRoute(":tableId/segmented", EditSandboxingModal),
);
PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES.push(
- <ModalRoute
- key="segmented/group/:groupId"
- path="segmented/group/:groupId"
- modal={EditSandboxingModal}
- />,
+ modalRoute("segmented/group/:groupId", EditSandboxingModal),
);
PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_OPTIONS.push(OPTION_SEGMENTED);
PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_ACTIONS[OPTION_SEGMENTED.value].push({
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
index 66114901216..275e424f919 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
@@ -15,9 +15,9 @@ import {
buildCollectionTree,
getCollectionIcon,
} from "metabase/common/collections/utils";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { useSetting } from "metabase/common/hooks/use-setting";
import { getGroupNameLocalized } from "metabase/common/utils/groups";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
import {
PLUGIN_ADMIN_PERMISSIONS_TABS,
PLUGIN_ADMIN_USER_MENU_ROUTES,
@@ -112,66 +112,70 @@ export function initializePlugin() {
PLUGIN_TENANTS.CreateTenantsOnboardingStep = CreateTenantsOnboardingStep;
PLUGIN_TENANTS.TenantsSummaryOnboardingStep = TenantsSummaryOnboardingStep;
- PLUGIN_TENANTS.userStrategyRoute = (
- <ModalRoute path="user-strategy" modal={EditUserStrategyModal} noWrap />
+ PLUGIN_TENANTS.userStrategyRoute = modalRoute(
+ "user-strategy",
+ EditUserStrategyModal,
+ { noWrap: true },
);
PLUGIN_TENANTS.tenantsRoutes = (
<>
<IndexRoute component={TenantsListingApp} />
<Route path="" component={TenantsListingApp}>
- <ModalRoute path="new" modal={NewTenantModal} noWrap />
- <ModalRoute
- path="user-strategy"
- modal={EditUserStrategyModal}
- noWrap
- />
+ {modalRoute("new", NewTenantModal, { noWrap: true })}
+ {modalRoute("user-strategy", EditUserStrategyModal, { noWrap: true })}
</Route>
<Route path="groups">
<IndexRoute component={ExternalGroupsListingApp} />
<Route path=":groupId" component={ExternalGroupDetailApp} />
</Route>
<Route path="people" component={ExternalPeopleListingApp}>
- <ModalRoute
- path="new"
- modal={(props) => <NewUserModal {...props} external />}
- noWrap
- />
+ {modalRoute(
+ "new",
+ (props) => (
+ <NewUserModal {...props} external />
+ ),
+ {
+ noWrap: true,
+ },
+ )}
<Route path=":userId">
<IndexRedirect to="/admin/people/tenants/people" />
- <ModalRoute
- path="edit"
- modal={(props) => <EditUserModal {...props} external />}
- noWrap
- />
- <ModalRoute path="deactivate" modal={UserActivationModal} noWrap />
- <ModalRoute path="reactivate" modal={UserActivationModal} noWrap />
- <ModalRoute path="success" modal={UserSuccessModal} noWrap />
- <ModalRoute path="reset" modal={UserPasswordResetModal} noWrap />
+ {modalRoute(
+ "edit",
+ (props) => (
+ <EditUserModal {...props} external />
+ ),
+ { noWrap: true },
+ )}
+ {modalRoute("deactivate", UserActivationModal, { noWrap: true })}
+ {modalRoute("reactivate", UserActivationModal, { noWrap: true })}
+ {modalRoute("success", UserSuccessModal, { noWrap: true })}
+ {modalRoute("reset", UserPasswordResetModal, { noWrap: true })}
{PLUGIN_ADMIN_USER_MENU_ROUTES.map((getRoutes, index) => (
<Fragment key={index}>{getRoutes()}</Fragment>
))}
</Route>
</Route>
<Route path=":tenantId" component={TenantsListingApp}>
- <ModalRoute
- path="edit"
+ {modalRoute(
+ "edit",
// @ts-expect-error - params prop can't be inferred
- modal={EditTenantModal}
- noWrap
- />
- <ModalRoute
- path="deactivate"
+ EditTenantModal,
+ { noWrap: true },
+ )}
+ {modalRoute(
+ "deactivate",
// @ts-expect-error - params prop can't be inferred
- modal={TenantActivationModal}
- noWrap
- />
- <ModalRoute
- path="reactivate"
+ TenantActivationModal,
+ { noWrap: true },
+ )}
+ {modalRoute(
+ "reactivate",
// @ts-expect-error - params prop can't be inferred
- modal={TenantActivationModal}
- noWrap
- />
+ TenantActivationModal,
+ { noWrap: true },
+ )}
</Route>
</>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/routes.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/routes.tsx
index 5de7eeb0f0d..35cf994951a 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/routes.tsx
@@ -1,4 +1,4 @@
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { Route } from "metabase/router";
import { NewPythonTransformPage } from "metabase/transforms/pages/NewTransformPage";
import { TransformListPage } from "metabase/transforms/pages/TransformListPage";
@@ -19,16 +19,12 @@ export function getPythonUpsellRoutes() {
return (
// Render upsell modal on python transforms routes if feature is not enabled
<Route path="" component={TransformListPage}>
- <ModalRoute
- path="library/:path"
- modal={PythonTransformsUpsellModal}
- noWrap
- />
- <ModalRoute
- path="new/python"
- modal={PythonTransformsUpsellModal}
- noWrap
- />
+ {modalRoute("library/:path", PythonTransformsUpsellModal, {
+ noWrap: true,
+ })}
+ {modalRoute("new/python", PythonTransformsUpsellModal, {
+ noWrap: true,
+ })}
</Route>
);
}
diff --git a/frontend/src/metabase/account/notifications/routes.tsx b/frontend/src/metabase/account/notifications/routes.tsx
index e0fd022b71c..f08ca60ae05 100644
--- a/frontend/src/metabase/account/notifications/routes.tsx
+++ b/frontend/src/metabase/account/notifications/routes.tsx
@@ -1,4 +1,4 @@
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { Route } from "metabase/router";
import { HelpModal } from "./components/HelpModal";
@@ -11,22 +11,13 @@ import { UnsubscribePulseModal } from "./containers/UnsubscribePulseModal";
export function getNotificationRoutes() {
return (
<Route path="notifications" component={NotificationsApp}>
- <ModalRoute path="help" modal={HelpModal} />
- <ModalRoute
- path="alert/:alertId/archive"
- modal={DeleteAlertModal}
- noWrap
- />
- <ModalRoute path="pulse/:pulseId/archive" modal={ArchivePulseModal} />
- <ModalRoute
- path="alert/:alertId/unsubscribe"
- modal={UnsubscribeAlertModal}
- noWrap
- />
- <ModalRoute
- path="pulse/:pulseId/unsubscribe"
- modal={UnsubscribePulseModal}
- />
+ {modalRoute("help", HelpModal)}
+ {modalRoute("alert/:alertId/archive", DeleteAlertModal, { noWrap: true })}
+ {modalRoute("pulse/:pulseId/archive", ArchivePulseModal)}
+ {modalRoute("alert/:alertId/unsubscribe", UnsubscribeAlertModal, {
+ noWrap: true,
+ })}
+ {modalRoute("pulse/:pulseId/unsubscribe", UnsubscribePulseModal)}
</Route>
);
}
diff --git a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
index 18a04bd3dea..8edae8c3351 100644
--- a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
@@ -3,7 +3,7 @@ import { useEffect } from "react";
import { skipToken, useGetActionQuery, useGetCardQuery } from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { connect, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
import type { AppErrorDescriptor } from "metabase/redux/store";
diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsx
index 27b097502c6..f1b88794946 100644
--- a/frontend/src/metabase/admin/routes.tsx
+++ b/frontend/src/metabase/admin/routes.tsx
@@ -28,11 +28,11 @@ import {
EmbeddingSettings,
GuestEmbedsSettings,
} from "metabase/admin/settings/components/EmbeddingSettings";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import {
SetupPermissionsAndTenantsPage,
SetupSsoPage,
} from "metabase/embedding/embedding-hub";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
import { DataModelV1 } from "metabase/metadata/pages/DataModelV1";
import { Help } from "metabase/monitor/tools/components/Help";
import { JobInfoApp } from "metabase/monitor/tools/components/JobInfoApp";
@@ -174,25 +174,17 @@ export const getRoutes = (
</Route>
<Route path="" component={PeopleListingApp}>
- <ModalRoute path="new" modal={NewUserModal} noWrap />
+ {modalRoute("new", NewUserModal, { noWrap: true })}
{PLUGIN_TENANTS.userStrategyRoute}
</Route>
<Route path=":userId" component={PeopleListingApp}>
<IndexRedirect to="/admin/people" />
- <ModalRoute path="edit" modal={EditUserModal} noWrap />
- <ModalRoute path="success" modal={UserSuccessModal} noWrap />
- <ModalRoute path="reset" modal={UserPasswordResetModal} noWrap />
- <ModalRoute
- path="deactivate"
- modal={UserActivationModal}
- noWrap
- />
- <ModalRoute
- path="reactivate"
- modal={UserActivationModal}
- noWrap
- />
+ {modalRoute("edit", EditUserModal, { noWrap: true })}
+ {modalRoute("success", UserSuccessModal, { noWrap: true })}
+ {modalRoute("reset", UserPasswordResetModal, { noWrap: true })}
+ {modalRoute("deactivate", UserActivationModal, { noWrap: true })}
+ {modalRoute("reactivate", UserActivationModal, { noWrap: true })}
{PLUGIN_ADMIN_USER_MENU_ROUTES.map((getRoutes, index) => (
<Fragment key={index}>{getRoutes()}</Fragment>
))}
@@ -335,27 +327,21 @@ export const getRoutes = (
component={PLUGIN_ADMIN_TOOLS.COMPONENT || ToolsUpsell}
/>
<Route path="model-caching" component={ModelCachePage}>
- <ModalRoute path=":jobId" modal={ModelCacheRefreshJobModal} />
+ {modalRoute(":jobId", ModelCacheRefreshJobModal)}
</Route>
<Route path="help" component={Help}>
- {PLUGIN_SUPPORT.isEnabled && (
- <ModalRoute
- modal={PLUGIN_SUPPORT.GrantAccessModal}
- path="grant-access"
- />
- )}
+ {PLUGIN_SUPPORT.isEnabled &&
+ modalRoute("grant-access", PLUGIN_SUPPORT.GrantAccessModal)}
</Route>
<Route path="tasks">{getTasksRoutes()}</Route>
<Route path="notifications">{getNotificationsRoutes()}</Route>
<Route path="jobs" component={JobInfoApp}>
- <ModalRoute
- path=":jobKey"
- modal={JobTriggersModal}
- modalProps={{ size: "85%" }}
- />
+ {modalRoute(":jobKey", JobTriggersModal, {
+ modalProps: { size: "85%" },
+ })}
</Route>
<Route path="logs" component={Logs}>
- <ModalRoute path="levels" modal={LogLevelsModal} />
+ {modalRoute("levels", LogLevelsModal)}
</Route>
{PLUGIN_DEPENDENCIES.isEnabled && (
<Route
diff --git a/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx b/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx
index 6b5aec7cb61..d56ce7bcc7f 100644
--- a/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx
+++ b/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx
@@ -49,7 +49,7 @@ const MoveCollectionModalView = ({
);
};
-// used with ModalRoute router
+// used with modalRoute
export const MoveCollectionModal = ({
collectionId,
params,
diff --git a/frontend/src/metabase/common/components/ModalRoute.tsx b/frontend/src/metabase/common/components/ModalRoute.tsx
new file mode 100644
index 00000000000..6e8c3b1845d
--- /dev/null
+++ b/frontend/src/metabase/common/components/ModalRoute.tsx
@@ -0,0 +1,101 @@
+import type { Location } from "history";
+import { useCallback } from "react";
+
+import { Route, useNavigate } from "metabase/router";
+import { Modal, type ModalProps } from "metabase/ui";
+
+type RouteParams = Record<string, string | undefined>;
+
+/**
+ * Base props any modal rendered by `modalRoute` must accept. Modals typically
+ * narrow `params` to specific keys (e.g. `{ alertId?: string }`), but they have
+ * to accept the full shape.
+ */
+export type ModalComponentProps = {
+ params: RouteParams;
+ location: Location;
+ /**
+ * The matched route, passed through only for `LeaveRouteConfirmModal`, which
+ * hands it to react-router v3's `setRouteLeaveHook`. Do not use it to derive
+ * URLs: `onClose` already returns to the parent page.
+ */
+ route?: Route;
+ onClose: () => void;
+};
+
+type ModalRouteOptions = {
+ /**
+ * Render the modal component on its own instead of wrapping it in a `<Modal>`,
+ * for components that bring their own overlay.
+ */
+ noWrap?: boolean;
+ modalProps?: Partial<ModalProps>;
+};
+
+/**
+ * Declare a modal as a child route of the page it opens over: the page stays
+ * mounted underneath, and closing the modal returns to the page's URL.
+ *
+ * `onClose` is wired here rather than left to each modal, so no modal has to
+ * work out its own parent URL.
+ */
+export function modalRoute(
+ path: string,
+ ComposedModal: React.ComponentType<ModalComponentProps>,
+ { noWrap = false, modalProps }: ModalRouteOptions = {},
+) {
+ function ModalRouteComponent({
+ params,
+ location,
+ route,
+ }: RouteInjectedProps) {
+ const navigate = useNavigate();
+ const onClose = useCallback(
+ () => navigate("..", { relative: "route" }),
+ [navigate],
+ );
+
+ const modal = (
+ <ComposedModal
+ params={params}
+ location={location}
+ route={route}
+ onClose={onClose}
+ />
+ );
+
+ if (noWrap) {
+ return modal;
+ }
+
+ return (
+ <Modal
+ opened
+ onClose={onClose}
+ withCloseButton={false}
+ padding={0}
+ size="lg"
+ {...modalProps}
+ >
+ {modal}
+ </Modal>
+ );
+ }
+
+ ModalRouteComponent.displayName = `ModalRoute[${
+ ComposedModal.displayName || ComposedModal.name
+ }]`;
+
+ // Keyed for the plugin route arrays, which React renders as a list.
+ return <Route key={path} path={path} component={ModalRouteComponent} />;
+}
+
+/**
+ * What react-router v3 injects into a route `component`. Replaced by the facade
+ * hooks when the engine swaps.
+ */
+type RouteInjectedProps = {
+ params: RouteParams;
+ location: Location;
+ route: Route;
+};
diff --git a/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx b/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx
new file mode 100644
index 00000000000..2e8cb1ccb39
--- /dev/null
+++ b/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx
@@ -0,0 +1,127 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+
+import { type ModalComponentProps, modalRoute } from "./ModalRoute";
+
+function CollectionPage({ children }: { children?: React.ReactNode }) {
+ return (
+ <div>
+ <span>Collection page</span>
+ {children}
+ </div>
+ );
+}
+
+function TestModal({ params, onClose }: ModalComponentProps) {
+ return (
+ <div>
+ <span>Modal for {params.slug ?? params.pulseId}</span>
+ <button onClick={onClose}>Close</button>
+ </div>
+ );
+}
+
+const modalProps = { transitionProps: { duration: 0 } };
+
+function setup(routes: React.ReactNode, initialRoute: string) {
+ const { history } = renderWithProviders(<>{routes}</>, {
+ withRouter: true,
+ initialRoute,
+ });
+
+ const pathname = () => history?.getCurrentLocation().pathname;
+ return { pathname };
+}
+
+const close = () =>
+ userEvent.click(screen.getByRole("button", { name: "Close" }));
+
+describe("modalRoute", () => {
+ it("renders the page and the modal when deep-linking to a modal URL", () => {
+ setup(
+ <Route path="collection/:slug" component={CollectionPage}>
+ {modalRoute("archive", TestModal, { modalProps })}
+ </Route>,
+ "/collection/5/archive",
+ );
+
+ expect(screen.getByText("Collection page")).toBeInTheDocument();
+ expect(screen.getByText("Modal for 5")).toBeInTheDocument();
+ });
+
+ it("returns to the parent URL on close", async () => {
+ const { pathname } = setup(
+ <Route path="collection/:slug" component={CollectionPage}>
+ {modalRoute("archive", TestModal, { modalProps })}
+ </Route>,
+ "/collection/5/archive",
+ );
+
+ await close();
+
+ expect(pathname()).toBe("/collection/5");
+ expect(screen.queryByText("Modal for 5")).not.toBeInTheDocument();
+ expect(screen.getByText("Collection page")).toBeInTheDocument();
+ });
+
+ it("closes a modal whose path spans several segments to the right parent", async () => {
+ const { pathname } = setup(
+ <Route path="account/notifications" component={CollectionPage}>
+ {modalRoute("pulse/:pulseId/archive", TestModal, { modalProps })}
+ </Route>,
+ "/account/notifications/pulse/7/archive",
+ );
+
+ expect(screen.getByText("Modal for 7")).toBeInTheDocument();
+
+ await close();
+
+ expect(pathname()).toBe("/account/notifications");
+ });
+
+ // The admin permissions pages hang modal routes off a parent whose path uses
+ // v3 optional groups, so the parent matches a variable number of segments.
+ it("closes to the right parent under a route with optional groups", async () => {
+ const { pathname } = setup(
+ <Route
+ path="database(/:databaseId)(/schema/:schemaName)(/table/:tableId)"
+ component={CollectionPage}
+ >
+ {modalRoute("impersonated/group/:groupId", TestModal, { modalProps })}
+ </Route>,
+ "/database/1/impersonated/group/2",
+ );
+
+ expect(screen.getByText("Collection page")).toBeInTheDocument();
+
+ await close();
+
+ expect(pathname()).toBe("/database/1");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("wraps the modal component in a dialog by default", () => {
+ setup(
+ <Route path="collection/:slug" component={CollectionPage}>
+ {modalRoute("archive", TestModal, { modalProps })}
+ </Route>,
+ "/collection/5/archive",
+ );
+
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("renders the modal component on its own with noWrap", () => {
+ setup(
+ <Route path="collection/:slug" component={CollectionPage}>
+ {modalRoute("archive", TestModal, { noWrap: true })}
+ </Route>,
+ "/collection/5/archive",
+ );
+
+ expect(screen.getByText("Modal for 5")).toBeInTheDocument();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/common/components/MoveQuestionsIntoDashboardsModal/MoveQuestionsIntoDashboardsModal.tsx b/frontend/src/metabase/common/components/MoveQuestionsIntoDashboardsModal/MoveQuestionsIntoDashboardsModal.tsx
index 60ccaa74e5b..9749452d7ec 100644
--- a/frontend/src/metabase/common/components/MoveQuestionsIntoDashboardsModal/MoveQuestionsIntoDashboardsModal.tsx
+++ b/frontend/src/metabase/common/components/MoveQuestionsIntoDashboardsModal/MoveQuestionsIntoDashboardsModal.tsx
@@ -1,5 +1,4 @@
import { QueryStatus } from "@reduxjs/toolkit/query";
-import type { Location } from "history";
import { useEffect } from "react";
import { t } from "ttag";
@@ -11,7 +10,7 @@ import {
import { useUserAcknowledgement } from "metabase/common/hooks/use-user-acknowledgement";
import { useDispatch, useSelector } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
-import { replace, withRouter } from "metabase/router";
+import { useNavigate } from "metabase/router";
import { getUserIsAdmin } from "metabase/selectors/user";
import * as Urls from "metabase/urls";
@@ -21,84 +20,80 @@ import { MoveQuestionsIntoDashboardsInfoModal } from "./MoveQuestionsIntoDashboa
interface MoveQuestionsIntoDashboardsModalProps {
onClose: () => void;
params: { slug?: string };
- location: Location<unknown>;
}
-export const MoveQuestionsIntoDashboardsModal = withRouter(
- ({
- location: { pathname },
- params,
- onClose: handleClose,
- }: MoveQuestionsIntoDashboardsModalProps) => {
- const collectionId = Urls.extractCollectionId(params.slug);
- const isAdmin = useSelector(getUserIsAdmin);
+export const MoveQuestionsIntoDashboardsModal = ({
+ params,
+ onClose: handleClose,
+}: MoveQuestionsIntoDashboardsModalProps) => {
+ const collectionId = Urls.extractCollectionId(params.slug);
+ const isAdmin = useSelector(getUserIsAdmin);
+ const navigate = useNavigate();
- const [ackedInfoStep, { ack: ackInfoStep, isLoading: isAckedInfoLoading }] =
- useUserAcknowledgement("dashboard_question_migration_info_modal");
+ const [ackedInfoStep, { ack: ackInfoStep, isLoading: isAckedInfoLoading }] =
+ useUserAcknowledgement("dashboard_question_migration_info_modal");
- const dispatch = useDispatch();
- const candidatesReq = useListCollectionDashboardQuestionCandidatesQuery(
- collectionId && isAdmin ? { collectionId } : skipToken,
- );
- const [bulkMove, bulkMoveReq] =
- useMoveCollectionDashboardQuestionCandidatesMutation();
-
- // redirect to base collection page if there's an invalid collection id
- useEffect(() => {
- if (collectionId === undefined || !isAdmin) {
- const redirectPath = pathname.replace("/move-questions-dashboard", "");
- dispatch(replace(redirectPath));
- }
- }, [dispatch, collectionId, pathname, isAdmin]);
+ const dispatch = useDispatch();
+ const candidatesReq = useListCollectionDashboardQuestionCandidatesQuery(
+ collectionId && isAdmin ? { collectionId } : skipToken,
+ );
+ const [bulkMove, bulkMoveReq] =
+ useMoveCollectionDashboardQuestionCandidatesMutation();
- const handleBulkMoveQuestionIntoDashboards = async () => {
- if (collectionId) {
- const cardIds = candidatesReq.data?.data.map((card) => card.id) ?? [];
- try {
- await bulkMove({ collectionId, cardIds }).unwrap();
- dispatch(
- addUndo({
- message: t`The questions were successfully moved into their dashboards`,
- }),
- );
- handleClose();
- } catch (err) {
- console.error(err);
- }
- }
- };
+ // redirect to base collection page if there's an invalid collection id
+ useEffect(() => {
+ if (collectionId === undefined || !isAdmin) {
+ navigate("..", { relative: "route", replace: true });
+ }
+ }, [navigate, collectionId, isAdmin]);
- // reset error state after 5 seconds
- useEffect(() => {
- if (bulkMoveReq.status === QueryStatus.rejected) {
- const timeout = setTimeout(() => bulkMoveReq.reset(), 5000);
- return () => clearTimeout(timeout);
+ const handleBulkMoveQuestionIntoDashboards = async () => {
+ if (collectionId) {
+ const cardIds = candidatesReq.data?.data.map((card) => card.id) ?? [];
+ try {
+ await bulkMove({ collectionId, cardIds }).unwrap();
+ dispatch(
+ addUndo({
+ message: t`The questions were successfully moved into their dashboards`,
+ }),
+ );
+ handleClose();
+ } catch (err) {
+ console.error(err);
}
- }, [bulkMoveReq]);
-
- if (isAckedInfoLoading) {
- return null;
}
+ };
- if (!ackedInfoStep) {
- return (
- <MoveQuestionsIntoDashboardsInfoModal
- onConfirm={ackInfoStep}
- onCancel={handleClose}
- />
- );
+ // reset error state after 5 seconds
+ useEffect(() => {
+ if (bulkMoveReq.status === QueryStatus.rejected) {
+ const timeout = setTimeout(() => bulkMoveReq.reset(), 5000);
+ return () => clearTimeout(timeout);
}
+ }, [bulkMoveReq]);
+ if (isAckedInfoLoading) {
+ return null;
+ }
+
+ if (!ackedInfoStep) {
return (
- <ConfirmMoveDashboardQuestionCandidatesModal
- candidates={candidatesReq.data?.data}
- isLoading={candidatesReq.isLoading}
- fetchError={candidatesReq.error}
- isMutating={bulkMoveReq.isLoading}
- mutationError={bulkMoveReq.error}
- onConfirm={handleBulkMoveQuestionIntoDashboards}
+ <MoveQuestionsIntoDashboardsInfoModal
+ onConfirm={ackInfoStep}
onCancel={handleClose}
/>
);
- },
-);
+ }
+
+ return (
+ <ConfirmMoveDashboardQuestionCandidatesModal
+ candidates={candidatesReq.data?.data}
+ isLoading={candidatesReq.isLoading}
+ fetchError={candidatesReq.error}
+ isMutating={bulkMoveReq.isLoading}
+ mutationError={bulkMoveReq.error}
+ onConfirm={handleBulkMoveQuestionIntoDashboards}
+ onCancel={handleClose}
+ />
+ );
+};
diff --git a/frontend/src/metabase/hoc/ModalRoute.tsx b/frontend/src/metabase/hoc/ModalRoute.tsx
deleted file mode 100644
index 80ab77c8e50..00000000000
--- a/frontend/src/metabase/hoc/ModalRoute.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import type { Location, LocationDescriptor } from "history";
-import { Component, cloneElement } from "react";
-
-import { connect } from "metabase/redux";
-import { Route, push } from "metabase/router";
-import { Modal, type ModalProps } from "metabase/ui";
-import MetabaseSettings from "metabase/utils/settings";
-
-type RouteParams = Record<string, string | undefined>;
-
-type IRoute = {
- path: string;
-};
-
-export const getParentPath = (route: IRoute, location: Location) => {
- // If instance has a custom url we need to exclude its subpath
- const siteUrlSegments = (MetabaseSettings.get("site-url") ?? "").split("/");
- const subPath = siteUrlSegments.slice(3).join("/");
-
- let pathName: string;
- if (subPath) {
- const subPathSplit = location.pathname.split(subPath);
-
- pathName =
- subPathSplit.length === 1
- ? subPathSplit[0]
- : subPathSplit.slice(1).join(subPath);
- } else {
- pathName = location.pathname;
- }
-
- const fullPathSegments = pathName.split("/");
- const routeSegments = route.path.split("/");
-
- fullPathSegments.splice(-routeSegments.length);
-
- return fullPathSegments.join("/");
-};
-
-export type ComposedModalProps<
- P extends RouteParams = RouteParams,
- Q = unknown,
-> = {
- params: P;
- location: Location<Q>;
- onClose: () => void;
-};
-
-interface WrappedModalRouteProps {
- route: IRoute;
- params: RouteParams;
- location: Location;
- onChangeLocation: (nextLocation: LocationDescriptor) => void;
-}
-
-const ModalWithRoute = (
- ComposedModal: React.ComponentType<ComposedModalProps>,
- modalProps: Partial<ModalProps> = {},
- noWrap = false,
-) => {
- class ModalRouteComponent extends Component<WrappedModalRouteProps> {
- static displayName: string = `ModalWithRoute[${
- ComposedModal.displayName || ComposedModal.name
- }]`;
-
- onClose = () => {
- const { location, route } = this.props;
-
- const parentPath = getParentPath(route, location);
- this.props.onChangeLocation(parentPath);
- };
-
- render() {
- if (noWrap) {
- return <ComposedModal {...this.props} onClose={this.onClose} />;
- }
-
- return (
- <Modal
- opened
- onClose={this.onClose}
- withCloseButton={false}
- padding={0}
- size="lg"
- {...modalProps}
- >
- <ComposedModal {...this.props} onClose={this.onClose} />
- </Modal>
- );
- }
- }
-
- return connect(null, { onChangeLocation: push })(ModalRouteComponent);
-};
-
-// Base props that any modal rendered by ModalRoute must accept.
-// Modal components typically narrow `params` to specific keys (e.g., { alertId?: string }),
-// but they must accept the full ComposedModalProps shape.
-export type ModalComponentProps = {
- params: RouteParams;
- location: Location;
- onClose: () => void;
-};
-
-interface ModalRouteProps {
- path: string;
- modal: React.ComponentType<ModalComponentProps>;
- modalProps?: Partial<ModalProps>;
- noWrap?: boolean;
-}
-
-// react-router Route wrapper that handles routed modals
-class _ModalRoute extends Route {
- static createRouteFromReactElement(element: React.ReactElement) {
- const { modal, modalProps, noWrap } = element.props;
-
- if (modal) {
- element = cloneElement(element, {
- component: ModalWithRoute(modal, modalProps, noWrap),
- });
-
- // @ts-expect-error - Route.createRouteFromReactElement is not typed
- return Route.createRouteFromReactElement(element);
- } else {
- throw new Error("`modal` property is missing from ModalRoute");
- }
- }
-}
-
-// Casting ModalRoute as there's no way to properly type its props
-// ModalRoute extends react-router's Route which is not generic,
-// so it's impossible to extend Route's props.
-export const ModalRoute =
- // Unjustified type cast. FIXME
- _ModalRoute as unknown as React.ComponentType<ModalRouteProps>;
diff --git a/frontend/src/metabase/hoc/ModalRoute.unit.spec.ts b/frontend/src/metabase/hoc/ModalRoute.unit.spec.ts
deleted file mode 100644
index b8d5be741fa..00000000000
--- a/frontend/src/metabase/hoc/ModalRoute.unit.spec.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { mockSettings } from "__support__/settings";
-import { createMockLocation } from "metabase/redux/store/mocks";
-
-import { getParentPath } from "./ModalRoute";
-
-const setup = (routePath: string, locationPath: string, siteURL?: string) => {
- if (siteURL) {
- mockSettings({ "site-url": siteURL });
- }
-
- return getParentPath(
- { path: routePath },
- createMockLocation({ pathname: locationPath }),
- );
-};
-
-describe("getParentPath", () => {
- describe("returns should cut off current route path", () => {
- it("without trailing slash", () => {
- const parentPath = setup(
- "segmented/group/5",
- "/admin/permissions/database/1/schema/2/table/3/segmented/group/5",
- );
-
- expect(parentPath).toEqual(
- "/admin/permissions/database/1/schema/2/table/3",
- );
- });
-
- it("with trailing slash", () => {
- const parentPath = setup(
- "segmented/group/5/",
- "/admin/permissions/database/1/schema/2/table/3/segmented/group/5/",
- );
-
- expect(parentPath).toEqual(
- "/admin/permissions/database/1/schema/2/table/3",
- );
- });
-
- it("for one route segment", () => {
- const parentPath = setup("c", "/a/b/c");
-
- expect(parentPath).toEqual("/a/b");
- });
-
- it("without single segment site url subpath", () => {
- const parentPath = setup(
- "c",
- "metabase/a/b/c",
- "https://somesite.com/metabase",
- );
-
- expect(parentPath).toEqual("/a/b");
- });
-
- it("without multi segment site url subpath", () => {
- const parentPath = setup(
- "c",
- "meta/base/a/b/c",
- "https://somesite.com/meta/base",
- );
-
- expect(parentPath).toEqual("/a/b");
- });
-
- // This is to handle the edge case where someone uses a subpath name
- // like "data" that is also used within Metabase's routes
- // e.g. If the site-url is "https://corp.com/data", it should not
- // remove the second "data" from the path in "https://corp.com/data/admin/permissions/data/groups"
- it("without leading url subpath while preserving later occurrences", () => {
- const parentPath = setup(
- "groups",
- "data/admin/permissions/data/groups",
- "https://corp.com/data",
- );
-
- expect(parentPath).toEqual("/admin/permissions/data");
- });
- });
-});
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
index a0fce2841b0..c4587be030f 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
@@ -111,7 +111,7 @@ function ModelActions({
model={model}
shouldShowActionsUI={shouldShowActionsUI}
/>
- {/* Required for rendering child `ModalRoute` elements */}
+ {/* Required for rendering child modal routes */}
{children}
</>
);
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
index 81d80703953..56f0c5606ac 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
@@ -18,7 +18,7 @@ import {
within,
} from "__support__/ui";
import ActionCreator from "metabase/actions/containers/ActionCreatorModal";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import {
createMockSettingsState,
createMockState,
@@ -224,16 +224,12 @@ async function setup({
<Route path="/model/:slug/detail">
<IndexRedirect to="actions" />
<Route path="actions" component={ModelActions}>
- <ModalRoute
- path="new"
- modal={ActionCreator}
- modalProps={{ transitionProps: { duration: 0 } }}
- />
- <ModalRoute
- path=":actionId"
- modal={ActionCreator}
- modalProps={{ transitionProps: { duration: 0 } }}
- />
+ {modalRoute("new", ActionCreator, {
+ modalProps: { transitionProps: { duration: 0 } },
+ })}
+ {modalRoute(":actionId", ActionCreator, {
+ modalProps: { transitionProps: { duration: 0 } },
+ })}
</Route>
</Route>
<Route path="/question/:slug" component={() => null} />
diff --git a/frontend/src/metabase/models/routes.tsx b/frontend/src/metabase/models/routes.tsx
index cae202e629e..de2c2dad07e 100644
--- a/frontend/src/metabase/models/routes.tsx
+++ b/frontend/src/metabase/models/routes.tsx
@@ -1,6 +1,6 @@
import ActionCreatorModal from "metabase/actions/containers/ActionCreatorModal/ActionCreatorModal";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { ModelDetailPage } from "metabase/detail-view/pages/ModelDetailPage/ModelDetailPage";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
import ModelActions from "metabase/models/containers/ModelActions/ModelActions";
import { IndexRedirect, Redirect, Route } from "metabase/router";
import {
@@ -16,16 +16,8 @@ export const getRoutes = () => {
return (
<Route path="/model/:slug/detail">
<Route path="actions" component={ModelActions}>
- <ModalRoute
- path="new"
- modal={ActionCreatorModal}
- modalProps={modalProps}
- />
- <ModalRoute
- path=":actionId"
- modal={ActionCreatorModal}
- modalProps={modalProps}
- />
+ {modalRoute("new", ActionCreatorModal, { modalProps })}
+ {modalRoute(":actionId", ActionCreatorModal, { modalProps })}
</Route>
<Route path=":rowId" component={ModelDetailPage} />
<IndexRedirect to="actions" />
diff --git a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx
index b3fd5d727c9..6befb192dd0 100644
--- a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx
@@ -14,7 +14,7 @@ import {
within,
} from "__support__/ui";
import { getNextId } from "__support__/utils";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { Route } from "metabase/router";
import { checkNotNull } from "metabase/utils/types";
import type { LoggerPreset } from "metabase-types/api";
@@ -56,11 +56,9 @@ const setup = ({ error, presets = [PRESET_A, PRESET_B] }: SetupOpts = {}) => {
return renderWithProviders(
<Route path="/">
- <ModalRoute
- path="levels"
- modal={LogLevelsModal}
- modalProps={{ transitionProps: { duration: 0 } }}
- />
+ {modalRoute("levels", LogLevelsModal, {
+ modalProps: { transitionProps: { duration: 0 } },
+ })}
</Route>,
{
initialRoute: "/levels",
diff --git a/frontend/src/metabase/monitor/tools/components/ModelCacheRefreshJobs/ModelCacheRefreshJobModal.tsx b/frontend/src/metabase/monitor/tools/components/ModelCacheRefreshJobs/ModelCacheRefreshJobModal.tsx
index 9a877255575..f463cc27ec5 100644
--- a/frontend/src/metabase/monitor/tools/components/ModelCacheRefreshJobs/ModelCacheRefreshJobModal.tsx
+++ b/frontend/src/metabase/monitor/tools/components/ModelCacheRefreshJobs/ModelCacheRefreshJobModal.tsx
@@ -9,8 +9,8 @@ import {
} from "metabase/api";
import { Link } from "metabase/common/components/Link";
import { ModalContent } from "metabase/common/components/ModalContent";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import ButtonsS from "metabase/css/components/buttons.module.css";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
import { Button } from "metabase/ui";
import { parseNumberParam } from "metabase/urls";
diff --git a/frontend/src/metabase/plugins/oss/support.ts b/frontend/src/metabase/plugins/oss/support.ts
index b41aad0022b..c885a8e1187 100644
--- a/frontend/src/metabase/plugins/oss/support.ts
+++ b/frontend/src/metabase/plugins/oss/support.ts
@@ -1,6 +1,6 @@
import type { ComponentType } from "react";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { PluginPlaceholder } from "../components/PluginPlaceholder";
diff --git a/frontend/src/metabase/router/conformance/relative-navigate.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/relative-navigate.conformance.unit.spec.tsx
new file mode 100644
index 00000000000..4b97aadbf68
--- /dev/null
+++ b/frontend/src/metabase/router/conformance/relative-navigate.conformance.unit.spec.tsx
@@ -0,0 +1,116 @@
+import userEvent from "@testing-library/user-event";
+
+import { screen } from "__support__/ui";
+
+import type { RouterApi } from "./test-utils";
+import { runBoth } from "./test-utils";
+
+/**
+ * Mounted in a child route, so `relative: "route"` resolves against the child.
+ * The readouts come from the parent route, which stays mounted after the probe
+ * navigates away.
+ */
+function RelativeNavigateProbe({ api }: { api: RouterApi }) {
+ const navigate = api.useNavigate();
+ return (
+ <div>
+ <button onClick={() => navigate("..", { relative: "route" })}>
+ up-route
+ </button>
+ <button onClick={() => navigate("..", { relative: "path" })}>
+ up-path
+ </button>
+ <button onClick={() => navigate("..")}>up-default</button>
+ <button onClick={() => navigate("../sibling")}>sibling</button>
+ <button onClick={() => navigate("..", { replace: true })}>
+ up-replace
+ </button>
+ <button onClick={() => navigate("?x=1")}>query-only</button>
+ </div>
+ );
+}
+
+const click = (name: string) =>
+ userEvent.click(screen.getByRole("button", { name }));
+
+const collectionRoute = {
+ initialRoute: "/collection/5/move",
+ facadePath: "collection/:slug",
+ v7Path: "collection/:slug",
+ childPath: "move",
+};
+
+// A modal route whose path spans several URL segments, e.g. the account
+// notification routes' `pulse/:pulseId/archive`.
+const multiSegmentRoute = {
+ initialRoute: "/account/notifications/pulse/7/archive",
+ facadePath: "account/notifications",
+ v7Path: "account/notifications",
+ childPath: "pulse/:pulseId/archive",
+};
+
+describe("router/useNavigate relative conformance", () => {
+ it('matches v7 when ".." climbs one route', async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...collectionRoute,
+ interact: () => click("up-route"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/collection/5");
+ });
+
+ it('matches v7 when ".." defaults to route-relative', async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...collectionRoute,
+ interact: () => click("up-default"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/collection/5");
+ });
+
+ it('matches v7 when ".." climbs a route spanning several segments', async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...multiSegmentRoute,
+ interact: () => click("up-route"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/account/notifications");
+ });
+
+ it('matches v7 when ".." climbs a single segment with relative: "path"', async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...multiSegmentRoute,
+ interact: () => click("up-path"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/account/notifications/pulse/7");
+ });
+
+ it("matches v7 when navigating to a sibling route", async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...collectionRoute,
+ interact: () => click("sibling"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/collection/5/sibling");
+ });
+
+ it('matches v7 when ".." replaces the current entry', async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...collectionRoute,
+ interact: () => click("up-replace"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/collection/5");
+ });
+
+ it("matches v7 when a destination carries only a query", async () => {
+ const { facade, v7 } = await runBoth(RelativeNavigateProbe, {
+ ...collectionRoute,
+ interact: () => click("query-only"),
+ });
+ expect(facade).toEqual(v7);
+ expect(facade["rr-pathname"]).toBe("/collection/5/move");
+ expect(facade["rr-search"]).toBe("?x=1");
+ });
+});
diff --git a/frontend/src/metabase/router/conformance/test-utils.tsx b/frontend/src/metabase/router/conformance/test-utils.tsx
index 69083f30341..608d3319fdb 100644
--- a/frontend/src/metabase/router/conformance/test-utils.tsx
+++ b/frontend/src/metabase/router/conformance/test-utils.tsx
@@ -1,8 +1,14 @@
-import type { ComponentType, PropsWithChildren, ReactElement } from "react";
+import type {
+ ComponentType,
+ PropsWithChildren,
+ ReactElement,
+ ReactNode,
+} from "react";
import { Route } from "react-router";
import {
MemoryRouter,
Navigate as V7Navigate,
+ Outlet as V7Outlet,
Route as V7Route,
Routes as V7Routes,
useLocation as v7UseLocation,
@@ -69,25 +75,83 @@ export type RenderOptions = {
initialRoute: string;
facadePath?: string;
v7Path?: string;
+ /**
+ * Mount the probe in a child route of `facadePath`/`v7Path` instead of in the
+ * route itself. The parent route emits the readouts, so they survive a probe
+ * that navigates itself out of the tree.
+ */
+ childPath?: string;
};
+function ParentReadouts({
+ location,
+}: {
+ location: { pathname: string; search: string };
+}) {
+ return (
+ <>
+ <span data-testid="rr-pathname">{location.pathname}</span>
+ <span data-testid="rr-search">{location.search}</span>
+ </>
+ );
+}
+
+function FacadeParent({ children }: { children?: ReactNode }) {
+ return (
+ <div>
+ <ParentReadouts location={useLocation()} />
+ {children}
+ </div>
+ );
+}
+
+function V7Parent() {
+ return (
+ <div>
+ <ParentReadouts location={v7UseLocation()} />
+ <V7Outlet />
+ </div>
+ );
+}
+
+// Keeps the parent route matched wherever a probe navigates below it, so both
+// engines are compared on the destination rather than on an unmatched URL.
+const Nothing = () => null;
+
function renderFacade(
Probe: Probe,
- { initialRoute, facadePath = "*" }: RenderOptions,
+ { initialRoute, facadePath = "*", childPath }: RenderOptions,
) {
const Mounted = () => <Probe api={facadeApi} />;
- renderWithProviders(<Route path={facadePath} component={Mounted} />, {
- withRouter: true,
- initialRoute,
- });
+ const tree = childPath ? (
+ <Route path={facadePath} component={FacadeParent}>
+ <Route path={childPath} component={Mounted} />
+ <Route path="*" component={Nothing} />
+ </Route>
+ ) : (
+ <Route path={facadePath} component={Mounted} />
+ );
+
+ renderWithProviders(tree, { withRouter: true, initialRoute });
}
-function renderV7(Probe: Probe, { initialRoute, v7Path = "*" }: RenderOptions) {
+function renderV7(
+ Probe: Probe,
+ { initialRoute, v7Path = "*", childPath }: RenderOptions,
+) {
+ const probe = <Probe api={v7Api} />;
+ const tree = childPath ? (
+ <V7Route path={v7Path} element={<V7Parent />}>
+ <V7Route path={childPath} element={probe} />
+ <V7Route path="*" element={<Nothing />} />
+ </V7Route>
+ ) : (
+ <V7Route path={v7Path} element={probe} />
+ );
+
renderWithProviders(
<MemoryRouter initialEntries={[initialRoute]}>
- <V7Routes>
- <V7Route path={v7Path} element={<Probe api={v7Api} />} />
- </V7Routes>
+ <V7Routes>{tree}</V7Routes>
</MemoryRouter>,
);
}
diff --git a/frontend/src/metabase/router/react-router.ts b/frontend/src/metabase/router/react-router.ts
index 59aa1642622..c409ea56ba1 100644
--- a/frontend/src/metabase/router/react-router.ts
+++ b/frontend/src/metabase/router/react-router.ts
@@ -24,6 +24,12 @@ export {
withRouter,
} from "react-router";
+// v3's own path matcher, used to work out how much of the URL each matched route
+// accounts for. Its pattern syntax has corners a hand-rolled parser gets wrong
+// (optional groups like `database(/:databaseId)`, splats), so the engine's
+// matcher is the only safe reader of it. Goes away with the engine swap.
+export { matchPattern } from "react-router/lib/PatternUtils";
+
export type {
InjectedRouter,
LinkProps as RouterLinkProps,
diff --git a/frontend/src/metabase/router/resolve-to.ts b/frontend/src/metabase/router/resolve-to.ts
new file mode 100644
index 00000000000..d0153319b36
--- /dev/null
+++ b/frontend/src/metabase/router/resolve-to.ts
@@ -0,0 +1,149 @@
+import { type PlainRoute, matchPattern } from "./react-router";
+import type { Path, To } from "./types";
+import { parsePath } from "./utils";
+
+/**
+ * The URL prefix each matched route accounts for, mirroring react-router v7's
+ * `match.pathnameBase`. Resolving `".."` walks this list rather than the URL,
+ * so a route whose path spans several segments (`pulse/:pulseId/archive`) is
+ * left in a single step, and a pathless route is left in no steps at all.
+ *
+ * How much of the URL a route accounts for is measured with v3's own
+ * `matchPattern` rather than by counting `/`. A v3 pattern segment does not map
+ * to one URL segment: `database(/:databaseId)(/schema/:schemaName)` matches
+ * anything from `database` to `database/1/schema/public`.
+ *
+ * A splat (`*`, `:entity_id(**)`) swallows the rest of the URL, so that route's
+ * own entry covers the splat where v7's `pathnameBase` would stop before it.
+ * `".."` reads the parent's entry rather than the route's own, so it still
+ * climbs correctly out of a splat route.
+ */
+export function getRoutePathnames(
+ routes: PlainRoute[],
+ locationPathname: string,
+): string[] {
+ let matched = "";
+ let remaining = locationPathname;
+
+ return routes.map((route) => {
+ const path = route.path;
+ if (path) {
+ // v3 matches an absolute child path against the whole pathname rather
+ // than against what its parents left over.
+ if (path.startsWith("/")) {
+ matched = "";
+ remaining = locationPathname;
+ }
+
+ const match = matchPattern(path, remaining);
+ if (match) {
+ // `matchPattern` hands back the separator at the head of the remainder,
+ // so what it consumed is the rest of the string.
+ const consumed = remaining.slice(
+ 0,
+ remaining.length - match.remainingPathname.length,
+ );
+ matched += consumed;
+ remaining = match.remainingPathname;
+ }
+ }
+ return withoutTrailingSlash(matched);
+ });
+}
+
+function withoutTrailingSlash(pathname: string): string {
+ const trimmed = pathname.replace(/\/+$/, "");
+ return trimmed === "" ? "/" : trimmed;
+}
+
+/**
+ * Resolve a `to` against the matched routes, mirroring react-router v7's
+ * `resolveTo`. Absolute destinations pass through untouched; `".."` climbs one
+ * route (or one path segment when `isPathRelative`), and a destination with no
+ * pathname keeps the current one.
+ *
+ * @see https://github.com/remix-run/react-router/blob/main/packages/react-router/lib/router/utils.ts
+ */
+export function resolveTo(
+ to: To,
+ routePathnames: string[],
+ locationPathname: string,
+ isPathRelative: boolean,
+): Path {
+ const path = typeof to === "string" ? parsePath(to) : { ...to };
+ const isEmptyPath = to === "" || path.pathname === "";
+ const toPathname = isEmptyPath ? "/" : path.pathname;
+
+ let from: string;
+ if (toPathname == null) {
+ from = locationPathname;
+ } else {
+ let routeIndex = routePathnames.length - 1;
+
+ if (!isPathRelative && toPathname.startsWith("..")) {
+ const segments = toPathname.split("/");
+ while (segments[0] === "..") {
+ segments.shift();
+ routeIndex -= 1;
+ }
+ path.pathname = segments.join("/");
+ }
+
+ from = routeIndex >= 0 ? routePathnames[routeIndex] : "/";
+ }
+
+ const resolved = resolvePath(path, from);
+
+ const hasExplicitTrailingSlash =
+ toPathname != null && toPathname !== "/" && toPathname.endsWith("/");
+ const hasCurrentTrailingSlash =
+ (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
+
+ if (
+ !resolved.pathname.endsWith("/") &&
+ (hasExplicitTrailingSlash || hasCurrentTrailingSlash)
+ ) {
+ resolved.pathname += "/";
+ }
+
+ return resolved;
+}
+
+function resolvePath(to: Partial<Path>, fromPathname: string): Path {
+ const { pathname: toPathname, search = "", hash = "" } = to;
+
+ const pathname = toPathname
+ ? toPathname.startsWith("/")
+ ? toPathname
+ : resolvePathname(toPathname, fromPathname)
+ : fromPathname;
+
+ return {
+ pathname,
+ search: normalize(search, "?"),
+ hash: normalize(hash, "#"),
+ };
+}
+
+function resolvePathname(relativePath: string, fromPathname: string): string {
+ const segments = fromPathname.replace(/\/+$/, "").split("/");
+
+ relativePath.split("/").forEach((segment) => {
+ if (segment === "..") {
+ if (segments.length > 1) {
+ segments.pop();
+ }
+ } else if (segment !== ".") {
+ segments.push(segment);
+ }
+ });
+
+ return segments.length > 1 ? segments.join("/") : "/";
+}
+
+function normalize(value: string, prefix: string): string {
+ if (!value || value === prefix) {
+ return "";
+ }
+ return value.startsWith(prefix) ? value : prefix + value;
+}
diff --git a/frontend/src/metabase/router/resolve-to.unit.spec.ts b/frontend/src/metabase/router/resolve-to.unit.spec.ts
new file mode 100644
index 00000000000..ca2417ae9b6
--- /dev/null
+++ b/frontend/src/metabase/router/resolve-to.unit.spec.ts
@@ -0,0 +1,102 @@
+import type { PlainRoute } from "./react-router";
+import { getRoutePathnames, resolveTo } from "./resolve-to";
+
+// getRoutePathnames only reads `path`; the rest of PlainRoute is irrelevant here.
+const route = (path?: string) => ({ path }) as PlainRoute;
+
+// The pathname `".."` resolves to, from the deepest of `routes`.
+const parentOf = (routes: PlainRoute[], pathname: string) =>
+ resolveTo("..", getRoutePathnames(routes, pathname), pathname, false)
+ .pathname;
+
+describe("getRoutePathnames", () => {
+ it("gives a route with no path the pathname of its parent", () => {
+ expect(
+ getRoutePathnames(
+ [route(), route("collection/:slug"), route(), route("archive")],
+ "/collection/5/archive",
+ ),
+ ).toEqual(["/", "/collection/5", "/collection/5", "/collection/5/archive"]);
+ });
+
+ it("matches an absolute child path against the whole pathname", () => {
+ expect(
+ getRoutePathnames(
+ [route("/model/:slug/detail"), route("actions"), route("new")],
+ "/model/5-orders/detail/actions/new",
+ )[1],
+ ).toBe("/model/5-orders/detail/actions");
+ });
+});
+
+describe("resolveTo", () => {
+ it('climbs one route for ".."', () => {
+ expect(
+ parentOf(
+ [route("collection/:slug"), route("archive")],
+ "/collection/5/archive",
+ ),
+ ).toBe("/collection/5");
+ });
+
+ it("climbs a route whose path spans several segments", () => {
+ expect(
+ parentOf(
+ [route("account/notifications"), route("pulse/:pulseId/archive")],
+ "/account/notifications/pulse/7/archive",
+ ),
+ ).toBe("/account/notifications");
+ });
+
+ // v3 optional groups match a variable number of URL segments, so the number of
+ // `/` in the pattern says nothing about how much of the URL it accounts for.
+ describe("v3 optional groups", () => {
+ const databaseRoutes = (child: string) => [
+ route("data"),
+ route("database(/:databaseId)(/schema/:schemaName)(/table/:tableId)"),
+ route(child),
+ ];
+
+ it("climbs past an optional group that matched nothing", () => {
+ expect(
+ parentOf(
+ databaseRoutes("impersonated/group/:groupId"),
+ "/data/database/1/impersonated/group/2",
+ ),
+ ).toBe("/data/database/1");
+ });
+
+ it("climbs past optional groups that all matched", () => {
+ expect(
+ parentOf(
+ databaseRoutes("segmented/group/:groupId"),
+ "/data/database/1/schema/public/table/3/segmented/group/5",
+ ),
+ ).toBe("/data/database/1/schema/public/table/3");
+ });
+
+ it("climbs out of a route whose path ends in a splat", () => {
+ expect(
+ parentOf(
+ [route("collection"), route("entity/:entity_id(**)")],
+ "/collection/entity/abc/def",
+ ),
+ ).toBe("/collection");
+ });
+
+ it("climbs past a group route with a partially matched optional tail", () => {
+ expect(
+ parentOf(
+ [
+ route("data"),
+ route(
+ "group(/:groupId)(/database/:databaseId)(/schema/:schemaName)",
+ ),
+ route("segmented/group/:groupId"),
+ ],
+ "/data/group/2/database/1/segmented/group/5",
+ ),
+ ).toBe("/data/group/2/database/1");
+ });
+ });
+});
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 2a346ef1b2c..ecba94122bb 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -31,6 +31,14 @@ export interface Location<State = unknown> {
key: string;
}
+/**
+ * Whether a relative `to` is resolved against the route hierarchy or against
+ * the current URL path.
+ *
+ * @see https://api.reactrouter.com/v7/types/react-router.RelativeRoutingType.html
+ */
+export type RelativeRoutingType = "route" | "path";
+
/**
* Options for the `navigate` function, mirroring react-router v7's
* `NavigateOptions`.
@@ -40,6 +48,7 @@ export interface Location<State = unknown> {
export interface NavigateOptions {
replace?: boolean;
state?: unknown;
+ relative?: RelativeRoutingType;
}
/**
diff --git a/frontend/src/metabase/router/use-navigate.ts b/frontend/src/metabase/router/use-navigate.ts
index 7bd40c556c6..21e1d2d9f74 100644
--- a/frontend/src/metabase/router/use-navigate.ts
+++ b/frontend/src/metabase/router/use-navigate.ts
@@ -1,29 +1,22 @@
-import type { LocationDescriptor } from "history";
-import { useCallback } from "react";
+import { useCallback, useRef } from "react";
+import { getRoutePathnames, resolveTo } from "./resolve-to";
import type { NavigateFunction, NavigateOptions, To } from "./types";
import { useRouter } from "./use-router";
-import { parsePath } from "./utils";
-
-function toLocationDescriptor(to: To, state: unknown): LocationDescriptor {
- if (typeof to === "string" && state === undefined) {
- return to;
- }
- if (typeof to === "string") {
- return { ...parsePath(to), state };
- }
- return { ...to, state };
-}
/**
* react-router v7's `useNavigate`, implemented over react-router v3's imperative
* router (`router.push/replace/go`).
*
- * - `navigate(to, { replace?, state? })` pushes (or replaces) the location.
+ * - `navigate(to, { replace?, state?, relative? })` pushes (or replaces) the location.
* - `navigate(delta)` moves through the history stack (e.g. `navigate(-1)`).
*
- * Absolute paths only: v7's relative `to` (`".."`, `"child"`) is not resolved on
- * v3, that lands with the engine swap and modal routes (Phase 1.3).
+ * A relative `to` (`".."`, `"child"`) resolves against the matched route branch,
+ * which v3 does not do on its own. The branch comes from the router context, so
+ * it always ends at the deepest matched route: unlike v7, a component rendered
+ * by a parent route resolves `".."` as if it sat in the leaf route. Nothing
+ * relies on that today, and the route context added with the engine swap removes
+ * the difference.
*
* The returned function gets a new identity whenever the pathname changes, like
* v7 (whose callback depends on the current pathname). Keeping it stable would
@@ -35,7 +28,14 @@ function toLocationDescriptor(to: To, state: unknown): LocationDescriptor {
* @see https://reactrouter.com/7.18.1/api/hooks/useNavigate
*/
export function useNavigate(): NavigateFunction {
- const { router, location } = useRouter();
+ const { router, location, routes } = useRouter();
+
+ // Read through a ref rather than listed as a dependency: v3 rebuilds `routes`
+ // on every transition, including a push to the pathname already showing. As a
+ // dependency it would hand back a new `navigate` after such a push, so a
+ // mounted `<Navigate>` would re-run its effect and push its target forever.
+ const routesRef = useRef(routes);
+ routesRef.current = routes;
return useCallback(
(to: To | number, options: NavigateOptions = {}) => {
@@ -44,16 +44,20 @@ export function useNavigate(): NavigateFunction {
return;
}
- const descriptor = toLocationDescriptor(to, options.state);
+ const path = resolveTo(
+ to,
+ getRoutePathnames(routesRef.current, location.pathname),
+ location.pathname,
+ options.relative === "path",
+ );
+ const descriptor = { ...path, state: options.state };
+
if (options.replace) {
router.replace(descriptor);
} else {
router.push(descriptor);
}
},
- // location.pathname does not affect a single call, it is here to give
- // `navigate` a new identity per navigation, matching v7.
- // eslint-disable-next-line react-hooks/exhaustive-deps
[router, location.pathname],
);
}
diff --git a/frontend/src/metabase/router/use-navigate.unit.spec.tsx b/frontend/src/metabase/router/use-navigate.unit.spec.tsx
index f55441eed36..d207415654f 100644
--- a/frontend/src/metabase/router/use-navigate.unit.spec.tsx
+++ b/frontend/src/metabase/router/use-navigate.unit.spec.tsx
@@ -1,4 +1,5 @@
import userEvent from "@testing-library/user-event";
+import { useState } from "react";
import { renderWithProviders, screen } from "__support__/ui";
@@ -27,6 +28,19 @@ function NavigateProbe() {
);
}
+function IdentityProbe() {
+ const navigate = useNavigate();
+ const [identities] = useState(() => new Set<unknown>());
+ identities.add(navigate);
+
+ return (
+ <div>
+ <span data-testid="identities">{identities.size}</span>
+ <button onClick={() => navigate("/same")}>push-same</button>
+ </div>
+ );
+}
+
function setup(initialRoute = "/") {
return renderWithProviders(<Route path="*" component={NavigateProbe} />, {
withRouter: true,
@@ -84,4 +98,19 @@ describe("router/useNavigate", () => {
await click("back"); // navigate(-1)
expect(history?.getCurrentLocation().pathname).toBe("/start");
});
+
+ it("keeps `navigate` stable when pushing the pathname already showing", async () => {
+ // v3 rebuilds the matched `routes` on every transition, so anything derived
+ // from them must not leak into `navigate`'s identity: a mounted <Navigate>
+ // re-runs its effect on a new identity and would push its target forever.
+ renderWithProviders(<Route path="*" component={IdentityProbe} />, {
+ withRouter: true,
+ initialRoute: "/same",
+ });
+
+ await click("push-same");
+ await click("push-same");
+
+ expect(screen.getByTestId("identities")).toHaveTextContent("1");
+ });
});
diff --git a/frontend/src/metabase/router/utils.ts b/frontend/src/metabase/router/utils.ts
index 9014cf55069..74546f4ae8d 100644
--- a/frontend/src/metabase/router/utils.ts
+++ b/frontend/src/metabase/router/utils.ts
@@ -2,27 +2,34 @@ import type { Path, URLSearchParamsInit } from "./types";
/**
* Split a path string into `pathname`, `search`, and `hash`, mirroring
- * react-router v7's `parsePath`. Used when a string destination has to be
- * combined with history `state` into a v3 location descriptor.
+ * react-router v7's `parsePath`. A part that the string does not carry is left
+ * out rather than set to `""`, which is how `resolveTo` tells `"?x=1"` (keep
+ * the current pathname) apart from `"/"` (go to the root).
*/
-export function parsePath(path: string): Path {
- let pathname = path;
- let search = "";
- let hash = "";
+export function parsePath(path: string): Partial<Path> {
+ const parsed: Partial<Path> = {};
- const hashIndex = pathname.indexOf("#");
+ if (!path) {
+ return parsed;
+ }
+
+ const hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
- hash = pathname.slice(hashIndex);
- pathname = pathname.slice(0, hashIndex);
+ parsed.hash = path.slice(hashIndex);
+ path = path.slice(0, hashIndex);
}
- const searchIndex = pathname.indexOf("?");
+ const searchIndex = path.indexOf("?");
if (searchIndex >= 0) {
- search = pathname.slice(searchIndex);
- pathname = pathname.slice(0, searchIndex);
+ parsed.search = path.slice(searchIndex);
+ path = path.slice(0, searchIndex);
+ }
+
+ if (path) {
+ parsed.pathname = path;
}
- return { pathname, search, hash };
+ return parsed;
}
/**
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 7919712b484..a2c5cc831f5 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -21,6 +21,7 @@ import CollectionLanding from "metabase/collections/components/CollectionLanding
import { MoveCollectionModal } from "metabase/collections/components/MoveCollectionModal";
import { TrashCollectionLanding } from "metabase/collections/components/TrashCollectionLanding";
import { Unauthorized } from "metabase/common/components/ErrorPages";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { MoveQuestionsIntoDashboardsModal } from "metabase/common/components/MoveQuestionsIntoDashboardsModal";
import { NotFoundFallbackPage } from "metabase/common/components/NotFoundFallbackPage";
import { UnsubscribePage } from "metabase/common/components/Unsubscribe";
@@ -34,7 +35,6 @@ import { getDataStudioRoutes } from "metabase/data-studio/routes";
import { TableDetailPage } from "metabase/detail-view/pages/TableDetailPage";
import { CommentsSidesheet } from "metabase/documents/components/CommentsSidesheet";
import { DocumentPageOuter } from "metabase/documents/routes";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
import { LandingPageRedirect } from "metabase/home/components/LandingPageRedirect";
import { Onboarding } from "metabase/home/components/Onboarding";
import { getMetabotRoutes } from "metabase/metabot/routes";
@@ -137,11 +137,9 @@ export const getRoutes = (store: AppStore) => {
<Route path="trash" component={TrashCollectionLanding} />
<Route path="document/:entityId" component={DocumentPageOuter}>
- <ModalRoute
- path="comments/:childTargetId"
- modal={CommentsSidesheet}
- noWrap
- />
+ {modalRoute("comments/:childTargetId", CommentsSidesheet, {
+ noWrap: true,
+ })}
</Route>
<Route
@@ -177,13 +175,13 @@ export const getRoutes = (store: AppStore) => {
</Route>
<Route path="collection/:slug" component={CollectionLanding}>
- <ModalRoute path="move" modal={MoveCollectionModal} noWrap />
- <ModalRoute path="archive" modal={ArchiveCollectionModal} noWrap />
- <ModalRoute path="permissions" modal={CollectionPermissionsModal} />
- <ModalRoute
- path="move-questions-dashboard"
- modal={MoveQuestionsIntoDashboardsModal}
- />
+ {modalRoute("move", MoveCollectionModal, { noWrap: true })}
+ {modalRoute("archive", ArchiveCollectionModal, { noWrap: true })}
+ {modalRoute("permissions", CollectionPermissionsModal)}
+ {modalRoute(
+ "move-questions-dashboard",
+ MoveQuestionsIntoDashboardsModal,
+ )}
{PLUGIN_COLLECTIONS.cleanUpRoute}
{getCollectionTimelineRoutes()}
</Route>
@@ -207,21 +205,11 @@ export const getRoutes = (store: AppStore) => {
/>
<Route path="dashboard/:slug" component={DashboardApp}>
- <ModalRoute
- path="move"
- modal={DashboardMoveModalConnected}
- noWrap
- />
- <ModalRoute
- path="copy"
- modal={DashboardCopyModalConnected}
- noWrap
- />
- <ModalRoute
- path="archive"
- modal={ArchiveDashboardModalConnected}
- noWrap
- />
+ {modalRoute("move", DashboardMoveModalConnected, { noWrap: true })}
+ {modalRoute("copy", DashboardCopyModalConnected, { noWrap: true })}
+ {modalRoute("archive", ArchiveDashboardModalConnected, {
+ noWrap: true,
+ })}
</Route>
<Route path="/question">
diff --git a/frontend/src/metabase/timelines/collections/containers/DeleteEventModal/DeleteEventModal.tsx b/frontend/src/metabase/timelines/collections/containers/DeleteEventModal/DeleteEventModal.tsx
index 9b5941a714d..3c879cc5a79 100644
--- a/frontend/src/metabase/timelines/collections/containers/DeleteEventModal/DeleteEventModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/DeleteEventModal/DeleteEventModal.tsx
@@ -5,7 +5,7 @@ import {
useGetTimelineQuery,
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import DeleteEventModal from "metabase/timelines/common/components/DeleteEventModal";
diff --git a/frontend/src/metabase/timelines/collections/containers/DeleteTimelineModal/DeleteTimelineModal.tsx b/frontend/src/metabase/timelines/collections/containers/DeleteTimelineModal/DeleteTimelineModal.tsx
index a5a56f2b7eb..c6994bb85f1 100644
--- a/frontend/src/metabase/timelines/collections/containers/DeleteTimelineModal/DeleteTimelineModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/DeleteTimelineModal/DeleteTimelineModal.tsx
@@ -4,7 +4,7 @@ import {
useGetTimelineQuery,
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import DeleteTimelineModal from "metabase/timelines/common/components/DeleteTimelineModal";
diff --git a/frontend/src/metabase/timelines/collections/containers/EditEventModal/EditEventModal.tsx b/frontend/src/metabase/timelines/collections/containers/EditEventModal/EditEventModal.tsx
index 11848f1515c..ad4853caf08 100644
--- a/frontend/src/metabase/timelines/collections/containers/EditEventModal/EditEventModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/EditEventModal/EditEventModal.tsx
@@ -5,7 +5,7 @@ import {
useUpdateTimelineEventMutation,
} from "metabase/api";
import { useSetArchive } from "metabase/archive/hooks";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import EditEventModal from "metabase/timelines/common/components/EditEventModal";
diff --git a/frontend/src/metabase/timelines/collections/containers/EditTimelineModal/EditTimelineModal.tsx b/frontend/src/metabase/timelines/collections/containers/EditTimelineModal/EditTimelineModal.tsx
index d9d498451a7..14fe796e9bf 100644
--- a/frontend/src/metabase/timelines/collections/containers/EditTimelineModal/EditTimelineModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/EditTimelineModal/EditTimelineModal.tsx
@@ -4,7 +4,7 @@ import {
useUpdateTimelineMutation,
} from "metabase/api";
import { useSetArchive } from "metabase/archive/hooks";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import EditTimelineModal from "metabase/timelines/common/components/EditTimelineModal";
diff --git a/frontend/src/metabase/timelines/collections/containers/MoveTimelineModal/MoveTimelineModal.tsx b/frontend/src/metabase/timelines/collections/containers/MoveTimelineModal/MoveTimelineModal.tsx
index a860280f41d..489a4d6cfbc 100644
--- a/frontend/src/metabase/timelines/collections/containers/MoveTimelineModal/MoveTimelineModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/MoveTimelineModal/MoveTimelineModal.tsx
@@ -6,9 +6,9 @@ import {
useGetCollectionQuery,
useGetTimelineQuery,
} from "metabase/api";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useSetCollection } from "metabase/common/hooks";
import { getDefaultTimelineName } from "metabase/common/utils/timelines";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import MoveTimelineModal from "metabase/timelines/common/components/MoveTimelineModal";
@@ -38,9 +38,9 @@ function MoveTimelineModalContainer({ params, ...props }: ModalComponentProps) {
? getDefaultTimelineName(sourceCollection)
: timeline.name;
// Fire-and-forget so the modal can close back to the parent path before
- // we push the new timeline detail URL — otherwise ModalRoute's onClose
- // would compute the parent off the post-navigation location and bounce
- // us off the timeline page.
+ // we push the new timeline detail URL, otherwise the modal route's
+ // onClose would resolve the parent off the post-navigation location and
+ // bounce us off the timeline page.
void (async () => {
await setCollection(
{ model: "timeline", id: timeline.id, name },
diff --git a/frontend/src/metabase/timelines/collections/containers/NewEventModal/NewEventModal.tsx b/frontend/src/metabase/timelines/collections/containers/NewEventModal/NewEventModal.tsx
index 3e6b38c740c..41379c5b18d 100644
--- a/frontend/src/metabase/timelines/collections/containers/NewEventModal/NewEventModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/NewEventModal/NewEventModal.tsx
@@ -3,7 +3,7 @@ import {
useCreateTimelineEventMutation,
useGetTimelineQuery,
} from "metabase/api";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import NewEventModal from "metabase/timelines/common/components/NewEventModal";
diff --git a/frontend/src/metabase/timelines/collections/containers/TimelineArchiveModal/TimelineArchiveModal.tsx b/frontend/src/metabase/timelines/collections/containers/TimelineArchiveModal/TimelineArchiveModal.tsx
index e30bf8ab76f..1745ceeb388 100644
--- a/frontend/src/metabase/timelines/collections/containers/TimelineArchiveModal/TimelineArchiveModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/TimelineArchiveModal/TimelineArchiveModal.tsx
@@ -1,6 +1,6 @@
import { skipToken, useGetTimelineQuery } from "metabase/api";
import { useSetArchive } from "metabase/archive/hooks";
-import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
import { useDispatch } from "metabase/redux";
import { push } from "metabase/router";
import * as Urls from "metabase/urls";
diff --git a/frontend/src/metabase/timelines/collections/routes.tsx b/frontend/src/metabase/timelines/collections/routes.tsx
index c358ba3ad6c..fb6174120be 100644
--- a/frontend/src/metabase/timelines/collections/routes.tsx
+++ b/frontend/src/metabase/timelines/collections/routes.tsx
@@ -1,6 +1,6 @@
import { Fragment } from "react";
-import { ModalRoute } from "metabase/hoc/ModalRoute";
+import { modalRoute } from "metabase/common/components/ModalRoute";
import { NO_ANIMATION_MODAL_PROPS } from "metabase/ui";
import DeleteEventModal from "./containers/DeleteEventModal";
@@ -17,101 +17,47 @@ import TimelineDetailsModal from "./containers/TimelineDetailsModal";
import TimelineIndexModal from "./containers/TimelineIndexModal";
import TimelineListArchiveModal from "./containers/TimelineListArchiveModal";
+const options = { modalProps: NO_ANIMATION_MODAL_PROPS };
+
const getRoutes = () => {
return (
<Fragment>
- <ModalRoute
- {...{
- path: "timelines",
- modal: TimelineIndexModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/new",
- modal: NewTimelineModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/archive",
- modal: TimelineListArchiveModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId",
- modal: TimelineDetailsModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/edit",
- modal: EditTimelineModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/move",
- modal: MoveTimelineModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- noWrap: true,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/archive",
- modal: TimelineArchiveModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/delete",
- modal: DeleteTimelineModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/new/events/new",
- modal: NewEventWithTimelineModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/events/new",
- modal: NewEventModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/events/:timelineEventId/edit",
- modal: EditEventModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/events/:timelineEventId/move",
- modal: MoveEventModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
- <ModalRoute
- {...{
- path: "timelines/:timelineId/events/:timelineEventId/delete",
- modal: DeleteEventModal,
- modalProps: NO_ANIMATION_MODAL_PROPS,
- }}
- />
+ {modalRoute("timelines", TimelineIndexModal, options)}
+ {modalRoute("timelines/new", NewTimelineModal, options)}
+ {modalRoute("timelines/archive", TimelineListArchiveModal, options)}
+ {modalRoute("timelines/:timelineId", TimelineDetailsModal, options)}
+ {modalRoute("timelines/:timelineId/edit", EditTimelineModal, options)}
+ {modalRoute("timelines/:timelineId/move", MoveTimelineModal, {
+ ...options,
+ noWrap: true,
+ })}
+ {modalRoute(
+ "timelines/:timelineId/archive",
+ TimelineArchiveModal,
+ options,
+ )}
+ {modalRoute("timelines/:timelineId/delete", DeleteTimelineModal, options)}
+ {modalRoute(
+ "timelines/new/events/new",
+ NewEventWithTimelineModal,
+ options,
+ )}
+ {modalRoute("timelines/:timelineId/events/new", NewEventModal, options)}
+ {modalRoute(
+ "timelines/:timelineId/events/:timelineEventId/edit",
+ EditEventModal,
+ options,
+ )}
+ {modalRoute(
+ "timelines/:timelineId/events/:timelineEventId/move",
+ MoveEventModal,
+ options,
+ )}
+ {modalRoute(
+ "timelines/:timelineId/events/:timelineEventId/delete",
+ DeleteEventModal,
+ options,
+ )}
</Fragment>
);
};