Skip to content

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

Swap placement of dashboard Subscriptions action with Auto-refresh action (#78063)

Maz Ameli694e3466a654
diff --git a/e2e/support/helpers/e2e-dashboard-helpers.ts b/e2e/support/helpers/e2e-dashboard-helpers.ts
index 62a9ead12e6..fabdad72442 100644
--- a/e2e/support/helpers/e2e-dashboard-helpers.ts
+++ b/e2e/support/helpers/e2e-dashboard-helpers.ts
@@ -445,6 +445,10 @@ export function openDashboardMenu(option?: string) {
}
}
+export function toggleDashboardSubscriptionsSidebar() {
+ dashboardHeader().findByTestId("dashboard-subscriptions-button").click();
+}
+
export function assertDashboardCardTitle(index: number, title: string) {
getDashboardCard(index)
.findByTestId("legend-caption-title")
diff --git a/e2e/support/helpers/e2e-email-helpers.js b/e2e/support/helpers/e2e-email-helpers.js
index 72588db6c2f..cc7beb94c57 100644
--- a/e2e/support/helpers/e2e-email-helpers.js
+++ b/e2e/support/helpers/e2e-email-helpers.js
@@ -1,4 +1,7 @@
-import { openDashboardMenu, sidebar } from "e2e/support/helpers";
+import {
+ sidebar,
+ toggleDashboardSubscriptionsSidebar,
+} from "e2e/support/helpers";
import { WEBMAIL_CONFIG } from "../cypress_data";
@@ -85,7 +88,7 @@ export const clickSend = () => {
};
export const openAndAddEmailsToSubscriptions = (recipients) => {
- openDashboardMenu("Subscriptions");
+ toggleDashboardSubscriptionsSidebar();
sidebar().findByText("Set up a dashboard subscription").should("be.visible");
diff --git a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
index 66288e1580c..c26e69383d6 100644
--- a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
@@ -47,7 +47,7 @@ describe("issue 12578", () => {
// Without tick the dashboard header will not load
cy.tick();
- cy.findByLabelText("Auto Refresh").click();
+ H.openDashboardMenu("Auto-refresh");
H.popover().findByText("1 minute").click();
// Mock slow card request
diff --git a/e2e/test/scenarios/permissions/application-permissions.cy.spec.js b/e2e/test/scenarios/permissions/application-permissions.cy.spec.js
index fea05d85bb7..447d096f653 100644
--- a/e2e/test/scenarios/permissions/application-permissions.cy.spec.js
+++ b/e2e/test/scenarios/permissions/application-permissions.cy.spec.js
@@ -86,7 +86,7 @@ describe("scenarios > admin > permissions > application", () => {
cy.log("Set up a dashboard subscription");
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().findByText("Email this dashboard").should("exist");
cy.log("Create a question alert");
diff --git a/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js b/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js
index 50b8c98471c..ecd957843fc 100644
--- a/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js
@@ -359,7 +359,7 @@ describe("issue 22473", () => {
it("nocollection user should be able to view and unsubscribe themselves from a subscription", () => {
cy.visit(`/dashboard/${ORDERS_DASHBOARD_ID}`);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText("Email it").click();
cy.findByPlaceholderText("Enter user names or email addresses")
diff --git a/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js b/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js
index 66e381e5d1e..7d62a0eedf4 100644
--- a/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js
+++ b/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js
@@ -1113,7 +1113,7 @@ describe("admin > permissions > sandboxes (tested via the API)", () => {
cy.signInAsSandboxedUser();
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// should forward to email since that is the only one setup
H.sidebar().findByText("Email this dashboard").should("exist");
@@ -1235,7 +1235,7 @@ describe("admin > permissions > sandboxes (tested via the API)", () => {
columnAssertion: Number(USERS.sandboxed.login_attributes.attr_uid),
});
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar()
.findByPlaceholderText("Enter user names or email addresses")
diff --git a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
index 1939e6a8385..4eeb4a691f3 100644
--- a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
@@ -199,7 +199,7 @@ describe("scenarios > alert", () => {
it("should validate approved email domains for a dashboard subscription (metabase#17977)", () => {
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().within(() => {
cy.findByText("Email it").click();
@@ -231,7 +231,7 @@ describe("scenarios > alert", () => {
});
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().within(() => {
addEmailRecipient(deniedEmail);
diff --git a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
index 61db08c7ea0..499c17d1e0a 100644
--- a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
@@ -34,7 +34,7 @@ describe("issue 18009", { tags: "@external" }, () => {
it("nodata user should be able to create and receive an email subscription without errors (metabase#18009)", () => {
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar()
.findByPlaceholderText("Enter user names or email addresses")
@@ -90,7 +90,7 @@ describe("issue 18344", { tags: "@external" }, () => {
it("subscription should not include original question name when it's been renamed in the dashboard (metabase#18344)", () => {
// Send a test email subscription
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText("Email it").click();
@@ -135,7 +135,7 @@ describe("issue 18352", { tags: "@external" }, () => {
});
it("should send the card with the INT64 values (metabase#18352)", () => {
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText("Email it").click();
@@ -206,7 +206,7 @@ describe("issue 18669", { tags: "@external" }, () => {
});
it("should send a test email with non-default parameters (metabase#18669)", () => {
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText("Email it").click();
@@ -709,7 +709,7 @@ describe("issue 30314", () => {
it("should clean the new subscription form on cancel (metabase#30314)", () => {
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().within(() => {
cy.findByText("Email it").click();
@@ -782,7 +782,7 @@ describe("issue 17657", () => {
it("frontend should gracefully handle the case of a subscription without a recipient (metabase#17657)", () => {
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText(/^Emailed monthly/).click();
@@ -877,7 +877,7 @@ describe("issue 17658", { tags: "@external" }, () => {
it("should delete dashboard subscription from any collection (metabase#17658)", () => {
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText(/^Emailed monthly/).click();
@@ -1025,7 +1025,7 @@ describe("issue 49525", { tags: "@external" }, () => {
it("Subscriptions with 'Keep the data pivoted' checked should work (metabase#49525)", () => {
// Send a test email subscription
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().within(() => {
cy.findByText("Email it").click();
cy.findByPlaceholderText("Enter user names or email addresses").click();
@@ -1070,7 +1070,7 @@ describe("issue 49525", { tags: "@external" }, () => {
});
it("renders the pivot table inline in the subscription email body (UXW-4378)", () => {
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().within(() => {
cy.findByText("Email it").click();
cy.findByPlaceholderText("Enter user names or email addresses").click();
@@ -1216,7 +1216,7 @@ describe("issue 54603", () => {
// subscription list so the panel reflects the archive without a refresh.
H.saveDashboard();
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().findByText("Weekly Category Roundup").should("not.exist");
});
diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
index 4e84ca460b3..9d4310d046f 100644
--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
@@ -51,7 +51,7 @@ describe("scenarios > dashboard > subscriptions", () => {
openDashboardSubscriptions();
// The sidebar starts open after the method there, so test that clicking the icon closes it
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar().should("not.exist");
});
});
@@ -358,10 +358,7 @@ describe("scenarios > dashboard > subscriptions", () => {
});
cy.reload();
- H.dashboardHeader()
- .findByLabelText("[zz] Move, trash, and more…")
- .click();
- H.popover().findByText("[zz] Subscriptions").click();
+ H.toggleDashboardSubscriptionsSidebar();
H.sidebar()
.findByText(/\[zz\] hourly/)
.click();
@@ -597,8 +594,8 @@ describe("scenarios > dashboard > subscriptions", () => {
it("should allow non-admin users to create subscriptions", () => {
cy.signInAsNormalUser();
H.visitDashboard(ORDERS_DASHBOARD_ID);
- H.openDashboardMenu();
- H.popover().findByText("Subscriptions").should("be.visible");
+ H.toggleDashboardSubscriptionsSidebar();
+ H.sidebar().should("be.visible");
});
it("should persist the immutable Slack channel_id alongside the channel name", () => {
@@ -935,7 +932,7 @@ describe("scenarios > dashboard > subscriptions", () => {
function openDashboardSubscriptions(dashboard_id = ORDERS_DASHBOARD_ID) {
// Orders in a dashboard
H.visitDashboard(dashboard_id);
- H.openDashboardMenu("Subscriptions");
+ H.toggleDashboardSubscriptionsSidebar();
}
function assignRecipient({
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx
index 997f0bf4e3f..8314982c378 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx
@@ -1,6 +1,7 @@
import userEvent from "@testing-library/user-event";
import { setupBookmarksEndpoints } from "__support__/server-mocks";
+import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen, within } from "__support__/ui";
import type { DashboardActionKey } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/types";
@@ -71,6 +72,10 @@ const DASHBOARD_EXPECTED_DATA_MAP: Record<
icon: "share",
tooltip: "Share",
},
+ [DASHBOARD_ACTION.DASHBOARD_SUBSCRIPTIONS_BUTTON]: {
+ icon: "subscription",
+ tooltip: "Subscriptions",
+ },
[DASHBOARD_ACTION.REFRESH_WIDGET]: {
icon: "clock",
tooltip: "Auto-refresh",
@@ -88,6 +93,10 @@ const DASHBOARD_EXPECTED_DATA_MAP: Record<
icon: "info",
tooltip: "More info",
},
+ [DASHBOARD_ACTION.AUTO_REFRESH_INDICATOR]: {
+ icon: "clock",
+ tooltip: "Auto-refresh",
+ },
[DASHBOARD_ACTION.DASHBOARD_ACTION_MENU]: {
icon: "ellipsis",
tooltip: "Move, trash, and more…",
@@ -111,6 +120,9 @@ const setup = ({
isPublic,
isAnalyticsDashboard,
isAdmin = false,
+ hasEmailSetup = true,
+ hasSlackSetup = true,
+ refreshPeriod = null,
}: Partial<{
isEditing: boolean;
hasModelActionsEnabled: boolean;
@@ -118,8 +130,15 @@ const setup = ({
isPublic: boolean;
isAnalyticsDashboard: boolean;
isAdmin: boolean;
+ hasEmailSetup: boolean;
+ hasSlackSetup: boolean;
+ refreshPeriod: number | null;
}>) => {
setupBookmarksEndpoints([]);
+ setupNotificationChannelsEndpoints({
+ email: { configured: hasEmailSetup },
+ slack: { configured: hasSlackSetup },
+ });
const MOCK_DATABASE = createMockDatabase({
settings: {
@@ -154,7 +173,7 @@ const setup = ({
path="*"
element={
<MockDashboardContext
- refreshPeriod={null}
+ refreshPeriod={refreshPeriod}
onRefreshPeriodChange={jest.fn()}
setRefreshElapsedHook={jest.fn()}
isFullscreen={isFullscreen}
@@ -301,7 +320,7 @@ describe("DashboardHeaderButtonRow", () => {
expectedButtons: [
DASHBOARD_ACTION.EDIT_DASHBOARD,
DASHBOARD_ACTION.DASHBOARD_SHARING,
- DASHBOARD_ACTION.REFRESH_WIDGET,
+ DASHBOARD_ACTION.DASHBOARD_SUBSCRIPTIONS_BUTTON,
DASHBOARD_ACTION.DASHBOARD_HEADER_ACTION_DIVIDER,
DASHBOARD_ACTION.DASHBOARD_BOOKMARK,
DASHBOARD_ACTION.DASHBOARD_INFO,
@@ -336,6 +355,42 @@ describe("DashboardHeaderButtonRow", () => {
expectedButtons: [DASHBOARD_ACTION.FULLSCREEN_TOGGLE],
});
});
+
+ it("should not show the auto-refresh indicator when auto-refresh is off", () => {
+ setup({ isEditing: false, isAdmin: true, refreshPeriod: null });
+
+ const buttons = screen.getAllByTestId("dashboard-header-row-button");
+ const buttonKeys = buttons.map((button) =>
+ button.getAttribute("data-element-id"),
+ );
+ expect(buttonKeys).not.toContain(DASHBOARD_ACTION.AUTO_REFRESH_INDICATOR);
+ });
+
+ it("should show the auto-refresh indicator to the left of the overflow menu when auto-refresh is on", async () => {
+ setup({ isEditing: false, isAdmin: true, refreshPeriod: 60 });
+
+ await expectButtonsToStrictMatchHeader({
+ expectedButtons: [
+ DASHBOARD_ACTION.EDIT_DASHBOARD,
+ DASHBOARD_ACTION.DASHBOARD_SHARING,
+ DASHBOARD_ACTION.DASHBOARD_SUBSCRIPTIONS_BUTTON,
+ DASHBOARD_ACTION.DASHBOARD_HEADER_ACTION_DIVIDER,
+ DASHBOARD_ACTION.DASHBOARD_BOOKMARK,
+ DASHBOARD_ACTION.DASHBOARD_INFO,
+ DASHBOARD_ACTION.AUTO_REFRESH_INDICATOR,
+ DASHBOARD_ACTION.DASHBOARD_ACTION_MENU,
+ ],
+ checkLength: true,
+ });
+ });
+
+ it("should show the auto-refresh indicator in fullscreen when auto-refresh is on", async () => {
+ setup({ isEditing: false, isFullscreen: true, refreshPeriod: 60 });
+
+ await expectButtonsToExistInHeader({
+ expectedButtons: [DASHBOARD_ACTION.AUTO_REFRESH_INDICATOR],
+ });
+ });
});
describe("when viewing analytics dashboard", () => {
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/action-buttons.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/action-buttons.tsx
index 107853a12f4..39fd7d3bee0 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/action-buttons.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/action-buttons.tsx
@@ -13,6 +13,7 @@ import {
CopyAnalyticsDashboardButton,
DashboardActionMenu,
DashboardInfoButton,
+ DashboardSubscriptionsButton,
EditDashboardButton,
ExportAsPdfButton,
FullscreenAnalyticsDashboard,
@@ -70,6 +71,10 @@ export const dashboardActionButtons: Record<
component: DashboardSharingMenu,
enabled: ({ isEditing }) => !isEditing,
},
+ [DASHBOARD_ACTION.DASHBOARD_SUBSCRIPTIONS_BUTTON]: {
+ component: DashboardSubscriptionsButton,
+ enabled: ({ isEditing, dashboard }) => !isEditing && !dashboard?.archived,
+ },
[DASHBOARD_ACTION.REFRESH_WIDGET]: {
component: () => <RefreshWidget />,
enabled: ({ dashboard, isEditing }) => !isEditing && !dashboard?.archived,
@@ -86,6 +91,14 @@ export const dashboardActionButtons: Record<
component: () => <DashboardInfoButton />,
enabled: ({ isEditing }) => !isEditing,
},
+ [DASHBOARD_ACTION.AUTO_REFRESH_INDICATOR]: {
+ component: () => <RefreshWidget />,
+ enabled: ({ isEditing, dashboard, refreshPeriod }) =>
+ !isEditing &&
+ !dashboard?.archived &&
+ refreshPeriod != null &&
+ refreshPeriod > 0,
+ },
[DASHBOARD_ACTION.DASHBOARD_ACTION_MENU]: {
component: ({
canResetFilters,
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants.ts b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants.ts
index c7ca7c17570..565f1191f53 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants.ts
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants.ts
@@ -21,10 +21,12 @@ export const DASHBOARD_VIEW_ACTIONS = [
DASHBOARD_ACTION.COPY_ANALYTICS_DASHBOARD,
DASHBOARD_ACTION.EDIT_DASHBOARD,
DASHBOARD_ACTION.DASHBOARD_SHARING,
- ...DASHBOARD_DISPLAY_ACTIONS,
+ DASHBOARD_ACTION.DASHBOARD_SUBSCRIPTIONS_BUTTON,
+ DASHBOARD_ACTION.FULLSCREEN_TOGGLE,
DASHBOARD_ACTION.DASHBOARD_HEADER_ACTION_DIVIDER,
DASHBOARD_ACTION.DASHBOARD_BOOKMARK,
DASHBOARD_ACTION.DASHBOARD_INFO,
+ DASHBOARD_ACTION.AUTO_REFRESH_INDICATOR,
DASHBOARD_ACTION.DASHBOARD_ACTION_MENU,
DASHBOARD_ACTION.FULLSCREEN_ANALYTICS_DASHBOARD,
];
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys.tsx
index c8a471e5e8f..69757ed0878 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/dashboard-action-keys.tsx
@@ -9,11 +9,13 @@ export const DASHBOARD_ACTION = {
COPY_ANALYTICS_DASHBOARD: "COPY_ANALYTICS_DASHBOARD",
EDIT_DASHBOARD: "EDIT_DASHBOARD",
DASHBOARD_SHARING: "DASHBOARD_SHARING",
+ DASHBOARD_SUBSCRIPTIONS_BUTTON: "DASHBOARD_SUBSCRIPTIONS_BUTTON",
REFRESH_WIDGET: "REFRESH_WIDGET",
FULLSCREEN_TOGGLE: "FULLSCREEN_TOGGLE",
DASHBOARD_HEADER_ACTION_DIVIDER: "DASHBOARD_HEADER_ACTION_DIVIDER",
DASHBOARD_BOOKMARK: "DASHBOARD_BOOKMARK",
DASHBOARD_INFO: "DASHBOARD_INFO",
+ AUTO_REFRESH_INDICATOR: "AUTO_REFRESH_INDICATOR",
DASHBOARD_ACTION_MENU: "DASHBOARD_ACTION_MENU",
FULLSCREEN_ANALYTICS_DASHBOARD: "FULLSCREEN_ANALYTICS_DASHBOARD",
DOWNLOAD_PDF: "DOWNLOAD_PDF",
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
index 9ab4e4dbd5d..5fea327d250 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
@@ -2,17 +2,18 @@ import { type MouseEvent, forwardRef, useState } from "react";
import { c, t } from "ttag";
import { ToolbarButton } from "metabase/common/components/ToolbarButton";
-import { setSharing as setDashboardSubscriptionSidebarOpen } from "metabase/dashboard/actions";
import { useDashboardContext } from "metabase/dashboard/context/context";
import { useRefreshDashboard } from "metabase/dashboard/hooks";
-import { getIsSharing as getIsDashboardSubscriptionSidebarOpen } from "metabase/dashboard/selectors";
-import { DashboardSubscriptionMenuItem } from "metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
import { PLUGIN_CACHING, PLUGIN_MODERATION } from "metabase/plugins";
-import { useDispatch, useSelector } from "metabase/redux";
import { Link, type LinkProps, useRouter } from "metabase/router";
import { Icon, Menu } from "metabase/ui";
+import {
+ AutoRefreshMenuItem,
+ AutoRefreshMenuOptions,
+} from "../../RefreshWidget";
+
type DashboardActionMenuProps = {
canResetFilters: boolean;
onResetFilters: () => void;
@@ -40,7 +41,14 @@ const DashboardActionMenuInner = ({
const { dashboard, isFullscreen, onFullscreenChange, onChangeLocation } =
useDashboardContext();
const [opened, setOpened] = useState(false);
- const dispatch = useDispatch();
+ const [showAutoRefreshOptions, setShowAutoRefreshOptions] = useState(false);
+
+ const handleOpenChange = (isOpen: boolean) => {
+ setOpened(isOpen);
+ if (!isOpen) {
+ setShowAutoRefreshOptions(false);
+ }
+ };
const { refreshDashboard } = useRefreshDashboard({
dashboardId: dashboard?.id ?? null,
@@ -52,15 +60,6 @@ const DashboardActionMenuInner = ({
refreshDashboard,
);
- const isDashboardSubscriptionSidebarOpen = useSelector(
- getIsDashboardSubscriptionSidebarOpen,
- );
-
- const toggleSubscriptionSidebar = () =>
- dispatch(
- setDashboardSubscriptionSidebarOpen(!isDashboardSubscriptionSidebarOpen),
- );
-
// solely for the dependency list below, so we don't ever have an undefined
const pathname = location?.pathname ?? "";
useRegisterShortcut(
@@ -85,7 +84,7 @@ const DashboardActionMenuInner = ({
dashboard.can_set_cache_policy && PLUGIN_CACHING.isGranularCachingEnabled();
return (
- <Menu position="bottom-end" opened={opened} onChange={setOpened}>
+ <Menu position="bottom-end" opened={opened} onChange={handleOpenChange}>
<Menu.Target>
<div>
<ToolbarButton
@@ -96,66 +95,71 @@ const DashboardActionMenuInner = ({
</div>
</Menu.Target>
<Menu.Dropdown>
- {canResetFilters && (
- <Menu.Item
- leftSection={<Icon name="revert" />}
- onClick={onResetFilters}
- >
- {t`Reset all filters`}
- </Menu.Item>
- )}
-
- <DashboardSubscriptionMenuItem
- dashboard={dashboard}
- onClick={toggleSubscriptionSidebar}
- />
-
- <Menu.Item
- leftSection={<Icon name="expand" />}
- onClick={(e: MouseEvent) =>
- onFullscreenChange(!isFullscreen, !e.altKey)
- }
- >
- {t`Enter fullscreen`}
- </Menu.Item>
-
- {(canEdit || canConfigureCaching) && (
- <Menu.Item
- leftSection={<Icon name="gear" />}
- onClick={openSettingsSidebar}
- >
- {t`Edit settings`}
- </Menu.Item>
- )}
-
- {canEdit && moderationItems}
-
- {canEdit && (
+ {showAutoRefreshOptions ? (
+ <AutoRefreshMenuOptions onSelect={() => handleOpenChange(false)} />
+ ) : (
<>
- <Menu.Divider />
+ {canResetFilters && (
+ <Menu.Item
+ leftSection={<Icon name="revert" />}
+ onClick={onResetFilters}
+ >
+ {t`Reset all filters`}
+ </Menu.Item>
+ )}
<Menu.Item
- leftSection={<Icon name="move" />}
- component={ForwardRefLink}
- to={`${location?.pathname}/move`}
- >{c("A verb, not a noun").t`Move`}</Menu.Item>
- </>
- )}
+ leftSection={<Icon name="expand" />}
+ onClick={(e: MouseEvent) =>
+ onFullscreenChange(!isFullscreen, !e.altKey)
+ }
+ >
+ {t`Enter fullscreen`}
+ </Menu.Item>
+
+ <AutoRefreshMenuItem
+ onClick={() => setShowAutoRefreshOptions(true)}
+ />
+
+ {(canEdit || canConfigureCaching) && (
+ <Menu.Item
+ leftSection={<Icon name="gear" />}
+ onClick={openSettingsSidebar}
+ >
+ {t`Edit settings`}
+ </Menu.Item>
+ )}
+
+ {canEdit && moderationItems}
+
+ {canEdit && (
+ <>
+ <Menu.Divider />
+
+ <Menu.Item
+ leftSection={<Icon name="move" />}
+ component={ForwardRefLink}
+ to={`${location?.pathname}/move`}
+ >{c("A verb, not a noun").t`Move`}</Menu.Item>
+ </>
+ )}
- <Menu.Item
- leftSection={<Icon name="clone" />}
- component={ForwardRefLink}
- to={`${location?.pathname}/copy`}
- >{c("A verb, not a noun").t`Duplicate`}</Menu.Item>
-
- {canEdit && (
- <>
- <Menu.Divider />
<Menu.Item
- leftSection={<Icon name="trash" />}
+ leftSection={<Icon name="clone" />}
component={ForwardRefLink}
- to={`${location?.pathname}/archive`}
- >{t`Move to trash`}</Menu.Item>
+ to={`${location?.pathname}/copy`}
+ >{c("A verb, not a noun").t`Duplicate`}</Menu.Item>
+
+ {canEdit && (
+ <>
+ <Menu.Divider />
+ <Menu.Item
+ leftSection={<Icon name="trash" />}
+ component={ForwardRefLink}
+ to={`${location?.pathname}/archive`}
+ >{t`Move to trash`}</Menu.Item>
+ </>
+ )}
</>
)}
</Menu.Dropdown>
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.unit.spec.tsx
index 1833a7976c1..c4fd20ffc65 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.unit.spec.tsx
@@ -5,7 +5,6 @@ import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pul
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen } from "__support__/ui";
import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
-import { getIsSharing } from "metabase/dashboard/selectors";
import { createMockDashboardState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import {
@@ -65,6 +64,9 @@ const setup = ({
dashboard={dashboard}
isFullscreen={false}
onFullscreenChange={jest.fn()}
+ refreshPeriod={null}
+ onRefreshPeriodChange={jest.fn()}
+ setRefreshElapsedHook={jest.fn()}
parameterQueryParams={{}}
>
<DashboardActionMenu
@@ -126,98 +128,32 @@ const openMenu = () => {
};
describe("DashboardActionMenu", () => {
- describe("dashboard subscriptions", () => {
- describe("admins", () => {
- it("should show the 'Subscriptions' menu item if email and slack are not setup", async () => {
- setup({ isAdmin: true, hasEmailSetup: false, hasSlackSetup: false });
- await openMenu();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- });
-
- it("should show the 'Subscriptions' menu item if email and slack are setup", async () => {
- setup({ isAdmin: true, hasEmailSetup: true, hasSlackSetup: true });
- await openMenu();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- });
-
- it("should toggle the subscriptions sidebar on click", async () => {
- const { store } = setup({ isAdmin: true });
- expect(getIsSharing(store.getState())).toBe(false);
- await openMenu();
- await userEvent.click(await screen.findByText("Subscriptions"));
- expect(getIsSharing(store.getState())).toBe(true);
- await openMenu();
- await userEvent.click(await screen.findByText("Subscriptions"));
- expect(getIsSharing(store.getState())).toBe(false);
- });
-
- it("should not show the subscriptions menu item if there are no data cards", async () => {
- setup({
- isAdmin: true,
- dashboard: {
- dashcards: [
- createMockDashboardCard({
- card: createMockCard({ display: "text" }),
- }),
- ],
- },
- });
- await openMenu();
- expect(screen.queryByText("Subscriptions")).not.toBeInTheDocument();
- });
- });
-
- describe("non-admins", () => {
- it("should show 'Subscriptions' option when email is set up, but slack is not setup", async () => {
- setup({ isAdmin: false, hasEmailSetup: true, hasSlackSetup: false });
- await openMenu();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- });
-
- it("should show 'Subscriptions' option when email is not set up, but slack is setup", async () => {
- setup({ isAdmin: false, hasEmailSetup: false, hasSlackSetup: true });
- await openMenu();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- });
-
- it("should not show the subscriptions menu item if there are no data cards", async () => {
- setup({
- isAdmin: false,
- dashboard: {
- dashcards: [
- createMockDashboardCard({
- card: createMockCard({ display: "heading" }),
- }),
- ],
- },
- });
- await openMenu();
- expect(screen.queryByText("Subscriptions")).not.toBeInTheDocument();
- });
- });
-
- describe("enterprise", () => {
- it('should show the "Subscriptions" menu item to non-admins with subscription permissions', async () => {
- setup({
- canManageSubscriptions: true,
- hasEmailSetup: true,
- isEnterprise: true,
- isAdmin: false,
- });
- await openMenu();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- });
+ it("should show the 'Enter fullscreen' and 'Auto-refresh' items", async () => {
+ setup({ isAdmin: true });
+ await openMenu();
+
+ expect(await screen.findByText("Enter fullscreen")).toBeInTheDocument();
+ expect(
+ screen.getByTestId("dashboard-auto-refresh-menu-item"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Auto-refresh")).toBeInTheDocument();
+ expect(screen.getByText("Duplicate")).toBeInTheDocument();
+ });
- it('should not show the "Subscriptions" menu item to non-admins without subscription permissions', async () => {
- setup({
- canManageSubscriptions: false,
- hasEmailSetup: true,
- isEnterprise: true,
- isAdmin: false,
- });
- await openMenu();
- expect(screen.queryByText("Subscriptions")).not.toBeInTheDocument();
- });
- });
+ it("should drill into the auto-refresh options when the trigger is clicked", async () => {
+ setup({ isAdmin: true });
+ await openMenu();
+
+ await userEvent.click(
+ screen.getByTestId("dashboard-auto-refresh-menu-item"),
+ );
+
+ // The main menu items are replaced by the auto-refresh options
+ expect(screen.getByText("Auto Refresh")).toBeInTheDocument();
+ expect(screen.getByText("Off")).toBeInTheDocument();
+ expect(screen.getByText("1 minute")).toBeInTheDocument();
+ expect(screen.getByText("60 minutes")).toBeInTheDocument();
+ expect(screen.queryByText("Duplicate")).not.toBeInTheDocument();
+ expect(screen.queryByText("Enter fullscreen")).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx
new file mode 100644
index 00000000000..c95759f7a2b
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx
@@ -0,0 +1,57 @@
+import { t } from "ttag";
+
+import { useGetChannelInfoQuery } from "metabase/api";
+import { ToolbarButton } from "metabase/common/components/ToolbarButton";
+import { toggleSharing } from "metabase/dashboard/actions";
+import { useDashboardContext } from "metabase/dashboard/context";
+import { getIsSharing } from "metabase/dashboard/selectors";
+import { useDispatch, useSelector } from "metabase/redux";
+import {
+ canManageSubscriptions as canManageSubscriptionsSelector,
+ getUserIsAdmin,
+} from "metabase/selectors/user";
+
+export const DashboardSubscriptionsButton = () => {
+ const { dashboard } = useDashboardContext();
+ const dispatch = useDispatch();
+
+ const isAdmin = useSelector(getUserIsAdmin);
+ const canManageSubscriptions = useSelector(canManageSubscriptionsSelector);
+ const isSharing = useSelector(getIsSharing);
+
+ // Skip the request entirely when the user can't manage subscriptions so we
+ // don't fetch channel info unnecessarily on dashboard load (EMB-967).
+ const { data: channelInfo } = useGetChannelInfoQuery(undefined, {
+ skip: !canManageSubscriptions,
+ });
+ const hasEmailSetup = !!channelInfo?.channels?.email?.configured;
+ const hasSlackSetup = !!channelInfo?.channels?.slack?.configured;
+
+ // dashcardData only contains question cards, text ones don't appear here
+ const hasDataCards = dashboard?.dashcards?.some(
+ (dashCard) => !["text", "heading"].includes(dashCard.card.display),
+ );
+
+ const hasAnySubscriptionChannel = hasEmailSetup || hasSlackSetup;
+
+ if (!dashboard || !canManageSubscriptions || !hasDataCards) {
+ return null;
+ }
+
+ // Hide subscriptions from non-admins when the instance has no email or Slack
+ // channel configured, since only admins can set those channels up.
+ if (!isAdmin && !hasAnySubscriptionChannel) {
+ return null;
+ }
+
+ return (
+ <ToolbarButton
+ icon="subscription"
+ aria-label={t`Subscriptions`}
+ tooltipLabel={t`Subscriptions`}
+ isActive={isSharing}
+ onClick={() => dispatch(toggleSharing())}
+ data-testid="dashboard-subscriptions-button"
+ />
+ );
+};
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.unit.spec.tsx
new file mode 100644
index 00000000000..d3e69fd0a8e
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.unit.spec.tsx
@@ -0,0 +1,249 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
+import { getIsSharing } from "metabase/dashboard/selectors";
+import { createMockDashboardState } from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
+import {
+ createMockCard,
+ createMockDashboard,
+ createMockDashboardCard,
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { DashboardSubscriptionsButton } from "./DashboardSubscriptionsButton";
+
+const DASHCARD = createMockDashboardCard({
+ card: createMockCard({ display: "pie" }),
+});
+
+const setup = ({
+ isAdmin = false,
+ hasEmailSetup = false,
+ hasSlackSetup = false,
+ canManageSubscriptions,
+ isEnterprise = false,
+ dashboard: dashboardOverrides = {},
+}: {
+ isAdmin?: boolean;
+ hasEmailSetup?: boolean;
+ hasSlackSetup?: boolean;
+ canManageSubscriptions?: boolean;
+ isEnterprise?: boolean;
+ dashboard?: Partial<ReturnType<typeof createMockDashboard>>;
+} = {}) => {
+ const dashboard = createMockDashboard({
+ dashcards: [DASHCARD],
+ ...dashboardOverrides,
+ });
+
+ if (isEnterprise) {
+ setupEnterpriseOnlyPlugin("application_permissions");
+ }
+
+ const currentUser = createMockUser({
+ is_superuser: isAdmin,
+ });
+
+ setupNotificationChannelsEndpoints({
+ email: { configured: hasEmailSetup },
+ slack: { configured: hasSlackSetup },
+ });
+
+ const { store } = renderWithProviders(
+ <Route
+ path="*"
+ element={
+ <MockDashboardContext
+ dashboardId={dashboard.id}
+ dashboard={dashboard}
+ isFullscreen={false}
+ onFullscreenChange={jest.fn()}
+ parameterQueryParams={{}}
+ >
+ <DashboardSubscriptionsButton />
+ </MockDashboardContext>
+ }
+ />,
+ {
+ withRouter: true,
+ storeInitialState: {
+ currentUser: isEnterprise
+ ? {
+ ...currentUser,
+ permissions: {
+ can_access_subscription: canManageSubscriptions ?? false,
+ },
+ }
+ : currentUser,
+ ...(isEnterprise && {
+ settings: mockSettings(
+ createMockSettings({
+ "token-features": createMockTokenFeatures({
+ advanced_permissions: true,
+ }),
+ }),
+ ),
+ }),
+ dashboard: createMockDashboardState({
+ dashboardId: dashboard.id,
+ dashboards: {
+ [dashboard.id]: {
+ ...dashboard,
+ dashcards: dashboard.dashcards.map((c) => c.id),
+ },
+ },
+ dashcards: {
+ [DASHCARD.id]: {
+ ...DASHCARD,
+ isDirty: false,
+ isRemoved: false,
+ },
+ },
+ }),
+ },
+ },
+ );
+
+ return { store };
+};
+
+const getButton = () => screen.getByTestId("dashboard-subscriptions-button");
+
+describe("DashboardSubscriptionsButton", () => {
+ describe("admins", () => {
+ it("should show an enabled button if email and slack are not setup", async () => {
+ setup({ isAdmin: true, hasEmailSetup: false, hasSlackSetup: false });
+
+ const button = await screen.findByTestId(
+ "dashboard-subscriptions-button",
+ );
+ expect(button).toBeEnabled();
+
+ await userEvent.hover(button);
+ expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
+ });
+
+ it("should show an enabled button if email and slack are setup", async () => {
+ setup({ isAdmin: true, hasEmailSetup: true, hasSlackSetup: true });
+ expect(
+ await screen.findByTestId("dashboard-subscriptions-button"),
+ ).toBeEnabled();
+ });
+
+ it("should toggle the subscriptions sidebar on click", async () => {
+ const { store } = setup({ isAdmin: true });
+ expect(getIsSharing(store.getState())).toBe(false);
+
+ await userEvent.click(getButton());
+ expect(getIsSharing(store.getState())).toBe(true);
+
+ await userEvent.click(getButton());
+ expect(getIsSharing(store.getState())).toBe(false);
+ });
+
+ it("should not render if there are no data cards", () => {
+ setup({
+ isAdmin: true,
+ dashboard: {
+ dashcards: [
+ createMockDashboardCard({
+ card: createMockCard({ display: "text" }),
+ }),
+ ],
+ },
+ });
+ expect(
+ screen.queryByTestId("dashboard-subscriptions-button"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("non-admins", () => {
+ it("should show an enabled button when email is set up", async () => {
+ setup({ isAdmin: false, hasEmailSetup: true, hasSlackSetup: false });
+ await waitFor(() => expect(getButton()).toBeEnabled());
+ });
+
+ it("should show an enabled button when slack is set up", async () => {
+ setup({ isAdmin: false, hasEmailSetup: false, hasSlackSetup: true });
+ await waitFor(() => expect(getButton()).toBeEnabled());
+ });
+
+ it("should not render when neither email nor slack is set up", async () => {
+ setup({ isAdmin: false, hasEmailSetup: false, hasSlackSetup: false });
+
+ // Wait for channel info to load so we don't assert on the pre-fetch state
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("dashboard-subscriptions-button"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("should not render if there are no data cards", () => {
+ setup({
+ isAdmin: false,
+ hasEmailSetup: true,
+ dashboard: {
+ dashcards: [
+ createMockDashboardCard({
+ card: createMockCard({ display: "heading" }),
+ }),
+ ],
+ },
+ });
+ expect(
+ screen.queryByTestId("dashboard-subscriptions-button"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("enterprise", () => {
+ it("should render for non-admins with subscription permissions when a channel is set up", async () => {
+ setup({
+ canManageSubscriptions: true,
+ hasEmailSetup: true,
+ isEnterprise: true,
+ isAdmin: false,
+ });
+ expect(
+ await screen.findByTestId("dashboard-subscriptions-button"),
+ ).toBeInTheDocument();
+ });
+
+ it("should not render for non-admins with subscription permissions when no channel is set up", async () => {
+ setup({
+ canManageSubscriptions: true,
+ hasEmailSetup: false,
+ hasSlackSetup: false,
+ isEnterprise: true,
+ isAdmin: false,
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("dashboard-subscriptions-button"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("should not render for non-admins without subscription permissions", () => {
+ setup({
+ canManageSubscriptions: false,
+ hasEmailSetup: true,
+ isEnterprise: true,
+ isAdmin: false,
+ });
+ expect(
+ screen.queryByTestId("dashboard-subscriptions-button"),
+ ).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/index.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/index.tsx
index 07ec1f95ab2..3b9c5bec155 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/index.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/index.tsx
@@ -7,6 +7,7 @@ export * from "./CancelEditButton";
export * from "./CopyAnalyticsDashboardButton";
export * from "./DashboardActionMenu";
export * from "./DashboardInfoButton";
+export * from "./DashboardSubscriptionsButton";
export * from "./EditDashboardButton";
export * from "./FullscreenAnalyticsDashboard";
export * from "./SaveEditButton";
diff --git a/frontend/src/metabase/dashboard/components/RefreshWidget/AutoRefreshMenuItem.tsx b/frontend/src/metabase/dashboard/components/RefreshWidget/AutoRefreshMenuItem.tsx
new file mode 100644
index 00000000000..4abfc5a69c1
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/RefreshWidget/AutoRefreshMenuItem.tsx
@@ -0,0 +1,75 @@
+import { t } from "ttag";
+
+import { useDashboardContext } from "metabase/dashboard/context";
+import { Box, Icon, Menu } from "metabase/ui";
+
+import { AUTO_REFRESH_OPTIONS } from "./options";
+
+type AutoRefreshMenuItemProps = {
+ onClick: () => void;
+};
+
+/**
+ * Trigger row shown in the dashboard overflow menu. Clicking it drills into the
+ * auto-refresh options (see {@link AutoRefreshMenuOptions}) instead of flying
+ * out a submenu on hover.
+ */
+export const AutoRefreshMenuItem = ({ onClick }: AutoRefreshMenuItemProps) => (
+ <Menu.Item
+ leftSection={<Icon name="clock" />}
+ rightSection={<Icon name="chevronright" />}
+ closeMenuOnClick={false}
+ onClick={onClick}
+ data-testid="dashboard-auto-refresh-menu-item"
+ >
+ {t`Auto-refresh`}
+ </Menu.Item>
+);
+
+type AutoRefreshMenuOptionsProps = {
+ onSelect: () => void;
+};
+
+/**
+ * The list of auto-refresh intervals that replaces the overflow menu content
+ * once the {@link AutoRefreshMenuItem} trigger is clicked. Mirrors the popover
+ * shown when clicking the auto-refresh countdown indicator.
+ */
+export const AutoRefreshMenuOptions = ({
+ onSelect,
+}: AutoRefreshMenuOptionsProps) => {
+ const { refreshPeriod, onRefreshPeriodChange } = useDashboardContext();
+
+ return (
+ <>
+ <Box
+ fw="bold"
+ fz="sm"
+ tt="uppercase"
+ mb="md"
+ ml="sm"
+ c="text-secondary"
+ >{t`Auto Refresh`}</Box>
+ {AUTO_REFRESH_OPTIONS.map((option) => (
+ <Menu.Item
+ key={String(option.period)}
+ leftSection={
+ <Icon
+ name="check"
+ style={{
+ visibility:
+ option.period === refreshPeriod ? "visible" : "hidden",
+ }}
+ />
+ }
+ onClick={() => {
+ onRefreshPeriodChange(option.period);
+ onSelect();
+ }}
+ >
+ {option.name}
+ </Menu.Item>
+ ))}
+ </>
+ );
+};
diff --git a/frontend/src/metabase/dashboard/components/RefreshWidget/AutoRefreshMenuItem.unit.spec.tsx b/frontend/src/metabase/dashboard/components/RefreshWidget/AutoRefreshMenuItem.unit.spec.tsx
new file mode 100644
index 00000000000..81ec80c435a
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/RefreshWidget/AutoRefreshMenuItem.unit.spec.tsx
@@ -0,0 +1,121 @@
+import userEvent from "@testing-library/user-event";
+import type { ReactNode } from "react";
+
+import { renderWithProviders, screen, within } from "__support__/ui";
+import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
+import { createMockDashboardState } from "metabase/redux/store/mocks";
+import { Menu } from "metabase/ui";
+import { createMockDashboard } from "metabase-types/api/mocks";
+
+import {
+ AutoRefreshMenuItem,
+ AutoRefreshMenuOptions,
+} from "./AutoRefreshMenuItem";
+
+const setup = ({
+ children,
+ refreshPeriod = null,
+ onRefreshPeriodChange = jest.fn(),
+}: {
+ children: ReactNode;
+ refreshPeriod?: number | null;
+ onRefreshPeriodChange?: jest.Mock;
+}) => {
+ const dashboard = createMockDashboard();
+
+ renderWithProviders(
+ <Menu opened>
+ <Menu.Dropdown>
+ <MockDashboardContext
+ dashboardId={dashboard.id}
+ dashboard={dashboard}
+ refreshPeriod={refreshPeriod}
+ onRefreshPeriodChange={onRefreshPeriodChange}
+ setRefreshElapsedHook={jest.fn()}
+ isFullscreen={false}
+ onFullscreenChange={jest.fn()}
+ >
+ {children}
+ </MockDashboardContext>
+ </Menu.Dropdown>
+ </Menu>,
+ {
+ storeInitialState: {
+ dashboard: createMockDashboardState({
+ dashboardId: dashboard.id,
+ dashboards: {
+ [dashboard.id]: { ...dashboard, dashcards: [] },
+ },
+ }),
+ },
+ },
+ );
+};
+
+describe("AutoRefreshMenuItem", () => {
+ it("should render the trigger with a right chevron and call onClick", async () => {
+ const onClick = jest.fn();
+ setup({ children: <AutoRefreshMenuItem onClick={onClick} /> });
+
+ const trigger = screen.getByTestId("dashboard-auto-refresh-menu-item");
+ expect(trigger).toBeInTheDocument();
+ expect(screen.getByText("Auto-refresh")).toBeInTheDocument();
+ expect(screen.getByLabelText("chevronright icon")).toBeInTheDocument();
+
+ await userEvent.click(trigger);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("AutoRefreshMenuOptions", () => {
+ it("should render the 'Auto Refresh' heading and interval options", () => {
+ setup({ children: <AutoRefreshMenuOptions onSelect={jest.fn()} /> });
+
+ expect(screen.getByText("Auto Refresh")).toBeInTheDocument();
+ expect(screen.getByText("Off")).toBeInTheDocument();
+ expect(screen.getByText("1 minute")).toBeInTheDocument();
+ expect(screen.getByText("60 minutes")).toBeInTheDocument();
+ });
+
+ it("should not render a divider or a clickable back heading", () => {
+ setup({ children: <AutoRefreshMenuOptions onSelect={jest.fn()} /> });
+
+ // The all-caps heading is a plain, non-interactive label (not a menu item)
+ expect(screen.getByText("Auto Refresh")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("menuitem", { name: /Auto Refresh/i }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole("separator")).not.toBeInTheDocument();
+ });
+
+ it("should apply the selected period and call onSelect", async () => {
+ const onSelect = jest.fn();
+ const onRefreshPeriodChange = jest.fn();
+ setup({
+ children: <AutoRefreshMenuOptions onSelect={onSelect} />,
+ onRefreshPeriodChange,
+ });
+
+ await userEvent.click(screen.getByText("5 minutes"));
+
+ expect(onRefreshPeriodChange).toHaveBeenCalledWith(300);
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
+
+ it("should mark the currently selected period", () => {
+ setup({
+ children: <AutoRefreshMenuOptions onSelect={jest.fn()} />,
+ refreshPeriod: 60,
+ });
+
+ const selectedOption = screen.getByRole("menuitem", { name: /1 minute/ });
+ expect(within(selectedOption).getByLabelText("check icon")).toHaveStyle({
+ visibility: "visible",
+ });
+
+ const unselectedOption = screen.getByRole("menuitem", { name: /Off/ });
+ expect(within(unselectedOption).getByLabelText("check icon")).toHaveStyle({
+ visibility: "hidden",
+ });
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/RefreshWidget/RefreshWidget.tsx b/frontend/src/metabase/dashboard/components/RefreshWidget/RefreshWidget.tsx
index b3ef7c274db..da0bf183aad 100644
--- a/frontend/src/metabase/dashboard/components/RefreshWidget/RefreshWidget.tsx
+++ b/frontend/src/metabase/dashboard/components/RefreshWidget/RefreshWidget.tsx
@@ -6,53 +6,7 @@ import { type ActionIconProps, Box, Popover } from "metabase/ui";
import { RefreshOption } from "./RefreshOption";
import { RefreshWidgetTarget } from "./RefreshWidgetTarget";
-
-const toSeconds = (minutes: number) => minutes * 60;
-
-const OPTIONS = [
- {
- get name() {
- return t`Off`;
- },
- period: null,
- },
- {
- get name() {
- return t`1 minute`;
- },
- period: toSeconds(1),
- },
- {
- get name() {
- return t`5 minutes`;
- },
- period: toSeconds(5),
- },
- {
- get name() {
- return t`10 minutes`;
- },
- period: toSeconds(10),
- },
- {
- get name() {
- return t`15 minutes`;
- },
- period: toSeconds(15),
- },
- {
- get name() {
- return t`30 minutes`;
- },
- period: toSeconds(30),
- },
- {
- get name() {
- return t`60 minutes`;
- },
- period: toSeconds(60),
- },
-];
+import { AUTO_REFRESH_OPTIONS } from "./options";
export const RefreshWidget = (
props: ActionIconProps & ButtonHTMLAttributes<HTMLButtonElement>,
@@ -94,7 +48,7 @@ export const RefreshWidget = (
c="text-secondary"
>{t`Auto Refresh`}</Box>
<ul>
- {OPTIONS.map((option) => (
+ {AUTO_REFRESH_OPTIONS.map((option) => (
<RefreshOption
key={option.period}
name={option.name}
diff --git a/frontend/src/metabase/dashboard/components/RefreshWidget/index.ts b/frontend/src/metabase/dashboard/components/RefreshWidget/index.ts
index cb2fd315a54..09368312226 100644
--- a/frontend/src/metabase/dashboard/components/RefreshWidget/index.ts
+++ b/frontend/src/metabase/dashboard/components/RefreshWidget/index.ts
@@ -1 +1,2 @@
export * from "./RefreshWidget";
+export * from "./AutoRefreshMenuItem";
diff --git a/frontend/src/metabase/dashboard/components/RefreshWidget/options.ts b/frontend/src/metabase/dashboard/components/RefreshWidget/options.ts
new file mode 100644
index 00000000000..b073f52365c
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/RefreshWidget/options.ts
@@ -0,0 +1,53 @@
+import { t } from "ttag";
+
+const toSeconds = (minutes: number) => minutes * 60;
+
+export type RefreshWidgetOption = {
+ readonly name: string;
+ readonly period: number | null;
+};
+
+export const AUTO_REFRESH_OPTIONS: RefreshWidgetOption[] = [
+ {
+ get name() {
+ return t`Off`;
+ },
+ period: null,
+ },
+ {
+ get name() {
+ return t`1 minute`;
+ },
+ period: toSeconds(1),
+ },
+ {
+ get name() {
+ return t`5 minutes`;
+ },
+ period: toSeconds(5),
+ },
+ {
+ get name() {
+ return t`10 minutes`;
+ },
+ period: toSeconds(10),
+ },
+ {
+ get name() {
+ return t`15 minutes`;
+ },
+ period: toSeconds(15),
+ },
+ {
+ get name() {
+ return t`30 minutes`;
+ },
+ period: toSeconds(30),
+ },
+ {
+ get name() {
+ return t`60 minutes`;
+ },
+ period: toSeconds(60),
+ },
+];
diff --git a/frontend/src/metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem.tsx b/frontend/src/metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem.tsx
deleted file mode 100644
index c5a7a41e53a..00000000000
--- a/frontend/src/metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { t } from "ttag";
-
-import { useHasEmailSetup, useHasSlackSetup } from "metabase/common/hooks";
-import { useSelector } from "metabase/redux";
-import {
- canManageSubscriptions as canManageSubscriptionsSelector,
- getUserIsAdmin,
-} from "metabase/selectors/user";
-import { Icon, Menu, Text } from "metabase/ui";
-import type { Dashboard } from "metabase-types/api";
-
-export function DashboardSubscriptionMenuItem({
- onClick,
- dashboard,
-}: {
- onClick: () => void;
- dashboard: Dashboard;
-}) {
- const isAdmin = useSelector(getUserIsAdmin);
- const hasEmailSetup = useHasEmailSetup();
- const hasSlackSetup = useHasSlackSetup();
-
- const canManageSubscriptions = useSelector(canManageSubscriptionsSelector);
-
- // dashcardData only contains question cards, text ones don't appear here
- const hasDataCards = dashboard?.dashcards?.some(
- (dashCard) => !["text", "heading"].includes(dashCard.card.display),
- );
-
- const hasAnySubscriptionChannel = hasEmailSetup || hasSlackSetup;
-
- if (!canManageSubscriptions || !hasDataCards) {
- return null;
- }
-
- if (!isAdmin && !hasAnySubscriptionChannel) {
- return (
- <Menu.Item
- data-testid="dashboard-subscription-menu-item"
- leftSection={<Icon name="subscription" />}
- disabled
- >
- <Text size="md" c="inherit">{t`Can't send subscriptions`}</Text>
- <Text
- size="sm"
- c="inherit"
- >{t`Ask your admin to set up email or Slack`}</Text>
- </Menu.Item>
- );
- }
-
- return (
- <Menu.Item
- data-testid="dashboard-subscription-menu-item"
- leftSection={<Icon name="subscription" />}
- onClick={onClick}
- >
- {t`Subscriptions`}
- </Menu.Item>
- );
-}
diff --git a/frontend/src/metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem.unit.spec.tsx b/frontend/src/metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem.unit.spec.tsx
deleted file mode 100644
index 3c428078707..00000000000
--- a/frontend/src/metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem.unit.spec.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";
-import { renderWithProviders, screen } from "__support__/ui";
-import { createMockState } from "metabase/redux/store/mocks";
-import { Menu } from "metabase/ui";
-import {
- createMockCard,
- createMockDashboard,
- createMockDashboardCard,
- createMockUser,
-} from "metabase-types/api/mocks";
-
-import { DashboardSubscriptionMenuItem } from "./DashboardSubscriptionMenuItem";
-
-const mockOnClick = jest.fn();
-
-const createDashboardWithDataCards = () => {
- return createMockDashboard({
- dashcards: [
- createMockDashboardCard({
- card: createMockCard({ display: "table" }),
- }),
- ],
- });
-};
-
-const setup = ({
- isSuperuser = false,
- hasEmailSetup = false,
- hasSlackSetup = false,
- dashboard: mockDashboard = createDashboardWithDataCards(),
-}: {
- isSuperuser?: boolean;
- hasEmailSetup?: boolean;
- hasSlackSetup?: boolean;
- dashboard?: ReturnType<typeof createMockDashboard>;
-} = {}) => {
- const currentUser = createMockUser({
- is_superuser: isSuperuser,
- });
- const storeInitialState = createMockState({
- currentUser,
- });
-
- setupNotificationChannelsEndpoints({
- email: { configured: hasEmailSetup },
- slack: { configured: hasSlackSetup },
- });
-
- renderWithProviders(
- <Menu opened>
- <Menu.Dropdown>
- <DashboardSubscriptionMenuItem
- onClick={mockOnClick}
- dashboard={mockDashboard}
- />
- </Menu.Dropdown>
- </Menu>,
- { storeInitialState },
- );
-};
-
-describe("DashboardSubscriptionMenuItem", () => {
- it("should show 'Subscriptions' menu item when can manage subscriptions and has no email or slack setup", async () => {
- setup({
- isSuperuser: true,
- hasEmailSetup: false,
- hasSlackSetup: false,
- });
-
- expect(
- screen.getByTestId("dashboard-subscription-menu-item"),
- ).toBeInTheDocument();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- });
-
- describe("when user can't manage subscriptions and dashboard has data cards", () => {
- it.each([
- { hasEmailSetup: true, hasSlackSetup: false },
- { hasEmailSetup: false, hasSlackSetup: true },
- { hasEmailSetup: true, hasSlackSetup: true },
- ])(
- "should show 'Subscriptions' menu item when email is $hasEmailSetup and slack is $hasSlackSetup",
- async ({ hasEmailSetup, hasSlackSetup }) => {
- setup({
- isSuperuser: false,
- hasEmailSetup,
- hasSlackSetup,
- });
-
- expect(
- screen.getByTestId("dashboard-subscription-menu-item"),
- ).toBeInTheDocument();
- expect(await screen.findByText("Subscriptions")).toBeInTheDocument();
- },
- );
-
- it('should show "Can\'t send subscriptions" menu item when email and slack are not set up', async () => {
- setup({
- isSuperuser: false,
- hasEmailSetup: false,
- hasSlackSetup: false,
- });
-
- expect(
- screen.getByTestId("dashboard-subscription-menu-item"),
- ).toBeInTheDocument();
- expect(
- await screen.findByText("Can't send subscriptions"),
- ).toBeInTheDocument();
- });
- });
-});
diff --git a/frontend/src/metabase/notifications/NotificationsActionsMenu/index.ts b/frontend/src/metabase/notifications/NotificationsActionsMenu/index.ts
index 9b35580e03c..3ad2c21c384 100644
--- a/frontend/src/metabase/notifications/NotificationsActionsMenu/index.ts
+++ b/frontend/src/metabase/notifications/NotificationsActionsMenu/index.ts
@@ -1 +1 @@
-export * from "./DashboardSubscriptionMenuItem";
+export * from "./CommonNotificationsMenuItem";