Skip to content

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

Delete RouterBridge and collapse the router facade onto v7 (#79130)

Romeo Van Snickaaada18ca840
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 622142df6d2..9bc3e92c044 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,7 +14,7 @@ import {
waitFor,
waitForLoaderToBeRemoved,
} from "__support__/ui";
-import { Route, useParams, useRouter } from "metabase/router";
+import { Route, useLocation, useParams } from "metabase/router";
import { ImpersonationModal } from "metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal";
import { advancedPermissionsSlice } from "metabase-enterprise/advanced_permissions/reducer";
import { getImpersonations } from "metabase-enterprise/advanced_permissions/selectors";
@@ -28,7 +28,7 @@ import {
/** Feeds the modal its route props the way `modalRoute` does in the app. */
function RoutedImpersonationModal({ onClose }: { onClose: () => void }) {
const params = useParams();
- const { location } = useRouter();
+ const location = useLocation();
return (
<ImpersonationModal params={params} location={location} onClose={onClose} />
);
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/cli-analytics/components/CliAnalyticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/cli-analytics/components/CliAnalyticsPage.tsx
index 5d5f9ec8446..6d545f8a9d1 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/cli-analytics/components/CliAnalyticsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/cli-analytics/components/CliAnalyticsPage.tsx
@@ -6,7 +6,7 @@ import { MetabotAdminLayout } from "metabase/admin/ai/MetabotAdminLayout";
import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
import { useSetting } from "metabase/common/hooks";
import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Flex, Loader, SimpleGrid, Stack, Tabs, Title } from "metabase/ui";
import {
@@ -32,7 +32,7 @@ import { CliEventsTable } from "./CliEventsTable";
* filters. Shows a single empty state (no tabs) when the filtered view has no activity.
*/
export function CliAnalyticsPage() {
- const { location } = useRouter();
+ const location = useLocation();
const [
{ date, user, group, tenant, tab, page, sort_column, sort_direction },
{ patchUrlState },
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx
index ecf24261209..ba2ab486e59 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx
@@ -6,7 +6,7 @@ import { MetabotAdminLayout } from "metabase/admin/ai/MetabotAdminLayout";
import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
import { useSetting } from "metabase/common/hooks";
import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { useRouter } from "metabase/router";
+import { useLocation, useNavigate } from "metabase/router";
import { Flex, Loader, SimpleGrid, Stack, Tabs, Title } from "metabase/ui";
import {
@@ -31,7 +31,8 @@ import { McpEventsTable } from "./McpEventsTable";
* filters. Shows a single empty state (no tabs) when the filtered view has no activity.
*/
export function McpAnalyticsPage() {
- const { location, router } = useRouter();
+ const location = useLocation();
+ const navigate = useNavigate();
const [
{ date, user, group, tenant, tab, page, sort_column, sort_direction },
{ patchUrlState },
@@ -88,9 +89,9 @@ export function McpAnalyticsPage() {
// is inaccessible — redirect away so it can't be reached by URL (the nav item also greys out).
useEffect(() => {
if (!mcpEnabled) {
- router.replace("/admin/metabot/usage-auditing");
+ navigate("/admin/metabot/usage-auditing", { replace: true });
}
- }, [mcpEnabled, router]);
+ }, [mcpEnabled, navigate]);
if (!mcpEnabled) {
return null;
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
index 53a6f8922ca..407b55e4814 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
@@ -9,7 +9,7 @@ import { useToast } from "metabase/common/hooks";
import { useUrlState } from "metabase/common/hooks/use-url-state";
import { serializeDateParameterValue } from "metabase/querying/parameters/utils/parsing";
import { useDispatch } from "metabase/redux";
-import { push, queryToSearch, useRouter } from "metabase/router";
+import { push, queryToSearch, useLocation } from "metabase/router";
import { Button, Flex, SimpleGrid, Tabs, Text, Title } from "metabase/ui";
import { hasPremiumFeature } from "metabase-enterprise/settings";
@@ -135,7 +135,7 @@ const labelUnknownIpAddress = (value: unknown) =>
value == null ? t`Unknown` : value;
export function ConversationStatsPage() {
- const { location } = useRouter();
+ const location = useLocation();
const dispatch = useDispatch();
const [{ date, user, group, tenant, metric }, { patchUrlState }] =
useUrlState(location, statsUrlStateConfig);
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.tsx
index 15b4bbf682d..a0f586e8c26 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.tsx
@@ -4,7 +4,7 @@ import { t } from "ttag";
import { MetabotAdminLayout } from "metabase/admin/ai/MetabotAdminLayout";
import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Flex, Title } from "metabase/ui";
import { useListMetabotAnalyticsConversationsQuery } from "../../api";
@@ -14,7 +14,7 @@ import { ConversationsTable } from "./ConversationsTable";
import { PAGE_SIZE, urlStateConfig } from "./utils";
export function ConversationsPage() {
- const { location } = useRouter();
+ const location = useLocation();
const [
{ page, sort_column, sort_direction, date, user, group, tenant },
{ patchUrlState },
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx
index 64c6329b263..0dbf794c20e 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef } from "react";
import { useUserKeyValue } from "metabase/common/hooks/use-user-key-value";
import { useDispatch } from "metabase/redux";
-import { replace, useRouter } from "metabase/router";
+import { replace, useLocation } from "metabase/router";
import type * as Urls from "metabase/urls";
import { DependencyDiagnostics } from "metabase-enterprise/monitor/dependency-diagnostics/components";
import type {
@@ -23,7 +23,7 @@ type DependencyDiagnosticsPageProps = {
};
function DependencyDiagnosticsPage({ mode }: DependencyDiagnosticsPageProps) {
- const { location } = useRouter();
+ const location = useLocation();
const isInitializingRef = useRef(false);
const dispatch = useDispatch();
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/tools/ErrorOverview/ErrorOverview.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/tools/ErrorOverview/ErrorOverview.tsx
index beb46702255..02d613c3493 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/tools/ErrorOverview/ErrorOverview.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/tools/ErrorOverview/ErrorOverview.tsx
@@ -16,7 +16,7 @@ import { useAbortableQuery } from "metabase/common/hooks/use-abortable-query";
import { useUrlState } from "metabase/common/hooks/use-url-state";
import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Center, Flex } from "metabase/ui";
import type { CardId } from "metabase-types/api";
@@ -36,7 +36,7 @@ import {
} from "./utils";
export const ErrorOverview = () => {
- const { location } = useRouter();
+ const location = useLocation();
const [{ page }, { patchUrlState }] = useUrlState(location, urlStateConfig);
const [filters, setFilters] =
useState<ErroringQuestionsFilters>(DEFAULT_FILTERS);
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataContainer.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataContainer.tsx
index 16661dfea8b..38d08b26efa 100644
--- a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataContainer.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataContainer.tsx
@@ -10,7 +10,7 @@ import {
import { GenericError } from "metabase/common/components/ErrorPages";
import { useCloseNavbarOnMount } from "metabase/common/hooks/use-close-navbar-on-mount";
import { useSelector } from "metabase/redux";
-import { useParams, useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { getUserIsAdmin } from "metabase/selectors/user";
import { Box, Flex, Stack, Text } from "metabase/ui";
import { extractRemappedColumns } from "metabase/visualizations";
@@ -45,7 +45,7 @@ type EditTableDataContainerParams = {
};
export const EditTableDataContainer = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { dbId: dbIdParam, tableId: tableIdParam } =
useParams<EditTableDataContainerParams>();
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/TransformInspectPage.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/TransformInspectPage.tsx
index 5ac0790df23..b9db5a13c0e 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/TransformInspectPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/TransformInspectPage.tsx
@@ -3,7 +3,7 @@ import { t } from "ttag";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { PageContainer } from "metabase/common/data-studio/components/PageContainer";
-import { useParams, useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { TransformDisconnectedDatabaseBanner } from "metabase/transforms/components/TransformDisconnectedDatabaseBanner";
import { TransformHeader } from "metabase/transforms/components/TransformHeader";
import { useTransformPermissions } from "metabase/transforms/hooks/use-transform-permissions";
@@ -17,7 +17,7 @@ import { InspectorContent } from "./components/InspectorContent";
import type { RouteParams } from "./types";
export const TransformInspectPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const params = useParams<RouteParams>();
const transformId = Urls.extractEntityId(params.transformId);
const {
diff --git a/frontend/src/metabase/AppComponent.tsx b/frontend/src/metabase/AppComponent.tsx
index 5476bc5301e..2ebac9fe037 100644
--- a/frontend/src/metabase/AppComponent.tsx
+++ b/frontend/src/metabase/AppComponent.tsx
@@ -27,7 +27,7 @@ import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
import type { AppErrorDescriptor } from "metabase/redux/store";
-import { Outlet, useRouter } from "metabase/router";
+import { Outlet, useLocation } from "metabase/router";
import { getErrorPage } from "metabase/selectors/app";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { StatusListing } from "metabase/status/components/StatusListing";
@@ -65,7 +65,7 @@ export function App() {
// These selectors derive the active app section from the URL, so they take
// the router props rather than reading them from the store.
- const { location } = useRouter();
+ const location = useLocation();
const routerProps = { location };
const errorPage = useSelector(getErrorPage);
const isAdminApp = useSelector((state) => getIsAdminApp(state, routerProps));
diff --git a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
index 8cf2b17bf9d..f644064e631 100644
--- a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
@@ -15,7 +15,6 @@ import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
import { useToast } from "metabase/common/hooks/use-toast";
import { connect, useSelector } from "metabase/redux";
import type { State } from "metabase/redux/store";
-import type { Route } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import { Modal } from "metabase/ui";
import type Question from "metabase-lib/v1/Question";
@@ -40,7 +39,11 @@ interface OwnProps {
databaseId?: DatabaseId;
action?: WritebackAction;
- route?: Route;
+ /**
+ * Whether the creator is mounted as its own route. A routed creator guards
+ * leaving with `LeaveRouteConfirmModal`; an inline one only has `beforeunload`.
+ */
+ isRouted?: boolean;
onSubmit?: (action: WritebackAction) => void;
onClose?: () => void;
@@ -62,7 +65,7 @@ const mapStateToProps = (state: State) => ({
metadata: getMetadata(state),
});
-function ActionCreator({ model, onSubmit, onClose, route }: Props) {
+function ActionCreator({ model, onSubmit, onClose, isRouted }: Props) {
const [createAction] = useCreateActionMutation();
const [updateAction] = useUpdateActionMutation();
const [sendToast] = useToast();
@@ -90,7 +93,7 @@ function ActionCreator({ model, onSubmit, onClose, route }: Props) {
const showUnsavedChangesWarning =
isEditable && isDirty && !isCallbackScheduled;
- useBeforeUnload(!route && showUnsavedChangesWarning);
+ useBeforeUnload(!isRouted && showUnsavedChangesWarning);
const handleCreate = async (values: CreateActionFormValues) => {
if (action.type !== "query") {
@@ -186,11 +189,8 @@ function ActionCreator({ model, onSubmit, onClose, route }: Props) {
/>
</Modal>
- {route && (
- <LeaveRouteConfirmModal
- isEnabled={showUnsavedChangesWarning}
- route={route}
- />
+ {isRouted && (
+ <LeaveRouteConfirmModal isEnabled={showUnsavedChangesWarning} />
)}
</>
);
diff --git a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
index 8be8da56b75..020a8842fea 100644
--- a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
@@ -6,7 +6,7 @@ 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";
-import { type LocationDescriptor, type Route, replace } from "metabase/router";
+import { type LocationDescriptor, replace } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import * as Urls from "metabase/urls";
import type Question from "metabase-lib/v1/Question";
@@ -28,19 +28,12 @@ interface EntityLoaderProps {
loading?: boolean;
}
-interface RouteProps {
- route?: Route;
-}
-
interface DispatchProps {
setErrorPage: (error: AppErrorDescriptor) => void;
onChangeLocation: (location: LocationDescriptor) => void;
}
-type ActionCreatorModalProps = OwnProps &
- EntityLoaderProps &
- RouteProps &
- DispatchProps;
+type ActionCreatorModalProps = OwnProps & EntityLoaderProps & DispatchProps;
const mapDispatchToProps = {
setErrorPage,
@@ -51,7 +44,6 @@ function ActionCreatorModal({
model,
params,
loading: isModelLoading,
- route,
onClose,
setErrorPage,
onChangeLocation,
@@ -91,7 +83,7 @@ function ActionCreatorModal({
actionId={actionId}
modelId={modelId}
databaseId={databaseId}
- route={route}
+ isRouted
onClose={onClose}
/>
);
diff --git a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx
index 0fa56ed2114..0763ae4e46f 100644
--- a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx
@@ -13,7 +13,7 @@ import {
waitFor,
waitForLoaderToBeRemoved,
} from "__support__/ui";
-import { Route, useParams, useRoute, useRouter } from "metabase/router";
+import { Route, useLocation, useParams } from "metabase/router";
import { checkNotNull } from "metabase/utils/types";
import type { Card, WritebackAction } from "metabase-types/api";
import {
@@ -27,15 +27,9 @@ import ActionCreatorModal from "./ActionCreatorModal";
/** Feeds the modal its route props the way `modalRoute` does in the app. */
function RoutedActionCreatorModal({ onClose }: { onClose: () => void }) {
const params = useParams<{ slug: string; actionId: string }>();
- const { location } = useRouter();
- const route = useRoute() ?? undefined;
+ const location = useLocation();
return (
- <ActionCreatorModal
- params={params}
- location={location}
- route={route}
- onClose={onClose}
- />
+ <ActionCreatorModal params={params} location={location} onClose={onClose} />
);
}
diff --git a/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsx b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsx
index cecd892eb87..f347abd4fc0 100644
--- a/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsx
+++ b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsx
@@ -15,7 +15,7 @@ import {
useUrlState,
} from "metabase/common/hooks/use-url-state";
import CS from "metabase/css/core/index.css";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import {
Badge,
type BadgeColor,
@@ -78,7 +78,7 @@ function parseEventType(param: QueryParam): EventTypeFilter {
}
export const OAuthAuthorizationsPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const [{ page, eventType }, { patchUrlState }] = useUrlState(
location,
urlStateConfig,
diff --git a/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx b/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx
index affe78cf40b..bf0e39861ab 100644
--- a/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx
+++ b/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef } from "react";
import ErrorBoundary from "metabase/ErrorBoundary";
import { NotFound } from "metabase/common/components/ErrorPages";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Box } from "metabase/ui";
import S from "./AdminSettingsLayout.module.css";
@@ -48,7 +48,7 @@ export const AdminSettingsLayout = ({
};
const useScrollToTop = (contentRef: React.RefObject<HTMLDivElement | null>) => {
- const { location } = useRouter();
+ const location = useLocation();
useEffect(() => {
contentRef.current?.scrollTo(0, 0);
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx b/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx
index a892e0c94c1..b4b88a028d3 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx
@@ -18,7 +18,7 @@ import type {
} from "metabase/databases/types";
import { useDispatch } from "metabase/redux";
import type { Dispatch } from "metabase/redux/store";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Text } from "metabase/ui";
import type {
DatabaseData,
@@ -57,7 +57,7 @@ export const DatabaseEditConnectionForm = ({
formLocation: Extract<FormLocation, "admin" | "full-page">;
}) => {
const dispatch = useDispatch();
- const { location } = useRouter();
+ const location = useLocation();
const [isDirty, setIsDirty] = useState(false);
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx
index dd0bb615b71..9b3ef3a5c07 100644
--- a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx
+++ b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx
@@ -22,7 +22,7 @@ import {
PLUGIN_WRITABLE_CONNECTION,
} from "metabase/plugins";
import { connect, useSelector } from "metabase/redux";
-import { Outlet, useRouter } from "metabase/router";
+import { Outlet, useParams } from "metabase/router";
import { getUserIsAdmin } from "metabase/selectors/user";
import { Box, Divider, Flex } from "metabase/ui";
import type { DatabaseId, Database as DatabaseType } from "metabase-types/api";
@@ -49,11 +49,11 @@ function DatabaseEditAppInner({
updateDatabase,
deleteDatabase,
}: DatabaseEditAppProps) {
- const { params } = useRouter();
+ const params = useParams();
const isAdmin = useSelector(getUserIsAdmin);
const isModelPersistenceEnabled = useSetting("persisted-models-enabled");
- const databaseId = parseInt(params.databaseId, 10);
+ const databaseId = parseInt(params.databaseId ?? "", 10);
const fromEmbeddingSetupGuide = new URLSearchParams(
window.location.search,
).has(RETURN_TO_SETUP_GUIDE_PARAM);
diff --git a/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.tsx b/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.tsx
index eb9e44e7d4f..dd5a197c244 100644
--- a/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.tsx
+++ b/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.tsx
@@ -13,7 +13,7 @@ import AdminS from "metabase/css/admin.module.css";
import CS from "metabase/css/core/index.css";
import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { getShallowTables } from "metabase/selectors/metadata";
import { getUserIsAdmin } from "metabase/selectors/user";
import { Button } from "metabase/ui";
@@ -95,7 +95,7 @@ function SegmentListAppInner({ segments, tableSelector }: Props) {
const FilteredSegmentList = FilteredToUrlTable(SegmentListAppInner);
export function SegmentListApp() {
- const { location } = useRouter();
+ const location = useLocation();
const { data: segments, isLoading, error } = useListSegmentsQuery();
if (isLoading || error || !segments) {
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
index 54bcc94ce5a..51655a818c3 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
@@ -1,7 +1,7 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import { useDispatch } from "metabase/redux";
-import { push, useRouter } from "metabase/router";
+import { push, useNavigate, useRouteLeaveHook } from "metabase/router";
type Props = {
shouldConfirm: boolean;
@@ -10,35 +10,30 @@ type Props = {
export const useConfirmOnRouteLeave = ({ shouldConfirm, confirm }: Props) => {
const dispatch = useDispatch();
- const { router, routes } = useRouter();
+ const navigate = useNavigate();
/**
* to prevent endless loop
*/
const confirmedRef = useRef<boolean>(false);
- const currentRoute = routes.at(-1);
- 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(() => {
- confirmedRef.current = true;
- if (nextLocation) {
- dispatch(push(nextLocation));
- }
- });
- return false;
- }),
- [router, currentRoute, shouldConfirm, confirm, dispatch],
- );
+ useRouteLeaveHook((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)
+ */
+ navigate(1);
+ confirm(() => {
+ confirmedRef.current = true;
+ if (nextLocation) {
+ dispatch(push(nextLocation));
+ }
+ });
+ return false;
+ });
};
diff --git a/frontend/src/metabase/app/nav/AppBar.tsx b/frontend/src/metabase/app/nav/AppBar.tsx
index 03bec24b67c..a458e17dc23 100644
--- a/frontend/src/metabase/app/nav/AppBar.tsx
+++ b/frontend/src/metabase/app/nav/AppBar.tsx
@@ -27,7 +27,7 @@ import {
} from "metabase/query_builder/selectors";
import { useDispatch, useSelector } from "metabase/redux";
import { closeNavbar, toggleNavbar } from "metabase/redux/app";
-import { push, useRouter } from "metabase/router";
+import { push, useLocation, useParams } from "metabase/router";
import { getDetailViewState, getIsNavbarOpen } from "metabase/selectors/app";
import { getIsEmbeddingIframe } from "metabase/selectors/embed";
import { getUser } from "metabase/selectors/user";
@@ -58,7 +58,8 @@ export function AppBarContainer() {
// These selectors derive app-bar visibility from the URL, so they take the
// router props rather than reading them from the store.
- const { location, params } = useRouter();
+ const location = useLocation();
+ const params = useParams();
const routerProps = { location };
const collectionId =
useInitialCollectionId({ location, params }) ?? undefined;
diff --git a/frontend/src/metabase/app/nav/Navbar.tsx b/frontend/src/metabase/app/nav/Navbar.tsx
index 930f1e3f134..c2068cb6407 100644
--- a/frontend/src/metabase/app/nav/Navbar.tsx
+++ b/frontend/src/metabase/app/nav/Navbar.tsx
@@ -6,7 +6,7 @@ import { AdminNavbar } from "metabase/nav/components/AdminNavbar";
import { MainNavbar } from "metabase/nav/containers/MainNavbar";
import { connect } from "metabase/redux";
import type { AdminPath, State, StoreDashboard } from "metabase/redux/store";
-import { useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { getAdminPaths } from "metabase/selectors/admin";
import { getIsNavbarOpen } from "metabase/selectors/app";
import { getUser } from "metabase/selectors/user";
@@ -30,7 +30,8 @@ const mapStateToProps = (state: State) => ({
});
function NavbarInner({ isOpen, user, adminPaths, dashboard }: NavbarProps) {
- const { location, params } = useRouter();
+ const location = useLocation();
+ const params = useParams();
useListDatabasesQuery();
const isAdminApp = useMemo(
() => location.pathname.startsWith("/admin/"),
diff --git a/frontend/src/metabase/common/collections/components/CreateCollectionForm/CreateCollectionForm.tsx b/frontend/src/metabase/common/collections/components/CreateCollectionForm/CreateCollectionForm.tsx
index 0385e079742..3d94044839d 100644
--- a/frontend/src/metabase/common/collections/components/CreateCollectionForm/CreateCollectionForm.tsx
+++ b/frontend/src/metabase/common/collections/components/CreateCollectionForm/CreateCollectionForm.tsx
@@ -20,7 +20,7 @@ import {
FormTextarea,
} from "metabase/forms";
import { PLUGIN_TENANTS } from "metabase/plugins";
-import { useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { Button, Flex } from "metabase/ui";
import * as Errors from "metabase/utils/errors";
import type { Collection, CollectionNamespace } from "metabase-types/api";
@@ -70,7 +70,8 @@ function CreateCollectionForm({
namespaces,
showAuthorityLevelPicker = true,
}: Props) {
- const { location, params } = useRouter();
+ const location = useLocation();
+ const params = useParams();
const defaultInitialCollectionId = useInitialCollectionId({
collectionId,
location,
diff --git a/frontend/src/metabase/common/components/LeaveConfirmModal/LeaveRouteConfirmModal.tsx b/frontend/src/metabase/common/components/LeaveConfirmModal/LeaveRouteConfirmModal.tsx
index 2cd502942d5..f65463585d3 100644
--- a/frontend/src/metabase/common/components/LeaveConfirmModal/LeaveRouteConfirmModal.tsx
+++ b/frontend/src/metabase/common/components/LeaveConfirmModal/LeaveRouteConfirmModal.tsx
@@ -2,24 +2,13 @@ import { useEffect } from "react";
import { usePrevious } from "react-use";
import { useConfirmRouteLeaveModal } from "metabase/common/hooks/use-confirm-route-leave-modal";
-import {
- type Location,
- type Route,
- useRoute,
- useRouter,
-} from "metabase/router";
+import type { Location } from "metabase/router";
import { LeaveConfirmModal } from "./LeaveConfirmModal";
interface LeaveRouteConfirmModalProps {
isEnabled: boolean;
isLocationAllowed?: (location?: Location) => boolean;
- /**
- * The route to guard. Omit it on an `element`-based page: the page's own
- * matched route comes from `useRoute()`, so the page does not need the
- * v3-injected `route`. Still accepted for callers that pass it explicitly.
- */
- route?: Route;
onConfirm?: () => void;
onOpenChange?: (opened: boolean) => void;
}
@@ -27,20 +16,12 @@ interface LeaveRouteConfirmModalProps {
export const LeaveRouteConfirmModal = ({
isEnabled,
isLocationAllowed,
- route,
onConfirm,
onOpenChange,
}: LeaveRouteConfirmModalProps) => {
- const { router, routes } = useRouter();
- const routeFromContext = useRoute();
- // The matched-route chain's leaf is this page's own route, which
- // `setRouteLeaveHook` (a no-op on v7) receives.
- const leafRoute = routes[routes.length - 1];
const { opened, close, confirm } = useConfirmRouteLeaveModal({
isEnabled,
isLocationAllowed,
- route: route ?? routeFromContext ?? leafRoute,
- router,
});
const previousIsOpened = usePrevious(opened);
diff --git a/frontend/src/metabase/common/components/ModalRoute.tsx b/frontend/src/metabase/common/components/ModalRoute.tsx
index 9bb3f5f9b5a..0d8ef9d545a 100644
--- a/frontend/src/metabase/common/components/ModalRoute.tsx
+++ b/frontend/src/metabase/common/components/ModalRoute.tsx
@@ -1,13 +1,7 @@
import { useCallback } from "react";
import type { Location } from "metabase/router";
-import {
- Route,
- useNavigate,
- useParams,
- useRoute,
- useRouter,
-} from "metabase/router";
+import { Route, useLocation, useNavigate, useParams } from "metabase/router";
import { Modal, type ModalProps } from "metabase/ui";
type RouteParams = Record<string, string | undefined>;
@@ -20,12 +14,6 @@ type RouteParams = Record<string, string | undefined>;
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;
};
@@ -52,8 +40,7 @@ export function modalRoute(
) {
function ModalRouteComponent() {
const params = useParams();
- const { location } = useRouter();
- const route = useRoute() ?? undefined;
+ const location = useLocation();
const navigate = useNavigate();
const onClose = useCallback(
() => navigate("..", { relative: "route" }),
@@ -61,12 +48,7 @@ export function modalRoute(
);
const modal = (
- <ComposedModal
- params={params}
- location={location}
- route={route}
- onClose={onClose}
- />
+ <ComposedModal params={params} location={location} onClose={onClose} />
);
if (noWrap) {
diff --git a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
index 7553e10a5b8..1b6b13a58d5 100644
--- a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
+++ b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
@@ -4,23 +4,17 @@ import { match } from "ts-pattern";
import { useDispatch } from "metabase/redux";
import {
type Action,
- type InjectedRouter,
type Location,
- type PlainRoute,
- type Route,
goBack,
push,
replace,
+ useRouteLeaveHook,
+ useRoutePathname,
} from "metabase/router";
import { useBeforeUnload } from "./use-before-unload";
interface UseConfirmLeaveModalInput {
- router: InjectedRouter;
- // The matched route handed to `setRouteLeaveHook` (typed `any`). Accepts the
- // route object in either representation the app threads it as: the config
- // object from `useRouter().routes` (`PlainRoute`) or the `Route` prop type.
- route: Route | PlainRoute;
isEnabled: boolean;
isLocationAllowed?: (location: Location | undefined) => boolean;
}
@@ -46,12 +40,11 @@ export const IS_LOCATION_ALLOWED = (location?: Location) => !location;
* whenever they try to leave a route
*/
export const useConfirmRouteLeaveModal = ({
- router,
- route,
isEnabled,
isLocationAllowed = IS_LOCATION_ALLOWED,
}: UseConfirmLeaveModalInput): UseConfirmLeaveModalResult => {
const dispatch = useDispatch();
+ const routePathname = useRoutePathname();
const [nextNavigation, setNextNavigation] = useState<{
location: Location;
navigationType: Action;
@@ -65,24 +58,15 @@ export const useConfirmRouteLeaveModal = ({
useBeforeUnload(isEnabled);
- useEffect(() => {
- const removeLeaveHook = router.setRouteLeaveHook(
- route,
- (location, navigationType) => {
- if (isEnabled && !isConfirmed && !isLocationAllowed?.(location)) {
- setOpened(true);
- setNextNavigation(
- location && navigationType
- ? { location, navigationType }
- : undefined,
- );
- return false;
- }
- },
- );
-
- return removeLeaveHook;
- }, [isLocationAllowed, router, route, isEnabled, isConfirmed]);
+ useRouteLeaveHook((location, navigationType) => {
+ if (isEnabled && !isConfirmed && !isLocationAllowed?.(location)) {
+ setOpened(true);
+ setNextNavigation(
+ location && navigationType ? { location, navigationType } : undefined,
+ );
+ return false;
+ }
+ });
useEffect(
function confirmNavigation() {
@@ -118,7 +102,7 @@ export const useConfirmRouteLeaveModal = ({
setIsConfirmed(false);
setOpened(false);
},
- [route],
+ [routePathname],
);
return {
diff --git a/frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx b/frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx
index 54a5ad901df..f5776ea1cd0 100644
--- a/frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx
@@ -7,7 +7,7 @@ import { useInitialCollectionId } from "metabase/common/collections/hooks";
import type { CopyDashboardFormProperties } from "metabase/common/components/CopyDashboardForm";
import { CopyModal } from "metabase/common/components/CopyModal";
import { useDispatch, useSelector } from "metabase/redux";
-import { replace, useRouter } from "metabase/router";
+import { replace, useLocation, useParams } from "metabase/router";
import * as Urls from "metabase/urls";
import type { Dashboard } from "metabase-types/api";
@@ -31,7 +31,8 @@ const getTitle = (
};
const DashboardCopyModal = ({ onClose }: DashboardCopyModalProps) => {
- const { location, params } = useRouter();
+ const location = useLocation();
+ const params = useParams();
const dispatch = useDispatch();
const [copyDashboard] = useCopyDashboardMutation();
const dashboard = useSelector(getDashboardComplete);
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/CopyAnalyticsDashboardButton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/CopyAnalyticsDashboardButton.tsx
index 592329d0d3d..7c5c7c379cf 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/CopyAnalyticsDashboardButton.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/CopyAnalyticsDashboardButton.tsx
@@ -1,11 +1,11 @@
import { t } from "ttag";
import { Link } from "metabase/common/components/Link";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Button, Icon } from "metabase/ui";
export const CopyAnalyticsDashboardButton = () => {
- const { location } = useRouter();
+ const location = useLocation();
return (
<Button
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
index 649c4b14eff..1d5dd2c9649 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
@@ -7,7 +7,7 @@ import { useDashboardContext } from "metabase/dashboard/context/context";
import { useRefreshDashboard } from "metabase/dashboard/hooks";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
import { PLUGIN_CACHING, PLUGIN_MODERATION } from "metabase/plugins";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Icon, Menu } from "metabase/ui";
import { parseSearchQuery } from "metabase/utils/browser";
@@ -39,7 +39,7 @@ const DashboardActionMenuInner = ({
canEdit,
openSettingsSidebar,
}: DashboardActionMenuProps) => {
- const { location } = useRouter();
+ const location = useLocation();
const { dashboard, isFullscreen, onFullscreenChange, onChangeLocation } =
useDashboardContext();
const [opened, setOpened] = useState(false);
diff --git a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx
index dcb2736e616..2ffb1f41a03 100644
--- a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx
@@ -5,7 +5,7 @@ import { updateDashboardAndCards } from "metabase/dashboard/actions/save";
import { getIsDirty, getIsEditing } from "metabase/dashboard/selectors";
import { useDispatch, useSelector } from "metabase/redux";
import { dismissAllUndo } from "metabase/redux/undo";
-import { useLocation, useRoute, useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Box, Button, Flex, Modal, Text } from "metabase/ui";
import { isNavigatingToCreateADashboardQuestion } from "./utils";
@@ -13,18 +13,12 @@ import { isNavigatingToCreateADashboardQuestion } from "./utils";
export const DashboardLeaveConfirmationModal = () => {
const isEditing = useSelector(getIsEditing);
const isDirty = useSelector(getIsDirty);
- const { router, routes } = useRouter();
- const route = useRoute();
const location = useLocation();
const dispatch = useDispatch();
const { opened, close, confirm, nextLocation } = useConfirmRouteLeaveModal({
isEnabled: isEditing && isDirty,
- // `routes` is the matched-route chain; its last entry is this page's own
- // route.
- route: route ?? routes[routes.length - 1],
- router,
});
const content = isNavigatingToCreateADashboardQuestion(nextLocation)
diff --git a/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx
index e4f0602b042..5bf0bb75670 100644
--- a/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx
@@ -10,7 +10,7 @@ import { getSelectedTabId } from "metabase/dashboard/selectors";
import { createTabSlug } from "metabase/dashboard/utils";
import { useSelector } from "metabase/redux";
import type { DashboardState } from "metabase/redux/store";
-import { type InjectedRouter, Route, useRouter } from "metabase/router";
+import { Route, useLocation } from "metabase/router";
import type { DashboardTab } from "metabase-types/api";
import { createMockCard } from "metabase-types/api/mocks";
import { createMockDashboardCard } from "metabase-types/api/mocks/dashboard";
@@ -48,9 +48,9 @@ function setup({
};
const RoutedDashboardComponent = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { selectedTabId } = useDashboardTabs();
- useDashboardUrlQuery(createMockRouter(), location);
+ useDashboardUrlQuery(location);
return (
<>
<DashboardTabs />
@@ -173,22 +173,6 @@ async function findSlug({ tabId, name }: { tabId: number; name: string }) {
return screen.findByText(new RegExp(createTabSlug({ id: tabId, name })));
}
-function createMockRouter(): InjectedRouter {
- return {
- push: jest.fn(),
- replace: jest.fn(),
- go: jest.fn(),
- goBack: jest.fn(),
- goForward: jest.fn(),
- setRouteLeaveHook: jest.fn(),
- createPath: jest.fn(),
- createHref: jest.fn(),
- isActive: jest.fn(),
- // @ts-expect-error missing type definition
- listen: jest.fn().mockReturnValue(jest.fn()),
- };
-}
-
describe("DashboardTabs", () => {
beforeEach(() => {
resetTempTabId();
diff --git a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx
index 6ac5b160770..db69d8aad9d 100644
--- a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx
+++ b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx
@@ -7,7 +7,7 @@ import { ArchiveModal } from "metabase/common/components/ArchiveModal";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { setArchivedDashboard } from "metabase/dashboard/actions";
import { useDispatch } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useParams } from "metabase/router";
import * as Urls from "metabase/urls";
import type { Dashboard } from "metabase-types/api";
@@ -57,7 +57,7 @@ const ArchiveDashboardModal = ({
};
export const ArchiveDashboardModalConnectedInner = (props: OwnProps) => {
- const { params } = useRouter();
+ const params = useParams();
const id = Urls.extractCollectionId(params?.slug);
const { currentData: dashboard, error } = useGetDashboardQuery(
id != null ? { id } : skipToken,
diff --git a/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx b/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx
index 2e6204aa964..7b2eb0f7a57 100644
--- a/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx
@@ -18,7 +18,7 @@ import { useDashboardUrlQuery } from "metabase/dashboard/hooks";
import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
-import { useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { Box, Button, Flex, Group, Icon } from "metabase/ui";
import * as Urls from "metabase/urls";
import { DASHBOARD_HEADER_PARAMETERS_PDF_EXPORT_NODE_ID } from "metabase/visualizations/lib/save-dashboard-pdf";
@@ -218,12 +218,13 @@ const AutomaticDashboardAppInner = () => {
};
export const AutomaticDashboardApp = () => {
- const { router, location, params } = useRouter();
- useDashboardUrlQuery(router, location);
+ const location = useLocation();
+ const params = useParams();
+ useDashboardUrlQuery(location);
const dispatch = useDispatch();
- const dashboardId = `/auto/dashboard/${params.splat}${location.hash.replace(/^#?/, "?")}`;
+ const dashboardId = `/auto/dashboard/${params["*"]}${location.hash.replace(/^#?/, "?")}`;
return (
<DashboardContextProvider
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
index ce3d02848fe..8f321082143 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
@@ -32,7 +32,7 @@ import {
import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
import type { Location } from "metabase/router";
-import { Outlet, replace, useRouter } from "metabase/router";
+import { Outlet, replace, useLocation, useParams } from "metabase/router";
import * as Urls from "metabase/urls";
import {
parseHashOptions,
@@ -78,7 +78,8 @@ export const DASHBOARD_APP_ACTIONS = ({ isEditing }: { isEditing: boolean }) =>
isEditing ? DASHBOARD_EDITING_ACTIONS : DASHBOARD_VIEW_ACTIONS;
export const DashboardApp = () => {
- const { location, params, router } = useRouter();
+ const location = useLocation();
+ const params = useParams();
const dispatch = useDispatch();
const [error, setError] = useState<string>();
@@ -91,7 +92,7 @@ export const DashboardApp = () => {
const dashboardId = Urls.extractEntityId(params.slug) as DashboardId;
useRegisterDashboardMetabotContext();
- useDashboardUrlQuery(router, location);
+ useDashboardUrlQuery(location);
const extractHashOption = async (
key: string,
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/use-dashboard-location-sync.ts b/frontend/src/metabase/dashboard/containers/DashboardApp/use-dashboard-location-sync.ts
index 21befdf9c55..f54ea051ff6 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/use-dashboard-location-sync.ts
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/use-dashboard-location-sync.ts
@@ -1,11 +1,13 @@
import { useDashboardContext } from "metabase/dashboard/context";
import { useLocationSync } from "metabase/dashboard/hooks";
import type { RefreshPeriod } from "metabase/dashboard/types";
-import type { WithRouterProps } from "metabase/router";
+import type { Location } from "metabase/router";
export const useDashboardLocationSync = ({
location,
-}: Pick<WithRouterProps, "location">) => {
+}: {
+ location: Location;
+}) => {
const {
refreshPeriod,
onRefreshPeriodChange,
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
index eba85734ee6..1d228a2f0ac 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
@@ -7,11 +7,11 @@ import { isEmbedPreview } from "metabase/embedding/config";
import { useDispatch, useSelector } from "metabase/redux";
import { selectTab } from "metabase/redux/dashboard";
import {
- type InjectedRouter,
type Location,
push,
queryToSearch,
replace,
+ subscribeLocation,
} from "metabase/router";
import * as Urls from "metabase/urls";
import { parseSearchQuery } from "metabase/utils/browser";
@@ -25,10 +25,7 @@ import {
} from "../selectors";
import { createTabSlug, parseTabSlug } from "../utils";
-export function useDashboardUrlQuery(
- router: InjectedRouter,
- location: Location,
-) {
+export function useDashboardUrlQuery(location: Location) {
const dashboardId = useSelector((state) => getDashboard(state)?.id);
const tabs = useSelector(getTabs);
const selectedTab = useSelector(getSelectedTab);
@@ -108,8 +105,7 @@ export function useDashboardUrlQuery(
]);
useEffect(() => {
- // @ts-expect-error missing type declaration
- const unsubscribe = router.listen((nextLocation) => {
+ return subscribeLocation((nextLocation) => {
const isSamePath = nextLocation.pathname === location.pathname;
if (!isSamePath) {
return;
@@ -122,9 +118,7 @@ export function useDashboardUrlQuery(
dispatch(selectTab({ tabId: nextTabId }));
}
});
-
- return () => unsubscribe();
- }, [router, location, selectedTab, dispatch]);
+ }, [location, selectedTab, dispatch]);
}
const QUERY_PARAMS_ALLOW_LIST = ["objectId", "returnToEmbeddingSetupGuide"];
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
index 39745b2822e..0908ae6a225 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
@@ -11,15 +11,15 @@ import {
} from "metabase/redux/store/mocks";
import type { Location } from "metabase/router";
import { push, replace } from "metabase/router";
+import { notifyLocationListeners } from "metabase/router/v7/navigator";
import type { ParameterValueOrArray } from "metabase-types/api";
import { createMockParameter } from "metabase-types/api/mocks";
import { useDashboardUrlQuery } from "./use-dashboard-url-query";
// Pins the dashboard URL-query sync seam: how dashboard parameter and tab state
-// gets pushed or replaced into the location query string, plus the router.listen
-// tab subscription. The react-router migration re-plumbs both of these, and
-// router.listen has no direct v7 equivalent, so this locks current behavior.
+// gets pushed or replaced into the location query string, plus the location
+// subscription that selects a tab. The react-router migration re-plumbs both.
jest.mock("metabase/router", () => ({
...jest.requireActual("metabase/router"),
@@ -56,16 +56,8 @@ function setup({
pathname = `/dashboard/${DASHBOARD_ID}`,
search = "",
}: SetupOptions = {}) {
- const listeners: ((location: Location) => void)[] = [];
- const unsubscribe = jest.fn();
- const router = {
- listen: jest.fn((cb: (location: Location) => void) => {
- listeners.push(cb);
- return unsubscribe;
- }),
- };
-
- // Unjustified type cast. FIXME
+ // Cast because the test only drives the URL parts the hook reads; `key` is
+ // supplied by the router at runtime and nothing here depends on it.
const location = {
pathname,
search,
@@ -96,12 +88,11 @@ function setup({
});
const { store, unmount } = renderHookWithProviders(
- // Unjustified type cast. FIXME
- () => useDashboardUrlQuery(router as any, location),
+ () => useDashboardUrlQuery(location),
{ storeInitialState },
);
- return { store, unmount, router, listeners, unsubscribe, location };
+ return { store, unmount, location };
}
describe("useDashboardUrlQuery", () => {
@@ -176,17 +167,14 @@ describe("useDashboardUrlQuery", () => {
expect(replace).not.toHaveBeenCalled();
});
- describe("router.listen tab subscription", () => {
+ describe("location tab subscription", () => {
it("selects the tab when a same-pathname navigation changes the tab query id", () => {
- const { store, listeners, location } = setup();
+ const { store, location } = setup();
expect(store.getState().dashboard.selectedTabId).toBe(null);
act(() => {
- listeners[0]({
- ...location,
- search: "?tab=5-tab-5",
- });
+ notifyLocationListeners({ ...location, search: "?tab=5-tab-5" });
});
// selectTab is the only reducer that sets selectedTabId, so this pins that
@@ -195,10 +183,10 @@ describe("useDashboardUrlQuery", () => {
});
it("does nothing when the pathname changes", () => {
- const { store, listeners, location } = setup();
+ const { store, location } = setup();
act(() => {
- listeners[0]({
+ notifyLocationListeners({
...location,
pathname: "/dashboard/999",
search: "?tab=5-tab-5",
@@ -208,12 +196,16 @@ describe("useDashboardUrlQuery", () => {
expect(store.getState().dashboard.selectedTabId).toBe(null);
});
- it("unsubscribes on unmount", () => {
- const { unmount, unsubscribe } = setup();
+ it("stops listening on unmount", () => {
+ const { store, unmount, location } = setup();
- expect(unsubscribe).not.toHaveBeenCalled();
unmount();
- expect(unsubscribe).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ notifyLocationListeners({ ...location, search: "?tab=5-tab-5" });
+ });
+
+ expect(store.getState().dashboard.selectedTabId).toBe(null);
});
});
diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsx
index 17477767161..1bb26539b5f 100644
--- a/frontend/src/metabase/documents/components/DocumentPage.tsx
+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx
@@ -38,7 +38,7 @@ import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
-import { Outlet, push, replace, useParams, useRouter } from "metabase/router";
+import { Outlet, push, replace, useLocation, useParams } from "metabase/router";
import { Box } from "metabase/ui";
import { extractEntityId } from "metabase/urls";
import * as Urls from "metabase/urls";
@@ -113,7 +113,7 @@ const DocumentPrintContextProvider = ({
};
export const DocumentPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { entityId, childTargetId: paramsChildTargetId } = useParams<{
entityId: string;
childTargetId: string;
diff --git a/frontend/src/metabase/metrics-viewer/hooks/use-viewer-state.ts b/frontend/src/metabase/metrics-viewer/hooks/use-viewer-state.ts
index f9860f378b8..2a779afc2f1 100644
--- a/frontend/src/metabase/metrics-viewer/hooks/use-viewer-state.ts
+++ b/frontend/src/metabase/metrics-viewer/hooks/use-viewer-state.ts
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { measureApi, metricApi, segmentApi } from "metabase/api";
import { useDispatch, useStore } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import { getObjectEntries } from "metabase/utils/objects";
import type { MetricDefinition, ProjectionClause } from "metabase-lib/metric";
@@ -87,7 +87,7 @@ async function loadMeasureDefinition(
}
export function useViewerState(): UseViewerStateResult {
- const { location } = useRouter();
+ const location = useLocation();
const dispatch = useDispatch();
const store = useStore();
diff --git a/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx b/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
index de23074d94d..17199ae60b1 100644
--- a/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
+++ b/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
@@ -16,7 +16,7 @@ import { MetricQueryEditor } from "metabase/metrics/components/MetricQueryEditor
import { NAME_MAX_LENGTH } from "metabase/metrics/constants";
import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";
import { useDispatch, useSelector } from "metabase/redux";
-import { goBack, push, useRouter } from "metabase/router";
+import { goBack, push, useLocation } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import { Breadcrumbs, Card, Icon } from "metabase/ui";
import * as Urls from "metabase/urls";
@@ -42,7 +42,7 @@ export function NewMetricPage({
showAppSwitcher = false,
triggeredFrom = "main_app",
}: NewMetricPageProps) {
- const { location } = useRouter();
+ const location = useLocation();
const metadata = useSelector(getMetadata);
const [name, setName] = useState("");
const [datasetQuery, setDatasetQuery] = useState(() =>
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx b/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
index 1af21031f14..f4edd944c4b 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
@@ -6,7 +6,7 @@ import { NoDatabasesEmptyState } from "metabase/common/components/NoDatabasesEmp
import CS from "metabase/css/core/index.css";
import { NewModelOption } from "metabase/models/components/NewModelOption";
import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { getLearnUrl, getSetting } from "metabase/selectors/settings";
import {
canUserCreateNativeQueries,
@@ -21,7 +21,7 @@ import S from "./NewModelOptions.module.css";
const EDUCATIONAL_LINK = getLearnUrl("metabase-basics/getting-started/models");
const NewModelOptions = () => {
- const { location } = useRouter();
+ const location = useLocation();
const hasDataAccess = useSelector(canUserCreateQueries);
const hasNativeWrite = useSelector(canUserCreateNativeQueries);
diff --git a/frontend/src/metabase/monitor/tools/components/Logs/Logs.tsx b/frontend/src/metabase/monitor/tools/components/Logs/Logs.tsx
index be2c305a62f..ed6a4c3bd57 100644
--- a/frontend/src/metabase/monitor/tools/components/Logs/Logs.tsx
+++ b/frontend/src/metabase/monitor/tools/components/Logs/Logs.tsx
@@ -11,7 +11,7 @@ import {
} from "metabase/monitor/components/LogsViewer";
import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
-import { Outlet, useRouter } from "metabase/router";
+import { Outlet, useLocation } from "metabase/router";
import {
Button,
Center,
@@ -41,7 +41,7 @@ export const DEFAULT_POLLING_DURATION_MS = 1000;
export const Logs = ({
pollingDurationMs = DEFAULT_POLLING_DURATION_MS,
}: LogsProps) => {
- const { location } = useRouter();
+ const location = useLocation();
const [{ process, query }, { patchUrlState }] = useUrlState(
location,
urlStateConfig,
diff --git a/frontend/src/metabase/monitor/tools/components/TaskListPage/TaskListPage.tsx b/frontend/src/metabase/monitor/tools/components/TaskListPage/TaskListPage.tsx
index c773aca6dfe..508f8a2039d 100644
--- a/frontend/src/metabase/monitor/tools/components/TaskListPage/TaskListPage.tsx
+++ b/frontend/src/metabase/monitor/tools/components/TaskListPage/TaskListPage.tsx
@@ -5,7 +5,7 @@ import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/Loadin
import { PaginationControls } from "metabase/common/components/PaginationControls";
import { useAbortableQuery } from "metabase/common/hooks/use-abortable-query";
import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Center, Flex, Group } from "metabase/ui";
import { TaskPicker } from "../TaskPicker";
@@ -18,7 +18,7 @@ import { urlStateConfig } from "./utils";
const PAGE_SIZE = 50;
export const TaskListPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const [
{ page, sort_column, sort_direction, status, task },
{ patchUrlState },
diff --git a/frontend/src/metabase/monitor/tools/components/TaskRunsPage/TaskRunsPage.tsx b/frontend/src/metabase/monitor/tools/components/TaskRunsPage/TaskRunsPage.tsx
index 67ccc0b5575..fb7565ee78e 100644
--- a/frontend/src/metabase/monitor/tools/components/TaskRunsPage/TaskRunsPage.tsx
+++ b/frontend/src/metabase/monitor/tools/components/TaskRunsPage/TaskRunsPage.tsx
@@ -6,7 +6,7 @@ import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/Loadin
import { PaginationControls } from "metabase/common/components/PaginationControls";
import { useAbortableQuery } from "metabase/common/hooks/use-abortable-query";
import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Center, Flex, Group } from "metabase/ui";
import { toBackendStartedAt } from "../../utils";
@@ -21,7 +21,7 @@ import { PAGE_SIZE } from "./constants";
import { urlStateConfig } from "./utils";
export const TaskRunsPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const [
{
page,
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
index 0940127b6f3..3f74945c9e2 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
@@ -23,7 +23,7 @@ import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
import { Sidebar } from "metabase/monitor/components/MonitorLayout/Sidebar";
import { useDispatch } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
-import { push, useParams, useRouter } from "metabase/router";
+import { push, useLocation, useParams } from "metabase/router";
import { Flex } from "metabase/ui";
import * as Urls from "metabase/urls";
import type { NotificationId, UserId } from "metabase-types/api";
@@ -52,7 +52,7 @@ import type { RouteParams } from "./types";
import { buildListParams, urlStateConfig } from "./utils";
export const NotificationsAdminPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { notificationId: notificationIdParam } = useParams<RouteParams>();
const notificationId = Urls.extractEntityId(notificationIdParam);
const { ref: containerRef, width: containerWidth } = useElementSize();
diff --git a/frontend/src/metabase/nav/components/AppSwitcher/useGetCurrentApp.tsx b/frontend/src/metabase/nav/components/AppSwitcher/useGetCurrentApp.tsx
index cd92a26b26d..632f41f46c9 100644
--- a/frontend/src/metabase/nav/components/AppSwitcher/useGetCurrentApp.tsx
+++ b/frontend/src/metabase/nav/components/AppSwitcher/useGetCurrentApp.tsx
@@ -1,11 +1,11 @@
import { match } from "ts-pattern";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
export type CurrentApp = "main" | "admin" | "data-studio" | "monitor";
export const useGetCurrentApp = (): CurrentApp => {
- const { location } = useRouter();
+ const location = useLocation();
return match<string, CurrentApp>(location.pathname)
.when(
(path) => path.startsWith("/admin"),
diff --git a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
index 91abf3ecf6b..048547e1e28 100644
--- a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
@@ -25,8 +25,8 @@ import type { LocationDescriptorObject } from "metabase/router";
import {
push,
queryToSearch,
+ useLocation,
useNavigationType,
- useRouter,
} from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Box, Flex, Icon, UnstyledButton, rem } from "metabase/ui";
@@ -56,7 +56,7 @@ function SearchBar({
onSearchInactive,
onSearchItemSelect: onSearchItemSelectProp,
}: Props) {
- const { location } = useRouter();
+ const location = useLocation();
const navigationType = useNavigationType();
const isTypeaheadEnabled = useSelector((state) =>
getSetting(state, "search-typeahead-enabled"),
diff --git a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx
index 4f2450929de..54a4b827bb9 100644
--- a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx
@@ -4,14 +4,14 @@ import { t } from "ttag";
import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";
import { getSearchTextFromLocation } from "metabase/common/search";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import { Button, type ButtonProps, Flex, Icon } from "metabase/ui";
import { METAKEY } from "metabase/utils/browser";
import S from "./SearchButton.module.css";
export const SearchButton = (props: ButtonProps) => {
- const { location } = useRouter();
+ const location = useLocation();
const kbar = useKBar();
const { setVisualState } = kbar.query;
const searchText = getSearchTextFromLocation(location);
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx b/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx
index 8138db950ad..36357ab7009 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx
@@ -26,7 +26,7 @@ import {
createMockQueryBuilderState,
createMockState,
} from "metabase/redux/store/mocks";
-import { Route, useRouter } from "metabase/router";
+import { Route, useLocation, useParams } from "metabase/router";
import * as iframeUtils from "metabase/utils/iframe";
import type {
Card,
@@ -48,7 +48,8 @@ import { MainNavbar } from "../MainNavbar";
function RoutedMainNavbar(
props: Omit<ComponentProps<typeof MainNavbar>, "location" | "params">,
) {
- const { location, params } = useRouter();
+ const location = useLocation();
+ const params = useParams();
return <MainNavbar {...props} location={location} params={params} />;
}
diff --git a/frontend/src/metabase/new/components/NewModals/NewModals.tsx b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
index 51736f375af..e2fa328a5df 100644
--- a/frontend/src/metabase/new/components/NewModals/NewModals.tsx
+++ b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
@@ -1,5 +1,4 @@
import { useCallback, useEffect } from "react";
-import { useLocation } from "react-use";
import ActionCreator from "metabase/actions/containers/ActionCreator";
import { CreateDashboardModal } from "metabase/common/CreateDashboard/CreateDashboardModal";
@@ -19,15 +18,16 @@ import type {
} from "metabase/plugins";
import { useDispatch, useSelector } from "metabase/redux";
import { closeModal, setOpenModal } from "metabase/redux/ui";
-import { push, useRouter } from "metabase/router";
+import { push, useLocation, useParams } from "metabase/router";
import { getCurrentOpenModalState } from "metabase/selectors/ui";
import { Modal, PREVENT_AUTOCOMPLETE_CLIPPING_MODAL_PROPS } from "metabase/ui";
import * as Urls from "metabase/urls";
import type { WritebackAction } from "metabase-types/api";
export const NewModals = () => {
- const { location, params } = useRouter();
- const { pathname } = useLocation();
+ const location = useLocation();
+ const params = useParams();
+ const { pathname } = location;
const { id: currentNewModalId, props: currentNewModalProps } = useSelector(
getCurrentOpenModalState<CreateCollectionModalOwnProps>,
);
diff --git a/frontend/src/metabase/palette/components/Palette.tsx b/frontend/src/metabase/palette/components/Palette.tsx
index f85131ca513..2f2fa7ecdd2 100644
--- a/frontend/src/metabase/palette/components/Palette.tsx
+++ b/frontend/src/metabase/palette/components/Palette.tsx
@@ -3,7 +3,7 @@ import { useEffect, useMemo, useRef } from "react";
import { useOnClickOutside } from "metabase/common/hooks/use-on-click-outside";
import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { getUser } from "metabase/selectors/user";
import { Box, Card, Center, Icon, Overlay, Stack, rem } from "metabase/ui";
import { type SearchQuery, parseSearchQuery } from "metabase/utils/browser";
@@ -21,8 +21,8 @@ const PALETTE_DISABLED_PATHS = ["/setup"];
/** Command palette */
export const Palette = () => {
- const routerProps = useRouter();
- const { location } = routerProps;
+ const location = useLocation();
+ const params = useParams();
const isLoggedIn = useSelector((state) => !!getUser(state));
const locationQuery = useMemo(
() => parseSearchQuery(location.search),
@@ -33,7 +33,7 @@ export const Palette = () => {
location.pathname.startsWith(path),
);
- useCommandPaletteBasicActions({ ...routerProps, isLoggedIn });
+ useCommandPaletteBasicActions({ location, params, isLoggedIn });
const { query } = useKBar();
const disabled = isWithinIframe() || !isLoggedIn || isDisabledForPath;
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
index 1e7e1b71e94..1d2699e0833 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
@@ -18,7 +18,7 @@ import {
createMockAdminState,
createMockState,
} from "metabase/redux/store/mocks";
-import { Route, useRouter } from "metabase/router";
+import { Route, useLocation, useParams } from "metabase/router";
import { parseSearchQuery } from "metabase/utils/browser";
import type { RecentItem, Settings } from "metabase-types/api";
import {
@@ -40,9 +40,10 @@ const TestComponent = ({
q?: string;
isLoggedIn: boolean;
}) => {
- const routerProps = useRouter();
- const locationQuery = parseSearchQuery(routerProps.location.search);
- useCommandPaletteBasicActions({ ...routerProps, isLoggedIn });
+ const location = useLocation();
+ const params = useParams();
+ const locationQuery = parseSearchQuery(location.search);
+ useCommandPaletteBasicActions({ location, params, isLoggedIn });
const {
searchRequestId,
searchResults,
diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
index 6ac850759c6..10c640e93b9 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
@@ -4,6 +4,7 @@ import { useLatest } from "react-use";
import { t } from "ttag";
import { skipToken, useSearchQuery } from "metabase/api";
+import type { UseInitialCollectionIdProps } from "metabase/common/collections/hooks";
import { useInitialCollectionId } from "metabase/common/collections/hooks";
import { trackMetricCreateStarted } from "metabase/common/data-studio/analytics";
import { canAccessDataStudio } from "metabase/common/data-studio/selectors";
@@ -16,7 +17,6 @@ import {
setOpenModal,
setOpenModalWithProps,
} from "metabase/redux/ui";
-import type { WithRouterProps } from "metabase/router";
import { push } from "metabase/router";
import { getHasDatabaseWithActionsEnabled } from "metabase/selectors/data";
import {
@@ -74,7 +74,9 @@ const getActionPriority = (id: string) => {
export const useCommandPaletteBasicActions = ({
isLoggedIn,
...props
-}: WithRouterProps & { isLoggedIn: boolean }) => {
+}: Pick<UseInitialCollectionIdProps, "location" | "params"> & {
+ isLoggedIn: boolean;
+}) => {
const dispatch = useDispatch();
const collectionId = useInitialCollectionId(props) ?? undefined;
diff --git a/frontend/src/metabase/public/components/EmbedFrame/SyncedEmbedFrame.tsx b/frontend/src/metabase/public/components/EmbedFrame/SyncedEmbedFrame.tsx
index d4611516750..87a9a4666bd 100644
--- a/frontend/src/metabase/public/components/EmbedFrame/SyncedEmbedFrame.tsx
+++ b/frontend/src/metabase/public/components/EmbedFrame/SyncedEmbedFrame.tsx
@@ -1,5 +1,5 @@
import { useEmbedFrameOptions } from "metabase/public/hooks";
-import { useRouter } from "metabase/router";
+import { useLocation } from "metabase/router";
import type { EmbedFrameProps } from "./EmbedFrame";
import { EmbedFrame } from "./EmbedFrame";
@@ -8,7 +8,7 @@ export const SyncedEmbedFrame = ({
children,
...embedFrameProps
}: Partial<EmbedFrameProps>) => {
- const { location } = useRouter();
+ const location = useLocation();
const { background, bordered, hide_parameters, theme, titled } =
useEmbedFrameOptions({ location });
diff --git a/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx b/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx
index 23c937720ee..9418b539315 100644
--- a/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx
+++ b/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx
@@ -23,7 +23,7 @@ import { ResizeNode } from "metabase/rich_text_editing/tiptap/extensions/ResizeN
import { SmartLink } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";
import { SupportingText } from "metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText";
import { DROP_ZONE_COLOR } from "metabase/rich_text_editing/tiptap/extensions/shared/constants";
-import { useParams, useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Box } from "metabase/ui";
import { initializeIframeResizer } from "metabase/utils/dom";
@@ -32,7 +32,7 @@ import type { Document } from "metabase-types/api";
import S from "./PublicDocument.module.css";
export const PublicDocument = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { uuid = "" } = useParams<{ uuid: string }>();
const dispatch = useDispatch();
const siteUrl = useSelector((state) => getSetting(state, "site-url"));
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx
index 4f8c481ff40..3e506f5c4b7 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx
@@ -10,7 +10,7 @@ import { EmbeddingEntityContextProvider } from "metabase/embedding/context";
import { useEmbedFrameOptions, useSetEmbedFont } from "metabase/public/hooks";
import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
-import { useParams, useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { getCanWhitelabel } from "metabase/selectors/whitelabel";
import { parseSearchQuery } from "metabase/utils/browser";
import { isActionDashCard, isQuestionCard } from "metabase/utils/dashboard";
@@ -22,10 +22,10 @@ import { usePublicEndpoints } from "../../../hooks/use-public-endpoints";
import { PublicOrEmbeddedDashboardView } from "../PublicOrEmbeddedDashboardView";
const PublicOrEmbeddedDashboardPageInner = () => {
- const { location, router } = useRouter();
+ const location = useLocation();
useDashboardLocationSync({ location });
- useDashboardUrlQuery(router, location);
+ useDashboardUrlQuery(location);
return <PublicOrEmbeddedDashboardView />;
};
@@ -33,7 +33,7 @@ const PublicOrEmbeddedDashboardPageInner = () => {
export const PublicOrEmbeddedDashboardPage = () => {
const dispatch = useDispatch();
- const { location } = useRouter();
+ const location = useLocation();
const { uuid, token } = useParams<{ uuid: string; token: EntityToken }>();
const parameterQueryParams = useMemo(
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx
index b709966634c..b8f9c6d7e3e 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx
@@ -14,7 +14,7 @@ import { useSetEmbedFont } from "metabase/public/hooks/use-set-embed-font";
import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
import { updateMetadata } from "metabase/redux/metadata";
-import { useParams, useRouter } from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { FieldSchema } from "metabase/schema";
import { getMetadata } from "metabase/selectors/metadata";
import { getCanWhitelabel } from "metabase/selectors/whitelabel";
@@ -33,7 +33,7 @@ import type { EntityToken } from "metabase-types/api/entity";
import { PublicOrEmbeddedQuestionView } from "../PublicOrEmbeddedQuestionView";
export const PublicOrEmbeddedQuestion = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { uuid, token } = useParams<{ uuid: string; token: EntityToken }>();
const dispatch = useDispatch();
diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
index 8fe9dae995b..3882eccd8d8 100644
--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
@@ -53,9 +53,9 @@ import type { QueryBuilderUIControls, State } from "metabase/redux/store";
import {
type Location,
push,
+ useLocation,
useNavigationType,
- useRoute,
- useRouter,
+ useParams,
} from "metabase/router";
import { getIsNavbarOpen } from "metabase/selectors/app";
import { getMetadata } from "metabase/selectors/metadata";
@@ -346,8 +346,8 @@ type ReduxProps = ConnectedProps<typeof connector>;
type QueryBuilderInnerProps = ReduxProps;
function QueryBuilderInner(props: QueryBuilderInnerProps) {
- const { location, params } = useRouter();
- const route = useRoute();
+ const location = useLocation();
+ const params = useParams();
useFavicon({ favicon: props.pageFavicon ?? null });
const navigationType = useNavigationType();
const { data: fetchedTimelines, isSuccess: areTimelinesLoaded } =
@@ -639,7 +639,6 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
<LeaveRouteConfirmModal
isEnabled={shouldShowUnsavedChangesWarning && !isCallbackScheduled}
isLocationAllowed={isLocationAllowed}
- route={route ?? undefined}
/>
</>
);
diff --git a/frontend/src/metabase/router/Outlet.tsx b/frontend/src/metabase/router/Outlet.tsx
index 1cbe3d24b84..937a295fdcd 100644
--- a/frontend/src/metabase/router/Outlet.tsx
+++ b/frontend/src/metabase/router/Outlet.tsx
@@ -1,17 +1,3 @@
-import { createContext, useContext } from "react";
-
-import type { Route } from "./route";
-
-export const RouteContext = createContext<Route | null>(null);
-
-/**
- * The route matched for the nearest `element`-based route ancestor, published by
- * `RouterBridge`. Consumers hand it back to `setRouteLeaveHook`.
- */
-export function useRoute(): Route | null {
- return useContext(RouteContext);
-}
-
/**
* react-router v7's `<Outlet>`: renders the matched child route (or nothing when
* there is none).
diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsx
index 3b2a3e1c711..c113c886003 100644
--- a/frontend/src/metabase/router/RouterProvider.tsx
+++ b/frontend/src/metabase/router/RouterProvider.tsx
@@ -1,16 +1,8 @@
-import { type PropsWithChildren, createContext } from "react";
+import type { PropsWithChildren } from "react";
-import type { WithRouterProps } from "./types";
import { RouterProviderV7 } from "./v7/RouterProviderV7";
import type { LocationMirror } from "./v7/location-mirror";
-type RouterContextType = WithRouterProps;
-
-/**
- * The router state the facade hooks read, published per route by `RouterBridge`.
- */
-export const RouterContext = createContext<RouterContextType | null>(null);
-
/**
* Hosts the app on react-router v7.
*
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 972d12bc51a..7831e7948b9 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -12,7 +12,7 @@ export * from "./use-location";
export * from "./use-navigate";
export * from "./use-navigation-type";
export * from "./use-params";
-export * from "./use-router";
+export * from "./use-route-leave-hook";
export * from "./use-search-params";
export { getRawBrowserHistory } from "./v7/blocking-history";
export { queryToSearch, toFacadeLocation } from "./v7/location";
@@ -20,7 +20,11 @@ export {
createLocationMirror,
type LocationMirror,
} from "./v7/location-mirror";
-export { createV7Navigator, toNavigateArgs } from "./v7/navigator";
+export {
+ createV7Navigator,
+ subscribeLocation,
+ toNavigateArgs,
+} from "./v7/navigator";
// The memory-history engine is test-only. It reaches the barrel rather than a
// deep import because `sideEffects: false` lets rspack drop it from the app
// bundles, where nothing references it.
diff --git a/frontend/src/metabase/router/redirect.tsx b/frontend/src/metabase/router/redirect.tsx
index b8d7cde8cbf..a1823ebacb1 100644
--- a/frontend/src/metabase/router/redirect.tsx
+++ b/frontend/src/metabase/router/redirect.tsx
@@ -1,8 +1,7 @@
-import { useState } from "react";
+import { useContext, useState } from "react";
+import { UNSAFE_RouteContext, useLocation, useParams } from "react-router";
import { Navigate } from "./Navigate";
-import type { PlainRoute } from "./types";
-import { useRouter } from "./use-router";
type RouteParams = Record<string, string | undefined>;
@@ -18,19 +17,35 @@ function formatPattern(pattern: string, params: RouteParams): string {
.replace(/:([A-Za-z0-9_]+)\??/g, (_, name) =>
encodeURIComponent(params[name] ?? ""),
)
- .replace(/\*/g, () => params.splat ?? "");
+ .replace(/\*/g, () => params["*"] ?? "");
+}
+
+/**
+ * The matched pathname of the parent of the route this redirect renders in.
+ * A relative `to` resolves against it, which is where v3's `<Redirect>` resolved
+ * from and is one route shallower than v7 would resolve a relative `<Navigate>`.
+ *
+ * Read off the route context rather than `useMatches`, which is data-router only.
+ */
+function useParentPathname(): string {
+ const { matches } = useContext(UNSAFE_RouteContext);
+ return matches.at(-2)?.pathname ?? "/";
}
function RedirectRoute({ to }: { to: string }): JSX.Element {
- const { routes, params, location } = useRouter();
+ const parentPathname = useParentPathname();
+ const params = useParams();
+ const location = useLocation();
// Resolve the target once, from the match this redirect was rendered into.
- // The router context is shared and updates as soon as the redirect fires, so
- // a later render (before this component unmounts) would resolve a relative
- // `to` against the already-changed, deeper location. v3's <Redirect> computed
- // its target once in `onEnter`, so freeze it here to match.
+ // The match updates as soon as the redirect fires, so a later render (before
+ // this component unmounts) would resolve a relative `to` against the
+ // already-changed, deeper location. v3's <Redirect> computed its target once
+ // in `onEnter`, so freeze it here to match.
const [target] = useState(() => ({
- pathname: resolveTarget(to, routes, params),
+ pathname: to.startsWith("/")
+ ? formatPattern(to, params)
+ : parentPathname.replace(/\/*$/, "/") + formatPattern(to, params),
search: location.search,
state: location.state,
}));
@@ -48,49 +63,9 @@ function RedirectRoute({ to }: { to: string }): JSX.Element {
* Reproduces react-router v3's `<Redirect>` as a v7-style redirecting route
* element. Used as `<Route path="x" element={redirect("y")} />`, it interpolates
* `:params` and the `*` splat into `to`, resolves a relative `to` against the
- * parent route (using v3's own matched-route resolution, so encoding and splats
- * behave identically), and preserves the current query string and history state
- * (dropping the hash, as v3 did). It collapses to a bare `<Navigate>` once the
- * engine swap supplies native relative resolution.
+ * parent route, and preserves the current query string and history state
+ * (dropping the hash, as v3 did).
*/
export function redirect(to: string): JSX.Element {
return <RedirectRoute to={to} />;
}
-
-/**
- * The redirect target, computed the way v3's `<Redirect>` did in its `onEnter`:
- * an absolute `to` is filled directly, a relative one is resolved against the
- * pattern of the parent of the matched (leaf) redirect route.
- */
-function resolveTarget(
- to: string,
- routes: PlainRoute[],
- params: RouteParams,
-): string {
- if (to.startsWith("/")) {
- return formatPattern(to, params);
- }
- const parentPattern = getRoutePattern(routes, routes.length - 2);
- const pattern = parentPattern.replace(/\/*$/, "/") + to;
- return formatPattern(pattern, params);
-}
-
-/**
- * The absolute pattern up to and including `routes[routeIndex]`, walking parents
- * until an absolute segment. Ported from v3's `Redirect.getRoutePattern`.
- */
-function getRoutePattern(routes: PlainRoute[], routeIndex: number): string {
- let parentPattern = "";
-
- for (let i = routeIndex; i >= 0; i--) {
- const pattern = routes[i].path || "";
-
- parentPattern = pattern.replace(/\/*$/, "/") + parentPattern;
-
- if (pattern.indexOf("/") === 0) {
- break;
- }
- }
-
- return "/" + parentPattern;
-}
diff --git a/frontend/src/metabase/router/resolve-to.ts b/frontend/src/metabase/router/resolve-to.ts
deleted file mode 100644
index 08f04d04bd1..00000000000
--- a/frontend/src/metabase/router/resolve-to.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import type { Path, PlainRoute, To } from "./types";
-import { parsePath } from "./utils";
-
-/**
- * The URL prefix each matched route accounts for. v7 computes this per matched
- * route as `match.pathname`, which `RouterBridge` stashes on each stub as
- * `pathnameBase`, so read it directly rather than re-matching patterns.
- *
- * 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, a
- * pathless route is left in no steps at all (v7 gives it its parent's pathname),
- * and a splat route's entry covers the splat (v7's `match.pathname` includes it).
- */
-export function getRoutePathnames(routes: PlainRoute[]): string[] {
- return routes.map((route) => withoutTrailingSlash(route.pathnameBase ?? ""));
-}
-
-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
deleted file mode 100644
index 416734d1298..00000000000
--- a/frontend/src/metabase/router/resolve-to.unit.spec.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { getRoutePathnames, resolveTo } from "./resolve-to";
-import type { PlainRoute } from "./types";
-
-// A matched route as `RouterBridge` builds it: `pathnameBase` is the URL prefix
-// v7 matched for that route (`match.pathname`). getRoutePathnames only reads it.
-const route = (pathnameBase?: string) => ({ pathnameBase }) as PlainRoute;
-
-// The pathname `".."` resolves to, from the deepest of `routes`.
-const parentOf = (routes: PlainRoute[], pathname: string) =>
- resolveTo("..", getRoutePathnames(routes), pathname, false).pathname;
-
-describe("getRoutePathnames", () => {
- it("reads each route's matched pathname, without a trailing slash", () => {
- expect(
- getRoutePathnames([
- route("/"),
- route("/collection/5"),
- route("/collection/5/"),
- route("/collection/5/archive"),
- ]),
- ).toEqual(["/", "/collection/5", "/collection/5", "/collection/5/archive"]);
- });
-
- it("gives a pathless route the empty base v7 reports as its parent's", () => {
- // v7 gives a pathless (layout) route its parent's `match.pathname`, so its
- // entry equals the neighbour rather than adding a step.
- expect(
- getRoutePathnames([route("/collection/5"), route("/collection/5")]),
- ).toEqual(["/collection/5", "/collection/5"]);
- });
-});
-
-describe("resolveTo", () => {
- it('climbs one route for ".."', () => {
- expect(
- parentOf(
- [route("/collection/5"), route("/collection/5/archive")],
- "/collection/5/archive",
- ),
- ).toBe("/collection/5");
- });
-
- it("climbs a route whose path spans several segments", () => {
- expect(
- parentOf(
- [
- route("/account/notifications"),
- route("/account/notifications/pulse/7/archive"),
- ],
- "/account/notifications/pulse/7/archive",
- ),
- ).toBe("/account/notifications");
- });
-
- it("climbs out of a route whose match includes a splat", () => {
- // A splat route's `match.pathname` covers the swallowed tail, so `".."`
- // reads the parent's entry and lands above the whole splat route.
- expect(
- parentOf(
- [route("/collection"), route("/collection/entity/abc/def")],
- "/collection/entity/abc/def",
- ),
- ).toBe("/collection");
- });
-
- it('resolves a named relative target ("child") against the deepest match', () => {
- expect(
- resolveTo(
- "sibling",
- getRoutePathnames([route("/data/5"), route("/data/5/edit")]),
- "/data/5/edit",
- false,
- ).pathname,
- ).toBe("/data/5/edit/sibling");
- });
-
- it("passes an absolute target through untouched", () => {
- expect(
- resolveTo(
- "/browse/databases",
- getRoutePathnames([route("/data/5")]),
- "/data/5",
- false,
- ).pathname,
- ).toBe("/browse/databases");
- });
-});
diff --git a/frontend/src/metabase/router/route.unit.spec.tsx b/frontend/src/metabase/router/route.unit.spec.tsx
index 581845e7a26..88523b87725 100644
--- a/frontend/src/metabase/router/route.unit.spec.tsx
+++ b/frontend/src/metabase/router/route.unit.spec.tsx
@@ -3,8 +3,9 @@ import { useEffect } from "react";
import { act, renderWithProviders, screen } from "__support__/ui";
import { checkNotNull } from "metabase/utils/types";
-import { Outlet, useRoute } from "./Outlet";
+import { Outlet } from "./Outlet";
import { Route } from "./route";
+import { useRoutePathname } from "./use-route-leave-hook";
const Parent = () => (
<div>
@@ -90,17 +91,16 @@ describe("router/Route element", () => {
});
function RoutePathProbe({ label }: { label: string }) {
- // The matched route is a v3 route config; read its `path` for the assertion.
- const route = useRoute() as { path?: string } | null;
+ const pathname = useRoutePathname();
return (
<div>
- <span>{`${label}:${route?.path ?? "none"}`}</span>
+ <span>{`${label}:${pathname ?? "none"}`}</span>
<Outlet />
</div>
);
}
-describe("router/useRoute", () => {
+describe("router/useRoutePathname", () => {
function setupNested(initialRoute: string) {
return renderWithProviders(
<Route path="/" element={<RoutePathProbe label="parent" />}>
@@ -110,12 +110,12 @@ describe("router/useRoute", () => {
);
}
- it("exposes the matched route to an `element` route", () => {
+ it("exposes the matched pathname to an `element` route", () => {
setupNested("/child");
- expect(screen.getByText("child:child")).toBeInTheDocument();
+ expect(screen.getByText("child:/child")).toBeInTheDocument();
});
- it("gives each route its own route, not the deepest match", () => {
+ it("gives each route its own pathname, not the deepest match", () => {
setupNested("/child");
// The parent still sees its own route even though a deeper child matched.
expect(screen.getByText("parent:/")).toBeInTheDocument();
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 2ce0b88e04f..c75c594e850 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -180,61 +180,16 @@ export interface RouteProps {
}
/**
- * A route object as v3 exposed it on the injected `routes` branch. The v7
- * `RouterBridge` republishes the matched branch in this shape, adding
- * `pathnameBase`, the URL prefix the route accounts for (v7's `match.pathname`).
- */
-export interface PlainRoute extends RouteProps {
- childRoutes?: PlainRoute[];
- indexRoute?: PlainRoute;
- pathnameBase?: string;
-}
-
-/**
- * A route-leave hook, v3's `setRouteLeaveHook` callback: it receives the
- * attempted destination and how it was reached, and returns `false` to cancel
- * the navigation. The navigation type is a second argument rather than a field
- * on the location, which carries only the URL parts.
+ * A route-leave hook: it receives the attempted destination and how it was
+ * reached, and returns `false` to cancel the navigation. The navigation type is
+ * a second argument rather than a field on the location, which carries only the
+ * URL parts.
*/
export type RouteHook = (
nextLocation?: Location,
navigationType?: Action,
) => unknown;
-/**
- * v3's imperative router, the `router` prop the facade injects. The v7
- * `RouterBridge` implements this shape over v7's `navigate`.
- */
-export interface InjectedRouter {
- push(location: LocationDescriptor): void;
- replace(location: LocationDescriptor): void;
- go(n: number): void;
- goBack(): void;
- goForward(): void;
- // `route` is the route to scope the hook to. v3 typed it `any` (callers pass a
- // route stub, a `<Route>`, or nothing); the shim reads its `pathnameBase`.
- setRouteLeaveHook(route: any, hook: RouteHook): () => void;
- createPath(location: LocationDescriptor): string;
- createHref(location: LocationDescriptor): string;
- isActive(location: LocationDescriptor, indexOnly?: boolean): boolean;
-}
-
-/**
- * The router-injected props v3 passed to route components (`router`, `location`,
- * `params`, `routes`). The `RouterBridge` republishes them from the v7 match,
- * and the facade hooks read them from there.
- *
- * `params` defaults to v3's non-optional string map (not the facade's optional
- * `Params`), because the legacy route-prop readers were written against that and
- * treat matched params as always present.
- */
-export interface WithRouterProps<P = Record<string, string>> {
- location: Location;
- params: P;
- router: InjectedRouter;
- routes: PlainRoute[];
-}
-
/**
* v3's function form of a `<Link to>`, kept because `RouterLink` still handles it.
*/
diff --git a/frontend/src/metabase/router/use-navigate.ts b/frontend/src/metabase/router/use-navigate.ts
index 08bee8dde52..f6a36d63011 100644
--- a/frontend/src/metabase/router/use-navigate.ts
+++ b/frontend/src/metabase/router/use-navigate.ts
@@ -1,63 +1,14 @@
-import { useCallback, useRef } from "react";
-
-import { getRoutePathnames, resolveTo } from "./resolve-to";
-import type { NavigateFunction, NavigateOptions, To } from "./types";
-import { useRouter } from "./use-router";
-
/**
- * react-router v7's `useNavigate`, implemented over react-router v3's imperative
- * router (`router.push/replace/go`).
+ * react-router v7's `useNavigate`.
*
* - `navigate(to, { replace?, state?, relative? })` pushes (or replaces) the location.
* - `navigate(delta)` moves through the history stack (e.g. `navigate(-1)`).
*
- * 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
- * be nicer, but it would diverge: a mounted `<Navigate>` would stop re-asserting
- * its target, and effects keyed on `navigate` would run a different number of
- * times, so code written against the facade would behave differently after the
- * swap.
+ * A relative `to` (`".."`, `"child"`) resolves against the route the calling
+ * component renders in. The facade used to resolve it against the deepest
+ * matched route instead, so a component rendered by a parent route climbed from
+ * the leaf; v7 climbs from the component's own route.
*
* @see https://reactrouter.com/7.18.1/api/hooks/useNavigate
*/
-export function useNavigate(): NavigateFunction {
- 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 = {}) => {
- if (typeof to === "number") {
- router.go(to);
- return;
- }
-
- const path = resolveTo(
- to,
- getRoutePathnames(routesRef.current),
- location.pathname,
- options.relative === "path",
- );
- const descriptor = { ...path, state: options.state };
-
- if (options.replace) {
- router.replace(descriptor);
- } else {
- router.push(descriptor);
- }
- },
- [router, location.pathname],
- );
-}
+export { useNavigate } from "react-router";
diff --git a/frontend/src/metabase/router/use-route-leave-hook.ts b/frontend/src/metabase/router/use-route-leave-hook.ts
new file mode 100644
index 00000000000..9ef079e0058
--- /dev/null
+++ b/frontend/src/metabase/router/use-route-leave-hook.ts
@@ -0,0 +1,51 @@
+import { useContext, useEffect, useRef } from "react";
+import { UNSAFE_RouteContext } from "react-router";
+
+import type { RouteHook } from "./types";
+import { registerLeaveHook } from "./v7/blocking-history";
+
+/**
+ * Register a hook that runs before a navigation leaves the route this component
+ * renders in, replacing v3's `router.setRouteLeaveHook(route, hook)`. Returning
+ * `false` cancels the navigation.
+ *
+ * The hook is scoped to the route's matched pathname, so it does not fire for a
+ * destination that stays inside that route, matching v3's
+ * `listenBeforeLeavingRoute`.
+ *
+ * Callers no longer pass the route in. v3 had to inject it because only the
+ * route object knew its own pattern; v7 publishes the matched branch, so the
+ * scope is read here instead of threaded through props.
+ *
+ * Replaced by native `useBlocker` once the data router hosts the app (DEV-2375).
+ */
+export function useRouteLeaveHook(hook: RouteHook): void {
+ const basePath = useRoutePathname();
+
+ // The hook closes over state that changes every render (whether the page is
+ // dirty, whether the user already confirmed). Read it through a ref so the
+ // registration survives those renders: re-registering would drop the hook for
+ // the moment a navigation could land in.
+ const latestHook = useRef(hook);
+ latestHook.current = hook;
+
+ useEffect(
+ () =>
+ registerLeaveHook(
+ (location, navigationType) =>
+ latestHook.current(location, navigationType),
+ basePath,
+ ),
+ [basePath],
+ );
+}
+
+/**
+ * The matched pathname of the route this component renders in. Changes whenever
+ * the component is reused across a navigation that re-matched its route, which
+ * is what the leave-confirm state keys its reset on.
+ */
+export function useRoutePathname(): string | undefined {
+ const { matches } = useContext(UNSAFE_RouteContext);
+ return matches.at(-1)?.pathname;
+}
diff --git a/frontend/src/metabase/router/use-router.tsx b/frontend/src/metabase/router/use-router.tsx
deleted file mode 100644
index 6e9d78e359d..00000000000
--- a/frontend/src/metabase/router/use-router.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-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/router/utils.ts b/frontend/src/metabase/router/utils.ts
index 74546f4ae8d..8baee041086 100644
--- a/frontend/src/metabase/router/utils.ts
+++ b/frontend/src/metabase/router/utils.ts
@@ -1,36 +1,4 @@
-import type { Path, URLSearchParamsInit } from "./types";
-
-/**
- * Split a path string into `pathname`, `search`, and `hash`, mirroring
- * 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): Partial<Path> {
- const parsed: Partial<Path> = {};
-
- if (!path) {
- return parsed;
- }
-
- const hashIndex = path.indexOf("#");
- if (hashIndex >= 0) {
- parsed.hash = path.slice(hashIndex);
- path = path.slice(0, hashIndex);
- }
-
- const searchIndex = path.indexOf("?");
- if (searchIndex >= 0) {
- parsed.search = path.slice(searchIndex);
- path = path.slice(0, searchIndex);
- }
-
- if (path) {
- parsed.pathname = path;
- }
-
- return parsed;
-}
+import type { URLSearchParamsInit } from "./types";
/**
* Build a `URLSearchParams`, mirroring react-router v7's `createSearchParams`.
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
deleted file mode 100644
index 20947350656..00000000000
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import { type ReactNode, useContext, useMemo, useRef } from "react";
-import {
- type NavigateOptions,
- type To,
- UNSAFE_RouteContext,
- type NavigateFunction as V7NavigateFunction,
- useLocation as useV7Location,
- useNavigate as useV7Navigate,
- useParams as useV7Params,
-} from "react-router";
-
-import { RouteContext } from "../Outlet";
-import { RouterContext } from "../RouterProvider";
-import type { Route } from "../route";
-import type {
- Location as HistoryLocation,
- InjectedRouter,
- LocationDescriptor,
- PlainRoute,
- WithRouterProps,
-} from "../types";
-
-import { registerLeaveHook } from "./blocking-history";
-import { toFacadeLocation } from "./location";
-import { subscribeLocation, toNavigateArgs } from "./navigator";
-
-// The facade route stub, plus the route's matched pathname so `setRouteLeaveHook`
-// can scope its hook to the route the way v3 does.
-type RouteStub = PlainRoute & { pathnameBase?: string };
-
-/**
- * Runs as the `element` of every v7 route and republishes v7's location,
- * params, matched-route branch, and an imperative-router shim into the shared
- * `RouterContext` (and the `Route` context). The facade hooks (`useNavigate`,
- * `useRouter`) read that context unchanged, so nothing downstream can tell
- * which engine it runs on. Deleted with the v3 engine in Phase 4.
- */
-export function RouterBridge({
- v3Element,
-}: {
- v3Element: ReactNode;
-}): JSX.Element {
- const v7Location = useV7Location();
- const navigate = useV7Navigate();
- const v7Params = useV7Params();
- // v7's `useParams` returns v7's readonly `Params`; the context wants v3's shape,
- // which is structurally the same string map apart from the splat: v3 exposed the
- // wildcard match as `splat`, v7 names it `*`. Republish it under both so v3-era
- // readers (`params.splat` in `AutomaticDashboardApp`) keep working.
- const params = useMemo<WithRouterProps["params"]>(() => {
- const { "*": splat, ...rest } = v7Params;
- const v3Params = splat === undefined ? rest : { ...rest, splat };
- // Cast because v7 types params as readonly and partial; v3's shape is the same
- // string map.
- return v3Params as WithRouterProps["params"];
- }, [v7Params]);
-
- // `useMatches` is data-router-only, so read the matched branch from the route
- // context that also drives `<Outlet>` (available in declarative mode). Each
- // route keeps its v3 path on `handle`, which the facade hooks match against.
- const { matches } = useContext(UNSAFE_RouteContext);
- // react-router hands back a fresh `matches` array on every render, so memoizing
- // on it would republish a new `routes`/`route` each time. v3's were stable, and
- // consumers key effects on `route`: the leave-confirm modal resets itself when
- // `route` changes, which closed it mid-interaction. Key on the matched branch.
- const matchesKey = matches
- .map((match) => {
- // `handle` is typed `unknown`; we only ever put `{ path }` on it.
- const handle = match.route.handle as { path?: string } | undefined;
- return `${match.pathname}|${handle?.path ?? ""}`;
- })
- .join(">");
- const routes = useMemo<RouteStub[]>(
- () =>
- matches.map((match) => {
- // `handle` is typed `unknown`; we only ever put `{ path }` on it.
- const handle = match.route.handle as { path?: string } | undefined;
- // The facade hooks read `route.path`; `pathnameBase` is the route's matched
- // pathname, which `setRouteLeaveHook` uses to scope its hook to this route.
- return { path: handle?.path, pathnameBase: match.pathname };
- }),
- // Keyed on the matched branch, not the array identity, which changes each render.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [matchesKey],
- );
-
- const location = useMemo<HistoryLocation>(
- () => toFacadeLocation(v7Location),
- [v7Location],
- );
-
- // v3 handed consumers a stable `router`, so effects keyed on it (notably the
- // `router.listen` subscriptions in `use-dashboard-url-query`) survive a
- // navigation. v7's `navigate` changes identity per location, which would tear
- // those effects down and re-subscribe them around every location change, so read
- // `navigate` through a ref and keep the shim itself stable.
- const navigateRef = useRef(navigate);
- navigateRef.current = navigate;
- const router = useMemo<InjectedRouter>(() => {
- const navigateLatest = (to: To | number, options?: NavigateOptions) => {
- if (typeof to === "number") {
- navigateRef.current(to);
- } else {
- navigateRef.current(to, options);
- }
- };
- // `NavigateFunction` is an overloaded signature (a `To` or a delta); the
- // wrapper implements both arms but TS cannot infer it back into the overload.
- return makeRouterShim(navigateLatest as V7NavigateFunction);
- }, []);
-
- const value = useMemo<WithRouterProps>(
- () => ({ router, location, params, routes }),
- [router, location, params, routes],
- );
-
- // The injected `route` prop / `useRoute()`: consumers hand it back to
- // `setRouteLeaveHook`, which reads its `pathnameBase` to scope the hook. Cast
- // because the facade types the injected route as `Route`.
- const route = (routes.at(-1) ?? null) as Route | null;
-
- return (
- <RouterContext.Provider value={value}>
- <RouteContext.Provider value={route}>{v3Element}</RouteContext.Provider>
- </RouterContext.Provider>
- );
-}
-
-/**
- * The v3 `InjectedRouter` (`router.push/replace/go/...`) reimplemented over v7's
- * `navigate`. The facade's `useNavigate` has already resolved relative targets to
- * absolute paths before calling `push`/`replace`, so these pass straight through.
- * `setRouteLeaveHook` registers into the blocking history, which cancels the
- * navigation when the hook returns `false`, matching v3. The route's matched
- * pathname scopes the hook, so it fires only when the destination leaves that
- * route, the way v3's `listenBeforeLeavingRoute` does.
- */
-function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {
- const href = (location: LocationDescriptor) =>
- typeof location === "string"
- ? location
- : `${location.pathname ?? ""}${location.search ?? ""}${location.hash ?? ""}`;
-
- // Cast because v3's own `InjectedRouter` type omits `listen`, even though both
- // engines expose it at runtime.
- return {
- push: (location) => navigate(...toNavigateArgs(location)),
- replace: (location) =>
- navigate(...toNavigateArgs(location, { replace: true })),
- go: (n) => navigate(n),
- goBack: () => navigate(-1),
- goForward: () => navigate(1),
- setRouteLeaveHook: (route, hook) => {
- // The facade types the route arg as v3's `Route`; on v7 it is our stub,
- // which carries the matched `pathnameBase` used to scope the hook.
- const basePath = (route as RouteStub | undefined)?.pathnameBase;
- return registerLeaveHook(hook, basePath);
- },
- createPath: href,
- createHref: href,
- isActive: () => false,
- // Stands in for v3's `router.listen` (used by e.g. `use-dashboard-url-query`).
- // `V7RouterBridge` feeds these subscribers every location change.
- listen: subscribeLocation,
- } as InjectedRouter;
-}
diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
index 7b9b4c8a3c2..670d28d78b8 100644
--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx
+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
@@ -40,7 +40,7 @@ export function V7RouterTree({
/**
* react-router v7 hosting the app, declarative mode. Replaces the v3 `<Router>` +
* `useRouterHistory` + `syncHistoryWithStore` stack. Hosted on a blocking history
- * so `setRouteLeaveHook` cancels navigation the way it did on v3.
+ * so a registered leave hook cancels navigation the way it did on v3.
*
* `onLocationChange` is how the location reaches redux: the app passes
* `createLocationMirror(store.dispatch)`, so the router itself stays unaware of
diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.ts
index f5d82275ca8..28fd59975af 100644
--- a/frontend/src/metabase/router/v7/blocking-history.ts
+++ b/frontend/src/metabase/router/v7/blocking-history.ts
@@ -16,10 +16,10 @@ import { toFacadeLocation } from "./location";
type History = HistoryRouterProps["history"];
/**
- * A route-leave hook, matching v3's `setRouteLeaveHook` callback: it receives
- * the attempted destination and how it was reached, and returns `false` to
- * cancel the navigation. The navigation type is a second argument rather than a
- * field on the location, which carries only the URL parts on v7.
+ * A route-leave hook: it receives the attempted destination and how it was
+ * reached, and returns `false` to cancel the navigation. The navigation type is
+ * a second argument rather than a field on the location, which carries only the
+ * URL parts on v7.
*/
type LeaveHook = (
nextLocation?: HistoryLocation,
@@ -28,9 +28,9 @@ type LeaveHook = (
interface Registration {
hook: LeaveHook;
- // The matched pathname of the guarded route. v3's `setRouteLeaveHook` is scoped
- // to a route and only fires when a navigation leaves that route's subtree, so a
- // hook with a base path does not fire for destinations that stay under it.
+ // The matched pathname of the guarded route. A leave hook is scoped to a route
+ // and only fires when a navigation leaves that route's subtree, so a hook with
+ // a base path does not fire for destinations that stay under it.
basePath?: string;
}
@@ -51,11 +51,11 @@ export function getRawBrowserHistory(): History {
}
/**
- * Register a leave hook. The v7 `setRouteLeaveHook` shim calls this, so the
- * leave-confirm modals block navigation on v7 the same way they do on v3.
- * `basePath` scopes the hook to a route: it fires only when the destination
- * leaves that route's subtree, matching v3's `listenBeforeLeavingRoute`. Returns
- * the unregister function the caller uses as effect cleanup.
+ * Register a leave hook, so the leave-confirm modals block navigation the way
+ * they did on v3. `useRouteLeaveHook` is the call site; `basePath` scopes the
+ * hook to a route, so it fires only when the destination leaves that route's
+ * subtree, matching v3's `listenBeforeLeavingRoute`. Returns the unregister
+ * function the caller uses as effect cleanup.
*/
export function registerLeaveHook(
hook: LeaveHook,
@@ -113,7 +113,7 @@ function toBlockedLocation(to: To, state: unknown): HistoryLocation {
/**
* Wrap a history so a registered leave hook can cancel navigation, restoring the
- * v3 `setRouteLeaveHook` behavior on the declarative v7 engine. react-router
+ * v3 route-leave behavior on the declarative v7 engine. react-router
* funnels `Link`, `Navigate`, `useNavigate`, and redux `push` through the
* history's `push`/`replace`, so checking there covers every in-app navigation.
* Browser back/forward arrives as a `POP` in the listener and is reverted a step
diff --git a/frontend/src/metabase/router/v7/map-to-v7.tsx b/frontend/src/metabase/router/v7/map-to-v7.tsx
index 913c361ac70..d413a71602e 100644
--- a/frontend/src/metabase/router/v7/map-to-v7.tsx
+++ b/frontend/src/metabase/router/v7/map-to-v7.tsx
@@ -10,15 +10,10 @@ import { Route as V7Route } from "react-router";
import type { RouteElementProps } from "../route";
import { Route } from "../route";
-import { RouterBridge } from "./RouterBridge";
-
/**
* Rebuild the facade route tree (`<Route path element>` + `<Outlet/>`, authored
* in v7 syntax) into a real react-router v7 route tree for `<Routes>`. Paths are
- * already v7-native, so they pass straight through; each `element` is wrapped in a
- * `RouterBridge` that republishes v7 state into the shared context. The v3 form of
- * the path is kept on `handle` so the bridge can hand the facade hooks a v3-shaped
- * `routes` branch (its matcher is v3's). Throwaway: goes away with the v3 engine.
+ * already v7-native, so they pass straight through, and elements render as-is.
*/
export function mapToV7(node: ReactNode): ReactNode {
return Children.map(node, (child) => {
@@ -46,23 +41,17 @@ export function mapToV7(node: ReactNode): ReactNode {
function toV7Route(element: ReactElement<RouteElementProps>): ReactElement {
const { path, index, element: routeElement, children } = element.props;
- // v7 defaults a route with no `element` to `<Outlet/>`; only wrap (and publish
- // context) when the facade route actually renders something.
- const bridged =
- routeElement !== undefined ? (
- <RouterBridge v3Element={routeElement} />
- ) : undefined;
-
- // Keep the route `path` on `handle`: the matched-route branch the facade
- // republishes exposes it, and consumers read it (`redirect` reads `route.path`).
- const handle = path != null ? { path } : undefined;
+ // v7 reads `element={null}` as "no element" and falls back to `<Outlet/>`,
+ // which would render the route's children. The facade keeps the two apart: an
+ // explicit null renders nothing and provides no outlet.
+ const routeContent = routeElement === null ? <Fragment /> : routeElement;
if (index) {
- return <V7Route index element={bridged} handle={handle} />;
+ return <V7Route index element={routeContent} />;
}
return (
- <V7Route path={path} element={bridged} handle={handle}>
+ <V7Route path={path} element={routeContent}>
{mapToV7(children)}
</V7Route>
);
diff --git a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
index adafd315abb..fa28cc658e2 100644
--- a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
+++ b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
@@ -1,24 +1,16 @@
-import { useEffect } from "react";
-
import { renderWithProviders, screen } from "__support__/ui";
import {
Outlet,
Route,
push,
useLocation,
- useRoute,
- useRouter,
+ useRouteLeaveHook,
} from "metabase/router";
// Registers an always-blocking leave hook scoped to the route it is rendered on,
// exactly as the leave-confirm modals do (guard on a parent layout route).
function Guard() {
- const { router } = useRouter();
- const route = useRoute();
- useEffect(
- () => router.setRouteLeaveHook(route, () => false),
- [router, route],
- );
+ useRouteLeaveHook(() => false);
return null;
}
@@ -43,7 +35,7 @@ const tree = (
</Route>
);
-// v3's `setRouteLeaveHook` is scoped to the guarded route: it fires only when a
+// A leave hook is scoped to the route it is registered on: it fires only when a
// navigation leaves that route's subtree. So moving between sibling child routes
// under the guarded layout is allowed, and only leaving the layout is blocked.
describe("route-scoped leave hook", () => {
diff --git a/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx b/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx
index 649b40541ea..ebc413c951e 100644
--- a/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx
+++ b/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx
@@ -1,28 +1,19 @@
import { useEffect, useState } from "react";
import { renderWithProviders, screen } from "__support__/ui";
-import { Outlet, Route, push, useRouter } from "metabase/router";
+import { Outlet, Route, push, subscribeLocation } from "metabase/router";
-import type { Location as HistoryLocation } from "../types";
-
-// Both engines expose `listen` at runtime; v3's `InjectedRouter` type omits it.
-type RouterWithListen = {
- listen: (callback: (location: HistoryLocation) => void) => () => void;
-};
-
-// v3's `router.listen` fires a callback on every location change and returns an
-// unsubscribe function. The v7 engine has no native equivalent, so the shim wires
-// it to the location fan-out; `use-dashboard-url-query` relies on it (and crashed
-// the dashboard on v7 when it was missing).
+// `subscribeLocation` fires a callback on every location change and returns an
+// unsubscribe function, standing in for v3's `router.listen`.
+// `use-dashboard-url-query` relies on it (and crashed the dashboard on v7 when it
+// was missing).
function Harness() {
- const { router } = useRouter();
const [seen, setSeen] = useState<string[]>([]);
useEffect(() => {
- // Cast because v3's `InjectedRouter` type omits `listen` (see above).
- return (router as unknown as RouterWithListen).listen((location) => {
+ return subscribeLocation((location) => {
setSeen((previous) => [...previous, location.pathname]);
});
- }, [router]);
+ }, []);
return (
<div>
<span data-testid="seen">{seen.join(",")}</span>
@@ -37,7 +28,7 @@ const tree = (
</Route>
);
-describe("router.listen", () => {
+describe("subscribeLocation", () => {
it("fires the callback on navigation and stops after unsubscribe", async () => {
const { store } = renderWithProviders(tree, {
withRouter: true,
diff --git a/frontend/src/metabase/search/containers/SearchApp.tsx b/frontend/src/metabase/search/containers/SearchApp.tsx
index f3695327a56..b71234994ec 100644
--- a/frontend/src/metabase/search/containers/SearchApp.tsx
+++ b/frontend/src/metabase/search/containers/SearchApp.tsx
@@ -20,7 +20,7 @@ import type { URLSearchFilterQueryParams } from "metabase/common/search/types";
import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/redux";
import type { Location, LocationDescriptorObject } from "metabase/router";
-import { push, queryToSearch, useRouter } from "metabase/router";
+import { push, queryToSearch, useLocation } from "metabase/router";
import { SearchSidebar } from "metabase/search/components/SearchSidebar";
import {
SearchBody,
@@ -40,7 +40,7 @@ const getPageFromLocation = (location: Location) => {
};
export function SearchApp() {
- const { location } = useRouter();
+ const location = useLocation();
const dispatch = useDispatch();
usePageTitle(t`Search`);
diff --git a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx
index 2574f0e9b87..9456433557a 100644
--- a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx
+++ b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx
@@ -12,7 +12,7 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErr
import { PaginationControls } from "metabase/common/components/PaginationControls";
import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/redux";
-import { replace, useParams, useRouter } from "metabase/router";
+import { replace, useLocation, useParams } from "metabase/router";
import { POLLING_INTERVAL } from "metabase/transforms/constants";
import { useJobHeaderState } from "metabase/transforms/hooks/use-job-header-state";
import { formatRunMethod, formatStatus } from "metabase/transforms/utils";
@@ -41,7 +41,7 @@ import { getParsedParams, getSortOptions } from "./utils";
const EMPTY_RUNS: TransformJobRun[] = [];
export function JobRunListPage() {
- const { location } = useRouter();
+ const location = useLocation();
const params = useParams<{ jobId: string }>();
usePageTitle(t`Run history`);
const jobId = Urls.extractEntityId(params.jobId);
diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.tsx b/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.tsx
index 120238ff937..dfcf9d35386 100644
--- a/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.tsx
+++ b/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.tsx
@@ -13,7 +13,7 @@ import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/Da
import { PaneHeader } from "metabase/common/data-studio/components/PaneHeader";
import { useSetting } from "metabase/common/hooks";
import { useDispatch } from "metabase/redux";
-import { replace, useRouter } from "metabase/router";
+import { replace, useLocation } from "metabase/router";
import { DetailedViewSwitch } from "metabase/transforms/components/DetailedViewSwitch";
import { LockedTransformsBanner } from "metabase/transforms/components/LockedTransformsBanner/LockedTransformsBanner";
import { POLLING_INTERVAL } from "metabase/transforms/constants";
@@ -42,7 +42,7 @@ import {
const EMPTY_RUNS: TransformRun[] = [];
export function RunListPage() {
- const { location } = useRouter();
+ const location = useLocation();
const params = getParsedParams(location);
const { page = 0 } = params;
const { ref: containerRef, width: containerWidth } = useElementSize();
diff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx
index e240d072c5f..8a2447874b8 100644
--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx
@@ -12,7 +12,7 @@ import { PaginationControls } from "metabase/common/components/PaginationControl
import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";
import { PaneHeader } from "metabase/common/data-studio/components/PaneHeader";
import { useDispatch } from "metabase/redux";
-import { replace, useRouter } from "metabase/router";
+import { replace, useLocation } from "metabase/router";
import { DetailedViewSwitch } from "metabase/transforms/components/DetailedViewSwitch";
import { POLLING_INTERVAL } from "metabase/transforms/constants";
import { isActiveRunStatus } from "metabase/transforms/utils";
@@ -39,7 +39,7 @@ import {
const EMPTY_RUNS: TransformGraphRun[] = [];
export function TransformGraphRunListPage() {
- const { location } = useRouter();
+ const location = useLocation();
const params = useMemo(() => getParsedParams(location), [location]);
const filterOptions = useMemo(() => getFilterOptions(params), [params]);
const { page = 0 } = params;
diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
index 0bc84d70942..0dc634c1596 100644
--- a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
@@ -20,7 +20,7 @@ import { useHasTokenFeature, useSetting } from "metabase/common/hooks";
import CS from "metabase/css/core/index.css";
import { PLUGIN_REPLACEMENT, PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";
import { useSelector } from "metabase/redux";
-import { Outlet, useRouter } from "metabase/router";
+import { Outlet, useLocation } from "metabase/router";
import { LockedTransformsBanner } from "metabase/transforms/components/LockedTransformsBanner/LockedTransformsBanner";
import { useTransformPermissions } from "metabase/transforms/hooks/use-transform-permissions";
import { getShouldShowPythonTransformsUpsell } from "metabase/transforms/selectors";
@@ -115,7 +115,7 @@ const globalFilterFn = (
};
export const TransformListPage = () => {
- const { location } = useRouter();
+ const location = useLocation();
const { transformsDatabases = [], isLoadingDatabases } =
useTransformPermissions();
const targetCollectionId =