Skip to content

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

Create use-page-title hook and remove SetTitle Hoc (#65782)

Fraserff6ec328f357
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx b/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx
index fcb05982fb3..69c1010d37d 100644
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx
@@ -1,4 +1,4 @@
-import { Route } from "metabase/hoc/Title";
+import { Route } from "react-router";
import ApplicationPermissionsPage from "./pages/ApplicationPermissionsPage";
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.module.css b/enterprise/frontend/src/metabase-enterprise/database_routing/DestinationDatabaseConnectionModal/DestinationDatabaseConnectionModal.module.css
similarity index 100%
rename from frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.module.css
rename to enterprise/frontend/src/metabase-enterprise/database_routing/DestinationDatabaseConnectionModal/DestinationDatabaseConnectionModal.module.css
diff --git a/enterprise/frontend/src/metabase-enterprise/database_routing/DestinationDatabaseConnectionModal/DestinationDatabaseConnectionModal.tsx b/enterprise/frontend/src/metabase-enterprise/database_routing/DestinationDatabaseConnectionModal/DestinationDatabaseConnectionModal.tsx
index 3f3f06515f1..8435a9be0c2 100644
--- a/enterprise/frontend/src/metabase-enterprise/database_routing/DestinationDatabaseConnectionModal/DestinationDatabaseConnectionModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/database_routing/DestinationDatabaseConnectionModal/DestinationDatabaseConnectionModal.tsx
@@ -4,12 +4,11 @@ import { push, replace } from "react-router-redux";
import { t } from "ttag";
import { DatabaseEditConnectionForm } from "metabase/admin/databases/components/DatabaseEditConnectionForm";
-import S from "metabase/admin/databases/containers/DatabaseConnectionModal.module.css";
import { useGetDatabaseQuery, useUpdateDatabaseMutation } from "metabase/api";
import ExternalLink from "metabase/common/components/ExternalLink";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useDocsUrl } from "metabase/common/hooks";
-import title from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { addUndo } from "metabase/redux/undo";
@@ -19,9 +18,10 @@ import type { Database, DatabaseData } from "metabase-types/api";
import { paramIdToGetQuery } from "../utils";
+import S from "./DestinationDatabaseConnectionModal.module.css";
import { pickPrefillFieldsFromPrimaryDb } from "./utils";
-export const DestinationDatabaseConnectionModalInner = ({
+export const DestinationDatabaseConnectionModal = ({
params: { databaseId, destinationDatabaseId },
route,
}: {
@@ -95,6 +95,8 @@ export const DestinationDatabaseConnectionModalInner = ({
handleCloseModal("replace");
};
+ usePageTitle(destinationDatabase?.name || "");
+
return (
<Modal
title={
@@ -151,7 +153,3 @@ export const DestinationDatabaseConnectionModalInner = ({
</Modal>
);
};
-
-export const DestinationDatabaseConnectionModal = title(
- ({ database }: { database: DatabaseData }) => database && database.name,
-)(DestinationDatabaseConnectionModalInner);
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
index 6009d9dd6df..21ef7a5e05f 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
@@ -25,7 +25,7 @@ import {
import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";
import { useToast } from "metabase/common/hooks";
import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
-import { SetTitle } from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch, useSelector } from "metabase/lib/redux";
import { extractEntityId } from "metabase/lib/urls";
import { setErrorPage } from "metabase/redux/app";
@@ -409,9 +409,10 @@ export const DocumentPage = ({
[dispatch, selectedEmbedIndex],
);
+ usePageTitle(documentData?.name || t`New document`, { titleIndex: 1 });
+
return (
<Box className={styles.documentPage}>
- <SetTitle title={documentData?.name || t`New document`} />
{documentData?.archived && <DocumentArchivedEntityBanner />}
<Box className={styles.contentArea}>
<Box className={styles.mainContent}>
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx b/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx
index 0ef919981ef..5ce790c7c55 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/documents/routes.tsx
@@ -1,7 +1,7 @@
import type { ComponentProps } from "react";
+import { Route } from "react-router";
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { Route } from "metabase/hoc/Title";
import { extractEntityId } from "metabase/lib/urls";
import { CommentsSidesheet } from "./components/CommentsSidesheet";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
index c3c44f8c945..84fed677790 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
@@ -1,9 +1,8 @@
-import { IndexRoute } from "react-router";
+import { IndexRoute, Route } from "react-router";
import { t } from "ttag";
import { createAdminRouteGuard } from "metabase/admin/utils";
import { AdminSettingsLayout } from "metabase/common/components/AdminLayout/AdminSettingsLayout";
-import { Route } from "metabase/hoc/Title";
import { PLUGIN_METABOT, PLUGIN_REDUCERS } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
@@ -75,7 +74,7 @@ export function initializePlugin() {
];
PLUGIN_METABOT.getAdminRoutes = () => (
<Route path="metabot" component={createAdminRouteGuard("metabot")}>
- <Route title={t`AI`} component={AdminSettingsLayout}>
+ <Route component={AdminSettingsLayout}>
<IndexRoute component={MetabotPurchasePage} />
</Route>
</Route>
@@ -90,7 +89,7 @@ export function initializePlugin() {
];
PLUGIN_METABOT.getAdminRoutes = () => (
<Route path="metabot" component={createAdminRouteGuard("metabot")}>
- <Route title={t`AI`} component={AdminSettingsLayout}>
+ <Route component={AdminSettingsLayout}>
<IndexRoute component={MetabotTrialPage} />
</Route>
</Route>
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx
index adf9cc09b14..3cdb316c773 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx
@@ -1,7 +1,7 @@
+import { Route } from "react-router";
import { t } from "ttag";
import { AdminNavItem } from "metabase/admin/components/AdminNav";
-import { Route } from "metabase/hoc/Title";
import * as Urls from "metabase/lib/urls";
import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx
index 3ab55d5862f..a4d30b3aacf 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx
@@ -1,8 +1,7 @@
-import { IndexRoute } from "react-router";
+import { IndexRoute, Route } from "react-router";
import { t } from "ttag";
import { createAdminRouteGuard } from "metabase/admin/utils";
-import { Route } from "metabase/hoc/Title";
import {
PLUGIN_ENTITIES,
PLUGIN_TRANSFORMS,
@@ -41,7 +40,7 @@ export function initializePlugin() {
PLUGIN_TRANSFORMS.getAdminRoutes = () => (
<Route path="transforms" component={createAdminRouteGuard("transforms")}>
- <Route title={t`Transforms`}>
+ <Route>
<Route component={ListPageLayout}>
<IndexRoute component={TransformListPage} />
<Route path="jobs" component={JobListPage} />
diff --git a/frontend/src/metabase/App.tsx b/frontend/src/metabase/App.tsx
index 07401e4781e..c8ca4f9bdab 100644
--- a/frontend/src/metabase/App.tsx
+++ b/frontend/src/metabase/App.tsx
@@ -15,8 +15,9 @@ import { UndoListing } from "metabase/common/components/UndoListing";
import { ContentViewportContext } from "metabase/common/context/ContentViewportContext";
import CS from "metabase/css/core/index.css";
import ScrollToTop from "metabase/hoc/ScrollToTop";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { initializeIframeResizer } from "metabase/lib/dom";
-import { connect } from "metabase/lib/redux";
+import { connect, useSelector } from "metabase/lib/redux";
import AppBar from "metabase/nav/containers/AppBar";
import Navbar from "metabase/nav/containers/Navbar";
import { PLUGIN_METABOT } from "metabase/plugins";
@@ -27,6 +28,7 @@ import {
getIsAppBarVisible,
getIsNavBarEnabled,
} from "metabase/selectors/app";
+import { getApplicationName } from "metabase/selectors/whitelabel";
import StatusListing from "metabase/status/components/StatusListing";
import type { AppErrorDescriptor, State } from "metabase-types/store";
@@ -94,6 +96,9 @@ function App({
onError,
}: AppProps) {
const [viewportElement, setViewportElement] = useState<HTMLElement | null>();
+ const applicationName = useSelector(getApplicationName);
+
+ usePageTitle(applicationName, { titleIndex: 0 });
useTokenRefresh();
useEffect(() => {
diff --git a/frontend/src/metabase/account/notifications/routes.jsx b/frontend/src/metabase/account/notifications/routes.jsx
index 1ed345ef6ec..d143dfa2443 100644
--- a/frontend/src/metabase/account/notifications/routes.jsx
+++ b/frontend/src/metabase/account/notifications/routes.jsx
@@ -1,5 +1,6 @@
+import { Route } from "react-router";
+
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { Route } from "metabase/hoc/Title";
import HelpModal from "./components/HelpModal";
import { DeleteAlertModal } from "./containers/ArchiveAlertModal";
diff --git a/frontend/src/metabase/account/routes.jsx b/frontend/src/metabase/account/routes.jsx
index 3fc2d446a40..7b2aca26746 100644
--- a/frontend/src/metabase/account/routes.jsx
+++ b/frontend/src/metabase/account/routes.jsx
@@ -1,7 +1,4 @@
-import { IndexRedirect } from "react-router";
-import { t } from "ttag";
-
-import { Route } from "metabase/hoc/Title";
+import { IndexRedirect, Route } from "react-router";
import AccountApp from "./app/containers/AccountApp";
import LoginHistoryApp from "./login-history/containers/LoginHistoryApp";
@@ -12,7 +9,7 @@ import UserProfileApp from "./profile/containers/UserProfileApp";
const getRoutes = (store, IsAuthenticated) => {
return (
<Route path="/account" component={IsAuthenticated}>
- <Route title={t`Account settings`} component={AccountApp}>
+ <Route component={AccountApp}>
<IndexRedirect to="profile" />
<Route path="profile" component={UserProfileApp} />
<Route path="password" component={UserPasswordApp} />
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.tsx
deleted file mode 100644
index 44d3fdfe1f2..00000000000
--- a/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { LocationDescriptor } from "history";
-import type { Route } from "react-router";
-
-import title from "metabase/hoc/Title";
-import { Modal } from "metabase/ui";
-import type { DatabaseData, DatabaseEditErrorType } from "metabase-types/api";
-
-import { DatabaseEditConnectionForm } from "../components/DatabaseEditConnectionForm";
-import { useDatabaseConnection } from "../hooks/use-database-connection";
-
-import S from "./DatabaseConnectionModal.module.css";
-
-export const DatabaseConnectionModalInner = ({
- route,
- params,
-}: {
- initializeError?: DatabaseEditErrorType;
- route: Route;
- location: LocationDescriptor;
- params: { databaseId: string };
-}) => {
- const {
- database,
- databaseReq,
- handleCancel: handleCloseModal,
- handleOnSubmit,
- title,
- config,
- } = useDatabaseConnection({ databaseId: params.databaseId });
-
- return (
- <Modal
- title={title}
- opened
- onClose={handleCloseModal}
- padding="xl"
- classNames={{
- content: S.modalRoot,
- header: S.modalHeader,
- body: S.modalBody,
- }}
- >
- <DatabaseEditConnectionForm
- database={database}
- isAttachedDWH={database?.is_attached_dwh ?? false}
- initializeError={databaseReq.error}
- onSubmitted={handleOnSubmit}
- onCancel={handleCloseModal}
- route={route}
- config={config}
- formLocation="admin"
- />
- </Modal>
- );
-};
-
-export const DatabaseConnectionModal = title(
- ({ database }: { database: DatabaseData }) => database && database.name,
-)(DatabaseConnectionModalInner);
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.unit.spec.tsx
deleted file mode 100644
index fa991243360..00000000000
--- a/frontend/src/metabase/admin/databases/containers/DatabaseConnectionModal.unit.spec.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
-import { IndexRoute, Route } from "react-router";
-
-import { callMockEvent } from "__support__/events";
-import {
- setupDatabaseEndpoints,
- setupDatabasesEndpoints,
-} from "__support__/server-mocks";
-import { mockSettings } from "__support__/settings";
-import {
- act,
- renderWithProviders,
- screen,
- waitFor,
- waitForLoaderToBeRemoved,
-} from "__support__/ui";
-import { BEFORE_UNLOAD_UNSAVED_MESSAGE } from "metabase/common/hooks/use-before-unload";
-import { checkNotNull } from "metabase/lib/types";
-import type { Engine } from "metabase-types/api";
-import {
- createMockDatabase,
- createMockEngineSource,
- createMockTokenFeatures,
-} from "metabase-types/api/mocks";
-
-import { DatabaseConnectionModal } from "./DatabaseConnectionModal";
-
-const ENGINES_MOCK: Record<string, Engine> = {
- H2: {
- "details-fields": [
- { "display-name": "Connection String", name: "db", required: true },
- { name: "advanced-options", type: "section", default: true },
- ],
- "driver-name": "H2",
- "superseded-by": null,
- source: createMockEngineSource(),
- "extra-info": null,
- },
- sqlite: {
- "details-fields": [
- { "display-name": "Filename", name: "db", required: true },
- { name: "advanced-options", type: "section", default: true },
- ],
- "driver-name": "SQLite",
- "superseded-by": null,
- source: createMockEngineSource(),
- "extra-info": null,
- },
-};
-
-const MockComponent = () => <div />;
-
-interface SetupOpts {
- databaseIdParam?: string;
- initialRoute?: string;
-}
-
-async function setup({
- databaseIdParam = "",
- initialRoute = `/${databaseIdParam}`,
-}: SetupOpts = {}) {
- const mockEventListener = jest.spyOn(window, "addEventListener");
-
- setupDatabasesEndpoints([]);
-
- const settings = mockSettings({
- engines: ENGINES_MOCK,
- "token-features": createMockTokenFeatures({
- cache_granular_controls: true,
- }),
- });
-
- const { history } = renderWithProviders(
- <Route path="/">
- <Route path="/home" component={MockComponent} />
- <Route path="/admin/databases/:id" component={MockComponent} />
- <IndexRoute component={DatabaseConnectionModal} />
- <Route path=":databaseId" component={DatabaseConnectionModal} />
- </Route>,
- {
- withRouter: true,
- initialRoute,
- storeInitialState: {
- settings,
- },
- },
- );
-
- await waitForLoaderToBeRemoved();
-
- return {
- history: checkNotNull(history),
- mockEventListener,
- };
-}
-
-describe("DatabaseConnectionModal", () => {
- describe("edit existing connection", () => {
- afterEach(() => {
- jest.restoreAllMocks();
- });
-
- it("should have save changes button disabled", async () => {
- setupDatabaseEndpoints(createMockDatabase());
- await setup({ databaseIdParam: "1" });
-
- const saveButton = await screen.findByRole("button", {
- name: /save changes/i,
- });
- expect(saveButton).toBeDisabled();
-
- const connectionField = await screen.findByLabelText("Connection String");
- await userEvent.type(connectionField, "Test Connection");
-
- await waitFor(() => {
- expect(saveButton).toBeEnabled();
- });
- });
-
- it("should trigger beforeunload event when database connection is edited", async () => {
- const { mockEventListener } = await setup();
-
- const displayNameInput = await screen.findByLabelText("Display name");
-
- await userEvent.type(displayNameInput, "Test database");
- const mockEvent = await waitFor(() => {
- return callMockEvent(mockEventListener, "beforeunload");
- });
- expect(mockEvent.preventDefault).toHaveBeenCalled();
- expect(mockEvent.returnValue).toBe(BEFORE_UNLOAD_UNSAVED_MESSAGE);
- });
-
- it("should not trigger beforeunload event when database connection is unchanged", async () => {
- const { mockEventListener } = await setup();
- const mockEvent = callMockEvent(mockEventListener, "beforeunload");
-
- expect(mockEvent.preventDefault).not.toHaveBeenCalled();
- expect(mockEvent.returnValue).toBe(undefined);
- });
-
- it("does not show custom warning modal when leaving with no changes via SPA navigation", async () => {
- const { history } = await setup({ initialRoute: "/home" });
-
- act(() => {
- history.push("/");
- });
-
- await waitForLoaderToBeRemoved();
-
- const displayNameInput = await screen.findByLabelText("Display name");
- await userEvent.type(displayNameInput, "ab");
- await userEvent.type(displayNameInput, "{backspace}{backspace}");
-
- act(() => {
- history.goBack();
- });
-
- expect(
- screen.queryByTestId("leave-confirmation"),
- ).not.toBeInTheDocument();
- });
-
- it("shows custom warning modal when leaving with unsaved changes via SPA navigation", async () => {
- const { history } = await setup({ initialRoute: "/home" });
-
- act(() => {
- history.push("/");
- });
-
- await waitForLoaderToBeRemoved();
-
- const displayNameInput = await screen.findByLabelText("Display name");
- await userEvent.type(displayNameInput, "Test database");
-
- act(() => {
- history.goBack();
- });
-
- expect(
- await screen.findByTestId("leave-confirmation"),
- ).toBeInTheDocument();
- });
-
- it("does not show custom warning modal after creating new database connection", async () => {
- const { history } = await setup({ initialRoute: "/home" });
-
- act(() => {
- history.push("/");
- });
-
- await waitForLoaderToBeRemoved();
-
- const displayNameInput = await screen.findByLabelText("Display name");
- await userEvent.type(displayNameInput, "Test database");
- const connectionStringInput =
- await screen.findByLabelText("Connection String");
- await userEvent.type(
- connectionStringInput,
- "file:/sample-database.db;USER=GUEST;PASSWORD=guest",
- );
-
- // need to add an id to the mocked db result so redirect can go the the correct location
- fetchMock.modifyRoute("database-post", {
- response: async (call) => {
- const lastCall = fetchMock.callHistory.lastCall(call.url);
- return { ...(await lastCall?.request?.json()), id: 1 };
- },
- });
-
- await userEvent.click(await screen.findByText("Save"));
-
- await waitFor(() => {
- expect(history.getCurrentLocation().pathname).toEqual(
- "/admin/databases/1",
- );
- });
-
- expect(
- screen.queryByTestId("leave-confirmation"),
- ).not.toBeInTheDocument();
- });
- });
-});
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx
index 91d344f67d7..445362f2c0a 100644
--- a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx
+++ b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx
@@ -13,7 +13,7 @@ import { GenericError } from "metabase/common/components/ErrorPages";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useSetting } from "metabase/common/hooks";
import CS from "metabase/css/core/index.css";
-import title from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { connect, useSelector } from "metabase/lib/redux";
import {
PLUGIN_DATABASE_REPLICATION,
@@ -22,11 +22,7 @@ import {
} from "metabase/plugins";
import { getUserIsAdmin } from "metabase/selectors/user";
import { Box, Divider, Flex } from "metabase/ui";
-import type {
- DatabaseData,
- DatabaseId,
- Database as DatabaseType,
-} from "metabase-types/api";
+import type { DatabaseId, Database as DatabaseType } from "metabase-types/api";
import { DatabaseConnectionInfoSection } from "../components/DatabaseConnectionInfoSection";
import { DatabaseDangerZoneSection } from "../components/DatabaseDangerZoneSection";
@@ -82,6 +78,8 @@ function DatabaseEditAppInner({
database?.name && [database?.name],
]);
+ usePageTitle(database?.name || "");
+
PLUGIN_DB_ROUTING.useRedirectDestinationDatabase(database);
return (
@@ -143,7 +141,4 @@ function DatabaseEditAppInner({
export const DatabaseEditApp = _.compose(
withRouter,
connect(undefined, mapDispatchToProps),
- title(
- ({ database }: { database: DatabaseData }) => database && database.name,
- ),
)(DatabaseEditAppInner);
diff --git a/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx b/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx
index cf3c7d4d83b..74f797cd930 100644
--- a/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx
@@ -1,4 +1,5 @@
import userEvent from "@testing-library/user-event";
+import { Route } from "react-router";
import { callMockEvent } from "__support__/events";
import {
@@ -17,7 +18,6 @@ import {
waitForLoaderToBeRemoved,
} from "__support__/ui";
import { BEFORE_UNLOAD_UNSAVED_MESSAGE } from "metabase/common/hooks/use-before-unload";
-import { Route } from "metabase/hoc/Title";
import { checkNotNull } from "metabase/lib/types";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
diff --git a/frontend/src/metabase/admin/permissions/routes.jsx b/frontend/src/metabase/admin/permissions/routes.jsx
index bff1a25440f..b5bfa19b084 100644
--- a/frontend/src/metabase/admin/permissions/routes.jsx
+++ b/frontend/src/metabase/admin/permissions/routes.jsx
@@ -1,7 +1,5 @@
-import { IndexRedirect } from "react-router";
-import { t } from "ttag";
+import { IndexRedirect, Route } from "react-router";
-import { Route } from "metabase/hoc/Title";
import {
PLUGIN_ADMIN_PERMISSIONS_DATABASE_GROUP_ROUTES,
PLUGIN_ADMIN_PERMISSIONS_DATABASE_ROUTES,
@@ -16,7 +14,7 @@ import DatabasesPermissionsPage from "./pages/DatabasePermissionsPage/DatabasesP
import GroupsPermissionsPage from "./pages/GroupDataPermissionsPage/GroupsPermissionsPage";
const getRoutes = () => (
- <Route title={t`Permissions`}>
+ <Route>
<IndexRedirect to="data" />
<Route path="data" component={DataPermissionsPage}>
diff --git a/frontend/src/metabase/admin/routes.jsx b/frontend/src/metabase/admin/routes.jsx
index 947b06dafcc..39ebf83e607 100644
--- a/frontend/src/metabase/admin/routes.jsx
+++ b/frontend/src/metabase/admin/routes.jsx
@@ -1,5 +1,5 @@
import { Fragment } from "react";
-import { IndexRedirect, IndexRoute, Redirect } from "react-router";
+import { IndexRedirect, IndexRoute, Redirect, Route } from "react-router";
import { t } from "ttag";
import AdminApp from "metabase/admin/app/components/AdminApp";
@@ -40,7 +40,6 @@ import { TasksApp } from "metabase/admin/tools/components/TasksApp";
import { ToolsApp } from "metabase/admin/tools/components/ToolsApp";
import { EmbeddingHubAdminSettingsPage } from "metabase/embedding/embedding-hub";
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { Route } from "metabase/hoc/Title";
import { DataModel } from "metabase/metadata/pages/DataModel";
import {
PLUGIN_ADMIN_SETTINGS,
@@ -64,7 +63,7 @@ import { RedirectToAllowedSettings, createAdminRouteGuard } from "./utils";
const getRoutes = (store, CanAccessSettings, IsAdmin) => (
<Route path="/admin" component={CanAccessSettings}>
- <Route title={t`Admin`} component={AdminApp}>
+ <Route component={AdminApp}>
<IndexRoute component={RedirectToAllowedSettings} />
<Route
path="databases"
diff --git a/frontend/src/metabase/admin/tools/components/TasksApp/TasksApp.unit.spec.tsx b/frontend/src/metabase/admin/tools/components/TasksApp/TasksApp.unit.spec.tsx
index 2d45a171d24..19cbb5e00e1 100644
--- a/frontend/src/metabase/admin/tools/components/TasksApp/TasksApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/tools/components/TasksApp/TasksApp.unit.spec.tsx
@@ -1,6 +1,7 @@
import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import type { Location } from "history";
+import { Route } from "react-router";
import {
setupDatabasesEndpoints,
@@ -16,7 +17,6 @@ import {
within,
} from "__support__/ui";
import { URL_UPDATE_DEBOUNCE_DELAY } from "metabase/common/hooks/use-url-state";
-import { Route } from "metabase/hoc/Title";
import type { ListTasksResponse } from "metabase-types/api";
import { createMockTask } from "metabase-types/api/mocks";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
diff --git a/frontend/src/metabase/auth/components/Login/Login.tsx b/frontend/src/metabase/auth/components/Login/Login.tsx
index 3532fe0ecd9..3ecebceebfc 100644
--- a/frontend/src/metabase/auth/components/Login/Login.tsx
+++ b/frontend/src/metabase/auth/components/Login/Login.tsx
@@ -2,6 +2,7 @@ import type { Location } from "history";
import { t } from "ttag";
import _ from "underscore";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { useSelector } from "metabase/lib/redux";
import type { AuthProvider } from "metabase/plugins/types";
import { getApplicationName } from "metabase/selectors/whitelabel";
@@ -29,6 +30,8 @@ export const Login = ({ params, location }: LoginProps): JSX.Element => {
const redirectUrl = location?.query?.redirect;
const applicationName = useSelector(getApplicationName);
+ usePageTitle(t`Login`);
+
const [passwordProvider, otherProviders] = _.partition(
providers,
(provider) => provider.name === "password",
diff --git a/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx b/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx
index 180e932f8f0..5db9ba2c374 100644
--- a/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/AutomaticDashboardApp/AutomaticDashboardApp.tsx
@@ -18,7 +18,7 @@ import {
useDashboardContext,
} from "metabase/dashboard/context";
import { useDashboardUrlQuery } from "metabase/dashboard/hooks";
-import { SetTitle } from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { addUndo } from "metabase/redux/undo";
@@ -40,6 +40,8 @@ const AutomaticDashboardAppInner = () => {
const { dashboard, parameters, isHeaderVisible, tabs } =
useDashboardContext();
+ usePageTitle(dashboard?.name || "", { titleIndex: 1 });
+
const dispatch = useDispatch();
const saveDashboard = (newDashboard: Omit<IDashboard, "id">) =>
@@ -98,8 +100,6 @@ const AutomaticDashboardAppInner = () => {
"AutomaticDashboard--withSidebar": hasSidebar,
})}
>
- {dashboard && <SetTitle title={dashboard.name} />}
-
{isHeaderVisible && (
<div
className={cx(CS.bgWhite, CS.borderBottom)}
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
index 573ef55bc66..e8a40a9f811 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
@@ -21,9 +21,16 @@ import {
import { DashboardLeaveConfirmationModal } from "metabase/dashboard/components/DashboardLeaveConfirmationModal";
import { addDashboardQuestion } from "metabase/dashboard/components/QuestionPicker/actions";
import { SIDEBAR_NAME } from "metabase/dashboard/constants";
-import { DashboardContextProvider } from "metabase/dashboard/context";
+import {
+ DashboardContextProvider,
+ useDashboardContext,
+} from "metabase/dashboard/context";
import { useDashboardUrlQuery } from "metabase/dashboard/hooks";
import { useAutoScrollToDashcard } from "metabase/dashboard/hooks/use-auto-scroll-to-dashcard";
+import {
+ usePageTitle,
+ usePageTitleWithLoadingTime,
+} from "metabase/hooks/use-page-title";
import { parseHashOptions, stringifyHashOptions } from "metabase/lib/browser";
import { isWithinIframe } from "metabase/lib/dom";
import { useDispatch, useSelector } from "metabase/lib/redux";
@@ -32,9 +39,8 @@ import { setErrorPage } from "metabase/redux/app";
import type { DashboardId, Dashboard as IDashboard } from "metabase-types/api";
import { useRegisterDashboardMetabotContext } from "../../hooks/use-register-dashboard-metabot-context";
-import { getFavicon } from "../../selectors";
+import { getDocumentTitle, getFavicon } from "../../selectors";
-import { DashboardTitle } from "./DashboardTitle";
import { useDashboardLocationSync } from "./use-dashboard-location-sync";
import { useSlowCardNotification } from "./use-slow-card-notification";
@@ -58,10 +64,18 @@ function DashboardAppInner({
const pageFavicon = useSelector(getFavicon);
useFavicon({ favicon: pageFavicon });
useSlowCardNotification();
+ const { dashboard, loadingStartTime, isRunning } = useDashboardContext();
+ const documentTitle = useSelector(getDocumentTitle);
+
+ usePageTitleWithLoadingTime(documentTitle || dashboard?.name || "", {
+ titleIndex: 2,
+ startTime: loadingStartTime,
+ isRunning,
+ });
+ usePageTitle("Dashboard", { titleIndex: 1 });
return (
<>
- <DashboardTitle />
<div className={cx(CS.shrinkBelowContentSize, CS.fullHeight)}>
<DashboardLeaveConfirmationModal route={route} />
<Dashboard />
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardTitle.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardTitle.tsx
deleted file mode 100644
index dfb3ac5d48d..00000000000
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardTitle.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import _ from "underscore";
-
-import { useDashboardContext } from "metabase/dashboard/context";
-import { getDocumentTitle } from "metabase/dashboard/selectors";
-import title from "metabase/hoc/Title";
-import titleWithLoadingTime from "metabase/hoc/TitleWithLoadingTime";
-import { useSelector } from "metabase/lib/redux";
-
-/**
- * Updates the browser tab title to reflect the current dashboard name and loading state.
- * Uses the dashboard from the dashboard context to show loading times when the
- * dashboard is slow and then shows the title
- */
-
-export const DashboardTitle = () => {
- const { dashboard } = useDashboardContext();
- const documentTitle = useSelector(getDocumentTitle);
-
- const Component = _.compose(
- title(() => ({
- title: documentTitle || dashboard?.name,
- titleIndex: 1,
- })),
- titleWithLoadingTime("loadingStartTime"),
- )(() => null);
-
- return <Component />;
-};
diff --git a/frontend/src/metabase/hoc/Title.jsx b/frontend/src/metabase/hoc/Title.jsx
deleted file mode 100644
index 0023de3cbe7..00000000000
--- a/frontend/src/metabase/hoc/Title.jsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import PropTypes from "prop-types";
-import { Component, cloneElement, memo } from "react";
-import { Route as _Route } from "react-router";
-import _ from "underscore";
-
-const componentStack = [];
-
-const SEPARATOR = " · ";
-
-const updateDocumentTitle = _.debounce(() => {
- document.title = componentStack
- .sort((a, b) => (a._titleIndex || 0) - (b._titleIndex || 0))
- .map((component) => component._documentTitle)
- .filter((title) => title)
- .reverse()
- .join(SEPARATOR);
-});
-
-/**
- * @deprecated HOCs are deprecated
- */
-const title = (documentTitleOrGetter) => (ComposedComponent) =>
- class extends Component {
- static displayName =
- "Title[" +
- (ComposedComponent.displayName || ComposedComponent.name) +
- "]";
-
- UNSAFE_componentWillMount() {
- componentStack.push(this);
- this._updateDocumentTitle();
- }
- componentDidUpdate() {
- this._updateDocumentTitle();
- }
- componentWillUnmount() {
- for (let i = 0; i < componentStack.length; i++) {
- if (componentStack[i] === this) {
- componentStack.splice(i, 1);
- break;
- }
- }
- this._updateDocumentTitle();
- }
-
- _updateDocumentTitle() {
- if (typeof documentTitleOrGetter === "string") {
- this._documentTitle = documentTitleOrGetter;
- } else if (typeof documentTitleOrGetter === "function") {
- const result = documentTitleOrGetter(this.props);
- if (result == null) {
- // title functions might return null before data is loaded
- this._documentTitle = "";
- } else if (result instanceof String || typeof result === "string") {
- this._documentTitle = result;
- } else if (typeof result === "object") {
- // The getter can return an object with a `refresh` promise along with
- // the title. When that promise resolves, we call
- // `documentTitleOrGetter` again.
- this._documentTitle = result.title;
- result.refresh?.then(() => this._updateDocumentTitle());
-
- // Getter can also return a priority index used for sorting the component stack
- if (result.titleIndex) {
- this._titleIndex = result.titleIndex;
- }
- }
- }
- updateDocumentTitle();
- }
-
- render() {
- return <ComposedComponent {...this.props} />;
- }
- };
-
-export default title;
-
-/**
- * Component version of the title HOC
- * @type {(props: { title: string }) => ReactNode}
- */
-export const SetTitle = memo(function SetTitle(props) {
- const Component = title(props.title)(() => null);
- return <Component />;
-});
-
-SetTitle.propTypes = {
- title: PropTypes.string,
-};
-
-// react-router Route wrapper that adds a `title` property
-export class Route extends _Route {
- static createRouteFromReactElement(element) {
- if (element.props.title) {
- element = cloneElement(element, {
- component: title(element.props.title)(
- element.props.component || (({ children }) => children),
- ),
- });
- }
- return _Route.createRouteFromReactElement(element);
- }
-}
-
-Route.propTypes = {
- title: PropTypes.string,
- path: PropTypes.string,
- component: PropTypes.any,
-};
diff --git a/frontend/src/metabase/hoc/TitleWithLoadingTime.jsx b/frontend/src/metabase/hoc/TitleWithLoadingTime.jsx
deleted file mode 100644
index 0954692c510..00000000000
--- a/frontend/src/metabase/hoc/TitleWithLoadingTime.jsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import title from "metabase/hoc/Title";
-import { delay } from "metabase/lib/promise";
-
-const SECONDS_UNTIL_DISPLAY = 10;
-
-/**
- * @deprecated HOCs are deprecated
- */
-export default (startTimePropName) => (ComposedComponent) =>
- title(({ [startTimePropName]: startTime, isRunning }) => {
- if (startTime == null || !isRunning) {
- return "";
- }
- const totalSeconds = (performance.now() - startTime) / 1000;
- const title =
- totalSeconds < SECONDS_UNTIL_DISPLAY
- ? "" // don't display the title until SECONDS_UNTIL_DISPLAY have elapsed
- : [totalSeconds / 60, totalSeconds % 60] // minutes, seconds
- .map(Math.floor) // round both down
- .map((x) => (x < 10 ? `0${x}` : `${x}`)) // pad with "0" to two digits
- .join(":"); // separate with ":"
- return { title, refresh: delay(100) };
- })(
- // remove the start time prop to prevent affecting child components
- ({ [startTimePropName]: _removed, ...props }) => (
- <ComposedComponent {...props} />
- ),
- );
diff --git a/frontend/src/metabase/hooks/use-page-title.ts b/frontend/src/metabase/hooks/use-page-title.ts
new file mode 100644
index 00000000000..a04777d1dbd
--- /dev/null
+++ b/frontend/src/metabase/hooks/use-page-title.ts
@@ -0,0 +1,104 @@
+import dayjs from "dayjs";
+import { useEffect, useRef, useState } from "react";
+import _ from "underscore";
+
+type TitleEntry = {
+ id: string;
+ title: string;
+ titleIndex: number;
+};
+
+const titleMap = new Map<string, TitleEntry>();
+const SEPARATOR = " · ";
+
+const updateDocumentTitle = _.debounce(() => {
+ document.title = Array.from(titleMap.values())
+ .sort((a, b) => a.titleIndex - b.titleIndex)
+ .map((entry) => entry.title)
+ .filter((title) => title)
+ .reverse()
+ .join(SEPARATOR);
+}, 100);
+
+let nextId = 0;
+
+/**
+ * Hook to set the page title with support for hierarchical stacking.
+ *
+ * Multiple components can set titles simultaneously, and they will be combined
+ * with " · " separator. Higher index titles appear first.
+ */
+export function usePageTitle(
+ title: string,
+ options?: {
+ titleIndex?: number;
+ },
+) {
+ const idRef = useRef<string>(`title-${nextId++}`);
+ const titleIndex = options?.titleIndex ?? 0;
+
+ useEffect(() => {
+ const id = idRef.current;
+
+ titleMap.set(id, { id, title, titleIndex });
+ updateDocumentTitle();
+
+ return () => {
+ titleMap.delete(id);
+ updateDocumentTitle();
+ };
+ }, [title, titleIndex]);
+}
+
+const SECONDS_UNTIL_DISPLAY = 10;
+
+/**
+ * Hook to set page title with optional loading time display.
+ *
+ * Displays the loading time in MM:SS format in the page title. Updates every 100ms.
+ */
+export function usePageTitleWithLoadingTime(
+ title: string,
+ options: {
+ titleIndex?: number;
+ startTime: number | null;
+ isRunning: boolean;
+ },
+) {
+ const [, setRefreshTrigger] = useState(0);
+ const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const { startTime, isRunning } = options || {};
+
+ useEffect(() => {
+ if (startTime != null && isRunning) {
+ intervalRef.current = setInterval(() => {
+ setRefreshTrigger((prev) => prev + 1);
+ }, 100);
+ } else if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+
+ return () => {
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ };
+ }, [startTime, isRunning]);
+
+ const getLoadingTime = () => {
+ if (startTime == null || !isRunning) {
+ return "";
+ }
+ const totalSeconds = (performance.now() - startTime) / 1000;
+ if (totalSeconds < SECONDS_UNTIL_DISPLAY) {
+ return ""; // don't display until threshold reached
+ }
+ return dayjs.duration(totalSeconds, "seconds").format("mm:ss");
+ };
+
+ const loadingTime = getLoadingTime();
+ const finalTitle = loadingTime ? `${loadingTime} ${title}` : title;
+ usePageTitle(finalTitle, { titleIndex: options?.titleIndex });
+}
diff --git a/frontend/src/metabase/hooks/use-page-title.unit.spec.ts b/frontend/src/metabase/hooks/use-page-title.unit.spec.ts
new file mode 100644
index 00000000000..25084c06310
--- /dev/null
+++ b/frontend/src/metabase/hooks/use-page-title.unit.spec.ts
@@ -0,0 +1,181 @@
+import { renderHook, waitFor } from "@testing-library/react";
+
+import { usePageTitle, usePageTitleWithLoadingTime } from "./use-page-title";
+
+describe("usePageTitle hooks", () => {
+ describe("usePageTitle", () => {
+ beforeEach(() => {
+ document.title = "";
+ });
+
+ it("should set a simple title", async () => {
+ renderHook(() => usePageTitle("Test Page"));
+ await waitFor(() => {
+ expect(document.title).toBe("Test Page");
+ });
+ });
+
+ it("should update title when value changes", async () => {
+ const { rerender } = renderHook(({ title }) => usePageTitle(title), {
+ initialProps: { title: "First Title" },
+ });
+
+ await waitFor(() => {
+ expect(document.title).toBe("First Title");
+ });
+
+ rerender({ title: "Second Title" });
+ await waitFor(() => {
+ expect(document.title).toBe("Second Title");
+ });
+ });
+
+ it("should stack titles with separator", async () => {
+ renderHook(() => usePageTitle("Metabase", { titleIndex: 0 }));
+ renderHook(() => usePageTitle("Admin", { titleIndex: 0 }));
+ renderHook(() => usePageTitle("Databases", { titleIndex: 1 }));
+
+ await waitFor(() => {
+ expect(document.title).toBe("Databases · Admin · Metabase");
+ });
+ });
+
+ it("should clean up title on unmount", async () => {
+ const { unmount: unmount1 } = renderHook(() => usePageTitle("Keep This"));
+ const { unmount: unmount2 } = renderHook(() =>
+ usePageTitle("Remove This"),
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("Remove This · Keep This");
+ });
+
+ unmount2();
+ await waitFor(() => {
+ expect(document.title).toBe("Keep This");
+ });
+
+ unmount1();
+ await waitFor(() => {
+ expect(document.title).toBe("");
+ });
+ });
+
+ it("should filter out empty titles", async () => {
+ renderHook(() => usePageTitle("Valid"));
+ renderHook(() => usePageTitle(""));
+
+ // Empty title should be filtered out
+ await waitFor(() => {
+ expect(document.title).toBe("Valid");
+ });
+ });
+ });
+
+ describe("usePageTitleWithLoadingTime", () => {
+ beforeEach(() => {
+ document.title = "";
+ });
+
+ it("should set title without loading time when not running", async () => {
+ renderHook(() =>
+ usePageTitleWithLoadingTime("Dashboard", {
+ startTime: performance.now(),
+ isRunning: false,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("Dashboard");
+ });
+ });
+
+ it("should set title without loading time when startTime is null", async () => {
+ renderHook(() =>
+ usePageTitleWithLoadingTime("Dashboard", {
+ startTime: null,
+ isRunning: true,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("Dashboard");
+ });
+ });
+
+ it("should not show loading time before 10 seconds", async () => {
+ const startTime = performance.now();
+
+ renderHook(() =>
+ usePageTitleWithLoadingTime("Dashboard", {
+ startTime,
+ isRunning: true,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("Dashboard");
+ });
+ });
+
+ it("should format time as MM:SS", async () => {
+ // Start time 75 seconds ago (1:15)
+ const startTime = performance.now() - 75000;
+
+ renderHook(() =>
+ usePageTitleWithLoadingTime("Dashboard", {
+ startTime,
+ isRunning: true,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("01:15 Dashboard");
+ });
+ });
+
+ it("should stop showing loading time when isRunning becomes false", async () => {
+ const startTime = performance.now() - 60000;
+
+ const { rerender } = renderHook(
+ ({ isRunning }) =>
+ usePageTitleWithLoadingTime("Dashboard", {
+ startTime,
+ isRunning,
+ }),
+ { initialProps: { isRunning: true } },
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("01:00 Dashboard");
+ });
+
+ rerender({ isRunning: false });
+
+ await waitFor(() => {
+ expect(document.title).toBe("Dashboard");
+ });
+ });
+
+ it("should respect titleIndex option", async () => {
+ const { unmount: unmount1 } = renderHook(() =>
+ usePageTitle("Metabase", { titleIndex: 0 }),
+ );
+
+ const { unmount: unmount2 } = renderHook(() =>
+ usePageTitleWithLoadingTime("Dashboard", {
+ titleIndex: 1,
+ startTime: performance.now() - 120000, // 2 minutes ago
+ isRunning: true,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(document.title).toBe("02:00 Dashboard · Metabase");
+ });
+
+ unmount2();
+ unmount1();
+ });
+ });
+});
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
index bab2f76af3d..5b7c77dcb5a 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
@@ -10,7 +10,7 @@ import Actions from "metabase/entities/actions";
import Databases from "metabase/entities/databases";
import Questions from "metabase/entities/questions";
import Tables from "metabase/entities/tables";
-import title from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { connect } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import ModelActionsView from "metabase/models/components/ModelActions";
@@ -57,6 +57,8 @@ function ModelActions({
}: Props) {
const [hasFetchedTableMetadata, setHasFetchedTableMetadata] = useState(false);
+ usePageTitle(model?.displayName() || "");
+
const database = model.database();
const hasActions = actions.length > 0;
const hasActionsEnabled = database != null && database.hasActionsEnabled();
@@ -114,10 +116,6 @@ function getModelId(state: State, props: OwnProps) {
return Urls.extractEntityId(props.params.slug);
}
-function getPageTitle({ model }: Props) {
- return model?.displayName();
-}
-
// eslint-disable-next-line import/no-default-export -- deprecated usage
export default _.compose(
Questions.load({ id: getModelId, entityAlias: "model" }),
@@ -131,5 +129,4 @@ export default _.compose(
null,
mapDispatchToProps,
),
- title(getPageTitle),
)(ModelActions);
diff --git a/frontend/src/metabase/models/routes.tsx b/frontend/src/metabase/models/routes.tsx
index 46f93a66613..ffd87f64680 100644
--- a/frontend/src/metabase/models/routes.tsx
+++ b/frontend/src/metabase/models/routes.tsx
@@ -1,9 +1,8 @@
-import { IndexRedirect, Redirect } from "react-router";
+import { IndexRedirect, Redirect, Route } from "react-router";
import ActionCreatorModal from "metabase/actions/containers/ActionCreatorModal/ActionCreatorModal";
import { ModelDetailPage } from "metabase/detail-view/pages/ModelDetailPage/ModelDetailPage";
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { Route } from "metabase/hoc/Title";
import ModelActions from "metabase/models/containers/ModelActions/ModelActions";
Intl.Collator("en");
diff --git a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx
index dc22eb5c1e3..95cbb5c9cab 100644
--- a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.styled.tsx
@@ -40,7 +40,6 @@ export const SearchInputContainer = styled.div<{
}
return css`
background-color: var(--mb-color-bg-white);
-
&:hover {
background-color: var(--mb-color-bg-light);
}
diff --git a/frontend/src/metabase/public/containers/PublicAction/PublicAction.tsx b/frontend/src/metabase/public/containers/PublicAction/PublicAction.tsx
index b6d851ddc59..35c98ed593d 100644
--- a/frontend/src/metabase/public/containers/PublicAction/PublicAction.tsx
+++ b/frontend/src/metabase/public/containers/PublicAction/PublicAction.tsx
@@ -2,7 +2,7 @@ import { useCallback, useState } from "react";
import ActionForm from "metabase/actions/components/ActionForm";
import { getSuccessMessage } from "metabase/actions/utils";
-import title from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { PublicApi } from "metabase/services";
import type {
ParametersForActionExecution,
@@ -26,6 +26,8 @@ function PublicAction({ action, publicId, onError }: Props) {
const [isSubmitted, setSubmitted] = useState(false);
const successMessage = getSuccessMessage(action);
+ usePageTitle(action.name);
+
const handleSubmit = useCallback(
async (parameters: ParametersForActionExecution) => {
try {
@@ -50,7 +52,5 @@ function PublicAction({ action, publicId, onError }: Props) {
);
}
-const getPageTitle = ({ action }: Props) => action.name;
-
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default title(getPageTitle)(PublicAction);
+export default PublicAction;
diff --git a/frontend/src/metabase/public/containers/PublicApp/PublicApp.tsx b/frontend/src/metabase/public/containers/PublicApp/PublicApp.tsx
index 2506cd570dd..dbaea1856bd 100644
--- a/frontend/src/metabase/public/containers/PublicApp/PublicApp.tsx
+++ b/frontend/src/metabase/public/containers/PublicApp/PublicApp.tsx
@@ -1,10 +1,12 @@
import { useLayoutEffect } from "react";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { isWithinIframe } from "metabase/lib/dom";
-import { connect } from "metabase/lib/redux";
+import { connect, useSelector } from "metabase/lib/redux";
import { PublicError } from "metabase/public/components/PublicError";
import { PublicNotFound } from "metabase/public/components/PublicNotFound";
import { getErrorPage } from "metabase/selectors/app";
+import { getApplicationName } from "metabase/selectors/whitelabel";
import { PublicStatusListing } from "metabase/status/components/PublicStatusListing";
import type { AppErrorDescriptor, State } from "metabase-types/store";
@@ -25,6 +27,9 @@ function mapStateToProps(state: State) {
}
function PublicApp({ errorPage, children }: Props) {
+ const applicationName = useSelector(getApplicationName);
+ usePageTitle(applicationName, { titleIndex: 0 });
+
useLayoutEffect(() => {
if (isWithinIframe()) {
document.body.style.backgroundColor = "transparent";
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView.tsx
index 8ef7667281c..77f2e91ede1 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView.tsx
@@ -6,7 +6,7 @@ import DashboardS from "metabase/css/dashboard.module.css";
import { Dashboard } from "metabase/dashboard/components/Dashboard";
import { DashboardHeaderButtonRow } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow";
import { useDashboardContext } from "metabase/dashboard/context";
-import { SetTitle } from "metabase/hoc/Title";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { isWithinIframe } from "metabase/lib/dom";
import { getTabHiddenParameterSlugs } from "metabase/public/lib/tab-parameters";
import type { DisplayTheme } from "metabase/public/lib/types";
@@ -35,6 +35,8 @@ export function PublicOrEmbeddedDashboardView() {
downloadsEnabled,
} = useDashboardContext();
+ usePageTitle(dashboard?.name || "", { titleIndex: 1 });
+
const buttons = !isWithinIframe() ? (
<DashboardHeaderButtonRow
canResetFilters={false}
@@ -82,7 +84,6 @@ export function PublicOrEmbeddedDashboardView() {
pdfDownloadsEnabled={downloadsEnabled.pdf}
withFooter={withFooter}
>
- {dashboard && <SetTitle title={dashboard.name} />}
<FullWidthContainer
className={cx({
[DashboardS.DashboardFullscreen]: isFullscreen,
diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
index 5701f8b2377..9f804cf8bd3 100644
--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
@@ -16,8 +16,7 @@ import { useLoadingTimer } from "metabase/common/hooks/use-loading-timer";
import { useWebNotification } from "metabase/common/hooks/use-web-notification";
import Bookmark from "metabase/entities/bookmarks";
import Timelines from "metabase/entities/timelines";
-import title from "metabase/hoc/Title";
-import titleWithLoadingTime from "metabase/hoc/TitleWithLoadingTime";
+import { usePageTitleWithLoadingTime } from "metabase/hooks/use-page-title";
import { isWithinIframe } from "metabase/lib/dom";
import { connect, useSelector } from "metabase/lib/redux";
import { closeNavbar } from "metabase/redux/app";
@@ -32,7 +31,6 @@ import {
import type {
BookmarkId,
Bookmark as BookmarkType,
- Card,
Series,
Timeline,
} from "metabase-types/api";
@@ -249,8 +247,16 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
queryBuilderMode,
didFirstNonTableChartGenerated,
setDidFirstNonTableChartRender,
+ documentTitle,
+ queryStartTime,
} = props;
+ usePageTitleWithLoadingTime(documentTitle || card?.name || t`Question`, {
+ titleIndex: 1,
+ startTime: queryStartTime,
+ isRunning: uiControls.isRunning,
+ });
+
const didTrackFirstNonTableChartGeneratedRef = useRef(
didFirstNonTableChartGenerated,
);
@@ -487,9 +493,4 @@ export const QueryBuilder = _.compose(
Bookmark.loadList(),
Timelines.loadList(timelineProps),
connector,
- title(({ card, documentTitle }: { card: Card; documentTitle: string }) => ({
- title: documentTitle || card?.name || t`Question`,
- titleIndex: 1,
- })),
- titleWithLoadingTime("queryStartTime"),
)(QueryBuilderInner);
diff --git a/frontend/src/metabase/routes-public.jsx b/frontend/src/metabase/routes-public.jsx
index b33002ac7fd..8cbfa1c62bb 100644
--- a/frontend/src/metabase/routes-public.jsx
+++ b/frontend/src/metabase/routes-public.jsx
@@ -1,4 +1,5 @@
-import { Route } from "metabase/hoc/Title";
+import { Route } from "react-router";
+
import { PLUGIN_PUBLIC_SHARING } from "metabase/plugins";
import { PublicNotFound } from "metabase/public/components/PublicNotFound";
import PublicAction from "metabase/public/containers/PublicAction";
@@ -6,12 +7,10 @@ import PublicApp from "metabase/public/containers/PublicApp";
import { PublicOrEmbeddedQuestion } from "metabase/public/containers/PublicOrEmbeddedQuestion";
import { PublicOrEmbeddedDashboardPage } from "./public/containers/PublicOrEmbeddedDashboard";
-import { getApplicationName } from "./selectors/whitelabel";
export const getRoutes = (store) => {
- const applicationName = getApplicationName(store.getState());
return (
- <Route title={applicationName}>
+ <Route>
<Route path="public" component={PublicApp}>
<Route path="action/:uuid" component={PublicAction} />
<Route path="question/:uuid" component={PublicOrEmbeddedQuestion} />
diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsx
index 6a664bc2907..f31bd512abf 100644
--- a/frontend/src/metabase/routes.jsx
+++ b/frontend/src/metabase/routes.jsx
@@ -1,5 +1,4 @@
-import { IndexRedirect, IndexRoute, Redirect } from "react-router";
-import { t } from "ttag";
+import { IndexRedirect, IndexRoute, Redirect, Route } from "react-router";
import App from "metabase/App.tsx";
import getAccountRoutes from "metabase/account/routes";
@@ -32,7 +31,6 @@ import { AutomaticDashboardApp } from "metabase/dashboard/containers/AutomaticDa
import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";
import { TableDetailPage } from "metabase/detail-view/pages/TableDetailPage";
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { Route } from "metabase/hoc/Title";
import { HomePage } from "metabase/home/components/HomePage";
import { Onboarding } from "metabase/home/components/Onboarding";
import { trackPageView } from "metabase/lib/analytics";
@@ -74,14 +72,12 @@ import {
} from "./route-guards";
import { createEntityIdRedirect } from "./routes-stable-id-aware";
import { getSetting } from "./selectors/settings";
-import { getApplicationName } from "./selectors/whitelabel";
export const getRoutes = (store) => {
- const applicationName = getApplicationName(store.getState());
const hasUserSetup = getSetting(store.getState(), "has-user-setup");
return (
- <Route title={applicationName} component={App}>
+ <Route component={App}>
{/* SETUP */}
<Route
path="/setup"
@@ -118,8 +114,8 @@ export const getRoutes = (store) => {
<Route path="/auth">
<IndexRedirect to="/auth/login" />
<Route component={IsNotAuthenticated}>
- <Route path="login" title={t`Login`} component={Login} />
- <Route path="login/:provider" title={t`Login`} component={Login} />
+ <Route path="login" component={Login} />
+ <Route path="login/:provider" component={Login} />
</Route>
<Route path="logout" component={Logout} />
<Route path="forgot_password" component={ForgotPassword} />
@@ -145,22 +141,14 @@ export const getRoutes = (store) => {
}}
/>
- <Route
- path="getting-started"
- title={t`Getting Started`}
- component={CanAccessOnboarding}
- >
+ <Route path="getting-started" component={CanAccessOnboarding}>
<IndexRoute component={Onboarding} />
</Route>
- <Route path="search" title={t`Search`} component={SearchApp} />
+ <Route path="search" component={SearchApp} />
{/* Send historical /archive route to trash - can remove in v52 */}
<Redirect from="archive" to="trash" replace />
- <Route
- path="trash"
- title={t`Trash`}
- component={TrashCollectionLanding}
- />
+ <Route path="trash" component={TrashCollectionLanding} />
{PLUGIN_DOCUMENTS.getRoutes()}
@@ -211,11 +199,7 @@ export const getRoutes = (store) => {
})}
/>
- <Route
- path="dashboard/:slug"
- title={t`Dashboard`}
- component={DashboardApp}
- >
+ <Route path="dashboard/:slug" component={DashboardApp}>
<ModalRoute
path="move"
modal={DashboardMoveModalConnected}
@@ -251,11 +235,7 @@ export const getRoutes = (store) => {
<Route path="/model">
<IndexRoute component={QueryBuilder} />
- <Route
- path="new"
- title={t`New Model`}
- component={NewModelOptions}
- />
+ <Route path="new" component={NewModelOptions} />
<Route path=":slug" component={QueryBuilder} />
<Route path=":slug/notebook" component={QueryBuilder} />
<Route path=":slug/query" component={QueryBuilder} />
@@ -307,7 +287,7 @@ export const getRoutes = (store) => {
<Route path="/auto/dashboard/*" component={AutomaticDashboardApp} />
{/* REFERENCE */}
- <Route path="/reference" title={t`Data Reference`}>
+ <Route path="/reference">
<IndexRedirect to="/reference/databases" />
<Route path="segments" component={SegmentListContainer} />
<Route
diff --git a/frontend/src/metabase/search/containers/SearchApp.jsx b/frontend/src/metabase/search/containers/SearchApp.jsx
index bf2f793e46b..cea98ee2e09 100644
--- a/frontend/src/metabase/search/containers/SearchApp.jsx
+++ b/frontend/src/metabase/search/containers/SearchApp.jsx
@@ -11,6 +11,7 @@ import { PaginationControls } from "metabase/common/components/PaginationControl
import { NoObjectError } from "metabase/common/components/errors/NoObjectError";
import { usePagination } from "metabase/common/hooks/use-pagination";
import Search from "metabase/entities/search";
+import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/lib/redux";
import { SearchSidebar } from "metabase/search/components/SearchSidebar";
import {
@@ -34,6 +35,8 @@ import { Box, Group, Paper, Text } from "metabase/ui";
function SearchApp({ location }) {
const dispatch = useDispatch();
+ usePageTitle(t`Search`);
+
const { handleNextPage, handlePreviousPage, page } = usePagination();
const searchText = useMemo(
diff --git a/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx b/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
index ad418b1d889..d2044380ef1 100644
--- a/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
+++ b/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
@@ -1,4 +1,5 @@
import userEvent from "@testing-library/user-event";
+import { Route } from "react-router";
import {
setupCollectionByIdEndpoint,
@@ -13,7 +14,6 @@ import {
waitForLoaderToBeRemoved,
within,
} from "__support__/ui";
-import { Route } from "metabase/hoc/Title";
import { checkNotNull } from "metabase/lib/types";
import SearchApp from "metabase/search/containers/SearchApp";
import type { SearchFilters } from "metabase/search/types";