Skip to content

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

GDGT-3396: Unwrap the remaining ModalContent modals and delete ModalContent (#84759)

Will Fry1c8b21790215
diff --git a/e2e/support/helpers/e2e-embedding-helpers.js b/e2e/support/helpers/e2e-embedding-helpers.js
index a3e84964ac4..a78b96d9a23 100644
--- a/e2e/support/helpers/e2e-embedding-helpers.js
+++ b/e2e/support/helpers/e2e-embedding-helpers.js
@@ -277,7 +277,7 @@ export function openLegacyStaticEmbeddingModal({
}
export function closeStaticEmbeddingModal() {
- modal().icon("close").click();
+ modal().findByLabelText("Close").click();
}
/**
diff --git a/e2e/support/helpers/e2e-filter-helpers.js b/e2e/support/helpers/e2e-filter-helpers.js
index 05da4d6cf0c..0774827bab7 100644
--- a/e2e/support/helpers/e2e-filter-helpers.js
+++ b/e2e/support/helpers/e2e-filter-helpers.js
@@ -81,7 +81,7 @@ export function checkFilterListSourceHasValue({ values }) {
modal().within(() => {
cy.findByText("Custom list").click();
cy.findByRole("textbox").should("have.value", expectedString);
- cy.icon("close").click();
+ cy.findByLabelText("Close").click();
});
}
diff --git a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js
index d2991c32ee0..086102b02fd 100644
--- a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js
+++ b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js
@@ -788,7 +788,7 @@ const MODEL_NAME = "Test Action Model";
cy.findByTestId("action-editor-modal").should("not.exist");
getActionParametersInputModal().within(() => {
- cy.findByTestId("modal-header").findByText("New action name");
+ cy.findByRole("heading", { name: "New action name" });
cy.findAllByPlaceholderText("Test placeholder");
@@ -915,7 +915,7 @@ describe(
);
cy.findByPlaceholderText("Score").should("have.value", "30");
- cy.icon("close").click();
+ cy.findByLabelText("Close").click();
});
H.filterWidget().click();
@@ -1106,8 +1106,8 @@ const changeValue = ({ fieldName, fieldType, oldValue, newValue }) => {
cy.findByPlaceholderText(fieldName)
.should("have.attr", "type", fieldType)
.should("have.value", oldValue)
- .clear()
- .type(newValue);
+ .clear({ scrollBehavior: "center" })
+ .type(newValue, { scrollBehavior: "center" });
};
function formFieldContainer(label) {
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
index 5c653864088..27d6b6e6785 100644
--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
@@ -776,7 +776,7 @@ describe("scenarios > dashboard", () => {
cy.get("body").should("have.attr", "data-scroll-locked");
H.modal().within(() => {
- cy.icon("close").click();
+ cy.findByLabelText("Close").click();
});
H.modal().should("not.exist");
cy.get("body").should("not.have.attr", "data-scroll-locked");
diff --git a/e2e/test/scenarios/models/models.cy.spec.js b/e2e/test/scenarios/models/models.cy.spec.js
index abedc88bf02..b1f61b60a5f 100644
--- a/e2e/test/scenarios/models/models.cy.spec.js
+++ b/e2e/test/scenarios/models/models.cy.spec.js
@@ -535,7 +535,7 @@ describe("scenarios > models", () => {
H.modal().within(() => {
cy.findByText("Variables in models aren't supported yet");
cy.button("Turn this into a model").should("not.exist");
- cy.icon("close").click();
+ cy.findByLabelText("Close").click();
});
H.openQuestionActions();
assertIsQuestion();
diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.tsx b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.tsx
deleted file mode 100644
index bb25ea416bf..00000000000
--- a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { type JSX, useCallback, useState } from "react";
-import { t } from "ttag";
-
-import { ModalContent } from "metabase/common/components/ModalContent";
-import { FormMessage } from "metabase/forms";
-import type { NotificationType } from "metabase/notifications/types";
-import { formatChannelRecipients } from "metabase/pulse";
-import { Box, Button, Stack } from "metabase/ui";
-import Settings from "metabase/utils/settings";
-import { formatDateTimeWithUnit } from "metabase/value-formatting";
-import type { Alert, DashboardSubscription, User } from "metabase-types/api";
-
-type ArchiveModalProps = {
- item: Alert | DashboardSubscription;
- type: NotificationType;
- user: User;
- hasUnsubscribed: boolean;
- onArchive: (
- item: Alert | DashboardSubscription,
- archived: boolean,
- ) => Promise<void>;
- onClose: () => void;
-};
-
-function ArchiveNotificationModal({
- item,
- type,
- user,
- hasUnsubscribed,
- onArchive,
- onClose,
-}: ArchiveModalProps): JSX.Element {
- const [error, setError] = useState<unknown>();
-
- const handleArchiveClick = useCallback(async () => {
- try {
- await onArchive(item, true);
- onClose();
- } catch (err) {
- setError(err);
- }
- }, [item, onArchive, onClose]);
-
- return (
- <ModalContent
- title={getTitleMessage(type, hasUnsubscribed)}
- footer={[
- error ? <FormMessage key="message" formError={error} /> : null,
- <Button key="cancel" onClick={onClose}>
- {getCancelMessage(hasUnsubscribed)}
- </Button>,
- <Button
- key="submit"
- variant="filled"
- color="negative"
- onClick={handleArchiveClick}
- >
- {getSubmitMessage(type, hasUnsubscribed)}
- </Button>,
- ]}
- onClose={onClose}
- >
- <Stack gap="lg">
- {isCreator(item, user) && hasUnsubscribed && (
- <Box data-server-date>
- {getCreatorMessage(type, user)}
- {t`As the creator you can also choose to delete this if it's no longer relevant to others as well.`}
- </Box>
- )}
- <Box>
- {getDateMessage(item, type)}
- {getRecipientsMessage(item)}
- </Box>
- </Stack>
- </ModalContent>
- );
-}
-
-const isCreator = (
- item: Alert | DashboardSubscription,
- user: User,
-): boolean => {
- return user.id === item.creator?.id;
-};
-
-const getTitleMessage = (
- type: NotificationType,
- hasUnsubscribed: boolean,
-): string => {
- switch (type) {
- case "alert":
- return hasUnsubscribed
- ? t`You're unsubscribed. Delete this alert as well?`
- : t`Delete this alert?`;
- case "pulse":
- return hasUnsubscribed
- ? t`You're unsubscribed. Delete this subscription as well?`
- : t`Delete this subscription?`;
- }
-};
-
-const getSubmitMessage = (
- type: NotificationType,
- hasUnsubscribed: boolean,
-): string => {
- switch (type) {
- case "alert":
- return hasUnsubscribed ? t`Delete this alert` : t`Yes, delete this alert`;
- case "pulse":
- return hasUnsubscribed
- ? t`Delete this subscription`
- : t`Yes, delete this subscription`;
- }
-};
-
-const getCancelMessage = (hasUnsubscribed: boolean): string => {
- return hasUnsubscribed ? t`Keep it around` : t`I changed my mind`;
-};
-
-const getCreatorMessage = (type: NotificationType, user: User): string => {
- switch (type) {
- case "alert":
- return t`You won't receive this alert at ${user.email} any more. `;
- case "pulse":
- return t`You won't receive this subscription at ${user.email} any more. `;
- }
-};
-
-const getDateMessage = (
- item: Alert | DashboardSubscription,
- type: NotificationType,
-): string => {
- const options = Settings.formattingOptions();
- const createdAt = formatDateTimeWithUnit(item.created_at, "day", options);
-
- switch (type) {
- case "alert":
- return t`You created this alert on ${createdAt}. `;
- case "pulse":
- return t`You created this subscription on ${createdAt}. `;
- }
-};
-
-const getRecipientsMessage = (item: Alert | DashboardSubscription): string => {
- return t`It's currently being sent to ${formatChannelRecipients(item)}.`;
-};
-
-export { ArchiveNotificationModal };
diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.tsx b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.tsx
deleted file mode 100644
index 1617b61acc9..00000000000
--- a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import { render, screen, waitFor } from "__support__/ui";
-import { getNextId } from "__support__/utils";
-import {
- createMockAlert,
- createMockChannel,
-} from "metabase-types/api/mocks/alert";
-import { createMockDashboardSubscription } from "metabase-types/api/mocks/pulse";
-import { createMockUser } from "metabase-types/api/mocks/user";
-
-import { ArchiveNotificationModal } from "./ArchiveModal";
-
-describe("ArchiveNotificationModal", () => {
- it("should render an email alert", () => {
- const alert = createMockAlert({
- id: getNextId(),
- created_at: "2021-05-08T02:02:07.441Z",
- channels: [
- createMockChannel({
- channel_id: getNextId(),
- channel_type: "email",
- recipients: [createMockUser({ id: getNextId() })],
- }),
- ],
- });
-
- render(
- <ArchiveNotificationModal
- item={alert}
- type="alert"
- user={createMockUser({ id: getNextId() })}
- hasUnsubscribed={false}
- onArchive={jest.fn()}
- onClose={jest.fn()}
- />,
- );
-
- expect(screen.getByText("Delete this alert?")).toBeInTheDocument();
- expect(screen.getByText("Yes, delete this alert")).toBeInTheDocument();
- expect(
- screen.getByText("You created this alert on May 8, 2021", {
- exact: false,
- }),
- ).toBeInTheDocument();
- expect(
- screen.getByText("It's currently being sent to 1 email.", {
- exact: false,
- }),
- ).toBeInTheDocument();
- });
-
- it("should render an email pulse", () => {
- const pulse = createMockDashboardSubscription({
- id: getNextId(),
- created_at: "2021-05-08T02:02:07.441Z",
- channels: [
- createMockChannel({
- channel_id: getNextId(),
- channel_type: "email",
- recipients: [createMockUser({ id: getNextId() })],
- }),
- ],
- });
-
- render(
- <ArchiveNotificationModal
- item={pulse}
- type="pulse"
- user={createMockUser({ id: getNextId() })}
- hasUnsubscribed={false}
- onArchive={jest.fn()}
- onClose={jest.fn()}
- />,
- );
-
- expect(screen.getByText("Delete this subscription?")).toBeInTheDocument();
- expect(
- screen.getByText("Yes, delete this subscription"),
- ).toBeInTheDocument();
- expect(
- screen.getByText("May 8, 2021", { exact: false }),
- ).toBeInTheDocument();
- expect(
- screen.getByText("It's currently being sent to 1 email.", {
- exact: false,
- }),
- ).toBeInTheDocument();
- });
-
- it("should render a slack pulse", () => {
- const pulse = createMockDashboardSubscription({
- id: getNextId(),
- channels: [
- createMockChannel({
- channel_id: getNextId(),
- channel_type: "slack",
- recipients: [createMockUser({ id: getNextId() })],
- }),
- ],
- });
-
- render(
- <ArchiveNotificationModal
- item={pulse}
- type="pulse"
- user={createMockUser({ id: getNextId() })}
- hasUnsubscribed={false}
- onArchive={jest.fn()}
- onClose={jest.fn()}
- />,
- );
-
- expect(
- screen.getByText("1 Slack channel", { exact: false }),
- ).toBeInTheDocument();
- });
-
- it("should render an alert with both email and slack channels", () => {
- const alert = createMockAlert({
- id: getNextId(),
- channels: [
- createMockChannel({
- channel_id: getNextId(),
- channel_type: "email",
- recipients: [
- createMockUser({ id: getNextId() }),
- createMockUser({ id: getNextId() }),
- ],
- }),
- createMockChannel({
- channel_id: getNextId(),
- channel_type: "slack",
- recipients: [
- createMockUser({ id: getNextId() }),
- createMockUser({ id: getNextId() }),
- createMockUser({ id: getNextId() }),
- ],
- }),
- ],
- });
-
- render(
- <ArchiveNotificationModal
- item={alert}
- type="alert"
- user={createMockUser({ id: getNextId() })}
- hasUnsubscribed={false}
- onArchive={jest.fn()}
- onClose={jest.fn()}
- />,
- );
-
- expect(
- screen.getByText("2 emails and 3 Slack channels", { exact: false }),
- ).toBeInTheDocument();
- });
-
- it("should close on submit", async () => {
- const alert = createMockAlert({ id: getNextId() });
- const onArchive = jest.fn();
- const onClose = jest.fn();
-
- onArchive.mockResolvedValue(undefined);
-
- render(
- <ArchiveNotificationModal
- item={alert}
- type="alert"
- user={createMockUser({ id: getNextId() })}
- hasUnsubscribed={false}
- onArchive={onArchive}
- onClose={onClose}
- />,
- );
-
- screen.getByText("Yes, delete this alert").click();
-
- await waitFor(() => {
- expect(onArchive).toHaveBeenCalledWith(alert, true);
- });
- expect(onClose).toHaveBeenCalled();
- });
-
- it("should not close on a submit error", async () => {
- const alert = createMockAlert({ id: getNextId() });
- const onArchive = jest.fn();
- const onClose = jest.fn();
-
- onArchive.mockRejectedValue({
- status: 500,
- data: { message: "An error occurred" },
- });
-
- render(
- <ArchiveNotificationModal
- item={alert}
- type="alert"
- user={createMockUser({ id: getNextId() })}
- hasUnsubscribed={false}
- onArchive={onArchive}
- onClose={onClose}
- />,
- );
-
- screen.getByText("Yes, delete this alert").click();
-
- await waitFor(() => {
- expect(screen.getByText("An error occurred")).toBeInTheDocument();
- });
- expect(onArchive).toHaveBeenCalledWith(alert, true);
- expect(onClose).not.toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/index.ts b/frontend/src/metabase/account/notifications/components/ArchiveModal/index.ts
deleted file mode 100644
index 522f174ae9e..00000000000
--- a/frontend/src/metabase/account/notifications/components/ArchiveModal/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { ArchiveNotificationModal } from "./ArchiveModal";
diff --git a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsx b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsx
index 8e4b5eebf63..8a20fcece96 100644
--- a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsx
+++ b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsx
@@ -2,10 +2,9 @@ import type { JSX } from "react";
import { jt, t } from "ttag";
import { ExternalLink } from "metabase/common/components/ExternalLink";
-import { ModalContent } from "metabase/common/components/ModalContent";
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
-import { Box, Button, Stack } from "metabase/ui";
+import { Box, Button, Modal, Stack } from "metabase/ui";
import Settings from "metabase/utils/settings";
type HelpModalProps = {
@@ -19,13 +18,10 @@ function HelpModal({ onClose }: HelpModalProps): JSX.Element {
const handleClose = () => onClose?.(true);
return (
- <ModalContent
+ <Modal
+ opened
+ size="lg"
title={t`Not seeing something listed here?`}
- footer={
- <Button key="close" onClick={handleClose}>
- {t`Got it`}
- </Button>
- }
onClose={handleClose}
>
<Stack gap="lg">
@@ -37,7 +33,10 @@ function HelpModal({ onClose }: HelpModalProps): JSX.Element {
{t`Hopefully they'll be able to help you out!`}
</Box>
</Stack>
- </ModalContent>
+ <Modal.Footer>
+ <Button onClick={handleClose}>{t`Got it`}</Button>
+ </Modal.Footer>
+ </Modal>
);
}
diff --git a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.tsx b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.tsx
deleted file mode 100644
index 98cbc6a9107..00000000000
--- a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { type JSX, useCallback, useState } from "react";
-import { t } from "ttag";
-
-import { ModalContent } from "metabase/common/components/ModalContent";
-import { FormMessage } from "metabase/forms";
-import type { NotificationType } from "metabase/notifications/types";
-import { Button } from "metabase/ui";
-import type { Alert, DashboardSubscription, User } from "metabase-types/api";
-
-type UnsubscribeModalProps = {
- item: Alert | DashboardSubscription;
- type: NotificationType;
- user: User;
- onUnsubscribe: (item: Alert | DashboardSubscription) => Promise<void>;
- onArchive: (
- item: Alert | DashboardSubscription,
- type: NotificationType,
- hasUnsubscribed: boolean,
- ) => void;
- onClose: () => void;
-};
-
-function UnsubscribeModal({
- item,
- type,
- user,
- onUnsubscribe,
- onArchive,
- onClose,
-}: UnsubscribeModalProps): JSX.Element {
- const [error, setError] = useState<unknown>();
-
- const handleUnsubscribeClick = useCallback(async () => {
- try {
- await onUnsubscribe(item);
-
- if (isCreator(item, user)) {
- onArchive(item, type, true);
- } else {
- onClose();
- }
- } catch (err) {
- setError(err);
- }
- }, [item, type, user, onUnsubscribe, onArchive, onClose]);
-
- return (
- <ModalContent
- title={t`Confirm you want to unsubscribe`}
- footer={[
- error ? <FormMessage key="message" formError={error} /> : null,
- <Button key="cancel" onClick={onClose}>
- {t`I changed my mind`}
- </Button>,
- <Button
- key="submit"
- variant="filled"
- color="negative"
- onClick={handleUnsubscribeClick}
- >
- {t`Unsubscribe`}
- </Button>,
- ]}
- onClose={onClose}
- >
- <p>
- {getUnsubscribeMessage(type)}
- {t`Depending on your organization's permissions you might need to ask a moderator to be re-added in the future.`}
- </p>
- </ModalContent>
- );
-}
-
-const isCreator = (
- item: Alert | DashboardSubscription,
- user: User,
-): boolean => {
- return user.id === item.creator?.id;
-};
-
-const getUnsubscribeMessage = (type: NotificationType): string => {
- switch (type) {
- case "alert":
- return t`You'll stop receiving this alert from now on. `;
- case "pulse":
- return t`You'll stop receiving this subscription from now on. `;
- }
-};
-
-export { UnsubscribeModal };
diff --git a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.tsx b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.tsx
deleted file mode 100644
index 7508cf73931..00000000000
--- a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { render, screen, waitFor } from "__support__/ui";
-import { getNextId } from "__support__/utils";
-import { createMockAlert } from "metabase-types/api/mocks/alert";
-import { createMockDashboardSubscription } from "metabase-types/api/mocks/pulse";
-import { createMockUser } from "metabase-types/api/mocks/user";
-
-import { UnsubscribeModal } from "./UnsubscribeModal";
-
-describe("UnsubscribeModal", () => {
- it("should render an alert", () => {
- const alert = createMockAlert();
-
- render(
- <UnsubscribeModal
- item={alert}
- type="alert"
- user={createMockUser()}
- onUnsubscribe={jest.fn()}
- onArchive={jest.fn()}
- onClose={jest.fn()}
- />,
- );
-
- expect(
- screen.getByText("this alert", { exact: false }),
- ).toBeInTheDocument();
- });
-
- it("should render a pulse", () => {
- const pulse = createMockDashboardSubscription();
-
- render(
- <UnsubscribeModal
- item={pulse}
- type="pulse"
- user={createMockUser()}
- onUnsubscribe={jest.fn()}
- onArchive={jest.fn()}
- onClose={jest.fn()}
- />,
- );
-
- expect(
- screen.getByText("this subscription", { exact: false }),
- ).toBeInTheDocument();
- });
-
- it("should close if unsubscribed successfully", async () => {
- const alert = createMockAlert({ creator_id: getNextId() });
- const user = createMockUser({ id: getNextId() });
- const onUnsubscribe = jest.fn();
- const onArchive = jest.fn();
- const onClose = jest.fn();
-
- onUnsubscribe.mockResolvedValue(undefined);
-
- render(
- <UnsubscribeModal
- item={alert}
- type="alert"
- user={user}
- onUnsubscribe={onUnsubscribe}
- onArchive={onArchive}
- onClose={onClose}
- />,
- );
-
- screen.getByText("Unsubscribe").click();
-
- await waitFor(() => {
- expect(onUnsubscribe).toHaveBeenCalledWith(alert);
- });
- expect(onArchive).not.toHaveBeenCalled();
- expect(onClose).toHaveBeenCalled();
- });
-
- it("should proceed with archiving if the notification is created by the user", async () => {
- const user = createMockUser({ id: getNextId() });
- const alert = createMockAlert({ creator_id: user.id, creator: user });
- const onUnsubscribe = jest.fn();
- const onArchive = jest.fn();
- const onClose = jest.fn();
-
- onUnsubscribe.mockResolvedValue(undefined);
-
- render(
- <UnsubscribeModal
- item={alert}
- type="alert"
- user={user}
- onUnsubscribe={onUnsubscribe}
- onArchive={onArchive}
- onClose={onClose}
- />,
- );
-
- screen.getByText("Unsubscribe").click();
-
- await waitFor(() => {
- expect(onUnsubscribe).toHaveBeenCalledWith(alert);
- });
- expect(onArchive).toHaveBeenCalledWith(alert, "alert", true);
- expect(onClose).not.toHaveBeenCalled();
- });
-
- it("should not close on a submit error", async () => {
- const user = createMockUser({ id: getNextId() });
- const alert = createMockAlert({ creator_id: user.id, creator: user });
- const onUnsubscribe = jest.fn();
- const onArchive = jest.fn();
- const onClose = jest.fn();
-
- onUnsubscribe.mockRejectedValue({
- status: 500,
- data: { message: "An error occurred" },
- });
-
- render(
- <UnsubscribeModal
- item={alert}
- type="alert"
- user={user}
- onUnsubscribe={onUnsubscribe}
- onArchive={onArchive}
- onClose={onClose}
- />,
- );
-
- screen.getByText("Unsubscribe").click();
-
- await waitFor(() => {
- expect(screen.getByText("An error occurred")).toBeInTheDocument();
- });
- expect(onUnsubscribe).toHaveBeenCalled();
- expect(onArchive).not.toHaveBeenCalled();
- expect(onClose).not.toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.ts b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.ts
deleted file mode 100644
index 21704527ebd..00000000000
--- a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { UnsubscribeModal } from "./UnsubscribeModal";
diff --git a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx
index 5ccc9c572d7..f0f52483089 100644
--- a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx
+++ b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx
@@ -1,4 +1,6 @@
import { skipToken } from "@reduxjs/toolkit/query/react";
+import { useState } from "react";
+import { t } from "ttag";
import {
useGetSubscriptionQuery,
@@ -6,10 +8,15 @@ import {
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { getUser } from "metabase/current-user";
+import { FormMessage } from "metabase/forms";
+import { formatChannelRecipients } from "metabase/pulse";
import { useSelector } from "metabase/redux";
import { useSearchParams } from "metabase/router";
+import { Box, Button, Modal, Stack } from "metabase/ui";
+import Settings from "metabase/utils/settings";
+import { formatDateTimeWithUnit } from "metabase/value-formatting";
+import type { DashboardSubscription, User } from "metabase-types/api";
-import { ArchiveNotificationModal } from "../../components/ArchiveModal";
import { getPulseId } from "../../selectors";
type ArchivePulseModalProps = {
@@ -21,6 +28,7 @@ export function ArchivePulseModal({ params, onClose }: ArchivePulseModalProps) {
const pulseId = getPulseId({ params });
const user = useSelector(getUser);
const [searchParams] = useSearchParams();
+ const hasUnsubscribed = Boolean(searchParams.get("unsubscribed"));
const {
data: pulse,
@@ -28,27 +36,95 @@ export function ArchivePulseModal({ params, onClose }: ArchivePulseModalProps) {
error,
} = useGetSubscriptionQuery(pulseId ?? skipToken);
+ if (!user) {
+ return null;
+ }
+
+ return (
+ <Modal
+ opened
+ size="lg"
+ title={
+ hasUnsubscribed
+ ? t`You're unsubscribed. Delete this subscription as well?`
+ : t`Delete this subscription?`
+ }
+ onClose={onClose}
+ >
+ {isLoading || error || !pulse ? (
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ ) : (
+ <ArchivePulseModalBody
+ pulse={pulse}
+ user={user}
+ hasUnsubscribed={hasUnsubscribed}
+ onClose={onClose}
+ />
+ )}
+ </Modal>
+ );
+}
+
+type ArchivePulseModalBodyProps = {
+ pulse: DashboardSubscription;
+ user: User;
+ hasUnsubscribed: boolean;
+ onClose: () => void;
+};
+
+function ArchivePulseModalBody({
+ pulse,
+ user,
+ hasUnsubscribed,
+ onClose,
+}: ArchivePulseModalBodyProps) {
const [updateSubscription] = useUpdateSubscriptionMutation();
+ const [error, setError] = useState<unknown>();
- const handleArchive = async (
- item: { id: number },
- archived: boolean,
- ): Promise<void> => {
- await updateSubscription({ id: item.id, archived });
+ const handleArchiveClick = async () => {
+ try {
+ await updateSubscription({ id: pulse.id, archived: true }).unwrap();
+ onClose();
+ } catch (err) {
+ setError(err);
+ }
};
- if (isLoading || error) {
- return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
- }
+ const createdAt = formatDateTimeWithUnit(
+ pulse.created_at,
+ "day",
+ Settings.formattingOptions(),
+ );
- return pulse && user ? (
- <ArchiveNotificationModal
- item={pulse}
- type="pulse"
- user={user}
- hasUnsubscribed={Boolean(searchParams.get("unsubscribed"))}
- onArchive={handleArchive}
- onClose={onClose}
- />
- ) : null;
+ return (
+ <>
+ <Stack gap="lg">
+ {user.id === pulse.creator_id && hasUnsubscribed && (
+ <Box data-server-date>
+ {t`You won't receive this subscription at ${user.email} any more. `}
+ {t`As the creator you can also choose to delete this if it's no longer relevant to others as well.`}
+ </Box>
+ )}
+ <Box>
+ {t`You created this subscription on ${createdAt}. `}
+ {t`It's currently being sent to ${formatChannelRecipients(pulse)}.`}
+ </Box>
+ </Stack>
+ <Modal.Footer>
+ {!!error && (
+ <Box flex={1}>
+ <FormMessage formError={error} noPadding />
+ </Box>
+ )}
+ <Button onClick={onClose}>
+ {hasUnsubscribed ? t`Keep it around` : t`I changed my mind`}
+ </Button>
+ <Button variant="filled" color="negative" onClick={handleArchiveClick}>
+ {hasUnsubscribed
+ ? t`Delete this subscription`
+ : t`Yes, delete this subscription`}
+ </Button>
+ </Modal.Footer>
+ </>
+ );
}
diff --git a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.unit.spec.tsx b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.unit.spec.tsx
new file mode 100644
index 00000000000..4cf4c29a21f
--- /dev/null
+++ b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.unit.spec.tsx
@@ -0,0 +1,143 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupSubscriptionEndpoint,
+ setupUpdateSubscriptionEndpoint,
+} from "__support__/server-mocks";
+import { createMockState } from "__support__/state";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { DashboardSubscription, User } from "metabase-types/api";
+import { createMockChannel } from "metabase-types/api/mocks/alert";
+import { createMockDashboardSubscription } from "metabase-types/api/mocks/pulse";
+import { createMockUser } from "metabase-types/api/mocks/user";
+
+import { ArchivePulseModal } from "./ArchivePulseModal";
+
+const CURRENT_USER = createMockUser({ id: 1, email: "[email protected]" });
+const OTHER_USER = createMockUser({ id: 2 });
+
+type SetupOpts = {
+ pulse?: DashboardSubscription;
+ user?: User;
+ hasUnsubscribed?: boolean;
+ updateResponse?: object;
+};
+
+const setup = ({
+ pulse = createMockDashboardSubscription({ creator_id: OTHER_USER.id }),
+ user = CURRENT_USER,
+ hasUnsubscribed = false,
+ updateResponse,
+}: SetupOpts = {}) => {
+ setupSubscriptionEndpoint(pulse);
+ setupUpdateSubscriptionEndpoint(pulse, updateResponse);
+ const onClose = jest.fn();
+
+ renderWithProviders(
+ <ArchivePulseModal
+ params={{ pulseId: String(pulse.id) }}
+ onClose={onClose}
+ />,
+ {
+ withRouter: true,
+ initialRoute: hasUnsubscribed ? "/?unsubscribed=true" : "/",
+ storeInitialState: createMockState({ currentUser: user }),
+ },
+ );
+
+ return { pulse, onClose };
+};
+
+describe("ArchivePulseModal", () => {
+ it("should describe the subscription", async () => {
+ setup({
+ pulse: createMockDashboardSubscription({
+ created_at: "2021-05-08T02:02:07.441Z",
+ channels: [
+ createMockChannel({
+ channel_type: "email",
+ recipients: [createMockUser(), createMockUser({ id: 3 })],
+ }),
+ createMockChannel({
+ channel_type: "slack",
+ recipients: [createMockUser()],
+ }),
+ ],
+ }),
+ });
+
+ expect(
+ await screen.findByText("You created this subscription on May 8, 2021", {
+ exact: false,
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("2 emails and 1 Slack channel", { exact: false }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Delete this subscription?")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Yes, delete this subscription" }),
+ ).toBeInTheDocument();
+ });
+
+ it("should offer the creator to delete it after unsubscribing", async () => {
+ setup({
+ pulse: createMockDashboardSubscription({ creator_id: CURRENT_USER.id }),
+ hasUnsubscribed: true,
+ });
+
+ expect(
+ await screen.findByText(
+ "You won't receive this subscription at [email protected] any more.",
+ { exact: false },
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "You're unsubscribed. Delete this subscription as well?",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Keep it around" }),
+ ).toBeInTheDocument();
+ });
+
+ it("should archive the subscription and close", async () => {
+ const { pulse, onClose } = setup();
+
+ await userEvent.click(
+ await screen.findByRole("button", {
+ name: "Yes, delete this subscription",
+ }),
+ );
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ expect(await getArchiveRequestBody(pulse)).toEqual({ archived: true });
+ });
+
+ it("should show the error and stay open when archiving fails", async () => {
+ const { pulse, onClose } = setup({
+ updateResponse: { status: 500, body: { message: "An error occurred" } },
+ });
+
+ await userEvent.click(
+ await screen.findByRole("button", {
+ name: "Yes, delete this subscription",
+ }),
+ );
+
+ expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ expect(await getArchiveRequestBody(pulse)).toEqual({ archived: true });
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
+
+async function getArchiveRequestBody(
+ pulse: DashboardSubscription,
+): Promise<unknown> {
+ const call = fetchMock.callHistory.lastCall(`path:/api/pulse/${pulse.id}`, {
+ method: "PUT",
+ });
+ return call?.request?.json();
+}
diff --git a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsx b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsx
index ca187051615..475187546ed 100644
--- a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsx
+++ b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsx
@@ -1,13 +1,17 @@
import { skipToken } from "@reduxjs/toolkit/query/react";
+import { useState } from "react";
+import { t } from "ttag";
import { useGetSubscriptionQuery, useUnsubscribeMutation } from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { getUser } from "metabase/current-user";
+import { FormMessage } from "metabase/forms";
import { useSelector } from "metabase/redux";
import { useNavigate } from "metabase/router";
+import { Box, Button, Modal, Text } from "metabase/ui";
+import type { DashboardSubscription, User } from "metabase-types/api";
import { getArchiveUrl } from "../../actions";
-import { UnsubscribeModal } from "../../components/UnsubscribeModal";
import { getPulseId } from "../../selectors";
type UnsubscribePulseModalProps = {
@@ -19,7 +23,6 @@ export function UnsubscribePulseModal({
params,
onClose,
}: UnsubscribePulseModalProps) {
- const navigate = useNavigate();
const pulseId = getPulseId({ params });
const user = useSelector(getUser);
@@ -29,32 +32,80 @@ export function UnsubscribePulseModal({
error,
} = useGetSubscriptionQuery(pulseId ?? skipToken);
+ if (!user) {
+ return null;
+ }
+
+ return (
+ <Modal
+ opened
+ size="lg"
+ title={t`Confirm you want to unsubscribe`}
+ onClose={onClose}
+ >
+ {isLoading || error || !pulse ? (
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ ) : (
+ <UnsubscribePulseModalBody
+ pulse={pulse}
+ user={user}
+ onClose={onClose}
+ />
+ )}
+ </Modal>
+ );
+}
+
+type UnsubscribePulseModalBodyProps = {
+ pulse: DashboardSubscription;
+ user: User;
+ onClose: () => void;
+};
+
+function UnsubscribePulseModalBody({
+ pulse,
+ user,
+ onClose,
+}: UnsubscribePulseModalBodyProps) {
+ const navigate = useNavigate();
const [unsubscribe] = useUnsubscribeMutation();
+ const [error, setError] = useState<unknown>();
- const handleUnsubscribe = async (item: { id: number }): Promise<void> => {
- await unsubscribe(item.id);
- };
+ const handleUnsubscribeClick = async () => {
+ try {
+ await unsubscribe(pulse.id).unwrap();
- const handleArchive = (
- item: { id: number },
- _type: "alert" | "pulse",
- hasUnsubscribed: boolean,
- ): void => {
- navigate(getArchiveUrl(item, "pulse", hasUnsubscribed));
+ if (user.id === pulse.creator_id) {
+ navigate(getArchiveUrl(pulse, "pulse", true));
+ } else {
+ onClose();
+ }
+ } catch (err) {
+ setError(err);
+ }
};
- if (isLoading || error) {
- return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
- }
-
- return pulse && user ? (
- <UnsubscribeModal
- item={pulse}
- type="pulse"
- user={user}
- onUnsubscribe={handleUnsubscribe}
- onArchive={handleArchive}
- onClose={onClose}
- />
- ) : null;
+ return (
+ <>
+ <Text>
+ {t`You'll stop receiving this subscription from now on. `}
+ {t`Depending on your organization's permissions you might need to ask a moderator to be re-added in the future.`}
+ </Text>
+ <Modal.Footer>
+ {!!error && (
+ <Box flex={1}>
+ <FormMessage formError={error} noPadding />
+ </Box>
+ )}
+ <Button onClick={onClose}>{t`I changed my mind`}</Button>
+ <Button
+ variant="filled"
+ color="negative"
+ onClick={handleUnsubscribeClick}
+ >
+ {t`Unsubscribe`}
+ </Button>
+ </Modal.Footer>
+ </>
+ );
}
diff --git a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.unit.spec.tsx b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.unit.spec.tsx
new file mode 100644
index 00000000000..67cd2e378e7
--- /dev/null
+++ b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.unit.spec.tsx
@@ -0,0 +1,109 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupSubscriptionEndpoint,
+ setupUnsubscribeFromSubscriptionEndpoint,
+} from "__support__/server-mocks";
+import { createMockState } from "__support__/state";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { DashboardSubscription } from "metabase-types/api";
+import { createMockDashboardSubscription } from "metabase-types/api/mocks/pulse";
+import { createMockUser } from "metabase-types/api/mocks/user";
+
+import { UnsubscribePulseModal } from "./UnsubscribePulseModal";
+
+const CURRENT_USER = createMockUser({ id: 1 });
+const OTHER_USER = createMockUser({ id: 2 });
+
+type SetupOpts = {
+ pulse?: DashboardSubscription;
+ unsubscribeResponse?: object;
+};
+
+const setup = ({
+ pulse = createMockDashboardSubscription({ creator_id: OTHER_USER.id }),
+ unsubscribeResponse,
+}: SetupOpts = {}) => {
+ setupSubscriptionEndpoint(pulse);
+ setupUnsubscribeFromSubscriptionEndpoint(pulse, unsubscribeResponse);
+ const onClose = jest.fn();
+
+ const { router } = renderWithProviders(
+ <UnsubscribePulseModal
+ params={{ pulseId: String(pulse.id) }}
+ onClose={onClose}
+ />,
+ {
+ withRouter: true,
+ storeInitialState: createMockState({ currentUser: CURRENT_USER }),
+ },
+ );
+
+ return { pulse, onClose, router };
+};
+
+const isUnsubscribeCalled = (pulse: DashboardSubscription) =>
+ fetchMock.callHistory.called(`path:/api/pulse/${pulse.id}/subscription`, {
+ method: "DELETE",
+ });
+
+describe("UnsubscribePulseModal", () => {
+ it("should describe the subscription", async () => {
+ setup();
+
+ expect(
+ await screen.findByText("You'll stop receiving this subscription", {
+ exact: false,
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it("should unsubscribe and close", async () => {
+ const { pulse, onClose, router } = setup();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Unsubscribe" }),
+ );
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ expect(isUnsubscribeCalled(pulse)).toBe(true);
+ expect(router?.location.pathname).toBe("/");
+ });
+
+ it("should offer the creator to delete it after unsubscribing", async () => {
+ const { pulse, onClose, router } = setup({
+ pulse: createMockDashboardSubscription({ creator_id: CURRENT_USER.id }),
+ });
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Unsubscribe" }),
+ );
+
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe(
+ `/account/notifications/pulse/${pulse.id}/archive`,
+ ),
+ );
+ expect(router?.location.search).toBe("?unsubscribed=true");
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("should show the error and stay open when unsubscribing fails", async () => {
+ const { pulse, onClose, router } = setup({
+ unsubscribeResponse: {
+ status: 500,
+ body: { message: "An error occurred" },
+ },
+ });
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Unsubscribe" }),
+ );
+
+ expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ expect(isUnsubscribeCalled(pulse)).toBe(true);
+ expect(onClose).not.toHaveBeenCalled();
+ expect(router?.location.pathname).toBe("/");
+ });
+});
diff --git a/frontend/src/metabase/account/notifications/routes.tsx b/frontend/src/metabase/account/notifications/routes.tsx
index 06bba9be318..a6182e529b4 100644
--- a/frontend/src/metabase/account/notifications/routes.tsx
+++ b/frontend/src/metabase/account/notifications/routes.tsx
@@ -11,13 +11,17 @@ import { UnsubscribePulseModal } from "./containers/UnsubscribePulseModal";
export function getNotificationRoutes() {
return (
<Route path="notifications" element={<NotificationsApp />}>
- {modalRoute("help", HelpModal)}
+ {modalRoute("help", HelpModal, { noWrap: true })}
{modalRoute("alert/:alertId/archive", DeleteAlertModal, { noWrap: true })}
- {modalRoute("pulse/:pulseId/archive", ArchivePulseModal)}
+ {modalRoute("pulse/:pulseId/archive", ArchivePulseModal, {
+ noWrap: true,
+ })}
{modalRoute("alert/:alertId/unsubscribe", UnsubscribeAlertModal, {
noWrap: true,
})}
- {modalRoute("pulse/:pulseId/unsubscribe", UnsubscribePulseModal)}
+ {modalRoute("pulse/:pulseId/unsubscribe", UnsubscribePulseModal, {
+ noWrap: true,
+ })}
</Route>
);
}
diff --git a/frontend/src/metabase/actions/components/DeleteObjectModal/DeleteObjectModal.tsx b/frontend/src/metabase/actions/components/DeleteObjectModal/DeleteObjectModal.tsx
index dd6fdfb5376..22e90b8144d 100644
--- a/frontend/src/metabase/actions/components/DeleteObjectModal/DeleteObjectModal.tsx
+++ b/frontend/src/metabase/actions/components/DeleteObjectModal/DeleteObjectModal.tsx
@@ -3,12 +3,12 @@ import { t } from "ttag";
import { getActionErrorMessage } from "metabase/actions/utils";
import { useExecuteActionMutation } from "metabase/api";
-import { ModalContent } from "metabase/common/components/ModalContent";
import { useToast } from "metabase/common/hooks/use-toast";
-import { Button } from "metabase/ui";
+import { Button, Modal, Text } from "metabase/ui";
import type { WritebackActionId } from "metabase-types/api";
interface Props {
+ opened: boolean;
actionId: WritebackActionId | undefined;
objectId: number | string | null | undefined;
onClose: () => void;
@@ -16,16 +16,18 @@ interface Props {
}
export const DeleteObjectModal: FunctionComponent<Props> = ({
+ opened,
actionId,
objectId,
onClose,
onSuccess,
}) => {
const [sendToast] = useToast();
- const [executeAction] = useExecuteActionMutation();
+ const [executeAction, { isLoading: isSubmitting }] =
+ useExecuteActionMutation();
const handleSubmit = async () => {
- if (actionId == null) {
+ if (actionId == null || isSubmitting) {
return;
}
@@ -51,26 +53,28 @@ export const DeleteObjectModal: FunctionComponent<Props> = ({
};
return (
- <ModalContent
+ <Modal
+ opened={opened}
data-testid="delete-object-modal"
+ size="lg"
title={t`Are you sure you want to delete this row?`}
- footer={[
- <Button key="cancel" onClick={onClose}>{t`Cancel`}</Button>,
+ onClose={onClose}
+ >
+ <Text>{t`This will permanently delete the row. There’s no undoing this, so please be sure.`}</Text>
+ <Modal.Footer>
+ <Button onClick={onClose}>{t`Cancel`}</Button>
<Button
- key="delete"
variant="filled"
color="negative"
+ loading={isSubmitting}
disabled={
typeof actionId === "undefined" ||
typeof objectId === "undefined" ||
objectId === null
}
onClick={handleSubmit}
- >{t`Delete forever`}</Button>,
- ]}
- onClose={onClose}
- >
- {t`This will permanently delete the row. There’s no undoing this, so please be sure.`}
- </ModalContent>
+ >{t`Delete forever`}</Button>
+ </Modal.Footer>
+ </Modal>
);
};
diff --git a/frontend/src/metabase/actions/containers/ActionParametersInputForm/ActionParametersInputModal.tsx b/frontend/src/metabase/actions/containers/ActionParametersInputForm/ActionParametersInputModal.tsx
index 10820a2d9e1..8ec12d0d94e 100644
--- a/frontend/src/metabase/actions/containers/ActionParametersInputForm/ActionParametersInputModal.tsx
+++ b/frontend/src/metabase/actions/containers/ActionParametersInputForm/ActionParametersInputModal.tsx
@@ -1,11 +1,8 @@
+import { useState } from "react";
import { t } from "ttag";
import { EmptyState } from "metabase/common/components/EmptyState";
-import {
- ModalContent,
- ModalContentActionIcon,
-} from "metabase/common/components/ModalContent";
-import { Modal } from "metabase/ui";
+import { ActionIcon, Group, Icon, Modal, Text, Tooltip } from "metabase/ui";
import type { ActionParametersInputFormProps } from "./ActionParametersInputForm";
import ActionParametersInputForm from "./ActionParametersInputForm";
@@ -33,34 +30,51 @@ function ActionParametersInputModal({
onClose,
...formProps
}: ActionParametersInputModalProps) {
+ const [isOpenOrClosing, setIsOpenOrClosing] = useState(opened);
+
+ if (opened && !isOpenOrClosing) {
+ setIsOpenOrClosing(true);
+ }
+
+ // Unlike `Modal`, `Modal.Root` still renders its portal while closed, and
+ // the action button keeps this mounted, so render nothing once it has
+ // finished closing, but stay rendered until then so it can fade out
+ if (!isOpenOrClosing) {
+ return null;
+ }
+
return (
- <Modal
+ <Modal.Root
data-testid="action-parameters-input-modal"
opened={opened}
- onClose={onClose}
size="lg"
- withCloseButton={false}
- padding={0}
+ density="relaxed"
+ onClose={onClose}
+ onExitTransitionEnd={() => setIsOpenOrClosing(false)}
>
- <ModalContent
- title={title}
- headerActions={
- onEdit ? (
- <ModalContentActionIcon
- name="pencil"
- tooltip={t`Edit this action`}
- onClick={onEdit}
- />
- ) : undefined
- }
- onClose={onClose}
- >
- <>
- {showEmptyState && (
+ <Modal.Overlay />
+ <Modal.Content>
+ <Modal.Header>
+ <Modal.Title>{title}</Modal.Title>
+ <Group gap="sm" wrap="nowrap">
+ {onEdit && (
+ <Tooltip label={t`Edit this action`}>
+ <ActionIcon
+ variant="subtle"
+ aria-label={t`Edit this action`}
+ onClick={onEdit}
+ >
+ <Icon name="pencil" />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ <Modal.CloseButton />
+ </Group>
+ </Modal.Header>
+ <Modal.Body>
+ {showEmptyState ? (
<EmptyState message={t`Choose a record to update`} />
- )}
-
- {!showEmptyState && (
+ ) : (
<>
{showConfirmMessage && (
<ConfirmMessage message={confirmMessage} />
@@ -68,14 +82,14 @@ function ActionParametersInputModal({
<ActionParametersInputForm {...formProps} />
</>
)}
- </>
- </ModalContent>
- </Modal>
+ </Modal.Body>
+ </Modal.Content>
+ </Modal.Root>
);
}
const ConfirmMessage = ({ message }: { message?: string }) => (
- <div>{message ?? t`This action cannot be undone.`}</div>
+ <Text mb="xl">{message ?? t`This action cannot be undone.`}</Text>
);
// eslint-disable-next-line import/no-default-export -- deprecated usage
diff --git a/frontend/src/metabase/common/components/ModalContent/ModalContent.stories.tsx b/frontend/src/metabase/common/components/ModalContent/ModalContent.stories.tsx
deleted file mode 100644
index 00b13069328..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/ModalContent.stories.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { action } from "@storybook/addon-actions";
-import type { StoryFn } from "@storybook/react";
-
-import { color } from "metabase/ui/colors";
-
-import {
- ModalContent,
- ModalContentActionIcon,
- type ModalContentProps,
-} from "./index";
-
-export default {
- title: "Components/ModalContent",
- component: ModalContent,
- argTypes: {
- children: {
- table: {
- disable: true,
- },
- },
- headerActions: {
- table: {
- disable: true,
- },
- },
- onClose: { action: "onClose" },
- onBack: { action: "onBack" },
- },
-};
-
-const Template: StoryFn<ModalContentProps> = (args) => {
- return (
- <div
- style={{
- width: 1200,
- background: color("background_page-primary"),
- border: "1px solid black",
- }}
- >
- <ModalContent {...args} />
- </div>
- );
-};
-
-const args = {
- id: "id",
- title: "Long Modal title Long Modal title Long Modal title Long Modal title",
- centeredTitle: false,
- children: <>Content</>,
- fullPageModal: false,
- onClose: action("onClose"),
- onBack: undefined,
-};
-
-export const Default = {
- render: Template,
-
- args: {
- ...args,
- },
-};
-
-export const WithHeaderActions = {
- render: Template,
-
- args: {
- ...args,
- headerActions: (
- <>
- <ModalContentActionIcon name="pencil" onClick={action("Action1")} />
- </>
- ),
- },
-};
-
-export const WithBackButton = {
- render: Template,
-
- args: {
- ...args,
- onBack: action("onBack"),
- },
-};
diff --git a/frontend/src/metabase/common/components/ModalContent/ModalContent.tsx b/frontend/src/metabase/common/components/ModalContent/ModalContent.tsx
deleted file mode 100644
index aeefe00f0ce..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/ModalContent.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import cx from "classnames";
-import type { ReactNode } from "react";
-import { Component } from "react";
-
-import CS from "metabase/css/core/index.css";
-import ZIndex from "metabase/css/core/z-index.module.css";
-
-import { ModalHeader } from "./ModalHeader";
-import type { CommonModalProps } from "./types";
-
-export interface ModalContentProps extends CommonModalProps {
- "data-testid"?: string;
- id?: string;
- title?: string | ReactNode;
- footer?: ReactNode;
- withFooterTopBorder?: boolean;
- children: ReactNode;
-
- className?: string;
-}
-
-export class ModalContent extends Component<ModalContentProps> {
- static defaultProps = {
- formModal: true,
- };
-
- render() {
- const {
- "data-testid": dataTestId,
- title,
- centeredTitle,
- footer,
- onClose,
- onBack,
- children,
- className,
- fullPageModal,
- formModal,
- headerActions,
- withFooterTopBorder,
- } = this.props;
-
- return (
- <div
- id={this.props.id}
- className={cx(
- "ModalContent",
- CS.flexFull,
- CS.flex,
- CS.flexColumn,
- CS.relative,
- className,
- { [CS.fullHeight]: fullPageModal && !formModal },
- // add bottom padding if this is a standard "form modal" with no footer
- { [CS.pb4]: formModal && !footer },
- ZIndex.Overlay,
- )}
- data-testid={dataTestId}
- >
- {title && (
- <ModalHeader
- fullPageModal={fullPageModal}
- centeredTitle={centeredTitle}
- formModal={formModal}
- headerActions={headerActions}
- onClose={onClose}
- onBack={onBack}
- >
- {title}
- </ModalHeader>
- )}
- <ModalBody fullPageModal={fullPageModal} formModal={formModal}>
- {children}
- </ModalBody>
- {footer && (
- <ModalFooter
- fullPageModal={fullPageModal}
- formModal={formModal}
- withTopBorder={withFooterTopBorder}
- >
- {footer}
- </ModalFooter>
- )}
- </div>
- );
- }
-}
-
-const FORM_WIDTH = 500 + 32 * 2; // includes padding
-
-interface ModalBodyProps extends CommonModalProps {
- children: ReactNode;
-}
-
-export const ModalBody = ({
- children,
- fullPageModal,
- formModal,
-}: ModalBodyProps) => (
- <div
- className={cx("ModalBody", {
- [CS.px4]: formModal,
- [cx(CS.flex, CS.flexFull, CS.flexBasisAuto)]: !formModal,
- })}
- >
- <div
- className={cx(
- CS.flexFull,
- CS.mlAuto,
- CS.mrAuto,
- CS.flex,
- CS.flexColumn,
- ZIndex.Overlay,
- )}
- style={{ maxWidth: formModal && fullPageModal ? FORM_WIDTH : undefined }}
- >
- {children}
- </div>
- </div>
-);
-
-interface ModalFooterProps extends CommonModalProps {
- withTopBorder?: boolean;
- children: ReactNode;
-}
-
-export const ModalFooter = ({
- children,
- fullPageModal,
- formModal,
- withTopBorder,
-}: ModalFooterProps) => (
- <div
- className={cx(
- "ModalFooter",
- CS.flex,
- CS.flexNoShrink,
- CS.px4,
- fullPageModal ? CS.py4 : CS.py3,
- withTopBorder && CS.borderTop,
- withTopBorder && CS.mt4,
- )}
- >
- <div
- className={cx(CS.mlAuto, CS.flex, CS.alignCenter)}
- style={{ maxWidth: formModal && fullPageModal ? FORM_WIDTH : undefined }}
- >
- {Array.isArray(children)
- ? children.map((child, index) => (
- <span key={index} className={CS.ml2}>
- {child}
- </span>
- ))
- : children}
- </div>
- </div>
-);
diff --git a/frontend/src/metabase/common/components/ModalContent/ModalContent.unit.spec.tsx b/frontend/src/metabase/common/components/ModalContent/ModalContent.unit.spec.tsx
deleted file mode 100644
index 7b5858494b5..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/ModalContent.unit.spec.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import userEvent from "@testing-library/user-event";
-
-import { getIcon, render, screen } from "__support__/ui";
-
-import type { ModalContentProps } from "./ModalContent";
-import { ModalContent } from "./ModalContent";
-import { ModalContentActionIcon } from "./ModalHeader";
-
-describe("ModalContent", () => {
- it("should render header action buttons", async () => {
- const headerActions = [
- {
- icon: "pencil" as const,
- onClick: jest.fn(),
- },
- {
- icon: "bolt" as const,
- onClick: jest.fn(),
- },
- ];
-
- const headerActionsEl = (
- <>
- {headerActions.map(({ icon, onClick }) => (
- <ModalContentActionIcon key={icon} name={icon} onClick={onClick} />
- ))}
- </>
- );
-
- setup({ headerActions: headerActionsEl });
-
- for (const { icon, onClick } of headerActions) {
- const iconEl = getIcon(icon);
- expect(iconEl).toBeInTheDocument();
-
- await userEvent.click(iconEl);
-
- expect(onClick).toHaveBeenCalledTimes(1);
- }
- });
-
- it("should render back button if onBack props is passed", async () => {
- const onBack = jest.fn();
-
- setup({ onBack });
-
- const backButton = screen.getByRole("button", { name: "Back" });
- expect(backButton).toBeInTheDocument();
-
- await userEvent.click(backButton);
- expect(onBack).toHaveBeenCalledTimes(1);
- });
-
- it("should activate the back button with the keyboard", async () => {
- const onBack = jest.fn();
-
- setup({ onBack });
-
- screen.getByRole("button", { name: "Back" }).focus();
-
- await userEvent.keyboard("{Enter}");
- expect(onBack).toHaveBeenCalledTimes(1);
-
- await userEvent.keyboard(" ");
- expect(onBack).toHaveBeenCalledTimes(2);
- });
-
- it("should go back when the title is clicked", async () => {
- const onBack = jest.fn();
-
- setup({ onBack });
-
- await userEvent.click(screen.getByText(/Long Modal title/));
- expect(onBack).toHaveBeenCalledTimes(1);
- });
-});
-
-function setup({
- id = "id",
- title = "Long Modal title Long Modal title Long Modal title",
- centeredTitle = false,
- children = <>Content</>,
- fullPageModal = false,
- onClose = jest.fn(),
- onBack,
- ...extraProps
-}: Partial<ModalContentProps> = {}) {
- const props = {
- id,
- title,
- centeredTitle,
- children,
- fullPageModal,
- onClose,
- onBack,
- ...extraProps,
- };
-
- render(<ModalContent {...props} />);
-}
diff --git a/frontend/src/metabase/common/components/ModalContent/ModalHeader.module.css b/frontend/src/metabase/common/components/ModalContent/ModalHeader.module.css
deleted file mode 100644
index 5b589446117..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/ModalHeader.module.css
+++ /dev/null
@@ -1,38 +0,0 @@
-.HeaderText {
- display: flex;
- align-items: center;
-
- /* kept in CSS so .clickable:hover can override it (style props render inline) */
- color: var(--modal-header-text-color, var(--mb-color-text-primary));
-
- &.HeaderTextCentered {
- justify-content: center;
- }
-}
-
-.HeaderTextContent {
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.HeaderTextContainer {
- overflow: hidden;
-
- &.clickable:hover > * {
- color: var(--mb-color-core-brand);
- cursor: pointer;
- }
-}
-
-.actionIcon {
- composes: textSecondaryHoverPrimary from "style";
- cursor: pointer;
-}
-
-.backButton {
- color: var(--mb-color-text-secondary);
-
- &:hover {
- color: var(--mb-color-core-brand);
- }
-}
diff --git a/frontend/src/metabase/common/components/ModalContent/ModalHeader.tsx b/frontend/src/metabase/common/components/ModalContent/ModalHeader.tsx
deleted file mode 100644
index 96d680877f2..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/ModalHeader.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import cx from "classnames";
-import type { ReactNode } from "react";
-import { t } from "ttag";
-
-import type { IconProps, MantineStyleProps } from "metabase/ui";
-import { Flex, Icon, Title, UnstyledButton } from "metabase/ui";
-
-import S from "./ModalHeader.module.css";
-import type { CommonModalProps } from "./types";
-
-export const ModalContentActionIcon = ({ className, ...props }: IconProps) => (
- <Icon {...props} className={cx(S.actionIcon, className)} />
-);
-
-export interface ModalHeaderProps extends CommonModalProps {
- children: ReactNode;
-
- className?: string;
- py?: MantineStyleProps["py"];
-}
-
-export const ModalHeader = ({
- children,
- className,
- py = "xxl",
- fullPageModal,
- centeredTitle,
- headerActions,
- onClose,
- onBack,
-}: ModalHeaderProps) => {
- const hasActions = !!headerActions || !!onClose;
- const actionIconSize = fullPageModal ? 24 : 16;
-
- return (
- <Flex
- gap="sm"
- align="center"
- px="xxl"
- py={py}
- flex="0 0 auto"
- className={className}
- data-testid="modal-header"
- >
- <Flex
- align="center"
- gap="sm"
- flex="1 1 auto"
- className={cx(S.HeaderTextContainer, {
- [S.clickable]: !!onBack,
- })}
- onClick={onBack}
- >
- {onBack && (
- <UnstyledButton
- display="flex"
- flex="0 0 auto"
- className={S.backButton}
- aria-label={t`Back`}
- onClick={(event) => {
- // the container's onClick also calls onBack; don't fire it twice
- event.stopPropagation();
- onBack();
- }}
- >
- <Icon name="chevronleft" />
- </UnstyledButton>
- )}
-
- <Title
- order={3}
- w="100%"
- flex="1 1 auto"
- className={cx(S.HeaderText, {
- [S.HeaderTextCentered]: fullPageModal || centeredTitle,
- })}
- >
- <span className={S.HeaderTextContent}>{children}</span>
- </Title>
- </Flex>
-
- {hasActions && (
- <Flex gap="sm">
- {headerActions}
- {onClose && (
- <ModalContentActionIcon
- name="close"
- size={actionIconSize}
- onClick={onClose}
- />
- )}
- </Flex>
- )}
- </Flex>
- );
-};
diff --git a/frontend/src/metabase/common/components/ModalContent/index.ts b/frontend/src/metabase/common/components/ModalContent/index.ts
deleted file mode 100644
index 8c02cfefacc..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export * from "./ModalContent";
-export { ModalContentActionIcon } from "./ModalHeader";
-export type { CommonModalProps } from "./types";
-export { ModalHeader } from "./ModalHeader";
-export type { ModalHeaderProps } from "./ModalHeader";
diff --git a/frontend/src/metabase/common/components/ModalContent/types.ts b/frontend/src/metabase/common/components/ModalContent/types.ts
deleted file mode 100644
index e7c376c49d6..00000000000
--- a/frontend/src/metabase/common/components/ModalContent/types.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { ReactNode } from "react";
-
-export interface CommonModalProps {
- // takes over the entire screen
- fullPageModal?: boolean;
- // standard modal
- formModal?: boolean;
- centeredTitle?: boolean;
-
- headerActions?: ReactNode;
- onClose?: () => void;
- onBack?: () => void;
-}
diff --git a/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx
index a86acbe6d46..9ec879fad95 100644
--- a/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx
@@ -229,7 +229,7 @@ describe("Actions > ActionViz > Action", () => {
await setup();
await userEvent.click(screen.getByRole("button"));
- expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
expect(screen.getByTestId("action-form")).toBeInTheDocument();
expect(screen.getByLabelText("Parameter 1")).toBeInTheDocument();
});
@@ -246,7 +246,7 @@ describe("Actions > ActionViz > Action", () => {
});
await userEvent.click(screen.getByRole("button"));
- expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
expect(screen.getByTestId("action-form")).toBeInTheDocument();
expect(screen.queryByLabelText(/^Parameter/)).not.toBeInTheDocument();
});
@@ -255,16 +255,22 @@ describe("Actions > ActionViz > Action", () => {
await setup();
await userEvent.click(screen.getByRole("button"));
- expect(screen.getByRole("dialog")).toHaveTextContent("My Awesome Action");
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
+ "My Awesome Action",
+ );
});
it("clicking the cancel button on the form should close the modal", async () => {
await setup();
await userEvent.click(screen.getByRole("button"));
- expect(screen.getByRole("dialog")).toHaveTextContent("My Awesome Action");
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
+ "My Awesome Action",
+ );
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ await waitFor(() => {
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
});
it("should format dashboard filter values for numeric parameters", async () => {
@@ -308,7 +314,7 @@ describe("Actions > ActionViz > Action", () => {
});
await userEvent.click(screen.getByRole("button", { name: "Click me" }));
- expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
expect(screen.getByTestId("action-form")).toBeInTheDocument();
await userEvent.click(
within(screen.getByRole("dialog")).getByRole("button", {
@@ -346,7 +352,9 @@ describe("Actions > ActionViz > Action", () => {
await userEvent.click(screen.getByText("Click me"));
- const editActionEl = getIcon("pencil");
+ const editActionEl = await screen.findByRole("button", {
+ name: "Edit this action",
+ });
expect(editActionEl).toBeInTheDocument();
await userEvent.click(editActionEl);
@@ -382,7 +390,9 @@ describe("Actions > ActionViz > Action", () => {
await userEvent.click(screen.getByText("Click me"));
- await userEvent.click(getIcon("pencil"));
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Edit this action" }),
+ );
// wait for action edit form to be loaded
const editorModal = await screen.findByTestId("action-editor-modal");
@@ -529,7 +539,9 @@ describe("Actions > ActionViz > Action", () => {
});
await userEvent.click(screen.getByRole("button"));
- expect(screen.getByRole("dialog")).toHaveTextContent(/cannot be undone/i);
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
+ /cannot be undone/i,
+ );
expect(
screen.getByRole("button", { name: "Delete" }),
).toBeInTheDocument();
diff --git a/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.unit.spec.tsx
index 473bcced243..7c6b1f7be79 100644
--- a/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.unit.spec.tsx
@@ -107,6 +107,8 @@ describe("Actions > ActionVizForm", () => {
await userEvent.click(screen.getByText("Click me"));
- expect(screen.getByText(/Choose a record to update/i)).toBeInTheDocument();
+ expect(
+ await screen.findByText(/Choose a record to update/i),
+ ).toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsx b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsx
index 687f9419ef2..7b709df0bd6 100644
--- a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsx
+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsx
@@ -34,7 +34,6 @@ import {
Group,
Icon,
Menu,
- Modal,
Stack,
Tooltip,
rem,
@@ -395,20 +394,13 @@ export function DetailViewSidesheet({
onSuccess={handleActionSuccess}
/>
- <Modal
+ <DeleteObjectModal
opened={isDeleteModalOpen}
+ actionId={deleteActionId}
+ objectId={rowId}
onClose={handleDeleteModalClose}
- size="lg"
- withCloseButton={false}
- padding={0}
- >
- <DeleteObjectModal
- actionId={deleteActionId}
- objectId={rowId}
- onClose={handleDeleteModalClose}
- onSuccess={handleDeleteSuccess}
- />
- </Modal>
+ onSuccess={handleDeleteSuccess}
+ />
</>
);
}
diff --git a/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.module.css b/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.module.css
index 716855b95c7..59c716f4863 100644
--- a/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.module.css
+++ b/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.module.css
@@ -1,9 +1,3 @@
-.embedModalHeader {
- --modal-header-text-color: var(--mb-color-text-secondary);
-
- border-bottom: 1px solid var(--mb-color-border-neutral);
-}
-
/* As tall as the viewport allows, so the header stays put and the columns below scroll on their own */
.content {
display: flex;
@@ -12,9 +6,37 @@
overflow: hidden;
}
+.header {
+ border-bottom: 1px solid var(--mb-color-border-neutral);
+}
+
+/* The setup pane runs edge to edge below the header */
.body {
display: flex;
flex-direction: column;
flex: 1 1 auto;
min-height: 0;
+ padding: 0;
+}
+
+.backButton {
+ display: flex;
+ color: var(--mb-color-text-secondary);
+
+ &:hover {
+ color: var(--mb-color-core-brand);
+ }
+}
+
+.clickableTitle {
+ cursor: pointer;
+
+ &:hover {
+ color: var(--mb-color-core-brand);
+ }
+}
+
+.header:has(.clickableTitle:hover) .backButton,
+.header:has(.backButton:hover) .clickableTitle {
+ color: var(--mb-color-core-brand);
}
diff --git a/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.tsx b/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.tsx
index 987329070a6..1fcc13dec13 100644
--- a/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.tsx
+++ b/frontend/src/metabase/embedding/components/EmbedModal/EmbedModal.tsx
@@ -1,13 +1,12 @@
import { t } from "ttag";
-import { ModalHeader } from "metabase/common/components/ModalContent";
import { StaticEmbedSetupPane } from "metabase/embedding/components/EmbedModal/StaticEmbedSetupPane";
import type {
EmbedResource,
EmbedResourceParameter,
GuestEmbedResourceType,
} from "metabase/embedding/types";
-import { Modal } from "metabase/ui";
+import { Group, Icon, Modal, UnstyledButton } from "metabase/ui";
import type { EmbeddingParameters } from "metabase-types/api";
import S from "./EmbedModal.module.css";
@@ -34,29 +33,43 @@ export const EmbedModal = ({
onBack,
onClose,
}: EmbedModalProps) => (
- <Modal
+ <Modal.Root
opened={opened}
onClose={onClose}
size="auto"
- withCloseButton={false}
- padding={0}
- classNames={{ content: S.content, body: S.body }}
+ classNames={{ content: S.content, header: S.header, body: S.body }}
>
- <ModalHeader
- py="xl"
- className={S.embedModalHeader}
- onClose={onClose}
- onBack={onBack}
- >
- {t`Static embedding`}
- </ModalHeader>
-
- <StaticEmbedSetupPane
- resource={resource}
- resourceType={resourceType}
- resourceParameters={resourceParameters}
- onUpdateEnableEmbedding={onUpdateEnableEmbedding}
- onUpdateEmbeddingParams={onUpdateEmbeddingParams}
- />
- </Modal>
+ <Modal.Overlay />
+ <Modal.Content>
+ <Modal.Header>
+ <Group gap="sm" wrap="nowrap" flex="1 1 auto" miw={0}>
+ {onBack && (
+ <UnstyledButton
+ className={S.backButton}
+ aria-label={t`Back`}
+ onClick={onBack}
+ >
+ <Icon name="chevronleft" />
+ </UnstyledButton>
+ )}
+ <Modal.Title
+ className={onBack ? S.clickableTitle : undefined}
+ onClick={onBack}
+ >
+ {t`Static embedding`}
+ </Modal.Title>
+ </Group>
+ <Modal.CloseButton />
+ </Modal.Header>
+ <Modal.Body>
+ <StaticEmbedSetupPane
+ resource={resource}
+ resourceType={resourceType}
+ resourceParameters={resourceParameters}
+ onUpdateEnableEmbedding={onUpdateEnableEmbedding}
+ onUpdateEmbeddingParams={onUpdateEmbeddingParams}
+ />
+ </Modal.Body>
+ </Modal.Content>
+ </Modal.Root>
);
diff --git a/frontend/src/metabase/monitor/routes.tsx b/frontend/src/metabase/monitor/routes.tsx
index 121086ee0ae..31fe1564413 100644
--- a/frontend/src/metabase/monitor/routes.tsx
+++ b/frontend/src/metabase/monitor/routes.tsx
@@ -172,7 +172,9 @@ export function getMonitorRoutes() {
<Route path=":jobKey" />
</Route>
<Route path="logs" lazy={logs}>
- {lazyModalRouteElement("levels", logLevelsModal)}
+ {lazyModalRouteElement("levels", logLevelsModal, {
+ noWrap: true,
+ })}
</Route>
<Route
path="errors"
@@ -181,7 +183,9 @@ export function getMonitorRoutes() {
)}
/>
<Route path="model-persistence-log" lazy={modelPersistenceLogPage}>
- {modalRoute(":jobId", ModelPersistenceLogJobModal)}
+ {modalRoute(":jobId", ModelPersistenceLogJobModal, {
+ noWrap: true,
+ })}
</Route>
</Route>
diff --git a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsForm.tsx b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsForm.tsx
index 818070044bb..6846b651474 100644
--- a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsForm.tsx
+++ b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsForm.tsx
@@ -4,7 +4,7 @@ import { t } from "ttag";
import { CodeEditor } from "metabase/common/components/CodeEditor";
import { Form, FormErrorMessage, FormSubmitButton } from "metabase/forms";
-import { Box, Button, Flex, Icon, Text, Tooltip } from "metabase/ui";
+import { Box, Button, Flex, Icon, Modal, Text, Tooltip } from "metabase/ui";
import type { LoggerPreset } from "metabase-types/api";
import { DurationInput } from "./DurationInput";
@@ -33,7 +33,7 @@ export const LogLevelsForm = ({ presets }: Props) => {
return (
<Form>
- <Flex align="flex-end" gap="lg" justify="space-between" mb="lg">
+ <Flex align="flex-end" gap="lg" justify="space-between" mb="xl">
<DurationInput />
{presets.length > 0 && (
@@ -76,22 +76,20 @@ export const LogLevelsForm = ({ presets }: Props) => {
<FormErrorMessage />
</Box>
- <Flex align="center" gap="lg" justify="space-between" mt="xxl">
- <Tooltip
- label={t`Available log levels: ${["off", "fatal", "error", "warn", "info", "debug", "trace"].join(", ")}`}
- >
- <Icon name="info" />
- </Tooltip>
-
- <Flex gap="lg" justify="flex-end">
- <Button
- leftSection={<Icon name="revert" />}
- type="reset"
- >{t`Reset to defaults`}</Button>
-
- <FormSubmitButton label={t`Save`} variant="filled" />
- </Flex>
- </Flex>
+ <Modal.Footer>
+ <Box flex={1}>
+ <Tooltip
+ label={t`Available log levels: ${["off", "fatal", "error", "warn", "info", "debug", "trace"].join(", ")}`}
+ >
+ <Icon name="info" />
+ </Tooltip>
+ </Box>
+ <Button
+ leftSection={<Icon name="revert" />}
+ type="reset"
+ >{t`Reset to defaults`}</Button>
+ <FormSubmitButton label={t`Save`} variant="filled" />
+ </Modal.Footer>
</Form>
);
};
diff --git a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.tsx b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.tsx
index 301c6f0668e..fb88074d8ef 100644
--- a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.tsx
+++ b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.tsx
@@ -7,8 +7,8 @@ import {
useResetLogLevelsMutation,
} from "metabase/api/logger";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import { ModalContent } from "metabase/common/components/ModalContent";
import { FormProvider } from "metabase/forms";
+import { Modal } from "metabase/ui";
import type { LoggerDurationUnit } from "metabase-types/api";
import { LogLevelsForm } from "./LogLevelsForm";
@@ -74,31 +74,34 @@ export const LogLevelsModal = ({ onClose }: Props) => {
}
};
- if (presetsError || isLoadingPresets) {
- return (
- <ModalContent title={t`Customize log levels`} onClose={onClose}>
- <LoadingAndErrorWrapper
- error={presetsError}
- loading={isLoadingPresets}
- />
- </ModalContent>
- );
- }
-
return (
- <ModalContent title={t`Customize log levels`} onClose={onClose}>
- <FormProvider
- initialValues={{
- duration: 60,
- durationUnit: "minutes",
- json: "",
- }}
- validationSchema={VALIDATION_SCHEMA}
- onReset={handleReset}
- onSubmit={handleSubmit}
+ <Modal
+ opened
+ size="lg"
+ density="relaxed"
+ title={t`Customize log levels`}
+ onClose={onClose}
+ >
+ <LoadingAndErrorWrapper
+ error={presetsError}
+ loading={isLoadingPresets}
+ noWrapper
>
- <LogLevelsForm presets={presets} />
- </FormProvider>
- </ModalContent>
+ {() => (
+ <FormProvider
+ initialValues={{
+ duration: 60,
+ durationUnit: "minutes",
+ json: "",
+ }}
+ validationSchema={VALIDATION_SCHEMA}
+ onReset={handleReset}
+ onSubmit={handleSubmit}
+ >
+ <LogLevelsForm presets={presets} />
+ </FormProvider>
+ )}
+ </LoadingAndErrorWrapper>
+ </Modal>
);
};
diff --git a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx
index 6befb192dd0..ab24e2e8c6a 100644
--- a/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.unit.spec.tsx
@@ -56,9 +56,7 @@ const setup = ({ error, presets = [PRESET_A, PRESET_B] }: SetupOpts = {}) => {
return renderWithProviders(
<Route path="/">
- {modalRoute("levels", LogLevelsModal, {
- modalProps: { transitionProps: { duration: 0 } },
- })}
+ {modalRoute("levels", LogLevelsModal, { noWrap: true })}
</Route>,
{
initialRoute: "/levels",
diff --git a/frontend/src/metabase/monitor/tools/components/ModelPersistenceLogJobs/ModelPersistenceLogJobModal.tsx b/frontend/src/metabase/monitor/tools/components/ModelPersistenceLogJobs/ModelPersistenceLogJobModal.tsx
index 4b4301e341a..298ecfeaa15 100644
--- a/frontend/src/metabase/monitor/tools/components/ModelPersistenceLogJobs/ModelPersistenceLogJobModal.tsx
+++ b/frontend/src/metabase/monitor/tools/components/ModelPersistenceLogJobs/ModelPersistenceLogJobModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from "react";
+import { useEffect } from "react";
import { usePrevious } from "react-use";
import { t } from "ttag";
@@ -8,9 +8,8 @@ import {
useRefreshModelCacheMutation,
} from "metabase/api";
import { Link } from "metabase/common/components/Link";
-import { ModalContent } from "metabase/common/components/ModalContent";
import type { ModalComponentProps } from "metabase/common/components/ModalRoute";
-import { Box, Button } from "metabase/ui";
+import { Box, Button, Modal } from "metabase/ui";
import { parseNumberParam } from "metabase/urls";
import S from "./ModelPersistenceLogJobs.module.css";
@@ -37,32 +36,23 @@ export function ModelPersistenceLogJobModal({
}
}, [prevModelInfo, persistedModel, onClose]);
- const footer = useMemo(() => {
- if (!persistedModel) {
- return null;
- }
-
- const onRefreshClick = () => refreshModelCache(persistedModel.card_id);
-
- return [
- <Button
- key="retry"
- variant="filled"
- onClick={onRefreshClick}
- >{t`Retry now`}</Button>,
- <Button
- key="edit"
- component={Link}
- to={`/model/${persistedModel.card_id}/query`}
- >{t`Edit model`}</Button>,
- ];
- }, [persistedModel, refreshModelCache]);
-
return (
- <ModalContent title={t`Oh oh…`} onClose={onClose} footer={footer}>
+ <Modal opened size="lg" title={t`Oh oh…`} onClose={onClose}>
{persistedModel?.error && (
<Box className={S.errorBox}>{persistedModel.error}</Box>
)}
- </ModalContent>
+ {persistedModel && (
+ <Modal.Footer>
+ <Button
+ component={Link}
+ to={`/model/${persistedModel.card_id}/query`}
+ >{t`Edit model`}</Button>
+ <Button
+ variant="filled"
+ onClick={() => refreshModelCache(persistedModel.card_id)}
+ >{t`Retry now`}</Button>
+ </Modal.Footer>
+ )}
+ </Modal>
);
}
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.tsx
index 8993ef57cb7..5171b073be7 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.tsx
+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.tsx
@@ -46,25 +46,32 @@ const ValuesSourceModal = ({
onClose();
}, [sourceType, sourceConfig, onSubmit, onClose]);
- return step === "main" ? (
- <ValuesSourceTypeModal
- parameter={parameter}
- sourceType={sourceType}
- sourceConfig={sourceConfig}
- onChangeSourceType={setSourceType}
- onChangeSourceConfig={setSourceConfig}
- onChangeCard={handlePickerOpen}
- onSubmit={handleSubmit}
- onClose={onClose}
- />
- ) : (
- <ValuesSourceCardModal
- parameter={parameter}
- sourceConfig={sourceConfig}
- onChangeSourceConfig={setSourceConfig}
- onSubmit={handlePickerClose}
- onClose={handlePickerClose}
- />
+ // The picker opens on top of the main step rather than replacing it, so the
+ // main step's modal isn't torn down and re-animated between steps. Its panel
+ // is hidden meanwhile, as it's wider than the picker on wide screens
+ return (
+ <>
+ <ValuesSourceTypeModal
+ parameter={parameter}
+ isContentHidden={step === "card"}
+ sourceType={sourceType}
+ sourceConfig={sourceConfig}
+ onChangeSourceType={setSourceType}
+ onChangeSourceConfig={setSourceConfig}
+ onChangeCard={handlePickerOpen}
+ onSubmit={handleSubmit}
+ onClose={onClose}
+ />
+ {step === "card" && (
+ <ValuesSourceCardModal
+ parameter={parameter}
+ sourceConfig={sourceConfig}
+ onChangeSourceConfig={setSourceConfig}
+ onSubmit={handlePickerClose}
+ onClose={handlePickerClose}
+ />
+ )}
+ </>
);
};
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx
index 199428ccc57..ab02800664d 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx
+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx
@@ -1,4 +1,5 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { setupEnterprisePlugins } from "__support__/enterprise";
import { createMockMetadata } from "__support__/metadata";
@@ -20,18 +21,23 @@ import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import { createMockEntitiesState } from "__support__/store";
import {
+ fireEvent,
+ mockGetBoundingClientRect,
renderWithProviders,
screen,
waitForLoaderToBeRemoved,
+ within,
} from "__support__/ui";
import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import { defer } from "metabase/utils/promise";
import { checkNotNull } from "metabase/utils/types";
import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
-import type { Card, ParameterValues } from "metabase-types/api";
+import type { Card, CollectionItem, ParameterValues } from "metabase-types/api";
import {
createMockCard,
createMockCollection,
+ createMockCollectionItem,
createMockDatabase,
createMockField,
createMockParameterValues,
@@ -429,6 +435,64 @@ describe("ValuesSourceModal", () => {
);
});
+ it("should show a loader instead of the previous card while the next card loads", async () => {
+ mockGetBoundingClientRect();
+ const nextCard = createMockCard({ id: 2, name: "Reviews" });
+ await setup({
+ parameter: createMockUiParameter({
+ values_source_type: "card",
+ values_source_config: { card_id: 1 },
+ }),
+ cards: [createMockCard({ id: 1, name: "Products" }), nextCard],
+ rootCollectionItems: [
+ createMockCollectionItem({
+ id: nextCard.id,
+ name: nextCard.name,
+ model: "card",
+ }),
+ ],
+ });
+ const nextCardResponse = defer<Card>();
+ fetchMock.removeRoute("card-2-get");
+ fetchMock.get("path:/api/card/2", nextCardResponse.promise);
+
+ await userEvent.click(screen.getByRole("button", { name: /Products/ }));
+ await userEvent.click(await screen.findByText("Reviews"));
+ await userEvent.click(
+ await screen.findByTestId("entity-picker-select-button"),
+ );
+
+ expect(
+ await screen.findByTestId("loading-indicator"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Products/ }),
+ ).not.toBeInTheDocument();
+
+ nextCardResponse.resolve(nextCard);
+ await waitForLoaderToBeRemoved();
+
+ expect(
+ screen.getByRole("button", { name: /Reviews/ }),
+ ).toBeInTheDocument();
+ });
+
+ it("should not block scrolling inside the picker", async () => {
+ await setup({
+ parameter: createMockUiParameter({
+ values_source_type: "card",
+ }),
+ });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: /Pick a model or question/ }),
+ );
+ const picker = await screen.findByTestId("entity-picker-modal");
+
+ // `fireEvent` returns false when a handler called `preventDefault`
+ expect(fireEvent.wheel(picker, { deltaY: 100 })).toBe(true);
+ });
+
it("should display a message when the user has no access to the card", async () => {
await setup({
parameter: createMockUiParameter({
@@ -446,8 +510,13 @@ describe("ValuesSourceModal", () => {
hasCollectionAccess: false,
});
+ // The error stays inside the modal, so it keeps its title and close button
+ const modal = screen.getByRole("dialog");
+ expect(
+ within(modal).getByText("You don't have permissions to do that."),
+ ).toBeInTheDocument();
expect(
- screen.getByText("You don't have permissions to do that."),
+ within(modal).getByRole("button", { name: "Close" }),
).toBeInTheDocument();
});
@@ -540,6 +609,83 @@ describe("ValuesSourceModal", () => {
).toBeChecked();
expect(screen.getByRole("textbox")).toHaveValue("A\nB\nC");
});
+
+ it("should not copy the previous card's values to a custom list", async () => {
+ mockGetBoundingClientRect();
+ const cards = [
+ createMockCard({
+ id: 1,
+ name: "Products",
+ result_metadata: [
+ createMockField({
+ id: 2,
+ display_name: "Category",
+ base_type: "type/Text",
+ effective_type: "type/Text",
+ }),
+ ],
+ }),
+ createMockCard({
+ id: 3,
+ name: "People",
+ result_metadata: [
+ createMockField({
+ id: 4,
+ display_name: "Source",
+ base_type: "type/Text",
+ effective_type: "type/Text",
+ }),
+ ],
+ }),
+ ];
+ await setup({
+ parameter: createMockUiParameter({
+ values_source_type: "card",
+ values_source_config: {
+ card_id: 1,
+ value_field: ["field", 2, null],
+ },
+ }),
+ parameterValues: createMockParameterValues({
+ values: [["A"], ["B"], ["C"]],
+ }),
+ cards,
+ rootCollectionItems: cards.map(({ id, name }) =>
+ createMockCollectionItem({ id, name, model: "card" }),
+ ),
+ });
+ const pickCard = async (currentName: RegExp, nextName: string) => {
+ await userEvent.click(
+ screen.getByRole("button", { name: currentName }),
+ );
+ const picker = await screen.findByTestId("entity-picker-modal");
+ await userEvent.click(await within(picker).findByText(nextName));
+ await userEvent.click(
+ await within(picker).findByTestId("entity-picker-select-button"),
+ );
+ await waitForLoaderToBeRemoved();
+ };
+
+ await pickCard(/Products/, "People");
+ await userEvent.click(
+ await screen.findByPlaceholderText(/Pick a column/),
+ );
+ await userEvent.click(
+ await screen.findByRole("option", { name: "Source" }),
+ );
+ expect(
+ await screen.findByRole("textbox", { name: "Values" }),
+ ).toHaveValue("A\nB\nC");
+
+ // Products is cached by now, so this pick doesn't show the loader
+ await pickCard(/People/, "Products");
+ expect(await screen.findByText("Pick a column")).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("radio", { name: "Custom list" }),
+ );
+ expect(screen.getByRole("textbox")).toHaveValue("");
+ });
});
describe("list source", () => {
@@ -990,6 +1136,7 @@ interface SetupOpts {
parameter?: UiParameter;
parameterValues?: ParameterValues;
cards?: Card[];
+ rootCollectionItems?: CollectionItem[];
hasCollectionAccess?: boolean;
hasParameterValuesError?: boolean;
showMetabaseLinks?: boolean;
@@ -999,6 +1146,7 @@ const setup = async ({
parameter = createMockUiParameter(),
parameterValues = createMockParameterValues(),
cards = [],
+ rootCollectionItems = [],
hasCollectionAccess = true,
hasParameterValuesError = false,
showMetabaseLinks = true,
@@ -1016,7 +1164,7 @@ const setup = async ({
setupSearchEndpoints([]);
setupRecentViewsAndSelectionsEndpoints([]);
setupCollectionByIdEndpoint({
- collections: [personalCollection],
+ collections: [rootCollection, personalCollection],
});
setupCollectionItemsEndpoint({
collection: personalCollection,
@@ -1025,6 +1173,10 @@ const setup = async ({
if (hasCollectionAccess) {
setupCollectionsEndpoints({ collections: [rootCollection] });
+ setupCollectionItemsEndpoint({
+ collection: rootCollection,
+ collectionItems: rootCollectionItems,
+ });
setupCardsEndpoints(cards);
cards.forEach((card) =>
setupTableQueryMetadataEndpoint(
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.module.css b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.module.css
index 43c0c97fb1d..c9b9ad328b8 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.module.css
+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.module.css
@@ -67,5 +67,10 @@
display: flex;
justify-content: center;
align-items: center;
- height: calc(50vh + 11.25rem);
+ /* The body plus the footer, so the modal keeps its size once loaded */
+ height: calc(50vh + 4rem);
+}
+
+.hiddenContent {
+ visibility: hidden;
}
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx
index 693c8343da4..5e218e73afe 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx
+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx
@@ -9,13 +9,21 @@ import {
useGetTableQueryMetadataQuery,
} from "metabase/api";
import { ExternalLink } from "metabase/common/components/ExternalLink";
-import { ModalContent } from "metabase/common/components/ModalContent";
import { SelectButton } from "metabase/common/components/SelectButton";
import { useQuestionFromCard } from "metabase/metadata-store";
import { connect, useSelector } from "metabase/redux";
import { getLearnUrl } from "metabase/selectors/settings";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
-import { Box, Button, Flex, Icon, Radio, Select, Stack } from "metabase/ui";
+import {
+ Box,
+ Button,
+ Flex,
+ Icon,
+ Modal,
+ Radio,
+ Select,
+ Stack,
+} from "metabase/ui";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";
@@ -80,6 +88,11 @@ interface ModalDispatchProps {
type ModalProps = ModalOwnProps & ModalQuestionProps & ModalDispatchProps;
+type ModalLoaderProps = ModalOwnProps & {
+ /** Hides the modal's panel but keeps it open, along with its backdrop. */
+ isContentHidden?: boolean;
+};
+
const ValuesSourceTypeModal = ({
parameter,
question,
@@ -90,21 +103,9 @@ const ValuesSourceTypeModal = ({
onChangeSourceConfig,
onChangeCard,
onSubmit,
- onClose,
}: ModalProps): JSX.Element => {
return (
- <ModalContent
- title={t`Selectable values for ${parameter.name}`}
- footer={[
- <Button
- key="submit"
- variant="filled"
- disabled={!isValidSourceConfig(sourceType, sourceConfig)}
- onClick={onSubmit}
- >{t`Done`}</Button>,
- ]}
- onClose={onClose}
- >
+ <>
{sourceType === null ? (
<FieldSourceModal
// if sourceType === null the parameter must have fields
@@ -135,7 +136,14 @@ const ValuesSourceTypeModal = ({
onChangeSourceConfig={onChangeSourceConfig}
/>
) : null}
- </ModalContent>
+ <Modal.Footer>
+ <Button
+ variant="filled"
+ disabled={!isValidSourceConfig(sourceType, sourceConfig)}
+ onClick={onSubmit}
+ >{t`Done`}</Button>
+ </Modal.Footer>
+ </>
);
};
@@ -692,7 +700,7 @@ const useParameterValues = ({
}, [isValidSource, handleFetchValues]);
return {
- values: value?.values ?? [],
+ values: isValidSource && !loading ? (value?.values ?? []) : [],
isLoading: loading,
isError: !!error,
};
@@ -710,29 +718,44 @@ const ValuesSourceTypeModalConnected = connect(
// Loads the source card and its virtual-table query metadata into the store (so
// the question and its connected fields are available) before rendering,
// replacing the former Questions.load / Tables.load HOCs.
-function ValuesSourceTypeModalLoader(props: ModalOwnProps) {
+function ValuesSourceTypeModalLoader({
+ isContentHidden = false,
+ ...props
+}: ModalLoaderProps) {
const { card_id } = props.sourceConfig;
const virtualTableId =
card_id != null ? getQuestionVirtualTableId(card_id) : undefined;
- const { isLoading: isMetadataLoading, error: metadataError } =
+ const { isFetching: isMetadataFetching, error: metadataError } =
useGetTableQueryMetadataQuery(
virtualTableId != null ? { id: virtualTableId } : skipToken,
);
const {
data: card,
- isLoading: isCardLoading,
+ isFetching: isCardFetching,
error: cardError,
} = useGetCardQuery(card_id != null ? { id: card_id } : skipToken);
const question = useQuestionFromCard(card);
return (
- <ModalLoadingAndErrorWrapper
- loading={isMetadataLoading || isCardLoading}
- error={metadataError ?? cardError}
- noWrapper
+ <Modal
+ opened
+ size="65%"
+ density="relaxed"
+ title={t`Selectable values for ${props.parameter.name}`}
+ classNames={{ content: isContentHidden ? S.hiddenContent : undefined }}
+ // The picker is outside this modal's React tree, so a lock here would
+ // treat it as outside the modal and cancel its wheel and touch scrolling
+ lockScroll={!isContentHidden}
+ onClose={props.onClose}
>
- <ValuesSourceTypeModalConnected {...props} question={question} />
- </ModalLoadingAndErrorWrapper>
+ <ModalLoadingAndErrorWrapper
+ loading={isMetadataFetching || isCardFetching}
+ error={metadataError ?? cardError}
+ noWrapper
+ >
+ <ValuesSourceTypeModalConnected {...props} question={question} />
+ </ModalLoadingAndErrorWrapper>
+ </Modal>
);
}
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceSettings/ValuesSourceSettings.tsx b/frontend/src/metabase/parameters/components/ValuesSourceSettings/ValuesSourceSettings.tsx
index c65f4d3155b..8294948bf9e 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceSettings/ValuesSourceSettings.tsx
+++ b/frontend/src/metabase/parameters/components/ValuesSourceSettings/ValuesSourceSettings.tsx
@@ -1,7 +1,7 @@
import { useState } from "react";
import { t } from "ttag";
-import { Box, Button, Flex, Modal, Radio, Stack, Tooltip } from "metabase/ui";
+import { Box, Button, Flex, Radio, Stack, Tooltip } from "metabase/ui";
import { getQueryType } from "metabase-lib/v1/parameters/utils/parameter-source";
import type {
Parameter,
@@ -66,19 +66,13 @@ export function ValuesSourceSettings({
/>
</Stack>
</Radio.Group>
- <Modal
- opened={isModalOpened}
- onClose={closeModal}
- size="65%"
- padding={0}
- withCloseButton={false}
- >
+ {isModalOpened && (
<ValuesSourceModal
parameter={parameter}
onSubmit={onChangeSourceSettings}
onClose={closeModal}
/>
- </Modal>
+ )}
</>
);
}
diff --git a/frontend/src/metabase/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx b/frontend/src/metabase/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
index d9a8785b979..61e3142e1f7 100644
--- a/frontend/src/metabase/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
+++ b/frontend/src/metabase/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
@@ -9,7 +9,6 @@ import {
} from "metabase/api";
import { isPersonalCollectionChild } from "metabase/common/collections/utils";
import { Link } from "metabase/common/components/Link";
-import { ModalContent } from "metabase/common/components/ModalContent";
import CS from "metabase/css/core/index.css";
import { connect, useSelector } from "metabase/redux";
import type { State } from "metabase/redux/store";
@@ -151,33 +150,7 @@ const CollectionPermissionsModalBody = ({
);
return (
- <ModalContent
- title={modalTitle}
- onClose={onClose}
- className={CS.overflowHidden}
- footer={[
- ...(isFolderNamespace(namespace)
- ? []
- : [
- <Link
- key="all-permissions"
- className={CS.link}
- to="/admin/permissions/collections"
- >
- {t`See all collection permissions`}
- </Link>,
- ]),
- <Button key="cancel" onClick={onClose}>{t`Cancel`}</Button>,
- <Button
- key="save"
- variant="filled"
- disabled={!isDirty}
- onClick={handleSave}
- >
- {t`Save`}
- </Button>,
- ]}
- >
+ <Modal opened size="lg" title={modalTitle} onClose={onClose}>
<div className={S.PermissionTableContainer}>
{permissionEditor && (
<PermissionsTable
@@ -186,7 +159,18 @@ const CollectionPermissionsModalBody = ({
/>
)}
</div>
- </ModalContent>
+ <Modal.Footer>
+ {!isFolderNamespace(namespace) && (
+ <Link className={CS.link} to="/admin/permissions/collections">
+ {t`See all collection permissions`}
+ </Link>
+ )}
+ <Button onClick={onClose}>{t`Cancel`}</Button>
+ <Button variant="filled" disabled={!isDirty} onClick={handleSave}>
+ {t`Save`}
+ </Button>
+ </Modal.Footer>
+ </Modal>
);
};
@@ -206,18 +190,10 @@ export function CollectionPermissionsModal({
onClose,
}: CollectionPermissionsModalProps) {
return (
- <Modal
- opened
+ <ConnectedCollectionPermissionsModalBody
+ params={params}
+ namespace={namespace}
onClose={onClose}
- withCloseButton={false}
- padding={0}
- size="lg"
- >
- <ConnectedCollectionPermissionsModalBody
- params={params}
- namespace={namespace}
- onClose={onClose}
- />
- </Modal>
+ />
);
}
diff --git a/frontend/src/metabase/query_builder/components/ImpossibleToCreateModelModal/ImpossibleToCreateModelModal.tsx b/frontend/src/metabase/query_builder/components/ImpossibleToCreateModelModal/ImpossibleToCreateModelModal.tsx
index abeb19817c7..968e4cf7855 100644
--- a/frontend/src/metabase/query_builder/components/ImpossibleToCreateModelModal/ImpossibleToCreateModelModal.tsx
+++ b/frontend/src/metabase/query_builder/components/ImpossibleToCreateModelModal/ImpossibleToCreateModelModal.tsx
@@ -1,13 +1,10 @@
-import cx from "classnames";
import { jt, t } from "ttag";
import { ExternalLink } from "metabase/common/components/ExternalLink";
-import { ModalContent } from "metabase/common/components/ModalContent";
-import CS from "metabase/css/core/index.css";
import { useSelector } from "metabase/redux";
import { getDocsUrl } from "metabase/selectors/settings";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
-import { Button } from "metabase/ui";
+import { Button, Modal, Text } from "metabase/ui";
type Props = {
onClose: () => void;
@@ -38,11 +35,13 @@ export function ImpossibleToCreateModelModal({ onClose }: Props) {
const showMetabaseLinks = useSelector(getShowMetabaseLinks);
return (
- <ModalContent
+ <Modal
+ opened
+ size="lg"
title={t`Variables in models aren't supported yet`}
onClose={onClose}
>
- <p className={CS.textParagraph}>
+ <Text>
{showMetabaseLinks
? jt`To solve this, just remove the variables in this question and try again. (It's okay to use ${(
<SQLSnippetsDocLink key="link-1" />
@@ -50,10 +49,10 @@ export function ImpossibleToCreateModelModal({ onClose }: Props) {
<ReferencingQuestionsDocLink key="link-2" />
)} in your query.)`
: t`To solve this, just remove the variables in this question and try again. (It's okay to use SQL snippets or reference the results of another saved question in your query.)`}
- </p>
- <div className={cx(CS.flex, CS.justifyCenter, CS.py1)}>
+ </Text>
+ <Modal.Footer>
<Button variant="filled" onClick={onClose}>{t`Okay`}</Button>
- </div>
- </ModalContent>
+ </Modal.Footer>
+ </Modal>
);
}
diff --git a/frontend/src/metabase/query_builder/components/NewDatasetModal/NewDatasetModal.tsx b/frontend/src/metabase/query_builder/components/NewDatasetModal/NewDatasetModal.tsx
index f62c9506632..aed22497bf1 100644
--- a/frontend/src/metabase/query_builder/components/NewDatasetModal/NewDatasetModal.tsx
+++ b/frontend/src/metabase/query_builder/components/NewDatasetModal/NewDatasetModal.tsx
@@ -2,10 +2,9 @@ import { useCallback } from "react";
import { t } from "ttag";
import ModelSVG from "assets/img/model-illustration.svg?component";
-import { ModalContent } from "metabase/common/components/ModalContent";
import { useUserAcknowledgement } from "metabase/current-user";
import { useDispatch } from "metabase/redux";
-import { Box, Button, Text } from "metabase/ui";
+import { Box, Button, Modal } from "metabase/ui";
import { turnQuestionIntoModel } from "../../actions";
@@ -23,41 +22,36 @@ export function NewDatasetModal({ onClose }: { onClose: () => void }) {
}, [dispatch, ack, onClose]);
return (
- <ModalContent
- footer={[
- <Button
- key="cancel"
- onClick={onClose}
- variant="subtle"
- color="neutral"
- >{t`Cancel`}</Button>,
- <Button
- key="action"
- variant="filled"
- onClick={onConfirm}
- >{t`Turn this into a model`}</Button>,
- ]}
+ <Modal
+ opened
+ size="md"
+ layout="centered"
+ illustration={<ModelSVG />}
+ title={t`Models`}
+ onClose={onClose}
>
- <Box p="2rem 1rem 0">
- <Box pt="lg">
- <ModelSVG />
- </Box>
- <Text component="h2" mt="2rem" mb="lg">{t`Models`}</Text>
- <ul>
- <li className={NewDatasetModalS.DatasetValueProp}>
- {t`Let you update column descriptions and customize metadata to create
+ <Box component="ul" ta="left">
+ <li className={NewDatasetModalS.DatasetValueProp}>
+ {t`Let you update column descriptions and customize metadata to create
great starting points for exploration.`}
- </li>
- <li className={NewDatasetModalS.DatasetValueProp}>
- {t`Show up higher in search results and get highlighted when other
+ </li>
+ <li className={NewDatasetModalS.DatasetValueProp}>
+ {t`Show up higher in search results and get highlighted when other
users start new questions to promote reuse.`}
- </li>
- <li className={NewDatasetModalS.DatasetValueProp}>
- {t`Live in collections to keep them separate from messy database
+ </li>
+ <li className={NewDatasetModalS.DatasetValueProp}>
+ {t`Live in collections to keep them separate from messy database
schemas.`}
- </li>
- </ul>
+ </li>
</Box>
- </ModalContent>
+ <Modal.Footer>
+ <Button onClick={onClose} variant="subtle" color="neutral">
+ {t`Cancel`}
+ </Button>
+ <Button variant="filled" onClick={onConfirm}>
+ {t`Turn this into a model`}
+ </Button>
+ </Modal.Footer>
+ </Modal>
);
}
diff --git a/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx b/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx
index b21f8ee0c9f..4adfc061ca3 100644
--- a/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx
+++ b/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx
@@ -17,7 +17,7 @@ import { MoveCardModal } from "metabase/questions/components/MoveCardModal";
import { useDispatch, useSelector } from "metabase/redux";
import type { QueryBuilderMode, QueryModalType } from "metabase/redux/store";
import { useNavigate } from "metabase/router";
-import { Modal, Text } from "metabase/ui";
+import { Text } from "metabase/ui";
import * as Urls from "metabase/urls";
import type Question from "metabase-lib/v1/Question";
import type { Card, DashboardTabId } from "metabase-types/api";
@@ -289,29 +289,9 @@ export function QueryModals({
/>
);
case MODAL_TYPES.TURN_INTO_DATASET:
- return (
- <Modal
- opened
- onClose={onCloseModal}
- size="md"
- withCloseButton={false}
- padding={0}
- >
- <NewDatasetModal onClose={onCloseModal} />
- </Modal>
- );
+ return <NewDatasetModal onClose={onCloseModal} />;
case MODAL_TYPES.CAN_NOT_CREATE_MODEL:
- return (
- <Modal
- opened
- onClose={onCloseModal}
- size="lg"
- withCloseButton={false}
- padding={0}
- >
- <ImpossibleToCreateModelModal onClose={onCloseModal} />
- </Modal>
- );
+ return <ImpossibleToCreateModelModal onClose={onCloseModal} />;
case MODAL_TYPES.PREVIEW_QUERY:
return <PreviewQueryModal onClose={onCloseModal} />;
case MODAL_TYPES.QUESTION_EMBED:
diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx
index f75d945fed8..63cfd35898f 100644
--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx
+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx
@@ -18,7 +18,7 @@ import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
import { NotFound } from "metabase/common/components/ErrorPages";
import CS from "metabase/css/core/index.css";
import { useDispatch } from "metabase/redux";
-import { Box, Center, Flex, Loader, Modal } from "metabase/ui";
+import { Box, Center, Flex, Loader } from "metabase/ui";
import * as Lib from "metabase-lib";
import { isVirtualCardId } from "metabase-lib/v1/metadata/utils/saved-questions";
import type {
@@ -369,14 +369,13 @@ export function ObjectDetailPanel({
onSuccess={onActionSuccess}
/>
- <Modal opened={isDeleteModalOpen} onClose={handleDeleteModalClose}>
- <DeleteObjectModal
- actionId={deleteActionId}
- objectId={zoomedRowID}
- onClose={handleDeleteModalClose}
- onSuccess={handleDeleteSuccess}
- />
- </Modal>
+ <DeleteObjectModal
+ opened={isDeleteModalOpen}
+ actionId={deleteActionId}
+ objectId={zoomedRowID}
+ onClose={handleDeleteModalClose}
+ onSuccess={handleDeleteSuccess}
+ />
</>
);
}
diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx
index a10c2386a35..8c2818f31f1 100644
--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx
@@ -503,9 +503,11 @@ describe("ObjectDetailPanel", () => {
const modal = await screen.findByTestId("delete-object-modal");
expect(modal).toBeInTheDocument();
- expect(within(modal).getByTestId("modal-header")).toHaveTextContent(
- "Are you sure you want to delete this row?",
- );
+ expect(
+ within(modal).getByRole("heading", {
+ name: "Are you sure you want to delete this row?",
+ }),
+ ).toBeInTheDocument();
});
describe("keyboard bindings", () => {
diff --git a/frontend/test/__support__/server-mocks/pulse.ts b/frontend/test/__support__/server-mocks/pulse.ts
index 1c70e806a11..e4e902455fc 100644
--- a/frontend/test/__support__/server-mocks/pulse.ts
+++ b/frontend/test/__support__/server-mocks/pulse.ts
@@ -34,3 +34,23 @@ export const setupUnsubscribeFromPulseEndpoint = (
) => {
fetchMock.post("path:/api/pulse/unsubscribe", response);
};
+
+export const setupSubscriptionEndpoint = (
+ subscription: DashboardSubscription,
+) => {
+ fetchMock.get(`path:/api/pulse/${subscription.id}`, subscription);
+};
+
+export const setupUpdateSubscriptionEndpoint = (
+ subscription: DashboardSubscription,
+ response: object | number = subscription,
+) => {
+ fetchMock.put(`path:/api/pulse/${subscription.id}`, response);
+};
+
+export const setupUnsubscribeFromSubscriptionEndpoint = (
+ subscription: DashboardSubscription,
+ response: object | number = 204,
+) => {
+ fetchMock.delete(`path:/api/pulse/${subscription.id}/subscription`, response);
+};