Skip to content

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

Delete withRouteProps (#78779)

Romeo Van Snickb4772edd33c6
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 3eb3546e2a5..622142df6d2 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, withRouteProps } from "metabase/router";
+import { Route, useParams, useRouter } 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";
@@ -25,7 +25,14 @@ import {
createMockTable,
} from "metabase-types/api/mocks";
-const RoutedImpersonationModal = withRouteProps(ImpersonationModal);
+/** Feeds the modal its route props the way `modalRoute` does in the app. */
+function RoutedImpersonationModal({ onClose }: { onClose: () => void }) {
+ const params = useParams();
+ const { location } = useRouter();
+ return (
+ <ImpersonationModal params={params} location={location} onClose={onClose} />
+ );
+}
const groupId = 2;
const databaseId = 1;
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx
index 2c947be6827..ab87aec2090 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx
@@ -1,6 +1,5 @@
import { useCallback, useEffect } from "react";
import { t } from "ttag";
-import _ from "underscore";
import { CollectionPermissionsHelp } from "metabase/admin/permissions/components/CollectionPermissionsHelp";
import {
@@ -10,26 +9,17 @@ import {
import { PermissionsPageLayout } from "metabase/admin/permissions/components/PermissionsPageLayout";
import { PermissionsSidebar } from "metabase/admin/permissions/components/PermissionsSidebar";
import {
- type UpdateTenantCollectionPermissionParams,
initializeTenantCollectionPermissions,
loadTenantCollectionPermissions,
saveTenantCollectionPermissions,
updateTenantCollectionPermission,
} from "metabase/admin/permissions/permissions";
-import type {
- CollectionIdProps,
- CollectionSidebarType,
-} from "metabase/admin/permissions/selectors/collection-permissions";
-import type {
- PermissionEditorEntity,
- PermissionEditorType,
-} from "metabase/admin/permissions/types";
+import type { PermissionEditorEntity } from "metabase/admin/permissions/types";
import { assertNumericId } from "metabase/admin/permissions/types";
import { useListCollectionsTreeQuery } from "metabase/api";
-import { connect } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import { push } from "metabase/router";
-import type { Collection, CollectionId } from "metabase-types/api";
+import { useDispatch, useSelector } from "metabase/redux";
+import { push, useParams } from "metabase/router";
+import type { CollectionId } from "metabase-types/api";
import {
getIsTenantDirty,
@@ -39,55 +29,31 @@ import {
tenantCollectionsQuery,
} from "./selectors";
-const mapDispatchToProps = {
- initialize: initializeTenantCollectionPermissions,
- loadPermissions: loadTenantCollectionPermissions,
- navigateToItem: ({ id }: { id: CollectionId }) =>
- push(`/admin/permissions/tenant-collections/${id}`),
- updateCollectionPermission: updateTenantCollectionPermission,
- savePermissions: saveTenantCollectionPermissions,
-};
-
-const mapStateToProps = (state: State, props: CollectionIdProps) => {
- return {
- sidebar: getTenantCollectionsSidebar(state, props),
- permissionEditor: getTenantCollectionsPermissionEditor(state, props),
- isDirty: getIsTenantDirty(state),
- collection: getTenantCollectionEntity(state, props),
- };
-};
-
-type TenantCollectionPermissionsPageProps = {
- params: CollectionIdProps["params"];
- sidebar: CollectionSidebarType;
- permissionEditor: PermissionEditorType | null;
- collection: Collection | null;
- navigateToItem: (item: { id: CollectionId }) => any;
- updateCollectionPermission: (
- params: UpdateTenantCollectionPermissionParams,
- ) => any;
- isDirty: boolean;
- savePermissions: (...args: any[]) => any;
- loadPermissions: (...args: any[]) => any;
- initialize: (...args: any[]) => any;
-};
-
-function TenantCollectionPermissionsPageView({
- sidebar,
- permissionEditor,
- collection,
- isDirty,
- savePermissions,
- loadPermissions,
- updateCollectionPermission,
- navigateToItem,
- initialize,
-}: TenantCollectionPermissionsPageProps) {
+export function TenantCollectionPermissionsPage() {
+ const dispatch = useDispatch();
useListCollectionsTreeQuery(tenantCollectionsQuery);
+ // These selectors resolve the selected collection from the route, so they
+ // take the route params rather than reading them from the store.
+ const params = useParams<{ collectionId: string }>();
+ const selectorProps = { params };
+ const sidebar = useSelector((state) =>
+ getTenantCollectionsSidebar(state, selectorProps),
+ );
+ const permissionEditor = useSelector((state) =>
+ getTenantCollectionsPermissionEditor(state, selectorProps),
+ );
+ const collection = useSelector((state) =>
+ getTenantCollectionEntity(state, selectorProps),
+ );
+ const isDirty = useSelector(getIsTenantDirty);
+
useEffect(() => {
- initialize();
- }, [initialize]);
+ dispatch(initializeTenantCollectionPermissions());
+ }, [dispatch]);
+
+ const navigateToItem = ({ id }: { id: CollectionId }) =>
+ dispatch(push(`/admin/permissions/tenant-collections/${id}`));
const handlePermissionChange = useCallback(
(
@@ -99,22 +65,24 @@ function TenantCollectionPermissionsPageView({
if (!collection) {
return;
}
- updateCollectionPermission({
- groupId: assertNumericId(item.id),
- collection,
- value,
- shouldPropagateToChildren: toggleState ?? false,
- });
+ dispatch(
+ updateTenantCollectionPermission({
+ groupId: assertNumericId(item.id),
+ collection,
+ value,
+ shouldPropagateToChildren: toggleState ?? false,
+ }),
+ );
},
- [collection, updateCollectionPermission],
+ [collection, dispatch],
);
return (
<PermissionsPageLayout
tab="tenant-collections"
isDirty={isDirty}
- onSave={savePermissions}
- onLoad={() => loadPermissions()}
+ onSave={() => dispatch(saveTenantCollectionPermissions())}
+ onLoad={() => dispatch(loadTenantCollectionPermissions())}
helpContent={<CollectionPermissionsHelp />}
>
<PermissionsSidebar {...sidebar} onSelect={navigateToItem} />
@@ -137,7 +105,3 @@ function TenantCollectionPermissionsPageView({
</PermissionsPageLayout>
);
}
-
-export const TenantCollectionPermissionsPage = _.compose(
- connect(mapStateToProps, mapDispatchToProps),
-)(TenantCollectionPermissionsPageView);
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
index 22073ad11ad..41c946c7895 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
@@ -24,7 +24,7 @@ import {
PLUGIN_TENANTS,
} from "metabase/plugins";
import { useSelector } from "metabase/redux";
-import { Route, redirect, withRouteProps } from "metabase/router";
+import { Route, redirect } from "metabase/router";
import { getIsTenantUser, getUserIsAdmin } from "metabase/selectors/user";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, Text } from "metabase/ui";
@@ -69,13 +69,6 @@ import {
isTenantGroup,
} from "./utils/utils";
-// Reads route params through `connect`'s `mapStateToProps`, so the hooks cannot
-// reach it. Migrating it means rewriting the connected container, tracked
-// separately.
-const RoutedTenantCollectionPermissionsPage = withRouteProps(
- TenantCollectionPermissionsPage,
-);
-
export function initializePlugin() {
if (hasPremiumFeature("tenants")) {
PLUGIN_TENANTS.isEnabled = true;
@@ -102,7 +95,7 @@ export function initializePlugin() {
<>
<Route
path="tenant-collections"
- element={<RoutedTenantCollectionPermissionsPage />}
+ element={<TenantCollectionPermissionsPage />}
>
<Route path=":collectionId" />
</Route>
diff --git a/frontend/src/metabase/AppComponent.tsx b/frontend/src/metabase/AppComponent.tsx
index 22b4860ac2b..5476bc5301e 100644
--- a/frontend/src/metabase/AppComponent.tsx
+++ b/frontend/src/metabase/AppComponent.tsx
@@ -24,11 +24,10 @@ import { ContentViewportContext } from "metabase/common/context/ContentViewportC
import CS from "metabase/css/core/index.css";
import ScrollToTop from "metabase/hoc/ScrollToTop";
import { usePageTitle } from "metabase/hooks/use-page-title";
-import { connect, useSelector } from "metabase/redux";
+import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
-import type { AppErrorDescriptor, State } from "metabase/redux/store";
-import type { Location } from "metabase/router";
-import { Outlet, useLocation } from "metabase/router";
+import type { AppErrorDescriptor } from "metabase/redux/store";
+import { Outlet, useRouter } from "metabase/router";
import { getErrorPage } from "metabase/selectors/app";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { StatusListing } from "metabase/status/components/StatusListing";
@@ -59,57 +58,33 @@ const getErrorComponent = ({ status, data, context }: AppErrorDescriptor) => {
return <GenericError details={data?.message} />;
};
-interface AppStateProps {
- errorPage: AppErrorDescriptor | null;
- isAdminApp: boolean;
- isDataStudioApp: boolean;
- isMonitorApp: boolean;
- isDataApp: boolean;
- bannerMessageDescriptor?: string;
- isAppBarVisible: boolean;
- isNavBarEnabled: boolean;
-}
-
-interface AppDispatchProps {
- onError: (error: unknown) => void;
-}
-
-interface AppRouterOwnProps {
- location: Location;
-}
-
-type AppProps = AppStateProps & AppDispatchProps & AppRouterOwnProps;
-
-const mapStateToProps = (
- state: State,
- props: AppRouterOwnProps,
-): AppStateProps => ({
- errorPage: getErrorPage(state),
- isAdminApp: getIsAdminApp(state, props),
- isDataStudioApp: getIsDataStudioApp(state, props),
- isMonitorApp: getIsMonitorApp(state, props),
- isDataApp: getIsDataApp(state, props),
- isAppBarVisible: getIsAppBarVisible(state, props),
- isNavBarEnabled: getIsNavBarEnabled(state, props),
-});
-
-const mapDispatchToProps: AppDispatchProps = {
- onError: setErrorPage,
-};
-
-function App({
- errorPage,
- isAdminApp,
- isDataStudioApp,
- isMonitorApp,
- isDataApp,
- isAppBarVisible,
- isNavBarEnabled,
- onError,
-}: AppProps) {
+export function App() {
const [viewportElement, setViewportElement] = useState<HTMLElement | null>();
+ const dispatch = useDispatch();
const applicationName = useSelector(getApplicationName);
- const { pathname } = useLocation();
+
+ // 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 routerProps = { location };
+ const errorPage = useSelector(getErrorPage);
+ const isAdminApp = useSelector((state) => getIsAdminApp(state, routerProps));
+ const isDataStudioApp = useSelector((state) =>
+ getIsDataStudioApp(state, routerProps),
+ );
+ const isMonitorApp = useSelector((state) =>
+ getIsMonitorApp(state, routerProps),
+ );
+ const isDataApp = useSelector((state) => getIsDataApp(state, routerProps));
+ const isAppBarVisible = useSelector((state) =>
+ getIsAppBarVisible(state, routerProps),
+ );
+ const isNavBarEnabled = useSelector((state) =>
+ getIsNavBarEnabled(state, routerProps),
+ );
+
+ const onError = (error: unknown) => dispatch(setErrorPage(error));
+ const { pathname } = location;
usePageTitle(applicationName, { titleIndex: 0 });
useTokenRefresh();
@@ -159,14 +134,3 @@ function App({
</ErrorBoundary>
);
}
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default connect<
- AppStateProps,
- AppDispatchProps,
- AppRouterOwnProps,
- State
->(
- mapStateToProps,
- mapDispatchToProps,
-)(App);
diff --git a/frontend/src/metabase/account/app/containers/AccountApp/AccountApp.tsx b/frontend/src/metabase/account/app/containers/AccountApp/AccountApp.tsx
index 6b1f677b4bb..46e95ca6da1 100644
--- a/frontend/src/metabase/account/app/containers/AccountApp/AccountApp.tsx
+++ b/frontend/src/metabase/account/app/containers/AccountApp/AccountApp.tsx
@@ -1,23 +1,19 @@
-import { connect } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import type { Location } from "metabase/router";
-import { push } from "metabase/router";
+import { useDispatch, useSelector } from "metabase/redux";
+import { push, useLocation } from "metabase/router";
import { getUser } from "metabase/selectors/user";
import AccountLayout from "../../components/AccountLayout";
-interface OwnProps {
- location: Location;
-}
-
-const mapStateToProps = (state: State, props: OwnProps) => ({
- user: getUser(state),
- path: props.location.pathname,
-});
+export function AccountApp() {
+ const dispatch = useDispatch();
+ const user = useSelector(getUser);
+ const { pathname } = useLocation();
-const mapDispatchToProps = {
- onChangeLocation: push,
-};
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default connect(mapStateToProps, mapDispatchToProps)(AccountLayout);
+ return (
+ <AccountLayout
+ user={user}
+ path={pathname}
+ onChangeLocation={(nextLocation) => dispatch(push(nextLocation))}
+ />
+ );
+}
diff --git a/frontend/src/metabase/account/app/containers/AccountApp/index.ts b/frontend/src/metabase/account/app/containers/AccountApp/index.ts
index 040b4be7aa7..ba679457e4c 100644
--- a/frontend/src/metabase/account/app/containers/AccountApp/index.ts
+++ b/frontend/src/metabase/account/app/containers/AccountApp/index.ts
@@ -1,2 +1 @@
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export { default } from "./AccountApp";
+export { AccountApp } from "./AccountApp";
diff --git a/frontend/src/metabase/account/routes.tsx b/frontend/src/metabase/account/routes.tsx
index 964517d24be..9dcc02af0b9 100644
--- a/frontend/src/metabase/account/routes.tsx
+++ b/frontend/src/metabase/account/routes.tsx
@@ -2,28 +2,21 @@ import type { Store } from "@reduxjs/toolkit";
import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";
import type { State } from "metabase/redux/store";
-import {
- Route,
- type RouteComponent,
- redirect,
- withRouteProps,
-} from "metabase/router";
+import { Route, type RouteComponent, redirect } from "metabase/router";
-import AccountApp from "./app/containers/AccountApp";
+import { AccountApp } from "./app/containers/AccountApp";
import LoginHistoryApp from "./login-history/containers/LoginHistoryApp";
import { getNotificationRoutes } from "./notifications/routes";
import UserPasswordApp from "./password/containers/UserPasswordApp";
import UserProfileApp from "./profile/containers/UserProfileApp";
-const RoutedAccountApp = withRouteProps(AccountApp);
-
export const getAccountRoutes = (
_store: Store<State>,
IsAuthenticated: RouteComponent,
) => {
return (
<Route path="/account" element={<IsAuthenticated />}>
- <Route element={<RoutedAccountApp />}>
+ <Route element={<AccountApp />}>
<Route index element={redirect("profile")} />
<Route path="profile" element={<UserProfileApp />} />
<Route path="password" element={<UserPasswordApp />} />
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 0cdd9c1e16f..0fa56ed2114 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, withRouteProps } from "metabase/router";
+import { Route, useParams, useRoute, useRouter } from "metabase/router";
import { checkNotNull } from "metabase/utils/types";
import type { Card, WritebackAction } from "metabase-types/api";
import {
@@ -24,7 +24,20 @@ import { createSampleDatabase } from "metabase-types/api/mocks/presets";
import ActionCreatorModal from "./ActionCreatorModal";
-const RoutedActionCreatorModal = withRouteProps(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;
+ return (
+ <ActionCreatorModal
+ params={params}
+ location={location}
+ route={route}
+ onClose={onClose}
+ />
+ );
+}
const MODEL = createMockCard({ id: 1, type: "model" });
const MODEL_SLUG = `${MODEL.id}-${MODEL.name.toLowerCase()}`;
diff --git a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx
index 1674c54a052..7b565fadbcd 100644
--- a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx
+++ b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx
@@ -1,13 +1,11 @@
import { useCallback, useEffect } from "react";
import { t } from "ttag";
-import _ from "underscore";
import { CollectionPermissionsHelp } from "metabase/admin/permissions/components/CollectionPermissionsHelp";
import { useListCollectionsTreeQuery } from "metabase/api";
-import { connect, useSelector } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import { push } from "metabase/router";
-import type { Collection, CollectionId } from "metabase-types/api";
+import { useDispatch, useSelector } from "metabase/redux";
+import { push, useParams } from "metabase/router";
+import type { CollectionId } from "metabase-types/api";
import {
PermissionsEditor,
@@ -16,16 +14,11 @@ import {
import { PermissionsPageLayout } from "../../components/PermissionsPageLayout";
import { PermissionsSidebar } from "../../components/PermissionsSidebar";
import {
- type UpdateCollectionPermissionParams,
initializeCollectionPermissions,
loadCollectionPermissions,
saveCollectionPermissions,
updateCollectionPermission,
} from "../../permissions";
-import type {
- CollectionIdProps,
- CollectionSidebarType,
-} from "../../selectors/collection-permissions";
import {
collectionsQuery,
getCollectionEntity,
@@ -33,60 +26,39 @@ import {
getCollectionsSidebar,
getIsDirty,
} from "../../selectors/collection-permissions";
-import type { PermissionEditorEntity, PermissionEditorType } from "../../types";
+import type { PermissionEditorEntity } from "../../types";
import { assertNumericId } from "../../types";
-const mapDispatchToProps = {
- initialize: initializeCollectionPermissions,
- loadPermissions: loadCollectionPermissions,
- navigateToItem: ({ id }: { id: CollectionId }) =>
- push(`/admin/permissions/collections/${id}`),
- updateCollectionPermission,
- savePermissions: saveCollectionPermissions,
-};
-
-const mapStateToProps = (state: State, props: CollectionIdProps) => {
- return {
- sidebar: getCollectionsSidebar(state, props),
- permissionEditor: getCollectionsPermissionEditor(state, props),
- isDirty: getIsDirty(state),
- collection: getCollectionEntity(state, props),
- };
-};
-
-type CollectionPermissionsPageProps = {
- params: CollectionIdProps["params"];
- sidebar: CollectionSidebarType;
- permissionEditor: PermissionEditorType | null;
- collection: Collection | undefined;
- navigateToItem: (item: any) => void;
- updateCollectionPermission: (params: UpdateCollectionPermissionParams) => any;
- isDirty: boolean;
- savePermissions: (...args: any[]) => any;
- loadPermissions: (...args: any[]) => any;
- initialize: (...args: any[]) => any;
-};
-
-function CollectionsPermissionsPageView({
- sidebar,
- permissionEditor,
- collection,
- isDirty,
- savePermissions,
- loadPermissions,
- updateCollectionPermission,
- navigateToItem,
- initialize,
-}: CollectionPermissionsPageProps) {
+export function CollectionPermissionsPage() {
+ const dispatch = useDispatch();
useListCollectionsTreeQuery(collectionsQuery);
+ // These selectors resolve the selected collection from the route, so they
+ // take the route params rather than reading them from the store.
+ const params = useParams<{ collectionId: string }>();
+ const selectorProps = { params };
+ const sidebar = useSelector((state) =>
+ getCollectionsSidebar(state, selectorProps),
+ );
+ const permissionEditor = useSelector((state) =>
+ getCollectionsPermissionEditor(state, selectorProps),
+ );
+ const collection = useSelector((state) =>
+ getCollectionEntity(state, selectorProps),
+ );
+ const isDirty = useSelector(getIsDirty);
+
const originalPermissionsState = useSelector(
({ admin }) => admin.permissions.originalCollectionPermissions,
);
+ // These thunks take a collection namespace; this page edits the default one.
useEffect(() => {
- initialize();
- }, [initialize]);
+ dispatch(initializeCollectionPermissions(undefined));
+ }, [dispatch]);
+
+ const navigateToItem = ({ id }: { id: CollectionId }) =>
+ dispatch(push(`/admin/permissions/collections/${id}`));
const handlePermissionChange = useCallback(
(
@@ -98,23 +70,25 @@ function CollectionsPermissionsPageView({
if (!collection) {
return;
}
- updateCollectionPermission({
- groupId: assertNumericId(item.id),
- collection,
- value,
- shouldPropagateToChildren: toggleState,
- originalPermissionsState,
- });
+ dispatch(
+ updateCollectionPermission({
+ groupId: assertNumericId(item.id),
+ collection,
+ value,
+ shouldPropagateToChildren: toggleState,
+ originalPermissionsState,
+ }),
+ );
},
- [collection, updateCollectionPermission, originalPermissionsState],
+ [collection, dispatch, originalPermissionsState],
);
return (
<PermissionsPageLayout
tab="collections"
isDirty={isDirty}
- onSave={savePermissions}
- onLoad={() => loadPermissions()}
+ onSave={() => dispatch(saveCollectionPermissions(undefined))}
+ onLoad={() => dispatch(loadCollectionPermissions(undefined))}
helpContent={<CollectionPermissionsHelp />}
key={collection?.id}
>
@@ -138,7 +112,3 @@ function CollectionsPermissionsPageView({
</PermissionsPageLayout>
);
}
-
-export const CollectionPermissionsPage = _.compose(
- connect(mapStateToProps, mapDispatchToProps),
-)(CollectionsPermissionsPageView);
diff --git a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx
index b2af1c252cb..d9f5cea4e5a 100644
--- a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx
+++ b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx
@@ -8,7 +8,7 @@ import {
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import { Route, withRouteProps } from "metabase/router";
+import { Route } from "metabase/router";
import type {
Collection,
CollectionPermissionsGraph,
@@ -24,10 +24,6 @@ import {
import { CollectionPermissionsPage } from "../CollectionPermissionsPage";
-const RoutedCollectionPermissionsPage = withRouteProps(
- CollectionPermissionsPage,
-);
-
const personalCollection = createMockCollection({
id: "personal",
name: "Personal",
@@ -186,11 +182,11 @@ export function setup({
<>
<Route
path="/admin/permissions/collections"
- element={<RoutedCollectionPermissionsPage />}
+ element={<CollectionPermissionsPage />}
/>
<Route
path="/admin/permissions/collections/:collectionId"
- element={<RoutedCollectionPermissionsPage />}
+ element={<CollectionPermissionsPage />}
/>
</>,
{
diff --git a/frontend/src/metabase/admin/permissions/pages/DatabasePermissionsPage/DatabasesPermissionsPage.tsx b/frontend/src/metabase/admin/permissions/pages/DatabasePermissionsPage/DatabasesPermissionsPage.tsx
index 41d096212e8..e862da3d97d 100644
--- a/frontend/src/metabase/admin/permissions/pages/DatabasePermissionsPage/DatabasesPermissionsPage.tsx
+++ b/frontend/src/metabase/admin/permissions/pages/DatabasePermissionsPage/DatabasesPermissionsPage.tsx
@@ -1,13 +1,12 @@
import { Fragment, useCallback } from "react";
import { useAsync } from "react-use";
import { t } from "ttag";
-import _ from "underscore";
import { PermissionsEditorLegacyNoSelfServiceWarning } from "metabase/admin/permissions/components/PermissionsEditor/PermissionsEditorLegacyWarning";
+import type { ITreeNodeItem } from "metabase/common/components/tree/types";
import { PLUGIN_ADVANCED_PERMISSIONS } from "metabase/plugins";
-import { connect, useDispatch, useSelector } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import { Outlet, push } from "metabase/router";
+import { useDispatch, useSelector } from "metabase/redux";
+import { Outlet, push, useParams } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Center, Loader } from "metabase/ui";
@@ -18,12 +17,10 @@ import {
import { PermissionsEditorSplitPermsMessage } from "../../components/PermissionsEditor/PermissionsEditorSplitPermsMessage";
import { PermissionsSidebar } from "../../components/PermissionsSidebar";
import {
- type UpdateDataPermissionParams,
loadDataPermissionsForDb,
updateDataPermission,
} from "../../permissions";
import {
- type DataSidebarProps,
type DataTreeNodeItem,
getDataFocusSidebar,
getGroupsDataPermissionEditor,
@@ -44,53 +41,41 @@ import {
getDatabaseFocusPermissionsUrl,
} from "../../utils/urls";
-const mapDispatchToProps = {
- updateDataPermission,
- switchView: (entityType: string) =>
- push(`/admin/permissions/data/${entityType}`),
- navigateToDatabaseList: () => push(DATABASES_BASE_PATH),
- navigateToItem: (item: DataTreeNodeItem) =>
- push(getDatabaseFocusPermissionsUrl(item.entityId)),
-};
-
-const mapStateToProps = (
- state: State,
- props: { params: RawDataRouteParams },
-) => {
- return {
- sidebar: getDataFocusSidebar(state, props),
- isSidebarLoading: getIsLoadingDatabaseTables(state, props),
- sidebarError: getLoadingDatabaseTablesError(state, props),
- };
-};
-
-interface DatabasesPermissionsPageInnerProps {
- sidebar: DataSidebarProps | null;
- params: RawDataRouteParams;
- navigateToItem: (item: any) => void;
- navigateToDatabaseList: () => void;
- switchView: (entityType: string) => void;
- updateDataPermission: (params: UpdateDataPermissionParams) => void;
- isSidebarLoading: boolean | undefined;
- sidebarError: string | undefined;
-}
+export function DatabasesPermissionsPage() {
+ const dispatch = useDispatch();
+
+ // These selectors resolve the focused database/schema/table from the route,
+ // so they take the route params rather than reading them from the store.
+ const params = useParams<RawDataRouteParams>();
+ const selectorProps = { params };
+ const sidebar = useSelector((state) =>
+ getDataFocusSidebar(state, selectorProps),
+ );
+ const isSidebarLoading = useSelector((state) =>
+ getIsLoadingDatabaseTables(state, selectorProps),
+ );
+ const sidebarError = useSelector((state) =>
+ getLoadingDatabaseTablesError(state, selectorProps),
+ );
-function DatabasesPermissionsPageInner({
- sidebar,
- params,
- navigateToItem,
- navigateToDatabaseList,
- switchView,
- updateDataPermission,
- isSidebarLoading,
- sidebarError,
-}: DatabasesPermissionsPageInnerProps) {
const dataRouteParams = parseDataRouteParams(params);
- const dispatch = useDispatch();
const permissionEditor = useSelector((state) =>
getGroupsDataPermissionEditor(state, { params: dataRouteParams }),
);
+ const navigateToItem = (item: ITreeNodeItem) =>
+ dispatch(
+ push(
+ getDatabaseFocusPermissionsUrl(
+ // The sidebar types `onSelect` with the base tree item, but every node
+ // it renders here comes from `getDataFocusSidebar`, which builds
+ // `DataTreeNodeItem`s carrying an `entityId`.
+ (item as DataTreeNodeItem).entityId,
+ ),
+ ),
+ );
+ const navigateToDatabaseList = () => dispatch(push(DATABASES_BASE_PATH));
+
const showSplitPermsMessage = useSelector((state) =>
getSetting(state, "show-updated-permission-banner"),
);
@@ -103,9 +88,9 @@ function DatabasesPermissionsPageInner({
const handleEntityChange = useCallback(
(entityType: string) => {
- switchView(entityType);
+ dispatch(push(`/admin/permissions/data/${entityType}`));
},
- [switchView],
+ [dispatch],
);
const handlePermissionChange = useCallback(
@@ -117,15 +102,17 @@ function DatabasesPermissionsPageInner({
if (!item.entityId) {
return;
}
- updateDataPermission({
- groupId: assertNumericId(item.id),
- permission,
- value,
- entityId: item.entityId,
- view: "database",
- });
+ dispatch(
+ updateDataPermission({
+ groupId: assertNumericId(item.id),
+ permission,
+ value,
+ entityId: item.entityId,
+ view: "database",
+ }),
+ );
},
- [updateDataPermission],
+ [dispatch],
);
const handleAction = (
@@ -194,7 +181,3 @@ function DatabasesPermissionsPageInner({
</Fragment>
);
}
-
-export const DatabasesPermissionsPage = _.compose(
- connect(mapStateToProps, mapDispatchToProps),
-)(DatabasesPermissionsPageInner);
diff --git a/frontend/src/metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage.tsx b/frontend/src/metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage.tsx
index b22301ac0c7..a22268b5203 100644
--- a/frontend/src/metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage.tsx
+++ b/frontend/src/metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage.tsx
@@ -1,16 +1,14 @@
import { Fragment, useCallback } from "react";
import { useAsync } from "react-use";
import { t } from "ttag";
-import _ from "underscore";
import { PermissionsEditorLegacyNoSelfServiceWarning } from "metabase/admin/permissions/components/PermissionsEditor/PermissionsEditorLegacyWarning";
+import type { ITreeNodeItem } from "metabase/common/components/tree/types";
import { PLUGIN_ADVANCED_PERMISSIONS } from "metabase/plugins";
-import { connect, useDispatch, useSelector } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import { Outlet, push } from "metabase/router";
+import { useDispatch, useSelector } from "metabase/redux";
+import { Outlet, push, useParams } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Center, Loader } from "metabase/ui";
-import type { GroupId } from "metabase-types/api";
import {
PermissionsEditor,
@@ -19,13 +17,10 @@ import {
import { PermissionsEditorSplitPermsMessage } from "../../components/PermissionsEditor/PermissionsEditorSplitPermsMessage";
import { PermissionsSidebar } from "../../components/PermissionsSidebar";
import {
- type UpdateDataPermissionParams,
loadDataPermissionsForGroup,
updateDataPermission,
} from "../../permissions";
import {
- type DataTreeNodeItem,
- type GroupSidebarProps,
getDatabasesPermissionEditor,
getGroupsSidebar,
getIsLoadingDatabaseTables,
@@ -45,57 +40,27 @@ import {
getGroupFocusPermissionsUrl,
} from "../../utils/urls";
-const mapDispatchToProps = {
- updateDataPermission,
- switchView: (entityType: string) =>
- push(`/admin/permissions/data/${entityType}/`),
- navigateToItem: (item: DataTreeNodeItem) =>
- push(`${GROUPS_BASE_PATH}/${item.id}`),
- navigateToTableItem: (
- item: PermissionEditorEntity,
- { groupId }: { groupId: GroupId },
- ) => {
- return push(getGroupFocusPermissionsUrl(groupId, item.entityId));
- },
-};
-
-const mapStateToProps = (
- state: State,
- props: { params: RawGroupRouteParams },
-) => {
- return {
- sidebar: getGroupsSidebar(state, props),
- isEditorLoading: getIsLoadingDatabaseTables(state, props),
- editorError: getLoadingDatabaseTablesError(state, props),
- };
-};
-
-interface GroupsPermissionsPageInnerProps {
- sidebar: GroupSidebarProps;
- params: RawGroupRouteParams;
- navigateToItem: (item: any) => void;
- switchView: (entityType: string) => void;
- navigateToTableItem: (
- item: PermissionEditorEntity,
- { groupId }: { groupId: GroupId },
- ) => void;
- updateDataPermission: (params: UpdateDataPermissionParams) => void;
- isEditorLoading: boolean | undefined;
- editorError: string | undefined;
-}
+export function GroupsPermissionsPage() {
+ const dispatch = useDispatch();
+
+ // These selectors resolve the focused group from the route, so they take the
+ // route params rather than reading them from the store.
+ const params = useParams<RawGroupRouteParams>();
+ const selectorProps = { params };
+ const sidebar = useSelector((state) =>
+ getGroupsSidebar(state, selectorProps),
+ );
+ const isEditorLoading = useSelector((state) =>
+ getIsLoadingDatabaseTables(state, selectorProps),
+ );
+ const editorError = useSelector((state) =>
+ getLoadingDatabaseTablesError(state, selectorProps),
+ );
-function GroupsPermissionsPageInner({
- sidebar,
- params,
- navigateToItem,
- switchView,
- navigateToTableItem,
- updateDataPermission,
- isEditorLoading,
- editorError,
-}: GroupsPermissionsPageInnerProps) {
const groupRouteParams = parseGroupRouteParams(params);
- const dispatch = useDispatch();
+
+ const navigateToItem = (item: ITreeNodeItem) =>
+ dispatch(push(`${GROUPS_BASE_PATH}/${item.id}`));
const { loading: isLoading } = useAsync(async () => {
if (groupRouteParams.groupId) {
@@ -112,9 +77,9 @@ function GroupsPermissionsPageInner({
const handleEntityChange = useCallback(
(entityType: string) => {
- switchView(entityType);
+ dispatch(push(`/admin/permissions/data/${entityType}/`));
},
- [switchView],
+ [dispatch],
);
const handleTableItemSelect = useCallback(
@@ -122,9 +87,13 @@ function GroupsPermissionsPageInner({
if (groupRouteParams.groupId == null) {
return;
}
- navigateToTableItem(item, { groupId: groupRouteParams.groupId });
+ dispatch(
+ push(
+ getGroupFocusPermissionsUrl(groupRouteParams.groupId, item.entityId),
+ ),
+ );
},
- [navigateToTableItem, groupRouteParams.groupId],
+ [dispatch, groupRouteParams.groupId],
);
const handlePermissionChange = useCallback(
@@ -136,15 +105,17 @@ function GroupsPermissionsPageInner({
if (item.entityId == null || groupRouteParams.groupId == null) {
return;
}
- updateDataPermission({
- groupId: groupRouteParams.groupId,
- permission,
- value,
- entityId: item.entityId,
- view: "group",
- });
+ dispatch(
+ updateDataPermission({
+ groupId: groupRouteParams.groupId,
+ permission,
+ value,
+ entityId: item.entityId,
+ view: "group",
+ }),
+ );
},
- [groupRouteParams.groupId, updateDataPermission],
+ [dispatch, groupRouteParams.groupId],
);
const handleAction = (
@@ -218,7 +189,3 @@ function GroupsPermissionsPageInner({
</Fragment>
);
}
-
-export const GroupsPermissionsPage = _.compose(
- connect(mapStateToProps, mapDispatchToProps),
-)(GroupsPermissionsPageInner);
diff --git a/frontend/src/metabase/admin/permissions/routes.tsx b/frontend/src/metabase/admin/permissions/routes.tsx
index bf3897cf830..0418d759563 100644
--- a/frontend/src/metabase/admin/permissions/routes.tsx
+++ b/frontend/src/metabase/admin/permissions/routes.tsx
@@ -6,22 +6,13 @@ import {
PLUGIN_ADMIN_PERMISSIONS_TABS,
PLUGIN_APPLICATION_PERMISSIONS,
} from "metabase/plugins";
-import { Route, redirect, withRouteProps } from "metabase/router";
+import { Route, redirect } from "metabase/router";
import { CollectionPermissionsPage } from "./pages/CollectionPermissionsPage/CollectionPermissionsPage";
import DataPermissionsPage from "./pages/DataPermissionsPage";
import { DatabasesPermissionsPage } from "./pages/DatabasePermissionsPage/DatabasesPermissionsPage";
import { GroupsPermissionsPage } from "./pages/GroupDataPermissionsPage/GroupsPermissionsPage";
-// These three read route params through `connect`'s `mapStateToProps`, so the
-// hooks cannot reach them. Migrating them means rewriting the connected
-// containers, tracked separately.
-const RoutedDatabasesPermissionsPage = withRouteProps(DatabasesPermissionsPage);
-const RoutedGroupsPermissionsPage = withRouteProps(GroupsPermissionsPage);
-const RoutedCollectionPermissionsPage = withRouteProps(
- CollectionPermissionsPage,
-);
-
// The permissions page renders at each drill-down depth with progressively more
// params. v3 expressed this with sequential optional groups
// (`database(/:databaseId)(/schema/:schemaName)`), which v7's matcher cannot
@@ -49,25 +40,21 @@ const getRoutes = () => (
<Route index element={redirect("group")} />
{DATABASES_PERMISSIONS_PATHS.map((path) => (
- <Route
- key={path}
- path={path}
- element={<RoutedDatabasesPermissionsPage />}
- >
+ <Route key={path} path={path} element={<DatabasesPermissionsPage />}>
{PLUGIN_ADMIN_PERMISSIONS_DATABASE_ROUTES}
{PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES}
</Route>
))}
{GROUPS_PERMISSIONS_PATHS.map((path) => (
- <Route key={path} path={path} element={<RoutedGroupsPermissionsPage />}>
+ <Route key={path} path={path} element={<GroupsPermissionsPage />}>
{PLUGIN_ADMIN_PERMISSIONS_DATABASE_GROUP_ROUTES}
{PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES}
</Route>
))}
</Route>
- <Route path="collections" element={<RoutedCollectionPermissionsPage />}>
+ <Route path="collections" element={<CollectionPermissionsPage />}>
<Route path=":collectionId" />
</Route>
diff --git a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx
index 4e549678648..37b9e2b9d56 100644
--- a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx
@@ -18,13 +18,9 @@ import DataPermissionsPage from "metabase/admin/permissions/pages/DataPermission
import { DatabasesPermissionsPage } from "metabase/admin/permissions/pages/DatabasePermissionsPage/DatabasesPermissionsPage";
import { BEFORE_UNLOAD_UNSAVED_MESSAGE } from "metabase/common/hooks/use-before-unload";
import { PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES } from "metabase/plugins";
-import { Route, withRouteProps } from "metabase/router";
+import { Route } from "metabase/router";
import { createMockGroup } from "metabase-types/api/mocks/group";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
-
-const RoutedDataPermissionsPage = withRouteProps(DataPermissionsPage);
-const RoutedDatabasesPermissionsPage = withRouteProps(DatabasesPermissionsPage);
-
const TEST_DATABASE = createSampleDatabase();
const TEST_GROUPS = [
@@ -49,10 +45,7 @@ const setup = async () => {
const mockEventListener = jest.spyOn(window, "addEventListener");
renderWithProviders(
- <Route
- path="/admin/permissions/data"
- element={<RoutedDataPermissionsPage />}
- >
+ <Route path="/admin/permissions/data" element={<DataPermissionsPage />}>
{/*
* v7 cannot parse v3 optional groups, so the app spells each depth out as
* its own route (see DATABASES_PERMISSIONS_PATHS in permissions/routes.tsx).
@@ -64,11 +57,7 @@ const setup = async () => {
"database/:databaseId/schema/:schemaName",
"database/:databaseId/schema/:schemaName/table/:tableId",
].map((path) => (
- <Route
- key={path}
- path={path}
- element={<RoutedDatabasesPermissionsPage />}
- >
+ <Route key={path} path={path} element={<DatabasesPermissionsPage />}>
{PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES}
</Route>
))}
diff --git a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx
index c2d288f9acf..b0b2b6376c4 100644
--- a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx
@@ -17,13 +17,9 @@ import DataPermissionsPage from "metabase/admin/permissions/pages/DataPermission
import { GroupsPermissionsPage } from "metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage";
import { BEFORE_UNLOAD_UNSAVED_MESSAGE } from "metabase/common/hooks/use-before-unload";
import { PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES } from "metabase/plugins";
-import { Route, withRouteProps } from "metabase/router";
+import { Route } from "metabase/router";
import { createMockGroup } from "metabase-types/api/mocks/group";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
-
-const RoutedDataPermissionsPage = withRouteProps(DataPermissionsPage);
-const RoutedGroupsPermissionsPage = withRouteProps(GroupsPermissionsPage);
-
const NATIVE_QUERIES_PERMISSION_INDEX = 0;
const TEST_DATABASE = createSampleDatabase();
@@ -52,10 +48,7 @@ const setup = async ({
const mockEventListener = jest.spyOn(window, "addEventListener");
renderWithProviders(
- <Route
- path="/admin/permissions/data"
- element={<RoutedDataPermissionsPage />}
- >
+ <Route path="/admin/permissions/data" element={<DataPermissionsPage />}>
{/*
* v7 cannot parse v3 optional groups, so the app spells each depth out as
* its own route (see GROUPS_PERMISSIONS_PATHS in permissions/routes.tsx).
@@ -67,7 +60,7 @@ const setup = async ({
"group/:groupId/database/:databaseId",
"group/:groupId/database/:databaseId/schema/:schemaName",
].map((path) => (
- <Route key={path} path={path} element={<RoutedGroupsPermissionsPage />}>
+ <Route key={path} path={path} element={<GroupsPermissionsPage />}>
{PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES}
</Route>
))}
diff --git a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx
index da7b1e518c3..441d767f445 100644
--- a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx
+++ b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx
@@ -14,13 +14,9 @@ import {
} from "__support__/ui";
import DataPermissionsPage from "metabase/admin/permissions/pages/DataPermissionsPage/DataPermissionsPage";
import { GroupsPermissionsPage } from "metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage";
-import { Route, withRouteProps } from "metabase/router";
+import { Route } from "metabase/router";
import { createMockGroup } from "metabase-types/api/mocks/group";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
-
-const RoutedDataPermissionsPage = withRouteProps(DataPermissionsPage);
-const RoutedGroupsPermissionsPage = withRouteProps(GroupsPermissionsPage);
-
const TEST_DATABASE = createSampleDatabase();
const TEST_TABLES = TEST_DATABASE.tables ?? [];
@@ -52,16 +48,9 @@ const setup = () => {
);
return renderWithProviders(
- <Route
- path="/admin/permissions/data"
- element={<RoutedDataPermissionsPage />}
- >
+ <Route path="/admin/permissions/data" element={<DataPermissionsPage />}>
{GROUPS_PERMISSIONS_PATHS.map((path) => (
- <Route
- key={path}
- path={path}
- element={<RoutedGroupsPermissionsPage />}
- />
+ <Route key={path} path={path} element={<GroupsPermissionsPage />} />
))}
</Route>,
{
diff --git a/frontend/src/metabase/app/nav/AppBar.tsx b/frontend/src/metabase/app/nav/AppBar.tsx
index 886d4dc0db5..03bec24b67c 100644
--- a/frontend/src/metabase/app/nav/AppBar.tsx
+++ b/frontend/src/metabase/app/nav/AppBar.tsx
@@ -18,7 +18,6 @@ import {
} from "metabase/documents/selectors";
import { getMetabotVisible } from "metabase/metabot/state";
import { AppBar as AppBarView } from "metabase/nav/components/AppBar";
-import type { AppBarProps } from "metabase/nav/components/AppBar/AppBar";
import { CollectionBreadcrumbs } from "metabase/nav/containers/CollectionBreadcrumbs";
import { isQuestionPath } from "metabase/nav/containers/MainNavbar/getSelectedItems";
import { zoomInRow } from "metabase/query_builder/actions";
@@ -26,11 +25,9 @@ import {
getOriginalQuestion,
getQuestion,
} from "metabase/query_builder/selectors";
-import { connect, useDispatch, useSelector } from "metabase/redux";
+import { useDispatch, useSelector } from "metabase/redux";
import { closeNavbar, toggleNavbar } from "metabase/redux/app";
-import type { State } from "metabase/redux/store";
-import { push, withRouteProps } from "metabase/router";
-import type { RouterProps } from "metabase/selectors/app";
+import { push, useRouter } from "metabase/router";
import { getDetailViewState, getIsNavbarOpen } from "metabase/selectors/app";
import { getIsEmbeddingIframe } from "metabase/selectors/embed";
import { getUser } from "metabase/selectors/user";
@@ -56,32 +53,42 @@ export function getSearchResultSelection(
return { type: "navigate", url: modelToUrl(result) };
}
-const mapStateToProps = (state: State, props: RouterProps) => ({
- currentUser: getUser(state),
- isNavBarOpen: getIsNavbarOpen(state),
- isNavBarEnabled: getIsNavBarEnabled(state, props),
- isMetabotVisible: getMetabotVisible(state, "omnibot"),
- isDocumentSidebarOpen: getSidebarOpen(state),
- isCommentSidebarOpen: getCommentSidebarOpen(state),
- isLogoVisible: getIsLogoVisible(state),
- isSearchVisible: getIsSearchVisible(state),
- isEmbeddingIframe: getIsEmbeddingIframe(state),
- isNewButtonVisible: getIsNewButtonVisible(state),
- isAppSwitcherVisible: getIsAppSwitcherVisible(state),
- isCollectionPathVisible: getIsCollectionPathVisible(state, props),
- isQuestionLineageVisible: getIsQuestionLineageVisible(state, props),
- detailView: getDetailViewState(state),
- isMetricsViewer: getIsMetricsViewer(state, props),
-});
+export function AppBarContainer() {
+ const dispatch = useDispatch();
-const mapDispatchToProps = {
- onToggleNavbar: toggleNavbar,
- onCloseNavbar: closeNavbar,
-};
+ // 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 routerProps = { location };
+ const collectionId =
+ useInitialCollectionId({ location, params }) ?? undefined;
+
+ const currentUser = useSelector(getUser);
+ const isNavBarOpen = useSelector(getIsNavbarOpen);
+ const isNavBarEnabled = useSelector((state) =>
+ getIsNavBarEnabled(state, routerProps),
+ );
+ const isMetabotVisible = useSelector((state) =>
+ getMetabotVisible(state, "omnibot"),
+ );
+ const isDocumentSidebarOpen = useSelector(getSidebarOpen);
+ const isCommentSidebarOpen = useSelector(getCommentSidebarOpen);
+ const isLogoVisible = useSelector(getIsLogoVisible);
+ const isSearchVisible = useSelector(getIsSearchVisible);
+ const isEmbeddingIframe = useSelector(getIsEmbeddingIframe);
+ const isNewButtonVisible = useSelector(getIsNewButtonVisible);
+ const isAppSwitcherVisible = useSelector(getIsAppSwitcherVisible);
+ const isCollectionPathVisible = useSelector((state) =>
+ getIsCollectionPathVisible(state, routerProps),
+ );
+ const isQuestionLineageVisible = useSelector((state) =>
+ getIsQuestionLineageVisible(state, routerProps),
+ );
+ const detailView = useSelector(getDetailViewState);
+ const isMetricsViewer = useSelector((state) =>
+ getIsMetricsViewer(state, routerProps),
+ );
-function AppBarContainerInner(props: AppBarProps & RouterProps) {
- const collectionId = useInitialCollectionId(props) ?? undefined;
- const dispatch = useDispatch();
const question = useSelector(getQuestion);
const originalQuestion = useSelector(getOriginalQuestion);
// The breadcrumbs' current collection is derived from the active
@@ -90,7 +97,7 @@ function AppBarContainerInner(props: AppBarProps & RouterProps) {
// app tier, so the app-tier AppBar resolves it and passes it down.
const breadcrumbCollectionId = useSelector(getCollectionId);
- const { pathname } = props.location;
+ const { pathname } = location;
const isOnQuestionPage = pathname && isQuestionPath(pathname);
const dashboardId = isOnQuestionPage ? question?.dashboard()?.id : undefined;
const { data: dashboard } = useGetDashboardQuery(
@@ -98,7 +105,7 @@ function AppBarContainerInner(props: AppBarProps & RouterProps) {
);
// Unjustified type cast. FIXME
- const locationState = props.location.state as { cardId?: number } | undefined;
+ const locationState = location.state as { cardId?: number } | undefined;
const onSearchItemSelect = (result: SearchResult) => {
const selection = getSearchResultSelection(result, locationState?.cardId);
@@ -111,7 +118,23 @@ function AppBarContainerInner(props: AppBarProps & RouterProps) {
return (
<AppBarView
- {...props}
+ currentUser={currentUser}
+ isNavBarOpen={isNavBarOpen}
+ isNavBarEnabled={isNavBarEnabled}
+ isMetabotVisible={isMetabotVisible}
+ isDocumentSidebarOpen={isDocumentSidebarOpen}
+ isCommentSidebarOpen={isCommentSidebarOpen}
+ isLogoVisible={isLogoVisible}
+ isSearchVisible={isSearchVisible}
+ isEmbeddingIframe={isEmbeddingIframe}
+ isNewButtonVisible={isNewButtonVisible}
+ isAppSwitcherVisible={isAppSwitcherVisible}
+ isCollectionPathVisible={isCollectionPathVisible}
+ isQuestionLineageVisible={isQuestionLineageVisible}
+ detailView={detailView}
+ isMetricsViewer={isMetricsViewer}
+ onToggleNavbar={() => dispatch(toggleNavbar())}
+ onCloseNavbar={() => dispatch(closeNavbar())}
collectionId={collectionId}
collectionBreadcrumbs={
<CollectionBreadcrumbs
@@ -129,7 +152,3 @@ function AppBarContainerInner(props: AppBarProps & RouterProps) {
/>
);
}
-
-export const AppBarContainer = withRouteProps(
- connect(mapStateToProps, mapDispatchToProps)(AppBarContainerInner),
-);
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx b/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx
index e02805fd2c7..8138db950ad 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx
@@ -1,5 +1,6 @@
import dayjs from "dayjs";
import fetchMock from "fetch-mock";
+import type { ComponentProps } from "react";
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
@@ -25,7 +26,7 @@ import {
createMockQueryBuilderState,
createMockState,
} from "metabase/redux/store/mocks";
-import { Route, withRouteProps } from "metabase/router";
+import { Route, useRouter } from "metabase/router";
import * as iframeUtils from "metabase/utils/iframe";
import type {
Card,
@@ -43,7 +44,13 @@ import {
import { MainNavbar } from "../MainNavbar";
-const RoutedMainNavbar = withRouteProps(MainNavbar);
+/** Feeds `MainNavbar` its route props the way `Navbar` does in the app. */
+function RoutedMainNavbar(
+ props: Omit<ComponentProps<typeof MainNavbar>, "location" | "params">,
+) {
+ const { location, params } = useRouter();
+ return <MainNavbar {...props} location={location} params={params} />;
+}
export type SetupOpts = {
pathname?: string;
diff --git a/frontend/src/metabase/reference/databases/DatabaseDetail.tsx b/frontend/src/metabase/reference/databases/DatabaseDetail.tsx
index 16c98b95ebc..24df4e62e82 100644
--- a/frontend/src/metabase/reference/databases/DatabaseDetail.tsx
+++ b/frontend/src/metabase/reference/databases/DatabaseDetail.tsx
@@ -56,7 +56,7 @@ const mapDispatchToProps = {
};
interface DatabaseDetailProps {
- style: React.CSSProperties;
+ style?: React.CSSProperties;
entity: StubbedDatabase;
user: User | null;
isEditing?: boolean;
diff --git a/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx b/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx
index 6f337662655..59871a6be8f 100644
--- a/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx
+++ b/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx
@@ -1,102 +1,77 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import DatabaseDetail from "metabase/reference/databases/DatabaseDetail";
import * as actions from "metabase/reference/reference";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getDatabase,
getDatabaseId,
getIsEditing,
} from "../selectors";
-import type { StubbedDatabase } from "../types";
import DatabaseSidebar from "./DatabaseSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface DatabaseDetailContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- database: StubbedDatabase;
- databaseId: number;
- isEditing?: boolean;
-
- // From mapDispatchToProps (metadataActions spread)
fetchDatabaseMetadata: (id: number) => Promise<unknown>;
}
-class DatabaseDetailContainer extends Component<DatabaseDetailContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchDatabaseMetadata(this.props, this.props.databaseId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function DatabaseDetailContainer(props: DatabaseDetailContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const database = useSelector((state) => getDatabase(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchDatabaseMetadata(props, databaseId);
}
- UNSAFE_componentWillReceiveProps(newProps: DatabaseDetailContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { database, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<DatabaseSidebar database={database} />}
- >
- <DatabaseDetail {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<DatabaseSidebar database={database} />}
+ >
+ <DatabaseDetail params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- DatabaseDetailContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(DatabaseDetailContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/databases/DatabaseDetailContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/DatabaseDetailContainer.unit.spec.tsx
new file mode 100644
index 00000000000..e62735f4733
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/DatabaseDetailContainer.unit.spec.tsx
@@ -0,0 +1,34 @@
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockDatabase } from "metabase-types/api/mocks";
+
+import DatabaseDetailContainer from "./DatabaseDetailContainer";
+
+const DATABASE = createMockDatabase({ id: 1, name: "Test Database" });
+
+function setup() {
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/databases/:databaseId"
+ element={<DatabaseDetailContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/databases/${DATABASE.id}`,
+ },
+ );
+}
+
+describe("DatabaseDetailContainer", () => {
+ it("renders the detail view for the database named by the route param", async () => {
+ setup();
+
+ expect(await screen.findAllByText("Test Database")).not.toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/reference/databases/FieldDetail.tsx b/frontend/src/metabase/reference/databases/FieldDetail.tsx
index 6ca234feec6..920f09dd203 100644
--- a/frontend/src/metabase/reference/databases/FieldDetail.tsx
+++ b/frontend/src/metabase/reference/databases/FieldDetail.tsx
@@ -286,9 +286,19 @@ const FieldDetail = (props: FieldDetailProps) => {
);
};
+// What the container has to supply: `params` feeds `mapStateToProps`, and
+// `metadata` is read here but selected by the container. Naming it keeps that
+// contract type-checked.
+type FieldDetailOwnProps = ReferenceRouteProps &
+ Pick<FieldDetailProps, "metadata">;
+
// eslint-disable-next-line import/no-default-export -- deprecated usage
export default connect(
mapStateToProps,
mapDispatchToProps,
- // Unjustified type cast. FIXME
-)(FieldDetail as unknown as React.ComponentType);
+)(
+ // connect HOC tangle: the `metadataActions` / `actions` spreads in
+ // `mapDispatchToProps` are untyped, so the dispatch props can't be matched
+ // against the component's own props.
+ FieldDetail as unknown as React.ComponentType<FieldDetailOwnProps>,
+);
diff --git a/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx b/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx
index 9fe36bc40d8..23be59f4b25 100644
--- a/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx
+++ b/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx
@@ -1,110 +1,84 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import FieldDetail from "metabase/reference/databases/FieldDetail";
import * as actions from "metabase/reference/reference";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getDatabase,
getDatabaseId,
getField,
getIsEditing,
getTable,
} from "../selectors";
-import type { StubbedDatabase, StubbedField, StubbedTable } from "../types";
import FieldSidebar from "./FieldSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- table: getTable(state, props),
- field: getField(state, props),
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
- metadata: getMetadata(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface FieldDetailContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- database: StubbedDatabase;
- databaseId: number;
- table: StubbedTable;
- field: StubbedField;
- isEditing?: boolean;
-
- // From mapDispatchToProps (metadataActions spread)
fetchDatabaseMetadata: (id: number) => Promise<unknown>;
}
-class FieldDetailContainer extends Component<FieldDetailContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchDatabaseMetadata(this.props, this.props.databaseId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function FieldDetailContainer(props: FieldDetailContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const database = useSelector((state) => getDatabase(state, { params }));
+ const table = useSelector((state) => getTable(state, { params }));
+ const field = useSelector((state) => getField(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+ // `FieldDetail` reads `metadata` but doesn't select it itself.
+ const metadata = useSelector(getMetadata);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchDatabaseMetadata(props, databaseId);
}
- UNSAFE_componentWillReceiveProps(newProps: FieldDetailContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { database, table, field, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={
- <FieldSidebar database={database} table={table} field={field} />
- }
- >
- <FieldDetail {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<FieldSidebar database={database} table={table} field={field} />}
+ >
+ <FieldDetail params={params} metadata={metadata} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- // Unjustified type cast. FIXME
- )(FieldDetailContainer as unknown as React.ComponentType<InjectedRouteProps>),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(FieldDetailContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/databases/FieldDetailContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/FieldDetailContainer.unit.spec.tsx
new file mode 100644
index 00000000000..231350a5ac3
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/FieldDetailContainer.unit.spec.tsx
@@ -0,0 +1,55 @@
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import {
+ createMockDatabase,
+ createMockField,
+ createMockTable,
+} from "metabase-types/api/mocks";
+
+import FieldDetailContainer from "./FieldDetailContainer";
+
+const TOTAL = createMockField({
+ id: 100,
+ name: "TOTAL",
+ display_name: "Total",
+ table_id: 10,
+});
+
+const TABLE = createMockTable({ id: 10, db_id: 1, fields: [TOTAL] });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+function setup() {
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/databases/:databaseId/tables/:tableId/fields/:fieldId"
+ element={<FieldDetailContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/databases/${DATABASE.id}/tables/${TABLE.id}/fields/${TOTAL.id}`,
+ },
+ );
+}
+
+describe("FieldDetailContainer", () => {
+ // `FieldDetail` reads `metadata` but doesn't select it, so the page blanks if
+ // the container stops passing it down.
+ it("renders the field named by the route params", async () => {
+ setup();
+
+ expect(await screen.findAllByText("Total")).not.toHaveLength(0);
+ });
+
+ it("offers the x-ray link from the sidebar", async () => {
+ setup();
+
+ expect(await screen.findByText("X-ray this field")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/databases/FieldListContainer.tsx b/frontend/src/metabase/reference/databases/FieldListContainer.tsx
index 690d22f6fe6..1e8cf79c946 100644
--- a/frontend/src/metabase/reference/databases/FieldListContainer.tsx
+++ b/frontend/src/metabase/reference/databases/FieldListContainer.tsx
@@ -1,103 +1,79 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import FieldList from "metabase/reference/databases/FieldList";
import * as actions from "metabase/reference/reference";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getDatabase,
getDatabaseId,
getIsEditing,
getTable,
} from "../selectors";
-import type { StubbedDatabase, StubbedTable } from "../types";
import TableSidebar from "./TableSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- table: getTable(state, props),
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface FieldListContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- database: StubbedDatabase;
- databaseId: number;
- table: StubbedTable;
- isEditing?: boolean;
-
- // From mapDispatchToProps (metadataActions spread)
fetchDatabaseMetadata: (id: number) => Promise<unknown>;
}
-class FieldListContainer extends Component<FieldListContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchDatabaseMetadata(this.props, this.props.databaseId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function FieldListContainer(props: FieldListContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const database = useSelector((state) => getDatabase(state, { params }));
+ const table = useSelector((state) => getTable(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchDatabaseMetadata(props, databaseId);
}
- UNSAFE_componentWillReceiveProps(newProps: FieldListContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { database, table, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<TableSidebar database={database} table={table} />}
- >
- <FieldList {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<TableSidebar database={database} table={table} />}
+ >
+ <FieldList params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- // Unjustified type cast. FIXME
- )(FieldListContainer as unknown as React.ComponentType<InjectedRouteProps>),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(FieldListContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/databases/FieldListContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/FieldListContainer.unit.spec.tsx
new file mode 100644
index 00000000000..124684d3e19
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/FieldListContainer.unit.spec.tsx
@@ -0,0 +1,53 @@
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import {
+ createMockDatabase,
+ createMockField,
+ createMockTable,
+} from "metabase-types/api/mocks";
+
+import FieldListContainer from "./FieldListContainer";
+
+const TOTAL = createMockField({
+ id: 100,
+ name: "TOTAL",
+ display_name: "Total",
+ table_id: 10,
+});
+
+const TABLE = createMockTable({
+ id: 10,
+ db_id: 1,
+ display_name: "Orders",
+ fields: [TOTAL],
+});
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+function setup() {
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/databases/:databaseId/tables/:tableId/fields"
+ element={<FieldListContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/databases/${DATABASE.id}/tables/${TABLE.id}/fields`,
+ },
+ );
+}
+
+describe("FieldListContainer", () => {
+ it("lists the fields of the table named by the route params", async () => {
+ setup();
+
+ expect(await screen.findAllByText("Fields in Orders")).not.toHaveLength(0);
+ expect(await screen.findByText("Total")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/databases/TableDetailContainer.tsx b/frontend/src/metabase/reference/databases/TableDetailContainer.tsx
index 120da28ff56..5f1b00ef1f1 100644
--- a/frontend/src/metabase/reference/databases/TableDetailContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableDetailContainer.tsx
@@ -1,103 +1,79 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import TableDetail from "metabase/reference/databases/TableDetail";
import * as actions from "metabase/reference/reference";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getDatabase,
getDatabaseId,
getIsEditing,
getTable,
} from "../selectors";
-import type { StubbedDatabase, StubbedTable } from "../types";
import TableSidebar from "./TableSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- table: getTable(state, props),
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface TableDetailContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- database: StubbedDatabase;
- databaseId: number;
- table: StubbedTable;
- isEditing?: boolean;
-
- // From mapDispatchToProps (metadataActions spread)
fetchDatabaseMetadata: (id: number) => Promise<unknown>;
}
-class TableDetailContainer extends Component<TableDetailContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchDatabaseMetadata(this.props, this.props.databaseId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function TableDetailContainer(props: TableDetailContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const database = useSelector((state) => getDatabase(state, { params }));
+ const table = useSelector((state) => getTable(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchDatabaseMetadata(props, databaseId);
}
- UNSAFE_componentWillReceiveProps(newProps: TableDetailContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { database, table, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<TableSidebar database={database} table={table} />}
- >
- <TableDetail {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<TableSidebar database={database} table={table} />}
+ >
+ <TableDetail params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- // Unjustified type cast. FIXME
- )(TableDetailContainer as unknown as React.ComponentType<InjectedRouteProps>),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(TableDetailContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/databases/TableDetailContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/TableDetailContainer.unit.spec.tsx
new file mode 100644
index 00000000000..5d34a396eec
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/TableDetailContainer.unit.spec.tsx
@@ -0,0 +1,39 @@
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockDatabase, createMockTable } from "metabase-types/api/mocks";
+
+const TABLE = createMockTable({ id: 10, db_id: 1, display_name: "Orders" });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+import TableDetailContainer from "./TableDetailContainer";
+
+function setup() {
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/databases/:databaseId/tables/:tableId"
+ element={<TableDetailContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/databases/${DATABASE.id}/tables/${TABLE.id}`,
+ },
+ );
+}
+
+describe("TableDetailContainer", () => {
+ it("renders the detail view for the table named by the route params", async () => {
+ setup();
+
+ expect(await screen.findAllByText("Orders")).not.toHaveLength(0);
+ expect(
+ await screen.findByText("Actual name in database"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/databases/TableListContainer.tsx b/frontend/src/metabase/reference/databases/TableListContainer.tsx
index 079770fcabb..ba2a1a90674 100644
--- a/frontend/src/metabase/reference/databases/TableListContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableListContainer.tsx
@@ -1,100 +1,77 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import TableList from "metabase/reference/databases/TableList";
import * as actions from "metabase/reference/reference";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getDatabase,
getDatabaseId,
getIsEditing,
} from "../selectors";
-import type { StubbedDatabase } from "../types";
import DatabaseSidebar from "./DatabaseSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface TableListContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- database: StubbedDatabase;
- databaseId: number;
- isEditing?: boolean;
-
- // From mapDispatchToProps (metadataActions spread)
fetchDatabaseMetadata: (id: number) => Promise<unknown>;
}
-class TableListContainer extends Component<TableListContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchDatabaseMetadata(this.props, this.props.databaseId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function TableListContainer(props: TableListContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const database = useSelector((state) => getDatabase(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchDatabaseMetadata(props, databaseId);
}
- UNSAFE_componentWillReceiveProps(newProps: TableListContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { database, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<DatabaseSidebar database={database} />}
- >
- <TableList {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<DatabaseSidebar database={database} />}
+ >
+ <TableList params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- // Unjustified type cast. FIXME
- )(TableListContainer as unknown as React.ComponentType<InjectedRouteProps>),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(TableListContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx
new file mode 100644
index 00000000000..d37db14e517
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx
@@ -0,0 +1,49 @@
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockDatabase, createMockTable } from "metabase-types/api/mocks";
+
+import TableListContainer from "./TableListContainer";
+
+const ORDERS = createMockTable({ id: 1, db_id: 1, display_name: "Orders" });
+const PEOPLE = createMockTable({ id: 2, db_id: 1, display_name: "People" });
+
+const DATABASE = createMockDatabase({
+ id: 1,
+ name: "Test Database",
+ tables: [ORDERS, PEOPLE],
+});
+
+function setup({ databaseId = DATABASE.id } = {}) {
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/databases/:databaseId/tables"
+ element={<TableListContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/databases/${databaseId}/tables`,
+ },
+ );
+}
+
+describe("TableListContainer", () => {
+ it("fetches metadata for the database in the route and lists its tables", async () => {
+ setup();
+
+ expect(await screen.findByText("Orders")).toBeInTheDocument();
+ expect(screen.getByText("People")).toBeInTheDocument();
+ });
+
+ it("resolves the database from the route param, not from a prop", async () => {
+ setup();
+
+ // The name only reaches the header if `useParams` fed `getDatabase`.
+ expect(
+ await screen.findAllByText("Tables in Test Database"),
+ ).not.toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
index e6f72b28598..18cbe8a884d 100644
--- a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
@@ -1,45 +1,29 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import { cardApi } from "metabase/api";
import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import type { Dispatch } from "metabase/redux/store";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import TableQuestions from "metabase/reference/databases/TableQuestions";
import * as actions from "metabase/reference/reference";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getDatabase,
getDatabaseId,
getIsEditing,
getTable,
} from "../selectors";
-import type { StubbedDatabase, StubbedTable } from "../types";
import TableSidebar from "./TableSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- table: getTable(state, props),
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
fetchQuestions: () => (dispatch: Dispatch) =>
runRtkEndpoint({}, dispatch, cardApi.endpoints.listCards),
@@ -48,67 +32,54 @@ const mapDispatchToProps = {
};
interface TableQuestionsContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- database: StubbedDatabase;
- databaseId: number;
- table: StubbedTable;
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchDatabaseMetadata: (id: number) => Promise<unknown>;
fetchQuestions: () => Promise<unknown>;
}
-class TableQuestionsContainer extends Component<TableQuestionsContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchDatabaseMetadataAndQuestion(
- this.props,
- this.props.databaseId,
- );
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function TableQuestionsContainer(props: TableQuestionsContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const database = useSelector((state) => getDatabase(state, { params }));
+ const table = useSelector((state) => getTable(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchDatabaseMetadataAndQuestion(props, databaseId);
}
- UNSAFE_componentWillReceiveProps(newProps: TableQuestionsContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { database, table, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<TableSidebar database={database} table={table} />}
- >
- <TableQuestions {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<TableSidebar database={database} table={table} />}
+ >
+ <TableQuestions params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- TableQuestionsContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(TableQuestionsContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/databases/TableQuestionsContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/TableQuestionsContainer.unit.spec.tsx
new file mode 100644
index 00000000000..4eca5ff6101
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/TableQuestionsContainer.unit.spec.tsx
@@ -0,0 +1,39 @@
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockDatabase, createMockTable } from "metabase-types/api/mocks";
+
+import TableQuestionsContainer from "./TableQuestionsContainer";
+
+const TABLE = createMockTable({ id: 10, db_id: 1, display_name: "Orders" });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+function setup() {
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+ fetchMock.get("path:/api/card", []);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/databases/:databaseId/tables/:tableId/questions"
+ element={<TableQuestionsContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/databases/${DATABASE.id}/tables/${TABLE.id}/questions`,
+ },
+ );
+}
+
+describe("TableQuestionsContainer", () => {
+ it("renders the questions view for the table named by the route params", async () => {
+ setup();
+
+ expect(
+ await screen.findAllByText("Questions about Orders"),
+ ).not.toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/reference/segments/SegmentDetailContainer.tsx b/frontend/src/metabase/reference/segments/SegmentDetailContainer.tsx
index 13e451e875a..f364c7cd7a6 100644
--- a/frontend/src/metabase/reference/segments/SegmentDetailContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentDetailContainer.tsx
@@ -1,106 +1,79 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import * as actions from "metabase/reference/reference";
import SegmentDetail from "metabase/reference/segments/SegmentDetail";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
-import type { User } from "metabase-types/api";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getIsEditing,
getSegment,
getSegmentId,
getUser,
} from "../selectors";
-import type { StubbedSegment } from "../types";
import SegmentSidebar from "./SegmentSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- user: getUser(state),
- segment: getSegment(state, props),
- segmentId: getSegmentId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface SegmentDetailContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- user: User | null;
- segment: StubbedSegment;
- segmentId: number;
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchSegmentTable: (id: number) => Promise<unknown>;
}
-class SegmentDetailContainer extends Component<SegmentDetailContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchSegmentDetail(this.props, this.props.segmentId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function SegmentDetailContainer(props: SegmentDetailContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const user = useSelector(getUser);
+ const segment = useSelector((state) => getSegment(state, { params }));
+ const segmentId = useSelector((state) => getSegmentId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchSegmentDetail(props, segmentId);
}
- UNSAFE_componentWillReceiveProps(newProps: SegmentDetailContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { user, segment, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<SegmentSidebar segment={segment} user={user} />}
- >
- <SegmentDetail {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<SegmentSidebar segment={segment} user={user} />}
+ >
+ <SegmentDetail params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- SegmentDetailContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(SegmentDetailContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/segments/SegmentDetailContainer.unit.spec.tsx b/frontend/src/metabase/reference/segments/SegmentDetailContainer.unit.spec.tsx
new file mode 100644
index 00000000000..85141c1a29a
--- /dev/null
+++ b/frontend/src/metabase/reference/segments/SegmentDetailContainer.unit.spec.tsx
@@ -0,0 +1,56 @@
+import {
+ setupSegmentsEndpoints,
+ setupTableEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockSegment, createMockTable } from "metabase-types/api/mocks";
+
+import SegmentDetailContainer from "./SegmentDetailContainer";
+
+const TABLE = createMockTable({ id: 10, db_id: 1 });
+
+const SEGMENT = createMockSegment({
+ id: 1,
+ name: "Active subscribers",
+ table_id: TABLE.id,
+});
+
+const OTHER_SEGMENT = createMockSegment({
+ id: 2,
+ name: "Churned accounts",
+ table_id: TABLE.id,
+});
+
+function setup({ segmentId = SEGMENT.id } = {}) {
+ setupSegmentsEndpoints([SEGMENT, OTHER_SEGMENT]);
+ setupTableEndpoints(TABLE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/segments/:segmentId"
+ element={<SegmentDetailContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/segments/${segmentId}`,
+ },
+ );
+}
+
+describe("SegmentDetailContainer", () => {
+ it("shows the segment named by the route param", async () => {
+ setup();
+
+ expect(await screen.findAllByText("Active subscribers")).not.toHaveLength(
+ 0,
+ );
+ });
+
+ it("selects the segment by id, so a different param shows a different segment", async () => {
+ setup({ segmentId: OTHER_SEGMENT.id });
+
+ expect(await screen.findAllByText("Churned accounts")).not.toHaveLength(0);
+ expect(screen.queryByText("Active subscribers")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.tsx b/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.tsx
index 6be64ddcc95..5b54f15fc17 100644
--- a/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.tsx
@@ -1,107 +1,81 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import * as actions from "metabase/reference/reference";
import SegmentFieldDetail from "metabase/reference/segments/SegmentFieldDetail";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getField,
getIsEditing,
getSegment,
getSegmentId,
} from "../selectors";
-import type { StubbedField, StubbedSegment } from "../types";
import SegmentFieldSidebar from "./SegmentFieldSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- segment: getSegment(state, props),
- segmentId: getSegmentId(state, props),
- field: getField(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface SegmentFieldDetailContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- segment: StubbedSegment;
- segmentId: number;
- field: StubbedField;
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchSegments: (id?: number) => Promise<unknown>;
fetchSegmentFields: (id: number) => Promise<unknown>;
fetchSegmentTable: (id: number) => Promise<unknown>;
}
-class SegmentFieldDetailContainer extends Component<SegmentFieldDetailContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchSegmentFields(this.props, this.props.segmentId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function SegmentFieldDetailContainer(props: SegmentFieldDetailContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const segment = useSelector((state) => getSegment(state, { params }));
+ const segmentId = useSelector((state) => getSegmentId(state, { params }));
+ const field = useSelector((state) => getField(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchSegmentFields(props, segmentId);
}
- UNSAFE_componentWillReceiveProps(newProps: SegmentFieldDetailContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { segment, field, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<SegmentFieldSidebar segment={segment} field={field} />}
- >
- <SegmentFieldDetail {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<SegmentFieldSidebar segment={segment} field={field} />}
+ >
+ <SegmentFieldDetail params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- SegmentFieldDetailContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(SegmentFieldDetailContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.unit.spec.tsx b/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.unit.spec.tsx
new file mode 100644
index 00000000000..c2b89999ab6
--- /dev/null
+++ b/frontend/src/metabase/reference/segments/SegmentFieldDetailContainer.unit.spec.tsx
@@ -0,0 +1,61 @@
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseEndpoints,
+ setupSegmentsEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import {
+ createMockDatabase,
+ createMockField,
+ createMockSegment,
+ createMockTable,
+} from "metabase-types/api/mocks";
+
+import SegmentFieldDetailContainer from "./SegmentFieldDetailContainer";
+
+const TOTAL = createMockField({
+ id: 100,
+ name: "TOTAL",
+ display_name: "Total",
+ table_id: 10,
+});
+
+const TABLE = createMockTable({ id: 10, db_id: 1, fields: [TOTAL] });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+const SEGMENT = createMockSegment({
+ id: 1,
+ name: "Orders < 100",
+ table_id: TABLE.id,
+});
+
+function setup() {
+ setupSegmentsEndpoints([SEGMENT]);
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/segments/:segmentId/fields/:fieldId"
+ element={<SegmentFieldDetailContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/segments/${SEGMENT.id}/fields/${TOTAL.id}`,
+ },
+ );
+}
+
+describe("SegmentFieldDetailContainer", () => {
+ it("renders the detail view for the field named by the route params", async () => {
+ setup();
+
+ expect(await screen.findAllByText("Total")).not.toHaveLength(0);
+ expect(
+ await screen.findByText("Actual name in database"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/segments/SegmentFieldList.tsx b/frontend/src/metabase/reference/segments/SegmentFieldList.tsx
index d121d5a1db9..b316dc3bf8c 100644
--- a/frontend/src/metabase/reference/segments/SegmentFieldList.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentFieldList.tsx
@@ -211,9 +211,19 @@ const SegmentFieldList = (props: SegmentFieldListProps) => {
);
};
+// What the container has to supply: `params` feeds `mapStateToProps`, and
+// `table` is read here but selected by the container. Naming it keeps that
+// contract type-checked.
+type SegmentFieldListOwnProps = ReferenceRouteProps &
+ Pick<SegmentFieldListProps, "table">;
+
// eslint-disable-next-line import/no-default-export -- deprecated usage
export default connect(
mapStateToProps,
mapDispatchToProps,
- // Unjustified type cast. FIXME
-)(SegmentFieldList as unknown as React.ComponentType);
+)(
+ // connect HOC tangle: the `metadataActions` / `actions` spreads in
+ // `mapDispatchToProps` are untyped, so the dispatch props can't be matched
+ // against the component's own props.
+ SegmentFieldList as unknown as React.ComponentType<SegmentFieldListOwnProps>,
+);
diff --git a/frontend/src/metabase/reference/segments/SegmentFieldListContainer.tsx b/frontend/src/metabase/reference/segments/SegmentFieldListContainer.tsx
index 3369341a0f0..6486ee03db7 100644
--- a/frontend/src/metabase/reference/segments/SegmentFieldListContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentFieldListContainer.tsx
@@ -1,111 +1,84 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import * as actions from "metabase/reference/reference";
import SegmentFieldList from "metabase/reference/segments/SegmentFieldList";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
-import type { User } from "metabase-types/api";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getIsEditing,
getSegment,
getSegmentId,
getTable,
getUser,
} from "../selectors";
-import type { StubbedSegment, StubbedTable } from "../types";
import SegmentSidebar from "./SegmentSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- user: getUser(state),
- segment: getSegment(state, props),
- segmentId: getSegmentId(state, props),
- table: getTable(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface SegmentFieldListContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- user: User | null;
- segment: StubbedSegment;
- segmentId: number;
- table: StubbedTable;
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchSegments: (id?: number) => Promise<unknown>;
fetchSegmentFields: (id: number) => Promise<unknown>;
fetchSegmentTable: (id: number) => Promise<unknown>;
}
-class SegmentFieldListContainer extends Component<SegmentFieldListContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchSegmentFields(this.props, this.props.segmentId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function SegmentFieldListContainer(props: SegmentFieldListContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const user = useSelector(getUser);
+ const segment = useSelector((state) => getSegment(state, { params }));
+ const segmentId = useSelector((state) => getSegmentId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+ // `SegmentFieldList` reads `table.db_id` but doesn't select the table itself.
+ const table = useSelector((state) => getTable(state, { params }));
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchSegmentFields(props, segmentId);
}
- UNSAFE_componentWillReceiveProps(newProps: SegmentFieldListContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { user, segment, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<SegmentSidebar segment={segment} user={user} />}
- >
- <SegmentFieldList {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<SegmentSidebar segment={segment} user={user} />}
+ >
+ <SegmentFieldList params={params} table={table} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- SegmentFieldListContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(SegmentFieldListContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/segments/SegmentFieldListContainer.unit.spec.tsx b/frontend/src/metabase/reference/segments/SegmentFieldListContainer.unit.spec.tsx
new file mode 100644
index 00000000000..324562ac78c
--- /dev/null
+++ b/frontend/src/metabase/reference/segments/SegmentFieldListContainer.unit.spec.tsx
@@ -0,0 +1,63 @@
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseEndpoints,
+ setupSegmentsEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import {
+ createMockDatabase,
+ createMockField,
+ createMockSegment,
+ createMockTable,
+} from "metabase-types/api/mocks";
+
+import SegmentFieldListContainer from "./SegmentFieldListContainer";
+
+const TOTAL = createMockField({
+ id: 100,
+ name: "TOTAL",
+ display_name: "Total",
+});
+
+const TABLE = createMockTable({ id: 10, db_id: 1, fields: [TOTAL] });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+const SEGMENT = createMockSegment({
+ id: 1,
+ name: "Orders < 100",
+ table_id: TABLE.id,
+});
+
+function setup() {
+ setupSegmentsEndpoints([SEGMENT]);
+ // Also registers the table endpoints for `DATABASE.tables`.
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/segments/:segmentId/fields"
+ element={<SegmentFieldListContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/segments/${SEGMENT.id}/fields`,
+ },
+ );
+}
+
+describe("SegmentFieldListContainer", () => {
+ // `SegmentFieldList` reads `table.db_id` while rendering each row, so it
+ // throws and blanks the page if the container stops passing `table` down.
+ it("renders the segment's fields", async () => {
+ setup();
+
+ expect(
+ await screen.findAllByText("Fields in Orders < 100"),
+ ).not.toHaveLength(0);
+ expect(await screen.findByText("Total")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/segments/SegmentListContainer.tsx b/frontend/src/metabase/reference/segments/SegmentListContainer.tsx
index 703da4dbdd2..1e3d4ffd7e8 100644
--- a/frontend/src/metabase/reference/segments/SegmentListContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentListContainer.tsx
@@ -1,35 +1,18 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import BaseSidebar from "metabase/reference/guide/BaseSidebar";
import * as actions from "metabase/reference/reference";
import { SegmentList } from "metabase/reference/segments/SegmentList";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
+import { useLocation } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
-import {
- type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
- getDatabaseId,
- getIsEditing,
-} from "../selectors";
-
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- databaseId: getDatabaseId(state, props),
- isEditing: getIsEditing(state),
-});
+import { getIsEditing } from "../selectors";
const mapDispatchToProps = {
...metadataActions,
@@ -37,58 +20,49 @@ const mapDispatchToProps = {
};
interface SegmentListContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchSegments: (id?: number) => Promise<unknown>;
}
-class SegmentListContainer extends Component<SegmentListContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchSegments(this.props);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
- }
+function SegmentListContainer(props: SegmentListContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
- UNSAFE_componentWillReceiveProps(newProps: SegmentListContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
- }
+ const isEditing = useSelector(getIsEditing);
- actions.clearState(newProps);
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchSegments(props);
}
- render() {
- const { isEditing } = this.props;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
+ }
+ }, [pathname, previousPathname, props]);
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<BaseSidebar />}
- >
- <SegmentList {...this.props} />
- </SidebarLayout>
- );
- }
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<BaseSidebar />}
+ >
+ <SegmentList />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- // Unjustified type cast. FIXME
- )(SegmentListContainer as unknown as React.ComponentType<InjectedRouteProps>),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(SegmentListContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/segments/SegmentListContainer.unit.spec.tsx b/frontend/src/metabase/reference/segments/SegmentListContainer.unit.spec.tsx
new file mode 100644
index 00000000000..1cef2dc7dfd
--- /dev/null
+++ b/frontend/src/metabase/reference/segments/SegmentListContainer.unit.spec.tsx
@@ -0,0 +1,25 @@
+import { setupSegmentsEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockSegment } from "metabase-types/api/mocks";
+
+import SegmentListContainer from "./SegmentListContainer";
+
+const SEGMENT = createMockSegment({ id: 1, name: "Active subscribers" });
+
+function setup() {
+ setupSegmentsEndpoints([SEGMENT]);
+
+ return renderWithProviders(
+ <Route path="/reference/segments" element={<SegmentListContainer />} />,
+ { withRouter: true, initialRoute: "/reference/segments" },
+ );
+}
+
+describe("SegmentListContainer", () => {
+ it("fetches segments on mount and lists them", async () => {
+ setup();
+
+ expect(await screen.findByText("Active subscribers")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx
index c0c38616cd2..49ebfca797d 100644
--- a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx
@@ -1,46 +1,29 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import { cardApi } from "metabase/api";
import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import type { Dispatch } from "metabase/redux/store";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import * as actions from "metabase/reference/reference";
import { SegmentQuestions } from "metabase/reference/segments/SegmentQuestions";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
-import type { User } from "metabase-types/api";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getIsEditing,
getSegment,
getSegmentId,
getUser,
} from "../selectors";
-import type { StubbedSegment } from "../types";
import SegmentSidebar from "./SegmentSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- user: getUser(state),
- segment: getSegment(state, props),
- segmentId: getSegmentId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
fetchQuestions: () => (dispatch: Dispatch) =>
runRtkEndpoint({}, dispatch, cardApi.endpoints.listCards),
@@ -49,65 +32,55 @@ const mapDispatchToProps = {
};
interface SegmentQuestionsContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- user: User | null;
- segment: StubbedSegment;
- segmentId: number;
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchSegments: (id?: number) => Promise<unknown>;
fetchSegmentTable: (id: number) => Promise<unknown>;
fetchQuestions: () => Promise<unknown>;
}
-class SegmentQuestionsContainer extends Component<SegmentQuestionsContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchSegmentQuestions(this.props, this.props.segmentId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function SegmentQuestionsContainer(props: SegmentQuestionsContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const user = useSelector(getUser);
+ const segment = useSelector((state) => getSegment(state, { params }));
+ const segmentId = useSelector((state) => getSegmentId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchSegmentQuestions(props, segmentId);
}
- UNSAFE_componentWillReceiveProps(newProps: SegmentQuestionsContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { user, segment, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<SegmentSidebar segment={segment} user={user} />}
- >
- <SegmentQuestions {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<SegmentSidebar segment={segment} user={user} />}
+ >
+ <SegmentQuestions params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- SegmentQuestionsContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(SegmentQuestionsContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.unit.spec.tsx b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.unit.spec.tsx
new file mode 100644
index 00000000000..e5c301b1724
--- /dev/null
+++ b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.unit.spec.tsx
@@ -0,0 +1,53 @@
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseEndpoints,
+ setupSegmentsEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import {
+ createMockDatabase,
+ createMockSegment,
+ createMockTable,
+} from "metabase-types/api/mocks";
+
+import SegmentQuestionsContainer from "./SegmentQuestionsContainer";
+
+const TABLE = createMockTable({ id: 10, db_id: 1 });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+const SEGMENT = createMockSegment({
+ id: 1,
+ name: "Orders < 100",
+ table_id: TABLE.id,
+});
+
+function setup() {
+ setupSegmentsEndpoints([SEGMENT]);
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+ fetchMock.get("path:/api/card", []);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/segments/:segmentId/questions"
+ element={<SegmentQuestionsContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/segments/${SEGMENT.id}/questions`,
+ },
+ );
+}
+
+describe("SegmentQuestionsContainer", () => {
+ it("renders the questions view for the segment named by the route param", async () => {
+ setup();
+
+ expect(
+ await screen.findAllByText("Questions about Orders < 100"),
+ ).not.toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.tsx b/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.tsx
index 2ff82251754..2d4402e21dd 100644
--- a/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.tsx
@@ -1,108 +1,81 @@
import cx from "classnames";
-import { Component } from "react";
+import { useEffect, useRef } from "react";
+import { usePrevious } from "react-use";
import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
import * as actions from "metabase/reference/reference";
import SegmentRevisions from "metabase/reference/segments/SegmentRevisions";
-import {
- type InjectedRouteProps,
- type Location,
- withRouteProps,
-} from "metabase/router";
-import type { User } from "metabase-types/api";
+import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps, FetchProps } from "../reference";
import {
type ReferenceRouteParams,
- type ReferenceRouteProps,
- type StateWithReference,
getIsEditing,
getSegment,
getSegmentId,
getUser,
} from "../selectors";
-import type { StubbedSegment } from "../types";
import SegmentSidebar from "./SegmentSidebar";
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- user: getUser(state),
- segment: getSegment(state, props),
- segmentId: getSegmentId(state, props),
- isEditing: getIsEditing(state),
-});
-
const mapDispatchToProps = {
...metadataActions,
...actions,
};
interface SegmentRevisionsContainerProps extends FetchProps, ClearStateProps {
- // From React Router
- params: ReferenceRouteParams;
- location: Location;
-
- // From route definition / parent
- style: React.CSSProperties;
-
- // From mapStateToProps
- user: User | null;
- segment: StubbedSegment;
- segmentId: number;
- isEditing?: boolean;
-
- // From mapDispatchToProps
fetchSegments: (id?: number) => Promise<unknown>;
fetchSegmentRevisions: (id: number) => Promise<unknown>;
fetchSegmentTable: (id: number) => Promise<unknown>;
}
-class SegmentRevisionsContainer extends Component<SegmentRevisionsContainerProps> {
- fetchContainerData() {
- actions.wrappedFetchSegmentRevisions(this.props, this.props.segmentId);
- }
-
- UNSAFE_componentWillMount() {
- this.fetchContainerData();
+function SegmentRevisionsContainer(props: SegmentRevisionsContainerProps) {
+ const { pathname } = useLocation();
+ const previousPathname = usePrevious(pathname);
+ const params = useParams<ReferenceRouteParams>();
+
+ const user = useSelector(getUser);
+ const segment = useSelector((state) => getSegment(state, { params }));
+ const segmentId = useSelector((state) => getSegmentId(state, { params }));
+ const isEditing = useSelector(getIsEditing);
+
+ // Dispatched during render, not from an effect, to reproduce the
+ // `UNSAFE_componentWillMount` this replaced: the child reads `loading` from
+ // the store, so it has to be true before the child's first render. From an
+ // effect (even `useLayoutEffect`) the tree commits once with no data, and the
+ // reference header lays out wrong — see DEV-2430.
+ const didFetch = useRef(false);
+ if (!didFetch.current) {
+ didFetch.current = true;
+ actions.wrappedFetchSegmentRevisions(props, segmentId);
}
- UNSAFE_componentWillReceiveProps(newProps: SegmentRevisionsContainerProps) {
- if (this.props.location.pathname === newProps.location.pathname) {
- return;
+ useEffect(() => {
+ const pathnameChanged =
+ previousPathname !== undefined && previousPathname !== pathname;
+ if (pathnameChanged) {
+ actions.clearState(props);
}
-
- actions.clearState(newProps);
- }
-
- render() {
- const { user, segment, isEditing } = this.props;
-
- return (
- <SidebarLayout
- className={cx(CS.flexFull, CS.relative)}
- style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<SegmentSidebar segment={segment} user={user} />}
- >
- <SegmentRevisions {...this.props} />
- </SidebarLayout>
- );
- }
+ }, [pathname, previousPathname, props]);
+
+ return (
+ <SidebarLayout
+ className={cx(CS.flexFull, CS.relative)}
+ style={isEditing ? { paddingTop: "43px" } : {}}
+ sidebar={<SegmentSidebar segment={segment} user={user} />}
+ >
+ <SegmentRevisions params={params} />
+ </SidebarLayout>
+ );
}
// connect HOC tangle: action-type constants in `actions` + JS-typed metadata thunks.
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default withRouteProps(
- connect(
- mapStateToProps,
- mapDispatchToProps,
- )(
- // Unjustified type cast. FIXME
- SegmentRevisionsContainer as unknown as React.ComponentType<InjectedRouteProps>,
- ),
-);
+export default connect(
+ null,
+ mapDispatchToProps,
+ // Unjustified type cast. FIXME
+)(SegmentRevisionsContainer as unknown as React.ComponentType);
diff --git a/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.unit.spec.tsx b/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.unit.spec.tsx
new file mode 100644
index 00000000000..4919fa2e242
--- /dev/null
+++ b/frontend/src/metabase/reference/segments/SegmentRevisionsContainer.unit.spec.tsx
@@ -0,0 +1,54 @@
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseEndpoints,
+ setupSegmentsEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { Route } from "metabase/router";
+import {
+ createMockDatabase,
+ createMockSegment,
+ createMockTable,
+} from "metabase-types/api/mocks";
+
+import SegmentRevisionsContainer from "./SegmentRevisionsContainer";
+
+const TABLE = createMockTable({ id: 10, db_id: 1 });
+
+const DATABASE = createMockDatabase({ id: 1, tables: [TABLE] });
+
+const SEGMENT = createMockSegment({
+ id: 1,
+ name: "Orders < 100",
+ table_id: TABLE.id,
+});
+
+function setup() {
+ setupSegmentsEndpoints([SEGMENT]);
+ setupDatabaseEndpoints(DATABASE);
+ fetchMock.get(`path:/api/database/${DATABASE.id}/metadata`, DATABASE);
+ fetchMock.get(`path:/api/revision?entity=segment&id=${SEGMENT.id}`, []);
+ fetchMock.get("path:/api/revision", []);
+
+ return renderWithProviders(
+ <Route
+ path="/reference/segments/:segmentId/revisions"
+ element={<SegmentRevisionsContainer />}
+ />,
+ {
+ withRouter: true,
+ initialRoute: `/reference/segments/${SEGMENT.id}/revisions`,
+ },
+ );
+}
+
+describe("SegmentRevisionsContainer", () => {
+ it("renders the revision history for the segment named by the route param", async () => {
+ setup();
+
+ expect(
+ await screen.findAllByText("Revision history for Orders < 100"),
+ ).not.toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/reference/selectors.ts b/frontend/src/metabase/reference/selectors.ts
index 4f5ce3e61c9..9b03a9a2312 100644
--- a/frontend/src/metabase/reference/selectors.ts
+++ b/frontend/src/metabase/reference/selectors.ts
@@ -18,12 +18,14 @@ import type {
} from "./types";
import { idsToObjectMap } from "./utils";
-export interface ReferenceRouteParams {
+// A `type`, not an `interface`, so `useParams<ReferenceRouteParams>()` accepts
+// it: the hook's constraint needs an implicit index signature.
+export type ReferenceRouteParams = {
segmentId?: string;
databaseId?: string;
tableId?: string;
fieldId?: string;
-}
+};
export interface ReferenceRouteProps {
params: ReferenceRouteParams;
@@ -45,22 +47,18 @@ export type StateWithReference = State & {
revisions?: Record<string, Record<string | number, unknown>>;
};
-export const getUser = (state: StateWithReference) => state.currentUser;
+export const getUser = (state: State) => state.currentUser;
-export const getSegmentId = (
- _state: StateWithReference,
- props: ReferenceRouteProps,
-) => Number.parseInt(props.params.segmentId ?? "");
+export const getSegmentId = (_state: State, props: ReferenceRouteProps) =>
+ Number.parseInt(props.params.segmentId ?? "");
export const getSegment = createSelector(
[getSegmentId, getSegments],
(segmentId, segments): StubbedSegment =>
segments?.[segmentId] || { id: segmentId },
);
-export const getDatabaseId = (
- _state: StateWithReference,
- props: ReferenceRouteProps,
-) => Number.parseInt(props.params.databaseId ?? "");
+export const getDatabaseId = (_state: State, props: ReferenceRouteProps) =>
+ Number.parseInt(props.params.databaseId ?? "");
export const getDatabase = createSelector(
[getDatabaseId, getDatabases],
@@ -68,10 +66,8 @@ export const getDatabase = createSelector(
databases?.[databaseId] || { id: databaseId },
);
-export const getTableId = (
- _state: StateWithReference,
- props: ReferenceRouteProps,
-) => Number.parseInt(props.params.tableId ?? "");
+export const getTableId = (_state: State, props: ReferenceRouteProps) =>
+ Number.parseInt(props.params.tableId ?? "");
// export const getTableId = (state, props) => Number.parseInt(props.params.tableId);
export const getTablesByDatabase = createSelector(
[getTables, getDatabase],
@@ -95,10 +91,8 @@ export const getTable = createSelector(
: { id: 0 },
);
-export const getFieldId = (
- _state: StateWithReference,
- props: ReferenceRouteProps,
-) => Number.parseInt(props.params.fieldId ?? "");
+export const getFieldId = (_state: State, props: ReferenceRouteProps) =>
+ Number.parseInt(props.params.fieldId ?? "");
export const getFieldsByTable = createSelector(
[getTable, getFields],
(table, fields) => (table.fields ? idsToObjectMap(table.fields, fields) : {}),
@@ -116,10 +110,12 @@ export const getFieldBySegment = createSelector(
(fieldId, fields): StubbedField => fields[fieldId] || { id: fieldId },
);
-const getQuestions = (state: StateWithReference) =>
+const getQuestions = (state: State) =>
getIn(state, ["entities", "questions"]) || {};
-const getRevisions = (state: StateWithReference) => state.revisions;
+const getRevisions = (state: State) =>
+ // Unjustified type cast. FIXME
+ (state as StateWithReference).revisions;
export const getSegmentRevisions = createSelector(
[getSegmentId, getRevisions],
@@ -162,5 +158,6 @@ export const getIsEditing = (state: State) =>
// Unjustified type cast. FIXME
(state as StateWithReference).reference.isEditing;
-export const getIsFormulaExpanded = (state: StateWithReference) =>
- state.reference.isFormulaExpanded;
+export const getIsFormulaExpanded = (state: State) =>
+ // Unjustified type cast. FIXME
+ (state as StateWithReference).reference.isFormulaExpanded;
diff --git a/frontend/src/metabase/router/RouterProvider.unit.spec.tsx b/frontend/src/metabase/router/RouterProvider.unit.spec.tsx
index f1cd4a49c31..a295a8b3903 100644
--- a/frontend/src/metabase/router/RouterProvider.unit.spec.tsx
+++ b/frontend/src/metabase/router/RouterProvider.unit.spec.tsx
@@ -3,25 +3,24 @@ import { usePrevious } from "react-use";
import { act, renderWithProviders, screen } from "__support__/ui";
import { Route } from "./route";
+import { useLocation } from "./use-location";
import { useParams } from "./use-params";
-import { withRouteProps } from "./with-route-props";
// Mirrors the document /new -> /new leave prompt: a page that derives transient
// state from `usePrevious(location.key)` and expects to stay rendered until the
// user acts on it. It only holds if a same-path navigation re-renders the page
// exactly once, the way v3 `component` routes did.
-const LeavePrompt = ({ location }: { location: { key?: string } }) => {
+const LeavePrompt = () => {
+ const location = useLocation();
const previousKey = usePrevious(location.key);
const navigatedInPlace =
previousKey !== undefined && location.key !== previousKey;
return <div>{navigatedInPlace ? "leave-prompt" : "no-prompt"}</div>;
};
-const RoutedLeavePrompt = withRouteProps(LeavePrompt);
-
const Page = () => {
const { id } = useParams();
- return <RoutedLeavePrompt key={id} />;
+ return <LeavePrompt key={id} />;
};
describe("router/RouterProvider context stability", () => {
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index dea47803529..d51897a691c 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -13,7 +13,6 @@ export * from "./use-navigate";
export * from "./use-params";
export * from "./use-router";
export * from "./use-search-params";
-export * from "./with-route-props";
export { getRawBrowserHistory } from "./v7/blocking-history";
export { queryToSearch, searchToQuery, toV3Location } from "./v7/location";
export {
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 2b093b49f15..1b0da848071 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -233,8 +233,8 @@ export interface InjectedRouter {
/**
* The router-injected props v3 passed to route components (`router`, `location`,
- * `params`, `routes`). The `RouterBridge` republishes them from the v7 match;
- * `withRouteProps` feeds them to legacy components.
+ * `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
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
index 24c8ccdfc28..cb6d2a51210 100644
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -33,9 +33,8 @@ 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`, `withRouteProps`) read that context unchanged, so nothing
- * downstream can tell which engine it runs on. Deleted with the v3 engine in
- * Phase 4.
+ * `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,
diff --git a/frontend/src/metabase/router/with-route-props.tsx b/frontend/src/metabase/router/with-route-props.tsx
deleted file mode 100644
index cf9bb79634a..00000000000
--- a/frontend/src/metabase/router/with-route-props.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { ComponentType } from "react";
-
-import { useRoute } from "./Outlet";
-import type { Route } from "./route";
-import type { InjectedRouter, Location, Params, PlainRoute } from "./types";
-import { useRouter } from "./use-router";
-
-/**
- * The v3 router props a wrapped component may read. `params`/`location` are
- * always injected; the rest are optional so a component that reads only a subset
- * still satisfies the constraint.
- */
-export interface InjectedRouteProps {
- params: Params;
- location: Location;
- route?: Route;
- router?: InjectedRouter;
- routes?: PlainRoute[];
-}
-
-/**
- * Temporary shim for the react-router v7 migration. Wraps a legacy component
- * that still reads the v3-injected router props (`params`, `location`, `route`,
- * `router`, `routes`) and feeds them in from the router context, so the
- * component runs as an `element` route without being rewritten. Removed in
- * Phase 4 once these components read the hooks themselves.
- */
-export function withRouteProps<Props extends object>(
- WrappedComponent: ComponentType<Props>,
-): ComponentType<Omit<Props, keyof InjectedRouteProps>> {
- function WithRouteProps(props: Omit<Props, keyof InjectedRouteProps>) {
- const { router, location, params, routes } = useRouter();
- const route = useRoute();
-
- // TS cannot see that re-adding the omitted route props reconstructs `Props`.
- const injectedProps = {
- ...props,
- router,
- location,
- params,
- routes,
- route,
- } as unknown as Props;
- return <WrappedComponent {...injectedProps} />;
- }
-
- const wrappedName =
- WrappedComponent.displayName ?? WrappedComponent.name ?? "Component";
- WithRouteProps.displayName = `withRouteProps(${wrappedName})`;
-
- return WithRouteProps;
-}
diff --git a/frontend/src/metabase/router/with-route-props.unit.spec.tsx b/frontend/src/metabase/router/with-route-props.unit.spec.tsx
deleted file mode 100644
index a57606e34aa..00000000000
--- a/frontend/src/metabase/router/with-route-props.unit.spec.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { renderWithProviders, screen } from "__support__/ui";
-import { Route } from "metabase/router";
-
-import type { Location, Params } from "./types";
-import { withRouteProps } from "./with-route-props";
-
-interface LegacyProps {
- params: Params;
- location: Location;
-}
-
-function LegacyComponent({ params, location }: LegacyProps) {
- return (
- <div>
- <span data-testid="segment">{params.segmentId}</span>
- <span data-testid="pathname">{location.pathname}</span>
- </div>
- );
-}
-
-const WrappedComponent = withRouteProps(LegacyComponent);
-
-describe("router/withRouteProps", () => {
- it("feeds params and location from the facade hooks into the wrapped component", () => {
- renderWithProviders(
- <Route
- path="reference/segments/:segmentId"
- element={<WrappedComponent />}
- />,
- {
- withRouter: true,
- initialRoute: "/reference/segments/42",
- },
- );
-
- expect(screen.getByTestId("segment")).toHaveTextContent("42");
- expect(screen.getByTestId("pathname")).toHaveTextContent(
- "/reference/segments/42",
- );
- });
-});
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 0989dfcf606..963e6953ab3 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -1,6 +1,6 @@
import type { Store, ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";
-import App from "metabase/AppComponent";
+import { App } from "metabase/AppComponent";
import { getAccountRoutes } from "metabase/account/routes";
import CollectionPermissionsModal from "metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal";
import { getRoutes as getAdminRoutes } from "metabase/admin/routes";
@@ -75,13 +75,7 @@ import {
IsAuthenticated,
IsNotAuthenticated,
} from "metabase/route-guards";
-import {
- Navigate,
- Route,
- redirect,
- useParams,
- withRouteProps,
-} from "metabase/router";
+import { Navigate, Route, redirect, useParams } from "metabase/router";
import { SearchApp } from "metabase/search/containers/SearchApp";
import { RedirectIfSetup } from "metabase/setup/components/RedirectIfSetup";
import { Setup } from "metabase/setup/components/Setup";
@@ -94,10 +88,6 @@ type AppStore = Store<State> & {
dispatch: ThunkDispatch<State, void, UnknownAction>;
};
-// Legacy containers that still read v3 router props (`params`/`location`/
-// `route`/`router`/`routes`), fed from the router context so they run as
-// `element` routes. Removed with the shim.
-
/**
* v48 and earlier linked databases as `/browse/<dbId>-<slug>`. That was a
* `:dbId-:slug` route, which react-router v7 cannot express: a dynamic segment
@@ -116,14 +106,9 @@ export function LegacyBrowseRedirect() {
return <Navigate to={`/browse/databases/${dbIdAndSlug}`} replace />;
}
-// Reads the route location through `connect`'s `mapStateToProps`, so the hooks
-// cannot reach it. Migrating it means rewriting the connected container,
-// tracked separately.
-const RoutedApp = withRouteProps(App);
-
export const getRoutes = (store: AppStore) => {
return (
- <Route element={<RoutedApp />}>
+ <Route element={<App />}>
{/* SETUP */}
<Route element={<RedirectIfSetup />}>
<Route path="/setup" element={<Setup />} />