Skip to content

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

UXW-491: prevent users from enterling long document titles (#62243)

Aleksandr Lesnenko2bc99f976a54
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.module.css b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.module.css
new file mode 100644
index 00000000000..b3e1ec67de9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.module.css
@@ -0,0 +1,15 @@
+.titleInput {
+ border: none !important;
+ padding: 0 !important;
+ font-size: 2rem !important;
+ font-weight: bold !important;
+}
+
+.titleContainer {
+ flex: 1;
+ min-width: 0;
+}
+
+.actionsContainer {
+ flex-shrink: 0;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx
new file mode 100644
index 00000000000..51daa6cadb2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx
@@ -0,0 +1,159 @@
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import DateTime, {
+ getFormattedTime,
+} from "metabase/common/components/DateTime";
+import {
+ ActionIcon,
+ Button,
+ Flex,
+ Icon,
+ Menu,
+ Text,
+ TextInput,
+ Tooltip,
+} from "metabase/ui";
+import type { Document } from "metabase-types/api";
+
+import { DOCUMENT_TITLE_MAX_LENGTH } from "../constants";
+
+import S from "./DocumentHeader.module.css";
+
+interface DocumentHeaderProps {
+ document: Document | undefined;
+ documentTitle: string;
+ isNewDocument: boolean;
+ canWrite: boolean;
+ showSaveButton: boolean;
+ isBookmarked: boolean;
+ onTitleChange: (title: string) => void;
+ onSave: () => void;
+ onMove: () => void;
+ onToggleBookmark: () => void;
+ onArchive: () => void;
+}
+
+export const DocumentHeader = ({
+ document,
+ documentTitle,
+ isNewDocument,
+ canWrite,
+ showSaveButton,
+ isBookmarked,
+ onTitleChange,
+ onSave,
+ onMove,
+ onToggleBookmark,
+ onArchive,
+}: DocumentHeaderProps) => {
+ const handlePrint = useCallback(() => {
+ window.print();
+ }, []);
+
+ return (
+ <Flex
+ justify="space-between"
+ align="flex-start"
+ gap="1rem"
+ mt="xl"
+ pt="xl"
+ pb="1rem"
+ maw={900}
+ mx="auto"
+ w="100%"
+ >
+ <Flex direction="column" className={S.titleContainer}>
+ <TextInput
+ aria-label={t`Document Title`}
+ autoFocus={isNewDocument}
+ value={documentTitle}
+ onChange={(event) => {
+ const value = event.currentTarget.value;
+ if (value.length <= DOCUMENT_TITLE_MAX_LENGTH) {
+ onTitleChange(value);
+ }
+ }}
+ placeholder={t`New document`}
+ readOnly={!canWrite}
+ maxLength={DOCUMENT_TITLE_MAX_LENGTH}
+ classNames={{ input: S.titleInput }}
+ />
+ {document && (
+ <Flex gap="md">
+ <Flex align="center" gap="0.25rem" c="text-secondary">
+ <Icon name="person" />
+ <Text>{document.creator.common_name}</Text>
+ </Flex>
+ <Tooltip
+ label={getFormattedTime(document.updated_at, "default", {
+ local: true,
+ })}
+ >
+ <Flex align="center" gap="0.25rem" c="text-secondary">
+ <Icon name="clock" />
+ <DateTime value={document.updated_at} unit="day" />
+ </Flex>
+ </Tooltip>
+ </Flex>
+ )}
+ </Flex>
+ <Flex gap="md" align="center" className={S.actionsContainer}>
+ {showSaveButton && (
+ <Button onClick={onSave} variant="filled" data-hide-on-print>
+ {t`Save`}
+ </Button>
+ )}
+ <Menu position="bottom-end">
+ <Menu.Target>
+ <ActionIcon
+ variant="subtle"
+ size="md"
+ aria-label={t`More options`}
+ data-hide-on-print
+ >
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={<Icon name="document" />}
+ onClick={handlePrint}
+ >
+ {t`Print Document`}
+ </Menu.Item>
+ {!isNewDocument && (
+ <>
+ {canWrite && (
+ <Menu.Item
+ leftSection={<Icon name="move" />}
+ onClick={onMove}
+ >
+ {t`Move`}
+ </Menu.Item>
+ )}
+ <Menu.Item
+ leftSection={<Icon name={"bookmark"} />}
+ onClick={onToggleBookmark}
+ >
+ {isBookmarked ? t`Remove from Bookmarks` : t`Bookmark`}
+ </Menu.Item>
+ {canWrite && (
+ <>
+ <Menu.Divider />
+ <Menu.Item
+ leftSection={<Icon name="trash" />}
+ onClick={onArchive}
+ >
+ {t`Move to trash`}
+ </Menu.Item>
+ </>
+ )}
+ </>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ </Flex>
+ </Flex>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx
new file mode 100644
index 00000000000..ee3033599a4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx
@@ -0,0 +1,188 @@
+import userEvent from "@testing-library/user-event";
+
+import { render, screen } from "__support__/ui";
+import { createMockDocument, createMockUser } from "metabase-types/api/mocks";
+
+import { DOCUMENT_TITLE_MAX_LENGTH } from "../constants";
+
+import { DocumentHeader } from "./DocumentHeader";
+
+const defaultDocument = createMockDocument({
+ creator: createMockUser({ common_name: "John Doe" }),
+ updated_at: "2024-01-15T10:30:00Z",
+});
+
+const setup = ({
+ document = defaultDocument,
+ documentTitle = "Test Document",
+ isNewDocument = false,
+ canWrite = true,
+ showSaveButton = false,
+ isBookmarked = false,
+ onTitleChange = jest.fn(),
+ onSave = jest.fn(),
+ onMove = jest.fn(),
+ onToggleBookmark = jest.fn(),
+ onArchive = jest.fn(),
+} = {}) => {
+ const props = {
+ document,
+ documentTitle,
+ isNewDocument,
+ canWrite,
+ showSaveButton,
+ isBookmarked,
+ onTitleChange,
+ onSave,
+ onMove,
+ onToggleBookmark,
+ onArchive,
+ };
+
+ render(<DocumentHeader {...props} />);
+
+ return props;
+};
+
+describe("DocumentHeader", () => {
+ describe("Title input", () => {
+ it("should render document title", () => {
+ setup({ documentTitle: "My Document" });
+ expect(screen.getByDisplayValue("My Document")).toBeInTheDocument();
+ });
+
+ it("should enforce maximum title length", async () => {
+ const onTitleChange = jest.fn();
+ const longTitle = "a".repeat(DOCUMENT_TITLE_MAX_LENGTH + 10);
+ setup({ documentTitle: "", onTitleChange });
+
+ const input = screen.getByLabelText("Document Title");
+ await userEvent.type(input, longTitle);
+
+ const lastCall =
+ onTitleChange.mock.calls[onTitleChange.mock.calls.length - 1];
+ expect(lastCall[0].length).toBeLessThanOrEqual(DOCUMENT_TITLE_MAX_LENGTH);
+ });
+
+ it("should be read-only when user cannot write", () => {
+ setup({ canWrite: false });
+ const input = screen.getByLabelText("Document Title");
+ expect(input).toHaveAttribute("readonly");
+ });
+
+ it("should have autofocus for new documents", () => {
+ setup({ isNewDocument: true });
+ const input = screen.getByLabelText("Document Title");
+ expect(input).toHaveFocus();
+ });
+ });
+
+ describe("Metadata", () => {
+ it("should show creator name and update time for existing documents", () => {
+ setup();
+ expect(screen.getByText("John Doe")).toBeInTheDocument();
+ expect(screen.getByText("January 15, 2024")).toBeInTheDocument();
+ });
+ });
+
+ describe("Save button", () => {
+ it("should show save button when showSaveButton is true", () => {
+ setup({ showSaveButton: true });
+ expect(screen.getByRole("button", { name: "Save" })).toBeInTheDocument();
+ });
+
+ it("should not show save button when showSaveButton is false", () => {
+ setup({ showSaveButton: false });
+ expect(
+ screen.queryByRole("button", { name: "Save" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should call onSave when save button is clicked", async () => {
+ const onSave = jest.fn();
+ setup({ showSaveButton: true, onSave });
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+ expect(onSave).toHaveBeenCalled();
+ });
+ });
+
+ describe("Menu actions", () => {
+ it("should show the print option", async () => {
+ const originalPrint = window.print;
+ window.print = jest.fn();
+
+ setup();
+
+ await userEvent.click(screen.getByLabelText("More options"));
+ await userEvent.click(screen.getByText("Print Document"));
+ expect(window.print).toHaveBeenCalled();
+
+ window.print = originalPrint;
+ });
+
+ it("should show bookmark option", async () => {
+ setup({ isNewDocument: false, isBookmarked: false });
+ await userEvent.click(screen.getByLabelText("More options"));
+ expect(screen.getByText("Bookmark")).toBeInTheDocument();
+ });
+
+ it("should show remove bookmark option when bookmarked", async () => {
+ setup({ isNewDocument: false, isBookmarked: true });
+ await userEvent.click(screen.getByLabelText("More options"));
+ expect(screen.getByText("Remove from Bookmarks")).toBeInTheDocument();
+ });
+
+ it("should call onToggleBookmark when bookmark is clicked", async () => {
+ const onToggleBookmark = jest.fn();
+ setup({ isNewDocument: false, onToggleBookmark });
+
+ await userEvent.click(screen.getByLabelText("More options"));
+ await userEvent.click(screen.getByText("Bookmark"));
+ expect(onToggleBookmark).toHaveBeenCalled();
+ });
+
+ it("should show move and archive options when user can write", async () => {
+ setup({ isNewDocument: false, canWrite: true });
+ await userEvent.click(screen.getByLabelText("More options"));
+
+ expect(screen.getByText("Move")).toBeInTheDocument();
+ expect(screen.getByText("Move to trash")).toBeInTheDocument();
+ });
+
+ it("should not show move and archive options when user cannot write", async () => {
+ setup({ isNewDocument: false, canWrite: false });
+ await userEvent.click(screen.getByLabelText("More options"));
+
+ expect(screen.queryByText("Move")).not.toBeInTheDocument();
+ expect(screen.queryByText("Move to trash")).not.toBeInTheDocument();
+ });
+
+ it("should call onMove when move is clicked", async () => {
+ const onMove = jest.fn();
+ setup({ isNewDocument: false, canWrite: true, onMove });
+
+ await userEvent.click(screen.getByLabelText("More options"));
+ await userEvent.click(screen.getByText("Move"));
+ expect(onMove).toHaveBeenCalled();
+ });
+
+ it("should call onArchive when archive is clicked", async () => {
+ const onArchive = jest.fn();
+ setup({ isNewDocument: false, canWrite: true, onArchive });
+
+ await userEvent.click(screen.getByLabelText("More options"));
+ await userEvent.click(screen.getByText("Move to trash"));
+ expect(onArchive).toHaveBeenCalled();
+ });
+
+ it("should not show saved document options for new documents", async () => {
+ setup({ isNewDocument: true });
+ await userEvent.click(screen.getByLabelText("More options"));
+
+ expect(screen.queryByText("Move")).not.toBeInTheDocument();
+ expect(screen.queryByText("Bookmark")).not.toBeInTheDocument();
+ expect(screen.queryByText("Move to trash")).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
index baea28a1721..4ca3c4acf8f 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx
@@ -1,6 +1,5 @@
import type { JSONContent, Editor as TiptapEditor } from "@tiptap/core";
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
-import cx from "classnames";
import dayjs from "dayjs";
import { useCallback, useEffect, useState } from "react";
import type { Route } from "react-router";
@@ -17,9 +16,6 @@ import {
useListBookmarksQuery,
} from "metabase/api";
import { canonicalCollectionId } from "metabase/collections/utils";
-import DateTime, {
- getFormattedTime,
-} from "metabase/common/components/DateTime";
import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";
import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";
import { useToast } from "metabase/common/hooks";
@@ -27,17 +23,7 @@ import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
import { useDispatch, useSelector } from "metabase/lib/redux";
import { extractEntityId } from "metabase/lib/urls";
import { setErrorPage } from "metabase/redux/app";
-import {
- ActionIcon,
- Box,
- Button,
- Flex,
- Icon,
- Menu,
- Text,
- TextInput,
- Tooltip,
-} from "metabase/ui";
+import { Box } from "metabase/ui";
import {
useCreateDocumentMutation,
useGetDocumentQuery,
@@ -64,6 +50,7 @@ import {
} from "../selectors";
import { DocumentArchivedEntityBanner } from "./DocumentArchivedEntityBanner";
+import { DocumentHeader } from "./DocumentHeader";
import styles from "./DocumentPage.module.css";
import { Editor } from "./Editor";
import { EmbedQuestionSettingsSidebar } from "./EmbedQuestionSettingsSidebar";
@@ -375,129 +362,27 @@ export const DocumentPage = ({
[dispatch, selectedEmbedIndex],
);
- const handlePrintDocument = useCallback(() => {
- window.print();
- }, []);
-
return (
<Box className={styles.documentPage}>
{documentData?.archived && <DocumentArchivedEntityBanner />}
<Box className={styles.contentArea}>
<Box className={styles.mainContent}>
<Box className={styles.documentContainer}>
- <Box className={styles.header} mt="xl" pt="xl">
- <Flex direction="column" w="100%">
- <TextInput
- aria-label={t`Document Title`}
- autoFocus={isNewDocument}
- value={documentTitle}
- onChange={(event) =>
- setDocumentTitle(event.currentTarget.value)
- }
- flex={1}
- placeholder={t`New document`}
- readOnly={!canWrite}
- styles={{
- input: {
- border: "none",
- padding: 0,
- fontSize: "2rem",
- fontWeight: "bold",
- },
- }}
- />
- {documentData && (
- <Flex gap="md">
- <Text className={styles.metadataItem}>
- <Icon name="person" />
- {documentData.creator.common_name}{" "}
- </Text>
- <Tooltip
- label={getFormattedTime(
- documentData.updated_at,
- "default",
- { local: true },
- )}
- >
- <Text className={styles.metadataItem}>
- <Icon name="clock" />
- <DateTime value={documentData.updated_at} unit="day" />
- </Text>
- </Tooltip>
- </Flex>
- )}
- </Flex>
- <Flex gap="md" align="center">
- <Box
- className={cx(styles.hidable, {
- [styles.visible]: showSaveButton,
- })}
- >
- <Button
- onClick={() => {
- isNewDocument
- ? setCollectionPickerMode("save")
- : handleSave();
- }}
- variant="filled"
- data-hide-on-print
- >
- {t`Save`}
- </Button>
- </Box>
- <Menu position="bottom-end">
- <Menu.Target>
- <ActionIcon
- variant="subtle"
- size="md"
- aria-label={t`More options`}
- data-hide-on-print
- >
- <Icon name="ellipsis" />
- </ActionIcon>
- </Menu.Target>
- <Menu.Dropdown>
- <Menu.Item
- leftSection={<Icon name="document" />}
- onClick={handlePrintDocument}
- >
- {t`Print Document`}
- </Menu.Item>
- {!isNewDocument && (
- <>
- {canWrite && (
- <Menu.Item
- leftSection={<Icon name="move" />}
- onClick={() => setCollectionPickerMode("move")}
- >
- {t`Move`}
- </Menu.Item>
- )}
- <Menu.Item
- leftSection={<Icon name={"bookmark"} />}
- onClick={handleToggleBookmark}
- >
- {isBookmarked
- ? t`Remove from Bookmarks`
- : t`Bookmark`}
- </Menu.Item>
- {canWrite && (
- <>
- <Menu.Divider />
- <Menu.Item
- leftSection={<Icon name="trash" />}
- onClick={() => handleUpdate({ archived: true })}
- >
- {t`Move to trash`}
- </Menu.Item>
- </>
- )}
- </>
- )}
- </Menu.Dropdown>
- </Menu>
- </Flex>
- </Box>
+ <DocumentHeader
+ document={documentData}
+ documentTitle={documentTitle}
+ isNewDocument={isNewDocument}
+ canWrite={canWrite ?? false}
+ showSaveButton={showSaveButton ?? false}
+ isBookmarked={isBookmarked}
+ onTitleChange={setDocumentTitle}
+ onSave={() => {
+ isNewDocument ? setCollectionPickerMode("save") : handleSave();
+ }}
+ onMove={() => setCollectionPickerMode("move")}
+ onToggleBookmark={handleToggleBookmark}
+ onArchive={() => handleUpdate({ archived: true })}
+ />
<Editor
onEditorReady={setEditorInstance}
onCardEmbedsChange={updateCardEmbeds}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/constants.ts b/enterprise/frontend/src/metabase-enterprise/documents/constants.ts
new file mode 100644
index 00000000000..6b2fb534c43
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/documents/constants.ts
@@ -0,0 +1 @@
+export const DOCUMENT_TITLE_MAX_LENGTH = 100;
diff --git a/frontend/src/metabase-types/api/mocks/document.ts b/frontend/src/metabase-types/api/mocks/document.ts
new file mode 100644
index 00000000000..872929a5a29
--- /dev/null
+++ b/frontend/src/metabase-types/api/mocks/document.ts
@@ -0,0 +1,20 @@
+import type { Document } from "metabase-types/api";
+
+import { createMockUser } from "./user";
+
+export const createMockDocument = (opts?: Partial<Document>): Document => ({
+ id: 1,
+ name: "Test Document",
+ creator: createMockUser(),
+ creator_id: 1,
+ document: { type: "doc", content: [] },
+ version: 1,
+ collection_id: null,
+ created_at: "2024-01-01T10:30:00Z",
+ updated_at: "2024-01-15T10:30:00Z",
+ archived: false,
+ can_delete: true,
+ can_restore: true,
+ can_write: true,
+ ...opts,
+});
diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.ts
index bc98ffba054..0ab584e765b 100644
--- a/frontend/src/metabase-types/api/mocks/index.ts
+++ b/frontend/src/metabase-types/api/mocks/index.ts
@@ -10,6 +10,7 @@ export * from "./collection";
export * from "./dashboard";
export * from "./database";
export * from "./dataset";
+export * from "./document";
export * from "./field";
export * from "./geojson";
export * from "./group";