Skip to content

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

Move onEnter/onChange/onLeave to components and effects (#77264)

Romeo Van Snick1ad3f2b11427
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjs
index 8916cabfe4a..29d494eaf58 100644
--- a/frontend/lint/module-boundaries.mjs
+++ b/frontend/lint/module-boundaries.mjs
@@ -193,6 +193,8 @@ const elements = [
"frontend/src/metabase/routes-embed.tsx",
"frontend/src/metabase/route-guards.tsx",
"frontend/src/metabase/route-guards.unit.spec.tsx",
+ "frontend/src/metabase/LoadCurrentUser.tsx",
+ "frontend/src/metabase/LoadCurrentUser.unit.spec.tsx",
"frontend/src/metabase/routes-public.tsx",
"frontend/src/metabase/AppThemeProvider.tsx",
"frontend/src/metabase/AppColorSchemeProvider.tsx",
diff --git a/frontend/src/metabase/AppComponent.tsx b/frontend/src/metabase/AppComponent.tsx
index 908bb2593a7..cbbc3e60785 100644
--- a/frontend/src/metabase/AppComponent.tsx
+++ b/frontend/src/metabase/AppComponent.tsx
@@ -26,6 +26,7 @@ import { usePageTitle } from "metabase/hooks/use-page-title";
import { connect, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
import type { AppErrorDescriptor, State } from "metabase/redux/store";
+import { useLocation } from "metabase/router";
import { getErrorPage } from "metabase/selectors/app";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { StatusListing } from "metabase/status/components/StatusListing";
@@ -34,6 +35,7 @@ import { initializeIframeResizer } from "metabase/utils/dom";
import { AppContainer, AppContent, AppContentContainer } from "./App.styled";
import { AppKBarProvider } from "./AppKBarProvider";
import ErrorBoundary from "./ErrorBoundary";
+import { trackPageView } from "./analytics";
import { useTokenRefresh } from "./api/utils/use-token-refresh";
import { Metabot } from "./metabot/components/Metabot";
import { NewModals } from "./new/components/NewModals/NewModals";
@@ -101,6 +103,7 @@ function App({
}: AppProps) {
const [viewportElement, setViewportElement] = useState<HTMLElement | null>();
const applicationName = useSelector(getApplicationName);
+ const { pathname } = useLocation();
usePageTitle(applicationName, { titleIndex: 0 });
useTokenRefresh();
@@ -109,6 +112,10 @@ function App({
initializeIframeResizer();
}, []);
+ useEffect(() => {
+ trackPageView(pathname);
+ }, [pathname]);
+
return (
<ErrorBoundary onError={onError}>
<ScrollToTop>
diff --git a/frontend/src/metabase/LoadCurrentUser.tsx b/frontend/src/metabase/LoadCurrentUser.tsx
new file mode 100644
index 00000000000..dc9b3993e66
--- /dev/null
+++ b/frontend/src/metabase/LoadCurrentUser.tsx
@@ -0,0 +1,29 @@
+import type { ReactNode } from "react";
+import { useEffect, useState } from "react";
+
+import { useDispatch } from "metabase/redux";
+import { loadCurrentUser } from "metabase/redux/user";
+
+/**
+ * Loads the current user before rendering the authenticated app, gating its
+ * children until the request settles. The route guards below it read
+ * `currentUser`, so they must not run before it has been fetched.
+ */
+export function LoadCurrentUser({ children }: { children: ReactNode }) {
+ const dispatch = useDispatch();
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ dispatch(loadCurrentUser()).finally(() => {
+ if (!cancelled) {
+ setIsLoaded(true);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [dispatch]);
+
+ return isLoaded ? <>{children}</> : null;
+}
diff --git a/frontend/src/metabase/LoadCurrentUser.unit.spec.tsx b/frontend/src/metabase/LoadCurrentUser.unit.spec.tsx
new file mode 100644
index 00000000000..10d03374d4c
--- /dev/null
+++ b/frontend/src/metabase/LoadCurrentUser.unit.spec.tsx
@@ -0,0 +1,35 @@
+import fetchMock from "fetch-mock";
+
+import { setupCurrentUserEndpoint } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
+import { createMockUser } from "metabase-types/api/mocks";
+
+import { LoadCurrentUser } from "./LoadCurrentUser";
+
+describe("LoadCurrentUser", () => {
+ const setup = () =>
+ renderWithProviders(
+ <Route component={LoadCurrentUser}>
+ <Route path="/" component={() => <div>app content</div>} />
+ </Route>,
+ {
+ storeInitialState: createMockState({ currentUser: undefined }),
+ withRouter: true,
+ initialRoute: "/",
+ },
+ );
+
+ it("gates its children until the current user has loaded", async () => {
+ setupCurrentUserEndpoint(createMockUser());
+ setup();
+
+ expect(screen.queryByText("app content")).not.toBeInTheDocument();
+
+ expect(await screen.findByText("app content")).toBeInTheDocument();
+ expect(fetchMock.callHistory.calls("path:/api/user/current")).toHaveLength(
+ 1,
+ );
+ });
+});
diff --git a/frontend/src/metabase/auth/components/SsoReload/SsoReload.tsx b/frontend/src/metabase/auth/components/SsoReload/SsoReload.tsx
new file mode 100644
index 00000000000..19734ccc444
--- /dev/null
+++ b/frontend/src/metabase/auth/components/SsoReload/SsoReload.tsx
@@ -0,0 +1,15 @@
+import { useEffect } from "react";
+
+import { reload } from "metabase/utils/dom";
+
+/**
+ * Frontend routes can sometimes be prioritized over the backend ones. Reloading
+ * lets the backend pick the SSO flow back up.
+ */
+export function SsoReload() {
+ useEffect(() => {
+ reload();
+ }, []);
+
+ return null;
+}
diff --git a/frontend/src/metabase/auth/components/SsoReload/SsoReload.unit.spec.tsx b/frontend/src/metabase/auth/components/SsoReload/SsoReload.unit.spec.tsx
new file mode 100644
index 00000000000..69f23fdfbbe
--- /dev/null
+++ b/frontend/src/metabase/auth/components/SsoReload/SsoReload.unit.spec.tsx
@@ -0,0 +1,24 @@
+import { renderWithProviders, waitFor } from "__support__/ui";
+import { Route } from "metabase/router";
+import * as domUtils from "metabase/utils/dom";
+
+import { SsoReload } from "./SsoReload";
+
+describe("SsoReload", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("reloads the page on mount", async () => {
+ const reloadSpy = jest
+ .spyOn(domUtils, "reload")
+ .mockImplementation(() => undefined);
+
+ renderWithProviders(<Route path="sso" component={SsoReload} />, {
+ withRouter: true,
+ initialRoute: "/sso",
+ });
+
+ await waitFor(() => expect(reloadSpy).toHaveBeenCalled());
+ });
+});
diff --git a/frontend/src/metabase/auth/components/SsoReload/index.ts b/frontend/src/metabase/auth/components/SsoReload/index.ts
new file mode 100644
index 00000000000..acb94c3dda2
--- /dev/null
+++ b/frontend/src/metabase/auth/components/SsoReload/index.ts
@@ -0,0 +1 @@
+export * from "./SsoReload";
diff --git a/frontend/src/metabase/data-studio/routes.tsx b/frontend/src/metabase/data-studio/routes.tsx
index 64d14eb31c3..fbf2cba3fbe 100644
--- a/frontend/src/metabase/data-studio/routes.tsx
+++ b/frontend/src/metabase/data-studio/routes.tsx
@@ -1,5 +1,3 @@
-import type { Store } from "@reduxjs/toolkit";
-
import { DependencyDiagnosticsSectionLayout } from "metabase/monitor/dependency-diagnostics/DependencyDiagnosticsSectionLayout";
import { DependencyDiagnosticsUpsellPage } from "metabase/monitor/dependency-diagnostics/DependencyDiagnosticsUpsellPage";
import {
@@ -9,8 +7,14 @@ import {
PLUGIN_SCHEMA_VIEWER,
PLUGIN_WORKSPACES,
} from "metabase/plugins";
+import { useSelector } from "metabase/redux";
import type { State } from "metabase/redux/store";
-import { IndexRoute, Route, type RouteComponent } from "metabase/router";
+import {
+ IndexRoute,
+ Navigate,
+ Route,
+ type RouteComponent,
+} from "metabase/router";
import { getDataStudioTransformRoutes } from "metabase/transforms/routes";
import { canAccessTransforms } from "metabase/transforms/selectors";
import * as Urls from "metabase/urls";
@@ -31,7 +35,6 @@ import {
} from "./upsells/pages";
export function getDataStudioRoutes(
- store: Store<State>,
CanAccessDataStudio: RouteComponent,
CanAccessDataModel: RouteComponent,
IsAdmin: RouteComponent,
@@ -39,11 +42,7 @@ export function getDataStudioRoutes(
return (
<Route component={CanAccessDataStudio}>
<Route path="data-studio" component={DataStudioLayout}>
- <IndexRoute
- onEnter={(_state, replace) => {
- replace(getIndexPath(store.getState()));
- }}
- />
+ <IndexRoute component={DataStudioIndexRedirect} />
<Route path="data" component={CanAccessDataModel}>
<Route component={DataSectionLayout}>
{getDataStudioMetadataRoutes(IsAdmin)}
@@ -95,6 +94,11 @@ export function getDataStudioRoutes(
);
}
+function DataStudioIndexRedirect() {
+ const indexPath = useSelector(getIndexPath);
+ return <Navigate to={indexPath} replace />;
+}
+
function getIndexPath(state: State) {
if (PLUGIN_FEATURE_LEVEL_PERMISSIONS.canAccessDataModel(state)) {
return Urls.dataStudioData();
diff --git a/frontend/src/metabase/home/components/LandingPageRedirect/LandingPageRedirect.tsx b/frontend/src/metabase/home/components/LandingPageRedirect/LandingPageRedirect.tsx
new file mode 100644
index 00000000000..0052e510539
--- /dev/null
+++ b/frontend/src/metabase/home/components/LandingPageRedirect/LandingPageRedirect.tsx
@@ -0,0 +1,24 @@
+import { PLUGIN_LANDING_PAGE } from "metabase/plugins";
+import { Navigate } from "metabase/router";
+
+import { HomePage } from "../HomePage";
+
+/**
+ * Renders the home page, or redirects to the configured landing page.
+ */
+export function LandingPageRedirect() {
+ const page = PLUGIN_LANDING_PAGE.getLandingPage();
+
+ if (page && page !== "/") {
+ const pathname = page.startsWith("/") ? page : `/${page}`;
+ return (
+ <Navigate
+ to={{ pathname }}
+ state={{ preserveNavbarState: true }}
+ replace
+ />
+ );
+ }
+
+ return <HomePage />;
+}
diff --git a/frontend/src/metabase/home/components/LandingPageRedirect/LandingPageRedirect.unit.spec.tsx b/frontend/src/metabase/home/components/LandingPageRedirect/LandingPageRedirect.unit.spec.tsx
new file mode 100644
index 00000000000..fe1e6f19e58
--- /dev/null
+++ b/frontend/src/metabase/home/components/LandingPageRedirect/LandingPageRedirect.unit.spec.tsx
@@ -0,0 +1,54 @@
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { PLUGIN_LANDING_PAGE } from "metabase/plugins";
+import { Route } from "metabase/router";
+
+import { LandingPageRedirect } from "./LandingPageRedirect";
+
+jest.mock("../HomePage", () => ({
+ HomePage: () => <div>home page</div>,
+}));
+
+describe("LandingPageRedirect", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ const setup = () =>
+ renderWithProviders(
+ <>
+ <Route path="/" component={LandingPageRedirect} />
+ <Route path="/custom" component={() => <div>custom page</div>} />
+ </>,
+ { withRouter: true, initialRoute: "/" },
+ );
+
+ it("renders the home page when the landing page is the home page", () => {
+ jest.spyOn(PLUGIN_LANDING_PAGE, "getLandingPage").mockReturnValue("/");
+ setup();
+ expect(screen.getByText("home page")).toBeInTheDocument();
+ });
+
+ it("redirects to the configured landing page, preserving navbar state", async () => {
+ jest
+ .spyOn(PLUGIN_LANDING_PAGE, "getLandingPage")
+ .mockReturnValue("/custom");
+ const { history } = setup();
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/custom"),
+ );
+ expect(history?.getCurrentLocation().state).toEqual({
+ preserveNavbarState: true,
+ });
+ expect(screen.getByText("custom page")).toBeInTheDocument();
+ });
+
+ it("prefixes a landing page that is missing a leading slash", async () => {
+ jest.spyOn(PLUGIN_LANDING_PAGE, "getLandingPage").mockReturnValue("custom");
+ const { history } = setup();
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/custom"),
+ );
+ });
+});
diff --git a/frontend/src/metabase/home/components/LandingPageRedirect/index.ts b/frontend/src/metabase/home/components/LandingPageRedirect/index.ts
new file mode 100644
index 00000000000..401dba24d72
--- /dev/null
+++ b/frontend/src/metabase/home/components/LandingPageRedirect/index.ts
@@ -0,0 +1 @@
+export * from "./LandingPageRedirect";
diff --git a/frontend/src/metabase/query_builder/components/QuestionHashRedirect.tsx b/frontend/src/metabase/query_builder/components/QuestionHashRedirect.tsx
new file mode 100644
index 00000000000..d8581d1e0e8
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/QuestionHashRedirect.tsx
@@ -0,0 +1,14 @@
+import { Navigate, useLocation, useParams } from "metabase/router";
+
+/**
+ * Redirects the deprecated `/q` and `/card/:slug` routes to `/question`,
+ * preserving the hash that holds the serialized question. A plain `<Redirect>`
+ * would drop it.
+ */
+export function QuestionHashRedirect() {
+ const { hash } = useLocation();
+ const { slug } = useParams();
+ const pathname = slug ? `/question/${slug}` : "/question";
+
+ return <Navigate to={{ pathname, hash }} replace />;
+}
diff --git a/frontend/src/metabase/query_builder/components/QuestionHashRedirect.unit.spec.tsx b/frontend/src/metabase/query_builder/components/QuestionHashRedirect.unit.spec.tsx
new file mode 100644
index 00000000000..4cb6eb6505c
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/QuestionHashRedirect.unit.spec.tsx
@@ -0,0 +1,37 @@
+import { renderWithProviders, waitFor } from "__support__/ui";
+import { Route } from "metabase/router";
+
+import { QuestionHashRedirect } from "./QuestionHashRedirect";
+
+const setup = (initialRoute: string) =>
+ renderWithProviders(
+ <>
+ <Route path="/q" component={QuestionHashRedirect} />
+ <Route path="/card/:slug" component={QuestionHashRedirect} />
+ <Route path="/question" component={() => <div>question</div>} />
+ <Route path="/question/:slug" component={() => <div>question</div>} />
+ </>,
+ { withRouter: true, initialRoute },
+ );
+
+describe("QuestionHashRedirect", () => {
+ it("redirects /q to /question, preserving the hash", async () => {
+ const { history } = setup("/q#foo=bar");
+
+ await waitFor(() => {
+ const location = history?.getCurrentLocation();
+ expect(location?.pathname).toBe("/question");
+ expect(location?.hash).toBe("#foo=bar");
+ });
+ });
+
+ it("redirects /card/:slug to /question/:slug, preserving the hash", async () => {
+ const { history } = setup("/card/123-foo#bar=baz");
+
+ await waitFor(() => {
+ const location = history?.getCurrentLocation();
+ expect(location?.pathname).toBe("/question/123-foo");
+ expect(location?.hash).toBe("#bar=baz");
+ });
+ });
+});
diff --git a/frontend/src/metabase/router/react-router.ts b/frontend/src/metabase/router/react-router.ts
index bb6d09ae4ad..6a074074f4a 100644
--- a/frontend/src/metabase/router/react-router.ts
+++ b/frontend/src/metabase/router/react-router.ts
@@ -7,12 +7,17 @@
// have not been given a v7 shape yet (route-tree components, withRouter, history
// helpers) plus the raw Link/LinkProps under `Router`-prefixed names for the few
// call sites that need the unstyled primitive.
+import type { ComponentClass } from "react";
+import type {
+ IndexRouteProps as BaseIndexRouteProps,
+ RouteProps as BaseRouteProps,
+} from "react-router";
+import { IndexRoute as BaseIndexRoute, Route as BaseRoute } from "react-router";
+
export {
IndexRedirect,
- IndexRoute,
Link as RouterLink,
Redirect,
- Route,
Router,
createMemoryHistory,
useRouterHistory,
@@ -24,6 +29,22 @@ export type {
LinkProps as RouterLinkProps,
PlainRoute,
RouteComponent,
- RouteProps,
WithRouterProps,
} from "react-router";
+
+/**
+ * v3's route lifecycle hooks. They have no v7 equivalent, and the app now does
+ * this work in components and effects instead, so they are dropped from the route
+ * props to keep them from coming back.
+ */
+type LifecycleHook = "onEnter" | "onChange" | "onLeave";
+
+export type RouteProps = Omit<BaseRouteProps, LifecycleHook>;
+export type IndexRouteProps = Omit<BaseIndexRouteProps, LifecycleHook>;
+
+// `react-router` exports each of these as both a value and a type, so mirror that.
+export type Route = ComponentClass<RouteProps>;
+export const Route = BaseRoute as Route;
+
+export type IndexRoute = ComponentClass<IndexRouteProps>;
+export const IndexRoute = BaseIndexRoute as IndexRoute;
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 721a3226b5f..e1e8359d4c6 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -8,6 +8,7 @@ import { ForgotPassword } from "metabase/auth/components/ForgotPassword";
import { Login } from "metabase/auth/components/Login";
import { Logout } from "metabase/auth/components/Logout";
import { ResetPassword } from "metabase/auth/components/ResetPassword";
+import { SsoReload } from "metabase/auth/components/SsoReload";
import {
BrowseDatabases,
BrowseMetrics,
@@ -34,7 +35,7 @@ import { TableDetailPage } from "metabase/detail-view/pages/TableDetailPage";
import { CommentsSidesheet } from "metabase/documents/components/CommentsSidesheet";
import { DocumentPageOuter } from "metabase/documents/routes";
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { HomePage } from "metabase/home/components/HomePage";
+import { LandingPageRedirect } from "metabase/home/components/LandingPageRedirect";
import { Onboarding } from "metabase/home/components/Onboarding";
import { getMetabotRoutes } from "metabase/metabot/routes";
import { getMetricRoutes } from "metabase/metrics/routes";
@@ -43,14 +44,13 @@ import NewModelOptions from "metabase/models/containers/NewModelOptions";
import { getRoutes as getModelRoutes } from "metabase/models/routes";
import {
PLUGIN_COLLECTIONS,
- PLUGIN_LANDING_PAGE,
PLUGIN_TABLE_EDITING,
PLUGIN_TENANTS,
} from "metabase/plugins";
import { MetabotQueryBuilder } from "metabase/query_builder/components/MetabotQueryBuilder";
+import { QuestionHashRedirect } from "metabase/query_builder/components/QuestionHashRedirect";
import { QueryBuilder } from "metabase/query_builder/containers/QueryBuilder";
import type { State } from "metabase/redux/store";
-import { loadCurrentUser } from "metabase/redux/user";
import DatabaseDetailContainer from "metabase/reference/databases/DatabaseDetailContainer";
import DatabaseListContainer from "metabase/reference/databases/DatabaseListContainer";
import FieldDetailContainer from "metabase/reference/databases/FieldDetailContainer";
@@ -67,10 +67,11 @@ import SegmentQuestionsContainer from "metabase/reference/segments/SegmentQuesti
import SegmentRevisionsContainer from "metabase/reference/segments/SegmentRevisionsContainer";
import { IndexRedirect, IndexRoute, Redirect, Route } from "metabase/router";
import { SearchApp } from "metabase/search/containers/SearchApp";
+import { RedirectIfSetup } from "metabase/setup/components/RedirectIfSetup";
import { Setup } from "metabase/setup/components/Setup";
import getCollectionTimelineRoutes from "metabase/timelines/collections/routes";
-import { trackPageView } from "./analytics";
+import { LoadCurrentUser } from "./LoadCurrentUser";
import {
CanAccessDataModel,
CanAccessDataStudio,
@@ -81,49 +82,28 @@ import {
IsNotAuthenticated,
} from "./route-guards";
import { createEntityIdRedirect } from "./routes-stable-id-aware";
-import { getSetting } from "./selectors/settings";
type AppStore = Store<State> & {
dispatch: ThunkDispatch<State, void, UnknownAction>;
};
export const getRoutes = (store: AppStore) => {
- const hasUserSetup = getSetting(store.getState(), "has-user-setup");
-
return (
<Route component={App}>
{/* SETUP */}
- <Route
- path="/setup"
- component={Setup}
- onEnter={(nextState, replace) => {
- if (hasUserSetup) {
- replace("/");
- }
- trackPageView(location.pathname);
- }}
- onChange={(prevState, nextState) => {
- trackPageView(nextState.location.pathname);
- }}
- props={{ disableCommandPalette: true }}
- />
+ <Route component={RedirectIfSetup}>
+ <Route
+ path="/setup"
+ component={Setup}
+ props={{ disableCommandPalette: true }}
+ />
+ </Route>
{/* For compatibility: use the standard setup for embedding */}
<Redirect from="/setup/embedding" to="/setup" />
{/* APP */}
- <Route
- onEnter={async (nextState, replace, done) => {
- await store.dispatch(loadCurrentUser());
- trackPageView(nextState.location.pathname);
- done?.();
- }}
- onChange={(prevState, nextState) => {
- if (nextState.location.pathname !== prevState.location.pathname) {
- trackPageView(nextState.location.pathname);
- }
- }}
- >
+ <Route component={LoadCurrentUser}>
{/* AUTH */}
<Route path="/auth">
<IndexRedirect to="/auth/login" />
@@ -136,11 +116,8 @@ export const getRoutes = (store: AppStore) => {
<Route path="reset_password/:token" component={ResetPassword} />
{/* FE routes can sometimes be prioritized over BE
reloading will correctly pick the SSO flow back up from the BE */}
- <Route path="sso" onEnter={() => window.location.reload()} />
- <Route
- path="sso/:provider"
- onEnter={() => window.location.reload()}
- />
+ <Route path="sso" component={SsoReload} />
+ <Route path="sso/:provider" component={SsoReload} />
</Route>
{/* MAIN */}
@@ -148,19 +125,7 @@ export const getRoutes = (store: AppStore) => {
{getMetabotRoutes()}
{/* The global all hands routes, things in here are for all the folks */}
- <Route
- path="/"
- component={HomePage}
- onEnter={(nextState, replace) => {
- const page = PLUGIN_LANDING_PAGE.getLandingPage();
- if (page && page !== "/") {
- replace({
- pathname: page.startsWith("/") ? page : `/${page}`,
- state: { preserveNavbarState: true },
- });
- }
- }}
- />
+ <Route path="/" component={LandingPageRedirect} />
<Route path="getting-started" component={CanAccessOnboarding}>
<IndexRoute component={Onboarding} />
@@ -392,7 +357,6 @@ export const getRoutes = (store: AppStore) => {
{/* DATA STUDIO */}
{getDataStudioRoutes(
- store,
CanAccessDataStudio,
CanAccessDataModel,
IsAdmin,
@@ -402,21 +366,8 @@ export const getRoutes = (store: AppStore) => {
{/* DEPRECATED */}
{/* NOTE: these custom routes are needed because <Redirect> doesn't preserve the hash */}
- <Route
- path="/q"
- onEnter={({ location }, replace) =>
- replace({ pathname: "/question", hash: location.hash })
- }
- />
- <Route
- path="/card/:slug"
- onEnter={({ location, params }, replace) =>
- replace({
- pathname: `/question/${params.slug}`,
- hash: location.hash,
- })
- }
- />
+ <Route path="/q" component={QuestionHashRedirect} />
+ <Route path="/card/:slug" component={QuestionHashRedirect} />
<Redirect from="/dash/:dashboardId" to="/dashboard/:dashboardId" />
<Redirect
from="/collections/permissions"
diff --git a/frontend/src/metabase/setup/components/RedirectIfSetup/RedirectIfSetup.tsx b/frontend/src/metabase/setup/components/RedirectIfSetup/RedirectIfSetup.tsx
new file mode 100644
index 00000000000..51c48c8694e
--- /dev/null
+++ b/frontend/src/metabase/setup/components/RedirectIfSetup/RedirectIfSetup.tsx
@@ -0,0 +1,22 @@
+import type { ReactNode } from "react";
+import { useState } from "react";
+
+import { useSelector } from "metabase/redux";
+import { Navigate } from "metabase/router";
+import { getSetting } from "metabase/selectors/settings";
+
+/**
+ * Sends users away from `/setup` once the instance has been set up.
+ *
+ * Only the value on entry decides: finishing the wizard's user step calls
+ * `/api/setup` and reloads settings, flipping `has-user-setup` to true midway
+ * through the flow. Reading it live would redirect the user out of setup.
+ */
+export function RedirectIfSetup({ children }: { children: ReactNode }) {
+ const hasUserSetup = useSelector((state) =>
+ getSetting(state, "has-user-setup"),
+ );
+ const [hadUserSetupOnEnter] = useState(hasUserSetup);
+
+ return hadUserSetupOnEnter ? <Navigate to="/" replace /> : <>{children}</>;
+}
diff --git a/frontend/src/metabase/setup/components/RedirectIfSetup/RedirectIfSetup.unit.spec.tsx b/frontend/src/metabase/setup/components/RedirectIfSetup/RedirectIfSetup.unit.spec.tsx
new file mode 100644
index 00000000000..a5d7f159cbe
--- /dev/null
+++ b/frontend/src/metabase/setup/components/RedirectIfSetup/RedirectIfSetup.unit.spec.tsx
@@ -0,0 +1,66 @@
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ createMockSettingsState,
+ createMockState,
+} from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
+import { createMockSettings } from "metabase-types/api/mocks";
+
+import { RedirectIfSetup } from "./RedirectIfSetup";
+
+// The `loadSettings` action, inlined: importing `metabase/redux/settings` pulls
+// in an import graph large enough to exhaust the jest heap.
+const loadSettings = (values: ReturnType<typeof createMockSettings>) => ({
+ type: "metabase/settings/LOAD_SETTINGS",
+ payload: values,
+});
+
+describe("RedirectIfSetup", () => {
+ const setup = (hasUserSetup: boolean) =>
+ renderWithProviders(
+ <>
+ <Route component={RedirectIfSetup}>
+ <Route path="setup" component={() => <div>setup page</div>} />
+ </Route>
+ <Route path="/" component={() => <div>home page</div>} />
+ </>,
+ {
+ storeInitialState: createMockState({
+ settings: createMockSettingsState({ "has-user-setup": hasUserSetup }),
+ }),
+ withRouter: true,
+ initialRoute: "/setup",
+ },
+ );
+
+ it("renders the setup page when the instance is not set up", () => {
+ setup(false);
+ expect(screen.getByText("setup page")).toBeInTheDocument();
+ });
+
+ it("redirects to the home page once the instance is set up", async () => {
+ const { history } = setup(true);
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/"),
+ );
+ expect(screen.queryByText("setup page")).not.toBeInTheDocument();
+ });
+
+ it("stays on setup when has-user-setup flips to true mid-wizard", () => {
+ const { history, store } = setup(false);
+ expect(screen.getByText("setup page")).toBeInTheDocument();
+
+ // The wizard's user step calls /api/setup, then reloads settings.
+ act(() => {
+ store.dispatch(
+ loadSettings(createMockSettings({ "has-user-setup": true })),
+ );
+ });
+
+ // Guards against the inlined action type drifting and voiding this test.
+ expect(store.getState().settings.values["has-user-setup"]).toBe(true);
+
+ expect(history?.getCurrentLocation().pathname).toBe("/setup");
+ expect(screen.getByText("setup page")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/setup/components/RedirectIfSetup/index.ts b/frontend/src/metabase/setup/components/RedirectIfSetup/index.ts
new file mode 100644
index 00000000000..81e3d5ac6fe
--- /dev/null
+++ b/frontend/src/metabase/setup/components/RedirectIfSetup/index.ts
@@ -0,0 +1 @@
+export * from "./RedirectIfSetup";