The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(data-studio): add Library dashboards to Data Studio (#84078)
Aleksandr Lesnenko378b6d97894e
diff --git a/e2e/support/helpers/e2e-data-studio-helpers.ts b/e2e/support/helpers/e2e-data-studio-helpers.tsindex ba08f682332..c4591de9dd3 100644--- a/e2e/support/helpers/e2e-data-studio-helpers.ts+++ b/e2e/support/helpers/e2e-data-studio-helpers.ts@@ -174,9 +174,6 @@ export const DataStudio = {DataStudio.Library.libraryPage().should("be.visible");DataStudio.Library.collectionItem("Data").should("be.visible");DataStudio.Library.collectionItem("Metrics").should("be.visible");- DataStudio.Library.collectionItem("Dashboards")- .scrollIntoView()- .should("be.visible");},libraryPage,allTableItems: () => libraryPage().findAllByTestId("table-name"),diff --git a/e2e/test/scenarios/data-studio/data-studio-dashboards.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-dashboards.cy.spec.tsnew file mode 100644index 00000000000..84a98b090ea--- /dev/null+++ b/e2e/test/scenarios/data-studio/data-studio-dashboards.cy.spec.ts@@ -0,0 +1,84 @@+const { H } = cy;++import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import type { DashboardId } from "metabase-types/api";++const { ORDERS_ID } = SAMPLE_DATABASE;++const DASHBOARD_NAME = "Sales overview";+const QUESTION_NAME = "Orders count";++const dashboardsPage = () => cy.findByTestId("library-page");+const dashboardHeader = () => cy.findByTestId("dashboard-pane-header");++function createLibraryDashboard() {+ H.createLibrary().then(({ body: library }) => {+ const dashboardsCollection = library.effective_children?.find(+ ({ type }) => type === "library-dashboards",+ );+ if (dashboardsCollection == null) {+ throw new Error("The Library has no Dashboards collection");+ }++ H.createQuestionAndDashboard({+ questionDetails: {+ name: QUESTION_NAME,+ query: { "source-table": ORDERS_ID, aggregation: [["count"]] },+ },+ dashboardDetails: {+ name: DASHBOARD_NAME,+ collection_id: dashboardsCollection.id,+ },+ }).then(({ body: dashcard }) => {+ cy.wrap(dashcard.dashboard_id).as("dashboardId");+ });+ });+}++describe("scenarios > data studio > dashboards", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("pro-self-hosted");+ createLibraryDashboard();+ });++ it("opens a Library dashboard, shows its contents, and returns from the editor", () => {+ cy.get<DashboardId>("@dashboardId").then((dashboardId) => {+ const overviewPath = `/data-studio/dashboards/${dashboardId}`;++ cy.visit("/data-studio/dashboards");+ dashboardsPage()+ .findByRole("link", { name: new RegExp(DASHBOARD_NAME) })+ .click();++ cy.location("pathname").should("eq", overviewPath);+ dashboardHeader().should("contain", DASHBOARD_NAME);+ cy.findByTestId("dashboard-preview")+ .findByText(QUESTION_NAME)+ .should("be.visible");++ cy.log("Contents lists the question on the dashboard");+ dashboardHeader().findByRole("link", { name: "Contents" }).click();+ cy.location("pathname").should("eq", `${overviewPath}/contents`);+ cy.findByTestId("dashboard-contents-page")+ .findByRole("row", { name: new RegExp(QUESTION_NAME) })+ .should("be.visible")+ .and("contain", "Question");++ cy.log(+ "Edit opens the main-app editor and Cancel comes back to Contents",+ );+ dashboardHeader().findByRole("button", { name: /Edit/ }).click();+ cy.location("pathname").should(+ "match",+ new RegExp(`^/dashboard/${dashboardId}-`),+ );+ cy.findByTestId("edit-bar").should("be.visible");+ H.dashboardCancelButton().click();++ cy.location("pathname").should("eq", `${overviewPath}/contents`);+ cy.findByTestId("dashboard-contents-page").should("be.visible");+ });+ });+});diff --git a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.tsindex 492650a8abe..7bb298961c3 100644--- a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts@@ -69,7 +69,6 @@ describe("scenarios > data studio > library", () => {cy.log("Verify library collections appear in the library table");H.DataStudio.Library.collectionItem("Data").should("be.visible");H.DataStudio.Library.collectionItem("Metrics").should("be.visible");- H.DataStudio.Library.collectionItem("Dashboards").should("be.visible");});it("should let you move metrics into the library, even when empty", () => {@@ -403,20 +402,24 @@ describe("scenarios > data studio > library", () => {cy.log("Verify SQL snippets tab empty state");H.DataStudio.nav().findByRole("link", { name: "SQL snippets" }).click();- H.DataStudio.Library.collectionItem("SQL snippets").should("be.visible");H.DataStudio.Library.emptyStateRow("Reusable bits of code that save your time",).should("be.visible");+ H.DataStudio.Library.libraryPage()+ .findAllByTestId("collection-name")+ .should("not.exist");H.DataStudio.Library.libraryPage().findByRole("link", { name: "New snippet" }).should("be.visible");cy.log("Verify Data actions tab empty state");H.DataStudio.nav().findByRole("link", { name: "Data actions" }).click();- H.DataStudio.Library.collectionItem("Data actions").should("be.visible");H.DataStudio.Library.emptyStateRow("Queries that change data").should("be.visible",);+ H.DataStudio.Library.libraryPage()+ .findAllByTestId("collection-name")+ .should("not.exist");});describe("read-only mode", () => {diff --git a/e2e/test/scenarios/data-studio/snippets.cy.spec.ts b/e2e/test/scenarios/data-studio/snippets.cy.spec.tsindex a82ff69b43e..2ef735696b4 100644--- a/e2e/test/scenarios/data-studio/snippets.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/snippets.cy.spec.ts@@ -126,7 +126,7 @@ describe("scenarios > data studio > snippets", () => {cy.log("Unarchive the snippet");H.DataStudio.Library.libraryPage()- .findByRole("button", { name: "Snippet collection options" })+ .findByRole("button", { name: "Snippet options" }).click();H.popover()diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsxindex 8fa3d5d46c8..2bedfa729fd 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx@@ -22,6 +22,7 @@ export const SidebarCacheForm = ({withOverlay = true,overlayProps,onBack,+ withBackButton,...stackProps}: SidebarCacheFormProps) => {const configurableModels = useMemo(() => [model], [model]);@@ -67,6 +68,7 @@ export const SidebarCacheForm = ({onBack={() =>isStrategyFormDirty ? askBeforeDiscardingChanges(onBack) : onBack()}+ withBackButton={withBackButton}><Stackalign="space-between"diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryEmptyState/LibraryEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryEmptyState/LibraryEmptyState.tsxrename to enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryEmptyState/LibraryEmptyState.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryEmptyState/LibraryEmptyState.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.unit.spec.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryEmptyState/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/index.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryEmptyState/index.tsrename to enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/index.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/constants.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/constants.tsnew file mode 100644index 00000000000..ddab3e25c67--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/constants.ts@@ -0,0 +1,11 @@+import type { EntityPickerOptions } from "metabase/common/components/Pickers";++export const LIBRARY_COLLECTION_PICKER_OPTIONS: EntityPickerOptions = {+ hasLibrary: true,+ hasRootCollection: false,+ hasPersonalCollections: false,+ hasRecents: false,+ hasSearch: false,+ hasConfirmButtons: true,+ canCreateCollections: false,+};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/analytics.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/analytics.tsnew file mode 100644index 00000000000..7eef8bfd04e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/analytics.ts@@ -0,0 +1,16 @@+import { trackSimpleEvent } from "metabase/analytics";+import type { DashboardId } from "metabase-types/api";++export function trackDataStudioDashboardCreated(dashboardId: DashboardId) {+ trackSimpleEvent({+ event: "data_studio_dashboard_created",+ target_id: Number(dashboardId),+ });+}++export function trackDataStudioDashboardEditStarted(dashboardId: DashboardId) {+ trackSimpleEvent({+ event: "data_studio_dashboard_edit_started",+ target_id: Number(dashboardId),+ });+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsxsimilarity index 72%rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsxrename to enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsxindex 1d42eafaafc..48ae08a630f 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsx@@ -5,7 +5,7 @@ import * as Yup from "yup";import { useCreateDashboardMutation } from "metabase/api";import FormCollectionPicker from "metabase/common/collections/containers/FormCollectionPicker/FormCollectionPicker";import { FormFooter } from "metabase/common/components/FormFooter";-import type { EntityPickerOptions } from "metabase/common/components/Pickers";+import { getDataStudioDashboardReturnState } from "metabase/common/data-studio/utils/return-to";import {DASHBOARD_DESCRIPTION_MAX_LENGTH,DASHBOARD_NAME_MAX_LENGTH,@@ -24,17 +24,21 @@ import * as Urls from "metabase/urls";import * as Errors from "metabase/utils/errors";import type { CollectionId } from "metabase-types/api";-const DASHBOARD_SCHEMA = Yup.object({- name: Yup.string()- .required(Errors.required)- .max(DASHBOARD_NAME_MAX_LENGTH, Errors.maxLength)- .default(""),- description: Yup.string()- .nullable()- .max(DASHBOARD_DESCRIPTION_MAX_LENGTH, Errors.maxLength)- .default(null),- collection_id: Yup.number().required(Errors.required),-});+import { LIBRARY_COLLECTION_PICKER_OPTIONS } from "../../../constants";+import { trackDataStudioDashboardCreated } from "../../analytics";++const getValidationSchema = () =>+ Yup.object({+ name: Yup.string()+ .required(Errors.required)+ .max(DASHBOARD_NAME_MAX_LENGTH, Errors.maxLength)+ .default(""),+ description: Yup.string()+ .nullable()+ .max(DASHBOARD_DESCRIPTION_MAX_LENGTH, Errors.maxLength)+ .default(null),+ collection_id: Yup.number().required(Errors.required),+ });type CreateLibraryDashboardValues = {name: string;@@ -42,16 +46,6 @@ type CreateLibraryDashboardValues = {collection_id: CollectionId;};-const LIBRARY_DASHBOARD_PICKER_OPTIONS: EntityPickerOptions = {- hasLibrary: true,- hasRootCollection: false,- hasPersonalCollections: false,- hasRecents: false,- hasSearch: false,- hasConfirmButtons: true,- canCreateCollections: false,-};-type CreateLibraryDashboardModalProps = {opened: boolean;collectionId: CollectionId;@@ -66,14 +60,18 @@ export function CreateLibraryDashboardModal({const navigate = useNavigate();const [createDashboard] = useCreateDashboardMutation();+ const validationSchema = useMemo(getValidationSchema, []);const initialValues = useMemo(- () => ({ ...DASHBOARD_SCHEMA.getDefault(), collection_id: collectionId }),- [collectionId],+ () => ({ ...validationSchema.getDefault(), collection_id: collectionId }),+ [validationSchema, collectionId],);const handleSubmit = async (values: CreateLibraryDashboardValues) => {const dashboard = await createDashboard(values).unwrap();- navigate(Urls.dashboard(dashboard, { editMode: true }));+ trackDataStudioDashboardCreated(dashboard.id);+ navigate(Urls.dashboard(dashboard, { editMode: true }), {+ state: getDataStudioDashboardReturnState(dashboard.id),+ });};return (@@ -81,7 +79,7 @@ export function CreateLibraryDashboardModal({<FormProviderinitialValues={initialValues}enableReinitialize- validationSchema={DASHBOARD_SCHEMA}+ validationSchema={validationSchema}onSubmit={handleSubmit}><Form as={Stack} gap={0}>@@ -109,7 +107,7 @@ export function CreateLibraryDashboardModal({title={t`Collection`}entityType="dashboard"collectionPickerModalProps={{- options: LIBRARY_DASHBOARD_PICKER_OPTIONS,+ options: LIBRARY_COLLECTION_PICKER_OPTIONS,}}/><FormFooter mt="lg">diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/CreateLibraryDashboardModal.unit.spec.tsxsimilarity index 77%rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/CreateLibraryDashboardModal.unit.spec.tsxindex 114d93fcf04..fc2d50d8640 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/CreateLibraryDashboardModal.unit.spec.tsx@@ -7,7 +7,11 @@ import {createMockDashboard,} from "metabase-types/api/mocks";-import { CreateLibraryDashboardModal } from ".";+import { trackDataStudioDashboardCreated } from "../../analytics";++import { CreateLibraryDashboardModal } from "./CreateLibraryDashboardModal";++jest.mock("../../analytics");const DASHBOARDS_COLLECTION = createMockCollection({id: 3,@@ -37,7 +41,7 @@ function setup() {collectionId={DASHBOARDS_COLLECTION.id}onClose={onClose}/>,- { withRouter: true },+ { withRouter: true, initialRoute: "/data-studio/dashboards" },);return { onClose, router };@@ -50,7 +54,7 @@ describe("CreateLibraryDashboardModal", () => {expect(await screen.findByText("Dashboards")).toBeInTheDocument();});- it("creates the dashboard in the Library and opens it in the main app", async () => {+ it("creates the dashboard in the Library and opens its editor, returning to the new dashboard", async () => {const { router } = setup();await userEvent.type(screen.getByLabelText("Name"), "Sales");@@ -61,6 +65,7 @@ describe("CreateLibraryDashboardModal", () => {expect(router?.location).toMatchObject({pathname: "/dashboard/42-sales",hash: "#edit",+ state: { returnTo: "/data-studio/dashboards/42" },}),);expect(@@ -72,6 +77,12 @@ describe("CreateLibraryDashboardModal", () => {description: "Revenue",collection_id: DASHBOARDS_COLLECTION.id,});+ expect(jest.mocked(trackDataStudioDashboardCreated)).toHaveBeenCalledTimes(+ 1,+ );+ expect(jest.mocked(trackDataStudioDashboardCreated)).toHaveBeenCalledWith(+ 42,+ );});it("calls onClose when Cancel is clicked", async () => {diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/index.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/index.tsrename to enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/CreateLibraryDashboardModal/index.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardArchivedBanner.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardArchivedBanner.tsxnew file mode 100644index 00000000000..c18cb7703c9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardArchivedBanner.tsx@@ -0,0 +1,50 @@+import { t } from "ttag";++import { useDeleteDashboardMutation } from "metabase/api";+import { ArchivedEntityBanner } from "metabase/archive/components/ArchivedEntityBanner";+import { useSetArchive } from "metabase/archive/hooks";+import { useSetCollection } from "metabase/common/hooks";+import { useDispatch, useSelector } from "metabase/redux";+import { addUndo } from "metabase/redux/undo";+import { useNavigate } from "metabase/router";+import * as Urls from "metabase/urls";+import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";+import type { Dashboard } from "metabase-types/api";++type DashboardArchivedBannerProps = {+ dashboard: Dashboard;+};++export function DashboardArchivedBanner({+ dashboard,+}: DashboardArchivedBannerProps) {+ const isReadOnly = useSelector(getIsRemoteSyncReadOnly);+ const dispatch = useDispatch();+ const navigate = useNavigate();+ const archive = useSetArchive();+ const setCollection = useSetCollection();+ const [deleteDashboard] = useDeleteDashboardMutation();++ return (+ <ArchivedEntityBanner+ name={dashboard.name}+ entityType={t`dashboard`}+ canMove={dashboard.can_write && !isReadOnly}+ canRestore={dashboard.can_restore && !isReadOnly}+ canDelete={dashboard.can_delete && !isReadOnly}+ onUnarchive={() =>+ archive({ id: dashboard.id, model: "dashboard" }, false)+ }+ onMove={({ id }) =>+ setCollection({ id: dashboard.id, model: "dashboard" }, { id })+ }+ onDeletePermanently={async () => {+ await deleteDashboard(dashboard.id).unwrap();+ navigate(Urls.dataStudioDashboards());+ dispatch(+ addUndo({ message: t`This item has been permanently deleted.` }),+ );+ }}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardHeader.tsxnew file mode 100644index 00000000000..d6799a1c35e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardHeader.tsx@@ -0,0 +1,61 @@+import { t } from "ttag";++import { Link } from "metabase/common/components/Link";+import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";+import {+ PaneHeader,+ PanelHeaderTitle,+} from "metabase/common/data-studio/components/PaneHeader";+import { useCollectionPath } from "metabase/common/data-studio/hooks/use-collection-path/useCollectionPath";+import * as Urls from "metabase/urls";+import type { Dashboard } from "metabase-types/api";++import type { DashboardTabsInfo } from "../../hooks/use-dashboard-tabs-info";++import { DashboardArchivedBanner } from "./DashboardArchivedBanner";+import { DashboardHeaderActions } from "./DashboardHeaderActions";+import { DashboardTabs } from "./DashboardTabs";+import { getDashboardFolders } from "./utils";++type DashboardHeaderProps = {+ dashboard: Dashboard;+ tabsInfo: DashboardTabsInfo;+};++export function DashboardHeader({ dashboard, tabsInfo }: DashboardHeaderProps) {+ const { path, isLoadingPath } = useCollectionPath({+ collectionId: dashboard.collection_id,+ });+ const folders = getDashboardFolders(path ?? []);++ return (+ <>+ {dashboard.archived && <DashboardArchivedBanner dashboard={dashboard} />}+ <PaneHeader+ data-testid="dashboard-pane-header"+ title={<PanelHeaderTitle>{dashboard.name}</PanelHeaderTitle>}+ icon="dashboard"+ tabs={<DashboardTabs dashboardId={dashboard.id} tabsInfo={tabsInfo} />}+ actions={<DashboardHeaderActions dashboard={dashboard} />}+ breadcrumbs={+ <DataStudioBreadcrumbs loading={isLoadingPath}>+ <Link to={Urls.dataStudioDashboards()}>{t`Dashboards`}</Link>+ {folders.map((folder, index) => (+ <Link+ key={folder.id}+ to={Urls.dataStudioDashboards({+ expandedIds: folders+ .slice(0, index + 1)+ .map((ancestor) => ancestor.id),+ })}+ >+ {folder.name}+ </Link>+ ))}+ <span>{dashboard.name}</span>+ </DataStudioBreadcrumbs>+ }+ />+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardHeaderActions.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardHeaderActions.tsxnew file mode 100644index 00000000000..ca364230ca1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardHeaderActions.tsx@@ -0,0 +1,48 @@+import { c, t } from "ttag";++import { ForwardRefLink } from "metabase/common/components/Link";+import { getDataStudioPageReturnState } from "metabase/common/data-studio/utils/return-to";+import { useLocation, useNavigate } from "metabase/router";+import { Button, Group, Icon } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { Dashboard } from "metabase-types/api";++import { trackDataStudioDashboardEditStarted } from "../../analytics";+import { useCanEditDashboard } from "../../hooks/use-can-edit-dashboard";++type DashboardHeaderActionsProps = {+ dashboard: Dashboard;+};++export function DashboardHeaderActions({+ dashboard,+}: DashboardHeaderActionsProps) {+ const location = useLocation();+ const navigate = useNavigate();+ const canEdit = useCanEditDashboard(dashboard);++ const handleEditClick = () => {+ trackDataStudioDashboardEditStarted(dashboard.id);+ navigate(Urls.dashboard(dashboard, { editMode: true }), {+ state: getDataStudioPageReturnState(location),+ });+ };++ return (+ <Group gap="sm" wrap="nowrap">+ <Button+ component={ForwardRefLink}+ to={Urls.dashboard(dashboard)}+ target="_blank"+ rightSection={<Icon name="external" />}+ >+ {c("A verb, not a noun").t`View`}+ </Button>+ {canEdit && (+ <Button leftSection={<Icon name="pencil" />} onClick={handleEditClick}>+ {t`Edit`}+ </Button>+ )}+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardTabs.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardTabs.tsxnew file mode 100644index 00000000000..5e1c70c483f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/DashboardTabs.tsx@@ -0,0 +1,53 @@+import { t } from "ttag";++import {+ type PillTab,+ PillTabNavigation,+} from "metabase/common/components/PillTabNavigation";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import * as Urls from "metabase/urls";+import type { DashboardId } from "metabase-types/api";++import type { DashboardTabsInfo } from "../../hooks/use-dashboard-tabs-info";++type DashboardTabsProps = {+ dashboardId: DashboardId;+ tabsInfo: DashboardTabsInfo;+};++export function DashboardTabs({ dashboardId, tabsInfo }: DashboardTabsProps) {+ const contentsUrl = Urls.dataStudioDashboardContents(dashboardId);+ const subscriptionsUrl = Urls.dataStudioDashboardSubscriptions(dashboardId);+ const tabs: PillTab[] = [+ { label: t`Overview`, to: Urls.dataStudioDashboard(dashboardId) },+ {+ label: t`Contents`,+ to: contentsUrl,+ isSelected: (pathname) => pathname.startsWith(contentsUrl),+ },+ ...(PLUGIN_DEPENDENCIES.isEnabled+ ? [+ {+ label: t`Dependencies`,+ to: Urls.dataStudioDashboardDependencies(dashboardId),+ },+ ]+ : []),+ ...(tabsInfo.hasUsageStats+ ? [+ {+ label: t`Usage stats`,+ to: Urls.dataStudioDashboardUsage(dashboardId),+ },+ ]+ : []),+ {+ label: t`Subscriptions`,+ to: subscriptionsUrl,+ count: tabsInfo.subscriptionCount,+ isSelected: (pathname) => pathname.startsWith(subscriptionsUrl),+ },+ ];++ return <PillTabNavigation tabs={tabs} />;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/index.tsnew file mode 100644index 00000000000..bdd3deb0e93--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/index.ts@@ -0,0 +1 @@+export { DashboardHeader } from "./DashboardHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/utils.tsnew file mode 100644index 00000000000..d04c56d9228--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/utils.ts@@ -0,0 +1,10 @@+import type { CollectionEssentials } from "metabase-types/api";++export function getDashboardFolders(+ path: CollectionEssentials[],+): CollectionEssentials[] {+ const sectionIndex = path.findIndex(+ (collection) => collection.type === "library-dashboards",+ );+ return sectionIndex === -1 ? [] : path.slice(sectionIndex + 1);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/utils.unit.spec.tsnew file mode 100644index 00000000000..b4784bd05f3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardHeader/utils.unit.spec.ts@@ -0,0 +1,27 @@+import { createMockCollection } from "metabase-types/api/mocks";++import { getDashboardFolders } from "./utils";++const LIBRARY = createMockCollection({ id: 1, type: "library" });+const DASHBOARDS = createMockCollection({ id: 2, type: "library-dashboards" });+const SALES = createMockCollection({ id: 3, type: "library-dashboards" });+const EMEA = createMockCollection({ id: 4, type: "library-dashboards" });++describe("getDashboardFolders", () => {+ it("returns the folders below the Dashboards section", () => {+ expect(getDashboardFolders([LIBRARY, DASHBOARDS, SALES, EMEA])).toEqual([+ SALES,+ EMEA,+ ]);+ });++ it("returns no folders for a dashboard at the section root", () => {+ expect(getDashboardFolders([LIBRARY, DASHBOARDS])).toEqual([]);+ });++ it("returns no folders outside the Dashboards section", () => {+ expect(+ getDashboardFolders([createMockCollection({ id: 5, type: null })]),+ ).toEqual([]);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardPageShell/DashboardPageShell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardPageShell/DashboardPageShell.tsxnew file mode 100644index 00000000000..d4d943dbbe0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardPageShell/DashboardPageShell.tsx@@ -0,0 +1,110 @@+import { useElementSize } from "@mantine/hooks";+import type { ReactNode } from "react";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Center, Flex } from "metabase/ui";+import type { Dashboard } from "metabase-types/api";++import {+ type DashboardTabsInfo,+ useDashboardTabsInfo,+} from "../../hooks/use-dashboard-tabs-info";+import { useRouteDashboard } from "../../hooks/use-route-dashboard";+import { DashboardHeader } from "../DashboardHeader";++type RenderPage = (dashboard: Dashboard) => ReactNode;++type RenderAside = (dashboard: Dashboard, containerWidth: number) => ReactNode;++type DashboardPageShellProps = {+ "data-testid"?: string;+ children: RenderPage;+ aside?: RenderAside;+};++/**+ * Loads the dashboard in the route and what its tabs need, and frames a Data+ * Studio dashboard page with its header. Renders a loader or the error until+ * all of it is there, then `children` with the dashboard. `aside` renders beside the page, at its+ * edge, with the width the page is left with.+ */+export function DashboardPageShell({+ "data-testid": dataTestId,+ children,+ aside,+}: DashboardPageShellProps) {+ const {+ dashboard,+ isLoading: isLoadingDashboard,+ error: dashboardError,+ } = useRouteDashboard();+ const {+ tabsInfo,+ isLoading: isLoadingTabsInfo,+ error: tabsInfoError,+ } = useDashboardTabsInfo(dashboard?.id);+ const isLoading = isLoadingDashboard || isLoadingTabsInfo;+ const error = dashboardError ?? tabsInfoError;++ if (isLoading || error != null || dashboard == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ if (aside != null) {+ return (+ <DashboardPageWithAside+ dashboard={dashboard}+ tabsInfo={tabsInfo}+ data-testid={dataTestId}+ aside={aside}+ >+ {children}+ </DashboardPageWithAside>+ );+ }++ return (+ <PageContainer data-testid={dataTestId}>+ <DashboardHeader dashboard={dashboard} tabsInfo={tabsInfo} />+ {children(dashboard)}+ </PageContainer>+ );+}++type DashboardPageWithAsideProps = {+ dashboard: Dashboard;+ tabsInfo: DashboardTabsInfo;+ "data-testid"?: string;+ children: RenderPage;+ aside: RenderAside;+};++function DashboardPageWithAside({+ dashboard,+ tabsInfo,+ "data-testid": dataTestId,+ children,+ aside,+}: DashboardPageWithAsideProps) {+ const { ref: containerRef, width: containerWidth } = useElementSize();++ return (+ <Flex h="100%" wrap="nowrap">+ <PageContainer+ ref={containerRef}+ flex={1}+ miw={0}+ data-testid={dataTestId}+ >+ <DashboardHeader dashboard={dashboard} tabsInfo={tabsInfo} />+ {children(dashboard)}+ </PageContainer>+ {aside(dashboard, containerWidth)}+ </Flex>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardPageShell/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardPageShell/index.tsnew file mode 100644index 00000000000..bdb90db9475--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/components/DashboardPageShell/index.ts@@ -0,0 +1 @@+export { DashboardPageShell } from "./DashboardPageShell";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-can-edit-dashboard/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-can-edit-dashboard/index.tsnew file mode 100644index 00000000000..cfd248f999f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-can-edit-dashboard/index.ts@@ -0,0 +1 @@+export { useCanEditDashboard } from "./use-can-edit-dashboard";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-can-edit-dashboard/use-can-edit-dashboard.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-can-edit-dashboard/use-can-edit-dashboard.tsnew file mode 100644index 00000000000..5ae8b185914--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-can-edit-dashboard/use-can-edit-dashboard.ts@@ -0,0 +1,14 @@+import { useSelector } from "metabase/redux";+import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";+import type { Dashboard } from "metabase-types/api";++/**+ * Whether the user can change the dashboard from Data Studio: they can write+ * it, it is not in the trash, and remote sync is not read-only.+ */+export function useCanEditDashboard(+ dashboard: Pick<Dashboard, "can_write" | "archived">,+): boolean {+ const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);+ return dashboard.can_write && !dashboard.archived && !isRemoteSyncReadOnly;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/index.tsnew file mode 100644index 00000000000..68500f5de46--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/index.ts@@ -0,0 +1,4 @@+export {+ type DashboardTabsInfo,+ useDashboardTabsInfo,+} from "./use-dashboard-tabs-info";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/use-dashboard-tabs-info.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/use-dashboard-tabs-info.tsnew file mode 100644index 00000000000..7c992b2767f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/use-dashboard-tabs-info.ts@@ -0,0 +1,52 @@+import { skipToken, useListSubscriptionsQuery } from "metabase/api";+import { getUserIsAdmin } from "metabase/current-user";+import { PLUGIN_AUDIT } from "metabase/plugins";+import { useSelector } from "metabase/redux";+import { useGetAuditInfoQuery } from "metabase-enterprise/api";+import type { DashboardId } from "metabase-types/api";++export type DashboardTabsInfo = {+ hasUsageStats: boolean;+ /** `undefined` for a non-admin, whose list holds only their own subscriptions. */+ subscriptionCount: number | undefined;+};++type DashboardTabsInfoResult = {+ tabsInfo: DashboardTabsInfo;+ isLoading: boolean;+ error: unknown;+};++/**+ * What a Data Studio dashboard's tabs depend on beyond the dashboard itself,+ * loaded together so a page can wait for all of it.+ */+export function useDashboardTabsInfo(+ dashboardId: DashboardId | undefined,+): DashboardTabsInfoResult {+ const isAdmin = useSelector(getUserIsAdmin);+ const {+ currentData: auditInfo,+ isFetching: isFetchingAuditInfo,+ error: auditInfoError,+ } = useGetAuditInfoQuery(PLUGIN_AUDIT.isEnabled ? undefined : skipToken);+ const {+ currentData: subscriptions,+ isFetching: isFetchingSubscriptions,+ error: subscriptionsError,+ } = useListSubscriptionsQuery(+ isAdmin && dashboardId != null ? { dashboard_id: dashboardId } : skipToken,+ );++ return {+ tabsInfo: {+ hasUsageStats:+ PLUGIN_AUDIT.isEnabled && auditInfo?.dashboard_overview != null,+ subscriptionCount: subscriptions?.length,+ },+ isLoading:+ (auditInfo === undefined && isFetchingAuditInfo) ||+ (subscriptions === undefined && isFetchingSubscriptions),+ error: auditInfoError ?? subscriptionsError,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/use-dashboard-tabs-info.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/use-dashboard-tabs-info.unit.spec.tsnew file mode 100644index 00000000000..987a8d68a8c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-dashboard-tabs-info/use-dashboard-tabs-info.unit.spec.ts@@ -0,0 +1,58 @@+import { setupListSubscriptionsEndpoint } from "__support__/server-mocks/pulse";+import { renderHookWithProviders, waitFor } from "__support__/ui";+import type { DashboardId } from "metabase-types/api";+import {+ createMockDashboardSubscription,+ createMockUser,+} from "metabase-types/api/mocks";++import { useDashboardTabsInfo } from "./use-dashboard-tabs-info";++describe("useDashboardTabsInfo", () => {+ it("doesn't show the previous dashboard's subscription count while the next one loads", async () => {+ setupListSubscriptionsEndpoint(+ [+ createMockDashboardSubscription({ id: 1, dashboard_id: 1 }),+ createMockDashboardSubscription({ id: 2, dashboard_id: 1 }),+ ],+ { dashboardId: 1 },+ );+ setupListSubscriptionsEndpoint(+ [createMockDashboardSubscription({ id: 3, dashboard_id: 2 })],+ { dashboardId: 2 },+ );+ const { result, rerender } = renderHookWithProviders(+ ({ dashboardId }: { dashboardId: DashboardId }) =>+ useDashboardTabsInfo(dashboardId),+ {+ initialProps: { dashboardId: 1 },+ storeInitialState: {+ currentUser: createMockUser({ is_superuser: true }),+ },+ },+ );+ await waitFor(() =>+ expect(result.current.tabsInfo.subscriptionCount).toBe(2),+ );++ rerender({ dashboardId: 2 });++ expect(result.current.isLoading).toBe(true);+ expect(result.current.tabsInfo.subscriptionCount).toBeUndefined();+ await waitFor(() =>+ expect(result.current.tabsInfo.subscriptionCount).toBe(1),+ );+ expect(result.current.isLoading).toBe(false);+ });++ it("is not loading when it doesn't count a non-admin's subscriptions", () => {+ const { result } = renderHookWithProviders(() => useDashboardTabsInfo(1), {+ storeInitialState: {+ currentUser: createMockUser({ is_superuser: false }),+ },+ });++ expect(result.current.isLoading).toBe(false);+ expect(result.current.tabsInfo.subscriptionCount).toBeUndefined();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-route-dashboard/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-route-dashboard/index.tsnew file mode 100644index 00000000000..131c488840b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-route-dashboard/index.ts@@ -0,0 +1 @@+export { useRouteDashboard } from "./use-route-dashboard";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-route-dashboard/use-route-dashboard.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-route-dashboard/use-route-dashboard.tsnew file mode 100644index 00000000000..0931ceb6611--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/hooks/use-route-dashboard/use-route-dashboard.ts@@ -0,0 +1,38 @@+import { t } from "ttag";++import { skipToken, useGetDashboardQuery } from "metabase/api";+import { useParams } from "metabase/router";+import * as Urls from "metabase/urls";+import type { Dashboard } from "metabase-types/api";++type RouteDashboardResult = {+ dashboard: Dashboard | undefined;+ isLoading: boolean;+ error: unknown;+};++export function useRouteDashboard(): RouteDashboardResult {+ const params = useParams<{ dashboardId: string }>();+ const dashboardId = Urls.extractEntityId(params.dashboardId);+ const {+ currentData: dashboard,+ isFetching,+ error,+ } = useGetDashboardQuery(+ dashboardId != null ? { id: dashboardId } : skipToken,+ );++ if (dashboardId == null) {+ return {+ dashboard: undefined,+ isLoading: false,+ error: t`Dashboard not found.`,+ };+ }++ return {+ dashboard,+ isLoading: dashboard === undefined && isFetching,+ error,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/ContentItemLink.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/ContentItemLink.tsxnew file mode 100644index 00000000000..2cbe494ca0e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/ContentItemLink.tsx@@ -0,0 +1,26 @@+import type { ReactNode } from "react";++import { skipToken, useGetCollectionQuery } from "metabase/api";+import { Link } from "metabase/common/components/Link";+import type { Card } from "metabase-types/api";++import { getDashboardContentItemUrl } from "./utils";++type ContentItemLinkProps = {+ item: Card;+ className: string;+ children: ReactNode;+};++export function ContentItemLink({ item, ...props }: ContentItemLinkProps) {+ // Dashcard cards carry no collection type, and only a metric's URL depends on+ // it. ContentLocationCell requests the same collection, so this shares its+ // cached response instead of sending another request.+ const { currentData: collection } = useGetCollectionQuery(+ item.type === "metric" ? { id: item.collection_id ?? "root" } : skipToken,+ );++ return (+ <Link to={getDashboardContentItemUrl(item, collection?.type)} {...props} />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/ContentLocationCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/ContentLocationCell.tsxnew file mode 100644index 00000000000..fd19233aab2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/ContentLocationCell.tsx@@ -0,0 +1,21 @@+import { skipToken, useGetCollectionQuery } from "metabase/api";+import { Text } from "metabase/ui";+import type { Card, Dashboard } from "metabase-types/api";++type ContentLocationCellProps = {+ item: Card;+ dashboard: Pick<Dashboard, "id" | "name">;+};++export function ContentLocationCell({+ item,+ dashboard,+}: ContentLocationCellProps) {+ const isSavedToDashboard = item.dashboard_id === dashboard.id;+ const { currentData: collection } = useGetCollectionQuery(+ isSavedToDashboard ? skipToken : { id: item.collection_id ?? "root" },+ );+ const locationName = isSavedToDashboard ? dashboard.name : collection?.name;++ return <Text truncate>{locationName}</Text>;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/DashboardContentsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/DashboardContentsPage.tsxnew file mode 100644index 00000000000..717ed1e25f7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/DashboardContentsPage.tsx@@ -0,0 +1,80 @@+import { useMemo, useState } from "react";+import { t } from "ttag";++import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import {+ Card,+ Icon,+ Stack,+ TextInput,+ TreeTable,+ useTreeTableInstance,+} from "metabase/ui";+import type { Dashboard } from "metabase-types/api";++import { DashboardPageShell } from "../../components/DashboardPageShell";+import { getDashcardCards } from "../../utils";++import { ContentItemLink } from "./ContentItemLink";+import { useContentColumns } from "./use-content-columns";+import { filterDashboardContentItems, getDashboardContentItems } from "./utils";++export function DashboardContentsPage() {+ return (+ <DashboardPageShell data-testid="dashboard-contents-page">+ {(dashboard) => <DashboardContents dashboard={dashboard} />}+ </DashboardPageShell>+ );+}++type DashboardContentsProps = {+ dashboard: Dashboard;+};++function DashboardContents({ dashboard }: DashboardContentsProps) {+ const [searchQuery, setSearchQuery] = useState("");+ const items = useMemo(+ () => getDashboardContentItems(getDashcardCards(dashboard)),+ [dashboard],+ );+ const filteredItems = useMemo(+ () => filterDashboardContentItems(items, searchQuery),+ [items, searchQuery],+ );+ const columns = useContentColumns(dashboard);+ const treeTableInstance = useTreeTableInstance({+ data: filteredItems,+ columns,+ getNodeId: (item) => String(item.id),+ });++ return (+ <Stack gap="lg">+ <TextInput+ placeholder={t`Search...`}+ leftSection={<Icon name="search" />}+ bdrs="sm"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ />+ <Card withBorder p={0}>+ <TreeTable+ instance={treeTableInstance}+ hierarchical={false}+ emptyState={+ <ListEmptyState+ label={+ searchQuery+ ? t`No results for "${searchQuery}"`+ : t`This dashboard has no questions yet`+ }+ />+ }+ renderRowLink={(row, props) => (+ <ContentItemLink item={row.original} {...props} />+ )}+ />+ </Card>+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/DashboardContentsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/DashboardContentsPage.unit.spec.tsxnew file mode 100644index 00000000000..4844846db7d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/DashboardContentsPage.unit.spec.tsx@@ -0,0 +1,223 @@+import userEvent from "@testing-library/user-event";++import {+ setupCollectionByIdEndpoint,+ setupDashboardEndpoints,+ setupDashboardNotFoundEndpoint,+} from "__support__/server-mocks";+import { setupListSubscriptionsEndpoint } from "__support__/server-mocks/pulse";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ waitForLoaderToBeRemoved,+ within,+} from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";+import { Route } from "metabase/router";+import type { Card, Dashboard } from "metabase-types/api";+import {+ createMockCard,+ createMockCollection,+ createMockDashboard,+ createMockDashboardCard,+} from "metabase-types/api/mocks";++import { DashboardContentsPage } from "./DashboardContentsPage";++const DASHBOARDS_COLLECTION = createMockCollection({+ id: 2,+ name: "Dashboards",+ type: "library-dashboards",+});++const SALES_COLLECTION = createMockCollection({ id: 3, name: "Sales" });++const METRICS_COLLECTION = createMockCollection({+ id: 4,+ name: "Metrics",+ type: "library-metrics",+});++const DASHBOARD_ID = 10;++const ORDERS = createMockCard({+ id: 1,+ name: "Orders",+ type: "question",+ collection_id: SALES_COLLECTION.id,+});++const REVENUE = createMockCard({+ id: 2,+ name: "Revenue",+ type: "metric",+ collection_id: SALES_COLLECTION.id,+});++const LIBRARY_METRIC = createMockCard({+ id: 4,+ name: "Churn rate",+ type: "metric",+ collection_id: METRICS_COLLECTION.id,+});++const DASHBOARD_QUESTION = createMockCard({+ id: 3,+ name: "Weekly signups",+ type: "question",+ dashboard_id: DASHBOARD_ID,+});++type SetupOpts = {+ dashboard?: Dashboard;+ dashboardSlug?: string;+ isNotFound?: boolean;+};++function setup({+ dashboard = createMockDashboard({ id: DASHBOARD_ID }),+ dashboardSlug = String(dashboard.id),+ isNotFound = false,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 800 });+ setupListSubscriptionsEndpoint([]);+ if (isNotFound) {+ setupDashboardNotFoundEndpoint(dashboard);+ } else {+ setupDashboardEndpoints(dashboard);+ }+ setupCollectionByIdEndpoint({+ collections: [+ createMockCollection(ROOT_COLLECTION),+ DASHBOARDS_COLLECTION,+ SALES_COLLECTION,+ METRICS_COLLECTION,+ ],+ });++ renderWithProviders(+ <Route+ path="/data-studio/dashboards/:dashboardId/contents"+ element={<DashboardContentsPage />}+ />,+ {+ withRouter: true,+ initialRoute: `/data-studio/dashboards/${dashboardSlug}/contents`,+ },+ );+}++function createDashboardWithCards(cards: Card[]) {+ return createMockDashboard({+ id: DASHBOARD_ID,+ name: "Sales overview",+ collection_id: DASHBOARDS_COLLECTION.id,+ dashcards: cards.map((card, index) =>+ createMockDashboardCard({ id: index + 1, card }),+ ),+ });+}++describe("DashboardContentsPage", () => {+ it("shows a loader, then a row per card with its type and location", async () => {+ setup({+ dashboard: createDashboardWithCards([+ ORDERS,+ REVENUE,+ DASHBOARD_QUESTION,+ ]),+ });++ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ await waitForLoaderToBeRemoved();+ expect(+ await screen.findByTestId("dashboard-contents-page"),+ ).toBeInTheDocument();++ const ordersRow = screen.getByRole("row", { name: /Orders/ });+ expect(within(ordersRow).getByText("Question")).toBeInTheDocument();+ expect(await within(ordersRow).findByText("Sales")).toBeInTheDocument();++ const revenueRow = screen.getByRole("row", { name: /Revenue/ });+ expect(within(revenueRow).getByText("Metric")).toBeInTheDocument();+ expect(await within(revenueRow).findByText("Sales")).toBeInTheDocument();++ const signupsRow = screen.getByRole("row", { name: /Weekly signups/ });+ expect(within(signupsRow).getByText("Question")).toBeInTheDocument();+ expect(within(signupsRow).getByText("Sales overview")).toBeInTheDocument();+ });++ it("links only metrics saved in the Library to Data Studio", async () => {+ setup({+ dashboard: createDashboardWithCards([ORDERS, REVENUE, LIBRARY_METRIC]),+ });++ await waitFor(() =>+ expect(screen.getByRole("link", { name: /Churn rate/ })).toHaveAttribute(+ "href",+ "/data-studio/library/metrics/4",+ ),+ );+ expect(screen.getByRole("link", { name: /Revenue/ })).toHaveAttribute(+ "href",+ "/metric/2-revenue",+ );+ expect(screen.getByRole("link", { name: /Orders/ })).toHaveAttribute(+ "href",+ "/question/1-orders",+ );+ });++ it("filters the cards by name and reports when nothing matches", async () => {+ setup({ dashboard: createDashboardWithCards([ORDERS, REVENUE]) });+ const searchInput = await screen.findByPlaceholderText("Search...");++ await userEvent.type(searchInput, "rev");+ expect(screen.getByText("Revenue")).toBeInTheDocument();+ expect(screen.queryByText("Orders")).not.toBeInTheDocument();++ await userEvent.clear(searchInput);+ await userEvent.type(searchInput, "churn");+ expect(screen.getByText('No results for "churn"')).toBeInTheDocument();+ expect(screen.queryByText("Revenue")).not.toBeInTheDocument();+ });++ it("tells the user when the dashboard has no questions", async () => {+ setup({ dashboard: createDashboardWithCards([]) });++ expect(+ await screen.findByText("This dashboard has no questions yet"),+ ).toBeInTheDocument();+ });++ it("shows the trash banner when the dashboard is archived", async () => {+ setup({+ dashboard: createMockDashboard({ id: DASHBOARD_ID, archived: true }),+ });++ expect(await screen.findByTestId("archive-banner")).toHaveTextContent(+ "This dashboard is in the trash.",+ );+ });++ it("shows an error when the dashboard cannot be loaded", async () => {+ setup({ isNotFound: true });++ await waitForLoaderToBeRemoved();+ expect(+ screen.queryByTestId("dashboard-contents-page"),+ ).not.toBeInTheDocument();+ expect(screen.getByText("An error occurred")).toBeInTheDocument();+ });++ it("says the dashboard is not found when the URL has no dashboard id", async () => {+ setup({ dashboardSlug: "sales" });++ expect(await screen.findByText("Dashboard not found.")).toBeInTheDocument();+ expect(+ screen.queryByTestId("dashboard-contents-page"),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/constants.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/constants.tsnew file mode 100644index 00000000000..29104c3c029--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/constants.ts@@ -0,0 +1,7 @@+import type { CardType, SearchModel } from "metabase-types/api";++export const CARD_TYPE_MODEL = {+ question: "card",+ model: "dataset",+ metric: "metric",+} as const satisfies Record<CardType, SearchModel>;diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/index.tsnew file mode 100644index 00000000000..1f5161bd0d3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/index.ts@@ -0,0 +1 @@+export { DashboardContentsPage } from "./DashboardContentsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/use-content-columns.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/use-content-columns.tsxnew file mode 100644index 00000000000..76ba24c914b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/use-content-columns.tsx@@ -0,0 +1,70 @@+import { useMemo } from "react";+import { t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import { getTranslatedEntityName } from "metabase/common/utils/model-names";+import { useGetIcon } from "metabase/hooks/use-icon";+import { EntityNameCell, type TreeTableColumnDef } from "metabase/ui";+import type { Card, Dashboard } from "metabase-types/api";++import { ContentLocationCell } from "./ContentLocationCell";+import { CARD_TYPE_MODEL } from "./constants";++export function useContentColumns(+ dashboard: Pick<Dashboard, "id" | "name">,+): TreeTableColumnDef<Card>[] {+ const getIcon = useGetIcon();++ return useMemo(+ () => [+ {+ id: "name",+ header: t`Name`,+ accessorKey: "name",+ enableSorting: true,+ minWidth: 200,+ cell: ({ row }) => (+ <EntityNameCell+ data-testid="dashboard-content-name"+ icon={+ getIcon({+ model: CARD_TYPE_MODEL[row.original.type],+ display: row.original.display,+ }).name+ }+ name={row.original.name}+ />+ ),+ },+ {+ id: "type",+ header: t`Type`,+ accessorKey: "type",+ enableSorting: true,+ width: "auto",+ widthPadding: 20,+ cell: ({ row }) =>+ getTranslatedEntityName(CARD_TYPE_MODEL[row.original.type]),+ },+ {+ id: "location",+ header: t`Location`,+ minWidth: 160,+ cell: ({ row }) => (+ <ContentLocationCell item={row.original} dashboard={dashboard} />+ ),+ },+ {+ id: "updatedAt",+ header: t`Last edited at`,+ accessorKey: "updated_at",+ enableSorting: true,+ sortingFn: "datetime",+ width: "auto",+ widthPadding: 20,+ cell: ({ row }) => <DateTime value={row.original.updated_at} />,+ },+ ],+ [dashboard, getIcon],+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/utils.tsnew file mode 100644index 00000000000..da326ea1fc8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/utils.ts@@ -0,0 +1,42 @@+import _ from "underscore";++import * as Urls from "metabase/urls";+import type { Card, Collection, UnreadableCard } from "metabase-types/api";+import { isReadableCard } from "metabase-types/guards/dashboard";++import { isLibraryCollectionType } from "../../../utils";++/**+ * The dashboard's contents: each distinct saved card it shows, in order. Text,+ * heading, link, iframe and action dashcards show no card, so they are not+ * contents, and neither is a card the user cannot read.+ */+export function getDashboardContentItems(+ cards: readonly (Card | UnreadableCard)[],+): Card[] {+ return _.uniq(cards.filter(isReadableCard), (card) => card.id);+}++export function filterDashboardContentItems(+ items: Card[],+ searchQuery: string,+): Card[] {+ const query = searchQuery.trim().toLowerCase();+ if (query.length === 0) {+ return items;+ }+ return items.filter((item) => item.name.toLowerCase().includes(query));+}++/**+ * Where a content row opens: Data Studio for a metric saved in the Library,+ * the main app for everything else, including a metric saved outside it.+ */+export function getDashboardContentItemUrl(+ item: Card,+ collectionType: Collection["type"],+): string {+ const isLibraryMetric =+ item.type === "metric" && isLibraryCollectionType(collectionType);+ return isLibraryMetric ? Urls.dataStudioMetric(item.id) : Urls.card(item);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/utils.unit.spec.tsnew file mode 100644index 00000000000..03a0bf13fca--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardContentsPage/utils.unit.spec.ts@@ -0,0 +1,71 @@+import type { UnreadableCard } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks";++import {+ filterDashboardContentItems,+ getDashboardContentItemUrl,+ getDashboardContentItems,+} from "./utils";++const ORDERS = createMockCard({ id: 1, name: "Orders" });+const REVENUE = createMockCard({ id: 2, name: "Revenue", type: "metric" });+const CUSTOMERS = createMockCard({ id: 3, name: "Customers", type: "model" });++describe("getDashboardContentItems", () => {+ it("returns each card once, in order", () => {+ expect(+ getDashboardContentItems([ORDERS, REVENUE, ORDERS, CUSTOMERS, REVENUE]),+ ).toEqual([ORDERS, REVENUE, CUSTOMERS]);+ });++ it("skips cards the user cannot read, which the API sends as a bare id", () => {+ const unreadableCard: UnreadableCard = { id: 4 };++ expect(+ getDashboardContentItems([+ unreadableCard,+ REVENUE,+ ORDERS,+ unreadableCard,+ ]),+ ).toEqual([REVENUE, ORDERS]);+ });+});++describe("filterDashboardContentItems", () => {+ const items = [ORDERS, REVENUE, CUSTOMERS];++ it("matches names case-insensitively", () => {+ expect(filterDashboardContentItems(items, " rEv ")).toEqual([REVENUE]);+ });++ it("returns every item for a blank query", () => {+ expect(filterDashboardContentItems(items, " ")).toEqual(items);+ });+});++describe("getDashboardContentItemUrl", () => {+ it("opens a metric saved in the Library in Data Studio", () => {+ expect(getDashboardContentItemUrl(REVENUE, "library-metrics")).toBe(+ "/data-studio/library/metrics/2",+ );+ });++ it("opens a metric saved outside the Library in the main app", () => {+ expect(getDashboardContentItemUrl(REVENUE, undefined)).toBe(+ "/metric/2-revenue",+ );+ expect(getDashboardContentItemUrl(REVENUE, "instance-analytics")).toBe(+ "/metric/2-revenue",+ );+ });++ it("opens questions and models in the main app, even in the Library", () => {+ expect(getDashboardContentItemUrl(ORDERS, undefined)).toBe(+ "/question/1-orders",+ );+ expect(getDashboardContentItemUrl(CUSTOMERS, "library-data")).toBe(+ "/model/3-customers",+ );+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/DashboardDependenciesPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/DashboardDependenciesPage.tsxnew file mode 100644index 00000000000..924e446ce2e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/DashboardDependenciesPage.tsx@@ -0,0 +1,25 @@+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { Outlet } from "metabase/router";+import { Card } from "metabase/ui";+import * as Urls from "metabase/urls";++import { DashboardPageShell } from "../../components/DashboardPageShell";++export function DashboardDependenciesPage() {+ return (+ <DashboardPageShell>+ {(dashboard) => (+ <PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider+ value={{+ baseUrl: Urls.dataStudioDashboardDependencies(dashboard.id),+ defaultEntry: { id: dashboard.id, type: "dashboard" },+ }}+ >+ <Card p={0} withBorder flex={1}>+ <Outlet />+ </Card>+ </PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>+ )}+ </DashboardPageShell>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/DashboardDependenciesPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/DashboardDependenciesPage.unit.spec.tsxnew file mode 100644index 00000000000..6461479067f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/DashboardDependenciesPage.unit.spec.tsx@@ -0,0 +1,77 @@+import userEvent from "@testing-library/user-event";++import {+ setupCollectionByIdEndpoint,+ setupDashboardEndpoints,+} from "__support__/server-mocks";+import { setupListSubscriptionsEndpoint } from "__support__/server-mocks/pulse";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";+import { Route } from "metabase/router";+import {+ createMockCollection,+ createMockDashboard,+} from "metabase-types/api/mocks";++import { DashboardDependenciesPage } from "./DashboardDependenciesPage";++jest.mock("../../analytics");++const DASHBOARDS_COLLECTION = createMockCollection({+ id: 2,+ name: "Dashboards",+ type: "library-dashboards",+});++const DASHBOARD = createMockDashboard({+ id: 10,+ name: "Sales overview",+ collection_id: DASHBOARDS_COLLECTION.id,+});++const DEPENDENCIES_PATH = `/data-studio/dashboards/${DASHBOARD.id}/dependencies`;++type SetupOpts = {+ search: string;+};++function setup({ search }: SetupOpts) {+ setupDashboardEndpoints(DASHBOARD);+ setupListSubscriptionsEndpoint([]);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection(ROOT_COLLECTION), DASHBOARDS_COLLECTION],+ });++ const { router } = renderWithProviders(+ <>+ <Route+ path="/data-studio/dashboards/:dashboardId/dependencies"+ element={<DashboardDependenciesPage />}+ />+ <Route path="/dashboard/:slug" element={null} />+ </>,+ {+ withRouter: true,+ initialRoute: `${DEPENDENCIES_PATH}${search}`,+ },+ );++ return { router };+}++describe("DashboardDependenciesPage", () => {+ it("opens the dashboard editor and asks it to return to this graph", async () => {+ const search = "?id=1&type=card";+ const { router } = setup({ search });++ await userEvent.click(await screen.findByRole("button", { name: /Edit/ }));++ await waitFor(() =>+ expect(router?.location).toMatchObject({+ pathname: "/dashboard/10-sales-overview",+ hash: "#edit",+ state: { returnTo: `${DEPENDENCIES_PATH}${search}` },+ }),+ );+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/index.tsnew file mode 100644index 00000000000..3dd7198a926--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardDependenciesPage/index.ts@@ -0,0 +1 @@+export { DashboardDependenciesPage } from "./DashboardDependenciesPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/AutoApplyFiltersStat.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/AutoApplyFiltersStat.tsxnew file mode 100644index 00000000000..f7fdc3cd91f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/AutoApplyFiltersStat.tsx@@ -0,0 +1,70 @@+import type { ChangeEvent } from "react";+import { t } from "ttag";++import { useUpdateDashboardMutation } from "metabase/api";+import { getErrorMessage } from "metabase/api/utils";+import { useMetadataToasts } from "metabase/common/hooks";+import { useUniqueId } from "metabase/common/hooks/use-unique-id";+import { trackAutoApplyFiltersDisabled } from "metabase/dashboard/analytics";+import { Switch } from "metabase/ui";+import type { Dashboard } from "metabase-types/api";++import { useCanEditDashboard } from "../../../hooks/use-can-edit-dashboard";++import { DashboardStat } from "./DashboardStat";++type AutoApplyFiltersStatProps = {+ dashboard: Pick<+ Dashboard,+ "id" | "auto_apply_filters" | "can_write" | "archived"+ >;+};++export function AutoApplyFiltersStat({ dashboard }: AutoApplyFiltersStatProps) {+ const labelId = useUniqueId();+ const canEdit = useCanEditDashboard(dashboard);+ const [updateDashboard, { isLoading: isUpdating }] =+ useUpdateDashboardMutation();+ const { sendErrorToast } = useMetadataToasts();++ if (!canEdit) {+ return (+ <DashboardStat+ label={t`Auto-apply filters`}+ value={dashboard.auto_apply_filters ? t`On` : t`Off`}+ />+ );+ }++ const handleChange = async (event: ChangeEvent<HTMLInputElement>) => {+ const isEnabled = event.currentTarget.checked;+ try {+ await updateDashboard({+ id: dashboard.id,+ auto_apply_filters: isEnabled,+ }).unwrap();+ if (!isEnabled) {+ trackAutoApplyFiltersDisabled(dashboard.id);+ }+ } catch (error) {+ sendErrorToast(+ getErrorMessage(error, t`Failed to update auto-apply filters`),+ );+ }+ };++ return (+ <DashboardStat+ label={t`Auto-apply filters`}+ labelId={labelId}+ value={+ <Switch+ aria-labelledby={labelId}+ checked={dashboard.auto_apply_filters}+ disabled={isUpdating}+ onChange={handleChange}+ />+ }+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/CachePolicyStat.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/CachePolicyStat.tsxnew file mode 100644index 00000000000..327a71267af--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/CachePolicyStat.tsx@@ -0,0 +1,82 @@+import { useDisclosure } from "@mantine/hooks";+import { t } from "ttag";+import _ from "underscore";++import { useCacheConfigs } from "metabase/admin/performance/hooks/useCacheConfigs";+import { getShortStrategyLabel } from "metabase/admin/performance/utils";+import { useUniqueId } from "metabase/common/hooks/use-unique-id";+import { PLUGIN_CACHING } from "metabase/plugins";+import { UnstyledButton } from "metabase/ui";+import type { CacheableDashboard, CacheableModel } from "metabase-types/api";++import { DashboardStat } from "./DashboardStat";++const CACHE_CONFIG_MODELS: CacheableModel[] = ["dashboard"];++type CachePolicyStatProps = {+ dashboard: CacheableDashboard;+};++/** The dashboard's caching policy, which opens the caching form unless the dashboard is in the trash */+export function CachePolicyStat({ dashboard }: CachePolicyStatProps) {+ const labelId = useUniqueId();+ const [isFormOpen, { open: openForm, close: closeForm }] =+ useDisclosure(false);+ const { configs, isLoading, error } = useCacheConfigs({+ model: CACHE_CONFIG_MODELS,+ id: dashboard.id,+ });++ if (isLoading) {+ return null;+ }++ if (error != null) {+ return (+ <DashboardStat label={t`Caching policy`} value={t`Failed to load`} />+ );+ }++ const config = _.findWhere(configs ?? [], {+ model: "dashboard",+ model_id: dashboard.id,+ });+ const strategyLabel =+ getShortStrategyLabel(config?.strategy, "dashboard") ?? t`Default`;++ if (dashboard.archived) {+ return <DashboardStat label={t`Caching policy`} value={strategyLabel} />;+ }++ return (+ <>+ <DashboardStat+ label={t`Caching policy`}+ labelId={labelId}+ value={+ <UnstyledButton+ c="core-brand"+ fw={600}+ aria-labelledby={labelId}+ onClick={openForm}+ >+ {strategyLabel}+ </UnstyledButton>+ }+ />+ {/* Mounted only while open: the form's route-leave guard keeps its+ dirty state, which would block every later navigation once closed */}+ {isFormOpen && (+ <PLUGIN_CACHING.SidebarCacheForm+ item={dashboard}+ model="dashboard"+ isOpen+ // Opened on its own, so there is no settings page to go back to+ withBackButton={false}+ onClose={closeForm}+ onBack={closeForm}+ />+ )}+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardInfo.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardInfo.tsxnew file mode 100644index 00000000000..f38e6a95df3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardInfo.tsx@@ -0,0 +1,106 @@+import type { ReactNode } from "react";+import { t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import { Markdown } from "metabase/common/components/Markdown";+import { useNumberFormatter } from "metabase/common/hooks/use-number-formatter";+import { isDashboardCacheable } from "metabase/dashboard/utils";+import { PLUGIN_CACHING } from "metabase/plugins";+import { Box, Card, Group, Icon, Stack, Text } from "metabase/ui";+import { getUserName } from "metabase/utils/user";+import type { Dashboard, IconName } from "metabase-types/api";++import { getLoadingTimeMs } from "../utils";++import { AutoApplyFiltersStat } from "./AutoApplyFiltersStat";+import { CachePolicyStat } from "./CachePolicyStat";+import { DashboardStat } from "./DashboardStat";++type DashboardInfoProps = {+ dashboard: Dashboard;+};++export function DashboardInfo({ dashboard }: DashboardInfoProps) {+ // The API leaves it out for a dashboard without revisions+ const lastEditInfo: Dashboard["last-edit-info"] | undefined =+ dashboard["last-edit-info"];+ const canSeeCachePolicy =+ dashboard.can_set_cache_policy && PLUGIN_CACHING.isGranularCachingEnabled();++ return (+ <Stack gap={0} align="stretch" data-testid="dashboard-info">+ <Box p="xl">+ {dashboard.description ? (+ <Markdown>{dashboard.description}</Markdown>+ ) : (+ <Text c="text-secondary">{t`No description`}</Text>+ )}+ </Box>+ <Card mx="xl" bg="background_page-secondary" shadow="none" radius="lg">+ {lastEditInfo && (+ <DashboardInfoItem+ icon="pencil"+ value={<DateTime value={lastEditInfo.timestamp} />}+ label={t`Last edited by ${getUserName(lastEditInfo)}`}+ />+ )}+ {dashboard.creator && (+ <DashboardInfoItem+ icon="person"+ value={getUserName(dashboard.creator)}+ label={t`Owner`}+ />+ )}+ </Card>+ <Card mx="xl" my="xl" shadow="none">+ <LoadingTimeStat dashboard={dashboard} />+ {canSeeCachePolicy && isDashboardCacheable(dashboard) && (+ <CachePolicyStat dashboard={dashboard} />+ )}+ <AutoApplyFiltersStat dashboard={dashboard} />+ </Card>+ </Stack>+ );+}++type DashboardInfoItemProps = {+ icon: IconName;+ value: ReactNode;+ label: string;+};++function DashboardInfoItem({ icon, value, label }: DashboardInfoItemProps) {+ return (+ <Card.Section withBorder p="lg">+ <Group gap="sm" mb="xxs" wrap="nowrap">+ <Icon name={icon} c="core-brand" />+ <Text size="md" fw={600} lh="1rem">+ {value}+ </Text>+ </Group>+ <Text size="sm" c="text-secondary" lh="1rem" ml="xl">+ {label}+ </Text>+ </Card.Section>+ );+}++type LoadingTimeStatProps = {+ dashboard: Pick<Dashboard, "dashcards">;+};++function LoadingTimeStat({ dashboard }: LoadingTimeStatProps) {+ const formatNumber = useNumberFormatter({ decimals: 1 });+ const loadingTimeMs = getLoadingTimeMs(dashboard);++ if (loadingTimeMs == null) {+ return null;+ }++ return (+ <DashboardStat+ label={t`Avg loading time (s)`}+ value={formatNumber(loadingTimeMs / 1000)}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardInfo.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardInfo.unit.spec.tsxnew file mode 100644index 00000000000..a663b05c16c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardInfo.unit.spec.tsx@@ -0,0 +1,263 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupDashboardEndpoints,+ setupUpdateDashboardEndpointWithError,+} from "__support__/server-mocks";+import {+ setupPerformanceEndpoints,+ setupPerformanceEndpointsError,+} from "__support__/server-mocks/performance";+import { mockSettings } from "__support__/settings";+import { createMockState } from "__support__/state";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { selectCacheStrategy } from "metabase/admin/performance/components/test-utils";+import { UndoListing } from "metabase/common/components/UndoListing";+import { reinitialize } from "metabase/plugins";+import { checkNotNull } from "metabase/utils/types";+import type { Dashboard } from "metabase-types/api";+import {+ createMockDashboard,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { DashboardInfo } from "./DashboardInfo";++type SetupOpts = {+ dashboard?: Dashboard;+ hasCacheConfigError?: boolean;+ hasUpdateError?: boolean;+ hasGranularCaching?: boolean;+ isRemoteSyncReadOnly?: boolean;+};++function setup({+ dashboard = createMockDashboard({ id: 10, can_set_cache_policy: true }),+ hasCacheConfigError = false,+ hasUpdateError = false,+ hasGranularCaching = true,+ isRemoteSyncReadOnly = false,+}: SetupOpts = {}) {+ const settings = mockSettings({+ "token-features": createMockTokenFeatures({+ cache_granular_controls: hasGranularCaching,+ remote_sync: isRemoteSyncReadOnly,+ }),+ "remote-sync-enabled": isRemoteSyncReadOnly,+ "remote-sync-type": isRemoteSyncReadOnly ? "read-only" : undefined,+ });+ // A plugin enabled by an earlier test stays enabled until it is reset+ reinitialize();+ setupEnterpriseOnlyPlugin("caching");+ setupEnterpriseOnlyPlugin("remote_sync");+ if (hasCacheConfigError) {+ setupPerformanceEndpointsError();+ } else {+ setupPerformanceEndpoints([]);+ }+ if (hasUpdateError) {+ setupUpdateDashboardEndpointWithError(dashboard.id);+ } else {+ setupDashboardEndpoints(dashboard);+ }++ const { router } = renderWithProviders(+ <>+ <DashboardInfo dashboard={dashboard} />+ <UndoListing />+ </>,+ {+ storeInitialState: createMockState({ settings }),+ withRouter: true,+ initialRoute: "/data-studio/dashboards/10",+ },+ );++ return { router: checkNotNull(router) };+}++function getLastUpdateBody(): unknown {+ return fetchMock.callHistory.lastCall("path:/api/dashboard/10", {+ method: "PUT",+ })?.options.body;+}++describe("DashboardInfo", () => {+ it("shows who last edited the dashboard", async () => {+ setup();++ expect(await screen.findByText("Caching policy")).toBeInTheDocument();+ expect(screen.getByText("Last edited by John Doe")).toBeInTheDocument();+ });++ it("omits the last edit for a dashboard without revisions", async () => {+ setup({+ // The API leaves it out for a dashboard without revisions+ dashboard: createMockDashboard({+ id: 10,+ can_set_cache_policy: true,+ "last-edit-info": undefined,+ }),+ });++ expect(await screen.findByText("Caching policy")).toBeInTheDocument();+ expect(screen.queryByText(/Last edited by/)).not.toBeInTheDocument();+ });++ it("shows the default caching policy when the dashboard has none of its own", async () => {+ setup();++ expect(await screen.findByText("Caching policy")).toBeInTheDocument();+ expect(screen.getByText("Default")).toBeInTheDocument();+ });++ it("says when the caching policy cannot be loaded", async () => {+ setup({ hasCacheConfigError: true });++ expect(await screen.findByText("Failed to load")).toBeInTheDocument();+ expect(screen.queryByText("Default")).not.toBeInTheDocument();+ });++ describe("caching policy", () => {+ it("opens the caching form and shows the saved policy", async () => {+ setup();++ await userEvent.click(+ await screen.findByRole("button", { name: "Caching policy" }),+ );+ const form = await screen.findByTestId("sidesheet");+ expect(within(form).getByText("Caching settings")).toBeInTheDocument();+ expect(+ within(form).queryByRole("button", { name: /Caching settings/ }),+ ).not.toBeInTheDocument();++ await selectCacheStrategy(/Don.t cache/i);+ await userEvent.click(+ within(form).getByTestId("strategy-form-submit-button"),+ );++ expect(+ await screen.findByRole("button", { name: "Caching policy" }),+ ).toHaveTextContent("No caching");+ });++ it("lets the page navigate after the form saves", async () => {+ const { router } = setup();++ await userEvent.click(+ await screen.findByRole("button", { name: "Caching policy" }),+ );+ const form = await screen.findByTestId("sidesheet");+ await selectCacheStrategy(/Don.t cache/i);+ await userEvent.click(+ within(form).getByTestId("strategy-form-submit-button"),+ );+ await waitFor(() =>+ expect(screen.queryByTestId("sidesheet")).not.toBeInTheDocument(),+ );++ act(() => router.navigate("/dashboard/10#edit"));++ expect(router.location.pathname).toBe("/dashboard/10");+ });++ it("is read-only for a dashboard in the trash", async () => {+ setup({+ dashboard: createMockDashboard({+ id: 10,+ can_set_cache_policy: true,+ archived: true,+ }),+ });++ expect(await screen.findByText("Default")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Caching policy" }),+ ).not.toBeInTheDocument();+ });++ it.each([+ {+ name: "the user cannot set the cache policy",+ opts: {+ dashboard: createMockDashboard({+ id: 10,+ can_set_cache_policy: false,+ }),+ },+ },+ {+ name: "granular caching is off",+ opts: { hasGranularCaching: false },+ },+ ])("is hidden when $name", async ({ opts }) => {+ setup(opts);++ expect(await screen.findByText("Auto-apply filters")).toBeInTheDocument();+ expect(screen.queryByText("Caching policy")).not.toBeInTheDocument();+ });+ });++ describe("auto-apply filters", () => {+ it("saves the new value", async () => {+ setup();++ await userEvent.click(+ await screen.findByRole("switch", { name: "Auto-apply filters" }),+ );++ await waitFor(() =>+ expect(getLastUpdateBody()).toBe(+ JSON.stringify({ auto_apply_filters: false }),+ ),+ );+ expect(+ fetchMock.callHistory.calls("path:/api/dashboard/10", {+ method: "PUT",+ }),+ ).toHaveLength(1);+ });++ it("shows an error when the change cannot be saved", async () => {+ setup({ hasUpdateError: true });++ await userEvent.click(+ await screen.findByRole("switch", { name: "Auto-apply filters" }),+ );++ const toast = await screen.findByRole("status");+ expect(+ within(toast).getByText("Failed to update auto-apply filters"),+ ).toBeInTheDocument();+ });++ it.each([+ {+ name: "the user cannot write the dashboard",+ opts: { dashboard: createMockDashboard({ id: 10, can_write: false }) },+ },+ {+ name: "the dashboard is in the trash",+ opts: { dashboard: createMockDashboard({ id: 10, archived: true }) },+ },+ {+ name: "remote sync is read-only",+ opts: { isRemoteSyncReadOnly: true },+ },+ ])("is read-only when $name", async ({ opts }) => {+ setup(opts);++ expect(await screen.findByText("Auto-apply filters")).toBeInTheDocument();+ expect(screen.getByText("On")).toBeInTheDocument();+ expect(screen.queryByRole("switch")).not.toBeInTheDocument();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardStat.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardStat.tsxnew file mode 100644index 00000000000..ce0e0a985cc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/DashboardStat.tsx@@ -0,0 +1,25 @@+import type { ReactNode } from "react";++import { Card, Flex, Text } from "metabase/ui";++type DashboardStatProps = {+ label: string;+ /** Lets a control in `value` take the label as its name */+ labelId?: string;+ value: ReactNode;+};++export function DashboardStat({ label, labelId, value }: DashboardStatProps) {+ return (+ <Card.Section withBorder py="md" px="lg">+ <Flex justify="space-between" align="center" gap="md">+ <Text id={labelId} size="md" c="text-secondary">+ {label}+ </Text>+ <Text component="div" size="md" fw={600}>+ {value}+ </Text>+ </Flex>+ </Card.Section>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/index.tsnew file mode 100644index 00000000000..2913ecce72b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardInfo/index.ts@@ -0,0 +1 @@+export { DashboardInfo } from "./DashboardInfo";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.module.cssnew file mode 100644index 00000000000..8721e23becf--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.module.css@@ -0,0 +1,16 @@+.preview {+ background-color: var(--mb-color-background_page-primary);+ border: 1px solid var(--mb-color-border-neutral);+ border-top-left-radius: var(--default-border-radius);+ border-bottom-left-radius: var(--default-border-radius);+ overflow: auto;+}++.infoPanel {+ background-color: var(--mb-color-background_page-primary);+ border: 1px solid var(--mb-color-border-neutral);+ border-left: none;+ border-top-right-radius: var(--default-border-radius);+ border-bottom-right-radius: var(--default-border-radius);+ overflow: auto;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.tsxnew file mode 100644index 00000000000..ff2f79f75ff--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.tsx@@ -0,0 +1,26 @@+import { Box, Flex, Stack } from "metabase/ui";++import { DashboardPageShell } from "../../components/DashboardPageShell";++import { DashboardInfo } from "./DashboardInfo";+import S from "./DashboardOverviewPage.module.css";+import { DashboardPreview } from "./DashboardPreview";++const INFO_PANEL_WIDTH_PX = 360;++export function DashboardOverviewPage() {+ return (+ <DashboardPageShell data-testid="dashboard-overview-page">+ {(dashboard) => (+ <Flex flex={1} gap={0} mih={0}>+ <Box className={S.preview} flex={1} miw={0}>+ <DashboardPreview dashboard={dashboard} />+ </Box>+ <Stack className={S.infoPanel} flex={`0 0 ${INFO_PANEL_WIDTH_PX}px`}>+ <DashboardInfo dashboard={dashboard} />+ </Stack>+ </Flex>+ )}+ </DashboardPageShell>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.unit.spec.tsxnew file mode 100644index 00000000000..1089393dfc0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardOverviewPage.unit.spec.tsx@@ -0,0 +1,231 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupCollectionByIdEndpoint,+ setupDashboardEndpoints,+ setupDashboardNotFoundEndpoint,+ setupDashboardQueryMetadataEndpoint,+} from "__support__/server-mocks";+import { setupListSubscriptionsEndpoint } from "__support__/server-mocks/pulse";+import {+ renderWithProviders,+ screen,+ waitFor,+ waitForLoaderToBeRemoved,+ within,+} from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";+import { Route } from "metabase/router";+import type { Dashboard } from "metabase-types/api";+import {+ createMockCollection,+ createMockDashboard,+ createMockDashboardQueryMetadata,+} from "metabase-types/api/mocks";++import { trackDataStudioDashboardEditStarted } from "../../analytics";++import { DashboardOverviewPage } from "./DashboardOverviewPage";++jest.mock("../../analytics");++const LIBRARY_COLLECTION = createMockCollection({+ id: 1,+ name: "Library",+ type: "library",+});++const DASHBOARDS_COLLECTION = createMockCollection({+ id: 2,+ name: "Dashboards",+ type: "library-dashboards",+});++const SALES_COLLECTION = createMockCollection({+ id: 3,+ name: "Sales",+ type: "library-dashboards",+ effective_ancestors: [LIBRARY_COLLECTION, DASHBOARDS_COLLECTION],+});++type SetupOpts = {+ dashboard?: Partial<Dashboard>;+ isNotFound?: boolean;+};++function setup({ dashboard: dashboardOpts, isNotFound = false }: SetupOpts) {+ const dashboard = createMockDashboard({+ id: 10,+ name: "Sales overview",+ collection_id: SALES_COLLECTION.id,+ dashcards: [],+ ...dashboardOpts,+ });+ setupListSubscriptionsEndpoint([]);+ if (isNotFound) {+ setupDashboardNotFoundEndpoint(dashboard);+ } else {+ setupDashboardEndpoints(dashboard);+ }+ setupDashboardQueryMetadataEndpoint(+ dashboard,+ createMockDashboardQueryMetadata(),+ );+ setupCollectionByIdEndpoint({+ collections: [+ createMockCollection(ROOT_COLLECTION),+ LIBRARY_COLLECTION,+ DASHBOARDS_COLLECTION,+ SALES_COLLECTION,+ ],+ });++ const { router } = renderWithProviders(+ <>+ <Route+ path="/data-studio/dashboards/:dashboardId"+ element={<DashboardOverviewPage />}+ />+ <Route path="/dashboard/:slug" element={null} />+ </>,+ {+ withRouter: true,+ initialRoute: `/data-studio/dashboards/${dashboard.id}`,+ },+ );++ return { router };+}++describe("DashboardOverviewPage", () => {+ it("shows a loader, then the dashboard name and its folder breadcrumbs", async () => {+ setup({});++ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ await waitForLoaderToBeRemoved();+ const header = await screen.findByTestId("dashboard-pane-header");+ expect(+ within(header).getByRole("link", { name: "Dashboards" }),+ ).toHaveAttribute("href", "/data-studio/dashboards");+ expect(+ await within(header).findByRole("link", { name: "Sales" }),+ ).toBeInTheDocument();+ // The title and the last breadcrumb+ expect(within(header).getAllByText("Sales overview")).toHaveLength(2);+ expect(screen.getByTestId("dashboard-preview")).toBeInTheDocument();+ });++ it("fetches the dashboard once for the header and the preview", async () => {+ setup({});++ expect(await screen.findByTestId("dashboard-preview")).toBeInTheDocument();+ await waitFor(() =>+ expect(+ fetchMock.callHistory.called("path:/api/dashboard/10/query_metadata"),+ ).toBe(true),+ );+ expect(+ fetchMock.callHistory.calls("path:/api/dashboard/10", { method: "GET" }),+ ).toHaveLength(1);+ });++ it("shows the description in the info sidebar", async () => {+ setup({ dashboard: { description: "Revenue by region" } });++ const info = await screen.findByTestId("dashboard-info");+ expect(within(info).getByText("Revenue by region")).toBeInTheDocument();+ expect(within(info).queryByText("No description")).not.toBeInTheDocument();+ });++ it("says when the dashboard has no description", async () => {+ setup({ dashboard: { description: null } });++ const info = await screen.findByTestId("dashboard-info");+ expect(within(info).getByText("No description")).toBeInTheDocument();+ });++ it("hides Edit when the user cannot write the dashboard", async () => {+ setup({ dashboard: { can_write: false } });++ expect(+ await screen.findByRole("link", { name: /View/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Edit/ }),+ ).not.toBeInTheDocument();+ });++ it("hides Edit and shows the trash banner when the dashboard is archived", async () => {+ setup({ dashboard: { archived: true, can_restore: true } });++ expect(await screen.findByTestId("archive-banner")).toHaveTextContent(+ "This dashboard is in the trash.",+ );+ expect(+ await screen.findByRole("link", { name: /View/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Edit/ }),+ ).not.toBeInTheDocument();+ });++ it("restores an archived dashboard from the trash banner", async () => {+ setup({ dashboard: { archived: true, can_restore: true } });++ const banner = await screen.findByTestId("archive-banner");+ await userEvent.click(within(banner).getByText("Restore"));++ await waitFor(() =>+ expect(+ fetchMock.callHistory.called("path:/api/dashboard/10", {+ method: "PUT",+ }),+ ).toBe(true),+ );+ const body: unknown = fetchMock.callHistory.lastCall(+ "path:/api/dashboard/10",+ { method: "PUT" },+ )?.options.body;+ expect(body).toBe(JSON.stringify({ archived: false }));+ });++ it("does not show the trash banner for a dashboard that is not archived", async () => {+ setup({});++ expect(+ await screen.findByRole("button", { name: /Edit/ }),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("archive-banner")).not.toBeInTheDocument();+ });++ it("opens the dashboard editor and asks it to return here", async () => {+ const { router } = setup({});++ await userEvent.click(await screen.findByRole("button", { name: /Edit/ }));++ await waitFor(() =>+ expect(router?.location).toMatchObject({+ pathname: "/dashboard/10-sales-overview",+ hash: "#edit",+ state: { returnTo: "/data-studio/dashboards/10" },+ }),+ );+ expect(+ jest.mocked(trackDataStudioDashboardEditStarted),+ ).toHaveBeenCalledTimes(1);+ expect(+ jest.mocked(trackDataStudioDashboardEditStarted),+ ).toHaveBeenCalledWith(10);+ });++ it("shows an error when the dashboard cannot be loaded", async () => {+ setup({ isNotFound: true });++ await waitForLoaderToBeRemoved();+ expect(screen.getByText("An error occurred")).toBeInTheDocument();+ expect(+ screen.queryByTestId("dashboard-overview-page"),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardPreview.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardPreview.tsxnew file mode 100644index 00000000000..23600cbc9ab--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardPreview.tsx@@ -0,0 +1,76 @@+import { useEffect } from "react";++import { setAutoApplyFilters } from "metabase/dashboard/actions";+import { Dashboard } from "metabase/dashboard/components/Dashboard";+import {+ DashboardContextProvider,+ useDashboardContext,+} from "metabase/dashboard/context";+import { useDispatch } from "metabase/redux";+import { Box, Stack } from "metabase/ui";+import type { Dashboard as DashboardType } from "metabase-types/api";++type DashboardPreviewProps = {+ dashboard: DashboardType;+};++export function DashboardPreview({ dashboard }: DashboardPreviewProps) {+ return (+ <DashboardContextProvider+ dashboardId={dashboard.id}+ prefetchedDashboard={dashboard}+ navigateToNewCardFromDashboard={null}+ dashboardActions={null}+ dashcardMenu={null}+ downloadsEnabled={{ pdf: false, results: false }}+ >+ <DashboardPreviewContent dashboard={dashboard} />+ </DashboardContextProvider>+ );+}++type DashboardPreviewContentProps = {+ dashboard: Pick<DashboardType, "id" | "auto_apply_filters">;+};++function DashboardPreviewContent({+ dashboard: hostDashboard,+}: DashboardPreviewContentProps) {+ const { dashboard, parameters, tabs } = useDashboardContext();+ const hasTabs = dashboard != null && tabs.length > 1;+ const hasParameters = parameters.length > 0;++ useAutoApplyFiltersSync(hostDashboard);++ return (+ <Stack gap="sm" p="sm" data-testid="dashboard-preview">+ {hasTabs && <Dashboard.Tabs />}+ {hasParameters && <Dashboard.ParametersList />}+ {/* A fixed-width grid centers itself with auto margins, which collapse to zero width as a flex item */}+ <Box>+ <Dashboard.Grid />+ </Box>+ </Stack>+ );+}++/**+ * The provider loads the dashboard once per id, so a saved auto-apply+ * filters setting reaches the loaded dashboard through here, without+ * reloading its cards or losing the filter values and the selected tab.+ */+function useAutoApplyFiltersSync(+ hostDashboard: Pick<DashboardType, "id" | "auto_apply_filters">,+) {+ const dispatch = useDispatch();+ const { dashboard } = useDashboardContext();+ const isOutOfSync =+ dashboard?.id === hostDashboard.id &&+ dashboard.auto_apply_filters !== hostDashboard.auto_apply_filters;++ useEffect(() => {+ if (isOutOfSync) {+ dispatch(setAutoApplyFilters(hostDashboard.auto_apply_filters));+ }+ }, [dispatch, isOutOfSync, hostDashboard.auto_apply_filters]);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardPreview.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardPreview.unit.spec.tsxnew file mode 100644index 00000000000..65ac9e94845--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/DashboardPreview.unit.spec.tsx@@ -0,0 +1,152 @@+import fetchMock from "fetch-mock";++import {+ setupDashboardQueryMetadataEndpoint,+ setupDatabasesEndpoints,+} from "__support__/server-mocks";+import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";+import { getIsAutoApplyFilters } from "metabase/dashboard/selectors";+import { defer } from "metabase/utils/promise";+import { registerVisualizations } from "metabase/visualizations/register";+import type {+ Dashboard,+ DashboardQueryMetadata,+ Dataset,+} from "metabase-types/api";+import {+ createMockCard,+ createMockDashboard,+ createMockDashboardCard,+ createMockDashboardQueryMetadata,+ createMockDatabase,+ createMockDataset,+} from "metabase-types/api/mocks";++import { DashboardPreview } from "./DashboardPreview";++registerVisualizations();++const DATABASE = createMockDatabase();++function createDashboard(id: number, cardName: string): Dashboard {+ const card = createMockCard({ id, name: cardName });+ return createMockDashboard({+ id,+ name: `Dashboard ${id}`,+ dashcards: [+ createMockDashboardCard({ id, dashboard_id: id, card_id: id, card }),+ ],+ });+}++const SALES = createDashboard(1, "Revenue by month");+const ORDERS = createDashboard(2, "Orders by state");++type SetupOpts = {+ pendingMetadataDashboard?: Dashboard;+ pendingQueryDashboard?: Dashboard;+};++function setup({+ pendingMetadataDashboard,+ pendingQueryDashboard,+}: SetupOpts = {}) {+ const pendingMetadata = defer<DashboardQueryMetadata>();+ const pendingQuery = defer<Dataset>();+ setupDatabasesEndpoints([DATABASE]);+ [SALES, ORDERS].forEach((dashboard) => {+ const [dashcard] = dashboard.dashcards;+ if (dashboard === pendingMetadataDashboard) {+ fetchMock.get(+ `path:/api/dashboard/${dashboard.id}/query_metadata`,+ pendingMetadata.promise,+ );+ } else {+ setupDashboardQueryMetadataEndpoint(+ dashboard,+ createMockDashboardQueryMetadata({ databases: [DATABASE] }),+ );+ }+ if (dashboard === pendingQueryDashboard) {+ fetchMock.post(+ `path:/api/dashboard/${dashboard.id}/dashcard/${dashcard.id}/card/${dashcard.card_id}/query`,+ pendingQuery.promise,+ );+ } else {+ setupDashcardQueryEndpoints(dashboard.id, dashcard, createMockDataset());+ }+ });++ const view = renderWithProviders(<DashboardPreview dashboard={SALES} />);+ const showDashboard = (dashboard: Dashboard) =>+ view.rerender(<DashboardPreview dashboard={dashboard} />);++ return { ...view, pendingMetadata, pendingQuery, showDashboard };+}++async function settle() {+ await act(() => fetchMock.callHistory.flush(true));+}++describe("DashboardPreview", () => {+ it("keeps showing the current dashboard when the previous one finishes loading later", async () => {+ const { pendingMetadata, showDashboard } = setup({+ pendingMetadataDashboard: SALES,+ });++ showDashboard(ORDERS);+ expect(await screen.findByText("Orders by state")).toBeInTheDocument();++ pendingMetadata.resolve(+ createMockDashboardQueryMetadata({ databases: [DATABASE] }),+ );+ await settle();++ expect(screen.getByText("Orders by state")).toBeInTheDocument();+ expect(screen.queryByText("Revenue by month")).not.toBeInTheDocument();+ });++ it("leaves no dashboard behind when it unmounts before the dashboard loads", async () => {+ const { pendingMetadata, store, unmount } = setup({+ pendingMetadataDashboard: SALES,+ });++ unmount();+ pendingMetadata.resolve(+ createMockDashboardQueryMetadata({ databases: [DATABASE] }),+ );+ await settle();++ expect(store.getState().dashboard.dashboardId).toBeNull();+ });++ it("follows a saved change to auto-apply filters", async () => {+ const { showDashboard, store } = setup();+ expect(await screen.findByText("Revenue by month")).toBeInTheDocument();+ expect(getIsAutoApplyFilters(store.getState())).toBe(true);++ showDashboard({ ...SALES, auto_apply_filters: false });++ await waitFor(() =>+ expect(getIsAutoApplyFilters(store.getState())).toBe(false),+ );+ expect(store.getState().dashboard.dashboardId).toBe(SALES.id);+ });++ it("drops the previous dashboard's card results when switching dashboards mid-load", async () => {+ const { pendingQuery, showDashboard, store } = setup({+ pendingQueryDashboard: SALES,+ });+ expect(await screen.findByText("Revenue by month")).toBeInTheDocument();++ showDashboard(ORDERS);+ expect(await screen.findByText("Orders by state")).toBeInTheDocument();+ pendingQuery.resolve(createMockDataset());+ await settle();++ expect(store.getState().dashboard.dashcardData).not.toHaveProperty(+ String(SALES.dashcards[0].id),+ );+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/index.tsnew file mode 100644index 00000000000..0f7e511f8d5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/index.ts@@ -0,0 +1 @@+export { DashboardOverviewPage } from "./DashboardOverviewPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/utils.tsnew file mode 100644index 00000000000..7112783fffe--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/utils.ts@@ -0,0 +1,16 @@+import type { Dashboard } from "metabase-types/api";+import { isReadableCard } from "metabase-types/guards/dashboard";++import { getDashcardCards } from "../../utils";++/** Dashcards query in parallel, so the dashboard loads as slowly as its slowest query */+export function getLoadingTimeMs(+ dashboard: Pick<Dashboard, "dashcards">,+): number | null {+ const durations = getDashcardCards(dashboard)+ .filter(isReadableCard)+ .map((card) => card.query_average_duration)+ .filter((duration) => duration != null);++ return durations.length > 0 ? Math.max(...durations) : null;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/utils.unit.spec.tsnew file mode 100644index 00000000000..85575e587e6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardOverviewPage/utils.unit.spec.ts@@ -0,0 +1,42 @@+import {+ createMockCard,+ createMockDashboard,+ createMockDashboardCard,+ createMockHeadingDashboardCard,+} from "metabase-types/api/mocks";++import { getLoadingTimeMs } from "./utils";++describe("getLoadingTimeMs", () => {+ it("returns the slowest query across cards and series", () => {+ const dashboard = createMockDashboard({+ dashcards: [+ createMockDashboardCard({+ id: 1,+ card: createMockCard({ id: 1, query_average_duration: 120 }),+ series: [createMockCard({ id: 2, query_average_duration: 900 })],+ }),+ createMockDashboardCard({+ id: 2,+ card: createMockCard({ id: 3, query_average_duration: 300 }),+ }),+ createMockHeadingDashboardCard({ id: 3 }),+ ],+ });++ expect(getLoadingTimeMs(dashboard)).toBe(900);+ });++ it("returns null when no query has run", () => {+ const dashboard = createMockDashboard({+ dashcards: [+ createMockDashboardCard({+ card: createMockCard({ query_average_duration: null }),+ }),+ createMockHeadingDashboardCard(),+ ],+ });++ expect(getLoadingTimeMs(dashboard)).toBeNull();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/DashboardSubscriptionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/DashboardSubscriptionsPage.tsxnew file mode 100644index 00000000000..8f8732d37e7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/DashboardSubscriptionsPage.tsx@@ -0,0 +1,190 @@+import { useMemo, useState } from "react";+import { t } from "ttag";++import { ForwardRefLink, Link } from "metabase/common/components/Link";+import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";+import { getUserIsAdmin } from "metabase/current-user";+import { useCanManageDashboardSubscriptions } from "metabase/dashboard/hooks";+import { useSelector } from "metabase/redux";+import {+ Button,+ Card,+ Group,+ Icon,+ Stack,+ Text,+ TextInput,+ TreeTable,+ useTreeTableInstance,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import type { Dashboard, DashboardSubscription } from "metabase-types/api";++import { DashboardPageShell } from "../../components/DashboardPageShell";++import { SubscriptionSidebar } from "./SubscriptionSidebar";+import { useDashboardSubscriptions } from "./use-dashboard-subscriptions";+import { useSubscriptionColumns } from "./use-subscription-columns";+import { filterSubscriptionRows, getSubscriptionRows } from "./utils";++export function DashboardSubscriptionsPage() {+ return (+ <DashboardPageShell+ data-testid="dashboard-subscriptions-page"+ aside={(dashboard, containerWidth) => (+ <SelectedSubscriptionSidebar+ dashboard={dashboard}+ containerWidth={containerWidth}+ />+ )}+ >+ {(dashboard) => <DashboardSubscriptions dashboard={dashboard} />}+ </DashboardPageShell>+ );+}++type DashboardSubscriptionsProps = {+ dashboard: Dashboard;+};++function DashboardSubscriptions({ dashboard }: DashboardSubscriptionsProps) {+ const [searchQuery, setSearchQuery] = useState("");+ const isAdmin = useSelector(getUserIsAdmin);+ const canManageSubscriptions = useCanManageDashboardSubscriptions(dashboard);+ const { subscriptions, isLoading, error, selection } =+ useDashboardSubscriptions(dashboard);+ const rows = useMemo(+ () => getSubscriptionRows(subscriptions ?? [], dashboard.parameters ?? []),+ [subscriptions, dashboard.parameters],+ );+ const filteredRows = useMemo(+ () => filterSubscriptionRows(rows, searchQuery),+ [rows, searchQuery],+ );+ const selectedSubscriptionId =+ selection.type === "found" ? selection.subscription.id : undefined;+ const columns = useSubscriptionColumns({+ isSidebarOpen: selection.type !== "none",+ });+ const treeTableInstance = useTreeTableInstance({+ data: filteredRows,+ columns,+ getNodeId: (row) => String(row.id),+ selectedRowId:+ selectedSubscriptionId != null ? String(selectedSubscriptionId) : null,+ });+ const manageUrl = Urls.dashboard(dashboard, { openSubscriptions: true });+ const listUrl = Urls.dataStudioDashboardSubscriptions(dashboard.id);+ const getRowUrl = (subscriptionId: DashboardSubscription["id"]) =>+ subscriptionId === selectedSubscriptionId+ ? listUrl+ : Urls.dataStudioDashboardSubscriptions(dashboard.id, subscriptionId);++ if (isLoading || error != null) {+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;+ }++ return (+ <Stack gap="lg">+ <Group gap="md" wrap="nowrap">+ <TextInput+ flex={1}+ placeholder={t`Search...`}+ leftSection={<Icon name="search" />}+ bdrs="sm"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ />+ {canManageSubscriptions && rows.length > 0 && (+ <Button component={ForwardRefLink} to={manageUrl}>+ {t`Manage subscriptions`}+ </Button>+ )}+ </Group>+ {!isAdmin && rows.length > 0 && (+ <Text c="text-secondary">+ {t`Only the subscriptions you created are listed.`}+ </Text>+ )}+ <Card withBorder p={0}>+ <TreeTable+ instance={treeTableInstance}+ hierarchical={false}+ emptyState={+ <SubscriptionsEmptyState+ searchQuery={searchQuery}+ manageUrl={canManageSubscriptions ? manageUrl : null}+ isAdmin={isAdmin}+ />+ }+ renderRowLink={(row, props) => (+ <Link to={getRowUrl(row.original.id)} {...props} />+ )}+ />+ </Card>+ </Stack>+ );+}++type SelectedSubscriptionSidebarProps = {+ dashboard: Dashboard;+ containerWidth: number;+};++function SelectedSubscriptionSidebar({+ dashboard,+ containerWidth,+}: SelectedSubscriptionSidebarProps) {+ const { isLoading, error, selection } = useDashboardSubscriptions(dashboard);++ if (isLoading || error != null || selection.type === "none") {+ return null;+ }++ return (+ <SubscriptionSidebar+ dashboard={dashboard}+ selection={selection}+ closeUrl={Urls.dataStudioDashboardSubscriptions(dashboard.id)}+ containerWidth={containerWidth}+ />+ );+}++type SubscriptionsEmptyStateProps = {+ searchQuery: string;+ /** Where to set up a subscription, or `null` when the user can't. */+ manageUrl: string | null;+ isAdmin: boolean;+};++function SubscriptionsEmptyState({+ searchQuery,+ manageUrl,+ isAdmin,+}: SubscriptionsEmptyStateProps) {+ if (searchQuery) {+ return <ListEmptyState label={t`No results for "${searchQuery}"`} />;+ }++ const label = isAdmin+ ? t`No subscriptions yet`+ : t`You haven't created any subscriptions yet`;++ if (manageUrl == null) {+ return <ListEmptyState label={label} />;+ }++ return (+ <ListEmptyState+ label={label}+ description={t`Subscriptions are set up from the dashboard.`}+ action={+ <Button component={ForwardRefLink} to={manageUrl} variant="filled">+ {t`Set up a subscription`}+ </Button>+ }+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/DashboardSubscriptionsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/DashboardSubscriptionsPage.unit.spec.tsxnew file mode 100644index 00000000000..f637ee49274--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/DashboardSubscriptionsPage.unit.spec.tsx@@ -0,0 +1,645 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupCollectionByIdEndpoint,+ setupDashboardEndpoints,+} from "__support__/server-mocks";+import {+ setupListSubscriptionsEndpoint,+ setupNotificationChannelsEndpointError,+ setupNotificationChannelsEndpoints,+} from "__support__/server-mocks/pulse";+import { mockSettings } from "__support__/settings";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";+import { Route } from "metabase/router";+import type {+ DashboardSubscription,+ ExternalEmailRecipient,+ Parameter,+ SubscriptionSupportingCard,+} from "metabase-types/api";+import {+ createMockCard,+ createMockChannel,+ createMockCollection,+ createMockDashboard,+ createMockDashboardCard,+ createMockDashboardSubscription,+ createMockParameter,+ createMockUser,+} from "metabase-types/api/mocks";++import { DashboardSubscriptionsPage } from "./DashboardSubscriptionsPage";++const CATEGORY_PARAMETER = createMockParameter({+ id: "1",+ name: "Category",+ slug: "category",+ type: "string/=",+});++const DASHBOARD = createMockDashboard({+ id: 10,+ name: "Sales overview",+ parameters: [CATEGORY_PARAMETER],+ dashcards: [createMockDashboardCard({ card: createMockCard() })],+});++const MANAGE_URL = "/dashboard/10-sales-overview#subscriptions";++const EMAIL_SUBSCRIPTION = createMockDashboardSubscription({+ id: 1,+ dashboard_id: DASHBOARD.id,+ creator: createMockUser({ common_name: "Bobby Tables" }),+ channels: [+ createMockChannel({+ channel_type: "email",+ schedule_type: "daily",+ schedule_hour: 8,+ recipients: [+ createMockUser({+ id: 2,+ common_name: "Ada Lovelace",+ email: "[email protected]",+ }),+ createMockUser({+ id: 3,+ common_name: "Alan Turing",+ email: "[email protected]",+ }),+ ],+ }),+ ],+ parameters: [createMockParameter({ id: "1", value: ["Gizmo"] })],+});++const SLACK_SUBSCRIPTION = createMockDashboardSubscription({+ id: 2,+ dashboard_id: DASHBOARD.id,+ creator: createMockUser({ common_name: "Grace Hopper" }),+ channels: [+ createMockChannel({+ channel_type: "slack",+ schedule_type: "weekly",+ schedule_day: "mon",+ schedule_hour: 9,+ details: { channel: "#sales" },+ }),+ ],+});++const SUBSCRIPTIONS_URL = `/data-studio/dashboards/${DASHBOARD.id}/subscriptions`;++const EXTERNAL_RECIPIENT: ExternalEmailRecipient = { email: "[email protected]" };++function createMockCardAttachment(+ opts: Partial<SubscriptionSupportingCard>,+): SubscriptionSupportingCard {+ return {+ id: 1,+ collection_id: null,+ description: null,+ display: "table",+ name: "Orders",+ include_csv: false,+ include_xls: false,+ dashboard_card_id: 1,+ dashboard_id: DASHBOARD.id,+ parameter_mappings: [],+ ...opts,+ };+}++const DETAILED_EMAIL_SUBSCRIPTION = createMockDashboardSubscription({+ ...EMAIL_SUBSCRIPTION,+ skip_if_empty: true,+ channels: [+ createMockChannel({+ channel_type: "email",+ schedule_type: "daily",+ schedule_hour: 8,+ recipients: [+ createMockUser({+ id: 2,+ common_name: "Ada Lovelace",+ email: "[email protected]",+ }),+ EXTERNAL_RECIPIENT,+ ],+ details: {+ subject: "Weekly sales",+ include_pdf: true,+ attachment_only: true,+ },+ }),+ ],+ cards: [+ createMockCardAttachment({+ id: 1,+ dashboard_card_id: 11,+ name: "Orders by month",+ include_csv: true,+ }),+ createMockCardAttachment({+ id: 2,+ dashboard_card_id: 12,+ name: "Revenue",+ include_xls: true,+ }),+ createMockCardAttachment({ id: 3, dashboard_card_id: 13, name: "Users" }),+ ],+});++type SetupOpts = {+ subscriptions?: DashboardSubscription[];+ dashboardParameters?: Parameter[];+ selectedSubscriptionId?: DashboardSubscription["id"];+ isEmailConfigured?: boolean;+ isSlackConfigured?: boolean;+ hasChannelInfoError?: boolean;+ isAdmin?: boolean;+};++function setup({+ subscriptions = [EMAIL_SUBSCRIPTION, SLACK_SUBSCRIPTION],+ dashboardParameters = [CATEGORY_PARAMETER],+ selectedSubscriptionId,+ isEmailConfigured = true,+ isSlackConfigured = true,+ hasChannelInfoError = false,+ isAdmin = true,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 800 });+ setupDashboardEndpoints({ ...DASHBOARD, parameters: dashboardParameters });+ setupCollectionByIdEndpoint({+ collections: [createMockCollection(ROOT_COLLECTION)],+ });+ setupListSubscriptionsEndpoint(subscriptions);+ if (hasChannelInfoError) {+ setupNotificationChannelsEndpointError();+ } else {+ setupNotificationChannelsEndpoints({+ email: { type: "email", configured: isEmailConfigured },+ slack: { type: "slack", configured: isSlackConfigured },+ });+ }++ renderWithProviders(+ <Route+ path="/data-studio/dashboards/:dashboardId/subscriptions/:subscriptionId?"+ element={<DashboardSubscriptionsPage />}+ />,+ {+ withRouter: true,+ storeInitialState: {+ currentUser: createMockUser({ is_superuser: isAdmin }),+ settings: mockSettings({ "report-timezone-short": "EST" }),+ },+ initialRoute:+ selectedSubscriptionId != null+ ? `${SUBSCRIPTIONS_URL}/${selectedSubscriptionId}`+ : SUBSCRIPTIONS_URL,+ },+ );+}++describe("DashboardSubscriptionsPage", () => {+ it("lists each subscription's schedule, recipients, filters, and creator", async () => {+ setup();++ const emailRow = await screen.findByRole("row", {+ name: /Daily at 8:00 AM/,+ });+ expect(within(emailRow).getByText("Daily at 8:00 AM")).toBeInTheDocument();+ expect(+ within(emailRow).getByText("Ada Lovelace and 1 other"),+ ).toBeInTheDocument();+ expect(within(emailRow).getByText("Category: Gizmo")).toBeInTheDocument();+ expect(within(emailRow).getByText("Bobby Tables")).toBeInTheDocument();++ const slackRow = screen.getByRole("row", { name: /Mondays at 9:00 AM/ });+ expect(within(slackRow).getByText("#sales")).toBeInTheDocument();+ expect(within(slackRow).getByText("None")).toBeInTheDocument();+ expect(within(slackRow).getByText("Grace Hopper")).toBeInTheDocument();+ });++ it("filters the subscriptions by any column and reports when nothing matches", async () => {+ setup();+ const searchInput = await screen.findByPlaceholderText("Search...");++ await userEvent.type(searchInput, "#sal");+ expect(screen.getByText("Mondays at 9:00 AM")).toBeInTheDocument();+ expect(screen.queryByText("Daily at 8:00 AM")).not.toBeInTheDocument();++ await userEvent.clear(searchInput);+ await userEvent.type(searchInput, "gizmo");+ expect(screen.getByText("Daily at 8:00 AM")).toBeInTheDocument();+ expect(screen.queryByText("Mondays at 9:00 AM")).not.toBeInTheDocument();++ await userEvent.clear(searchInput);+ await userEvent.type(searchInput, "churn");+ expect(screen.getByText('No results for "churn"')).toBeInTheDocument();+ });++ it("finds a subscription by a recipient the Recipients column abbreviates", async () => {+ setup();++ await userEvent.type(+ await screen.findByPlaceholderText("Search..."),+ "alan@example",+ );+ expect(screen.getByText("Daily at 8:00 AM")).toBeInTheDocument();+ expect(screen.queryByText("Mondays at 9:00 AM")).not.toBeInTheDocument();+ });++ it("keeps the sidebar open when the search hides its row", async () => {+ setup({ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id });+ const details = await screen.findByTestId("subscription-details");++ await userEvent.type(screen.getByPlaceholderText("Search..."), "#sal");++ expect(+ screen.queryByRole("row", { name: /Daily at 8:00 AM/ }),+ ).not.toBeInTheDocument();+ expect(details).toBeInTheDocument();+ expect(+ within(details).getByRole("group", { name: "Sends" }),+ ).toHaveTextContent("Email with the default subject");+ });++ it("links each row to its subscription", async () => {+ setup();++ expect(+ await screen.findByRole("link", { name: /Daily at 8:00 AM/ }),+ ).toHaveAttribute("href", `${SUBSCRIPTIONS_URL}/1`);+ expect(+ screen.getByRole("link", { name: /Mondays at 9:00 AM/ }),+ ).toHaveAttribute("href", `${SUBSCRIPTIONS_URL}/2`);+ expect(+ screen.getByRole("row", { name: /Daily at 8:00 AM/ }),+ ).toHaveAttribute("aria-selected", "false");+ });++ it("selects the subscription in the URL and links its row back to the list", async () => {+ setup({ selectedSubscriptionId: 1 });++ expect(+ await screen.findByRole("row", { name: /Daily at 8:00 AM/ }),+ ).toHaveAttribute("aria-selected", "true");+ expect(+ screen.getByRole("row", { name: /Mondays at 9:00 AM/ }),+ ).toHaveAttribute("aria-selected", "false");+ expect(+ screen.getByRole("link", { name: /Daily at 8:00 AM/ }),+ ).toHaveAttribute("href", SUBSCRIPTIONS_URL);+ expect(+ screen.getByRole("link", { name: /Mondays at 9:00 AM/ }),+ ).toHaveAttribute("href", `${SUBSCRIPTIONS_URL}/2`);+ });++ it("drops the columns the sidebar repeats while it is open", async () => {+ setup({ selectedSubscriptionId: 1 });++ expect(+ await screen.findByRole("columnheader", { name: /Schedule/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("columnheader", { name: /Filters/ }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("columnheader", { name: /Created by/ }),+ ).not.toBeInTheDocument();+ });++ it("links to the dashboard's subscriptions sidebar", async () => {+ setup();++ expect(+ await screen.findByRole("link", { name: "Manage subscriptions" }),+ ).toHaveAttribute("href", MANAGE_URL);+ });++ it("offers to set up a subscription when there is none", async () => {+ setup({ subscriptions: [] });++ expect(await screen.findByText("No subscriptions yet")).toBeInTheDocument();+ expect(+ screen.getByText("Subscriptions are set up from the dashboard."),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: "Set up a subscription" }),+ ).toHaveAttribute("href", MANAGE_URL);+ expect(+ screen.queryByRole("link", { name: "Manage subscriptions" }),+ ).not.toBeInTheDocument();+ });++ describe("for a user who can't manage the dashboard's subscriptions", () => {+ const setupWithoutChannels = (opts: SetupOpts = {}) =>+ setup({+ isAdmin: false,+ isEmailConfigured: false,+ isSlackConfigured: false,+ ...opts,+ });++ it("does not link to the dashboard's subscriptions sidebar", async () => {+ setupWithoutChannels();++ expect(await screen.findByText("Daily at 8:00 AM")).toBeInTheDocument();+ expect(+ screen.queryByRole("link", { name: "Manage subscriptions" }),+ ).not.toBeInTheDocument();+ });++ it("shows the empty state without offering to set up a subscription", async () => {+ setupWithoutChannels({ subscriptions: [] });++ expect(+ await screen.findByText("You haven't created any subscriptions yet"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Subscriptions are set up from the dashboard."),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("link", { name: "Set up a subscription" }),+ ).not.toBeInTheDocument();+ });++ it("does not offer to edit a subscription on the dashboard", async () => {+ setupWithoutChannels({ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id });+ const details = await screen.findByTestId("subscription-details");++ expect(within(details).getByText("Daily at 8:00 AM EST")).toBeVisible();+ expect(+ within(details).queryByLabelText("Edit on dashboard"),+ ).not.toBeInTheDocument();+ });+ });++ it("tells a non-admin that only their own subscriptions are listed", async () => {+ setup({ isAdmin: false });++ expect(+ await screen.findByText("Only the subscriptions you created are listed."),+ ).toBeInTheDocument();+ });++ it("does not repeat the non-admin notice above the empty state", async () => {+ setup({ subscriptions: [], isAdmin: false });++ expect(+ await screen.findByText("You haven't created any subscriptions yet"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Only the subscriptions you created are listed."),+ ).not.toBeInTheDocument();+ });++ it("does not limit the list for an admin", async () => {+ setup();++ expect(await screen.findByText("Bobby Tables")).toBeInTheDocument();+ expect(+ screen.queryByText("Only the subscriptions you created are listed."),+ ).not.toBeInTheDocument();+ });++ it("tells a non-admin they have not created a subscription", async () => {+ setup({ subscriptions: [], isAdmin: false });++ expect(+ await screen.findByText("You haven't created any subscriptions yet"),+ ).toBeInTheDocument();+ expect(screen.queryByText("No subscriptions yet")).not.toBeInTheDocument();+ });++ it("shows the number of subscriptions on the Subscriptions tab", async () => {+ setup();++ const header = await screen.findByTestId("dashboard-pane-header");+ const tab = within(header).getByRole("link", { name: "Subscriptions" });+ expect(tab).toHaveAttribute("aria-current", "page");+ expect(await within(tab).findByTestId("pill-tab-count")).toHaveTextContent(+ "2",+ );+ });++ it("does not count a non-admin's subscriptions on the Subscriptions tab, as the list holds only their own", async () => {+ setup({ isAdmin: false });++ expect(await screen.findByText("Daily at 8:00 AM")).toBeInTheDocument();+ const header = screen.getByTestId("dashboard-pane-header");+ const tab = within(header).getByRole("link", { name: "Subscriptions" });+ expect(within(tab).queryByTestId("pill-tab-count")).not.toBeInTheDocument();+ });++ describe("subscription details", () => {+ it("shows everything an email subscription sends and to whom", async () => {+ setup({+ subscriptions: [DETAILED_EMAIL_SUBSCRIPTION],+ selectedSubscriptionId: DETAILED_EMAIL_SUBSCRIPTION.id,+ });+ const details = await screen.findByTestId("subscription-details");++ expect(within(details).getByText("Daily at 8:00 AM EST")).toBeVisible();+ expect(+ within(details).getByText('Email with the subject "Weekly sales"'),+ ).toBeVisible();++ const recipients = within(+ within(details).getByRole("group", { name: "Recipients" }),+ ).getAllByTestId("subscription-recipient");+ expect(recipients[0]).toHaveTextContent("Ada Lovelace");+ expect(recipients[0]).toHaveTextContent("[email protected]");+ expect(recipients[1]).toHaveTextContent("[email protected]");+ expect(recipients[1]).toHaveTextContent("Not a Metabase user");++ expect(within(details).getByText("Category: Gizmo")).toBeVisible();++ expect(within(details).getByText("PDF of the dashboard")).toBeVisible();+ const attachments = within(details).getAllByTestId(+ "subscription-card-attachment",+ );+ expect(attachments).toHaveLength(2);+ expect(attachments[0]).toHaveTextContent("Orders by month");+ expect(attachments[0]).toHaveTextContent("CSV");+ expect(attachments[1]).toHaveTextContent("Revenue");+ expect(attachments[1]).toHaveTextContent("XLSX");+ expect(+ within(details).getByText("Send only attachments (no charts)"),+ ).toBeVisible();++ expect(+ within(details).getByRole("group", {+ name: "When there are no results",+ }),+ ).toHaveTextContent("Don't send");+ expect(+ within(details).getByRole("group", { name: "Created by" }),+ ).toHaveTextContent("Bobby Tables");+ });++ it("shows a Slack subscription's channel and no recipients", async () => {+ setup({ selectedSubscriptionId: SLACK_SUBSCRIPTION.id });+ const details = await screen.findByTestId("subscription-details");++ expect(within(details).getByText("Mondays at 9:00 AM EST")).toBeVisible();+ expect(+ within(details).getByText("Slack message to #sales"),+ ).toBeVisible();+ expect(+ within(details).queryByRole("group", { name: "Recipients" }),+ ).not.toBeInTheDocument();+ expect(within(details).getByText("No filters")).toBeVisible();+ expect(within(details).getByText("No attachments")).toBeVisible();+ expect(+ within(details).getByRole("group", {+ name: "When there are no results",+ }),+ ).toHaveTextContent("Send anyway");+ });++ it("links to the subscription's edit form on the dashboard", async () => {+ setup({ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id });+ const details = await screen.findByTestId("subscription-details");++ expect(+ await within(details).findByRole("link", { name: "Edit on dashboard" }),+ ).toHaveAttribute("href", "/dashboard/10-sales-overview#subscriptions=1");+ });++ it("links to the edit form of a subscription whose channel is not configured", async () => {+ setup({+ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id,+ isEmailConfigured: false,+ });+ const details = await screen.findByTestId("subscription-details");++ expect(+ await within(details).findByRole("link", { name: "Edit on dashboard" }),+ ).toHaveAttribute("href", "/dashboard/10-sales-overview#subscriptions=1");+ });++ it("disables editing a webhook subscription and says why", async () => {+ const webhookSubscription = createMockDashboardSubscription({+ ...EMAIL_SUBSCRIPTION,+ channels: [createMockChannel({ channel_type: "http" })],+ });+ setup({+ subscriptions: [webhookSubscription],+ selectedSubscriptionId: webhookSubscription.id,+ });+ const details = await screen.findByTestId("subscription-details");++ const button = await within(details).findByRole("button", {+ name: "Edit on dashboard",+ });+ expect(button).toBeDisabled();+ expect(+ within(details).queryByRole("link", { name: "Edit on dashboard" }),+ ).not.toBeInTheDocument();+ await userEvent.hover(button);+ expect(await screen.findByRole("tooltip")).toHaveTextContent(+ "Webhook subscriptions can't be edited on the dashboard",+ );+ });++ it("disables editing when the channel setup fails to load", async () => {+ setup({+ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id,+ hasChannelInfoError: true,+ });+ const details = await screen.findByTestId("subscription-details");++ await waitFor(() =>+ expect(fetchMock.callHistory.done("path:/api/pulse/form_input")).toBe(+ true,+ ),+ );+ expect(+ within(details).getByRole("button", { name: "Edit on dashboard" }),+ ).toBeDisabled();+ expect(+ within(details).queryByRole("link", { name: "Edit on dashboard" }),+ ).not.toBeInTheDocument();+ });++ it("closes back to the list", async () => {+ setup({ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id });+ const details = await screen.findByTestId("subscription-details");++ expect(+ within(details).getByRole("link", { name: "Close" }),+ ).toHaveAttribute("href", SUBSCRIPTIONS_URL);+ });++ it("shows no details without a selection", async () => {+ setup();++ const emailRow = await screen.findByRole("row", {+ name: /Daily at 8:00 AM/,+ });+ expect(emailRow).toHaveAttribute("aria-selected", "false");+ expect(+ screen.getByRole("columnheader", { name: /Created by/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("subscription-details"),+ ).not.toBeInTheDocument();+ });++ it("says an unknown subscription was not found and closes back to the list", async () => {+ setup({ selectedSubscriptionId: 99 });+ const details = await screen.findByTestId("subscription-details");++ expect(within(details).getByText("Subscription not found")).toBeVisible();+ expect(+ within(details).getByRole("link", { name: "Close" }),+ ).toHaveAttribute("href", SUBSCRIPTIONS_URL);+ expect(+ screen.getByRole("row", { name: /Daily at 8:00 AM/ }),+ ).toHaveAttribute("aria-selected", "false");+ });++ it("lists filters that share a name and value separately", async () => {+ setup({+ subscriptions: [+ createMockDashboardSubscription({+ ...EMAIL_SUBSCRIPTION,+ parameters: [+ createMockParameter({ id: "1", value: ["Gizmo"] }),+ createMockParameter({ id: "2", value: ["Gizmo"] }),+ ],+ }),+ ],+ dashboardParameters: [+ CATEGORY_PARAMETER,+ createMockParameter({+ id: "2",+ name: "Category",+ slug: "category_2",+ type: "string/=",+ }),+ ],+ selectedSubscriptionId: EMAIL_SUBSCRIPTION.id,+ });+ const details = await screen.findByTestId("subscription-details");++ expect(+ within(+ within(details).getByRole("group", { name: "Filters" }),+ ).getAllByText("Category: Gizmo"),+ ).toHaveLength(2);+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/InfoSection/InfoSection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/InfoSection/InfoSection.tsxnew file mode 100644index 00000000000..03cac2d3303--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/InfoSection/InfoSection.tsx@@ -0,0 +1,152 @@+import { t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import CS from "metabase/css/core/index.css";+import {+ type SubscriptionRecipient,+ formatFilter,+ getActiveFilters,+ getChannelRecipients,+} from "metabase/notifications/pulse/subscription-formatting";+import { useSelector } from "metabase/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";+import { SidebarInfoRow } from "metabase/transforms/components/SidebarInfoRow";+import { Card, Group, Stack, Text } from "metabase/ui";+import type {+ Channel,+ DashboardSubscription,+ Parameter,+} from "metabase-types/api";++import { getCardAttachments, getChannelDescription } from "../../utils";++type InfoSectionProps = {+ subscription: DashboardSubscription;+ channel: Channel;+ parameters: Parameter[];+};++export function InfoSection({+ subscription,+ channel,+ parameters,+}: InfoSectionProps) {+ const filters = getActiveFilters(subscription, parameters);++ return (+ <Card p={0} shadow="none" withBorder role="region" aria-label={t`Info`}>+ <SidebarInfoRow label={t`Sends`}>+ {getChannelDescription(channel)}+ </SidebarInfoRow>+ {channel.channel_type === "email" && (+ <SidebarInfoRow label={t`Recipients`}>+ <RecipientList channel={channel} />+ </SidebarInfoRow>+ )}+ <SidebarInfoRow label={t`Filters`}>+ {filters.length > 0 ? (+ filters.map((filter) => (+ <Text key={filter.id}>{formatFilter(filter)}</Text>+ ))+ ) : (+ <Text c="text-secondary">{t`No filters`}</Text>+ )}+ </SidebarInfoRow>+ <SidebarInfoRow label={t`Attachments`}>+ <AttachmentList subscription={subscription} channel={channel} />+ </SidebarInfoRow>+ <SidebarInfoRow label={t`When there are no results`}>+ {subscription.skip_if_empty ? t`Don't send` : t`Send anyway`}+ </SidebarInfoRow>+ <SidebarInfoRow label={t`Created by`}>+ {subscription.creator.common_name}+ </SidebarInfoRow>+ <SidebarInfoRow label={t`Created at`}>+ <DateTime value={subscription.created_at} unit="day" />+ </SidebarInfoRow>+ </Card>+ );+}++type RecipientListProps = {+ channel: Channel;+};++function RecipientList({ channel }: RecipientListProps) {+ const recipients = getChannelRecipients(channel);++ if (recipients.length === 0) {+ return <Text c="text-secondary">{t`No recipients`}</Text>;+ }++ return (+ <Stack gap="sm">+ {recipients.map((recipient) => (+ <RecipientItem+ key={`${recipient.type}-${recipient.email}`}+ recipient={recipient}+ />+ ))}+ </Stack>+ );+}++type RecipientItemProps = {+ recipient: SubscriptionRecipient;+};++function RecipientItem({ recipient }: RecipientItemProps) {+ const applicationName = useSelector(getApplicationName);+ const [primaryText, secondaryText] =+ recipient.type === "user"+ ? [recipient.name, recipient.email]+ : [recipient.email, t`Not a ${applicationName} user`];++ return (+ <Stack gap={0} data-testid="subscription-recipient">+ <Text className={CS.textWrap}>{primaryText}</Text>+ <Text className={CS.textWrap} fz="sm" lh="h5" c="text-secondary">+ {secondaryText}+ </Text>+ </Stack>+ );+}++type AttachmentListProps = {+ subscription: DashboardSubscription;+ channel: Channel;+};++function AttachmentList({ subscription, channel }: AttachmentListProps) {+ const includesPdf = channel.details?.include_pdf === true;+ const isAttachmentOnly = channel.details?.attachment_only === true;+ const cardAttachments = getCardAttachments(subscription);+ const hasAttachments = includesPdf || cardAttachments.length > 0;++ if (!hasAttachments) {+ return <Text c="text-secondary">{t`No attachments`}</Text>;+ }++ return (+ <Stack gap="xs">+ {includesPdf && <Text>{t`PDF of the dashboard`}</Text>}+ {cardAttachments.map((attachment) => (+ <Group+ key={attachment.dashcardId}+ justify="space-between"+ gap="md"+ wrap="nowrap"+ data-testid="subscription-card-attachment"+ >+ <Text className={CS.textWrap}>+ {attachment.name ?? t`Untitled question`}+ </Text>+ <Text c="text-secondary">{attachment.formats.join(", ")}</Text>+ </Group>+ ))}+ {isAttachmentOnly && (+ <Text c="text-secondary">{t`Send only attachments (no charts)`}</Text>+ )}+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/InfoSection/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/InfoSection/index.tsnew file mode 100644index 00000000000..952735a7a9d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/InfoSection/index.ts@@ -0,0 +1 @@+export { InfoSection } from "./InfoSection";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/SubscriptionSidebar.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/SubscriptionSidebar.module.cssnew file mode 100644index 00000000000..77c6b127301--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/SubscriptionSidebar.module.css@@ -0,0 +1,5 @@+.sidebar {+ flex: 1 1 auto;+ overflow: auto;+ border-left: 1px solid var(--mb-color-border-neutral);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/SubscriptionSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/SubscriptionSidebar.tsxnew file mode 100644index 00000000000..5c66b320b87--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/SubscriptionSidebar.tsx@@ -0,0 +1,211 @@+import { t } from "ttag";++import { skipToken, useGetChannelInfoQuery } from "metabase/api";+import { ForwardRefLink } from "metabase/common/components/Link";+import CS from "metabase/css/core/index.css";+import { useCanManageDashboardSubscriptions } from "metabase/dashboard/hooks";+import { SidebarResizableBox } from "metabase/monitor/components/MonitorLayout/SidebarResizableBox";+import { getSubscriptionEditUnavailableReason } from "metabase/notifications/pulse/subscription-editing";+import { useSetting } from "metabase/settings";+import {+ ActionIcon,+ Box,+ FixedSizeIcon,+ Group,+ Stack,+ Text,+ Tooltip,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import type {+ Channel,+ Dashboard,+ DashboardSubscription,+} from "metabase-types/api";++import {+ CHANNEL_ICONS,+ SIDEBAR_WIDTH,+ TOOLTIP_OPEN_DELAY_MS,+} from "../constants";+import { type SubscriptionSelection, formatChannelSchedule } from "../utils";++import { InfoSection } from "./InfoSection";+import S from "./SubscriptionSidebar.module.css";++type SubscriptionSidebarProps = {+ dashboard: Dashboard;+ selection: Exclude<SubscriptionSelection, { type: "none" }>;+ closeUrl: string;+ containerWidth: number;+};++export function SubscriptionSidebar({+ dashboard,+ selection,+ closeUrl,+ containerWidth,+}: SubscriptionSidebarProps) {+ return (+ <SidebarResizableBox+ containerWidth={containerWidth}+ defaultWidth={SIDEBAR_WIDTH}+ >+ <Stack+ className={S.sidebar}+ p="lg"+ gap="lg"+ bg="background_page-primary"+ role="region"+ aria-label={t`Subscription details`}+ data-testid="subscription-details"+ >+ {selection.type === "found" ? (+ <>+ <SidebarHeader+ dashboard={dashboard}+ subscription={selection.subscription}+ channel={selection.channel}+ closeUrl={closeUrl}+ />+ <InfoSection+ subscription={selection.subscription}+ channel={selection.channel}+ parameters={dashboard.parameters ?? []}+ />+ </>+ ) : (+ <Group+ gap="0.75rem"+ wrap="nowrap"+ align="start"+ justify="space-between"+ >+ <Text fz="h3" fw="bold" lh="h3">+ {t`Subscription not found`}+ </Text>+ <CloseLink closeUrl={closeUrl} />+ </Group>+ )}+ </Stack>+ </SidebarResizableBox>+ );+}++type SidebarHeaderProps = {+ dashboard: Dashboard;+ subscription: DashboardSubscription;+ channel: Channel;+ closeUrl: string;+};++function SidebarHeader({+ dashboard,+ subscription,+ channel,+ closeUrl,+}: SidebarHeaderProps) {+ const timezone = useSetting("report-timezone-short");++ return (+ <Group gap="0.75rem" wrap="nowrap" align="start" justify="space-between">+ <Group gap="sm" wrap="nowrap" align="center" miw={0}>+ <FixedSizeIcon name={CHANNEL_ICONS[channel.channel_type]} aria-hidden />+ <Text className={CS.textWrap} fz="h3" fw="bold" lh="h3">+ {formatChannelSchedule(channel, timezone)}+ </Text>+ </Group>+ <Group gap="xs" wrap="nowrap">+ <EditOnDashboardAction+ dashboard={dashboard}+ subscription={subscription}+ channel={channel}+ />+ <CloseLink closeUrl={closeUrl} />+ </Group>+ </Group>+ );+}++type CloseLinkProps = {+ closeUrl: string;+};++function CloseLink({ closeUrl }: CloseLinkProps) {+ return (+ <ActionIcon component={ForwardRefLink} to={closeUrl} aria-label={t`Close`}>+ <FixedSizeIcon name="close" />+ </ActionIcon>+ );+}++type EditOnDashboardActionProps = {+ dashboard: Dashboard;+ subscription: DashboardSubscription;+ channel: Channel;+};++function EditOnDashboardAction({+ dashboard,+ subscription,+ channel,+}: EditOnDashboardActionProps) {+ const canManageSubscriptions = useCanManageDashboardSubscriptions(dashboard);+ const {+ data: channelInfo,+ isLoading,+ error,+ } = useGetChannelInfoQuery(canManageSubscriptions ? undefined : skipToken);++ if (!canManageSubscriptions) {+ return null;+ }++ if (isLoading) {+ return <DisabledEditAction reason={null} />;+ }++ if (error != null || channelInfo == null) {+ return (+ <DisabledEditAction reason={t`Couldn't load the notification channels`} />+ );+ }++ const unavailableReason = getSubscriptionEditUnavailableReason(+ channel,+ channelInfo,+ );+ if (unavailableReason != null) {+ return <DisabledEditAction reason={unavailableReason} />;+ }++ return (+ <Tooltip label={t`Edit on dashboard`} openDelay={TOOLTIP_OPEN_DELAY_MS}>+ <ActionIcon+ component={ForwardRefLink}+ to={Urls.dashboard(dashboard, { openSubscriptions: subscription.id })}+ aria-label={t`Edit on dashboard`}+ >+ <FixedSizeIcon name="pencil" />+ </ActionIcon>+ </Tooltip>+ );+}++type DisabledEditActionProps = {+ /** Why the subscription can't be edited, or `null` while that's unknown. */+ reason: string | null;+};++function DisabledEditAction({ reason }: DisabledEditActionProps) {+ return (+ <Tooltip label={reason} disabled={reason == null}>+ {/* a disabled button fires no pointer events, so the tooltip listens on a wrapper */}+ <Box>+ <ActionIcon aria-label={t`Edit on dashboard`} disabled>+ <FixedSizeIcon name="pencil" />+ </ActionIcon>+ </Box>+ </Tooltip>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/index.tsnew file mode 100644index 00000000000..40fa49c3645--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/SubscriptionSidebar/index.ts@@ -0,0 +1 @@+export { SubscriptionSidebar } from "./SubscriptionSidebar";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/constants.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/constants.tsnew file mode 100644index 00000000000..e86b63d593e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/constants.ts@@ -0,0 +1,23 @@+import type {+ ChannelType,+ IconName,+ SubscriptionSupportingCard,+} from "metabase-types/api";++export const CHANNEL_ICONS = {+ email: "mail",+ slack: "slack",+ http: "webhook",+} as const satisfies Record<ChannelType, IconName>;++export const CARD_ATTACHMENT_FORMATS = [+ { key: "include_csv", label: "CSV" },+ { key: "include_xls", label: "XLSX" },+] as const satisfies {+ key: keyof SubscriptionSupportingCard;+ label: string;+}[];++export const SIDEBAR_WIDTH = 512;++export const TOOLTIP_OPEN_DELAY_MS = 300;diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/index.tsnew file mode 100644index 00000000000..04f67f39be6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/index.ts@@ -0,0 +1 @@+export { DashboardSubscriptionsPage } from "./DashboardSubscriptionsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/use-dashboard-subscriptions.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/use-dashboard-subscriptions.tsnew file mode 100644index 00000000000..b81a321fc42--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/use-dashboard-subscriptions.ts@@ -0,0 +1,24 @@+import { useListSubscriptionsQuery } from "metabase/api";+import { useParams } from "metabase/router";+import type { Dashboard } from "metabase-types/api";++import { getSubscriptionSelection } from "./utils";++/**+ * The dashboard's subscriptions and the one the URL selects. The selection is+ * `missing` while the list loads, so check `isLoading` before trusting it.+ */+export function useDashboardSubscriptions(dashboard: Dashboard) {+ const { subscriptionId } = useParams<{ subscriptionId?: string }>();+ const {+ data: subscriptions,+ isLoading,+ error,+ } = useListSubscriptionsQuery({ dashboard_id: dashboard.id });+ const selection = getSubscriptionSelection(+ subscriptions ?? [],+ subscriptionId,+ );++ return { subscriptions, isLoading, error, selection };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/use-subscription-columns.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/use-subscription-columns.tsxnew file mode 100644index 00000000000..edd50c0263a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/use-subscription-columns.tsx@@ -0,0 +1,77 @@+import { useMemo } from "react";+import { t } from "ttag";++import {+ Ellipsified,+ EntityNameCell,+ Text,+ type TreeTableColumnDef,+} from "metabase/ui";++import { CHANNEL_ICONS } from "./constants";+import type { SubscriptionRow } from "./utils";++type SubscriptionColumn = TreeTableColumnDef<SubscriptionRow> & {+ isRepeatedInSidebar?: boolean;+};++type UseSubscriptionColumnsOptions = {+ isSidebarOpen: boolean;+};++export function useSubscriptionColumns({+ isSidebarOpen,+}: UseSubscriptionColumnsOptions): TreeTableColumnDef<SubscriptionRow>[] {+ return useMemo(() => {+ const columns: SubscriptionColumn[] = [+ {+ id: "schedule",+ header: t`Schedule`,+ accessorKey: "schedule",+ enableSorting: true,+ minWidth: 200,+ cell: ({ row }) => (+ <EntityNameCell+ icon={CHANNEL_ICONS[row.original.channelType]}+ name={row.original.schedule}+ />+ ),+ },+ {+ id: "recipients",+ header: t`Recipients`,+ accessorKey: "recipients",+ enableSorting: true,+ minWidth: 160,+ cell: ({ row }) => <Ellipsified>{row.original.recipients}</Ellipsified>,+ },+ {+ id: "filters",+ header: t`Filters`,+ accessorKey: "filters",+ minWidth: 160,+ isRepeatedInSidebar: true,+ cell: ({ row }) =>+ row.original.filters ? (+ <Ellipsified>{row.original.filters}</Ellipsified>+ ) : (+ <Text c="text-tertiary">{t`None`}</Text>+ ),+ },+ {+ id: "creator",+ header: t`Created by`,+ accessorKey: "creatorName",+ enableSorting: true,+ width: "auto",+ widthPadding: 20,+ isRepeatedInSidebar: true,+ cell: ({ row }) => row.original.creatorName,+ },+ ];++ return isSidebarOpen+ ? columns.filter((column) => !column.isRepeatedInSidebar)+ : columns;+ }, [isSidebarOpen]);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/utils.tsnew file mode 100644index 00000000000..ab75126e60f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/utils.ts@@ -0,0 +1,165 @@+import { match } from "ts-pattern";+import { t } from "ttag";++import {+ buildFilterText,+ buildRecipientText,+ formatSubscriptionSchedule,+ getChannelRecipients,+} from "metabase/notifications/pulse/subscription-formatting";+import * as Urls from "metabase/urls";+import type {+ Channel,+ ChannelType,+ DashCardId,+ DashboardSubscription,+ Parameter,+ SubscriptionSupportingCard,+} from "metabase-types/api";++import { CARD_ATTACHMENT_FORMATS } from "./constants";++export type SubscriptionRow = {+ id: DashboardSubscription["id"];+ channelType: ChannelType;+ schedule: string;+ recipients: string;+ /** Every email recipient's name and address, which `recipients` abbreviates. */+ recipientSearchTerms: string[];+ filters: string;+ creatorName: string;+};++export function getSubscriptionRows(+ subscriptions: readonly DashboardSubscription[],+ parameters: Parameter[],+): SubscriptionRow[] {+ return subscriptions.flatMap((subscription) => {+ const [channel] = subscription.channels;+ if (channel == null) {+ return [];+ }+ return [+ {+ id: subscription.id,+ channelType: channel.channel_type,+ schedule: formatSubscriptionSchedule(channel),+ recipients: getRecipientsText(subscription, channel),+ recipientSearchTerms: getRecipientSearchTerms(channel),+ filters: buildFilterText(subscription, parameters),+ creatorName: subscription.creator.common_name,+ },+ ];+ });+}++function getRecipientsText(+ subscription: DashboardSubscription,+ channel: Channel,+): string {+ return channel.channel_type === "slack"+ ? (channel.details?.channel ?? "")+ : buildRecipientText(subscription);+}++function getRecipientSearchTerms(channel: Channel): string[] {+ return getChannelRecipients(channel).flatMap((recipient) =>+ recipient.type === "user"+ ? [recipient.name, recipient.email]+ : [recipient.email],+ );+}++export type SubscriptionSelection =+ | { type: "none" }+ | { type: "missing" }+ | { type: "found"; subscription: DashboardSubscription; channel: Channel };++export function getSubscriptionSelection(+ subscriptions: readonly DashboardSubscription[],+ subscriptionIdParam: string | undefined,+): SubscriptionSelection {+ if (subscriptionIdParam == null) {+ return { type: "none" };+ }+ const subscriptionId = Urls.extractEntityId(subscriptionIdParam);+ const subscription = subscriptions.find(({ id }) => id === subscriptionId);+ const [channel] = subscription?.channels ?? [];+ return subscription != null && channel != null+ ? { type: "found", subscription, channel }+ : { type: "missing" };+}++export function filterSubscriptionRows(+ rows: SubscriptionRow[],+ searchQuery: string,+): SubscriptionRow[] {+ const query = searchQuery.trim().toLowerCase();+ if (query.length === 0) {+ return rows;+ }+ return rows.filter((row) =>+ [+ row.schedule,+ row.recipients,+ ...row.recipientSearchTerms,+ row.filters,+ row.creatorName,+ ].some((text) => text.toLowerCase().includes(query)),+ );+}++// An hourly schedule has no time of day, so it carries no timezone.+export function formatChannelSchedule(+ channel: Channel,+ timezone: string,+): string {+ const schedule = formatSubscriptionSchedule(channel);+ if (+ channel.schedule_type === "hourly" ||+ channel.schedule_hour == null ||+ !timezone+ ) {+ return schedule;+ }+ // Not translated: ttag rejects a message made only of placeholders+ return `${schedule} ${timezone}`;+}++export function getChannelDescription({+ channel_type,+ details,+}: Channel): string {+ return match(channel_type)+ .with("email", () =>+ details?.subject+ ? t`Email with the subject "${details.subject}"`+ : t`Email with the default subject`,+ )+ .with("slack", () =>+ details?.channel+ ? t`Slack message to ${details.channel}`+ : t`Slack message`,+ )+ .with("http", () => t`Webhook`)+ .exhaustive();+}++export type CardAttachment = {+ dashcardId: DashCardId;+ name: SubscriptionSupportingCard["name"];+ formats: string[];+};++export function getCardAttachments(+ subscription: DashboardSubscription,+): CardAttachment[] {+ return subscription.cards.flatMap((card) => {+ const formats = CARD_ATTACHMENT_FORMATS.filter(({ key }) => card[key]).map(+ ({ label }) => label,+ );+ return formats.length > 0+ ? [{ dashcardId: card.dashboard_card_id, name: card.name, formats }]+ : [];+ });+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/utils.unit.spec.tsnew file mode 100644index 00000000000..5fa022b632e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardSubscriptionsPage/utils.unit.spec.ts@@ -0,0 +1,135 @@+import {+ createMockChannel,+ createMockDashboardSubscription,+ createMockParameter,+ createMockUser,+} from "metabase-types/api/mocks";++import {+ filterSubscriptionRows,+ formatChannelSchedule,+ getSubscriptionRows,+} from "./utils";++const CATEGORY_PARAMETER = createMockParameter({+ id: "1",+ name: "Category",+ slug: "category",+ type: "string/=",+});++const EMAIL_SUBSCRIPTION = createMockDashboardSubscription({+ id: 1,+ creator: createMockUser({ common_name: "Bobby Tables" }),+ channels: [+ createMockChannel({+ schedule_type: "hourly",+ recipients: [+ createMockUser({+ common_name: "Ada Lovelace",+ email: "[email protected]",+ }),+ { email: "[email protected]" },+ ],+ }),+ ],+ parameters: [createMockParameter({ id: "1", value: "Gizmo" })],+});++const SLACK_SUBSCRIPTION = createMockDashboardSubscription({+ id: 2,+ creator: createMockUser({ common_name: "Grace Hopper" }),+ channels: [+ createMockChannel({+ channel_type: "slack",+ schedule_type: "daily",+ schedule_hour: 8,+ details: { channel: "#sales" },+ }),+ ],+});++describe("getSubscriptionRows", () => {+ it("formats a row per subscription", () => {+ expect(+ getSubscriptionRows(+ [EMAIL_SUBSCRIPTION, SLACK_SUBSCRIPTION],+ [CATEGORY_PARAMETER],+ ),+ ).toEqual([+ {+ id: 1,+ channelType: "email",+ schedule: "Hourly",+ recipients: "Ada Lovelace and 1 other",+ recipientSearchTerms: [+ "Ada Lovelace",+ "[email protected]",+ "[email protected]",+ ],+ filters: "Category: Gizmo",+ creatorName: "Bobby Tables",+ },+ {+ id: 2,+ channelType: "slack",+ schedule: "Daily at 8:00 AM",+ recipients: "#sales",+ recipientSearchTerms: [],+ filters: "",+ creatorName: "Grace Hopper",+ },+ ]);+ });++ it("skips a subscription without a channel", () => {+ expect(+ getSubscriptionRows(+ [createMockDashboardSubscription({ channels: [] })],+ [],+ ),+ ).toEqual([]);+ });+});++describe("filterSubscriptionRows", () => {+ const rows = getSubscriptionRows(+ [EMAIL_SUBSCRIPTION, SLACK_SUBSCRIPTION],+ [CATEGORY_PARAMETER],+ );++ it("matches any column case-insensitively", () => {+ expect(filterSubscriptionRows(rows, " HOPPER ")).toEqual([rows[1]]);+ expect(filterSubscriptionRows(rows, "gizmo")).toEqual([rows[0]]);+ });++ it("matches any recipient's name or address, not only the first", () => {+ expect(filterSubscriptionRows(rows, "partner.com")).toEqual([rows[0]]);+ expect(filterSubscriptionRows(rows, "ada@")).toEqual([rows[0]]);+ expect(filterSubscriptionRows(rows, "#sales")).toEqual([rows[1]]);+ });++ it("returns every row for a blank query", () => {+ expect(filterSubscriptionRows(rows, " ")).toEqual(rows);+ });+});++describe("formatChannelSchedule", () => {+ it("adds the timezone to a schedule with a send time", () => {+ const channel = createMockChannel({+ schedule_type: "daily",+ schedule_hour: 8,+ });++ expect(formatChannelSchedule(channel, "PST")).toBe("Daily at 8:00 AM PST");+ });++ it("leaves the timezone off a schedule without a send time", () => {+ const channel = createMockChannel({+ schedule_type: "daily",+ schedule_hour: null,+ });++ expect(formatChannelSchedule(channel, "PST")).toBe("Schedule not set");+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/DashboardUsageStatsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/DashboardUsageStatsPage.tsxnew file mode 100644index 00000000000..f0e8e8bd1a5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/DashboardUsageStatsPage.tsx@@ -0,0 +1,95 @@+import { t } from "ttag";++import { skipToken, useGetDashboardQuery } from "metabase/api";+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";+import { Center, Stack, Text } from "metabase/ui";+import { useGetAuditInfoQuery } from "metabase-enterprise/api";+import type { Dashboard } from "metabase-types/api";++import { DashboardPageShell } from "../../components/DashboardPageShell";++import { UsageStatsCard } from "./UsageStatsCard";+import {+ getDashboardIdParameter,+ getUsageStatsDashcards,+ getUsageStatsParameters,+} from "./utils";++export function DashboardUsageStatsPage() {+ return (+ <DashboardPageShell data-testid="dashboard-usage-stats-page">+ {(dashboard) => <DashboardUsageStats dashboard={dashboard} />}+ </DashboardPageShell>+ );+}++type DashboardUsageStatsProps = {+ dashboard: Dashboard;+};++function DashboardUsageStats({ dashboard }: DashboardUsageStatsProps) {+ const {+ data: auditInfo,+ isLoading: isLoadingAuditInfo,+ error: auditInfoError,+ } = useGetAuditInfoQuery();+ const auditDashboardId = auditInfo?.dashboard_overview;+ const {+ data: auditDashboard,+ isLoading: isLoadingAuditDashboard,+ error: auditDashboardError,+ } = useGetDashboardQuery(+ auditDashboardId != null ? { id: auditDashboardId } : skipToken,+ );+ const isLoading = isLoadingAuditInfo || isLoadingAuditDashboard;+ const error = auditInfoError ?? auditDashboardError;++ if (isLoading || error != null) {+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;+ }++ if (auditDashboardId == null || auditDashboard == null) {+ return (+ <UsageStatsNotice+ message={t`To see usage stats, you need access to the Usage analytics collection.`}+ />+ );+ }++ const dashboardIdParameter = getDashboardIdParameter(auditDashboard);+ const dashcards = getUsageStatsDashcards(auditDashboard);+ if (dashboardIdParameter == null || dashcards.length === 0) {+ return (+ <UsageStatsNotice+ message={t`Usage stats aren't available for this dashboard.`}+ />+ );+ }++ const parameters = getUsageStatsParameters(auditDashboard, dashboard.id);++ return (+ <Stack gap="lg">+ {dashcards.map((dashcard) => (+ <UsageStatsCard+ key={dashcard.id}+ auditDashboardId={auditDashboardId}+ dashcard={dashcard}+ parameters={parameters}+ />+ ))}+ </Stack>+ );+}++type UsageStatsNoticeProps = {+ message: string;+};++function UsageStatsNotice({ message }: UsageStatsNoticeProps) {+ return (+ <Center py="xl">+ <Text c="text-secondary">{message}</Text>+ </Center>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/DashboardUsageStatsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/DashboardUsageStatsPage.unit.spec.tsxnew file mode 100644index 00000000000..4cbd47dcb43--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/DashboardUsageStatsPage.unit.spec.tsx@@ -0,0 +1,226 @@+import fetchMock from "fetch-mock";++import {+ setupAuditInfoEndpoint,+ setupCollectionByIdEndpoint,+ setupDashboardEndpoints,+} from "__support__/server-mocks";+import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";+import { setupListSubscriptionsEndpoint } from "__support__/server-mocks/pulse";+import { renderWithProviders, screen, within } from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";+import { Route } from "metabase/router";+import type { DashboardCard, RawSeries } from "metabase-types/api";+import {+ createMockCard,+ createMockCollection,+ createMockDashboard,+ createMockDashboardCard,+ createMockDataset,+ createMockParameter,+} from "metabase-types/api/mocks";+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";++import { DashboardUsageStatsPage } from "./DashboardUsageStatsPage";+import { USAGE_STATS_CARD_ENTITY_IDS } from "./constants";++jest.mock("metabase/visualizations/components/Visualization", () => {+ const StubVisualization = ({ rawSeries }: { rawSeries?: RawSeries }) => (+ <div data-testid="visualization">{rawSeries?.[0]?.card.display}</div>+ );+ return { __esModule: true, default: StubVisualization };+});++const DASHBOARD = createMockDashboard({ id: 10, name: "Sales overview" });+const AUDIT_DASHBOARD_ID = 201;++const DATE_FILTER_PARAMETER = createMockParameter({+ id: "25f8871e",+ name: "Date Filter",+ slug: "date_filter",+ type: "date/all-options",+ default: "past12months~",+});++const GROUP_NAME_PARAMETER = createMockParameter({+ id: "2ea1dae2",+ name: "Group Name",+ slug: "group_name",+ type: "string/=",+ default: ["All Users"],+ required: true,+});++const DASHBOARD_NAME_PARAMETER = createMockParameter({+ id: "c02bd3d3",+ name: "Dashboard name",+ slug: "dashboard_name",+ type: "string/=",+});++const DASHBOARD_ID_PARAMETER = createMockParameter({+ id: "4b39cd95",+ name: "Dashboard ID",+ slug: "dashboard_id",+ type: "id",+});++const [VIEWS_ENTITY_ID, PEOPLE_ENTITY_ID, ACTIVITY_ENTITY_ID] =+ USAGE_STATS_CARD_ENTITY_IDS;++const VIEWS_DASHCARD = createMockDashboardCard({+ id: 1,+ card_id: 101,+ card: createMockCard({+ id: 101,+ name: "Dashboard views per month",+ display: "line",+ entity_id: createMockEntityId(VIEWS_ENTITY_ID),+ }),+});++const PEOPLE_DASHCARD = createMockDashboardCard({+ id: 2,+ card_id: 102,+ card: createMockCard({+ id: 102,+ name: "Most active people on this dashboard",+ display: "row",+ entity_id: createMockEntityId(PEOPLE_ENTITY_ID),+ }),+});++const ACTIVITY_DASHCARD = createMockDashboardCard({+ id: 3,+ card_id: 103,+ card: createMockCard({+ id: 103,+ name: "Recent activity on dashboard",+ display: "table",+ entity_id: createMockEntityId(ACTIVITY_ENTITY_ID),+ }),+});++const USAGE_STATS_DASHCARDS = [+ VIEWS_DASHCARD,+ PEOPLE_DASHCARD,+ ACTIVITY_DASHCARD,+];++type SetupOpts = {+ hasUsageAnalyticsAccess?: boolean;+ auditDashcards?: DashboardCard[];+};++function setup({+ hasUsageAnalyticsAccess = true,+ auditDashcards = [ACTIVITY_DASHCARD, VIEWS_DASHCARD, PEOPLE_DASHCARD],+}: SetupOpts = {}) {+ setupDashboardEndpoints(DASHBOARD);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection(ROOT_COLLECTION)],+ });+ setupListSubscriptionsEndpoint([]);+ setupAuditInfoEndpoint({+ auditInfo: hasUsageAnalyticsAccess+ ? { dashboard_overview: AUDIT_DASHBOARD_ID }+ : {},+ });+ setupDashboardEndpoints(+ createMockDashboard({+ id: AUDIT_DASHBOARD_ID,+ name: "Dashboard overview",+ parameters: [+ DATE_FILTER_PARAMETER,+ GROUP_NAME_PARAMETER,+ DASHBOARD_ID_PARAMETER,+ DASHBOARD_NAME_PARAMETER,+ ],+ dashcards: auditDashcards,+ }),+ );+ USAGE_STATS_DASHCARDS.forEach((dashcard) =>+ setupDashcardQueryEndpoints(+ AUDIT_DASHBOARD_ID,+ dashcard,+ createMockDataset(),+ ),+ );++ renderWithProviders(+ <Route+ path="/data-studio/dashboards/:dashboardId/usage"+ element={<DashboardUsageStatsPage />}+ />,+ {+ withRouter: true,+ initialRoute: `/data-studio/dashboards/${DASHBOARD.id}/usage`,+ },+ );+}++describe("DashboardUsageStatsPage", () => {+ it("shows the usage stats cards of the dashboard in order", async () => {+ setup();++ const cards = await screen.findAllByTestId("usage-stats-card");+ expect(cards).toHaveLength(3);+ expect(cards[0]).toHaveTextContent("Dashboard views per month");+ expect(cards[1]).toHaveTextContent("Most active people on this dashboard");+ expect(cards[2]).toHaveTextContent("Recent activity on dashboard");+ expect(+ await within(cards[0]).findByTestId("visualization"),+ ).toHaveTextContent("line");+ });++ it("filters each card to the dashboard with the audit dashboard defaults", async () => {+ setup();++ await screen.findAllByTestId("visualization");+ const lastCall = fetchMock.callHistory.lastCall(+ `path:/api/dashboard/${AUDIT_DASHBOARD_ID}/dashcard/${VIEWS_DASHCARD.id}/card/${VIEWS_DASHCARD.card_id}/query`,+ );+ const body: unknown = await lastCall?.request?.json();+ expect(body).toEqual({+ parameters: [+ {+ id: DATE_FILTER_PARAMETER.id,+ type: "date/all-options",+ value: "past12months~",+ },+ {+ id: GROUP_NAME_PARAMETER.id,+ type: "string/=",+ value: ["All Users"],+ },+ {+ id: DASHBOARD_ID_PARAMETER.id,+ type: "id",+ value: [DASHBOARD.id],+ },+ ],+ });+ });++ it("tells the user they need access to Usage analytics", async () => {+ setup({ hasUsageAnalyticsAccess: false });++ expect(+ await screen.findByText(+ "To see usage stats, you need access to the Usage analytics collection.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("usage-stats-card")).not.toBeInTheDocument();+ });++ it("tells the user usage stats are unavailable when no audit card matches", async () => {+ setup({ auditDashcards: [] });++ expect(+ await screen.findByText(+ "Usage stats aren't available for this dashboard.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("usage-stats-card")).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/UsageStatsCard.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/UsageStatsCard.module.cssnew file mode 100644index 00000000000..3f066460761--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/UsageStatsCard.module.css@@ -0,0 +1,10 @@+.card {+ & :global(.CardVisualization) {+ padding: 0;+ }++ /* Data grid cells and ECharts series (inline) set a pointer even when nothing is clickable */+ & * {+ cursor: default !important;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/UsageStatsCard.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/UsageStatsCard.tsxnew file mode 100644index 00000000000..c89cebcdaf7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/UsageStatsCard.tsx@@ -0,0 +1,59 @@+import { useGetDashboardCardQueryQuery } from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { Card, Skeleton, Text } from "metabase/ui";+import Visualization from "metabase/visualizations/components/Visualization";+import type {+ DashboardId,+ NormalizedQueryParameter,+ QuestionDashboardCard,+} from "metabase-types/api";++import S from "./UsageStatsCard.module.css";+import { USAGE_STATS_CARD_HEIGHT } from "./constants";++type UsageStatsCardProps = {+ auditDashboardId: DashboardId;+ dashcard: QuestionDashboardCard;+ parameters: NormalizedQueryParameter[];+};++export function UsageStatsCard({+ auditDashboardId,+ dashcard,+ parameters,+}: UsageStatsCardProps) {+ const { currentData: dataset, error } = useGetDashboardCardQueryQuery({+ dashboardId: auditDashboardId,+ dashcardId: dashcard.id,+ cardId: dashcard.card.id,+ parameters,+ });++ if (dataset == null && error == null) {+ return <Skeleton h={USAGE_STATS_CARD_HEIGHT} />;+ }++ return (+ <Card+ className={S.card}+ withBorder+ shadow="none"+ px="xl"+ py="lg"+ h={USAGE_STATS_CARD_HEIGHT}+ data-testid="usage-stats-card"+ >+ <Text fw="bold" mb="lg">+ {dashcard.card.name}+ </Text>+ {dataset != null ? (+ <Visualization+ rawSeries={[{ card: dashcard.card, data: dataset.data }]}+ isDashboard+ />+ ) : (+ <LoadingAndErrorWrapper error={error} />+ )}+ </Card>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/constants.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/constants.tsnew file mode 100644index 00000000000..31f400fae36--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/constants.ts@@ -0,0 +1,10 @@+// From resources/instance_analytics/collections/main/usage_analytics/dashboard_overview, in display order+export const USAGE_STATS_CARD_ENTITY_IDS = [+ "XIiIsCNMk9gg-eO2hkl8S",+ "_p6UGMWOQn5-yf03uGsaN",+ "xrgv7nzXe_v8ORWIbq839",+] as const;++export const DASHBOARD_ID_PARAMETER_SLUG = "dashboard_id";++export const USAGE_STATS_CARD_HEIGHT = 400;diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/index.tsnew file mode 100644index 00000000000..65e69f66370--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/index.ts@@ -0,0 +1 @@+export { DashboardUsageStatsPage } from "./DashboardUsageStatsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/utils.tsnew file mode 100644index 00000000000..701c0b7801b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/utils.ts@@ -0,0 +1,61 @@+import { isQuestionDashCard } from "metabase/utils/dashboard";+import {+ getDefaultValuePopulatedParameters,+ normalizeParameters,+} from "metabase-lib/v1/parameters/utils/parameter-values";+import type {+ Dashboard,+ DashboardId,+ NormalizedQueryParameter,+ Parameter,+ ParameterValuesMap,+ QuestionDashboardCard,+} from "metabase-types/api";++import {+ DASHBOARD_ID_PARAMETER_SLUG,+ USAGE_STATS_CARD_ENTITY_IDS,+} from "./constants";++export function getUsageStatsDashcards(+ auditDashboard: Pick<Dashboard, "dashcards">,+): QuestionDashboardCard[] {+ const questionDashcards = auditDashboard.dashcards.filter(isQuestionDashCard);++ return USAGE_STATS_CARD_ENTITY_IDS.flatMap((entityId) => {+ const dashcard = questionDashcards.find(+ ({ card }) => card.entity_id === entityId,+ );+ return dashcard ? [dashcard] : [];+ });+}++export function getDashboardIdParameter(+ auditDashboard: Pick<Dashboard, "parameters">,+): Parameter | undefined {+ return auditDashboard.parameters?.find(+ (parameter) => parameter.slug === DASHBOARD_ID_PARAMETER_SLUG,+ );+}++/**+ * Returns the audit dashboard parameters to send with each usage stats card query: every parameter with a shipped+ * default, set to that default, plus the dashboard id filter set to `dashboardId`. The backend ignores dashboard+ * parameter defaults for a dashcard query, so they must be sent as values.+ */+export function getUsageStatsParameters(+ auditDashboard: Pick<Dashboard, "parameters">,+ dashboardId: DashboardId,+): NormalizedQueryParameter[] {+ const dashboardIdParameter = getDashboardIdParameter(auditDashboard);+ const parameterValues: ParameterValuesMap =+ dashboardIdParameter != null+ ? { [dashboardIdParameter.id]: [dashboardId] }+ : {};+ const parametersWithValues = getDefaultValuePopulatedParameters(+ auditDashboard.parameters ?? [],+ parameterValues,+ ).filter((parameter) => parameter.value != null);++ return normalizeParameters(parametersWithValues);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/utils.unit.spec.tsnew file mode 100644index 00000000000..5380c29e1b6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardUsageStatsPage/utils.unit.spec.ts@@ -0,0 +1,135 @@+import {+ createMockCard,+ createMockDashboard,+ createMockDashboardCard,+ createMockHeadingDashboardCard,+ createMockParameter,+} from "metabase-types/api/mocks";+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";++import { USAGE_STATS_CARD_ENTITY_IDS } from "./constants";+import {+ getDashboardIdParameter,+ getUsageStatsDashcards,+ getUsageStatsParameters,+} from "./utils";++const [VIEWS_ENTITY_ID, PEOPLE_ENTITY_ID, ACTIVITY_ENTITY_ID] =+ USAGE_STATS_CARD_ENTITY_IDS;++function createDashcard(id: number, entityId: string) {+ return createMockDashboardCard({+ id,+ card: createMockCard({ id, entity_id: createMockEntityId(entityId) }),+ });+}++describe("getUsageStatsDashcards", () => {+ it("returns the usage stats dashcards in display order", () => {+ const activity = createDashcard(1, ACTIVITY_ENTITY_ID);+ const views = createDashcard(2, VIEWS_ENTITY_ID);+ const people = createDashcard(3, PEOPLE_ENTITY_ID);+ const other = createDashcard(4, "some-other-entity-id");++ const dashboard = createMockDashboard({+ dashcards: [+ activity,+ createMockHeadingDashboardCard({ id: 5 }),+ other,+ people,+ views,+ ],+ });++ expect(getUsageStatsDashcards(dashboard)).toEqual([+ views,+ people,+ activity,+ ]);+ });++ it("skips cards the audit dashboard does not have", () => {+ const people = createDashcard(1, PEOPLE_ENTITY_ID);++ expect(+ getUsageStatsDashcards(createMockDashboard({ dashcards: [people] })),+ ).toEqual([people]);+ });+});++describe("getDashboardIdParameter", () => {+ it("finds the parameter by its slug", () => {+ const dashboardIdParameter = createMockParameter({+ id: "4b39cd95",+ slug: "dashboard_id",+ type: "id",+ });+ const dashboard = createMockDashboard({+ parameters: [+ createMockParameter({ id: "25f8871e", slug: "date_filter" }),+ dashboardIdParameter,+ ],+ });++ expect(getDashboardIdParameter(dashboard)).toBe(dashboardIdParameter);+ });++ it("returns undefined when the audit dashboard has no such parameter", () => {+ expect(+ getDashboardIdParameter(createMockDashboard({ parameters: [] })),+ ).toBeUndefined();+ });+});++describe("getUsageStatsParameters", () => {+ const dateFilterParameter = createMockParameter({+ id: "25f8871e",+ slug: "date_filter",+ type: "date/all-options",+ default: "past12months~",+ });+ const groupNameParameter = createMockParameter({+ id: "2ea1dae2",+ slug: "group_name",+ type: "string/=",+ default: ["All Users"],+ required: true,+ });+ const dashboardIdParameter = createMockParameter({+ id: "4b39cd95",+ slug: "dashboard_id",+ type: "id",+ });+ const dashboardNameParameter = createMockParameter({+ id: "c02bd3d3",+ slug: "dashboard_name",+ type: "string/=",+ });++ it("returns the parameter defaults and the dashboard id, skipping parameters without a default", () => {+ const dashboard = createMockDashboard({+ parameters: [+ dateFilterParameter,+ groupNameParameter,+ dashboardIdParameter,+ dashboardNameParameter,+ ],+ });++ expect(getUsageStatsParameters(dashboard, 10)).toEqual([+ { id: "25f8871e", type: "date/all-options", value: "past12months~" },+ { id: "2ea1dae2", type: "string/=", value: ["All Users"] },+ { id: "4b39cd95", type: "id", value: [10] },+ ]);+ });++ it("overrides a default of the dashboard id parameter", () => {+ const dashboard = createMockDashboard({+ parameters: [{ ...dashboardIdParameter, default: [1] }],+ });++ expect(getUsageStatsParameters(dashboard, 10)).toEqual([+ { id: "4b39cd95", type: "id", value: [10] },+ ]);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/DashboardsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/DashboardsPage.tsxnew file mode 100644index 00000000000..262b4d01a6b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/DashboardsPage.tsx@@ -0,0 +1,153 @@+import { useDisclosure } from "@mantine/hooks";+import { type ReactNode, useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "metabase/common/collections/components/CollectionRowModal";+import { Unauthorized } from "metabase/common/components/ErrorPages";+import { LibraryTreePage } from "metabase/data-studio/common/components/LibraryTreePage";+import { useErrorHandling } from "metabase/data-studio/common/hooks/use-error-handling";+import type { TreeItem } from "metabase/data-studio/common/types";+import { isCollectionData } from "metabase/data-studio/common/utils";+import type { CollectionItemModel } from "metabase-types/api";++import { LibraryEmptyState } from "../../../components/LibraryEmptyState";+import { useCollectionItemsTree } from "../../../hooks/use-collection-items-tree";+import {+ type LibraryCollections,+ useLibraryCollections,+} from "../../../hooks/use-library-collections";+import {+ type LibrarySearchModel,+ useLibrarySearchResults,+} from "../../../hooks/use-library-search-results";+import { CreateLibraryDashboardModal } from "../../components/CreateLibraryDashboardModal";++import { NewDashboardMenu } from "./NewDashboardMenu";++const ITEM_MODELS: CollectionItemModel[] = ["dashboard", "collection"];+const SEARCH_MODELS: LibrarySearchModel[] = ["dashboard"];+const NO_ITEMS: TreeItem[] = [];++export function DashboardsPage() {+ const [searchQuery, setSearchQuery] = useState("");+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();+ const [+ isCreateDashboardModalOpened,+ { open: openCreateDashboardModal, close: closeCreateDashboardModal },+ ] = useDisclosure(false);+ const libraryCollections = useLibraryCollections();+ const { isLoading: isLoadingCollections, dashboardCollection } =+ libraryCollections;+ const {+ items,+ isLoading: isLoadingItems,+ error: itemsError,+ watchRows,+ isChildrenLoading,+ } = useCollectionItemsTree(dashboardCollection, ITEM_MODELS);+ const {+ items: searchItems,+ isActive: isSearchActive,+ isLoading: isSearchLoading,+ error: searchError,+ } = useLibrarySearchResults(+ searchQuery,+ dashboardCollection?.id,+ SEARCH_MODELS,+ );+ useErrorHandling(itemsError || searchError);++ const writableDashboardCollection = dashboardCollection?.can_write+ ? dashboardCollection+ : undefined;+ const defaultMoveCollectionIds = useMemo(+ () => ({ dashboards: dashboardCollection?.id }),+ [dashboardCollection],+ );+ const renderRowMenu = useCallback(+ (item: TreeItem) => (+ <DashboardRowMenu item={item} onOpenModal={setCollectionModal} />+ ),+ [],+ );++ return (+ <LibraryTreePage+ title={t`Dashboards`}+ tree={isSearchActive ? searchItems : (items ?? NO_ITEMS)}+ isLoading={isLoadingCollections || isLoadingItems || isSearchLoading}+ isSearchActive={isSearchActive}+ searchQuery={searchQuery}+ emptyMessage={t`No dashboards yet`}+ defaultMoveCollectionIds={defaultMoveCollectionIds}+ emptyState={getEmptyState(libraryCollections)}+ createMenu={+ writableDashboardCollection && (+ <NewDashboardMenu+ dashboardCollectionId={writableDashboardCollection.id}+ onNewDashboardClick={openCreateDashboardModal}+ />+ )+ }+ pageMenu={{+ label: t`Dashboard options`,+ permissionsCollection: dashboardCollection,+ onOpenModal: setCollectionModal,+ }}+ renderRowMenu={renderRowMenu}+ isChildrenLoading={isChildrenLoading}+ onRowsChange={watchRows}+ onSearchQueryChange={setSearchQuery}+ >+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}+ />+ {writableDashboardCollection && (+ <CreateLibraryDashboardModal+ opened={isCreateDashboardModalOpened}+ collectionId={writableDashboardCollection.id}+ onClose={closeCreateDashboardModal}+ />+ )}+ </LibraryTreePage>+ );+}++function getEmptyState({+ isLoading,+ libraryCollection,+ dashboardCollection,+}: LibraryCollections): ReactNode {+ if (isLoading) {+ return undefined;+ }+ if (libraryCollection == null) {+ return <LibraryEmptyState />;+ }+ // The collection tree leaves out the sections the user cannot read+ if (dashboardCollection == null) {+ return <Unauthorized />;+ }+ return undefined;+}++type DashboardRowMenuProps = {+ item: TreeItem;+ onOpenModal: (modal: CollectionRowModalState) => void;+};++function DashboardRowMenu({+ item: { data },+ onOpenModal,+}: DashboardRowMenuProps) {+ if (!isCollectionData(data)) {+ return null;+ }+ return <CollectionRowMenu collection={data} onOpenModal={onOpenModal} />;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/DashboardsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/DashboardsPage.unit.spec.tsxnew file mode 100644index 00000000000..89c39afef59--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/DashboardsPage.unit.spec.tsx@@ -0,0 +1,325 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupCollectionItemsEndpoint,+ setupCollectionTreeEndpoint,+ setupDashboardEndpoints,+ setupSearchEndpoints,+ setupUnauthorizedCollectionEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { createMockState } from "__support__/state";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Route } from "metabase/router";+import type { CollectionItem, SearchResult } from "metabase-types/api";+import {+ createMockCollection,+ createMockCollectionItem,+ createMockDashboard,+ createMockSearchResult,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { DashboardsPage } from "./DashboardsPage";++const SALES_FOLDER = createMockCollectionItem({+ id: 3,+ model: "collection",+ name: "Sales",+ type: "library-dashboards",+ here: ["dashboard"],+});++const REVENUE_DASHBOARD = createMockCollectionItem({+ id: 20,+ model: "dashboard",+ name: "Revenue overview",+ can_write: true,+});++const DASHBOARDS_COLLECTION_ID = 2;++type SetupOpts = {+ hasLibrary?: boolean;+ canRead?: boolean;+ canWrite?: boolean;+ isRemoteSyncReadOnly?: boolean;+ items?: CollectionItem[];+ searchResults?: SearchResult[];+ hasItemsError?: boolean;+};++function setup({+ hasLibrary = true,+ canRead = true,+ canWrite = true,+ isRemoteSyncReadOnly = false,+ items = [SALES_FOLDER, REVENUE_DASHBOARD],+ searchResults = [],+ hasItemsError = false,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 800 });+ const settings = mockSettings({+ "token-features": createMockTokenFeatures({+ library: true,+ remote_sync: isRemoteSyncReadOnly,+ }),+ "remote-sync-enabled": isRemoteSyncReadOnly,+ "remote-sync-type": isRemoteSyncReadOnly ? "read-only" : undefined,+ });+ setupEnterpriseOnlyPlugin("library");+ setupEnterpriseOnlyPlugin("remote_sync");++ const dashboardsCollection = createMockCollection({+ id: DASHBOARDS_COLLECTION_ID,+ name: "Dashboards",+ type: "library-dashboards",+ can_write: canWrite,+ });+ const libraryCollection = createMockCollection({+ id: 1,+ name: "Library",+ type: "library",+ children: canRead ? [dashboardsCollection] : [],+ });+ setupCollectionTreeEndpoint(hasLibrary ? [libraryCollection] : []);+ if (hasItemsError) {+ setupUnauthorizedCollectionEndpoints(dashboardsCollection);+ } else {+ setupCollectionItemsEndpoint({+ collection: dashboardsCollection,+ collectionItems: items,+ });+ }+ setupSearchEndpoints(searchResults);+ setupDashboardEndpoints(+ createMockDashboard({ id: REVENUE_DASHBOARD.id, name: "Revenue overview" }),+ );++ return renderWithProviders(+ <Route path="/data-studio/dashboards" element={<DashboardsPage />} />,+ {+ withRouter: true,+ withUndos: true,+ initialRoute: "/data-studio/dashboards",+ storeInitialState: createMockState({ settings }),+ },+ );+}++describe("DashboardsPage", () => {+ it("lists folders and dashboards at the top level, linking each dashboard to its Data Studio page", async () => {+ setup();++ expect(await screen.findByText("Sales")).toBeInTheDocument();+ expect(+ screen.getAllByTestId("collection-name").map((row) => row.textContent),+ ).toEqual(["Sales"]);+ expect(+ screen.getByRole("link", { name: /Revenue overview/ }),+ ).toHaveAttribute("href", "/data-studio/dashboards/20");+ });++ it("offers New when the user can write the Dashboards collection", async () => {+ setup();++ await userEvent.click(await screen.findByRole("button", { name: /New/ }));+ expect(+ await screen.findByRole("menuitem", { name: /Dashboard/ }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("menuitem", { name: /Collection/ }),+ ).toBeInTheDocument();+ });++ it("opens the New collection modal in the Dashboards collection", async () => {+ const { store } = setup();++ await userEvent.click(await screen.findByRole("button", { name: /New/ }));+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Collection/ }),+ );++ expect(store.getState().modal).toMatchObject({+ id: "collection",+ props: {+ initialCollectionId: DASHBOARDS_COLLECTION_ID,+ namespaces: [null],+ pickerOptions: { hasLibrary: true, hasRootCollection: false },+ },+ });+ });++ it.each([+ { name: "the user cannot write", canWrite: false },+ { name: "remote sync is read-only", isRemoteSyncReadOnly: true },+ ])("hides New when $name", async ({ canWrite, isRemoteSyncReadOnly }) => {+ setup({ canWrite, isRemoteSyncReadOnly });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /New/ }),+ ).not.toBeInTheDocument();+ });++ it("says when there are no dashboards yet", async () => {+ setup({ items: [] });++ expect(await screen.findByText("No dashboards yet")).toBeInTheDocument();+ });++ it("searches dashboards and reports when nothing matches", async () => {+ setup({+ searchResults: [+ createMockSearchResult({+ id: 20,+ model: "dashboard",+ name: "Revenue overview",+ }),+ ],+ });+ const searchInput = await screen.findByPlaceholderText("Search...");++ await userEvent.type(searchInput, "revenue");+ await waitFor(() =>+ expect(screen.queryByText("Sales")).not.toBeInTheDocument(),+ );+ expect(+ await screen.findByRole("link", { name: /Revenue overview/ }),+ ).toHaveAttribute("href", "/data-studio/dashboards/20");++ await userEvent.clear(searchInput);+ await userEvent.type(searchInput, "churn");+ expect(+ await screen.findByText('No results for "churn"'),+ ).toBeInTheDocument();+ });++ it("reports an error when the dashboards cannot be fetched", async () => {+ setup({ hasItemsError: true });++ expect(+ await screen.findByText(/Data couldn't be fetched properly/, undefined, {+ timeout: 3000,+ }),+ ).toBeInTheDocument();+ });++ it("moves a selected dashboard to the trash and refreshes the list", async () => {+ setup();+ const dashboardRow = await screen.findByRole("row", {+ name: /Revenue overview/,+ });++ await userEvent.click(+ within(dashboardRow).getByRole("checkbox", { name: "Select row" }),+ );+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();++ setupCollectionItemsEndpoint({+ collection: { id: DASHBOARDS_COLLECTION_ID },+ collectionItems: [SALES_FOLDER],+ });+ await userEvent.click(+ screen.getByRole("button", { name: "Move to trash" }),+ );+ await userEvent.click(+ within(await screen.findByRole("dialog")).getByRole("button", {+ name: "Move to trash",+ }),+ );++ await waitFor(() =>+ expect(screen.queryByText("Revenue overview")).not.toBeInTheDocument(),+ );+ expect(screen.getByText("Sales")).toBeInTheDocument();+ expect(screen.queryByText("1 item selected")).not.toBeInTheDocument();+ const archiveCalls = fetchMock.callHistory.calls(+ `path:/api/dashboard/${REVENUE_DASHBOARD.id}`,+ { method: "PUT" },+ );+ expect(archiveCalls).toHaveLength(1);+ const archiveBody: unknown = JSON.parse(+ String(archiveCalls[0].options.body),+ );+ expect(archiveBody).toEqual({ archived: true });+ });++ it("selects every top-level row with Select all, and clears them on a second click", async () => {+ setup();+ const dashboardRow = await screen.findByRole("row", {+ name: /Revenue overview/,+ });+ const selectAll = screen.getByRole("checkbox", { name: "Select all" });++ await userEvent.click(+ within(dashboardRow).getByRole("checkbox", { name: "Select row" }),+ );+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();+ expect(selectAll).toBePartiallyChecked();++ await userEvent.click(selectAll);+ expect(await screen.findByText("2 items selected")).toBeInTheDocument();+ expect(selectAll).toBeChecked();+ expect(+ within(screen.getByRole("row", { name: /Sales/ })).getByRole("checkbox"),+ ).toBeChecked();++ await userEvent.click(selectAll);+ await waitFor(() =>+ expect(screen.queryByText("2 items selected")).not.toBeInTheDocument(),+ );+ expect(selectAll).not.toBeChecked();+ expect(selectAll).not.toBePartiallyChecked();+ });++ it("clears the selection when the search changes", async () => {+ setup();+ const dashboardRow = await screen.findByRole("row", {+ name: /Revenue overview/,+ });+ await userEvent.click(+ within(dashboardRow).getByRole("checkbox", { name: "Select row" }),+ );+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();++ await userEvent.type(screen.getByPlaceholderText("Search..."), "sales");++ await waitFor(() =>+ expect(screen.queryByText("1 item selected")).not.toBeInTheDocument(),+ );+ });++ it("offers no row selection when remote sync is read-only", async () => {+ setup({ isRemoteSyncReadOnly: true });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();+ });++ it("says the user has no access when they cannot read the Dashboards collection", async () => {+ setup({ canRead: false });++ expect(+ await screen.findByText("Sorry, you don’t have permission to see that."),+ ).toBeInTheDocument();+ expect(screen.queryByPlaceholderText("Search...")).not.toBeInTheDocument();+ expect(screen.queryByText("No dashboards yet")).not.toBeInTheDocument();+ });++ it("offers to create the semantic layer when there is no library", async () => {+ setup({ hasLibrary: false });++ expect(+ await screen.findByText("Create my semantic layer"),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/NewDashboardMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/NewDashboardMenu.tsxnew file mode 100644index 00000000000..6106d62ae8c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/NewDashboardMenu.tsx@@ -0,0 +1,53 @@+import { t } from "ttag";++import { openNewCollectionModal } from "metabase/data-studio/common/utils";+import { useDispatch } from "metabase/redux";+import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";+import type { CollectionId, CollectionNamespace } from "metabase-types/api";++import { LIBRARY_COLLECTION_PICKER_OPTIONS } from "../../../constants";++const LIBRARY_COLLECTION_NAMESPACES: CollectionNamespace[] = [null];++type NewDashboardMenuProps = {+ dashboardCollectionId: CollectionId;+ onNewDashboardClick: () => void;+};++export function NewDashboardMenu({+ dashboardCollectionId,+ onNewDashboardClick,+}: NewDashboardMenuProps) {+ const dispatch = useDispatch();++ const handleNewCollectionClick = () =>+ dispatch(+ openNewCollectionModal({+ initialCollectionId: dashboardCollectionId,+ namespaces: LIBRARY_COLLECTION_NAMESPACES,+ pickerOptions: LIBRARY_COLLECTION_PICKER_OPTIONS,+ }),+ );++ return (+ <Menu position="bottom-end">+ <Menu.Target>+ <Button size="lg" leftSection={<Icon name="add" />}>{t`New`}</Button>+ </Menu.Target>+ <Menu.Dropdown>+ <Menu.Item+ leftSection={<FixedSizeIcon name="dashboard" />}+ onClick={onNewDashboardClick}+ >+ {t`Dashboard`}+ </Menu.Item>+ <Menu.Item+ leftSection={<FixedSizeIcon name="folder" />}+ onClick={handleNewCollectionClick}+ >+ {t`Collection`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/index.tsnew file mode 100644index 00000000000..3b5ca1a62ee--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsPage/index.ts@@ -0,0 +1 @@+export { DashboardsPage } from "./DashboardsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsSectionLayout/DashboardsSectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsSectionLayout/DashboardsSectionLayout.tsxnew file mode 100644index 00000000000..9766e470e60--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsSectionLayout/DashboardsSectionLayout.tsx@@ -0,0 +1,10 @@+import { t } from "ttag";++import { usePageTitle } from "metabase/hooks/use-page-title";+import { Outlet } from "metabase/router";++export function DashboardsSectionLayout() {+ usePageTitle(t`Dashboards`);++ return <Outlet />;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsSectionLayout/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsSectionLayout/index.tsnew file mode 100644index 00000000000..51b70aea9d2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/pages/DashboardsSectionLayout/index.ts@@ -0,0 +1 @@+export { DashboardsSectionLayout } from "./DashboardsSectionLayout";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/routes.tsxnew file mode 100644index 00000000000..6a0bbb7854d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/routes.tsx@@ -0,0 +1,74 @@+import { PLUGIN_AUDIT, PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { Route } from "metabase/router";++import { DashboardsSectionLayout } from "./pages/DashboardsSectionLayout";++/**+ * The Data Studio dashboard pages, in one chunk. The section layout stays+ * eager: it frames every page under it, so it is on screen before any of them+ * arrive.+ */+const dashboardsPage = () =>+ import(+ /* webpackChunkName: "data-studio-dashboards" */ "./pages/DashboardsPage"+ ).then(({ DashboardsPage }) => ({ Component: DashboardsPage }));++const dashboardOverviewPage = () =>+ import(+ /* webpackChunkName: "data-studio-dashboards" */ "./pages/DashboardOverviewPage"+ ).then(({ DashboardOverviewPage }) => ({+ Component: DashboardOverviewPage,+ }));++const dashboardContentsPage = () =>+ import(+ /* webpackChunkName: "data-studio-dashboards" */ "./pages/DashboardContentsPage"+ ).then(({ DashboardContentsPage }) => ({+ Component: DashboardContentsPage,+ }));++const dashboardDependenciesPage = () =>+ import(+ /* webpackChunkName: "data-studio-dashboards" */ "./pages/DashboardDependenciesPage"+ ).then(({ DashboardDependenciesPage }) => ({+ Component: DashboardDependenciesPage,+ }));++const dashboardUsageStatsPage = () =>+ import(+ /* webpackChunkName: "data-studio-dashboards" */ "./pages/DashboardUsageStatsPage"+ ).then(({ DashboardUsageStatsPage }) => ({+ Component: DashboardUsageStatsPage,+ }));++const dashboardSubscriptionsPage = () =>+ import(+ /* webpackChunkName: "data-studio-dashboards" */ "./pages/DashboardSubscriptionsPage"+ ).then(({ DashboardSubscriptionsPage }) => ({+ Component: DashboardSubscriptionsPage,+ }));++export function getDataStudioDashboardRoutes() {+ return (+ <Route path="dashboards" element={<DashboardsSectionLayout />}>+ <Route index lazy={dashboardsPage} />+ <Route path=":dashboardId" lazy={dashboardOverviewPage} />+ <Route path=":dashboardId/contents" lazy={dashboardContentsPage} />+ {PLUGIN_DEPENDENCIES.isEnabled && (+ <Route+ path=":dashboardId/dependencies"+ lazy={dashboardDependenciesPage}+ >+ <Route index element={<PLUGIN_DEPENDENCIES.DependencyGraphPage />} />+ </Route>+ )}+ {PLUGIN_AUDIT.isEnabled && (+ <Route path=":dashboardId/usage" lazy={dashboardUsageStatsPage} />+ )}+ <Route+ path=":dashboardId/subscriptions/:subscriptionId?"+ lazy={dashboardSubscriptionsPage}+ />+ </Route>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/routes.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/routes.unit.spec.tsxnew file mode 100644index 00000000000..0e52a693467--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/routes.unit.spec.tsx@@ -0,0 +1,206 @@+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupAuditInfoEndpoint,+ setupCollectionByIdEndpoint,+ setupDashboardEndpoints,+} from "__support__/server-mocks";+import { setupDependencyGraphEndpoint } from "__support__/server-mocks/dependencies";+import {+ setupListSubscriptionsEndpoint,+ setupNotificationChannelsEndpoints,+} from "__support__/server-mocks/pulse";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen, within } from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";+import { reinitialize } from "metabase/plugins";+import { Route } from "metabase/router";+import {+ createMockCollection,+ createMockDashboard,+ createMockDependencyGraph,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { getDataStudioDashboardRoutes } from "./routes";++const DASHBOARD = createMockDashboard({ id: 10, name: "Sales overview" });+const CONTENTS_PATH = "/data-studio/dashboards/10/contents";+const DEPENDENCIES_PATH = "/data-studio/dashboards/10/dependencies";+const USAGE_PATH = "/data-studio/dashboards/10/usage";+const SUBSCRIPTIONS_PATH = "/data-studio/dashboards/10/subscriptions";+const SUBSCRIPTION_PATH = "/data-studio/dashboards/10/subscriptions/1";+const AUDIT_DASHBOARD = createMockDashboard({+ id: 201,+ name: "Dashboard overview",+});++type SetupOpts = {+ initialRoute: string;+ hasUsageAnalyticsAccess?: boolean;+};++function setup({ initialRoute, hasUsageAnalyticsAccess = true }: SetupOpts) {+ setupDashboardEndpoints(DASHBOARD);+ setupDashboardEndpoints(AUDIT_DASHBOARD);+ setupListSubscriptionsEndpoint([]);+ setupNotificationChannelsEndpoints({});+ setupAuditInfoEndpoint({+ auditInfo: hasUsageAnalyticsAccess+ ? { dashboard_overview: AUDIT_DASHBOARD.id }+ : {},+ });+ setupCollectionByIdEndpoint({+ collections: [createMockCollection(ROOT_COLLECTION)],+ });+ setupDependencyGraphEndpoint(createMockDependencyGraph());++ renderWithProviders(+ <>+ <Route path="/data-studio">{getDataStudioDashboardRoutes()}</Route>+ <Route path="*" element={<div>No route matched</div>} />+ </>,+ { withRouter: true, initialRoute },+ );+}++beforeEach(() => {+ reinitialize();+});++describe("Data Studio dashboard routes without plugins", () => {+ it("has no Dependencies tab", async () => {+ setup({ initialRoute: CONTENTS_PATH });++ const header = await screen.findByTestId("dashboard-pane-header");+ expect(+ within(header).getByRole("link", { name: "Contents" }),+ ).toBeInTheDocument();+ expect(+ within(header).queryByRole("link", { name: "Dependencies" }),+ ).not.toBeInTheDocument();+ });++ it("has no Dependencies page", async () => {+ setup({ initialRoute: DEPENDENCIES_PATH });++ expect(await screen.findByText("No route matched")).toBeInTheDocument();+ });++ it("has no Usage stats tab", async () => {+ setup({ initialRoute: CONTENTS_PATH });++ const header = await screen.findByTestId("dashboard-pane-header");+ expect(+ within(header).queryByRole("link", { name: "Usage stats" }),+ ).not.toBeInTheDocument();+ });++ it("has no Usage stats page", async () => {+ setup({ initialRoute: USAGE_PATH });++ expect(await screen.findByText("No route matched")).toBeInTheDocument();+ });++ it.each([SUBSCRIPTIONS_PATH, SUBSCRIPTION_PATH])(+ "renders the Subscriptions page with its tab selected at %s",+ async (initialRoute) => {+ setup({ initialRoute });++ expect(+ await screen.findByTestId("dashboard-subscriptions-page"),+ ).toBeInTheDocument();+ const header = screen.getByTestId("dashboard-pane-header");+ expect(+ within(header).getByRole("link", { name: "Subscriptions" }),+ ).toHaveAttribute("aria-current", "page");+ },+ );+});++describe("Data Studio dashboard routes with the dependencies plugin", () => {+ beforeEach(() => {+ mockSettings({+ "token-features": createMockTokenFeatures({ dependencies: true }),+ });+ setupEnterpriseOnlyPlugin("dependencies");+ });++ it("links the Dependencies tab to the dashboard's dependency graph", async () => {+ setup({ initialRoute: CONTENTS_PATH });++ const header = await screen.findByTestId("dashboard-pane-header");+ expect(+ within(header).getByRole("link", { name: "Dependencies" }),+ ).toHaveAttribute("href", DEPENDENCIES_PATH);+ });++ it("renders the Dependencies page with its tab selected", async () => {+ setup({ initialRoute: DEPENDENCIES_PATH });++ const header = await screen.findByTestId("dashboard-pane-header");+ expect(+ within(header).getByRole("link", { name: "Dependencies" }),+ ).toHaveAttribute("aria-current", "page");+ expect(screen.queryByText("No route matched")).not.toBeInTheDocument();+ });+});++describe("Data Studio dashboard routes with the audit app plugin", () => {+ beforeEach(() => {+ mockSettings({+ "token-features": createMockTokenFeatures({+ dependencies: true,+ audit_app: true,+ }),+ });+ setupEnterpriseOnlyPlugin("dependencies");+ setupEnterpriseOnlyPlugin("audit_app");+ });++ it("puts the Usage stats tab between Dependencies and Subscriptions", async () => {+ setup({ initialRoute: CONTENTS_PATH });++ const header = await screen.findByTestId("dashboard-pane-header");+ const usageTab = await within(header).findByRole("link", {+ name: "Usage stats",+ });+ expect(usageTab).toHaveAttribute("href", USAGE_PATH);+ expect(+ within(within(header).getByRole("navigation"))+ .getAllByRole("link")+ .map((link) => link.getAttribute("aria-label")),+ ).toEqual([+ "Overview",+ "Contents",+ "Dependencies",+ "Usage stats",+ "Subscriptions",+ ]);+ });++ it("hides the Usage stats tab without access to Usage analytics", async () => {+ setup({ initialRoute: USAGE_PATH, hasUsageAnalyticsAccess: false });++ expect(+ await screen.findByText(+ "To see usage stats, you need access to the Usage analytics collection.",+ ),+ ).toBeInTheDocument();+ const header = screen.getByTestId("dashboard-pane-header");+ expect(+ within(header).queryByRole("link", { name: "Usage stats" }),+ ).not.toBeInTheDocument();+ });++ it("renders the Usage stats page with its tab selected", async () => {+ setup({ initialRoute: USAGE_PATH });++ expect(+ await screen.findByTestId("dashboard-usage-stats-page"),+ ).toBeInTheDocument();+ const header = screen.getByTestId("dashboard-pane-header");+ expect(+ await within(header).findByRole("link", { name: "Usage stats" }),+ ).toHaveAttribute("aria-current", "page");+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/utils.tsnew file mode 100644index 00000000000..f0de3544d76--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/utils.ts@@ -0,0 +1,15 @@+import { isQuestionDashCard } from "metabase/utils/dashboard";+import type { Card, Dashboard, UnreadableCard } from "metabase-types/api";++/**+ * The cards a dashboard's question dashcards show, series included, in+ * dashcard order and as the API sends them, so a card the user cannot read is+ * a bare `{ id }`.+ */+export function getDashcardCards(+ dashboard: Pick<Dashboard, "dashcards">,+): (Card | UnreadableCard)[] {+ return dashboard.dashcards+ .filter(isQuestionDashCard)+ .flatMap((dashcard) => [dashcard.card, ...(dashcard.series ?? [])]);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/utils.unit.spec.tsnew file mode 100644index 00000000000..067b7a7e2a5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/dashboards/utils.unit.spec.ts@@ -0,0 +1,53 @@+import {+ createMockActionDashboardCard,+ createMockCard,+ createMockDashboard,+ createMockDashboardCard,+ createMockHeadingDashboardCard,+} from "metabase-types/api/mocks";++import { getDashcardCards } from "./utils";++const ORDERS = createMockCard({ id: 1, name: "Orders" });+const REVENUE = createMockCard({ id: 2, name: "Revenue", type: "metric" });+const CUSTOMERS = createMockCard({ id: 3, name: "Customers", type: "model" });++describe("getDashcardCards", () => {+ it("returns the cards of question dashcards and their series in dashcard order", () => {+ const dashboard = createMockDashboard({+ dashcards: [+ createMockDashboardCard({ id: 1, card: ORDERS, series: [REVENUE] }),+ createMockDashboardCard({ id: 2, card: CUSTOMERS }),+ createMockDashboardCard({ id: 3, card: ORDERS }),+ ],+ });++ expect(getDashcardCards(dashboard)).toEqual([+ ORDERS,+ REVENUE,+ CUSTOMERS,+ ORDERS,+ ]);+ });++ it("skips virtual and action dashcards", () => {+ const dashboard = createMockDashboard({+ dashcards: [+ createMockHeadingDashboardCard({ id: 1 }),+ createMockActionDashboardCard({+ id: 2,+ card: createMockCard({ id: 9, name: "Action model" }),+ }),+ createMockDashboardCard({ id: 3, card: ORDERS }),+ ],+ });++ expect(getDashcardCards(dashboard)).toEqual([ORDERS]);+ });++ it("returns nothing for an empty dashboard", () => {+ expect(getDashcardCards(createMockDashboard({ dashcards: [] }))).toEqual(+ [],+ );+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-collection-items-tree/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-collection-items-tree/index.tsnew file mode 100644index 00000000000..a9cbf83ce26--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-collection-items-tree/index.ts@@ -0,0 +1 @@+export { useCollectionItemsTree } from "./use-collection-items-tree";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-collection-items-tree/use-collection-items-tree.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-collection-items-tree/use-collection-items-tree.tsnew file mode 100644index 00000000000..98f13d7eef9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-collection-items-tree/use-collection-items-tree.ts@@ -0,0 +1,264 @@+import type { Row } from "@tanstack/react-table";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { shallowEqual } from "react-redux";++import {+ collectionApi,+ skipToken,+ useListCollectionItemsQuery,+} from "metabase/api";+import type { TreeItem } from "metabase/data-studio/common/types";+import { useGetIcon } from "metabase/hooks/use-icon";+import { useDispatch, useSelector } from "metabase/redux";+import type { State } from "metabase/redux/store";+import type {+ Collection,+ CollectionId,+ CollectionItem,+ CollectionItemModel,+} from "metabase-types/api";++const NO_ITEMS: CollectionItem[] = [];++const getCollectionItemsRequest = (+ collectionId: CollectionId,+ models: CollectionItemModel[],+) => ({+ id: collectionId,+ models,+ archived: false,+});++type CollectionItemsTree = {+ /** The collection's folders and items, or nothing until they have loaded */+ items: TreeItem[] | undefined;+ isLoading: boolean;+ error: unknown;+ watchRows: (rows: Row<TreeItem>[]) => void;+ isChildrenLoading: (row: Row<TreeItem>) => boolean;+};++/**+ * The folders and `models` items of a collection, with folders loading their+ * own items once their rows expand. `watchRows` subscribes the expanded folders+ * of this tree to the API cache, so a later invalidation refreshes them.+ */+export function useCollectionItemsTree(+ collection: Collection | undefined,+ models: CollectionItemModel[],+): CollectionItemsTree {+ const dispatch = useDispatch();+ const getIcon = useGetIcon();++ const {+ data: topLevelItems,+ isLoading,+ error,+ } = useListCollectionItemsQuery(+ collection ? getCollectionItemsRequest(collection.id, models) : skipToken,+ );++ const [expandedCollectionIds, setExpandedCollectionIds] = useState<+ CollectionId[]+ >([]);+ const subscriptionsRef = useRef(+ new Map<CollectionId, { unsubscribe: () => void }>(),+ );++ const collectionId = collection?.id;+ useEffect(() => {+ setExpandedCollectionIds((ids) => (ids.length > 0 ? [] : ids));+ }, [collectionId, models]);++ useEffect(() => {+ const subscriptions = subscriptionsRef.current;+ expandedCollectionIds.forEach((expandedId) => {+ if (!subscriptions.has(expandedId)) {+ subscriptions.set(+ expandedId,+ dispatch(+ collectionApi.endpoints.listCollectionItems.initiate(+ getCollectionItemsRequest(expandedId, models),+ ),+ ),+ );+ }+ });+ subscriptions.forEach((subscription, expandedId) => {+ if (!expandedCollectionIds.includes(expandedId)) {+ subscription.unsubscribe();+ subscriptions.delete(expandedId);+ }+ });+ }, [dispatch, expandedCollectionIds, models]);++ useEffect(() => {+ const subscriptions = subscriptionsRef.current;+ return () => {+ subscriptions.forEach((subscription) => subscription.unsubscribe());+ subscriptions.clear();+ };+ }, []);++ const expandedCollectionSelectors = useMemo(+ () =>+ expandedCollectionIds.map((expandedId) =>+ collectionApi.endpoints.listCollectionItems.select(+ getCollectionItemsRequest(expandedId, models),+ ),+ ),+ [expandedCollectionIds, models],+ );++ const expandedCollectionItems = useSelector(+ (state: State) =>+ expandedCollectionSelectors.map((selectCollectionItems) => {+ const { data, isError } = selectCollectionItems(state);+ return data?.data ?? (isError ? NO_ITEMS : undefined);+ }),+ shallowEqual,+ );++ const loadedCollections = useMemo(+ () =>+ new Map(+ expandedCollectionIds.flatMap((expandedId, index) => {+ const items = expandedCollectionItems[index];+ return items ? [[expandedId, items] as const] : [];+ }),+ ),+ [expandedCollectionIds, expandedCollectionItems],+ );++ const items = useMemo(+ (): TreeItem[] | undefined =>+ isLoading || !topLevelItems || !collection+ ? undefined+ : buildChildren(topLevelItems.data, loadedCollections, getIcon),+ [isLoading, topLevelItems, collection, loadedCollections, getIcon],+ );++ const folderIds = useMemo(() => getFolderIds(items ?? []), [items]);+ const watchRows = useCallback(+ (rows: Row<TreeItem>[]) => {+ const collectionIdsToLoad = rows.flatMap((row) => {+ const { original } = row;+ const isExpandedWithoutChildren =+ row.getIsExpanded() &&+ row.getCanExpand() &&+ original.model === "collection" &&+ original.children?.length === 0;+ return isExpandedWithoutChildren &&+ original.data.model === "collection" &&+ original.data.id !== undefined &&+ folderIds.has(original.data.id)+ ? [original.data.id]+ : [];+ });+ if (collectionIdsToLoad.length === 0) {+ return;+ }+ setExpandedCollectionIds((previousIds) => {+ const newIds = collectionIdsToLoad.filter(+ (idToLoad) => !previousIds.includes(idToLoad),+ );+ return newIds.length > 0 ? [...previousIds, ...newIds] : previousIds;+ });+ },+ [folderIds],+ );++ const isChildrenLoading = useCallback(+ (row: Row<TreeItem>): boolean =>+ row.getIsExpanded() &&+ row.getCanExpand() &&+ row.original.children?.length === 0,+ [],+ );++ return {+ items,+ isLoading,+ error,+ watchRows,+ isChildrenLoading,+ };+}++/** Build children for a collection from its fetched items. Subcollections+ * that haven't been loaded yet get `children: []` (if they have content+ * according to `here`/`below`) so they render as expandable rows that+ * trigger a lazy load, or `undefined` if they're empty. */+function buildChildren(+ items: CollectionItem[],+ loadedCollections: Map<CollectionId, CollectionItem[]>,+ getIcon: ReturnType<typeof useGetIcon>,+): TreeItem[] {+ const visibleItems = items.filter((item) => !item.archived);+ const collections = visibleItems.filter(+ (item) => item.model === "collection",+ );+ const leafItems = visibleItems.filter((item) => item.model !== "collection");++ return [+ ...collections.map((col): TreeItem => {+ const childItems = loadedCollections.get(col.id);+ let children: TreeItem[] | undefined;++ if (childItems !== undefined) {+ const built = buildChildren(childItems, loadedCollections, getIcon);+ children = built.length > 0 ? built : undefined;+ } else if (hasContent(col)) {+ children = [];+ }++ return {+ name: col.name,+ id: `collection:${col.id}`,+ icon: "folder",+ data: col,+ model: "collection",+ children,+ childrenLoaded: childItems !== undefined,+ };+ }),+ ...leafItems.map((leafItem) => buildItemNode(leafItem, getIcon)),+ ];+}++function buildItemNode(+ item: CollectionItem,+ getIcon: ReturnType<typeof useGetIcon>,+): TreeItem {+ return {+ name: item.name,+ updatedAt: item["last-edit-info"]?.timestamp,+ icon: getIcon({ model: item.model }).name,+ data: item,+ id: `${item.model}:${item.id}`,+ model: item.model,+ };+}++function hasContent(item: CollectionItem): boolean {+ return (+ (item.here != null && item.here.length > 0) ||+ (item.below != null && item.below.length > 0)+ );+}++function getFolderIds(items: TreeItem[]): Set<CollectionId> {+ return new Set(+ items.flatMap((item): CollectionId[] => {+ const { data } = item;+ if (+ item.model !== "collection" ||+ data.model !== "collection" ||+ data.id === undefined+ ) {+ return [];+ }+ return [data.id, ...getFolderIds(item.children ?? [])];+ }),+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-collections/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-collections/index.tsnew file mode 100644index 00000000000..b9bdeb39baf--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-collections/index.ts@@ -0,0 +1,4 @@+export {+ type LibraryCollections,+ useLibraryCollections,+} from "./use-library-collections";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-collections/use-library-collections.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-collections/use-library-collections.tsnew file mode 100644index 00000000000..756c807c50f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-collections/use-library-collections.ts@@ -0,0 +1,40 @@+import { useMemo } from "react";++import { useListCollectionsTreeQuery } from "metabase/api";+import { isLibraryCollection } from "metabase/common/collections/utils";+import type { Collection, CollectionType } from "metabase-types/api";++import { getAccessibleCollection } from "../../utils";++export type LibraryCollections = {+ isLoading: boolean;+ libraryCollection: Collection | undefined;+ tableCollection: Collection | undefined;+ metricCollection: Collection | undefined;+ dashboardCollection: Collection | undefined;+};++/**+ * The Library root and the section collections the user can read, from the+ * collection tree. Each is `undefined` while loading or when it is missing.+ */+export function useLibraryCollections(): LibraryCollections {+ const { data: collections, isLoading } = useListCollectionsTreeQuery({+ "exclude-other-user-collections": true,+ "exclude-archived": true,+ "include-library": true,+ });++ return useMemo(() => {+ const libraryCollection = collections?.find(isLibraryCollection);+ const getSection = (type: CollectionType) =>+ libraryCollection && getAccessibleCollection(libraryCollection, type);+ return {+ isLoading,+ libraryCollection,+ tableCollection: getSection("library-data"),+ metricCollection: getSection("library-metrics"),+ dashboardCollection: getSection("library-dashboards"),+ };+ }, [collections, isLoading]);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/index.tsnew file mode 100644index 00000000000..eb2f7c17b75--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/index.ts@@ -0,0 +1,4 @@+export {+ type LibrarySearchModel,+ useLibrarySearchResults,+} from "./use-library-search-results";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.tsnew file mode 100644index 00000000000..090e1ecde36--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.ts@@ -0,0 +1,91 @@+import { useMemo } from "react";++import { skipToken, useSearchQuery } from "metabase/api";+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";+import type { TreeItem } from "metabase/data-studio/common/types";+import { useGetIcon } from "metabase/hooks/use-icon";+import type { CollectionId, SearchResult } from "metabase-types/api";++const SEARCH_DEBOUNCE_MS = 300;+const NO_ITEMS: TreeItem[] = [];++export type LibrarySearchModel = "table" | "metric" | "dashboard";++type LibrarySearchResults = {+ items: TreeItem[];+ isActive: boolean;+ isLoading: boolean;+ error: unknown;+};++/**+ * Debounced server-side search for `models` inside a Library collection.+ * `items` is empty until the query has text and the collection is known.+ */+export function useLibrarySearchResults(+ searchQuery: string,+ collectionId: CollectionId | undefined,+ models: LibrarySearchModel[],+): LibrarySearchResults {+ const debouncedQuery = useDebouncedValue(searchQuery, SEARCH_DEBOUNCE_MS);+ const isActive = debouncedQuery.trim().length > 0;+ const getIcon = useGetIcon();++ const {+ data: searchResponse,+ isLoading,+ isFetching,+ error,+ } = useSearchQuery(+ isActive && collectionId != null+ ? {+ q: debouncedQuery,+ collection: collectionId,+ models,+ context: "library",+ }+ : skipToken,+ );++ const items = useMemo((): TreeItem[] => {+ if (!isActive || !searchResponse) {+ return NO_ITEMS;+ }+ return searchResponse.data.flatMap((result) => {+ const model = models.find((searchModel) => searchModel === result.model);+ return model ? [createSearchResultItem(result, model, getIcon)] : [];+ });+ }, [isActive, searchResponse, models, getIcon]);++ return {+ items,+ isActive,+ isLoading: isLoading || isFetching,+ error,+ };+}++function createSearchResultItem(+ result: SearchResult,+ model: LibrarySearchModel,+ getIcon: ReturnType<typeof useGetIcon>,+): TreeItem {+ return {+ id: `${model}:${result.id}`,+ name: result.name,+ icon: getIcon({ model }).name,+ updatedAt: result.last_edited_at ?? result.updated_at,+ model,+ parentCollectionName: result.collection?.name,+ data: {+ id: Number(result.id),+ model,+ name: result.name,+ description: result.description,+ collection_id: result.collection_id ?? null,+ archived: result.archived ?? false,+ collection_position: result.collection_position,+ "last-edit-info": result["last-edit-info"],+ },+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.tsindex 7319984fc03..4d9ff5a3531 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts@@ -8,6 +8,7 @@ import { CreateLibraryModal } from "./components/CreateLibraryModal";import { DataReferenceLibraryPane } from "./components/DataReferenceLibraryPane";import { PublishTablesModal } from "./components/PublishTablesModal";import { UnpublishTablesModal } from "./components/UnpublishTablesModal";+import { getDataStudioDashboardRoutes } from "./dashboards/routes";import { useGetLibraryChildCollectionByType } from "./hooks/use-get-library-child-collection-by-type";import { useGetLibraryCollection } from "./hooks/use-get-library-collection";import { useGetResolvedLibraryCollection } from "./hooks/use-get-resolved-library-collection";@@ -25,6 +26,7 @@ export function initializePlugin() {if (hasPremiumFeature("library")) {PLUGIN_LIBRARY.isEnabled = true;PLUGIN_LIBRARY.getDataStudioLibraryRoutes = getDataStudioLibraryRoutes;+ PLUGIN_LIBRARY.getDataStudioDashboardRoutes = getDataStudioDashboardRoutes;PLUGIN_LIBRARY.useGetLibraryCollection = useGetLibraryCollection;PLUGIN_LIBRARY.useGetLibraryChildCollectionByType =useGetLibraryChildCollectionByType;diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.tsxindex 7ca742f2007..755d4e73650 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.tsx@@ -4,13 +4,14 @@ import { t } from "ttag";import { ForwardRefLink } from "metabase/common/components/Link";import { trackMetricCreateStarted } from "metabase/common/data-studio/analytics";import { canUserCreateQueries } from "metabase/current-user";+import { openNewCollectionModal } from "metabase/data-studio/common/utils";import { useDispatch, useSelector } from "metabase/redux";-import { setOpenModalWithProps } from "metabase/redux/ui";import { useNavigate } from "metabase/router";import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";import type { CollectionId, CollectionNamespace } from "metabase-types/api";+import { LIBRARY_COLLECTION_PICKER_OPTIONS } from "../../../constants";import { PublishTableModal } from "../PublishTableModal";export const CreateMenu = ({@@ -18,17 +19,11 @@ export const CreateMenu = ({canWriteToMetricCollection,dataCollectionId,canWriteToDataCollection,- dashboardCollectionId,- canWriteToDashboardCollection,- onNewDashboardClick,}: {metricCollectionId?: CollectionId;canWriteToMetricCollection?: boolean;dataCollectionId?: CollectionId;canWriteToDataCollection?: boolean;- dashboardCollectionId?: CollectionId;- canWriteToDashboardCollection?: boolean;- onNewDashboardClick: () => void;}) => {const dispatch = useDispatch();const navigate = useNavigate();@@ -41,20 +36,15 @@ export const CreateMenu = ({const canCreateMetric =hasDataAccess && metricCollectionId && canWriteToMetricCollection;- const canCreateDashboard =- dashboardCollectionId && canWriteToDashboardCollection;-const canCreateLibraryCollection =(dataCollectionId && canWriteToDataCollection) ||- (metricCollectionId && canWriteToMetricCollection) ||- canCreateDashboard;+ (metricCollectionId && canWriteToMetricCollection);const collectionNamespaces: CollectionNamespace[] = [null];const initialCollectionId =(dataCollectionId && canWriteToDataCollection && dataCollectionId) ||(metricCollectionId && canWriteToMetricCollection && metricCollectionId) ||- (canCreateDashboard && dashboardCollectionId) ||null;const menuItems = [@@ -78,29 +68,16 @@ export const CreateMenu = ({{t`Metric`}</Menu.Item>),- canCreateDashboard && (- <Menu.Item- key="dashboard"- leftSection={<FixedSizeIcon name="dashboard" />}- onClick={onNewDashboardClick}- >- {t`Dashboard`}- </Menu.Item>- ),canCreateLibraryCollection && (<Menu.Itemkey="collection"leftSection={<FixedSizeIcon name="folder" />}onClick={() =>dispatch(- setOpenModalWithProps({- id: "collection",- props: {- initialCollectionId,- namespaces: collectionNamespaces,- pickerOptions: LIBRARY_COLLECTION_PICKER_OPTIONS,- showAuthorityLevelPicker: false,- },+ openNewCollectionModal({+ initialCollectionId,+ namespaces: collectionNamespaces,+ pickerOptions: LIBRARY_COLLECTION_PICKER_OPTIONS,}),)}@@ -130,13 +107,3 @@ export const CreateMenu = ({</>);};--const LIBRARY_COLLECTION_PICKER_OPTIONS = {- hasLibrary: true,- hasRootCollection: false,- hasPersonalCollections: false,- hasRecents: false,- hasSearch: false,- hasConfirmButtons: true,- canCreateCollections: false,-};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.unit.spec.tsxindex 778b107f415..7e8658a3b3f 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateMenu/CreateMenu.unit.spec.tsx@@ -17,7 +17,6 @@ interface SetupOptions {dataCollectionId?: number;canWriteToDataCollection?: boolean;canWriteToMetricCollection?: boolean;- canWriteToDashboardCollection?: boolean;}const fullPermissionsUser: Partial<User> = {@@ -33,9 +32,7 @@ const setup = ({dataCollectionId = 2,canWriteToDataCollection = true,canWriteToMetricCollection = true,- canWriteToDashboardCollection = false,}: SetupOptions = {}) => {- const onNewDashboardClick = jest.fn();const state = createMockState({settings: mockSettings({"token-features": createMockTokenFeatures({ library: true }),@@ -49,16 +46,13 @@ const setup = ({dataCollectionId={dataCollectionId}canWriteToDataCollection={canWriteToDataCollection}canWriteToMetricCollection={canWriteToMetricCollection}- dashboardCollectionId={3}- canWriteToDashboardCollection={canWriteToDashboardCollection}- onNewDashboardClick={onNewDashboardClick}/>,{storeInitialState: state,},);- return { ...utils, onNewDashboardClick };+ return utils;};describe("CreateMenu", () => {@@ -166,36 +160,4 @@ describe("CreateMenu", () => {},});});-- it("renders the Dashboard option when the Dashboards collection is writable", async () => {- const { onNewDashboardClick } = setup({- user: fullPermissionsUser,- canWriteToDashboardCollection: true,- });-- await userEvent.click(screen.getByRole("button", { name: /New/ }));- expect(- screen.getAllByRole("menuitem").map((item) => item.textContent),- ).toEqual(["Published table", "Metric", "Dashboard", "Collection"]);-- await userEvent.click(screen.getByRole("menuitem", { name: /Dashboard/ }));- expect(onNewDashboardClick).toHaveBeenCalled();- });-- it("renders the Collection option when only the Dashboards collection is writable", async () => {- const { store } = setup({- user: {},- canWriteToDataCollection: false,- canWriteToMetricCollection: false,- canWriteToDashboardCollection: true,- });-- await userEvent.click(screen.getByRole("button", { name: /New/ }));- await userEvent.click(screen.getByRole("menuitem", { name: /Collection/ }));-- expect(store.getState().modal.props).toMatchObject({- initialCollectionId: 3,- namespaces: [null],- });- });});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.tsxindex fb757e79ec2..8497999f499 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.tsx@@ -3,7 +3,6 @@ import type { Row } from "@tanstack/react-table";import { useCallback, useMemo, useState } from "react";import { t } from "ttag";-import { useListCollectionsTreeQuery } from "metabase/api";import {CollectionRowModal,type CollectionRowModalState,@@ -19,23 +18,20 @@ import {type TableModalState,} from "metabase-enterprise/data-studio/library/tables/components/TableModal";+import { LibraryEmptyState } from "../../components/LibraryEmptyState";+import { useLibraryCollections } from "../../hooks/use-library-collections";+import type { LibrarySearchModel } from "../../hooks/use-library-search-results";+import { ActionCell } from "./ActionCell";-import { CreateLibraryDashboardModal } from "./CreateLibraryDashboardModal";import { CreateMenu } from "./CreateMenu";-import { LibraryEmptyState } from "./LibraryEmptyState";import { PublishTableModal } from "./PublishTableModal";-import {- useLibraryCollectionTree,- useLibraryCollections,- useLibrarySearch,-} from "./hooks";-import type { LibrarySearchModel } from "./hooks";+import { useLibraryCollectionTree, useLibrarySearch } from "./hooks";import {getArchiveLibraryCollectionsMessage,getWritableCollection,} from "./utils";-const SEARCH_MODELS: LibrarySearchModel[] = ["table", "metric", "dashboard"];+const SEARCH_MODELS: LibrarySearchModel[] = ["table", "metric"];function getTrashMessage(section: LibrarySection, count: number) {return section === "data"@@ -62,22 +58,12 @@ function LibraryPageContent() {showPublishTableModal,{ open: openPublishTableModal, close: closePublishTableModal },] = useDisclosure(false);- const [- showCreateDashboardModal,- { open: openCreateDashboardModal, close: closeCreateDashboardModal },- ] = useDisclosure(false);- const { data: collections = [], isLoading: isLoadingCollections } =- useListCollectionsTreeQuery({- "exclude-other-user-collections": true,- "exclude-archived": true,- "include-library": true,- });const {+ isLoading: isLoadingCollections,libraryCollection,tableCollection,metricCollection,- dashboardCollection,- } = useLibraryCollections(collections);+ } = useLibraryCollections();const writableMetricCollection = useMemo(() =>libraryCollection &&@@ -103,48 +89,34 @@ function LibraryPageContent() {"metrics",metricCollection?.id,);- const {- tree: dashboardsTree,- isLoading: isLoadingDashboards,- error: dashboardsError,- watchRows: watchDashboardRows,- isChildrenLoading: isDashboardChildrenLoading,- } = useLibraryCollectionTree(dashboardCollection, "dashboards");const {tree: searchTree,isActive: isSearchActive,isLoading: isSearchLoading,} = useLibrarySearch(searchQuery, libraryCollection?.id, SEARCH_MODELS);- useErrorHandling(tablesError || metricsError || dashboardsError);+ useErrorHandling(tablesError || metricsError);const tree = useMemo(- () =>- isSearchActive- ? searchTree- : [...tablesTree, ...metricsTree, ...dashboardsTree],- [isSearchActive, searchTree, tablesTree, metricsTree, dashboardsTree],+ () => (isSearchActive ? searchTree : [...tablesTree, ...metricsTree]),+ [isSearchActive, searchTree, tablesTree, metricsTree],);const defaultExpandedIds = useMemo(() =>- [tableCollection, metricCollection, dashboardCollection].flatMap(- (collection) => (collection ? [`collection:${collection.id}`] : []),+ [tableCollection, metricCollection].flatMap((collection) =>+ collection ? [`collection:${collection.id}`] : [],),- [tableCollection, metricCollection, dashboardCollection],+ [tableCollection, metricCollection],);const defaultMoveCollectionIds = useMemo(() => ({data: tableCollection?.id,metrics: metricCollection?.id,- dashboards: dashboardCollection?.id,}),- [tableCollection, metricCollection, dashboardCollection],+ [tableCollection, metricCollection],);const emptyStateActions = useMemo(- () => ({- data: openPublishTableModal,- dashboards: openCreateDashboardModal,- }),- [openPublishTableModal, openCreateDashboardModal],+ () => ({ data: openPublishTableModal }),+ [openPublishTableModal],);const renderRowMenu = useCallback(@@ -161,20 +133,13 @@ function LibraryPageContent() {(rows: Row<TreeItem>[]) => {watchTableRows(rows);watchMetricRows(rows);- watchDashboardRows(rows);},- [watchTableRows, watchMetricRows, watchDashboardRows],+ [watchTableRows, watchMetricRows],);const isChildrenLoading = useCallback((row: Row<TreeItem>) =>- isTableChildrenLoading(row) ||- isMetricChildrenLoading(row) ||- isDashboardChildrenLoading(row),- [- isTableChildrenLoading,- isMetricChildrenLoading,- isDashboardChildrenLoading,- ],+ isTableChildrenLoading(row) || isMetricChildrenLoading(row),+ [isTableChildrenLoading, isMetricChildrenLoading],);return (@@ -185,12 +150,11 @@ function LibraryPageContent() {isLoadingCollections ||isLoadingTables ||isLoadingMetrics ||- isLoadingDashboards ||isSearchLoading}isSearchActive={isSearchActive}searchQuery={searchQuery}- emptyMessage={t`No tables, metrics, or dashboards yet`}+ emptyMessage={t`No tables or metrics yet`}defaultExpandedIds={defaultExpandedIds}defaultMoveCollectionIds={defaultMoveCollectionIds}emptyState={@@ -204,9 +168,6 @@ function LibraryPageContent() {canWriteToMetricCollection={!!writableMetricCollection}dataCollectionId={tableCollection?.id}canWriteToDataCollection={!!tableCollection?.can_write}- dashboardCollectionId={dashboardCollection?.id}- canWriteToDashboardCollection={!!dashboardCollection?.can_write}- onNewDashboardClick={openCreateDashboardModal}/>}emptyStateActions={emptyStateActions}@@ -221,13 +182,6 @@ function LibraryPageContent() {onClose={closePublishTableModal}onPublished={closePublishTableModal}/>- {dashboardCollection && (- <CreateLibraryDashboardModal- opened={showCreateDashboardModal}- collectionId={dashboardCollection.id}- onClose={closeCreateDashboardModal}- />- )}<CollectionRowModalmodal={collectionModal}onClose={() => setCollectionModal(undefined)}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/hooks.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/hooks.tsindex fe287ab6361..d918d456000 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/hooks.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/hooks.ts@@ -1,196 +1,53 @@-import type { Row } from "@tanstack/react-table";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { shallowEqual } from "react-redux";+import { useMemo } from "react";import { t } from "ttag";-import {- collectionApi,- skipToken,- useListCollectionItemsQuery,- useSearchQuery,-} from "metabase/api";-import { isLibraryCollection } from "metabase/common/collections/utils";-import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";import type {LibrarySectionType,TreeItem,} from "metabase/data-studio/common/types";import { createEmptyStateItem } from "metabase/data-studio/common/utils";import { useGetIcon } from "metabase/hooks/use-icon";-import { useDispatch, useSelector } from "metabase/redux";-import type { State } from "metabase/redux/store";+import { useSelector } from "metabase/redux";import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";import type {Collection,CollectionId,- CollectionItem,CollectionItemModel,IconName,- SearchResult,} from "metabase-types/api";-import { getAccessibleCollection } from "./utils";--export const useLibraryCollections = (collections: Collection[]) => {- const libraryCollection = useMemo(- () => collections.find(isLibraryCollection),- [collections],- );-- const tableCollection = useMemo(- () =>- libraryCollection &&- getAccessibleCollection(libraryCollection, "library-data"),- [libraryCollection],- );-- const metricCollection = useMemo(- () =>- libraryCollection &&- getAccessibleCollection(libraryCollection, "library-metrics"),- [libraryCollection],- );-- const dashboardCollection = useMemo(- () =>- libraryCollection &&- getAccessibleCollection(libraryCollection, "library-dashboards"),- [libraryCollection],- );-- return {- libraryCollection,- tableCollection,- metricCollection,- dashboardCollection,- };-};+import { useCollectionItemsTree } from "../../hooks/use-collection-items-tree";+import {+ type LibrarySearchModel,+ useLibrarySearchResults,+} from "../../hooks/use-library-search-results";const SECTION_ITEM_MODELS: Record<LibrarySectionType, CollectionItemModel[]> = {data: ["table", "collection"],metrics: ["metric", "collection"],- dashboards: ["dashboard", "collection"],snippets: ["snippet", "collection"],actions: ["action", "collection"],};-const NO_ITEMS: CollectionItem[] = [];--const getCollectionItemsRequest = (- collectionId: CollectionId,- models: CollectionItemModel[],-) => ({- id: collectionId,- models,- archived: false,-});-+/**+ * A Semantic layer section: the section's collection as a root row holding its+ * folders and items, or the section's empty-state row when it has none.+ */export function useLibraryCollectionTree(collection: Collection | undefined,sectionType: LibrarySectionType,metricCollectionId?: CollectionId,) {- const dispatch = useDispatch();const getIcon = useGetIcon();- const models = SECTION_ITEM_MODELS[sectionType];-- // 1. Fetch top-level items- const {- data: topLevelItems,- isLoading,- error,- } = useListCollectionItemsQuery(- collection ? getCollectionItemsRequest(collection.id, models) : skipToken,- );-const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);+ const { items, isLoading, error, watchRows, isChildrenLoading } =+ useCollectionItemsTree(collection, SECTION_ITEM_MODELS[sectionType]);- // 2. Expanded subcollection items, subscribed to the API cache- const [expandedCollectionIds, setExpandedCollectionIds] = useState<- CollectionId[]- >([]);- const subscriptionsRef = useRef(- new Map<CollectionId, { unsubscribe: () => void }>(),- );-- const sectionCollectionId = collection?.id;- useEffect(() => {- setExpandedCollectionIds((ids) => (ids.length > 0 ? [] : ids));- }, [sectionCollectionId, models]);-- useEffect(() => {- const subscriptions = subscriptionsRef.current;- expandedCollectionIds.forEach((collectionId) => {- if (!subscriptions.has(collectionId)) {- subscriptions.set(- collectionId,- dispatch(- collectionApi.endpoints.listCollectionItems.initiate(- getCollectionItemsRequest(collectionId, models),- ),- ),- );- }- });- subscriptions.forEach((subscription, collectionId) => {- if (!expandedCollectionIds.includes(collectionId)) {- subscription.unsubscribe();- subscriptions.delete(collectionId);- }- });- }, [dispatch, expandedCollectionIds, models]);-- useEffect(() => {- const subscriptions = subscriptionsRef.current;- return () => {- subscriptions.forEach((subscription) => subscription.unsubscribe());- subscriptions.clear();- };- }, []);-- const expandedCollectionSelectors = useMemo(- () =>- expandedCollectionIds.map((collectionId) =>- collectionApi.endpoints.listCollectionItems.select(- getCollectionItemsRequest(collectionId, models),- ),- ),- [expandedCollectionIds, models],- );-- const expandedCollectionItems = useSelector(- (state: State) =>- expandedCollectionSelectors.map((selectCollectionItems) => {- const { data, isError } = selectCollectionItems(state);- return data?.data ?? (isError ? NO_ITEMS : undefined);- }),- shallowEqual,- );-- const loadedCollections = useMemo(- () =>- new Map(- expandedCollectionIds.flatMap((collectionId, index) => {- const items = expandedCollectionItems[index];- return items ? [[collectionId, items] as const] : [];- }),- ),- [expandedCollectionIds, expandedCollectionItems],- );-- // 3. Build treeconst tree = useMemo((): TreeItem[] => {- if (isLoading || !topLevelItems || !collection) {+ if (!collection || !items) {return [];}- const children = buildChildren(- topLevelItems.data,- loadedCollections,- getIcon,- );- const hasItems = children.length > 0;-return [{name: collection.name,@@ -198,71 +55,27 @@ export function useLibraryCollectionTree(icon: getIcon({ ...collection, model: "collection" }).name,data: { ...collection, model: "collection" as const },model: "collection",- children: hasItems- ? children- : [- createEmptyStateItem(- sectionType,- metricCollectionId,- isRemoteSyncReadOnly,- ),- ],+ children:+ items.length > 0+ ? items+ : [+ createEmptyStateItem(+ sectionType,+ metricCollectionId,+ isRemoteSyncReadOnly,+ ),+ ],},];}, [- isLoading,- topLevelItems,collection,- loadedCollections,+ items,getIcon,sectionType,metricCollectionId,isRemoteSyncReadOnly,]);- // 4. Watch rows for expanded-but-empty collections → subscribe to their items- const sectionRowId = tree[0]?.id;- const watchRows = useCallback(- (rows: Row<TreeItem>[]) => {- const collectionIdsToLoad = rows.flatMap((row) => {- const { original } = row;- const isExpandedWithoutChildren =- row.getIsExpanded() &&- row.getCanExpand() &&- original.model === "collection" &&- original.children?.length === 0;- const isInSection =- sectionRowId !== undefined &&- row.getParentRows()[0]?.id === sectionRowId;- return isExpandedWithoutChildren &&- isInSection &&- original.data.model === "collection" &&- original.data.id !== undefined- ? [original.data.id]- : [];- });- if (collectionIdsToLoad.length === 0) {- return;- }- setExpandedCollectionIds((previousIds) => {- const newIds = collectionIdsToLoad.filter(- (collectionId) => !previousIds.includes(collectionId),- );- return newIds.length > 0 ? [...previousIds, ...newIds] : previousIds;- });- },- [sectionRowId],- );-- // 5. isChildrenLoading for the spinner- const isChildrenLoading = useCallback(- (row: Row<TreeItem>): boolean =>- row.getIsExpanded() &&- row.getCanExpand() &&- row.original.children?.length === 0,- [],- );-return {tree,isLoading,@@ -272,70 +85,6 @@ export function useLibraryCollectionTree(};}-/** Build children for a collection from its fetched items. Subcollections- * that haven't been loaded yet get `children: []` (if they have content- * according to `here`/`below`) so they render as expandable rows that- * trigger a lazy load, or `undefined` if they're empty. */-function buildChildren(- items: CollectionItem[],- loadedCollections: Map<CollectionId, CollectionItem[]>,- getIcon: ReturnType<typeof useGetIcon>,-): TreeItem[] {- const visibleItems = items.filter((i) => !i.archived);- const collections = visibleItems.filter((i) => i.model === "collection");- const leafItems = visibleItems.filter((i) => i.model !== "collection");-- return [- ...collections.map((col): TreeItem => {- const childItems = loadedCollections.get(col.id);- let children: TreeItem[] | undefined;-- if (childItems !== undefined) {- const built = buildChildren(childItems, loadedCollections, getIcon);- children = built.length > 0 ? built : undefined;- } else if (hasContent(col)) {- children = [];- }-- return {- name: col.name,- id: `collection:${col.id}`,- icon: "folder",- data: col,- model: "collection",- children,- childrenLoaded: childItems !== undefined,- };- }),- ...leafItems.map((leafItem) => buildItemNode(leafItem, getIcon)),- ];-}--function buildItemNode(- item: CollectionItem,- getIcon: ReturnType<typeof useGetIcon>,-): TreeItem {- return {- name: item.name,- updatedAt: item["last-edit-info"]?.timestamp,- icon: getIcon({ model: item.model }).name,- data: item,- id: `${item.model}:${item.id}`,- model: item.model,- };-}--function hasContent(item: CollectionItem): boolean {- return (- (item.here != null && item.here.length > 0) ||- (item.below != null && item.below.length > 0)- );-}--const SEARCH_DEBOUNCE_MS = 300;--export type LibrarySearchModel = "table" | "metric" | "dashboard";-type SearchSection = {id: string;name: string;@@ -352,41 +101,22 @@ const getSearchSections = (): Record<LibrarySearchModel, SearchSection> => ({},});+/** Search results across the Library, grouped under a row per section */export function useLibrarySearch(searchQuery: string,libraryCollectionId: CollectionId | undefined,models: LibrarySearchModel[],) {- const debouncedQuery = useDebouncedValue(searchQuery, SEARCH_DEBOUNCE_MS);- const isActive = debouncedQuery.trim().length > 0;- const getIcon = useGetIcon();-- const {- data: searchResponse,- isLoading,- isFetching,- error,- } = useSearchQuery(- isActive && libraryCollectionId != null- ? {- q: debouncedQuery,- collection: libraryCollectionId,- models,- context: "library",- }- : skipToken,+ const { items, isActive, isLoading, error } = useLibrarySearchResults(+ searchQuery,+ libraryCollectionId,+ models,);const tree = useMemo((): TreeItem[] => {- if (!isActive || !searchResponse) {- return [];- }-const sections = getSearchSections();return models.flatMap((model): TreeItem[] => {- const children = searchResponse.data- .filter((result) => result.model === model)- .map((result) => createSearchResultItem(result, model, getIcon));+ const children = items.filter((item) => item.model === model);if (children.length === 0) {return [];}@@ -402,37 +132,7 @@ export function useLibrarySearch(},];});- }, [isActive, searchResponse, models, getIcon]);+ }, [items, models]);- return {- tree,- isActive,- isLoading: isLoading || isFetching,- error,- };-}--function createSearchResultItem(- result: SearchResult,- model: LibrarySearchModel,- getIcon: ReturnType<typeof useGetIcon>,-): TreeItem {- return {- id: `${model}:${result.id}`,- name: result.name,- icon: getIcon({ model }).name,- updatedAt: result.last_edited_at ?? result.updated_at,- model,- parentCollectionName: result.collection?.name,- data: {- id: Number(result.id),- model,- name: result.name,- description: result.description,- collection_id: result.collection_id ?? null,- archived: result.archived ?? false,- collection_position: result.collection_position,- "last-edit-info": result["last-edit-info"],- },- };+ return { tree, isActive, isLoading, error };}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.tsindex 28ff61227ed..e1692355b62 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.ts@@ -2,6 +2,8 @@ import { msgid, ngettext } from "ttag";import type { Collection, CollectionType } from "metabase-types/api";+import { getAccessibleCollection } from "../../utils";+export function getArchiveLibraryCollectionsMessage(count: number): string {return ngettext(msgid`Archiving this collection will also unpublish the tables inside it (and any tables that depend on them) and archive any other child items.`,@@ -10,15 +12,6 @@ export function getArchiveLibraryCollectionsMessage(count: number): string {);}-export function getAccessibleCollection(- rootCollection: Collection,- type: CollectionType,-) {- return rootCollection.children?.find(- (collection) => collection.type === type,- );-}-export function getWritableCollection(rootCollection: Collection,type: CollectionType,diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.unit.spec.tsindex f933f20f59f..fc7fac39b32 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/utils.unit.spec.ts@@ -1,6 +1,6 @@import { createMockCollection } from "metabase-types/api/mocks";-import { getAccessibleCollection, getWritableCollection } from "./utils";+import { getWritableCollection } from "./utils";describe("getWritableCollection", () => {it("returns collection when can_write is true", () => {@@ -51,64 +51,3 @@ describe("getWritableCollection", () => {expect(result).toBeUndefined();});});--describe("getAccessibleCollection", () => {- it("returns collection when it exists with can_write true", () => {- const childCollection = createMockCollection({- id: 2,- type: "library-data",- can_write: true,- });- const rootCollection = createMockCollection({- id: 1,- children: [childCollection],- });-- const result = getAccessibleCollection(rootCollection, "library-data");-- expect(result).toEqual(childCollection);- });-- it("returns collection when it exists with can_write false", () => {- const childCollection = createMockCollection({- id: 2,- type: "library-data",- can_write: false,- });- const rootCollection = createMockCollection({- id: 1,- children: [childCollection],- });-- const result = getAccessibleCollection(rootCollection, "library-data");-- expect(result).toEqual(childCollection);- });-- it("returns undefined when collection type does not exist", () => {- const childCollection = createMockCollection({- id: 2,- type: "library-metrics",- can_write: true,- });- const rootCollection = createMockCollection({- id: 1,- children: [childCollection],- });-- const result = getAccessibleCollection(rootCollection, "library-data");-- expect(result).toBeUndefined();- });-- it("returns undefined when root collection has no children", () => {- const rootCollection = createMockCollection({- id: 1,- children: undefined,- });-- const result = getAccessibleCollection(rootCollection, "library-data");-- expect(result).toBeUndefined();- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.tsindex ce6323022c9..34120dc4f0d 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts@@ -9,7 +9,11 @@ import type {GetEntityPickerSyntheticLibraryItemFunction,LibrarySubCollectionType,} from "metabase/plugins/oss/library";-import type { CollectionItem } from "metabase-types/api";+import type {+ Collection,+ CollectionItem,+ CollectionType,+} from "metabase-types/api";type LibrarySectionCollectionItem = CollectionItem &OmniPickerCollectionItem & {@@ -135,3 +139,13 @@ export const isLibraryCollectionType = (): type is LibrarySubCollectionType => {return isLibrarySubCollectionType(type) || type === "library";};++/** The Library section collection of `type` that the collection tree holds */+export function getAccessibleCollection(+ rootCollection: Collection,+ type: CollectionType,+) {+ return rootCollection.children?.find(+ (collection) => collection.type === type,+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.tsindex 75fb3f0fd00..444648ed0a9 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.ts@@ -1,7 +1,10 @@import type { OmniPickerItem } from "metabase/common/components/Pickers/EntityPicker/types";-import { createMockCollectionItem } from "metabase-types/api/mocks";+import {+ createMockCollection,+ createMockCollectionItem,+} from "metabase-types/api/mocks";-import { getCollectionPickerItems } from "./utils";+import { getAccessibleCollection, getCollectionPickerItems } from "./utils";const libraryParentItem: OmniPickerItem = {id: 1,@@ -99,3 +102,64 @@ describe("getCollectionPickerItems", () => {).toBeUndefined();});});++describe("getAccessibleCollection", () => {+ it("returns collection when it exists with can_write true", () => {+ const childCollection = createMockCollection({+ id: 2,+ type: "library-data",+ can_write: true,+ });+ const rootCollection = createMockCollection({+ id: 1,+ children: [childCollection],+ });++ const result = getAccessibleCollection(rootCollection, "library-data");++ expect(result).toEqual(childCollection);+ });++ it("returns collection when it exists with can_write false", () => {+ const childCollection = createMockCollection({+ id: 2,+ type: "library-data",+ can_write: false,+ });+ const rootCollection = createMockCollection({+ id: 1,+ children: [childCollection],+ });++ const result = getAccessibleCollection(rootCollection, "library-data");++ expect(result).toEqual(childCollection);+ });++ it("returns undefined when collection type does not exist", () => {+ const childCollection = createMockCollection({+ id: 2,+ type: "library-metrics",+ can_write: true,+ });+ const rootCollection = createMockCollection({+ id: 1,+ children: [childCollection],+ });++ const result = getAccessibleCollection(rootCollection, "library-data");++ expect(result).toBeUndefined();+ });++ it("returns undefined when root collection has no children", () => {+ const rootCollection = createMockCollection({+ id: 1,+ children: undefined,+ });++ const result = getAccessibleCollection(rootCollection, "library-data");++ expect(result).toBeUndefined();+ });+});diff --git a/frontend/lint/side-effect-files.json b/frontend/lint/side-effect-files.jsonindex 9977edadc63..c0227544806 100644--- a/frontend/lint/side-effect-files.json+++ b/frontend/lint/side-effect-files.json@@ -48,9 +48,7 @@"enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx": "self","enterprise/frontend/src/metabase-enterprise/auth/constants.ts": "self","enterprise/frontend/src/metabase-enterprise/auth/index.ts": "global",- "enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/utils.ts": "self","enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizPage.tsx": "self",- "enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/CreateLibraryDashboardModal/CreateLibraryDashboardModal.tsx": "self","enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx": "entry","enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts": "entry","enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsx": "self",@@ -73,7 +71,6 @@"enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-script-plugins.ts": "entry","enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts": "entry","enterprise/frontend/src/metabase-enterprise/shared/index.ts": "global",- "enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/TenantForm.tsx": "self","enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonEditor/utils.ts": "self","enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.tsx": "self","enterprise/frontend/src/metabase-enterprise/whitelabel/lib/whitelabel.ts": "global",@@ -87,22 +84,18 @@"frontend/src/embedding-sdk-bundle/store/use-sdk-selector.ts": "self","frontend/src/embedding-sdk-bundle/test/CommonSdkCorsStoryWrapper.tsx": "entry","frontend/src/embedding-sdk-bundle/test/CommonSdkStoryWrapper.tsx": "entry",- "frontend/src/metabase/account/password/components/UserPasswordForm/UserPasswordForm.tsx": "self","frontend/src/metabase/account/profile/components/UserProfileForm/UserProfileForm.tsx": "self","frontend/src/metabase/actions/containers/ActionCreator/CreateActionForm/CreateActionForm.tsx": "self","frontend/src/metabase/admin/ai/MetabotSlackSetup.tsx": "self","frontend/src/metabase/admin/performance/utils.tsx": "self","frontend/src/metabase/admin/settings/auth/constants.ts": "self",- "frontend/src/metabase/admin/settings/components/ApiKeys/utils.ts": "self","frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.tsx": "self",- "frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx": "self","frontend/src/metabase/admin/settings/slack/SlackSetupForm.tsx": "self","frontend/src/metabase/api/ai-streaming/schemas.ts": "self","frontend/src/metabase/api/analytics.ts": "self","frontend/src/metabase/api/api.ts": "self","frontend/src/metabase/auth/components/ForgotPasswordForm/ForgotPasswordForm.tsx": "self","frontend/src/metabase/auth/components/LoginForm/LoginForm.tsx": "self",- "frontend/src/metabase/auth/components/ResetPasswordForm/ResetPasswordForm.tsx": "self","frontend/src/metabase/auth/plugins/index.ts": "entry","frontend/src/metabase/comments/components/CommentEditor/EmojiSuggestionExtension.tsx": "self","frontend/src/metabase/common/CreateDashboard/CreateDashboardForm.tsx": "self",@@ -126,7 +119,6 @@"frontend/src/metabase/common/components/tree/TreeNode.tsx": "self","frontend/src/metabase/common/utils/chart-clipboard.ts": "self","frontend/src/metabase/css/core/base.styled.ts": "self",- "frontend/src/metabase/dashboard/actions/auto-wire-parameters/toasts.ts": "self","frontend/src/metabase/dashboard/components/ActionViz/ActionViz.tsx": "self","frontend/src/metabase/dashboard/components/grid/GridLayout.tsx": "self","frontend/src/metabase/dashboard/visualizations/Heading/index.ts": "self",@@ -153,7 +145,6 @@"frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/trustedDocChangesOnly.ts": "self","frontend/src/metabase/metrics/pages/NewMetricPage/CreateMetricModal/CreateMetricModal.tsx": "self","frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.tsx": "self",- "frontend/src/metabase/palette/components/PaletteShortcutsModal/PaletteShortcutsModal.tsx": "self","frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx": "self","frontend/src/metabase/plugins/oss/caching.ts": "self","frontend/src/metabase/querying/components/CodeMirrorEditor/language.ts": "self",@@ -180,9 +171,6 @@"frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx": "self","frontend/src/metabase/routes-public.tsx": "self","frontend/src/metabase/routes.tsx": "entry",- "frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx": "self",- "frontend/src/metabase/setup/components/LicenseTokenStep/constants.tsx": "self",- "frontend/src/metabase/setup/components/UserForm/UserForm.tsx": "self","frontend/src/metabase/static-viz/index.tsx": "entry","frontend/src/metabase/static-viz/lib/text.ts": "self","frontend/src/metabase/static-viz/polyfill.ts": "global",@@ -205,7 +193,6 @@"frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx": "self","frontend/src/metabase/visualizations/components/LeafletMap.tsx": "self","frontend/src/metabase/visualizations/visualizations/Map/Map.tsx": "self",- "frontend/src/metabase/visualizations/visualizations/ObjectDetail/ObjectDetail.ts": "self","frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTable.tsx": "self","frontend/src/metabase/visualizer/visualizer.slice.ts": "self"},diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.tsindex 4ed01ee300c..5a18102324a 100644--- a/frontend/src/metabase-types/api/dashboard.ts+++ b/frontend/src/metabase-types/api/dashboard.ts@@ -196,6 +196,14 @@ export type ActionDashboardCard = Omit<};};+/**+ * What GET /api/dashboard/:id sends in place of a dashcard's card, or one of+ * its series, when the user cannot read that card: only its id.+ * `QuestionDashboardCard` does not model it, so read the stub through+ * `isReadableCard` where it matters.+ */+export type UnreadableCard = Pick<Card, "id">;+export type QuestionDashboardCard = BaseDashboardCard & {card_id: CardId | null; // will be null for virtual cardcard: Card;@@ -348,6 +356,7 @@ export type UpdateDashboardRequest = {| "width"| "embedding_params"| "cache_ttl"+ | "auto_apply_filters">>;diff --git a/frontend/src/metabase-types/api/notification-channels.ts b/frontend/src/metabase-types/api/notification-channels.tsindex 256585a2acc..aa926d54f15 100644--- a/frontend/src/metabase-types/api/notification-channels.ts+++ b/frontend/src/metabase-types/api/notification-channels.ts@@ -108,11 +108,18 @@ export type PulseChannelDetails = {[specFieldName: string]: string | boolean | undefined;};+/** An address outside Metabase, which the API returns without a user id. */+export type ExternalEmailRecipient = {+ email: string;+};++export type ChannelRecipient = User | ExternalEmailRecipient;+export type Channel = {channel_type: ChannelType;details?: PulseChannelDetails;enabled?: boolean;- recipients?: User[];+ recipients?: ChannelRecipient[];channel_id?: number;} & Pick<ScheduleSettings,diff --git a/frontend/src/metabase-types/guards/dashboard.ts b/frontend/src/metabase-types/guards/dashboard.tsindex 24be6fc5183..4210e95f186 100644--- a/frontend/src/metabase-types/guards/dashboard.ts+++ b/frontend/src/metabase-types/guards/dashboard.ts@@ -7,6 +7,7 @@ import type {DashCardSeriesItem,LinkEntity,RestrictedLinkEntity,+ UnreadableCard,VirtualCard,VisualizerDashboardCard,VisualizerDataSeries,@@ -31,6 +32,10 @@ export const isVisualizerDashboardCard = (return dashcard.visualization_settings["visualization"] !== undefined;};+export function isReadableCard(card: Card | UnreadableCard): card is Card {+ return "dataset_query" in card;+}+export function isVirtualCard(card: Card | VirtualCard): card is VirtualCard {return isVirtualCardDisplayType(card.display);}diff --git a/frontend/src/metabase-types/guards/index.ts b/frontend/src/metabase-types/guards/index.tsindex 08cf1fb10c7..d5721d65f0e 100644--- a/frontend/src/metabase-types/guards/index.ts+++ b/frontend/src/metabase-types/guards/index.ts@@ -2,6 +2,7 @@ export * from "./card";export * from "./click-behavior";export * from "./common";export * from "./dom";+export * from "./notification-channels";export * from "./parameters";export * from "./remote-sync";export * from "./settings";diff --git a/frontend/src/metabase-types/guards/notification-channels.ts b/frontend/src/metabase-types/guards/notification-channels.tsnew file mode 100644index 00000000000..2d88090ef17--- /dev/null+++ b/frontend/src/metabase-types/guards/notification-channels.ts@@ -0,0 +1,5 @@+import type { ChannelRecipient, User } from "metabase-types/api";++export const isUserRecipient = (+ recipient: ChannelRecipient,+): recipient is User => "id" in recipient;diff --git a/frontend/src/metabase/common/collections/containers/CreateCollectionModal.tsx b/frontend/src/metabase/common/collections/containers/CreateCollectionModal.tsxindex 03ffb760045..7a96fa98947 100644--- a/frontend/src/metabase/common/collections/containers/CreateCollectionModal.tsx+++ b/frontend/src/metabase/common/collections/containers/CreateCollectionModal.tsx@@ -72,6 +72,10 @@ function CreateCollectionModal({// eslint-disable-next-line import/no-default-export -- deprecated usageexport default CreateCollectionModal;+// The Library root is a top-level collection and its sections are its direct+// children, so a section's own folders start this deep in a collection's path+const LIBRARY_SECTION_FOLDER_DEPTH = 2;+export function getCreatedCollectionUrl(collection: Collection): string {const expandedIds = getCollectionPathAsArray(collection);if (collection.namespace === "snippets") {@@ -80,6 +84,12 @@ export function getCreatedCollectionUrl(collection: Collection): string {if (collection.namespace === "data-actions") {return Urls.dataStudioActions({ expandedIds });}+ // The Dashboards page lists the section's contents, so only its folders are rows there+ if (collection.type === "library-dashboards") {+ return Urls.dataStudioDashboards({+ expandedIds: expandedIds.slice(LIBRARY_SECTION_FOLDER_DEPTH),+ });+ }if (PLUGIN_LIBRARY.isLibraryCollectionType(collection.type)) {return Urls.dataStudioLibrary({ expandedIds });}diff --git a/frontend/src/metabase/common/collections/containers/CreateCollectionModal.unit.spec.ts b/frontend/src/metabase/common/collections/containers/CreateCollectionModal.unit.spec.tsindex 4f16353ab4d..9a211886034 100644--- a/frontend/src/metabase/common/collections/containers/CreateCollectionModal.unit.spec.ts+++ b/frontend/src/metabase/common/collections/containers/CreateCollectionModal.unit.spec.ts@@ -1,8 +1,18 @@-import { createMockCollection } from "metabase-types/api/mocks";+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import { mockSettings } from "__support__/settings";+import { reinitialize } from "metabase/plugins";+import {+ createMockCollection,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";import { getCreatedCollectionUrl } from "./CreateCollectionModal";describe("getCreatedCollectionUrl", () => {+ beforeEach(() => {+ reinitialize();+ });+it("opens a new data actions folder on the Data actions tab with its path expanded", () => {const collection = createMockCollection({id: 12,@@ -27,6 +37,46 @@ describe("getCreatedCollectionUrl", () => {);});+ it.each([+ {+ name: "a top-level folder",+ location: "/7/10/",+ expectedUrl: "/data-studio/dashboards?expandedId=12",+ },+ {+ name: "a nested folder",+ location: "/7/10/11/",+ expectedUrl: "/data-studio/dashboards?expandedId=11&expandedId=12",+ },+ ])(+ "opens $name on the Dashboards tab with only its folders expanded",+ ({ location, expectedUrl }) => {+ const collection = createMockCollection({+ id: 12,+ type: "library-dashboards",+ location,+ });++ expect(getCreatedCollectionUrl(collection)).toBe(expectedUrl);+ },+ );++ it("opens a new Semantic layer folder with its whole path expanded", () => {+ mockSettings({+ "token-features": createMockTokenFeatures({ library: true }),+ });+ setupEnterpriseOnlyPlugin("library");+ const collection = createMockCollection({+ id: 12,+ type: "library-metrics",+ location: "/7/9/",+ });++ expect(getCreatedCollectionUrl(collection)).toBe(+ "/data-studio/library?expandedId=7&expandedId=9&expandedId=12",+ );+ });+it("opens a new regular collection in the main app", () => {const collection = createMockCollection({ id: 12, name: "Sales" });diff --git a/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsx b/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsxindex cfa48d2b192..abca4de4a14 100644--- a/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsx+++ b/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsx@@ -1,14 +1,21 @@+import type { ReactNode } from "react";import { t } from "ttag";import EmptyDashboardBot from "assets/img/dashboard-empty.svg";import { EmptyState } from "metabase/common/components/EmptyState";-import { Box } from "metabase/ui";+import { Box, Stack, Text } from "metabase/ui";type ListEmptyStateProps = {label: string;+ description?: string;+ action?: ReactNode;};-export function ListEmptyState({ label }: ListEmptyStateProps) {+export function ListEmptyState({+ label,+ description,+ action,+}: ListEmptyStateProps) {return (<Box p="xxl"><EmptyState@@ -23,6 +30,16 @@ export function ListEmptyState({ label }: ListEmptyStateProps) {/>}/>+ {(description != null || action != null) && (+ <Stack align="center" gap="md" mt="xs">+ {description != null && (+ <Text c="text-secondary" ta="center">+ {description}+ </Text>+ )}+ {action}+ </Stack>+ )}</Box>);}diff --git a/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.unit.spec.tsx b/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.unit.spec.tsxindex 3d1a45cf80d..23057911126 100644--- a/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.unit.spec.tsx+++ b/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.unit.spec.tsx@@ -1,13 +1,23 @@+import type { ReactNode } from "react";+import { renderWithProviders, screen } from "__support__/ui";import { ListEmptyState } from "./ListEmptyState";type SetupOpts = {label?: string;+ description?: string;+ action?: ReactNode;};-function setup({ label = "No items found" }: SetupOpts = {}) {- renderWithProviders(<ListEmptyState label={label} />);+function setup({+ label = "No items found",+ description,+ action,+}: SetupOpts = {}) {+ renderWithProviders(+ <ListEmptyState label={label} description={description} action={action} />,+ );}describe("ListEmptyState", () => {@@ -16,4 +26,15 @@ describe("ListEmptyState", () => {setup({ label });expect(screen.getByText(label)).toBeInTheDocument();});++ it("should render a description and an action under the label", () => {+ setup({+ description: "Add one to get started.",+ action: <button>Add item</button>,+ });+ expect(screen.getByText("Add one to get started.")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Add item" }),+ ).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsx b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsxindex a512b0b12d2..4dd0093724a 100644--- a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsx+++ b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsx@@ -3,7 +3,7 @@ import cx from "classnames";import { ForwardRefLink } from "metabase/common/components/Link";import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";import { useLocation } from "metabase/router";-import { Ellipsified, FixedSizeIcon, Flex } from "metabase/ui";+import { Badge, Ellipsified, FixedSizeIcon, Flex } from "metabase/ui";import type { IconName } from "metabase-types/api";import S from "./PillTabNavigation.module.css";@@ -13,6 +13,7 @@ export type PillTab = {to: string;icon?: IconName;isGated?: boolean;+ count?: number;isSelected?: boolean | ((pathname: string) => boolean);};@@ -47,6 +48,16 @@ export function PillTabNavigation({ tabs }: PillTabNavigationProps) {>{tab.icon !== undefined && <FixedSizeIcon name={tab.icon} />}<Ellipsified className={S.label}>{tab.label}</Ellipsified>+ {tab.count !== undefined && (+ <Badge+ variant="light"+ color="neutral"+ c="text-secondary"+ data-testid="pill-tab-count"+ >+ {tab.count}+ </Badge>+ )}{tab.isGated && <UpsellGem.New size={14} />}</Flex>);diff --git a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsx b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsxindex a3396a69f47..495fd3a3655 100644--- a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsx+++ b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsx@@ -103,4 +103,21 @@ describe("PillTabNavigation", () => {expect(screen.queryByTestId("upsell-gem")).not.toBeInTheDocument();});++ it("shows the tab count after its label", () => {+ setup({+ tabs: [+ { label: "Usage", to: "/monitor/example/usage" },+ { label: "Events", to: "/monitor/example/events", count: 0 },+ ],+ });++ const tab = screen.getByRole("link", { name: "Events" });+ expect(within(tab).getByTestId("pill-tab-count")).toHaveTextContent("0");+ expect(+ within(screen.getByRole("link", { name: "Usage" })).queryByTestId(+ "pill-tab-count",+ ),+ ).not.toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx b/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsxindex 42151727d7b..8e70bd6fcd1 100644--- a/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx+++ b/frontend/src/metabase/common/components/Sidesheet/SidesheetSubPage.tsx@@ -14,6 +14,8 @@ interface SidesheetSubPageProps {isOpen: boolean;onClose: () => void;onBack: () => void;+ /** When false, the title is plain text instead of a button that calls `onBack` */+ withBackButton?: boolean;children: React.ReactNode;size?: SidesheetSize;/** Whether to show a translucent backdrop */@@ -44,6 +46,7 @@ export const SidesheetSubPage = ({title,onClose,onBack,+ withBackButton = true,children,isOpen,size,@@ -52,7 +55,13 @@ export const SidesheetSubPage = ({}: SidesheetSubPageProps) => (<SidesheetisOpen={isOpen}- title={<SidesheetSubPageTitle title={title} onClick={onBack} />}+ title={+ withBackButton ? (+ <SidesheetSubPageTitle title={title} onClick={onBack} />+ ) : (+ title+ )+ }onClose={onClose}size={size}withOverlay={withOverlay}diff --git a/frontend/src/metabase/common/data-studio/utils/return-to.ts b/frontend/src/metabase/common/data-studio/utils/return-to.tsnew file mode 100644index 00000000000..cc4e9225369--- /dev/null+++ b/frontend/src/metabase/common/data-studio/utils/return-to.ts@@ -0,0 +1,42 @@+import * as Urls from "metabase/urls";+import type { DashboardId } from "metabase-types/api";++/** Router state that sends the main-app dashboard editor back to Data Studio when editing ends */+export type DataStudioReturnState = {+ returnTo: string;+};++export function getDataStudioDashboardReturnState(+ dashboardId: DashboardId,+): DataStudioReturnState {+ return { returnTo: Urls.dataStudioDashboard(dashboardId) };+}++/** Router state that sends the dashboard editor back to `location` when it is a Data Studio page */+export function getDataStudioPageReturnState(location: {+ pathname: string;+ search: string;+}): DataStudioReturnState | undefined {+ const path = `${location.pathname}${location.search}`;+ return isDataStudioPath(path) ? { returnTo: path } : undefined;+}++export function getDataStudioReturnPath(state: unknown): string | undefined {+ if (typeof state !== "object" || state === null || !("returnTo" in state)) {+ return undefined;+ }+ const { returnTo } = state;+ return typeof returnTo === "string" && isDataStudioPath(returnTo)+ ? returnTo+ : undefined;+}++function isDataStudioPath(path: string): boolean {+ return path.startsWith(`${Urls.dataStudio()}/`);+}++export function isReturningToDataStudio(location?: {+ state?: unknown;+}): boolean {+ return getDataStudioReturnPath(location?.state) != null;+}diff --git a/frontend/src/metabase/common/data-studio/utils/return-to.unit.spec.ts b/frontend/src/metabase/common/data-studio/utils/return-to.unit.spec.tsnew file mode 100644index 00000000000..987b0f04c3b--- /dev/null+++ b/frontend/src/metabase/common/data-studio/utils/return-to.unit.spec.ts@@ -0,0 +1,33 @@+import {+ getDataStudioPageReturnState,+ getDataStudioReturnPath,+} from "./return-to";++const DATA_STUDIO_PATH = "/data-studio/dashboards/1";++describe("getDataStudioReturnPath", () => {+ it.each([+ [{ returnTo: DATA_STUDIO_PATH }, DATA_STUDIO_PATH],+ [{ returnTo: "/collection/1" }, undefined],+ [{ returnTo: "https://example.com/data-studio/" }, undefined],+ [{ returnTo: 1 }, undefined],+ [{}, undefined],+ [null, undefined],+ ["/data-studio/dashboards/1", undefined],+ ])("reads %j as %s", (state, expected) => {+ expect(getDataStudioReturnPath(state)).toBe(expected);+ });+});++describe("getDataStudioPageReturnState", () => {+ it.each([+ [+ { pathname: "/data-studio/library/metrics/1", search: "?tab=2" },+ { returnTo: "/data-studio/library/metrics/1?tab=2" },+ ],+ [{ pathname: "/metric/1", search: "" }, undefined],+ [{ pathname: "/data-studio", search: "" }, undefined],+ ])("reads %j as %j", (location, expected) => {+ expect(getDataStudioPageReturnState(location)).toEqual(expected);+ });+});diff --git a/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts b/frontend/src/metabase/dashboard/actions/actions.unit.spec.tsindex 058bf6495fb..214ab9350ab 100644--- a/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts+++ b/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts@@ -177,7 +177,7 @@ describe("dashboard actions", () => {});describe("updateDashboardAndCards", () => {- it("should not save anything if the dashboard has not changed", async () => {+ it("should only leave edit mode if the dashboard has not changed", async () => {const dashcard1 = createMockDashboardCard({ id: 1, card_id: 1 });const dashcard2 = createMockDashboardCard({ id: 2, card_id: 2 });@@ -208,14 +208,14 @@ describe("dashboard actions", () => {await updateDashboardAndCards()(dispatch, getState);- // createThunkAction dispatches the result action once;- // no additional dispatches means the dashboard was not saved- expect(dispatch).toHaveBeenCalledTimes(1);+ // Leaving edit mode, then createThunkAction's result action; saving+ // would dispatch more+ expect(dispatch).toHaveBeenCalledTimes(2);});});describe("setEditingDashboard", () => {- it("should remove any hash parameters from url when not editing", () => {+ it("should remove any hash parameters from url when leaving edit mode", () => {const location = createMockLocation({pathname: "/dashboard/1",hash: "#hashparam",@@ -257,5 +257,20 @@ describe("dashboard actions", () => {payload: null,});});++ it("should return to Data Studio instead of stripping the hash", () => {+ const location = createMockLocation({+ pathname: "/dashboard/1",+ hash: "#hashparam",+ state: { returnTo: "/data-studio/dashboards/1" },+ });++ setEditingDashboard(null, location)(dispatch);++ expect(navigate).toHaveBeenCalledTimes(1);+ expect(navigate).toHaveBeenCalledWith("/data-studio/dashboards/1", {+ replace: true,+ });+ });});});diff --git a/frontend/src/metabase/dashboard/actions/core.ts b/frontend/src/metabase/dashboard/actions/core.tsindex a964aa8d1cd..ad11927bec6 100644--- a/frontend/src/metabase/dashboard/actions/core.ts+++ b/frontend/src/metabase/dashboard/actions/core.ts@@ -1,5 +1,6 @@import { createAction } from "@reduxjs/toolkit";+import { getDataStudioReturnPath } from "metabase/common/data-studio/utils/return-to";import type { Dispatch } from "metabase/redux/store";import { type Location, navigate } from "metabase/router";import type {@@ -20,15 +21,17 @@ export const setEditingDashboard = (location?: Omit<Location, "query" | "action">,) => {return (dispatch: Dispatch) => {- // Leaving edit mode drops any hash params from the URL. The caller passes the- // current location, since this no longer reads the retired routing slice.- //- // Only navigate when there is actually a hash to strip. The location is- // captured when the caller rendered, so navigating unconditionally would+ const isLeavingEditMode = dashboard === null;+ const returnPath = isLeavingEditMode+ ? getDataStudioReturnPath(location?.state)+ : undefined;++ // Leaving edit mode drops hash params from the URL. The location is captured+ // when the caller rendered, so navigating with no hash to strip would// clobber query params written since then (e.g. the tab the dashboard URL// sync just selected, which it will not re-add because it dedupes on the// previous params).- if (dashboard === null && location?.hash) {+ if (isLeavingEditMode && returnPath == null && location?.hash) {navigate(`${location.pathname}${location.search}`);}@@ -36,6 +39,11 @@ export const setEditingDashboard = (type: SET_EDITING_DASHBOARD,payload: dashboard,});++ // After the dispatch, so the unsaved-changes guard lets the return through+ if (returnPath != null) {+ navigate(returnPath, { replace: true });+ }};};diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.tsindex 3a02beb6079..4655ee89ebc 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts@@ -707,6 +707,11 @@ function copyVirtualCardsToCards(dashboard: Dashboard): Dashboard {let fetchDashboardCancellation: AbortController | null;+export function cancelFetchDashboard() {+ fetchDashboardCancellation?.abort();+ fetchDashboardCancellation = null;+}+const EMPTY_LINK_TARGETS: DashboardLinkTargets = {questions: {},dashboards: {},@@ -765,10 +770,9 @@ export const fetchDashboard = createAsyncThunk(},{ getState, dispatch, rejectWithValue },) => {- if (fetchDashboardCancellation) {- fetchDashboardCancellation.abort();- }+ cancelFetchDashboard();fetchDashboardCancellation = new AbortController();+ const { signal } = fetchDashboardCancellation;try {let entities;@@ -798,7 +802,7 @@ export const fetchDashboard = createAsyncThunk({ uuid: dashId, dashboard_load_id: dashboardLoadId },dispatch,publicApi.endpoints.getPublicDashboard,- { signal: fetchDashboardCancellation.signal },+ { signal },);result = {...result,@@ -813,7 +817,7 @@ export const fetchDashboard = createAsyncThunk({ token: dashId, dashboard_load_id: dashboardLoadId },dispatch,embedApi.endpoints.getEmbedDashboard,- { signal: fetchDashboardCancellation.signal },+ { signal },);result = {...result,@@ -831,7 +835,7 @@ export const fetchDashboard = createAsyncThunk({ subPath, dashboard_load_id: dashboardLoadId },dispatch,automagicDashboardsApi.endpoints.getXrayDashboard,- { signal: fetchDashboardCancellation.signal },+ { signal },),runRtkEndpoint({@@ -841,7 +845,7 @@ export const fetchDashboard = createAsyncThunk(},dispatch,automagicDashboardsApi.endpoints.getXrayDashboardQueryMetadata,- { signal: fetchDashboardCancellation.signal },+ { signal },),]);linkTargets = toLinkTargets(queryMetadata);@@ -880,7 +884,7 @@ export const fetchDashboard = createAsyncThunk({ id: dashId, dashboard_load_id: dashboardLoadId },dispatch,dashboardApi.endpoints.getDashboard,- { signal: fetchDashboardCancellation.signal },+ { signal },);const queryMetadataRequest = runRtkEndpoint({ id: dashId, dashboard_load_id: dashboardLoadId },@@ -916,6 +920,9 @@ export const fetchDashboard = createAsyncThunk(result = response;}+ // A request without the signal, such as the prefetched path's metadata,+ // can outlive a newer fetch or an unmount, so its result is dropped here+ signal.throwIfAborted();fetchDashboardCancellation = null;const isUsingCachedResults = entities != null;diff --git a/frontend/src/metabase/dashboard/actions/parameters.tsx b/frontend/src/metabase/dashboard/actions/parameters.tsxindex dbceb412e55..a3a38d96ccd 100644--- a/frontend/src/metabase/dashboard/actions/parameters.tsx+++ b/frontend/src/metabase/dashboard/actions/parameters.tsx@@ -1200,11 +1200,12 @@ export const setParameterValuesFromQueryParams =dispatch(setParameterValues(parameterValues));};-export const TOGGLE_AUTO_APPLY_FILTERS =- "metabase/dashboard/TOGGLE_AUTO_APPLY_FILTERS";-export const toggleAutoApplyFilters = createThunkAction(- TOGGLE_AUTO_APPLY_FILTERS,- (isEnabled: boolean) => (dispatch, getState) => {+/**+ * Turns auto-apply filters on or off for the loaded dashboard without saving+ * it, applying the pending filter values first.+ */+export const setAutoApplyFilters =+ (isEnabled: boolean) => (dispatch: Dispatch, getState: GetState) => {const dashboardId = getDashboardId(getState());if (dashboardId) {@@ -1215,6 +1216,18 @@ export const toggleAutoApplyFilters = createThunkAction(attributes: { auto_apply_filters: isEnabled },}),);+ }+ };++export const TOGGLE_AUTO_APPLY_FILTERS =+ "metabase/dashboard/TOGGLE_AUTO_APPLY_FILTERS";+export const toggleAutoApplyFilters = createThunkAction(+ TOGGLE_AUTO_APPLY_FILTERS,+ (isEnabled: boolean) => (dispatch, getState) => {+ const dashboardId = getDashboardId(getState());++ if (dashboardId) {+ dispatch(setAutoApplyFilters(isEnabled));dispatch(updateDashboard({ attributeNames: ["auto_apply_filters"] }));if (!isEnabled) {trackAutoApplyFiltersDisabled(dashboardId);diff --git a/frontend/src/metabase/dashboard/actions/save.ts b/frontend/src/metabase/dashboard/actions/save.tsindex 332a1ff7e6c..d5238961420 100644--- a/frontend/src/metabase/dashboard/actions/save.ts+++ b/frontend/src/metabase/dashboard/actions/save.ts@@ -3,6 +3,7 @@ import _ from "underscore";import { cardApi, dashboardApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import { isReturningToDataStudio } from "metabase/common/data-studio/utils/return-to";import { createThunkAction } from "metabase/redux";import { UPDATE_DASHBOARD_AND_CARDS } from "metabase/redux/dashboard";import type { StoreDashboard, StoreDashcard } from "metabase/redux/store";@@ -68,6 +69,7 @@ export const updateDashboardAndCards = createThunkAction();if (!cardsHaveChanged && !dashboardHasChanged) {+ dispatch(setEditingDashboard(null, location));return;}}@@ -214,6 +216,11 @@ export const updateDashboardAndCards = createThunkAction(dispatch(setEditingDashboard(null, location));+ // Returning to Data Studio unmounts the dashboard, which resets its state+ if (isReturningToDataStudio(location)) {+ return;+ }+// Reset the dashboard state from the save response instead of re-fetching// it. Re-using the just-returned dashboard avoids an extra round-trip and// the race condition where a parameter-less GET could cancel thediff --git a/frontend/src/metabase/dashboard/actions/sharing.ts b/frontend/src/metabase/dashboard/actions/sharing.tsindex 4fff02b406e..12c78abdb77 100644--- a/frontend/src/metabase/dashboard/actions/sharing.ts+++ b/frontend/src/metabase/dashboard/actions/sharing.ts@@ -1,7 +1,11 @@+import { subscriptionApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import { canManageSubscriptions } from "metabase/current-user";import { SIDEBAR_NAME } from "metabase/dashboard/constants";import type { Dispatch, GetState } from "metabase/redux/store";+import type { Dashboard, DashboardSubscription } from "metabase-types/api";-import { getIsSharing } from "../selectors";+import { getCanManageDashboardSubscriptions, getIsSharing } from "../selectors";import { closeSidebar, setSidebar } from "./ui";@@ -17,6 +21,53 @@ export const setSharing = (isSharing: boolean) => (dispatch: Dispatch) => {}};+export const editSubscriptionInSidebar = (+ subscriptionId: DashboardSubscription["id"],+) =>+ setSidebar({+ name: SIDEBAR_NAME.sharing,+ props: { subscriptionId },+ });++/**+ * Opens the subscriptions sidebar, on the edit form of `subscriptionId` when+ * there is one, if the user can manage the dashboard's subscriptions.+ */+export const openSubscriptionsSidebarIfAllowed =+ (+ dashboard: Pick<Dashboard, "dashcards">,+ subscriptionId: DashboardSubscription["id"] | undefined,+ ) =>+ async (dispatch: Dispatch, getState: GetState) => {+ if (canManageSubscriptions(getState())) {+ try {+ await runRtkEndpoint(+ undefined,+ dispatch,+ subscriptionApi.endpoints.getChannelInfo,+ { forceRefetch: false },+ );+ } catch {+ // Without channel info, only an admin can manage subscriptions+ }+ }+ const state = getState();+ const { data: channelInfo } =+ subscriptionApi.endpoints.getChannelInfo.select()(state);+ if (!getCanManageDashboardSubscriptions(state, dashboard, channelInfo)) {+ return;+ }+ dispatch(+ subscriptionId != null+ ? editSubscriptionInSidebar(subscriptionId)+ : setSharing(true),+ );+ };++/** Keeps the subscriptions sidebar open and drops the subscription it was asked to edit. */+export const clearRequestedSubscription = () =>+ setSidebar({ name: SIDEBAR_NAME.sharing });+export const closeSidebarIfSubscriptionsSidebarOpen =() => (dispatch: Dispatch, getState: GetState) => {const state = getState();diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsxindex 39f5aee9cf0..2bfc79029b1 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx@@ -4,6 +4,7 @@ import { t } from "ttag";import { useGetCollectionQuery } from "metabase/api";import { LeaveConfirmModal } from "metabase/common/components/LeaveConfirmModal";+import { isReturningToDataStudio } from "metabase/common/data-studio/utils/return-to";import { canManageSubscriptions as canManageSubscriptionsSelector } from "metabase/current-user";import {cancelEditingDashboard,@@ -77,13 +78,15 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {};const onConfirmCancel = () => {- dispatch(- fetchDashboard({- dashId: dashboard.id,- queryParams: parameterQueryParams ?? {},- options: { preserveParameters: true },- }),- );+ if (!isReturningToDataStudio(location)) {+ dispatch(+ fetchDashboard({+ dashId: dashboard.id,+ queryParams: parameterQueryParams ?? {},+ options: { preserveParameters: true },+ }),+ );+ }dispatch(cancelEditingDashboard(location));closeModal();};diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsxindex ded15f6fe79..b826a711207 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx@@ -3,14 +3,20 @@ import { c, t } from "ttag";import { Link, type LinkProps } from "metabase/common/components/Link";import { ToolbarButton } from "metabase/common/components/ToolbarButton";+import { canAccessDataStudio } from "metabase/common/data-studio/selectors";import { openEventsSidebar } from "metabase/dashboard/actions";import { useDashboardContext } from "metabase/dashboard/context/context";import { useRefreshDashboard } from "metabase/dashboard/hooks";import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";-import { PLUGIN_CACHING, PLUGIN_MODERATION } from "metabase/plugins";-import { useDispatch } from "metabase/redux";+import {+ PLUGIN_CACHING,+ PLUGIN_LIBRARY,+ PLUGIN_MODERATION,+} from "metabase/plugins";+import { useDispatch, useSelector } from "metabase/redux";import { useLocation } from "metabase/router";import { Icon, Menu } from "metabase/ui";+import * as Urls from "metabase/urls";import { parseSearchQuery } from "metabase/utils/browser";import {@@ -50,6 +56,7 @@ const DashboardActionMenuInner = ({onChangeLocation,withTimelineEvents = false,} = useDashboardContext();+ const hasDataStudioAccess = useSelector(canAccessDataStudio);const [opened, setOpened] = useState(false);const [showAutoRefreshOptions, setShowAutoRefreshOptions] = useState(false);@@ -97,6 +104,9 @@ const DashboardActionMenuInner = ({const canConfigureCaching =dashboard.can_set_cache_policy && PLUGIN_CACHING.isGranularCachingEnabled();+ const showDataStudioLink =+ hasDataStudioAccess &&+ PLUGIN_LIBRARY.isLibraryCollectionType(dashboard.collection?.type);return (<Menu position="bottom-end" opened={opened} onChange={handleOpenChange}>@@ -114,6 +124,17 @@ const DashboardActionMenuInner = ({<AutoRefreshMenuOptions onSelect={() => handleOpenChange(false)} />) : (<>+ {showDataStudioLink && (+ <>+ <Menu.Item+ leftSection={<Icon name="grid_bordered" />}+ component={ForwardRefLink}+ to={Urls.dataStudioDashboard(dashboard.id)}+ >{t`Open in Data Studio`}</Menu.Item>+ <Menu.Divider />+ </>+ )}+{canResetFilters && (<Menu.ItemleftSection={<Icon name="revert" />}diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsxindex c7c222dce8b..1372d2b4734 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx@@ -1,46 +1,20 @@import { t } from "ttag";-import { useGetChannelInfoQuery } from "metabase/api";import { ToolbarButton } from "metabase/common/components/ToolbarButton";-import {- canManageSubscriptions as canManageSubscriptionsSelector,- getUserIsAdmin,-} from "metabase/current-user";import { toggleSharing } from "metabase/dashboard/actions";import { useDashboardContext } from "metabase/dashboard/context";+import { useCanManageDashboardSubscriptions } from "metabase/dashboard/hooks";import { getIsSharing } from "metabase/dashboard/selectors";import { useDispatch, useSelector } from "metabase/redux";export const DashboardSubscriptionsButton = () => {const { dashboard } = useDashboardContext();const dispatch = useDispatch();-- const isAdmin = useSelector(getUserIsAdmin);- const canManageSubscriptions = useSelector(canManageSubscriptionsSelector);const isSharing = useSelector(getIsSharing);+ const canManageDashboardSubscriptions =+ useCanManageDashboardSubscriptions(dashboard);- // 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) {+ if (!canManageDashboardSubscriptions) {return null;}diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsxindex 35539ed2543..bb2a47f587f 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx@@ -15,11 +15,8 @@ export const SaveEditButton = () => {// The SDK renders the dashboard header outside the app router, and has no URL// hash to strip, so leaving edit mode there simply skips the navigation.const location = useMaybeLocation() ?? undefined;- const {- setEditingDashboard,- updateDashboardAndCards,- onRefreshPeriodChange,- } = useDashboardContext();+ const { updateDashboardAndCards, onRefreshPeriodChange } =+ useDashboardContext();const missingRequiredParameters = useSelector(getMissingRequiredParameters);@@ -28,18 +25,12 @@ export const SaveEditButton = () => {);const isSaveDisabled = missingRequiredParameters.length > 0;- const handleDoneEditing = () => {- onRefreshPeriodChange(null);- setEditingDashboard(null, location);- };-const onSave = async () => {// optimistically dismissing all the undos before the saving has finished// clicking on them wouldn't do anything at this moment anywaydispatch(dismissAllUndo());await updateDashboardAndCards(location);-- handleDoneEditing();+ onRefreshPeriodChange(null);};useRegisterShortcut([diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/tests/enterprise.unit.spec.ts b/frontend/src/metabase/dashboard/components/DashboardHeader/tests/enterprise.unit.spec.tsindex dc0d6079482..f167cdc47f5 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/tests/enterprise.unit.spec.ts+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/tests/enterprise.unit.spec.ts@@ -1,4 +1,7 @@-import { screen } from "__support__/ui";+import userEvent from "@testing-library/user-event";++import { screen, within } from "__support__/ui";+import type { Dashboard } from "metabase-types/api";import {createMockCollection,createMockDashboard,@@ -6,6 +9,27 @@ import {import { setup } from "./setup";+type SetupOpts = {+ dashboard: Dashboard;+ isAdmin: boolean;+};++const setupWithLibrary = ({ dashboard, isAdmin }: SetupOpts) =>+ setup({+ dashboard,+ collections: [LIBRARY_COLLECTION],+ isAdmin,+ tokenFeatures: { library: true },+ enterprisePlugins: ["library"],+ });++async function openDashboardMenu() {+ await userEvent.click(+ await screen.findByRole("button", { name: "Move, trash, and more…" }),+ );+ return screen.findByRole("menu");+}+const setupEnterprise = (opts: any) => {return setup({...opts,@@ -28,6 +52,26 @@ const INSTANCE_ANALYTICS_COLLECTION = createMockCollection({can_write: false,});+const LIBRARY_COLLECTION = createMockCollection({+ name: "Dashboards",+ id: 20,+ type: "library-dashboards",+});++const LIBRARY_DASHBOARD = createMockDashboard({+ name: "Library Dashboard",+ id: 4,+ collection_id: LIBRARY_COLLECTION.id,+ collection: LIBRARY_COLLECTION,+ can_write: true,+});++const REGULAR_DASHBOARD = createMockDashboard({+ name: "Regular Dashboard",+ id: 5,+ can_write: true,+});+describe("DashboardHeader - enterprise", () => {it("should render the correct buttons for instance analytics dashboard", async () => {await setupEnterprise({@@ -56,8 +100,56 @@ describe("DashboardHeader - enterprise", () => {screen.getByRole("button", { name: /fullscreen/i }),).toBeInTheDocument();+ expect(screen.queryByLabelText("Edit dashboard")).not.toBeInTheDocument();+ });+});++describe("DashboardHeader - library dashboard", () => {+ it("should keep Edit and offer Open in Data Studio first in the menu", async () => {+ await setupWithLibrary({ dashboard: LIBRARY_DASHBOARD, isAdmin: true });++ expect(await screen.findByLabelText("Edit dashboard")).toBeInTheDocument();++ const menu = await openDashboardMenu();+ const [firstItem] = within(menu).getAllByRole("menuitem");+ expect(firstItem).toHaveTextContent("Open in Data Studio");+ expect(firstItem).toHaveAttribute(+ "href",+ `/data-studio/dashboards/${LIBRARY_DASHBOARD.id}`,+ );+ });++ it("should keep Edit without Open in Data Studio for a user without Data Studio access", async () => {+ await setupWithLibrary({ dashboard: LIBRARY_DASHBOARD, isAdmin: false });++ expect(await screen.findByLabelText("Edit dashboard")).toBeInTheDocument();++ const menu = await openDashboardMenu();+ expect(+ within(menu).queryByRole("menuitem", { name: /Open in Data Studio/ }),+ ).not.toBeInTheDocument();+ });++ it("should hide Edit for a user who cannot write the dashboard", async () => {+ await setupWithLibrary({+ dashboard: { ...LIBRARY_DASHBOARD, can_write: false },+ isAdmin: false,+ });++ expect(+ await screen.findByRole("button", { name: "Move, trash, and more…" }),+ ).toBeInTheDocument();+ expect(screen.queryByLabelText("Edit dashboard")).not.toBeInTheDocument();+ });++ it("should keep Edit and no Open in Data Studio for a dashboard outside the Library", async () => {+ await setupWithLibrary({ dashboard: REGULAR_DASHBOARD, isAdmin: true });++ expect(await screen.findByLabelText("Edit dashboard")).toBeInTheDocument();++ const menu = await openDashboardMenu();expect(- screen.queryByRole("button", { name: /edit dashboard/i }),+ within(menu).queryByRole("menuitem", { name: /Open in Data Studio/ }),).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsxindex d3d7d9d4f86..bdafb4b37f6 100644--- a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx@@ -3,9 +3,8 @@ import { t } from "ttag";import { useConfirmRouteLeaveModal } from "metabase/common/hooks/use-confirm-route-leave-modal";import { updateDashboardAndCards } from "metabase/dashboard/actions/save";import { getIsDirty, getIsEditing } from "metabase/dashboard/selectors";-import { useDispatch, useSelector } from "metabase/redux";+import { useDispatch, useSelector, useStore } from "metabase/redux";import { dismissAllUndo } from "metabase/redux/undo";-import { useLocation } from "metabase/router";import { Button, Modal, Text } from "metabase/ui";import { isNavigatingToCreateADashboardQuestion } from "./utils";@@ -13,12 +12,15 @@ import { isNavigatingToCreateADashboardQuestion } from "./utils";export const DashboardLeaveConfirmationModal = () => {const isEditing = useSelector(getIsEditing);const isDirty = useSelector(getIsDirty);- const location = useLocation();const dispatch = useDispatch();+ const store = useStore();const { opened, close, confirm, nextLocation } = useConfirmRouteLeaveModal({isEnabled: isEditing && isDirty,+ // Save and Cancel navigate right after leaving edit mode, before this+ // re-renders, so the store is the only up-to-date source+ isLocationAllowed: () => !getIsEditing(store.getState()),});const content = isNavigatingToCreateADashboardQuestion(nextLocation)@@ -28,7 +30,8 @@ export const DashboardLeaveConfirmationModal = () => {actionBtn: {message: t`Save changes`,},- onConfirm: () => dispatch(updateDashboardAndCards(location)),+ // No location: leaving edit mode must not navigate over the pending one+ onConfirm: () => dispatch(updateDashboardAndCards()),}: {title: t`Discard your changes?`,diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsxindex 15155bd9990..c96bf218df0 100644--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx@@ -20,8 +20,9 @@ import {getEditingPulse,getPulseFormInput,} from "metabase/notifications/pulse/selectors";+import { getEditableSubscriptionChannel } from "metabase/notifications/pulse/subscription-editing";import { NEW_PULSE_TEMPLATE, cleanPulse, createChannel } from "metabase/pulse";-import { connect, useDispatch } from "metabase/redux";+import { connect, useDispatch, useSelector } from "metabase/redux";import type { State } from "metabase/redux/store";import type { UiParameter } from "metabase-lib/v1/parameters/types";import type {@@ -38,7 +39,9 @@ import type {User,} from "metabase-types/api";+import { clearRequestedSubscription } from "../../actions";import { useDashboardContext } from "../../context";+import { getSharingSubscriptionId } from "../../selectors";import {AddEditEmailSidebar,@@ -163,6 +166,8 @@ interface DashboardSubscriptionsSidebarInnerProps {onCancel: () => void;params?: Record<string, string>;loading?: boolean;+ requestedSubscriptionId?: DashboardSubscription["id"];+ onSubscriptionRequestHandled: () => void;}function DashboardSubscriptionsSidebarInner({@@ -178,6 +183,8 @@ function DashboardSubscriptionsSidebarInner({pulses,onCancel,loading: isSubscriptionListLoading,+ requestedSubscriptionId,+ onSubscriptionRequestHandled,}: DashboardSubscriptionsSidebarInnerProps) {const dispatch = useDispatch();const archive = useSetArchive();@@ -384,6 +391,29 @@ function DashboardSubscriptionsSidebarInner({[editingMode, setPulse],);+ useEffect(() => {+ if (requestedSubscriptionId == null || !pulses || !formInput?.channels) {+ return;+ }+ const requestedPulse = pulses.find(+ (pulse) => pulse.id === requestedSubscriptionId,+ );+ const editableChannel =+ requestedPulse != null+ ? getEditableSubscriptionChannel(requestedPulse, formInput)+ : null;+ if (requestedPulse != null && editableChannel != null) {+ editPulse(requestedPulse, editableChannel.channel_type);+ }+ onSubscriptionRequestHandled();+ }, [+ requestedSubscriptionId,+ pulses,+ formInput,+ editPulse,+ onSubscriptionRequestHandled,+ ]);+const handleArchive = useCallback(async () => {if (pulse.id != null) {await archive({ id: pulse.id, model: "pulse" }, true);@@ -632,6 +662,12 @@ const DashboardSubscriptionsSidebarConnected = connect(// eslint-disable-next-line import/no-default-export -- deprecated usageexport default function DashboardSubscriptionsSidebar() {const { dashboard, setSharing } = useDashboardContext();+ const dispatch = useDispatch();+ const requestedSubscriptionId = useSelector(getSharingSubscriptionId);+ const handleSubscriptionRequestHandled = useCallback(+ () => dispatch(clearRequestedSubscription()),+ [dispatch],+ );const { data: pulses, isFetching: isSubscriptionListLoading } =useListSubscriptionsQuery(@@ -648,6 +684,8 @@ export default function DashboardSubscriptionsSidebar() {pulses={pulses}loading={isSubscriptionListLoading}onCancel={() => setSharing(false)}+ requestedSubscriptionId={requestedSubscriptionId}+ onSubscriptionRequestHandled={handleSubscriptionRequestHandled}/>);}diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsxindex 952ee34ecf8..be359689454 100644--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx@@ -1,13 +1,16 @@import cx from "classnames";-import { msgid, ngettext, t } from "ttag";-import _ from "underscore";+import { t } from "ttag";import { Sidebar } from "metabase/common/components/Sidebar";import { Label } from "metabase/common/components/type/Label";import { Subhead } from "metabase/common/components/type/Subhead";import CS from "metabase/css/core/index.css";-import { formatDateValue } from "metabase/parameters/utils/date-formatting";-import { getActivePulseParameters } from "metabase/pulse";+import { getEditableSubscriptionChannel } from "metabase/notifications/pulse/subscription-editing";+import {+ buildFilterText,+ buildRecipientText,+ formatSubscriptionDelivery,+} from "metabase/notifications/pulse/subscription-formatting";import { connect } from "metabase/redux";import type { State } from "metabase/redux/store";import {@@ -20,16 +23,8 @@ import {Text,Tooltip,} from "metabase/ui";-import { conjunct } from "metabase/utils/formatting";-import { formatFrame } from "metabase/utils/time-dayjs";-import { isNotNull } from "metabase/utils/types";-import {- formatDateTimeWithUnit,- formatTimeWithUnit,-} from "metabase/value-formatting";import type { UiParameter } from "metabase-lib/v1/parameters/types";import type {- Channel,ChannelApiResponse,ChannelType,DashboardSubscription,@@ -115,7 +110,11 @@ function _PulsesListSidebar({</div><div className={cx(CS.my2, CS.mx4)}>{pulses.map((pulse) => {- const canEdit = canEditPulse(pulse, formInput);+ const editableChannel = getEditableSubscriptionChannel(+ pulse,+ formInput,+ );+ const canEdit = editableChannel != null;return (<Card@@ -127,7 +126,8 @@ function _PulsesListSidebar({shadow="none"withBorderonClick={() =>- canEdit && editPulse(pulse, pulse.channels[0].channel_type)+ editableChannel != null &&+ editPulse(pulse, editableChannel.channel_type)}><div@@ -154,7 +154,7 @@ function _PulsesListSidebar({size={12}/><Label className={cx(CS.hoverChild, CS.hoverInherit)} mb="0">- {friendlySchedule(pulse.channels[0])}+ {formatSubscriptionDelivery(pulse.channels[0])}</Label></div><PulseDetails pulse={pulse} parameters={parameters} />@@ -167,20 +167,6 @@ function _PulsesListSidebar({);}-function canEditPulse(- pulse: DashboardSubscription,- formInput: ChannelApiResponse,-): boolean {- switch (pulse.channels[0].channel_type) {- case "email":- return formInput.channels.email != null;- case "slack":- return formInput.channels.slack != null;- default:- return false;- }-}-function getEmailSubject({channels: [firstChannel],}: DashboardSubscription): string {@@ -189,75 +175,6 @@ function getEmailSubject({: "";}-function buildRecipientText(pulse: DashboardSubscription): string {- const {- channels: [firstChannel],- } = pulse;-- const { channel_type, recipients } = firstChannel;-- if (channel_type !== "email" || !recipients || recipients.length === 0) {- return "";- }-- const [firstRecipient, ...otherRecipients] = recipients;- const firstRecipientText = firstRecipient.common_name || firstRecipient.email;- return _.isEmpty(otherRecipients)- ? firstRecipientText- : `${firstRecipientText} ${ngettext(- msgid`and ${otherRecipients.length} other`,- `and ${otherRecipients.length} others`,- otherRecipients.length,- )}`;-}--export function buildFilterText(- pulse: DashboardSubscription,- parameters: UiParameter[],-): string {- const activeParameters = getActivePulseParameters(pulse, parameters);-- if (_.isEmpty(activeParameters)) {- return "";- }-- const [firstParameter, ...otherParameters] = activeParameters;-- // Format the first parameter value using the same logic as DefaultParametersSection- let formattedValue;- if (firstParameter.type && firstParameter.type.startsWith("date/")) {- const values = Array.isArray(firstParameter.value)- ? firstParameter.value- : [firstParameter.value];- const formattedValues = values- .map((val) => formatDateValue(firstParameter, val))- .filter(isNotNull);- if (formattedValues.length > 0) {- formattedValue = conjunct(formattedValues, t`and`);- } else {- formattedValue = firstParameter.value;- }- } else {- const values = Array.isArray(firstParameter.value)- ? firstParameter.value- : [firstParameter.value];- formattedValue =- values.length > 1- ? t`${values.length} selections`- : conjunct(values.filter(isNotNull), t`and`);- }-- const firstFilterText = `${firstParameter.name}: ${formattedValue}`;-- return _.isEmpty(otherParameters)- ? firstFilterText- : `${firstFilterText} ${ngettext(- msgid`and ${otherParameters.length} more filter`,- `and ${otherParameters.length} more filters`,- otherParameters.length,- )}`;-}-type PulseDetailsProps = {pulse: DashboardSubscription;parameters: UiParameter[];@@ -313,56 +230,5 @@ function PulseDetailsItem({ icon, text }: PulseDetailsItemProps) {);}-function friendlySchedule(channel: Channel): string {- const {- channel_type,- details,- schedule_day,- schedule_frame,- schedule_hour,- schedule_type,- } = channel;-- let scheduleString = "";-- if (channel_type === "email") {- scheduleString += t`Emailed `;- } else if (channel_type === "slack") {- scheduleString += t`Sent to ` + details?.channel + " ";- } else {- scheduleString += t`Sent `;- }-- switch (schedule_type) {- case "hourly":- scheduleString += t`hourly`;- break;- case "daily": {- const hour = formatTimeWithUnit(schedule_hour ?? 0, "hour-of-day");- scheduleString += t`daily at ${hour}`;- break;- }- case "weekly": {- const hour = formatTimeWithUnit(schedule_hour ?? 0, "hour-of-day");- const day = formatDateTimeWithUnit(schedule_day ?? "mon", "day-of-week");- scheduleString += t`${day} at ${hour}`;- break;- }- case "monthly": {- const hour = formatTimeWithUnit(schedule_hour ?? 0, "hour-of-day");- const day = schedule_day- ? formatDateTimeWithUnit(schedule_day, "day-of-week")- : "calendar day";- const frame = formatFrame(schedule_frame ?? "first");- scheduleString += t`monthly on the ${frame} ${day} at ${hour}`;- break;- }- default:- scheduleString += schedule_type;- }-- return scheduleString;-}-// eslint-disable-next-line import/no-default-export -- deprecated usageexport default PulsesListSidebar;diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsxindex fca01591180..abf846da4c3 100644--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx@@ -1,135 +1,113 @@+import userEvent from "@testing-library/user-event";+import { renderWithProviders, screen } from "__support__/ui";-import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";-import type { Channel, ParameterValueOrArray } from "metabase-types/api";+import type { Channel, ChannelApiResponse } from "metabase-types/api";import {createMockChannel,createMockDashboardSubscription,- createMockParameter,createMockUser,} from "metabase-types/api/mocks";-import { PulsesListSidebar, buildFilterText } from "./PulsesListSidebar";--jest.mock("metabase/parameters/utils/date-formatting", () => ({- formatDateValue: jest.fn((_parameter, value) =>- value === "2024-01-15" ? "January 15, 2024" : null,- ),-}));--describe("buildFilterText", () => {- const stateParameter = createMockUiParameter({- id: "1",- name: "State",- slug: "state",- type: "string/=",- });-- const buildPulse = (value: ParameterValueOrArray) =>- createMockDashboardSubscription({- parameters: [createMockParameter({ id: "1", value })],- });-- it("returns an empty string when no parameters have values", () => {- expect(- buildFilterText(createMockDashboardSubscription(), [stateParameter]),- ).toBe("");- });-- it("renders a single value", () => {- expect(buildFilterText(buildPulse("CA"), [stateParameter])).toBe(- "State: CA",- );- });-- it("renders a single-element array value", () => {- expect(buildFilterText(buildPulse(["CA"]), [stateParameter])).toBe(- "State: CA",- );- });+import { PulsesListSidebar } from "./PulsesListSidebar";++const UNCONFIGURED_EMAIL: ChannelApiResponse = {+ channels: {+ email: {+ type: "email",+ name: "Email",+ schedules: ["hourly", "daily", "weekly", "monthly"],+ schedule_type: "hourly",+ allows_recipients: true,+ configured: false,+ recipients: ["user", "email"],+ },+ },+};++type SetupOpts = {+ channel: Channel;+ formInput?: ChannelApiResponse;+};- it("renders a numeric value", () => {- expect(buildFilterText(buildPulse(42), [stateParameter])).toBe("State: 42");- });-- it("summarizes multi-value selections", () => {- expect(buildFilterText(buildPulse(["CA", "NY"]), [stateParameter])).toBe(- "State: 2 selections",- );- });-- it("drops nullish array entries instead of rendering them", () => {- expect(buildFilterText(buildPulse([null]), [stateParameter])).toBe(- "State: ",- );- });-- it("mentions the number of additional filters", () => {- const cityParameter = createMockUiParameter({- id: "2",- name: "City",- slug: "city",- type: "string/=",- });- const pulse = createMockDashboardSubscription({- parameters: [- createMockParameter({ id: "1", value: "CA" }),- createMockParameter({ id: "2", value: "SF" }),- ],- });- expect(buildFilterText(pulse, [stateParameter, cityParameter])).toBe(- "State: CA and 1 more filter",- );- });-- it("formats date parameter values", () => {- const dateParameter = createMockUiParameter({- id: "3",- name: "Created At",- slug: "created_at",- type: "date/single",- });+describe("PulsesListSidebar", () => {+ const setup = ({ channel, formInput = { channels: {} } }: SetupOpts) => {const pulse = createMockDashboardSubscription({- parameters: [createMockParameter({ id: "3", value: "2024-01-15" })],+ id: 1,+ channels: [channel],});- expect(buildFilterText(pulse, [dateParameter])).toBe(- "Created At: January 15, 2024",- );- });-});+ const editPulse = jest.fn();-describe("PulsesListSidebar", () => {- const setup = (channel: Channel) => {renderWithProviders(<PulsesListSidebar- pulses={[- createMockDashboardSubscription({ id: 1, channels: [channel] }),- ]}- formInput={{ channels: {} }}+ pulses={[pulse]}+ formInput={formInput}createSubscription={jest.fn()}onCancel={jest.fn()}- editPulse={jest.fn()}+ editPulse={editPulse}/>,);++ return { pulse, editPulse };};const recipient = createMockUser({ common_name: "Ada Lovelace" });it("shows the custom subject of an email subscription", () => {- setup(- createMockChannel({+ setup({+ channel: createMockChannel({recipients: [recipient],details: { subject: "Weekly revenue" },}),- );+ });expect(screen.getByText("Weekly revenue")).toBeInTheDocument();expect(screen.getByText("Ada Lovelace")).toBeInTheDocument();});it("shows only the recipients when no subject is set", () => {- setup(createMockChannel({ recipients: [recipient] }));+ setup({ channel: createMockChannel({ recipients: [recipient] }) });expect(screen.getAllByRole("listitem")).toHaveLength(1);expect(screen.getByRole("listitem")).toHaveTextContent("Ada Lovelace");});++ it("says how and when each subscription sends", () => {+ setup({+ channel: createMockChannel({+ channel_type: "slack",+ details: { channel: "#sales" },+ schedule_type: "weekly",+ schedule_day: "mon",+ schedule_hour: 9,+ }),+ });++ expect(screen.getByText("Sent to #sales Monday at 9:00 AM")).toBeVisible();+ });++ it("opens the edit form of an email subscription whose channel is not configured", async () => {+ const channel = createMockChannel({+ schedule_type: "daily",+ schedule_hour: 8,+ });+ const { pulse, editPulse } = setup({+ channel,+ formInput: UNCONFIGURED_EMAIL,+ });++ await userEvent.click(screen.getByText("Emailed daily at 8:00 AM"));++ expect(editPulse).toHaveBeenCalledTimes(1);+ expect(editPulse).toHaveBeenCalledWith(pulse, "email");+ });++ it("does not open an edit form for a channel the form input leaves out", async () => {+ const { editPulse } = setup({+ channel: createMockChannel({ schedule_type: "hourly" }),+ });++ await userEvent.click(screen.getByText("Emailed hourly"));++ expect(editPulse).not.toHaveBeenCalled();+ });});diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.tsindex b0a65e5c4d8..1b3ef8d925e 100644--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts@@ -500,4 +500,68 @@ describe("DashboardSubscriptionsSidebar", () => {});});});++ describe("requested subscription", () => {+ const pulse = createMockDashboardSubscription({+ id: 10,+ channels: [+ createMockChannel({+ schedule_type: "hourly",+ recipients: [user],+ details: { subject: "Weekly revenue" },+ }),+ ],+ });++ it("opens the edit form of the requested subscription once", async () => {+ setup({ isAdmin: true, pulses: [pulse], requestedSubscriptionId: 10 });++ expect(+ await screen.findByText("Email this dashboard"),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Subject")).toHaveValue("Weekly revenue");++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(await screen.findByText("Emailed hourly")).toBeInTheDocument();+ expect(+ screen.queryByText("Email this dashboard"),+ ).not.toBeInTheDocument();+ });++ it("shows the list when the requested subscription does not exist", async () => {+ setup({ isAdmin: true, pulses: [pulse], requestedSubscriptionId: 99 });++ expect(await screen.findByText("Emailed hourly")).toBeInTheDocument();+ expect(+ screen.queryByText("Email this dashboard"),+ ).not.toBeInTheDocument();+ });++ it("opens the edit form of a requested subscription whose channel is not configured, like the list does", async () => {+ setup({+ isAdmin: true,+ emailConfigured: false,+ pulses: [pulse],+ requestedSubscriptionId: 10,+ });++ expect(+ await screen.findByText("Email this dashboard"),+ ).toBeInTheDocument();+ });++ it("shows the list when the form input leaves out the requested subscription's channel", async () => {+ setup({+ isAdmin: true,+ email: false,+ pulses: [pulse],+ requestedSubscriptionId: 10,+ });++ expect(await screen.findByText("Emailed hourly")).toBeInTheDocument();+ expect(+ screen.queryByText("Email this dashboard"),+ ).not.toBeInTheDocument();+ });+ });});diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsxindex ea9ecca8c70..9f7c26ae3f3 100644--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx@@ -59,14 +59,30 @@ const defaultParameters = [},];-function createDashboardState(- dashboard: Dashboard,- dashcards: DashboardCard[],- selectedTabId: SelectedTabId = null,-) {+type DashboardStateOpts = {+ dashboard: Dashboard;+ dashcards: DashboardCard[];+ selectedTabId: SelectedTabId;+ requestedSubscriptionId?: DashboardSubscription["id"];+};++function createDashboardState({+ dashboard,+ dashcards,+ selectedTabId,+ requestedSubscriptionId,+}: DashboardStateOpts) {return createMockDashboardState({dashboardId: dashboard.id,selectedTabId,+ ...(requestedSubscriptionId != null+ ? {+ sidebar: {+ name: "sharing",+ props: { subscriptionId: requestedSubscriptionId },+ },+ }+ : {}),dashcards: dashcards.reduce((acc, card) => {acc[card.id] = card;@@ -86,6 +102,7 @@ function createDashboardState(type SetupOpts = {email?: boolean;+ emailConfigured?: boolean;slack?: boolean;tokenFeatures?: Partial<TokenFeatures>;enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];@@ -102,10 +119,12 @@ type SetupOpts = {lastName: string;};pulseListDelay?: number;+ requestedSubscriptionId?: DashboardSubscription["id"];};export function setup({email = true,+ emailConfigured = true,slack = true,tokenFeatures = {},enterprisePlugins,@@ -119,6 +138,7 @@ export function setup({pulses = [],currentUser,pulseListDelay = 0,+ requestedSubscriptionId,}: SetupOpts = {}) {const dashboard = createMockDashboard({dashcards,@@ -140,7 +160,7 @@ export function setup({allows_recipients: true,recipients: ["user", "email"],schedules: ["hourly", "daily", "weekly", "monthly"],- configured: true,+ configured: emailConfigured,};}@@ -217,7 +237,12 @@ export function setup({last_name: currentUser?.lastName,is_superuser: isAdmin,}),- dashboard: createDashboardState(dashboard, dashcards, selectedTabId),+ dashboard: createDashboardState({+ dashboard,+ dashcards,+ selectedTabId,+ requestedSubscriptionId,+ }),}),},);diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.return-to-data-studio.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.return-to-data-studio.unit.spec.tsxnew file mode 100644index 00000000000..00175291795--- /dev/null+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.return-to-data-studio.unit.spec.tsx@@ -0,0 +1,440 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupActionsEndpoints,+ setupBookmarksEndpoints,+ setupCardQueryEndpoints,+ setupCardQueryMetadataEndpoint,+ setupCardsEndpoints,+ setupCollectionByIdEndpoint,+ setupCollectionsEndpoints,+ setupDashboardEndpoints,+ setupDashboardQueryMetadataEndpoint,+ setupDatabasesEndpoints,+ setupSearchEndpoints,+} from "__support__/server-mocks";+import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";+import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";+import { mockSettings } from "__support__/settings";+import { createMockDashboardState } from "__support__/state";+import { createMockEntitiesState } from "__support__/store";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ waitForDashboardToLoad,+} from "__support__/ui";+import type { DataStudioReturnState } from "metabase/common/data-studio/utils/return-to";+import { getNewQuestionUrl } from "metabase/dashboard/components/QuestionPicker/actions";+import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";+import { Route, useNavigate } from "metabase/router";+import { checkNotNull } from "metabase/utils/types";+import { registerVisualizations } from "metabase/visualizations/register";+import type { Dashboard } from "metabase-types/api";+import {+ createMockCard,+ createMockCardQueryMetadata,+ createMockCollection,+ createMockDashboard,+ createMockDashboardCard,+ createMockDashboardQueryMetadata,+ createMockDatabase,+ createMockDataset,+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";++registerVisualizations();++const CARD = createMockCard({ id: 1 });+const DASHCARD = createMockDashboardCard({+ id: 1,+ dashboard_id: 1,+ card_id: CARD.id,+ card: CARD,+});+const DASHBOARD = createMockDashboard({+ id: 1,+ name: "Sales",+ dashcards: [DASHCARD],+});+const LIBRARY_COLLECTION = createMockCollection({+ id: 20,+ name: "Dashboards",+ type: "library-dashboards",+});+const LIBRARY_DASHBOARD: Dashboard = {+ ...DASHBOARD,+ collection_id: LIBRARY_COLLECTION.id,+ collection: LIBRARY_COLLECTION,+};+const OTHER_DASHBOARD = createMockDashboard({ id: 2, name: "Marketing" });+const DATA_STUDIO_PATH = "/data-studio/dashboards/1";+const NEW_QUESTION_PATH = "/question/notebook";++type SetupOpts = {+ returnState?: DataStudioReturnState;+ dashboard?: Dashboard;+ hash?: string;+ isAdmin?: boolean;+ hasLibrary?: boolean;+};++function OpenDashboardButton({+ returnState,+ hash = "",+}: Pick<SetupOpts, "returnState" | "hash">) {+ const navigate = useNavigate();+ return (+ <button+ onClick={() =>+ navigate(`/dashboard/${DASHBOARD.id}${hash}`, { state: returnState })+ }+ >+ Open dashboard+ </button>+ );+}++async function renderDashboardApp({+ returnState,+ dashboard = DASHBOARD,+ hash,+ isAdmin = false,+ hasLibrary = false,+}: SetupOpts = {}) {+ const settings = mockSettings({+ "site-url": "http://localhost:3000",+ "token-features": createMockTokenFeatures({ library: hasLibrary }),+ });+ if (hasLibrary) {+ setupEnterpriseOnlyPlugin("library");+ }+ const collections = dashboard.collection ? [dashboard.collection] : [];+ const database = createMockDatabase();+ setupNotificationChannelsEndpoints({});+ setupDatabasesEndpoints([database]);+ [dashboard, OTHER_DASHBOARD].forEach((mockDashboard) => {+ // The echoed request would drop the `card` the real response hydrates on each dashcard+ setupDashboardEndpoints(mockDashboard, { updatedDashboard: mockDashboard });+ setupDashboardQueryMetadataEndpoint(+ mockDashboard,+ createMockDashboardQueryMetadata({+ databases: [database],+ cards: [CARD],+ }),+ );+ });+ setupDashcardQueryEndpoints(DASHBOARD.id, DASHCARD, createMockDataset());+ setupCollectionsEndpoints({ collections });+ setupCollectionByIdEndpoint({ collections });+ setupSearchEndpoints([]);+ setupCardsEndpoints([CARD]);+ setupCardQueryEndpoints(CARD, createMockDataset());+ setupCardQueryMetadataEndpoint(+ CARD,+ createMockCardQueryMetadata({ databases: [database] }),+ );+ setupBookmarksEndpoints([]);+ setupActionsEndpoints([]);++ const { router } = renderWithProviders(+ <>+ <Route+ path="/"+ element={<OpenDashboardButton returnState={returnState} hash={hash} />}+ />+ <Route path="/dashboard/:slug" element={<DashboardApp />} />+ <Route+ path="/data-studio/dashboards/:dashboardId"+ element={<div>Data Studio dashboard</div>}+ />+ <Route path={NEW_QUESTION_PATH} element={<div>New question</div>} />+ </>,+ {+ initialRoute: "/",+ withRouter: true,+ storeInitialState: {+ currentUser: createMockUser({ is_superuser: isAdmin }),+ dashboard: createMockDashboardState(),+ entities: createMockEntitiesState({ databases: [database] }),+ settings,+ },+ },+ );+ const testRouter = checkNotNull(router);+ const visitedPaths: string[] = [];+ testRouter.onLocationChange((location) =>+ visitedPaths.push(location.pathname),+ );++ // DashboardApp reads the edit hash from window.location, which the memory router neither sets nor clears+ window.location.hash = hash ?? "";+ await userEvent.click(screen.getByRole("button", { name: "Open dashboard" }));+ await waitForDashboardToLoad();+ window.location.hash = "";++ return { router: testRouter, visitedPaths };+}++async function setup(opts: SetupOpts = {}) {+ const view = await renderDashboardApp(opts);+ await userEvent.click(screen.getByLabelText("Edit dashboard"));+ expect(await screen.findByRole("button", { name: "Save" })).toBeVisible();+ return view;+}++async function renameDashboard() {+ const heading = screen.getByTestId("dashboard-name-heading");+ await userEvent.type(heading, " v2");+ await userEvent.tab();+}++function getRequestCount() {+ return fetchMock.callHistory.calls().length;+}++function getDashboardRequestsSince(requestCount: number) {+ return fetchMock.callHistory+ .calls()+ .slice(requestCount)+ .map((call) => ({+ method: (call.options.method ?? "get").toUpperCase(),+ pathname: new URL(call.url).pathname,+ }))+ .filter(({ pathname }) =>+ pathname.startsWith(`/api/dashboard/${DASHBOARD.id}`),+ )+ .map(({ method, pathname }) => `${method} ${pathname}`);+}++async function settleRequests() {+ let requestCount;+ do {+ requestCount = getRequestCount();+ await act(() => fetchMock.callHistory.flush(true));+ } while (getRequestCount() !== requestCount);+}++const RETURN_STATE: DataStudioReturnState = { returnTo: DATA_STUDIO_PATH };+const ADD_CARD_HASH = `#add=${CARD.id}&edit`;++async function discardAddedCard() {+ await userEvent.click(await screen.findByRole("button", { name: "Cancel" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Discard changes" }),+ );+}++describe("DashboardApp return to Data Studio", () => {+ it("returns to Data Studio once after saving changes", async () => {+ const { router, visitedPaths } = await setup({ returnState: RETURN_STATE });++ await renameDashboard();+ await userEvent.click(screen.getByRole("button", { name: "Save" }));++ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ await waitFor(() =>+ expect(+ fetchMock.callHistory.calls(`path:/api/dashboard/${DASHBOARD.id}`, {+ method: "PUT",+ }),+ ).toHaveLength(1),+ );+ expect(router.location.pathname).toBe(DATA_STUDIO_PATH);+ expect(visitedPaths.filter((path) => path === DATA_STUDIO_PATH)).toEqual([+ DATA_STUDIO_PATH,+ ]);+ });++ it("returns to Data Studio after saving without changes", async () => {+ const { router } = await setup({ returnState: RETURN_STATE });++ await userEvent.click(screen.getByRole("button", { name: "Save" }));++ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ expect(router.location.pathname).toBe(DATA_STUDIO_PATH);+ });++ it("returns to Data Studio on Cancel", async () => {+ const { router } = await setup({ returnState: RETURN_STATE });++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ expect(router.location.pathname).toBe(DATA_STUDIO_PATH);+ });++ it("returns to Data Studio after discarding changes, asking only once", async () => {+ const { router } = await setup({ returnState: RETURN_STATE });++ await renameDashboard();+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Discard changes" }),+ );++ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ expect(router.location.pathname).toBe(DATA_STUDIO_PATH);+ expect(screen.queryByText("Discard your changes?")).not.toBeInTheDocument();+ });++ it("does not reload the dashboard after saving returns to Data Studio", async () => {+ await setup({ returnState: RETURN_STATE });+ await renameDashboard();+ const requestCount = getRequestCount();++ await userEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ await settleRequests();++ expect(getDashboardRequestsSince(requestCount)).toEqual([+ `PUT /api/dashboard/${DASHBOARD.id}`,+ ]);+ });++ it("does not reload the dashboard after canceling returns to Data Studio", async () => {+ await setup({ returnState: RETURN_STATE });+ const requestCount = getRequestCount();++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ await settleRequests();++ expect(getDashboardRequestsSince(requestCount)).toEqual([]);+ });++ it("replaces the dashboard history entry when returning to Data Studio", async () => {+ const { router } = await setup({ returnState: RETURN_STATE });++ await userEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ act(() => router.back());++ await waitFor(() => expect(router.location.pathname).toBe("/"));+ });++ it("stays on the dashboard when it was not opened from Data Studio", async () => {+ const { router, visitedPaths } = await setup();++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(await screen.findByLabelText("Edit dashboard")).toBeInTheDocument();+ expect(router.location.pathname).toBe(`/dashboard/${DASHBOARD.id}`);+ expect(visitedPaths).not.toContain(DATA_STUDIO_PATH);+ });++ it("does not return to Data Studio when switching dashboards while editing", async () => {+ const { router, visitedPaths } = await setup({ returnState: RETURN_STATE });++ act(() => {+ router.navigate(`/dashboard/${OTHER_DASHBOARD.id}`);+ });++ expect(await screen.findByDisplayValue(OTHER_DASHBOARD.name)).toBeVisible();+ expect(router.location.pathname).toBe(`/dashboard/${OTHER_DASHBOARD.id}`);+ expect(visitedPaths).not.toContain(DATA_STUDIO_PATH);+ });++ it("continues to the new question after saving from the leave confirmation", async () => {+ const { router, visitedPaths } = await setup({ returnState: RETURN_STATE });++ await renameDashboard();+ act(() => {+ router.navigate(+ getNewQuestionUrl({ dashboard: DASHBOARD, type: "notebook" }),+ );+ });+ await userEvent.click(+ await screen.findByRole("button", { name: "Save changes" }),+ );++ expect(await screen.findByText("New question")).toBeVisible();+ expect(router.location.pathname).toBe(NEW_QUESTION_PATH);+ expect(visitedPaths).not.toContain(DATA_STUDIO_PATH);+ });+});++describe("DashboardApp editing a Library dashboard", () => {+ const USERS = [+ { isAdmin: true, user: "a Data Studio user" },+ { isAdmin: false, user: "a user without Data Studio access" },+ ];++ it.each(USERS)(+ "stays on the dashboard when $user opens the editor from the URL",+ async ({ isAdmin }) => {+ const { router, visitedPaths } = await renderDashboardApp({+ dashboard: LIBRARY_DASHBOARD,+ hash: "#edit=true",+ isAdmin,+ hasLibrary: true,+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Cancel" }),+ );++ expect(+ await screen.findByLabelText("Edit dashboard"),+ ).toBeInTheDocument();+ expect(router.location.pathname).toBe(`/dashboard/${DASHBOARD.id}`);+ expect(visitedPaths).not.toContain(DATA_STUDIO_PATH);+ },+ );++ it.each(USERS)(+ "stays on the dashboard when $user discards a card added from #add",+ async ({ isAdmin }) => {+ const { router, visitedPaths } = await renderDashboardApp({+ dashboard: LIBRARY_DASHBOARD,+ hash: ADD_CARD_HASH,+ isAdmin,+ hasLibrary: true,+ });++ await discardAddedCard();++ expect(+ await screen.findByLabelText("Edit dashboard"),+ ).toBeInTheDocument();+ expect(router.location.pathname).toBe(`/dashboard/${DASHBOARD.id}`);+ expect(visitedPaths).not.toContain(DATA_STUDIO_PATH);+ },+ );++ it("returns to Data Studio when the editor opens from Data Studio", async () => {+ const { router } = await renderDashboardApp({+ dashboard: LIBRARY_DASHBOARD,+ hash: "#edit=true",+ isAdmin: true,+ hasLibrary: true,+ returnState: RETURN_STATE,+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Cancel" }),+ );++ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ expect(router.location.pathname).toBe(DATA_STUDIO_PATH);+ });++ it("returns to Data Studio when a card added from #add was opened from Data Studio", async () => {+ const { router } = await renderDashboardApp({+ dashboard: LIBRARY_DASHBOARD,+ hash: ADD_CARD_HASH,+ isAdmin: true,+ hasLibrary: true,+ returnState: RETURN_STATE,+ });++ await discardAddedCard();++ expect(await screen.findByText("Data Studio dashboard")).toBeVisible();+ expect(router.location.pathname).toBe(DATA_STUDIO_PATH);+ });+});diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsxindex 5cfefffad61..0477dfb0581 100644--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx@@ -8,6 +8,7 @@ import CS from "metabase/css/core/index.css";import {addCardToDashboard,navigateToNewCardFromDashboard,+ openSubscriptionsSidebarIfAllowed,setEditingDashboard,toggleSidebar,} from "metabase/dashboard/actions";@@ -107,6 +108,7 @@ export const DashboardApp = () => {window.location.hash,);const editingOnLoad = options.edit;+ const subscriptionsOnLoad = options.subscriptions;const addCardOnLoad = options.add != null ? Number(options.add) : undefined;try {@@ -115,6 +117,17 @@ export const DashboardApp = () => {options = await extractHashOption("edit", options);}+ if (subscriptionsOnLoad) {+ dispatch(+ openSubscriptionsSidebarIfAllowed(+ dashboard,+ // a numeric hash value is parsed into a number, whatever its type says+ Urls.extractEntityId(String(subscriptionsOnLoad)),+ ),+ );+ options = await extractHashOption("subscriptions", options);+ }+if (addCardOnLoad != null && dashboardId != null) {options = await extractHashOption("add", options);const searchParams = new URLSearchParams(window.location.search);diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsxindex b0a673e75f8..fb9e5152270 100644--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.unit.spec.tsx@@ -11,10 +11,13 @@ import {setupDashboardEndpoints,setupDashboardQueryMetadataEndpoint,setupDatabasesEndpoints,+ setupListSubscriptionsEndpoint,+ setupNotificationChannelsEndpoints,setupSearchEndpoints,setupTableEndpoints,+ setupUserRecipientsEndpoint,} from "__support__/server-mocks";-import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";+import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";import { mockSettings } from "__support__/settings";import { createMockDashboardState } from "__support__/state";import { createMockEntitiesState } from "__support__/store";@@ -22,21 +25,27 @@ import {act,renderWithProviders,screen,+ waitFor,waitForDashboardToLoad,} from "__support__/ui";import { getBeforeUnloadUnsavedMessage } from "metabase/common/hooks/use-before-unload";import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";+import { getIsSharing } from "metabase/dashboard/selectors";import { Route } from "metabase/router";import { defer } from "metabase/utils/promise";import { checkNotNull } from "metabase/utils/types";import type { Dashboard } from "metabase-types/api";import {createMockCard,+ createMockChannel,createMockCollection,createMockCollectionItem,createMockDashboard,+ createMockDashboardCard,createMockDashboardQueryMetadata,+ createMockDashboardSubscription,createMockDatabase,+ createMockDataset,createMockHeadingDashboardCard,createMockTable,createMockTextDashboardCard,@@ -64,12 +73,14 @@ interface Options {slug?: string;/** Holds the query metadata response until `resolveQueryMetadata` is called. */deferQueryMetadata?: boolean;+ channels?: Parameters<typeof setupNotificationChannelsEndpoints>[0];}function renderDashboardApp({dashboard,slug,deferQueryMetadata = false,+ channels = {},}: Options = {}) {const mockDashboard = createMockDashboard(dashboard);const dashboardId = mockDashboard.id;@@ -78,7 +89,7 @@ function renderDashboardApp({});const queryMetadataRequest = defer();- setupNotificationChannelsEndpoints({});+ setupNotificationChannelsEndpoints(channels);setupDatabasesEndpoints([TEST_DATABASE_WITH_ACTIONS]);setupDashboardEndpoints(mockDashboard);@@ -299,6 +310,99 @@ describe("DashboardApp", () => {);});+ describe("subscriptions hash", () => {+ const subscription = createMockDashboardSubscription({+ id: 12,+ channels: [createMockChannel({ schedule_type: "hourly" })],+ });+ const channels: Options["channels"] = {+ email: {+ type: "email",+ name: "Email",+ configured: true,+ allows_recipients: true,+ recipients: ["user", "email"],+ schedules: ["hourly", "daily", "weekly", "monthly"],+ },+ };+ const dashcard = createMockDashboardCard({ card: TEST_CARD });+ const dashboard: Options["dashboard"] = { dashcards: [dashcard] };++ beforeEach(() => {+ setupDashcardQueryEndpoints(+ createMockDashboard().id,+ dashcard,+ createMockDataset(),+ );+ setupListSubscriptionsEndpoint([subscription]);+ setupUserRecipientsEndpoint({ users: [] });+ });++ afterEach(() => {+ window.location.hash = "";+ });++ it("opens the subscriptions sidebar when the URL asks for it", async () => {+ // DashboardApp reads hash options from window.location, which the memory router does not set+ window.location.hash = "#subscriptions";+ const { router } = await setup({ dashboard, channels });++ expect(await screen.findByText("Emailed hourly")).toBeInTheDocument();+ expect(router.location.hash).toBe("");+ });++ it("opens the edit form of the subscription named in the URL", async () => {+ window.location.hash = "#subscriptions=12";+ await setup({ dashboard, channels });++ expect(+ await screen.findByText("Email this dashboard"),+ ).toBeInTheDocument();+ });++ it("opens the subscriptions list when the subscription id in the URL is not a number", async () => {+ window.location.hash = "#subscriptions=abc";+ await setup({ dashboard, channels });++ expect(await screen.findByText("Emailed hourly")).toBeInTheDocument();+ expect(+ screen.queryByText("Email this dashboard"),+ ).not.toBeInTheDocument();+ });++ it.each<{ name: string; options: Options }>([+ {+ name: "no email or Slack is set up for a non-admin",+ options: { dashboard, channels: {} },+ },+ {+ name: "the dashboard has no card with data to send",+ options: {+ dashboard: { dashcards: [createMockTextDashboardCard()] },+ channels,+ },+ },+ ])(+ "keeps the sidebar closed and drops the hash when $name",+ async ({ options }) => {+ window.location.hash = "#subscriptions=12";+ const { router, store } = await setup(options);++ await waitFor(() => expect(router.location.hash).toBe(""));+ expect(getIsSharing(store.getState())).toBe(false);+ expect(+ screen.queryByText("Email this dashboard"),+ ).not.toBeInTheDocument();+ },+ );++ it("keeps the subscriptions sidebar closed otherwise", async () => {+ const { store } = await setup({ dashboard, channels });++ expect(getIsSharing(store.getState())).toBe(false);+ });+ });+it("should show the error page instead of an endless loader for a non-numeric slug (metabase#78725)", async () => {const { store } = await setup({ slug: "thisisinvalid" });diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsxindex e59979d06ac..568848d783b 100644--- a/frontend/src/metabase/dashboard/context/context.tsx+++ b/frontend/src/metabase/dashboard/context/context.tsx@@ -27,6 +27,7 @@ import type {} from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";+import { cancelFetchDashboard } from "../actions";import type { DashboardCardMenu } from "../components/DashCard/DashCardMenu/dashcard-menu";import type { NavigateToNewCardFromDashboardOpts } from "../components/DashCard/types";import type { DashboardActionKey } from "../components/DashboardHeader/DashboardHeaderButtonRow/types";@@ -55,6 +56,11 @@ type DashboardActionButtonList = DashboardActionKey[] | null;export type DashboardContextOwnProps = {dashboardId: DashboardId;+ /**+ * The dashboard the host already fetched for `dashboardId`. The provider+ * loads it instead of fetching it again; a forced refetch still fetches.+ */+ prefetchedDashboard?: Dashboard;parameterQueryParams?: ParameterValuesMap;onLoad?: (dashboard: Dashboard) => void;onError?: (error: unknown) => void;@@ -109,7 +115,7 @@ export type DashboardContextProps = DashboardContextOwnProps &type ContextProps = DashboardContextProps & ReduxProps;export type DashboardContextReturned = DashboardContextOwnResult &- Omit<DashboardContextOwnProps, "dashboardId"> &+ Omit<DashboardContextOwnProps, "dashboardId" | "prefetchedDashboard"> &ReduxProps &Required<DashboardControls> &DashboardContextErrorState &@@ -135,6 +141,7 @@ const DashboardContextProviderInner = forwardRef(function DashboardContextProviderInner({dashboardId,+ prefetchedDashboard,parameterQueryParams = {},onLoad,onLoadWithoutCards,@@ -254,6 +261,10 @@ const DashboardContextProviderInner = forwardRef(options: {clearCache: !effectiveIsNavigatingBackToDashboard,preserveParameters: effectiveIsNavigatingBackToDashboard,+ prefetchedDashboard:+ !forceRefetch && prefetchedDashboard?.id === dashboardId+ ? prefetchedDashboard+ : undefined,},}).then((result) => {@@ -270,6 +281,7 @@ const DashboardContextProviderInner = forwardRef(initialize,isNavigatingBackToDashboard,parameterQueryParams,+ prefetchedDashboard,previousDashboardId,],);@@ -321,10 +333,18 @@ const DashboardContextProviderInner = forwardRef(useEffect(() => {if (dashboardId && dashboardId !== previousDashboardId) {+ cancelFetchDashboardCardData();reset();fetchData({ dashboardId, token });}- }, [dashboardId, token, fetchData, previousDashboardId, reset]);+ }, [+ dashboardId,+ token,+ fetchData,+ previousDashboardId,+ cancelFetchDashboardCardData,+ reset,+ ]);useEffect(() => {if (dashboard) {@@ -357,6 +377,7 @@ const DashboardContextProviderInner = forwardRef(}, [isLoading, previousIsLoading, dashboard, onLoad, error]);useUnmount(() => {+ cancelFetchDashboard();cancelFetchDashboardCardData();reset();closeDashboard();diff --git a/frontend/src/metabase/dashboard/hooks/index.ts b/frontend/src/metabase/dashboard/hooks/index.tsindex ccfe3777dcc..70dd4b49274 100644--- a/frontend/src/metabase/dashboard/hooks/index.ts+++ b/frontend/src/metabase/dashboard/hooks/index.ts@@ -4,3 +4,4 @@ export * from "./use-dashboard-refresh-period";export * from "./use-dashboard-url-query";export * from "./use-refresh-dashboard";export * from "./use-location-sync";+export * from "./use-can-manage-dashboard-subscriptions";diff --git a/frontend/src/metabase/dashboard/hooks/use-can-manage-dashboard-subscriptions.ts b/frontend/src/metabase/dashboard/hooks/use-can-manage-dashboard-subscriptions.tsnew file mode 100644index 00000000000..c902231f64a--- /dev/null+++ b/frontend/src/metabase/dashboard/hooks/use-can-manage-dashboard-subscriptions.ts@@ -0,0 +1,28 @@+import { skipToken, useGetChannelInfoQuery } from "metabase/api";+import { canManageSubscriptions } from "metabase/current-user";+import { useSelector } from "metabase/redux";+import type { Dashboard } from "metabase-types/api";++import { getCanManageDashboardSubscriptions } from "../selectors";++/**+ * Whether the current user can set up and edit this dashboard's+ * subscriptions, by `getCanManageDashboardSubscriptions`. `false` while the+ * channel setup loads for a non-admin.+ */+export function useCanManageDashboardSubscriptions(+ dashboard: Pick<Dashboard, "dashcards"> | null | undefined,+): boolean {+ const hasSubscriptionsPermission = useSelector(canManageSubscriptions);+ // Skip the request when the user can't manage subscriptions, as it fails+ // for them anyway (EMB-967)+ const { data: channelInfo } = useGetChannelInfoQuery(+ hasSubscriptionsPermission ? undefined : skipToken,+ );++ return useSelector(+ (state) =>+ dashboard != null &&+ getCanManageDashboardSubscriptions(state, dashboard, channelInfo),+ );+}diff --git a/frontend/src/metabase/dashboard/reducers-typed.ts b/frontend/src/metabase/dashboard/reducers-typed.tsindex ff2b8616fc8..797b295d280 100644--- a/frontend/src/metabase/dashboard/reducers-typed.ts+++ b/frontend/src/metabase/dashboard/reducers-typed.ts@@ -1,6 +1,6 @@import type { UnknownAction } from "@reduxjs/toolkit";import { createReducer } from "@reduxjs/toolkit";-import { assocIn, dissocIn } from "icepick";+import { assocIn } from "icepick";import _ from "underscore";import {@@ -480,12 +480,15 @@ export const dashcardData = createReducer(.addCase(fetchCardDataAction.fulfilled, (state, action) => {const { dashcard_id, card_id, result } = action.payload ?? {};if (dashcard_id && card_id && result != null) {- return assocIn(state, [dashcard_id, card_id], result);+ // Mutates the draft: icepick would copy child drafts into a frozen+ // object Immer skips when finalizing, leaving revoked proxies behind.+ // Object.assign because DashCardDataMap does not model { error } results.+ Object.assign((state[dashcard_id] ??= {}), { [card_id]: result });}}).addCase(clearCardData, (state, action) => {const { cardId, dashcardId } = action.payload;- return dissocIn(state, [dashcardId, cardId]);+ delete state[dashcardId]?.[cardId];}).addCase<string, { type: string; payload: { object?: Card } }>(CARD_UPDATED,diff --git a/frontend/src/metabase/dashboard/reducers.unit.spec.ts b/frontend/src/metabase/dashboard/reducers.unit.spec.tsindex d7dde2baff2..e8a3e9c06af 100644--- a/frontend/src/metabase/dashboard/reducers.unit.spec.ts+++ b/frontend/src/metabase/dashboard/reducers.unit.spec.ts@@ -10,6 +10,7 @@ import {SET_DASHBOARD_ATTRIBUTES,SET_EDITING_DASHBOARD,SET_SIDEBAR,+ clearCardData,fetchCardDataAction,fetchDashboard,markTimelineEventsShown,@@ -439,6 +440,26 @@ describe("dashboard reducers", () => {});expect(result.dashcardData).toEqual({ 5: { 2: { data: [] } } });});++ it("keeps every dashcard's results readable as more results arrive and clear", () => {+ const fulfilled = (dashcard_id: number, card_id: number) => ({+ type: fetchCardDataAction.fulfilled.type,+ payload: { dashcard_id, card_id, result: { data: [card_id] } },+ });+ const state = [+ fulfilled(1, 10),+ fulfilled(2, 20),+ fulfilled(3, 30),+ clearCardData(30, 3),+ fulfilled(1, 11),+ ].reduce(reducer, initState);++ expect(state.dashcardData).toEqual({+ 1: { 10: { data: [10] }, 11: { data: [11] } },+ 2: { 20: { data: [20] } },+ 3: {},+ });+ });});describe("timelineEvents selection", () => {diff --git a/frontend/src/metabase/dashboard/selectors.ts b/frontend/src/metabase/dashboard/selectors.tsindex 888328dbe60..16e4aba39c0 100644--- a/frontend/src/metabase/dashboard/selectors.ts+++ b/frontend/src/metabase/dashboard/selectors.ts@@ -2,6 +2,7 @@ import { createSelector } from "@reduxjs/toolkit";import _ from "underscore";import { LOAD_COMPLETE_FAVICON } from "metabase/common/hooks/constants";+import { canManageSubscriptions, getUserIsAdmin } from "metabase/current-user";import {DASHBOARD_SLOW_TIMEOUT,SIDEBAR_NAME,@@ -25,6 +26,7 @@ import type {ClickBehaviorSidebarState,EditParameterSidebarState,EventsSidebarState,+ SharingSidebarState,State,StoreDashboard,StoreDashcard,@@ -42,6 +44,7 @@ import {} from "metabase-lib/v1/parameters/utils/parameter-values";import type {Card,+ ChannelApiResponse,DashCardId,Dashboard,DashboardCard,@@ -88,6 +91,17 @@ export const getEventsSidebarProps = (state: State) => {return isEventsSidebar(sidebar) ? sidebar.props : null;};+function isSharingSidebar(+ sidebar: SidebarState,+): sidebar is SharingSidebarState {+ return sidebar.name === SIDEBAR_NAME.sharing;+}++export const getSharingSubscriptionId = (state: State) => {+ const { sidebar } = state.dashboard;+ return isSharingSidebar(sidebar) ? sidebar.props.subscriptionId : undefined;+};+function isEditParameterSidebar(sidebar: SidebarState,): sidebar is EditParameterSidebarState {@@ -158,6 +172,32 @@ export const getIsSharing = createSelector((sidebar) => sidebar.name === SIDEBAR_NAME.sharing,);+/**+ * Whether the current user can set up and edit this dashboard's+ * subscriptions. It takes the Subscriptions permission and a card with data+ * to send, and for a non-admin a configured email or Slack channel, since+ * only an admin can set one up. `channelInfo` is `undefined` while it loads+ * or when its request fails, which leaves only an admin able to manage them.+ */+export const getCanManageDashboardSubscriptions = (+ state: State,+ dashboard: Pick<Dashboard, "dashcards">,+ channelInfo: ChannelApiResponse | undefined,+): boolean => {+ const hasDataCards = dashboard.dashcards.some(+ (dashcard) => !["text", "heading"].includes(dashcard.card.display),+ );+ const hasConfiguredChannel =+ channelInfo?.channels.email?.configured === true ||+ channelInfo?.channels.slack?.configured === true;++ return (+ canManageSubscriptions(state) &&+ hasDataCards &&+ (getUserIsAdmin(state) || hasConfiguredChannel)+ );+};+export const getShowAddQuestionSidebar = createSelector([getSidebar],(sidebar) => sidebar.name === SIDEBAR_NAME.addQuestion,diff --git a/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/use-build-action-tree.ts b/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/use-build-action-tree.tsindex b72d6c266cb..8da18f5f6be 100644--- a/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/use-build-action-tree.ts+++ b/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/use-build-action-tree.ts@@ -5,7 +5,9 @@ import {useListActionsQuery,useListCollectionsQuery,} from "metabase/api";+import { isRootCollection } from "metabase/common/collections/utils";import type { TreeItem } from "metabase/data-studio/common/types";+import type { Collection } from "metabase-types/api";import { buildActiveActionTree, buildArchivedActionTree } from "./utils";@@ -20,6 +22,7 @@ export function useBuildActionTree({}: ActionTreeOptions = {}): {isLoading: boolean;tree: TreeItem[];+ rootCollection?: Collection;error?: unknown;} {const {@@ -56,6 +59,7 @@ export function useBuildActionTree({return {isLoading: false,error,+ rootCollection: collections.find(isRootCollection),tree: archived? buildArchivedActionTree(collections, actions, activeCollections ?? []): buildActiveActionTree(collections, actions, canCreateActions),diff --git a/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.ts b/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.tsindex eca6db093ba..accc35079d7 100644--- a/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.ts+++ b/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.ts@@ -1,23 +1,16 @@-import { t } from "ttag";-import { isRootCollection } from "metabase/common/collections/utils";import type { TreeItem } from "metabase/data-studio/common/types";-import { createEmptyStateItem } from "metabase/data-studio/common/utils";+import {+ buildCollectionTreeChildren,+ buildCollectionTreeNode,+ createEmptyStateItem,+} from "metabase/data-studio/common/utils";import type {Collection,CollectionId,WritebackAction,} from "metabase-types/api";-// The data actions root has the same "root" id as the SQL snippets root, so its node needs its own key.-const DATA_ACTIONS_ROOT_NODE_KEY = "data-actions-root";--export function getActionCollectionNodeId(collection: Pick<Collection, "id">) {- return isRootCollection(collection)- ? `collection:${DATA_ACTIONS_ROOT_NODE_KEY}`- : `collection:${collection.id}`;-}-function createActionNode(action: WritebackAction): TreeItem {return {id: `action:${action.id}`,@@ -37,31 +30,6 @@ function createActionNode(action: WritebackAction): TreeItem {};}-function buildActionCollectionNode(- collection: Collection,- collections: Collection[],- actions: WritebackAction[],-): TreeItem {- const parentId = isRootCollection(collection) ? null : collection.id;- const children = [- ...collections- .filter((child) => child.parent_id === parentId)- .map((child) => buildActionCollectionNode(child, collections, actions)),- ...actions- .filter((action) => action.collection_id === parentId)- .map(createActionNode),- ];-- return {- id: getActionCollectionNodeId(collection),- name: collection.name,- model: "collection",- icon: isRootCollection(collection) ? "bolt" : "folder",- data: { ...collection, model: "collection" },- children: children.length > 0 ? children : undefined,- };-}-function isDataAction(action: WritebackAction,collectionIds: Set<CollectionId>,@@ -73,16 +41,15 @@ function isDataAction(}/**- * The data actions root with its folders and the actions without a model under it, or nothing without a readable- * root.+ * The folders and actions without a model at the top of the data actions collection, an empty-state row when it holds+ * none, or nothing without a readable root.*/export function buildActiveActionTree(actionCollections: Collection[],actions: WritebackAction[],canCreateActions: boolean,): TreeItem[] {- const rootCollection = actionCollections.find(isRootCollection);- if (!rootCollection) {+ if (!actionCollections.some(isRootCollection)) {return [];}@@ -93,22 +60,16 @@ export function buildActiveActionTree(const dataActions = actions.filter((action) => !action.archived && isDataAction(action, collectionIds),);- const rootNode = buildActionCollectionNode(- rootCollection,+ const items = buildCollectionTreeChildren(+ null,collections,dataActions,+ createActionNode,);- const hasContent = dataActions.length > 0 || collections.length > 0;- return [- {- ...rootNode,- name: t`Data actions`,- children: hasContent- ? rootNode.children- : [createEmptyStateItem("actions", undefined, !canCreateActions)],- },- ];+ return items.length > 0+ ? items+ : [createEmptyStateItem("actions", undefined, !canCreateActions)];}/**@@ -136,7 +97,12 @@ export function buildArchivedActionTree(return [...topLevelCollections.map((collection) =>- buildActionCollectionNode(collection, archivedCollections, dataActions),+ buildCollectionTreeNode(+ collection,+ archivedCollections,+ dataActions,+ createActionNode,+ ),),...dataActions.filter(diff --git a/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.unit.spec.ts b/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.unit.spec.tsindex ade1f68f38c..145161dcf1e 100644--- a/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.unit.spec.ts+++ b/frontend/src/metabase/data-studio/actions/hooks/use-build-action-tree/utils.unit.spec.ts@@ -19,7 +19,7 @@ const FOLDER = createMockCollection({});describe("buildActiveActionTree", () => {- it("should put actions without a model under the root and their folders", () => {+ it("should list the top-level folders and actions without a model, with folder actions nested", () => {const tree = buildActiveActionTree([ROOT, FOLDER],[@@ -29,18 +29,13 @@ describe("buildActiveActionTree", () => {true,);- expect(tree).toHaveLength(1);- expect(tree[0]).toMatchObject({- id: "collection:data-actions-root",- name: "Data actions",- children: [- {- id: "collection:10",- children: [{ id: "action:2", model: "action" }],- },- { id: "action:1", model: "action" },- ],- });+ expect(tree).toMatchObject([+ {+ id: "collection:10",+ children: [{ id: "action:2", model: "action" }],+ },+ { id: "action:1", model: "action" },+ ]);});it("should leave out model actions and actions outside data actions folders", () => {@@ -53,13 +48,11 @@ describe("buildActiveActionTree", () => {true,);- expect(tree[0].children).toEqual([- expect.objectContaining({ model: "empty-state" }),- ]);+ expect(tree).toEqual([expect.objectContaining({ model: "empty-state" })]);});- it("should keep the root with an empty state without an action when no action can be created", () => {- expect(buildActiveActionTree([ROOT], [], false)[0].children).toEqual([+ it("should show an empty state without an action when no action can be created", () => {+ expect(buildActiveActionTree([ROOT], [], false)).toEqual([expect.objectContaining({model: "empty-state",data: expect.objectContaining({ actionUrl: undefined }),@@ -68,7 +61,7 @@ describe("buildActiveActionTree", () => {});it("should show the empty state when an action can be created", () => {- expect(buildActiveActionTree([ROOT], [], true)[0].children).toEqual([+ expect(buildActiveActionTree([ROOT], [], true)).toEqual([expect.objectContaining({ model: "empty-state" }),]);});diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsxindex b6d8afeb9a8..e84449fec25 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx@@ -13,10 +13,10 @@ import type { TreeItem } from "metabase/data-studio/common/types";import {filterTreeByName,isCollectionData,+ openNewCollectionModal,} from "metabase/data-studio/common/utils";-import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import { PLUGIN_LIBRARY, PLUGIN_REMOTE_SYNC } from "metabase/plugins";import { useDispatch, useSelector } from "metabase/redux";-import { setOpenModalWithProps } from "metabase/redux/ui";import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";@@ -28,8 +28,6 @@ import { useActionDatabases } from "../../hooks/use-action-databases";import { useBuildActionTree } from "../../hooks/use-build-action-tree";import { canCreateActions } from "../../utils";-import { RootDataActionsMenu } from "./RootDataActionsMenu";-export function ActionListPage() {const [searchQuery, setSearchQuery] = useState("");const [collectionModal, setCollectionModal] =@@ -45,6 +43,7 @@ export function ActionListPage() {const canCreate = canCreateActions(databases);const {tree,+ rootCollection,isLoading: isLoadingActions,error: actionsError,} = useBuildActionTree({@@ -57,10 +56,6 @@ export function ActionListPage() {() => (isSearchActive ? filterTreeByName(tree, searchQuery) : tree),[isSearchActive, tree, searchQuery],);- const defaultExpandedIds = useMemo(- () => tree.slice(0, 1).map((node) => node.id),- [tree],- );const renderRowMenu = useCallback((item: TreeItem) => (<ActionRowMenu item={item} onOpenModal={setCollectionModal} />@@ -76,8 +71,21 @@ export function ActionListPage() {isSearchActive={isSearchActive}searchQuery={searchQuery}emptyMessage={t`No actions yet`}- defaultExpandedIds={defaultExpandedIds}createMenu={canCreate && <ActionsCreateMenu />}+ pageMenu={{+ label: t`Data action options`,+ actions: [+ {+ label: t`View archived actions`,+ icon: "view_archive",+ to: Urls.dataStudioArchivedActions(),+ },+ ],+ permissionsCollection: PLUGIN_LIBRARY.isEnabled+ ? rootCollection+ : undefined,+ onOpenModal: setCollectionModal,+ }}renderRowMenu={renderRowMenu}onSearchQueryChange={setSearchQuery}>@@ -98,9 +106,6 @@ function ActionRowMenu({ item: { data }, onOpenModal }: ActionRowMenuProps) {if (!isCollectionData(data)) {return null;}- if (data.id === "root") {- return <RootDataActionsMenu collection={data} onOpenModal={onOpenModal} />;- }return <CollectionRowMenu collection={data} onOpenModal={onOpenModal} />;}@@ -109,14 +114,10 @@ function ActionsCreateMenu() {const handleNewCollectionClick = useCallback(() => {dispatch(- setOpenModalWithProps({- id: "collection",- props: {- initialCollectionId: null,- namespaces: ACTION_COLLECTION_NAMESPACES,- pickerOptions: ACTION_COLLECTION_PICKER_OPTIONS,- showAuthorityLevelPicker: false,- },+ openNewCollectionModal({+ initialCollectionId: null,+ namespaces: ACTION_COLLECTION_NAMESPACES,+ pickerOptions: ACTION_COLLECTION_PICKER_OPTIONS,}),);}, [dispatch]);diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsxindex 67a6c038e01..2fe948e3ade 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsx@@ -59,7 +59,7 @@ describe("ActionListPage", () => {mockGetBoundingClientRect({ width: 1000, height: 1000 });});- it("lists actions without a model under the Data actions root", async () => {+ it("lists actions without a model at the top level, without a root row", async () => {setup({actions: [createMockQueryAction({@@ -72,8 +72,8 @@ describe("ActionListPage", () => {expect(await screen.findByText("Refund order")).toBeInTheDocument();expect(- within(screen.getByTestId("library-page")).getByText("Data actions"),- ).toBeInTheDocument();+ within(screen.getByTestId("library-page")).queryByText("Data actions"),+ ).not.toBeInTheDocument();});it("offers new actions and collections with native write on an actions-enabled database", async () => {@@ -113,24 +113,4 @@ describe("ActionListPage", () => {screen.getByRole("menuitem", { name: /View archived actions/ }),).toBeInTheDocument();});-- it("keeps the root row expanded when clicking inside the root options menu", async () => {- setup({- actions: [- createMockQueryAction({- id: 1,- name: "Refund order",- collection_id: null,- }),- ],- });-- expect(await screen.findByText("Refund order")).toBeInTheDocument();- await userEvent.click(- screen.getByRole("button", { name: "Data action options" }),- );- await userEvent.click(await screen.findByRole("menu"));-- expect(screen.getByText("Refund order")).toBeInTheDocument();- });});diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/RootDataActionsMenu.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/RootDataActionsMenu.tsxdeleted file mode 100644index 08329ef81de..00000000000--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/RootDataActionsMenu.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { t } from "ttag";--import type { CollectionRowModalState } from "metabase/common/collections/components/CollectionRowModal";-import { Link } from "metabase/common/components/Link";-import { getUserIsAdmin } from "metabase/current-user";-import { PLUGIN_LIBRARY, PLUGIN_REMOTE_SYNC } from "metabase/plugins";-import { useSelector } from "metabase/redux";-import { ActionIcon, FixedSizeIcon, Menu, Tooltip } from "metabase/ui";-import * as Urls from "metabase/urls";-import type { Collection } from "metabase-types/api";--type RootDataActionsMenuProps = {- collection: Collection;- onOpenModal: (modal: CollectionRowModalState) => void;-};--export function RootDataActionsMenu({- collection,- onOpenModal,-}: RootDataActionsMenuProps) {- const isAdmin = useSelector(getUserIsAdmin);- const remoteSyncReadOnly = useSelector(- PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,- );- const canChangePermissions =- PLUGIN_LIBRARY.isEnabled && isAdmin && !remoteSyncReadOnly;- const optionsLabel = t`Data action options`;-- return (- <Menu position="bottom-end">- <Menu.Target>- <Tooltip- label={optionsLabel}- onClick={(event) => event.stopPropagation()}- openDelay={1000}- >- <ActionIcon aria-label={optionsLabel} size="md">- <FixedSizeIcon name="ellipsis" size={16} />- </ActionIcon>- </Tooltip>- </Menu.Target>- <Menu.Dropdown onClick={(event) => event.stopPropagation()}>- {canChangePermissions && (- <Menu.Item- leftSection={<FixedSizeIcon name="lock" />}- onClick={() => onOpenModal({ type: "permissions", collection })}- >- {t`Change permissions`}- </Menu.Item>- )}- <Menu.Item- component={Link}- leftSection={<FixedSizeIcon name="view_archive" />}- to={Urls.dataStudioArchivedActions()}- >- {t`View archived actions`}- </Menu.Item>- </Menu.Dropdown>- </Menu>- );-}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/index.ts b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/index.tsdeleted file mode 100644index 62884e0951d..00000000000--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./RootDataActionsMenu";diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsxindex 38ec69e086e..d53beb5f3bc 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx@@ -113,6 +113,14 @@ export function DataStudioLayout() {) : null}/>+ <AreaTab+ label={t`Dashboards`}+ icon="dashboard"+ to={Urls.dataStudioDashboards()}+ isSelected={currentTab === "dashboards"}+ showLabel={isNavbarOpened}+ isGated={!hasLibraryFeature}+ /><AreaTablabel={t`SQL snippets`}icon="snippet"diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsxindex 7128aa205a9..876066e361b 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx@@ -33,12 +33,16 @@ describe("DataStudioLayout", () => {const nav = await screen.findByTestId("data-studio-nav");for (const label of ["Semantic layer",+ "Dashboards","SQL snippets","Data actions","Glossary",]) {expect(within(nav).getByText(label)).toBeInTheDocument();}+ expect(+ within(nav).getByRole("link", { name: /Dashboards/ }),+ ).toHaveAttribute("href", "/data-studio/dashboards");expect(within(nav).getByRole("link", { name: /SQL snippets/ }),).toHaveAttribute("href", "/data-studio/snippets");diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsxindex c8b746d27dc..ea7c5561880 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx@@ -152,7 +152,12 @@ describe("DataStudioLayout", () => {});describe("library tab dirty indicators", () => {- const LIBRARY_TABS = ["Semantic layer", "SQL snippets", "Data actions"];+ const LIBRARY_TABS = [+ "Semantic layer",+ "Dashboards",+ "SQL snippets",+ "Data actions",+ ];const getTabStatus = (label: string) =>within(screen.getByLabelText(label)).queryByTestId("remote-sync-status");@@ -195,6 +200,7 @@ describe("DataStudioLayout", () => {await waitFor(() => {expect(getTabStatus("Semantic layer")).toBeInTheDocument();});+ expect(getTabStatus("Dashboards")).not.toBeInTheDocument();expect(getTabStatus("SQL snippets")).not.toBeInTheDocument();expect(getTabStatus("Data actions")).not.toBeInTheDocument();});diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.tsindex 08be54a77f2..e1a2254e1ad 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts@@ -4,6 +4,7 @@ type TabName =| "guide"| "data"| "library"+ | "dashboards"| "snippets"| "actions"| "transforms"@@ -31,6 +32,8 @@ export const getCurrentTab = (pathname: string): TabName => {return "actions";case pathname.startsWith(Urls.dataStudioLibrary()):return "library";+ case pathname.startsWith(Urls.dataStudioDashboards()):+ return "dashboards";case pathname.startsWith(Urls.transformList()):return "transforms";case pathname.startsWith(Urls.dataStudioData()):diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.ts b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.tsindex 764ef37cd19..044690d25f0 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.ts+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.ts@@ -16,6 +16,8 @@ describe("getCurrentTab", () => {${"/data-studio/library/metrics/456"} | ${"library"}${"/data-studio/library/metrics/456/overview"} | ${"library"}${"/data-studio/library/tables/42"} | ${"library"}+ ${"/data-studio/dashboards"} | ${"dashboards"}+ ${"/data-studio/dashboards/7/contents"} | ${"dashboards"}${"/data-studio/snippets"} | ${"snippets"}${"/data-studio/snippets/12"} | ${"snippets"}${"/data-studio/actions"} | ${"actions"}diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryPageMenu/LibraryPageMenu.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryPageMenu/LibraryPageMenu.tsxnew file mode 100644index 00000000000..f9b3ca0c02f--- /dev/null+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryPageMenu/LibraryPageMenu.tsx@@ -0,0 +1,78 @@+import { t } from "ttag";++import type { CollectionRowModalState } from "metabase/common/collections/components/CollectionRowModal";+import { ForwardRefLink } from "metabase/common/components/Link";+import { getUserIsAdmin } from "metabase/current-user";+import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import { useSelector } from "metabase/redux";+import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";+import type { Collection, IconName } from "metabase-types/api";++export type LibraryPageAction = {+ label: string;+ icon: IconName;+ to: string;+};++export type LibraryPageMenuProps = {+ label: string;+ actions?: LibraryPageAction[];+ /** Admins get a Change permissions item for it, unless remote sync is read-only. */+ permissionsCollection?: Collection;+ onOpenModal: (modal: CollectionRowModalState) => void;+};++export function LibraryPageMenu({+ label,+ actions = [],+ permissionsCollection,+ onOpenModal,+}: LibraryPageMenuProps) {+ const isAdmin = useSelector(getUserIsAdmin);+ const isRemoteSyncReadOnly = useSelector(+ PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,+ );+ const editablePermissionsCollection =+ isAdmin && !isRemoteSyncReadOnly ? permissionsCollection : undefined;++ if (editablePermissionsCollection == null && actions.length === 0) {+ return null;+ }++ return (+ <Menu position="bottom-end">+ <Menu.Target>+ <Button+ size="lg"+ aria-label={label}+ leftSection={<Icon name="ellipsis" />}+ />+ </Menu.Target>+ <Menu.Dropdown>+ {editablePermissionsCollection != null && (+ <Menu.Item+ leftSection={<FixedSizeIcon name="lock" />}+ onClick={() =>+ onOpenModal({+ type: "permissions",+ collection: editablePermissionsCollection,+ })+ }+ >+ {t`Change permissions`}+ </Menu.Item>+ )}+ {actions.map((action) => (+ <Menu.Item+ key={action.label}+ component={ForwardRefLink}+ to={action.to}+ leftSection={<FixedSizeIcon name={action.icon} />}+ >+ {action.label}+ </Menu.Item>+ ))}+ </Menu.Dropdown>+ </Menu>+ );+}diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryPageMenu/index.ts b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryPageMenu/index.tsnew file mode 100644index 00000000000..21dd35f35b7--- /dev/null+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryPageMenu/index.ts@@ -0,0 +1,2 @@+export { LibraryPageMenu } from "./LibraryPageMenu";+export type { LibraryPageMenuProps } from "./LibraryPageMenu";diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsxindex 4855311f87c..40cda48c91a 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsx+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsx@@ -28,8 +28,11 @@ import {import type { CollectionId } from "metabase-types/api";import { LibraryBulkActions } from "./LibraryBulkActions";+import { LibraryPageMenu, type LibraryPageMenuProps } from "./LibraryPageMenu";import { useLibraryTreeTableInstance } from "./hooks";+const NO_EXPANDED_IDS: readonly string[] = [];+type LibraryTreePageProps = {title: string;tree: TreeItem[];@@ -37,9 +40,10 @@ type LibraryTreePageProps = {isSearchActive: boolean;searchQuery: string;emptyMessage: string;- defaultExpandedIds: string[];+ defaultExpandedIds?: readonly string[];defaultMoveCollectionIds?: Partial<Record<LibrarySection, CollectionId>>;createMenu?: ReactNode;+ pageMenu?: LibraryPageMenuProps;emptyState?: ReactNode;children?: ReactNode;renderRowMenu: (item: TreeItem) => ReactNode;@@ -60,9 +64,10 @@ export function LibraryTreePage({isSearchActive,searchQuery,emptyMessage: defaultEmptyMessage,- defaultExpandedIds,+ defaultExpandedIds = NO_EXPANDED_IDS,defaultMoveCollectionIds,createMenu,+ pageMenu,emptyState,children,renderRowMenu,@@ -94,6 +99,7 @@ export function LibraryTreePage({getSelectionState,getRowCovered,onCheckboxClick,+ onSelectAllClick,clear: clearSelection,} = useLibraryBulkSelection(allRows);@@ -133,6 +139,7 @@ export function LibraryTreePage({onChange={(e) => onSearchQueryChange(e.target.value)}/>{!isRemoteSyncReadOnly && createMenu}+ {pageMenu && <LibraryPageMenu {...pageMenu} />}</Flex><Card withBorder p={0}>{isLoading ? (@@ -144,6 +151,8 @@ export function LibraryTreePage({getSelectionState={getSelectionState}isRowDisabled={getRowCovered}onCheckboxClick={onCheckboxClick}+ onHeaderCheckboxClick={onSelectAllClick}+ headerCheckboxAriaLabel={t`Select all`}emptyState={<ListEmptyState label={emptyMessage} />}onRowClick={(row) => {if (row.original.model === "empty-state") {diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/hooks.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/hooks.tsxindex b7a6877f475..06964408d86 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/hooks.tsx+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/hooks.tsx@@ -39,7 +39,7 @@ type Params = {isSearchActive: boolean;searchQuery: string;emptyMessage: string;- defaultExpandedIds: string[];+ defaultExpandedIds: readonly string[];renderRowMenu: (item: TreeItem) => ReactNode;emptyStateActions?: Partial<Record<LibrarySectionType, () => void>>;};diff --git a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/use-library-bulk-selection.ts b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/use-library-bulk-selection.tsindex 87b2b5b84ed..c6c2bd55738 100644--- a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/use-library-bulk-selection.ts+++ b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/use-library-bulk-selection.ts@@ -17,6 +17,7 @@ import {isSectionRoot,isSelectableItem,toggleItem,+ toggleItems,toggleSectionRoot,} from "./utils";@@ -27,6 +28,8 @@ export type UseLibraryBulkSelectionResult = {getSelectionState: (row: Row<TreeItem>) => SelectionState;getRowCovered: (row: Row<TreeItem>) => boolean;onCheckboxClick: (row: Row<TreeItem>) => void;+ /** Undefined when the top level holds no selectable rows, e.g. section roots. */+ onSelectAllClick: (() => void) | undefined;clear: () => void;};@@ -79,6 +82,27 @@ export function useLibraryBulkSelection(}}, []);+ const topLevelSelectables = useMemo(+ () =>+ rows+ .filter((row) => row.depth === 0)+ .map((row) => row.original)+ .filter(isSelectableItem),+ [rows],+ );++ // Unlike a section root, the header stands for the whole list, so its second+ // click also clears the nested rows ticked inside folders.+ const onSelectAllClick = useCallback(() => {+ setSelected((prev) => {+ const prevKeys = getSelectedKeySet(prev);+ const isAllSelected = topLevelSelectables.every((item) =>+ prevKeys.has(item.id),+ );+ return isAllSelected ? [] : toggleItems(prev, topLevelSelectables);+ });+ }, [topLevelSelectables]);+const clear = useCallback(() => {setSelected([]);}, []);@@ -109,6 +133,8 @@ export function useLibraryBulkSelection(getSelectionState,getRowCovered,onCheckboxClick,+ onSelectAllClick:+ topLevelSelectables.length > 0 ? onSelectAllClick : undefined,clear,};}diff --git a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.ts b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.tsindex 3f36a4ac007..8666d30c96c 100644--- a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.ts+++ b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.ts@@ -166,11 +166,17 @@ export function toggleSectionRoot(selected: TreeItem[],sectionRoot: TreeItem,): TreeItem[] {- const selectables = getSectionDirectSelectables(sectionRoot);+ return toggleItems(selected, getSectionDirectSelectables(sectionRoot));+}++export function toggleItems(+ selected: TreeItem[],+ selectables: TreeItem[],+): TreeItem[] {if (selectables.length === 0) {return selected;}- const section = getItemSection(sectionRoot);+ const section = getItemSection(selectables[0]);const current = getSelectionSection(selected);if (current !== null && current !== section) {return selectables;diff --git a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.unit.spec.ts b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.unit.spec.tsindex e9c7247341d..87b8d2ca3cb 100644--- a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.unit.spec.ts+++ b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/utils.unit.spec.ts@@ -22,6 +22,7 @@ import {isSectionRoot,isSelectableItem,toggleItem,+ toggleItems,toggleSectionRoot,} from "./utils";@@ -253,6 +254,44 @@ describe("library-bulk-selection.utils", () => {});});+ describe("toggleItems", () => {+ it("leaves the selection unchanged when there is nothing to toggle", () => {+ const selected = [tableItem(1)];+ expect(toggleItems(selected, [])).toBe(selected);+ });++ it("selects every item, then deselects them on a second toggle", () => {+ const s1 = snippetItem(1);+ const c1 = subCollection(4, "snippets");++ const selected = toggleItems([], [s1, c1]);+ expect(ids(selected)).toEqual(["snippet:1", "collection:4"]);+ expect(toggleItems(selected, [s1, c1])).toEqual([]);+ });++ it("adds the missing items when only some are selected", () => {+ const d1 = dashboardItem(1);+ const d2 = dashboardItem(2);+ expect(ids(toggleItems([d1], [d1, d2]))).toEqual([+ "dashboard:1",+ "dashboard:2",+ ]);+ });++ it("keeps selected items that are not being toggled when deselecting", () => {+ const d1 = dashboardItem(1);+ const d2 = dashboardItem(2);+ const d3 = dashboardItem(3);+ expect(ids(toggleItems([d1, d2, d3], [d1, d2]))).toEqual(["dashboard:3"]);+ });++ it("replaces a selection from another section", () => {+ expect(+ ids(toggleItems([tableItem(1)], [actionItem(1), actionItem(2)])),+ ).toEqual(["action:1", "action:2"]);+ });+ });+describe("toggleSectionRoot", () => {it("selects all direct selectables, then deselects them", () => {const t1 = tableItem(1);diff --git a/frontend/src/metabase/data-studio/common/types.ts b/frontend/src/metabase/data-studio/common/types.tsindex 3e52bcc9418..aa099641749 100644--- a/frontend/src/metabase/data-studio/common/types.ts+++ b/frontend/src/metabase/data-studio/common/types.ts@@ -6,12 +6,7 @@ import type {Table,} from "metabase-types/api";-export type LibrarySectionType =- | "data"- | "metrics"- | "dashboards"- | "snippets"- | "actions";+export type LibrarySectionType = "data" | "metrics" | "snippets" | "actions";export type EmptyStateData = {model: "empty-state";diff --git a/frontend/src/metabase/data-studio/common/utils/build-collection-tree.ts b/frontend/src/metabase/data-studio/common/utils/build-collection-tree.tsnew file mode 100644index 00000000000..c9e70a41303--- /dev/null+++ b/frontend/src/metabase/data-studio/common/utils/build-collection-tree.ts@@ -0,0 +1,55 @@+import type { Collection, CollectionId } from "metabase-types/api";++import type { TreeItem } from "../types";++type CollectionTreeLeaf = {+ collection_id?: CollectionId | null;+};++/**+ * The folders directly under `parentId`, each with its own subtree, followed by the leaves directly under it. Pass+ * `null` for the top level.+ */+export function buildCollectionTreeChildren<Leaf extends CollectionTreeLeaf>(+ parentId: CollectionId | null,+ collections: Collection[],+ leaves: Leaf[],+ createLeafNode: (leaf: Leaf) => TreeItem,+): TreeItem[] {+ return [+ ...collections+ .filter((collection) => collection.parent_id === parentId)+ .map((child) =>+ buildCollectionTreeNode(child, collections, leaves, createLeafNode),+ ),+ ...leaves+ .filter((leaf) => leaf.collection_id === parentId)+ .map(createLeafNode),+ ];+}++/**+ * A folder row for `collection` with the folders and leaves under it as children, or no children when it holds none.+ */+export function buildCollectionTreeNode<Leaf extends CollectionTreeLeaf>(+ collection: Collection,+ collections: Collection[],+ leaves: Leaf[],+ createLeafNode: (leaf: Leaf) => TreeItem,+): TreeItem {+ const children = buildCollectionTreeChildren(+ collection.id,+ collections,+ leaves,+ createLeafNode,+ );++ return {+ id: `collection:${collection.id}`,+ name: collection.name,+ model: "collection",+ icon: "folder",+ data: { ...collection, model: "collection" },+ children: children.length > 0 ? children : undefined,+ };+}diff --git a/frontend/src/metabase/data-studio/common/utils/build-collection-tree.unit.spec.ts b/frontend/src/metabase/data-studio/common/utils/build-collection-tree.unit.spec.tsnew file mode 100644index 00000000000..75a33a73578--- /dev/null+++ b/frontend/src/metabase/data-studio/common/utils/build-collection-tree.unit.spec.ts@@ -0,0 +1,93 @@+import type { Collection, NativeQuerySnippet } from "metabase-types/api";+import {+ createMockCollection,+ createMockNativeQuerySnippet,+} from "metabase-types/api/mocks";++import type { TreeItem } from "../types";++import {+ buildCollectionTreeChildren,+ buildCollectionTreeNode,+} from "./build-collection-tree";++const createLeafNode = (snippet: NativeQuerySnippet): TreeItem => ({+ id: `snippet:${snippet.id}`,+ name: snippet.name,+ icon: "snippet",+ model: "snippet",+ data: { ...snippet, model: "snippet" },+});++const ids = (items: TreeItem[] = []): string[] => items.map((item) => item.id);++const TOP_FOLDER = createMockCollection({ id: 1, parent_id: null });+const NESTED_FOLDER = createMockCollection({ id: 2, parent_id: 1 });+const EMPTY_FOLDER = createMockCollection({ id: 3, parent_id: null });+const COLLECTIONS: Collection[] = [TOP_FOLDER, NESTED_FOLDER, EMPTY_FOLDER];++const TOP_SNIPPET = createMockNativeQuerySnippet({+ id: 10,+ collection_id: null,+});+const FOLDER_SNIPPET = createMockNativeQuerySnippet({+ id: 11,+ collection_id: 1,+});+const NESTED_SNIPPET = createMockNativeQuerySnippet({+ id: 12,+ collection_id: 2,+});+const SNIPPETS = [TOP_SNIPPET, FOLDER_SNIPPET, NESTED_SNIPPET];++describe("buildCollectionTreeChildren", () => {+ it("lists the folders before the leaves under a parent, with each folder's subtree", () => {+ const tree = buildCollectionTreeChildren(+ null,+ COLLECTIONS,+ SNIPPETS,+ createLeafNode,+ );++ expect(ids(tree)).toEqual(["collection:1", "collection:3", "snippet:10"]);+ expect(ids(tree[0].children)).toEqual(["collection:2", "snippet:11"]);+ expect(ids(tree[0].children?.[0].children)).toEqual(["snippet:12"]);+ });++ it("returns nothing for a parent with no folders or leaves", () => {+ expect(+ buildCollectionTreeChildren(3, COLLECTIONS, SNIPPETS, createLeafNode),+ ).toEqual([]);+ });+});++describe("buildCollectionTreeNode", () => {+ it("builds a folder row with the folders and leaves under it", () => {+ const node = buildCollectionTreeNode(+ NESTED_FOLDER,+ COLLECTIONS,+ SNIPPETS,+ createLeafNode,+ );++ expect(node).toEqual({+ id: "collection:2",+ name: NESTED_FOLDER.name,+ model: "collection",+ icon: "folder",+ data: { ...NESTED_FOLDER, model: "collection" },+ children: [createLeafNode(NESTED_SNIPPET)],+ });+ });++ it("leaves children undefined for an empty folder", () => {+ const node = buildCollectionTreeNode(+ EMPTY_FOLDER,+ COLLECTIONS,+ SNIPPETS,+ createLeafNode,+ );++ expect(node.children).toBeUndefined();+ });+});diff --git a/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.ts b/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.tsindex fbbeea126d6..8cee8e12ab2 100644--- a/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.ts+++ b/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.ts@@ -6,19 +6,14 @@ import type { CollectionId } from "metabase-types/api";import type { LibrarySectionType, TreeItem } from "../types";type EmptyStateConfig = {- sectionType: LibrarySectionType;description: string;actionLabel: string;- actionUrl?: string;};const getEmptyStateConfig = (sectionType: LibrarySectionType,-): Omit<EmptyStateConfig, "sectionType" | "actionUrl"> => {- const config: Record<- LibrarySectionType,- Omit<EmptyStateConfig, "sectionType" | "actionUrl">- > = {+): EmptyStateConfig => {+ const config: Record<LibrarySectionType, EmptyStateConfig> = {data: {description: t`Cleaned, pre-transformed data sources ready for exploring`,actionLabel: t`Publish a table`,@@ -27,10 +22,6 @@ const getEmptyStateConfig = (description: t`Standardized calculations with known dimensions`,actionLabel: t`New metric`,},- dashboards: {- description: t`Curated dashboards built on the semantic layer`,- actionLabel: t`Create a dashboard`,- },snippets: {description: t`Reusable bits of code that save your time`,actionLabel: t`New snippet`,@@ -59,7 +50,7 @@ export const createEmptyStateItem = (} else if (sectionType === "actions" && !hideAction) {actionUrl = Urls.newDataStudioAction();}- // "data" and "dashboards" sections open a modal, so no actionUrl+ // The "data" section opens a modal, so no actionUrlreturn {id: `empty-state:${sectionType}`,diff --git a/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.ts b/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.tsindex 0d65d8f55d7..d47b052fdb0 100644--- a/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.ts+++ b/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.ts@@ -3,7 +3,7 @@ import * as Urls from "metabase/urls";import type { TreeItem } from "../types";export const getTreeRowHref = (row: { original: TreeItem }): string | null => {- const { data, name } = row.original;+ const { data } = row.original;if (data.model === "empty-state" || data.model === "collection") {return null;@@ -22,7 +22,7 @@ export const getTreeRowHref = (row: { original: TreeItem }): string | null => {case "action":return Urls.dataStudioAction(data.id);case "dashboard":- return Urls.dashboard({ id: data.id, name });+ return Urls.dataStudioDashboard(data.id);default:return null;}diff --git a/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.unit.spec.ts b/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.unit.spec.tsindex c1ee1ce0d9d..6aed657514d 100644--- a/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.unit.spec.ts+++ b/frontend/src/metabase/data-studio/common/utils/get-tree-row-href.unit.spec.ts@@ -23,7 +23,7 @@ describe("getTreeRowHref", () => {["metric", "/data-studio/library/metrics/7"],["snippet", "/data-studio/snippets/7"],["action", "/data-studio/actions/7"],- ["dashboard", "/dashboard/7-sales"],+ ["dashboard", "/data-studio/dashboards/7"],])("links a %s row to %s", (model, expectedHref) => {expect(getTreeRowHref({ original: createLeafItem(model, 7) })).toBe(expectedHref,diff --git a/frontend/src/metabase/data-studio/common/utils/index.ts b/frontend/src/metabase/data-studio/common/utils/index.tsindex 91ea6741524..41f0ab7d4d6 100644--- a/frontend/src/metabase/data-studio/common/utils/index.ts+++ b/frontend/src/metabase/data-studio/common/utils/index.ts@@ -7,11 +7,16 @@ import type {TreeItem,} from "../types";+export {+ buildCollectionTreeChildren,+ buildCollectionTreeNode,+} from "./build-collection-tree";export { createEmptyStateItem } from "./create-empty-space-item";export { filterTreeByName } from "./filter-tree-by-name";export { getDatasetQueryPreviewUrl } from "./get-dataset-query-preview-url";export { getLibraryCollectionDisplayName } from "./get-library-collection-display-name";export { getTreeRowHref } from "./get-tree-row-href";+export { openNewCollectionModal } from "./open-new-collection-modal";export { getResultMetadata } from "metabase/common/data-studio/utils/get-result-metadata";// TODO Alex P 12/05/2025 Fix the endpoint to return sensible datadiff --git a/frontend/src/metabase/data-studio/common/utils/open-new-collection-modal.ts b/frontend/src/metabase/data-studio/common/utils/open-new-collection-modal.tsnew file mode 100644index 00000000000..c7edfeecd7b--- /dev/null+++ b/frontend/src/metabase/data-studio/common/utils/open-new-collection-modal.ts@@ -0,0 +1,25 @@+import type { EntityPickerOptions } from "metabase/common/components/Pickers";+import { setOpenModalWithProps } from "metabase/redux/ui";+import type { CollectionId, CollectionNamespace } from "metabase-types/api";++type NewCollectionModalOptions = {+ initialCollectionId: CollectionId | null;+ namespaces: CollectionNamespace[];+ pickerOptions: EntityPickerOptions;+};++/** The action that opens the New collection modal without the official-collection picker. */+export const openNewCollectionModal = ({+ initialCollectionId,+ namespaces,+ pickerOptions,+}: NewCollectionModalOptions) =>+ setOpenModalWithProps({+ id: "collection",+ props: {+ initialCollectionId,+ namespaces,+ pickerOptions,+ showAuthorityLevelPicker: false,+ },+ });diff --git a/frontend/src/metabase/data-studio/routes.tsx b/frontend/src/metabase/data-studio/routes.tsxindex 81cddbdef8d..28d07069f4f 100644--- a/frontend/src/metabase/data-studio/routes.tsx+++ b/frontend/src/metabase/data-studio/routes.tsx@@ -118,6 +118,11 @@ export function getDataStudioRoutes(IsAdmin: RouteComponent) {) : (<Route path="library" lazy={libraryUpsellPage} />)}+ {PLUGIN_LIBRARY.isEnabled ? (+ PLUGIN_LIBRARY.getDataStudioDashboardRoutes()+ ) : (+ <Route path="dashboards" lazy={libraryUpsellPage} />+ )}{PLUGIN_DEPENDENCIES.isEnabled ? (<Route path="dependencies" lazy={dependenciesSectionLayout}>{PLUGIN_DEPENDENCIES.getDataStudioDependencyRoutes()}diff --git a/frontend/src/metabase/data-studio/routes.unit.spec.tsx b/frontend/src/metabase/data-studio/routes.unit.spec.tsxindex 36a651b2271..4323b556b30 100644--- a/frontend/src/metabase/data-studio/routes.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/routes.unit.spec.tsx@@ -20,9 +20,9 @@ describe("data-studio routes", () => {it("resolves every page", async () => {const loaders = lazyLoaders(getDataStudioRoutes(Guard));- // Includes the transform, data model, glossary, settings, snippet and action- // routes, which this tree nests.- expect(loaders).toHaveLength(52);+ // Includes the transform, data model, glossary, settings, snippet, action+ // and dashboard routes, which this tree nests.+ expect(loaders).toHaveLength(53);for (const load of loaders) {expect((await load()).Component).toBeDefined();diff --git a/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/use-build-snippet-tree.ts b/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/use-build-snippet-tree.tsindex 174115a4998..8532eccc060 100644--- a/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/use-build-snippet-tree.ts+++ b/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/use-build-snippet-tree.ts@@ -1,15 +1,18 @@import { useMemo } from "react";import { useListCollectionsQuery, useListSnippetsQuery } from "metabase/api";+import { isRootCollection } from "metabase/common/collections/utils";import type { TreeItem } from "metabase/data-studio/common/types";import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";import { useSelector } from "metabase/redux";+import type { Collection } from "metabase-types/api";import { buildActiveSnippetTree, buildArchivedSnippetTree } from "./utils";export const useBuildSnippetTree = ({ archived = false } = {}): {isLoading: boolean;tree: TreeItem[];+ rootCollection?: Collection;error?: unknown;} => {const {@@ -52,6 +55,7 @@ export const useBuildSnippetTree = ({ archived = false } = {}): {return {isLoading: false,error,+ rootCollection: snippetCollections.find(isRootCollection),tree: archived? buildArchivedSnippetTree(snippetCollections, snippets): buildActiveSnippetTree(diff --git a/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/utils.ts b/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/utils.tsindex 2928de270ab..b73fe39ef75 100644--- a/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/utils.ts+++ b/frontend/src/metabase/data-studio/snippets/hooks/use-build-snippet-tree/utils.ts@@ -1,11 +1,13 @@-import { t } from "ttag";-import {coerceCollectionId,isRootCollection,} from "metabase/common/collections/utils";import type { TreeItem } from "metabase/data-studio/common/types";-import { createEmptyStateItem } from "metabase/data-studio/common/utils";+import {+ buildCollectionTreeChildren,+ buildCollectionTreeNode,+ createEmptyStateItem,+} from "metabase/data-studio/common/utils";import type { Collection, NativeQuerySnippet } from "metabase-types/api";function createSnippetNode(snippet: NativeQuerySnippet): TreeItem {@@ -19,65 +21,33 @@ function createSnippetNode(snippet: NativeQuerySnippet): TreeItem {};}-function buildSnippetCollectionNode(- collection: Collection,- allCollections: Collection[],- allSnippets: NativeQuerySnippet[],-): TreeItem {- const isRoot = isRootCollection(collection);- const parentIdToMatch = isRoot ? null : collection.id;-- const childCollections = allCollections.filter(- (c) => c.parent_id === parentIdToMatch,- );- const childSnippets = allSnippets.filter(- (s) => s.collection_id === parentIdToMatch,- );-- const children = [- ...childCollections.map((child) =>- buildSnippetCollectionNode(child, allCollections, allSnippets),- ),- ...childSnippets.map(createSnippetNode),- ];-- return {- id: `collection:${collection.id}`,- name: collection.name,- model: "collection",- icon: isRoot ? "snippet" : "folder",- data: { ...collection, model: "collection" },- children: children.length > 0 ? children : undefined,- };-}-+/**+ * The folders and snippets at the top of the snippets collection, an empty-state row when it holds none, or nothing+ * without a readable root.+ */export function buildActiveSnippetTree(snippetCollections: Collection[],snippets: NativeQuerySnippet[],canWriteSnippets: boolean,): TreeItem[] {- const collections = snippetCollections.filter((c) => !c.archived);- const activeSnippets = snippets.filter((s) => !s.archived);-- const rootCollection = collections.find(isRootCollection);- if (!rootCollection) {+ if (!snippetCollections.some(isRootCollection)) {return [];}- const nonRootCollections = collections.filter((c) => !isRootCollection(c));- const rootNode = buildSnippetCollectionNode(- rootCollection,- nonRootCollections,+ const collections = snippetCollections.filter(+ (c) => !c.archived && !isRootCollection(c),+ );+ const activeSnippets = snippets.filter((s) => !s.archived);+ const items = buildCollectionTreeChildren(+ null,+ collections,activeSnippets,+ createSnippetNode,);- // If the root has no children (no snippets or subfolders), add an empty state- const hasContent = activeSnippets.length > 0 || nonRootCollections.length > 0;- const children = hasContent- ? rootNode.children+ return items.length > 0+ ? items: [createEmptyStateItem("snippets", undefined, !canWriteSnippets)];-- return [{ ...rootNode, name: t`SQL snippets`, children }];}export function buildArchivedSnippetTree(@@ -93,10 +63,11 @@ export function buildArchivedSnippetTree(return [...archivedCollections.map((collection) =>- buildSnippetCollectionNode(+ buildCollectionTreeNode(collection,archivedCollections,archivedSnippets,+ createSnippetNode,),),...archivedSnippetsdiff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsx b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsxdeleted file mode 100644index ec86526ca5b..00000000000--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { t } from "ttag";--import type { CollectionRowModalState } from "metabase/common/collections/components/CollectionRowModal";-import { Link } from "metabase/common/components/Link";-import { getUserIsAdmin } from "metabase/current-user";-import { PLUGIN_REMOTE_SYNC, PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";-import { useSelector } from "metabase/redux";-import { ActionIcon, FixedSizeIcon, Menu, Tooltip } from "metabase/ui";-import { dataStudioArchivedSnippets } from "metabase/urls";-import type { Collection } from "metabase-types/api";--type RootSnippetsCollectionMenuProps = {- collection: Collection;- onOpenModal: (modal: CollectionRowModalState) => void;-};--export const RootSnippetsCollectionMenu = ({- collection,- onOpenModal,-}: RootSnippetsCollectionMenuProps) => {- const isAdmin = useSelector(getUserIsAdmin);- const remoteSyncReadOnly = useSelector(- PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,- );- const canChangePermissions =- PLUGIN_SNIPPET_FOLDERS.isEnabled && isAdmin && !remoteSyncReadOnly;-- const optionsLabel = t`Snippet collection options`;-- return (- <Menu position="bottom-end">- <Menu.Target>- <Tooltip- label={optionsLabel}- onClick={(e) => e.stopPropagation()}- openDelay={1000}- >- <ActionIcon aria-label={optionsLabel} size="md">- <FixedSizeIcon name="ellipsis" size={16} />- </ActionIcon>- </Tooltip>- </Menu.Target>- <Menu.Dropdown onClick={(e) => e.stopPropagation()}>- {canChangePermissions && (- <Menu.Item- leftSection={<FixedSizeIcon name="lock" />}- onClick={() => onOpenModal({ type: "permissions", collection })}- >- {t`Change permissions`}- </Menu.Item>- )}- <Menu.Item- component={Link}- leftSection={<FixedSizeIcon name="view_archive" />}- to={dataStudioArchivedSnippets()}- >- {t`View archived snippets`}- </Menu.Item>- </Menu.Dropdown>- </Menu>- );-};diff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.unit.spec.tsx b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.unit.spec.tsxdeleted file mode 100644index 1118bc5bfa4..00000000000--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.unit.spec.tsx+++ /dev/null@@ -1,192 +0,0 @@-import userEvent from "@testing-library/user-event";-import { useState } from "react";--import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";-import {- setupCollectionPermissionsGraphEndpoint,- setupCollectionsEndpoints,- setupGroupsEndpoint,-} from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import { createMockState } from "__support__/state/state";-import { renderWithProviders, screen, within } from "__support__/ui";-import {- CollectionRowModal,- type CollectionRowModalState,-} from "metabase/common/collections/components/CollectionRowModal";-import { reinitialize } from "metabase/plugins";-import { Route } from "metabase/router";-import { dataStudioArchivedSnippets } from "metabase/urls";-import type { Collection, EnterpriseSettings } from "metabase-types/api";-import {- createMockCollection,- createMockTokenFeatures,- createMockUser,-} from "metabase-types/api/mocks";--import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";--function RootSnippetsCollectionMenuWithModal({- collection,-}: {- collection: Collection;-}) {- const [modal, setModal] = useState<CollectionRowModalState>();- return (- <>- <RootSnippetsCollectionMenu- collection={collection}- onOpenModal={setModal}- />- <CollectionRowModal modal={modal} onClose={() => setModal(undefined)} />- </>- );-}--interface SetupOptions {- isEnterprise?: boolean;- isSuperuser?: boolean;- remoteSyncType?: EnterpriseSettings["remote-sync-type"];-}--const collection = createMockCollection({- id: "root",- name: "SQL Snippets",- namespace: "snippets",-});--const setup = ({- isEnterprise = true,- isSuperuser = true,- remoteSyncType,-}: SetupOptions = {}) => {- const state = createMockState({- settings: mockSettings({- "remote-sync-type": remoteSyncType,- "remote-sync-enabled": !!remoteSyncType,- "token-features": createMockTokenFeatures({- snippet_collections: isEnterprise,- remote_sync: !!remoteSyncType,- }),- }),- currentUser: createMockUser({ is_superuser: isSuperuser }),- });- if (isEnterprise) {- setupEnterpriseOnlyPlugin("snippets");- }- if (remoteSyncType) {- setupEnterpriseOnlyPlugin("remote_sync");- }- setupCollectionsEndpoints({ collections: [collection] });- setupGroupsEndpoint([]);- setupCollectionPermissionsGraphEndpoint({ revision: 1, groups: {} });-- return renderWithProviders(- <>- <Route- path="/"- element={- <RootSnippetsCollectionMenuWithModal collection={collection} />- }- />- <Route- path={dataStudioArchivedSnippets()}- element={<div data-testid="archived-snippets" />}- />- </>,- {- storeInitialState: state,- withRouter: true,- },- );-};--describe("RootSnippetsCollectionMenu", () => {- beforeEach(() => {- jest.clearAllMocks();- reinitialize();- });-- it("renders snippets options menu", () => {- setup();- expect(- screen.getByRole("button", { name: "Snippet collection options" }),- ).toBeInTheDocument();- });-- it("does not render 'change permissions' option if user is not a superuser", async () => {- setup({ isSuperuser: false });-- await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),- );- expect(- screen.queryByRole("menuitem", { name: /Change permissions/ }),- ).not.toBeInTheDocument();- });-- it("does not render 'change permissions' option without snippet folders", async () => {- setup({ isEnterprise: false });-- await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),- );- expect(- screen.queryByRole("menuitem", { name: /Change permissions/ }),- ).not.toBeInTheDocument();- expect(- screen.getByRole("menuitem", { name: /View archived snippets/ }),- ).toBeInTheDocument();- });-- it("does not render 'change permissions' option if remote sync is set to read-only", async () => {- setup({ remoteSyncType: "read-only" });-- await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),- );- expect(- screen.queryByRole("menuitem", { name: /Change permissions/ }),- ).not.toBeInTheDocument();- });-- describe("show permissions option", () => {- it("is rendered on menu click", async () => {- setup();- await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),- );- expect(- screen.getByRole("menuitem", { name: /Change permissions/ }),- ).toBeInTheDocument();- });-- it("shows permissions modal on click", async () => {- setup();- await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),- );- await userEvent.click(- screen.getByRole("menuitem", { name: /Change permissions/ }),- );- expect(- await within(screen.getByRole("dialog")).findByRole("heading", {- name: /Permissions for SQL Snippets/,- }),- ).toBeInTheDocument();- });- });-- describe("view archived snippets option", () => {- it("navigates to archived snippets page", async () => {- const { router } = setup();- await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),- );- await userEvent.click(- screen.getByRole("menuitem", { name: /View archived snippets/ }),- );- expect(router?.location?.pathname).toMatch(/\/snippets\/archived/);- });- });-});diff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/index.ts b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/index.tsdeleted file mode 100644index 9ee528de755..00000000000--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/index.ts+++ /dev/null@@ -1 +0,0 @@-export { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";diff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsx b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsxindex b40ad496377..422a297d966 100644--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsx+++ b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsx@@ -14,17 +14,15 @@ import type { TreeItem } from "metabase/data-studio/common/types";import {filterTreeByName,isCollectionData,+ openNewCollectionModal,} from "metabase/data-studio/common/utils";import { PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";import { useDispatch, useSelector } from "metabase/redux";-import { setOpenModalWithProps } from "metabase/redux/ui";import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";import { useBuildSnippetTree } from "../../hooks/use-build-snippet-tree";-import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";-const SNIPPET_COLLECTION_PICKER_OPTIONS = {hasLibrary: false,hasRootCollection: true,@@ -39,7 +37,7 @@ export function SnippetListPage() {const [searchQuery, setSearchQuery] = useState("");const [collectionModal, setCollectionModal] =useState<CollectionRowModalState>();- const { tree, isLoading, error } = useBuildSnippetTree();+ const { tree, rootCollection, isLoading, error } = useBuildSnippetTree();useErrorHandling(error);const isSearchActive = searchQuery.trim().length > 0;@@ -47,10 +45,6 @@ export function SnippetListPage() {() => (isSearchActive ? filterTreeByName(tree, searchQuery) : tree),[isSearchActive, tree, searchQuery],);- const defaultExpandedIds = useMemo(- () => tree.slice(0, 1).map((node) => node.id),- [tree],- );const renderRowMenu = useCallback((item: TreeItem) => (<SnippetRowMenu item={item} onOpenModal={setCollectionModal} />@@ -66,8 +60,21 @@ export function SnippetListPage() {isSearchActive={isSearchActive}searchQuery={searchQuery}emptyMessage={t`No snippets yet`}- defaultExpandedIds={defaultExpandedIds}createMenu={<SnippetsCreateMenu />}+ pageMenu={{+ label: t`Snippet options`,+ actions: [+ {+ label: t`View archived snippets`,+ icon: "view_archive",+ to: Urls.dataStudioArchivedSnippets(),+ },+ ],+ permissionsCollection: PLUGIN_SNIPPET_FOLDERS.isEnabled+ ? rootCollection+ : undefined,+ onOpenModal: setCollectionModal,+ }}renderRowMenu={renderRowMenu}onSearchQueryChange={setSearchQuery}>@@ -88,11 +95,6 @@ function SnippetRowMenu({ item: { data }, onOpenModal }: SnippetRowMenuProps) {if (!isCollectionData(data)) {return null;}- if (data.id === "root") {- return (- <RootSnippetsCollectionMenu collection={data} onOpenModal={onOpenModal} />- );- }return <CollectionRowMenu collection={data} onOpenModal={onOpenModal} />;}@@ -104,14 +106,10 @@ function SnippetsCreateMenu() {const handleNewFolderClick = useCallback(() => {dispatch(- setOpenModalWithProps({- id: "collection",- props: {- initialCollectionId: null,- namespaces: ["snippets"],- pickerOptions: SNIPPET_COLLECTION_PICKER_OPTIONS,- showAuthorityLevelPicker: false,- },+ openNewCollectionModal({+ initialCollectionId: null,+ namespaces: ["snippets"],+ pickerOptions: SNIPPET_COLLECTION_PICKER_OPTIONS,}),);}, [dispatch]);diff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.unit.spec.tsx b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.unit.spec.tsxindex c79b441dd28..db863905658 100644--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.unit.spec.tsx@@ -13,10 +13,12 @@ import {mockGetBoundingClientRect,renderWithProviders,screen,+ waitFor,within,} from "__support__/ui";import { reinitialize } from "metabase/plugins";import { Route } from "metabase/router";+import { dataStudioArchivedSnippets } from "metabase/urls";import type { User } from "metabase-types/api";import {createMockCollection,@@ -87,13 +89,13 @@ describe("SnippetListPage", () => {mockGetBoundingClientRect({ width: 1000, height: 1000 });});- it("lists snippets under the SQL snippets root", async () => {+ it("lists the top-level folders and snippets without a root row", async () => {setup({});const page = await screen.findByTestId("library-page");expect(await within(page).findByText("Orders filter")).toBeInTheDocument();- expect(within(page).getByText("SQL snippets")).toBeInTheDocument();expect(within(page).getByText("Revenue folder")).toBeInTheDocument();+ expect(within(page).queryByText("SQL snippets")).not.toBeInTheDocument();});it("filters snippets by name, including ones in folders", async () => {@@ -106,6 +108,35 @@ describe("SnippetListPage", () => {expect(screen.queryByText("Orders filter")).not.toBeInTheDocument();});+ it("clears a selected nested snippet when Select all is clicked twice", async () => {+ setup({});++ await userEvent.click(await screen.findByText("Revenue folder"));+ const nestedRow = await screen.findByRole("row", { name: /Revenue sum/ });+ await userEvent.click(+ within(nestedRow).getByRole("checkbox", { name: "Select row" }),+ );+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();++ const selectAll = screen.getByRole("checkbox", { name: "Select all" });+ await userEvent.click(selectAll);+ expect(await screen.findByText("2 items selected")).toBeInTheDocument();+ expect(selectAll).toBeChecked();++ await userEvent.click(selectAll);+ await waitFor(() =>+ expect(screen.queryByText(/selected$/)).not.toBeInTheDocument(),+ );+ expect(selectAll).not.toBeChecked();+ expect(selectAll).not.toBePartiallyChecked();+ expect(+ within(screen.getByRole("row", { name: /Revenue sum/ })).getByRole(+ "checkbox",+ { name: "Select row" },+ ),+ ).not.toBeChecked();+ });+it("offers only new snippets without snippet folders", async () => {setup({});@@ -116,6 +147,20 @@ describe("SnippetListPage", () => {).toEqual(["Snippet"]);});+ it("places the page menu after the New button", async () => {+ setup({});++ const newButton = await screen.findByRole("button", { name: /New/ });+ const pageMenuButton = screen.getByRole("button", {+ name: "Snippet options",+ });++ expect(+ newButton.compareDocumentPosition(pageMenuButton) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });+it("offers new snippets and folders with snippet folders", async () => {setup({ isEnterprise: true });@@ -135,7 +180,7 @@ describe("SnippetListPage", () => {).not.toBeInTheDocument();});- it("keeps the root row expanded when clicking inside the permissions modal it opened", async () => {+ it("opens the permissions of the snippets collection from the page menu", async () => {setupGroupsEndpoint([]);setupCollectionPermissionsGraphEndpoint({ revision: 1, groups: {} });setup({@@ -143,31 +188,44 @@ describe("SnippetListPage", () => {user: { ...NATIVE_WRITE_USER, is_superuser: true },});- expect(await screen.findByText("Orders filter")).toBeInTheDocument();await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),+ await screen.findByRole("button", { name: "Snippet options" }),);await userEvent.click(screen.getByRole("menuitem", { name: /Change permissions/ }),);- await userEvent.click(++ expect(await within(screen.getByRole("dialog")).findByRole("heading", {- name: /Permissions for/,+ name: "Permissions for Root",}),+ ).toBeInTheDocument();+ });++ it("offers only archived snippets without snippet folders", async () => {+ setup({ user: { ...NATIVE_WRITE_USER, is_superuser: true } });++ await userEvent.click(+ await screen.findByRole("button", { name: "Snippet options" }),);- expect(screen.getByText("Orders filter")).toBeInTheDocument();+ expect(+ screen.getAllByRole("menuitem").map((item) => item.textContent),+ ).toEqual(["View archived snippets"]);+ expect(+ screen.getByRole("menuitem", { name: /View archived snippets/ }),+ ).toHaveAttribute("href", dataStudioArchivedSnippets());});- it("keeps the root row expanded when clicking inside the root options menu", async () => {- setup({});+ it("does not offer to change permissions to non-admins", async () => {+ setup({ isEnterprise: true });- expect(await screen.findByText("Orders filter")).toBeInTheDocument();await userEvent.click(- screen.getByRole("button", { name: "Snippet collection options" }),+ await screen.findByRole("button", { name: "Snippet options" }),);- await userEvent.click(await screen.findByRole("menu"));- expect(screen.getByText("Orders filter")).toBeInTheDocument();+ expect(+ screen.queryByRole("menuitem", { name: /Change permissions/ }),+ ).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/notifications/pulse/subscription-editing.ts b/frontend/src/metabase/notifications/pulse/subscription-editing.tsnew file mode 100644index 00000000000..dcea2367008--- /dev/null+++ b/frontend/src/metabase/notifications/pulse/subscription-editing.ts@@ -0,0 +1,48 @@+import { match } from "ts-pattern";+import { t } from "ttag";++import type {+ Channel,+ ChannelApiResponse,+ DashboardSubscription,+} from "metabase-types/api";++/**+ * Why the dashboard's subscriptions sidebar can't open this channel's edit+ * form, or `null` when it can. The sidebar has an edit form for email and+ * Slack, and opens it whenever `form_input` lists the channel type, set up or+ * not, so a subscription can still be changed or deleted after its channel+ * stops working. It has no edit form for webhooks.+ */+export function getSubscriptionEditUnavailableReason(+ { channel_type }: Pick<Channel, "channel_type">,+ channelInfo: ChannelApiResponse,+): string | null {+ const hasChannelSpec = channelInfo.channels[channel_type] != null;+ return match(channel_type)+ .with("email", () =>+ hasChannelSpec ? null : t`You can't edit email subscriptions`,+ )+ .with("slack", () =>+ hasChannelSpec ? null : t`You can't edit Slack subscriptions`,+ )+ .with(+ "http",+ () => t`Webhook subscriptions can't be edited on the dashboard`,+ )+ .exhaustive();+}++/**+ * The channel the dashboard edits a subscription through, its first, or+ * `null` when it has none or the sidebar can't edit it.+ */+export function getEditableSubscriptionChannel(+ { channels: [channel] }: Pick<DashboardSubscription, "channels">,+ channelInfo: ChannelApiResponse,+): Channel | null {+ return channel != null &&+ getSubscriptionEditUnavailableReason(channel, channelInfo) == null+ ? channel+ : null;+}diff --git a/frontend/src/metabase/notifications/pulse/subscription-editing.unit.spec.ts b/frontend/src/metabase/notifications/pulse/subscription-editing.unit.spec.tsnew file mode 100644index 00000000000..6cd9b73eb17--- /dev/null+++ b/frontend/src/metabase/notifications/pulse/subscription-editing.unit.spec.ts@@ -0,0 +1,117 @@+import type { ChannelApiResponse, ChannelSpec } from "metabase-types/api";+import {+ createMockChannel,+ createMockDashboardSubscription,+} from "metabase-types/api/mocks";++import {+ getEditableSubscriptionChannel,+ getSubscriptionEditUnavailableReason,+} from "./subscription-editing";++const createChannelSpec = (opts: Partial<ChannelSpec>): ChannelSpec => ({+ type: "email",+ name: "Email",+ schedules: ["hourly", "daily", "weekly", "monthly"],+ schedule_type: "hourly",+ allows_recipients: true,+ configured: true,+ ...opts,+});++const CONFIGURED_CHANNELS: ChannelApiResponse = {+ channels: {+ email: { ...createChannelSpec({ type: "email" }), recipients: ["user"] },+ slack: { ...createChannelSpec({ type: "slack" }), fields: [] },+ http: createChannelSpec({ type: "http" }),+ },+};++const UNCONFIGURED_CHANNELS: ChannelApiResponse = {+ channels: {+ email: {+ ...createChannelSpec({ type: "email", configured: false }),+ recipients: ["user"],+ },+ slack: {+ ...createChannelSpec({ type: "slack", configured: false }),+ fields: [],+ },+ },+};++describe("getSubscriptionEditUnavailableReason", () => {+ it.each([CONFIGURED_CHANNELS, UNCONFIGURED_CHANNELS])(+ "allows editing an email or Slack channel the form input lists, set up or not",+ (channelInfo) => {+ expect(+ getSubscriptionEditUnavailableReason(+ { channel_type: "email" },+ channelInfo,+ ),+ ).toBeNull();+ expect(+ getSubscriptionEditUnavailableReason(+ { channel_type: "slack" },+ channelInfo,+ ),+ ).toBeNull();+ },+ );++ it("explains that a channel the form input leaves out can't be edited", () => {+ expect(+ getSubscriptionEditUnavailableReason(+ { channel_type: "email" },+ { channels: {} },+ ),+ ).toBe("You can't edit email subscriptions");+ expect(+ getSubscriptionEditUnavailableReason(+ { channel_type: "slack" },+ { channels: {} },+ ),+ ).toBe("You can't edit Slack subscriptions");+ });++ it("never allows editing a webhook, even when it is configured", () => {+ expect(+ getSubscriptionEditUnavailableReason(+ { channel_type: "http" },+ CONFIGURED_CHANNELS,+ ),+ ).toBe("Webhook subscriptions can't be edited on the dashboard");+ });+});++describe("getEditableSubscriptionChannel", () => {+ it("returns the first channel when the dashboard can edit it", () => {+ const channel = createMockChannel({ channel_type: "slack" });+ expect(+ getEditableSubscriptionChannel(+ createMockDashboardSubscription({ channels: [channel] }),+ CONFIGURED_CHANNELS,+ ),+ ).toBe(channel);+ });++ it("returns null when the sidebar can't edit the first channel", () => {+ expect(+ getEditableSubscriptionChannel(+ createMockDashboardSubscription({+ channels: [createMockChannel({ channel_type: "http" })],+ }),+ CONFIGURED_CHANNELS,+ ),+ ).toBeNull();+ });++ it("returns null for a subscription without a channel", () => {+ expect(+ getEditableSubscriptionChannel(+ createMockDashboardSubscription({ channels: [] }),+ CONFIGURED_CHANNELS,+ ),+ ).toBeNull();+ });+});diff --git a/frontend/src/metabase/notifications/pulse/subscription-formatting.ts b/frontend/src/metabase/notifications/pulse/subscription-formatting.tsnew file mode 100644index 00000000000..e0af2654003--- /dev/null+++ b/frontend/src/metabase/notifications/pulse/subscription-formatting.ts@@ -0,0 +1,358 @@+import { P, match } from "ts-pattern";+import { c, msgid, ngettext, t } from "ttag";+import _ from "underscore";++import { formatDateValue } from "metabase/parameters/utils/date-formatting";+import { renderNumberOfSelections } from "metabase/parameters/utils/formatting";+import { getActivePulseParameters } from "metabase/pulse";+import {+ deserializeBooleanParameterValue,+ deserializeNumberParameterValue,+ deserializeStringParameterValue,+ deserializeTemporalUnitParameterValue,+} from "metabase/querying/parameters/utils/parsing";+import { conjunct } from "metabase/utils/formatting";+import MetabaseSettings from "metabase/utils/settings";+import { formatFrame } from "metabase/utils/time-dayjs";+import { isNotNull } from "metabase/utils/types";+import {+ formatDateTimeWithUnit,+ formatTimeWithUnit,+} from "metabase/value-formatting";+import * as Lib from "metabase-lib";+import { getParameterType } from "metabase-lib/v1/parameters/utils/parameter-type";+import type {+ Channel,+ ChannelRecipient,+ DashboardSubscription,+ Parameter,+ ScheduleDayType,+ ScheduleFrameType,+} from "metabase-types/api";+import { isUserRecipient } from "metabase-types/guards";++type ChannelSchedule = Pick<+ Channel,+ "schedule_type" | "schedule_day" | "schedule_frame" | "schedule_hour"+>;++/**+ * A schedule with the fields its type needs. One that misses any is `unset`:+ * the API never saves such a schedule, so there is no send time to show.+ */+type SubscriptionSchedule =+ | { type: "hourly" }+ | { type: "daily"; hour: number }+ | { type: "weekly"; day: ScheduleDayType; hour: number }+ | {+ type: "monthly";+ frame: ScheduleFrameType;+ day: ScheduleDayType | null;+ hour: number;+ }+ | { type: "unset" };++type SetSubscriptionSchedule = Exclude<SubscriptionSchedule, { type: "unset" }>;++function getSubscriptionSchedule({+ schedule_type,+ schedule_day,+ schedule_frame,+ schedule_hour,+}: ChannelSchedule): SubscriptionSchedule {+ return match({ schedule_type, schedule_day, schedule_frame, schedule_hour })+ .returnType<SubscriptionSchedule>()+ .with({ schedule_type: "hourly" }, () => ({ type: "hourly" }))+ .with(+ { schedule_type: "daily", schedule_hour: P.number },+ ({ schedule_hour }) => ({ type: "daily", hour: schedule_hour }),+ )+ .with(+ {+ schedule_type: "weekly",+ schedule_day: P.nonNullable,+ schedule_hour: P.number,+ },+ ({ schedule_day, schedule_hour }) => ({+ type: "weekly",+ day: schedule_day,+ hour: schedule_hour,+ }),+ )+ .with(+ {+ schedule_type: "monthly",+ schedule_frame: P.nonNullable,+ schedule_hour: P.number,+ },+ ({ schedule_day, schedule_frame, schedule_hour }) => ({+ type: "monthly",+ frame: schedule_frame,+ day: schedule_day ?? null,+ hour: schedule_hour,+ }),+ )+ .otherwise(() => ({ type: "unset" }));+}++// The instance's time format settings decide between 12- and 24-hour times+function formatHour(hour: number): string {+ return formatTimeWithUnit(+ hour,+ "hour-of-day",+ MetabaseSettings.formattingOptions(),+ );+}++function formatDayOfWeek(day: ScheduleDayType) {+ return formatDateTimeWithUnit(+ day,+ "day-of-week",+ MetabaseSettings.formattingOptions(),+ );+}++const WEEKLY_SCHEDULES: Record<ScheduleDayType, (hour: string) => string> = {+ sun: (hour) => t`Sundays at ${hour}`,+ mon: (hour) => t`Mondays at ${hour}`,+ tue: (hour) => t`Tuesdays at ${hour}`,+ wed: (hour) => t`Wednesdays at ${hour}`,+ thu: (hour) => t`Thursdays at ${hour}`,+ fri: (hour) => t`Fridays at ${hour}`,+ sat: (hour) => t`Saturdays at ${hour}`,+};++/** When a subscription sends, as a title, like "Daily at 8:00 AM". */+export function formatSubscriptionSchedule(channel: ChannelSchedule): string {+ return match(getSubscriptionSchedule(channel))+ .with({ type: "hourly" }, () => t`Hourly`)+ .with({ type: "daily" }, ({ hour }) => t`Daily at ${formatHour(hour)}`)+ .with({ type: "weekly" }, ({ day, hour }) =>+ WEEKLY_SCHEDULES[day](formatHour(hour)),+ )+ .with({ type: "monthly", day: P.nullish }, ({ frame, hour }) => {+ const frameText = formatFrame(frame);+ const hourText = formatHour(hour);+ return t`Monthly on the ${frameText} calendar day at ${hourText}`;+ })+ .with({ type: "monthly", day: P.nonNullable }, ({ frame, day, hour }) => {+ const frameText = formatFrame(frame);+ const dayText = formatDayOfWeek(day);+ const hourText = formatHour(hour);+ return t`Monthly on the ${frameText} ${dayText} at ${hourText}`;+ })+ .with({ type: "unset" }, () => t`Schedule not set`)+ .exhaustive();+}++/**+ * How and when a subscription sends, like "Emailed daily at 8:00 AM" or+ * "Sent to #sales hourly".+ */+export function formatSubscriptionDelivery(+ channel: ChannelSchedule & Pick<Channel, "channel_type" | "details">,+): string {+ const schedule = getSubscriptionSchedule(channel);+ if (schedule.type === "unset") {+ return t`Schedule not set`;+ }+ const when = formatScheduleInSentence(schedule);+ const slackChannel = channel.details?.channel;+ return match(channel.channel_type)+ .with(+ "email",+ () =>+ c("{0} is when a subscription sends, like 'daily at 8:00 AM'")+ .t`Emailed ${when}`,+ )+ .with("slack", () =>+ slackChannel+ ? c(+ "{0} is a Slack channel, and {1} is when a subscription sends, like 'daily at 8:00 AM'",+ ).t`Sent to ${slackChannel} ${when}`+ : c("{0} is when a subscription sends, like 'daily at 8:00 AM'")+ .t`Sent ${when}`,+ )+ .with(+ "http",+ () =>+ c("{0} is when a subscription sends, like 'daily at 8:00 AM'")+ .t`Sent ${when}`,+ )+ .exhaustive();+}++function formatScheduleInSentence(schedule: SetSubscriptionSchedule): string {+ return match(schedule)+ .with({ type: "hourly" }, () => t`hourly`)+ .with({ type: "daily" }, ({ hour }) => {+ const hourText = formatHour(hour);+ return t`daily at ${hourText}`;+ })+ .with({ type: "weekly" }, ({ day, hour }) => {+ const dayText = formatDayOfWeek(day);+ const hourText = formatHour(hour);+ return c("{0} is a day of the week, and {1} is a time of day")+ .t`${dayText} at ${hourText}`;+ })+ .with({ type: "monthly", day: P.nullish }, ({ frame, hour }) => {+ const frameText = formatFrame(frame);+ const hourText = formatHour(hour);+ return t`monthly on the ${frameText} calendar day at ${hourText}`;+ })+ .with({ type: "monthly", day: P.nonNullable }, ({ frame, day, hour }) => {+ const frameText = formatFrame(frame);+ const dayText = formatDayOfWeek(day);+ const hourText = formatHour(hour);+ return t`monthly on the ${frameText} ${dayText} at ${hourText}`;+ })+ .exhaustive();+}++export type SubscriptionRecipient =+ | { type: "user"; name: string; email: string }+ | { type: "external"; email: string };++/**+ * A channel's recipients, each address once. An address saved both as a user+ * and as a plain email is listed as the user.+ */+export function getChannelRecipients(+ channel: Pick<Channel, "recipients">,+): SubscriptionRecipient[] {+ const recipients = (channel.recipients ?? []).map(getRecipient);+ const userEmails = new Set(+ recipients+ .filter((recipient) => recipient.type === "user")+ .map((recipient) => recipient.email),+ );+ // /api/pulse lists an address twice when it was saved both as a user and as a plain email+ const withoutShadowedExternals = recipients.filter(+ (recipient) =>+ recipient.type === "user" || !userEmails.has(recipient.email),+ );+ return _.uniq(+ withoutShadowedExternals,+ false,+ (recipient) => recipient.email,+ );+}++function getRecipient(recipient: ChannelRecipient): SubscriptionRecipient {+ return isUserRecipient(recipient)+ ? {+ type: "user",+ name: getRecipientName(recipient),+ email: recipient.email,+ }+ : { type: "external", email: recipient.email };+}++/**+ * The first email recipient and how many more there are, counted as+ * `getChannelRecipients` lists them, or an empty string when there are none.+ */+export function buildRecipientText({+ channels: [firstChannel],+}: Pick<DashboardSubscription, "channels">): string {+ if (firstChannel?.channel_type !== "email") {+ return "";+ }++ const [firstRecipient, ...otherRecipients] =+ getChannelRecipients(firstChannel);+ if (firstRecipient == null) {+ return "";+ }++ const firstRecipientText =+ firstRecipient.type === "user" ? firstRecipient.name : firstRecipient.email;+ const otherCount = otherRecipients.length;+ return otherCount === 0+ ? firstRecipientText+ : ngettext(+ msgid`${firstRecipientText} and ${otherCount} other`,+ `${firstRecipientText} and ${otherCount} others`,+ otherCount,+ );+}++/** A Metabase user's name, or the address of a recipient outside Metabase. */+export function getRecipientName(recipient: ChannelRecipient): string {+ return isUserRecipient(recipient)+ ? recipient.common_name || recipient.email+ : recipient.email;+}++/**+ * A filter's values deserialized by its parameter type and shown as a filter+ * widget shows them. Empty when none of them parses.+ */+function getFilterValues(parameter: Parameter): string[] {+ const { value } = parameter;+ return match(getParameterType(parameter))+ .returnType<string[]>()+ .with("date", () => {+ const dateText = formatDateValue(parameter, value);+ return dateText != null ? [dateText] : [];+ })+ .with("temporal-unit", () => {+ const unit = deserializeTemporalUnitParameterValue(value);+ return unit != null ? [Lib.describeTemporalUnit(unit)] : [];+ })+ .with("number", () =>+ deserializeNumberParameterValue(parameter.type, value)+ .filter(isNotNull)+ .map(String),+ )+ .with("boolean", () => deserializeBooleanParameterValue(value).map(String))+ .otherwise(() => deserializeStringParameterValue(value));+}++/**+ * The subscription's active filters, without any whose value doesn't parse,+ * as there is no value to show for it.+ */+export function getActiveFilters(+ pulse: DashboardSubscription,+ parameters: Parameter[],+): Parameter[] {+ return getActivePulseParameters(pulse, parameters).filter(+ (parameter) => getFilterValues(parameter).length > 0,+ );+}++/** A filter with every value it sends, like "State: CA and NY". */+export function formatFilter(parameter: Parameter): string {+ return `${parameter.name}: ${conjunct(getFilterValues(parameter), t`and`)}`;+}++/**+ * The first active filter, with a multi-value one counted rather than listed,+ * and how many other filters there are, or an empty string when none is active.+ */+export function buildFilterText(+ pulse: DashboardSubscription,+ parameters: Parameter[],+): string {+ const activeParameters = getActiveFilters(pulse, parameters);++ if (_.isEmpty(activeParameters)) {+ return "";+ }++ const [firstParameter, ...otherParameters] = activeParameters;+ const firstValueCount = getFilterValues(firstParameter).length;+ const firstFilterText =+ firstValueCount > 1+ ? `${firstParameter.name}: ${renderNumberOfSelections(firstValueCount)}`+ : formatFilter(firstParameter);++ return _.isEmpty(otherParameters)+ ? firstFilterText+ : `${firstFilterText} ${ngettext(+ msgid`and ${otherParameters.length} more filter`,+ `and ${otherParameters.length} more filters`,+ otherParameters.length,+ )}`;+}diff --git a/frontend/src/metabase/notifications/pulse/subscription-formatting.unit.spec.ts b/frontend/src/metabase/notifications/pulse/subscription-formatting.unit.spec.tsnew file mode 100644index 00000000000..9d3a46ea952--- /dev/null+++ b/frontend/src/metabase/notifications/pulse/subscription-formatting.unit.spec.ts@@ -0,0 +1,460 @@+import { mockSettings } from "__support__/settings";+import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";+import type { Channel, ParameterValueOrArray } from "metabase-types/api";+import {+ createMockChannel,+ createMockDashboardSubscription,+ createMockParameter,+ createMockUser,+} from "metabase-types/api/mocks";++import {+ buildFilterText,+ buildRecipientText,+ formatFilter,+ formatSubscriptionDelivery,+ formatSubscriptionSchedule,+ getActiveFilters,+ getChannelRecipients,+ getRecipientName,+} from "./subscription-formatting";++beforeEach(() => {+ jest.useFakeTimers({ now: new Date(2024, 5, 1) });+});++afterEach(() => {+ jest.useRealTimers();+});++describe("buildFilterText", () => {+ const stateParameter = createMockUiParameter({+ id: "1",+ name: "State",+ slug: "state",+ type: "string/=",+ });++ const buildPulse = (value: ParameterValueOrArray) =>+ createMockDashboardSubscription({+ parameters: [createMockParameter({ id: "1", value })],+ });++ it("returns an empty string when no parameters have values", () => {+ expect(+ buildFilterText(createMockDashboardSubscription(), [stateParameter]),+ ).toBe("");+ });++ it("renders a single value", () => {+ expect(buildFilterText(buildPulse("CA"), [stateParameter])).toBe(+ "State: CA",+ );+ });++ it("renders a single-element array value", () => {+ expect(buildFilterText(buildPulse(["CA"]), [stateParameter])).toBe(+ "State: CA",+ );+ });++ it("renders a numeric value", () => {+ expect(buildFilterText(buildPulse(42), [stateParameter])).toBe("State: 42");+ });++ it("summarizes multi-value selections", () => {+ expect(buildFilterText(buildPulse(["CA", "NY"]), [stateParameter])).toBe(+ "State: 2 selections",+ );+ });++ it("omits a filter whose only entries are nullish", () => {+ expect(buildFilterText(buildPulse([null]), [stateParameter])).toBe("");+ });++ it("mentions the number of additional filters", () => {+ const cityParameter = createMockUiParameter({+ id: "2",+ name: "City",+ slug: "city",+ type: "string/=",+ });+ const pulse = createMockDashboardSubscription({+ parameters: [+ createMockParameter({ id: "1", value: "CA" }),+ createMockParameter({ id: "2", value: "SF" }),+ ],+ });+ expect(buildFilterText(pulse, [stateParameter, cityParameter])).toBe(+ "State: CA and 1 more filter",+ );+ });++ it("formats date parameter values", () => {+ const dateParameter = createMockUiParameter({+ id: "3",+ name: "Created At",+ slug: "created_at",+ type: "date/single",+ });+ const pulse = createMockDashboardSubscription({+ parameters: [createMockParameter({ id: "3", value: "2024-01-15" })],+ });+ expect(buildFilterText(pulse, [dateParameter])).toBe(+ "Created At: January 15, 2024",+ );+ });++ it("omits a date filter whose value doesn't parse, and doesn't count it", () => {+ const dateParameter = createMockUiParameter({+ id: "3",+ name: "Created At",+ slug: "created_at",+ type: "date/single",+ });+ const pulse = createMockDashboardSubscription({+ parameters: [+ createMockParameter({ id: "3", value: "not a date" }),+ createMockParameter({ id: "1", value: "CA" }),+ ],+ });+ expect(buildFilterText(pulse, [dateParameter, stateParameter])).toBe(+ "State: CA",+ );+ });+});++describe("getActiveFilters", () => {+ it("leaves out a date filter whose value doesn't parse", () => {+ const dateParameter = createMockUiParameter({+ id: "3",+ name: "Created At",+ type: "date/single",+ });+ const stateParameter = createMockUiParameter({+ id: "1",+ name: "State",+ type: "string/=",+ });+ const pulse = createMockDashboardSubscription({+ parameters: [+ createMockParameter({ id: "3", value: "not a date" }),+ createMockParameter({ id: "1", value: "CA" }),+ ],+ });+ expect(+ getActiveFilters(pulse, [dateParameter, stateParameter]).map(+ (parameter) => parameter.name,+ ),+ ).toEqual(["State"]);+ });+});++describe("formatFilter", () => {+ it("lists every value of a filter", () => {+ expect(+ formatFilter(+ createMockParameter({ name: "State", value: ["CA", "NY", "WA"] }),+ ),+ ).toBe("State: CA, NY, and WA");+ });++ it("formats date values", () => {+ expect(+ formatFilter(+ createMockParameter({+ name: "Created At",+ type: "date/single",+ value: "2024-01-15",+ }),+ ),+ ).toBe("Created At: January 15, 2024");+ });++ it("formats relative date values", () => {+ expect(+ formatFilter(+ createMockParameter({+ name: "Created At",+ type: "date/relative",+ value: "past30days",+ }),+ ),+ ).toBe("Created At: Previous 30 days");+ });++ it("describes a time grouping value", () => {+ expect(+ formatFilter(+ createMockParameter({+ name: "Group by",+ type: "temporal-unit",+ value: "month",+ }),+ ),+ ).toBe("Group by: Month");+ });+});++describe("formatSubscriptionSchedule", () => {+ it("formats hourly and daily schedules", () => {+ expect(+ formatSubscriptionSchedule(+ createMockChannel({ schedule_type: "hourly" }),+ ),+ ).toBe("Hourly");+ expect(+ formatSubscriptionSchedule(+ createMockChannel({ schedule_type: "daily", schedule_hour: 8 }),+ ),+ ).toBe("Daily at 8:00 AM");+ });++ it("formats a weekly schedule with the day of the week", () => {+ expect(+ formatSubscriptionSchedule(+ createMockChannel({+ schedule_type: "weekly",+ schedule_day: "mon",+ schedule_hour: 9,+ }),+ ),+ ).toBe("Mondays at 9:00 AM");+ });++ it("formats a monthly schedule with the frame and day", () => {+ expect(+ formatSubscriptionSchedule(+ createMockChannel({+ schedule_type: "monthly",+ schedule_frame: "first",+ schedule_day: "mon",+ schedule_hour: 8,+ }),+ ),+ ).toBe("Monthly on the first Monday at 8:00 AM");+ expect(+ formatSubscriptionSchedule(+ createMockChannel({+ schedule_type: "monthly",+ schedule_frame: "last",+ schedule_hour: 20,+ }),+ ),+ ).toBe("Monthly on the last calendar day at 8:00 PM");+ });++ it.each<Partial<Channel>>([+ { schedule_type: "daily" },+ { schedule_type: "weekly", schedule_hour: 9 },+ { schedule_type: "weekly", schedule_day: "mon" },+ { schedule_type: "monthly", schedule_hour: 8 },+ { schedule_type: "monthly", schedule_frame: "first" },+ ])(+ "says the schedule is not set when $schedule_type misses a field",+ (opts) => {+ expect(formatSubscriptionSchedule(createMockChannel(opts))).toBe(+ "Schedule not set",+ );+ },+ );+});++describe("formatSubscriptionDelivery", () => {+ afterEach(() => {+ mockSettings();+ });++ it("says how and when a subscription sends", () => {+ expect(+ formatSubscriptionDelivery(+ createMockChannel({ schedule_type: "daily", schedule_hour: 8 }),+ ),+ ).toBe("Emailed daily at 8:00 AM");+ expect(+ formatSubscriptionDelivery(+ createMockChannel({+ channel_type: "slack",+ details: { channel: "#sales" },+ schedule_type: "hourly",+ }),+ ),+ ).toBe("Sent to #sales hourly");+ expect(+ formatSubscriptionDelivery(+ createMockChannel({+ channel_type: "http",+ schedule_type: "weekly",+ schedule_day: "mon",+ schedule_hour: 8,+ }),+ ),+ ).toBe("Sent Monday at 8:00 AM");+ });++ it("formats monthly schedules with and without a day of the week", () => {+ expect(+ formatSubscriptionDelivery(+ createMockChannel({+ schedule_type: "monthly",+ schedule_frame: "first",+ schedule_day: "mon",+ schedule_hour: 8,+ }),+ ),+ ).toBe("Emailed monthly on the first Monday at 8:00 AM");+ expect(+ formatSubscriptionDelivery(+ createMockChannel({+ schedule_type: "monthly",+ schedule_frame: "first",+ schedule_hour: 8,+ }),+ ),+ ).toBe("Emailed monthly on the first calendar day at 8:00 AM");+ });++ it("says the schedule is not set when it misses its hour", () => {+ expect(+ formatSubscriptionDelivery(+ createMockChannel({ schedule_type: "daily", schedule_hour: null }),+ ),+ ).toBe("Schedule not set");+ });++ it("uses the instance's time format", () => {+ mockSettings({+ "custom-formatting": { "type/Temporal": { time_style: "HH:mm" } },+ });+ const channel = createMockChannel({+ schedule_type: "daily",+ schedule_hour: 20,+ });++ expect(formatSubscriptionDelivery(channel)).toBe("Emailed daily at 20:00");+ expect(formatSubscriptionSchedule(channel)).toBe("Daily at 20:00");+ });+});++describe("buildRecipientText", () => {+ const buildPulse = (recipientNames: string[]) =>+ createMockDashboardSubscription({+ channels: [+ createMockChannel({+ recipients: recipientNames.map((common_name, index) =>+ createMockUser({ common_name, email: `user${index}@example.com` }),+ ),+ }),+ ],+ });++ it("names the first email recipient and counts the others", () => {+ expect(buildRecipientText(buildPulse(["Ada Lovelace"]))).toBe(+ "Ada Lovelace",+ );+ expect(+ buildRecipientText(+ buildPulse(["Ada Lovelace", "Alan Turing", "Grace Hopper"]),+ ),+ ).toBe("Ada Lovelace and 2 others");+ });++ it("counts an address saved both as a user and as a plain email once", () => {+ expect(+ buildRecipientText(+ createMockDashboardSubscription({+ channels: [+ createMockChannel({+ recipients: [+ { email: "[email protected]" },+ createMockUser({+ common_name: "Ada Lovelace",+ email: "[email protected]",+ }),+ { email: "[email protected]" },+ ],+ }),+ ],+ }),+ ),+ ).toBe("Ada Lovelace and 1 other");+ });++ it("names a recipient outside Metabase by their address", () => {+ expect(+ buildRecipientText(+ createMockDashboardSubscription({+ channels: [+ createMockChannel({ recipients: [{ email: "[email protected]" }] }),+ ],+ }),+ ),+ ).toBe("[email protected]");+ });++ it("returns an empty string for a subscription without a channel", () => {+ expect(+ buildRecipientText(createMockDashboardSubscription({ channels: [] })),+ ).toBe("");+ });++ it("returns an empty string for a Slack channel", () => {+ expect(+ buildRecipientText(+ createMockDashboardSubscription({+ channels: [+ createMockChannel({+ channel_type: "slack",+ details: { channel: "#sales" },+ }),+ ],+ }),+ ),+ ).toBe("");+ });+});++describe("getRecipientName", () => {+ it("prefers a user's name to their address", () => {+ expect(+ getRecipientName(+ createMockUser({+ common_name: "Ada Lovelace",+ email: "[email protected]",+ }),+ ),+ ).toBe("Ada Lovelace");+ });++ it("uses the address of a recipient outside Metabase", () => {+ expect(getRecipientName({ email: "[email protected]" })).toBe(+ "[email protected]",+ );+ });+});++describe("getChannelRecipients", () => {+ it("lists an address saved both as a user and as a plain email once, as the user", () => {+ const user = createMockUser({+ common_name: "Ada Lovelace",+ email: "[email protected]",+ });+ const channel = createMockChannel({+ recipients: [{ email: "[email protected]" }, user],+ });++ expect(getChannelRecipients(channel)).toEqual([+ { type: "user", name: "Ada Lovelace", email: "[email protected]" },+ ]);+ });++ it("keeps an address outside Metabase as an external recipient", () => {+ const channel = createMockChannel({+ recipients: [{ email: "[email protected]" }],+ });++ expect(getChannelRecipients(channel)).toEqual([+ { type: "external", email: "[email protected]" },+ ]);+ });+});diff --git a/frontend/src/metabase/plugins/oss/caching.ts b/frontend/src/metabase/plugins/oss/caching.tsindex 8f5db295856..0f0038991e2 100644--- a/frontend/src/metabase/plugins/oss/caching.ts+++ b/frontend/src/metabase/plugins/oss/caching.ts@@ -64,6 +64,8 @@ export type SidebarCacheFormProps = {overlayProps?: ModalOverlayProps;onClose: () => void;onBack: () => void;+ /** When false, the form is not a sub-page with a title to go back by */+ withBackButton?: boolean;} & StackProps;export type PreemptiveCachingSwitchProps = {diff --git a/frontend/src/metabase/plugins/oss/library.ts b/frontend/src/metabase/plugins/oss/library.tsindex ccd79023618..a867c4c0807 100644--- a/frontend/src/metabase/plugins/oss/library.ts+++ b/frontend/src/metabase/plugins/oss/library.ts@@ -84,6 +84,7 @@ export type GetEntityPickerSyntheticLibraryItemFunction = {type LibraryPlugin = {isEnabled: boolean;getDataStudioLibraryRoutes: (IsAdmin: ComponentType) => ReactNode;+ getDataStudioDashboardRoutes: () => ReactNode;useGetLibraryCollection: (params?: { skip?: boolean }) => {data: undefined | LibraryCollection;isLoading: boolean;@@ -133,6 +134,7 @@ type LibraryPlugin = {const getDefaultPluginLibrary = (): LibraryPlugin => ({isEnabled: false,getDataStudioLibraryRoutes: () => null,+ getDataStudioDashboardRoutes: () => null,useGetLibraryCollection: () => ({ isLoading: false, data: undefined }),useGetLibraryChildCollectionByType: () => ({data: undefined,diff --git a/frontend/src/metabase/pulse/pulse.ts b/frontend/src/metabase/pulse/pulse.tsindex 473de61c37b..84993d8eab9 100644--- a/frontend/src/metabase/pulse/pulse.ts+++ b/frontend/src/metabase/pulse/pulse.ts@@ -16,6 +16,7 @@ import type {Alert,Channel,ChannelApiResponse,+ ChannelRecipient,ChannelSpec,ChannelSpecs,DashboardSubscription,@@ -24,6 +25,7 @@ import type {ScheduleSettings,User,} from "metabase-types/api";+import { isUserRecipient } from "metabase-types/guards";export const NEW_PULSE_TEMPLATE = {name: null,@@ -112,7 +114,7 @@ function pulseChannelsAreValid();}-export type RecipientPickerValue = (User | { email: string }) & {+export type RecipientPickerValue = ChannelRecipient & {entityId?: number;};@@ -325,7 +327,9 @@ export const canArchiveLegacyAlert = (): boolean => {const recipients = item.channels.flatMap((channel) => {if (channel.recipients) {- return channel.recipients.map((recipient) => recipient.id);+ return channel.recipients.map((recipient) =>+ isUserRecipient(recipient) ? recipient.id : null,+ );} else {return [];}diff --git a/frontend/src/metabase/redux/store/dashboard.ts b/frontend/src/metabase/redux/store/dashboard.tsindex 37e940a4386..25e0f9a787b 100644--- a/frontend/src/metabase/redux/store/dashboard.ts+++ b/frontend/src/metabase/redux/store/dashboard.ts@@ -6,6 +6,7 @@ import type {Dashboard,DashboardCard,DashboardId,+ DashboardSubscription,DashboardTab,DashboardTabId,ParameterId,@@ -61,11 +62,22 @@ export interface EventsSidebarState extends BaseSidebarState {props: EventsSidebarProps;}+type SharingSidebarProps = {+ dashcardId?: DashCardId;+ subscriptionId?: DashboardSubscription["id"];+};++export interface SharingSidebarState extends BaseSidebarState {+ name: "sharing";+ props: SharingSidebarProps;+}+export type DashboardSidebarState =| BaseSidebarState| ClickBehaviorSidebarState| EditParameterSidebarState- | EventsSidebarState;+ | EventsSidebarState+ | SharingSidebarState;export type TimelineEventsSelection = {dashcardId?: DashCardId;diff --git a/frontend/src/metabase/urls/dashboards.ts b/frontend/src/metabase/urls/dashboards.tsindex a4cf1348494..ab891075712 100644--- a/frontend/src/metabase/urls/dashboards.ts+++ b/frontend/src/metabase/urls/dashboards.ts@@ -9,6 +9,7 @@ import type Question from "metabase-lib/v1/Question";import type {DashCardId,DashboardId,+ DashboardSubscription,DashboardTabId,} from "metabase-types/api";@@ -17,6 +18,8 @@ import { appendSlug } from "./utils";type DashboardUrlBuilderOpts = {addCardWithId?: number;editMode?: boolean;+ /** `true` opens the subscriptions sidebar, a subscription id opens its edit form */+ openSubscriptions?: boolean | DashboardSubscription["id"];tabId?: DashboardTabId | undefined;scrollToDashcard?: DashCardId | undefined;};@@ -29,6 +32,7 @@ export function dashboard({addCardWithId,editMode,+ openSubscriptions,tabId,scrollToDashcard,}: DashboardUrlBuilderOpts = {},@@ -46,6 +50,7 @@ export function dashboard(const hash = stringifyHashOptions({...(addCardWithId ? { add: addCardWithId } : {}),...(editMode ? { edit: editMode } : {}),+ ...(openSubscriptions ? { subscriptions: openSubscriptions } : {}),...(scrollToDashcard ? { scrollTo: scrollToDashcard } : {}),});diff --git a/frontend/src/metabase/urls/data-studio.ts b/frontend/src/metabase/urls/data-studio.tsindex 690ab95dbe6..51097695bcc 100644--- a/frontend/src/metabase/urls/data-studio.ts+++ b/frontend/src/metabase/urls/data-studio.ts@@ -1,6 +1,8 @@import type {CardId,CollectionId,+ DashboardId,+ DashboardSubscription,DatabaseId,ErdParams,FieldId,@@ -117,6 +119,34 @@ export function dataStudioActions(params: ExpandedIdsParams = {}) {return `${ROOT_URL}/actions${getExpandedIdsQueryString(params)}`;}+export function dataStudioDashboards(params: ExpandedIdsParams = {}) {+ return `${ROOT_URL}/dashboards${getExpandedIdsQueryString(params)}`;+}++export function dataStudioDashboard(dashboardId: DashboardId) {+ return `${dataStudioDashboards()}/${dashboardId}`;+}++export function dataStudioDashboardContents(dashboardId: DashboardId) {+ return `${dataStudioDashboard(dashboardId)}/contents`;+}++export function dataStudioDashboardDependencies(dashboardId: DashboardId) {+ return `${dataStudioDashboard(dashboardId)}/dependencies`;+}++export function dataStudioDashboardUsage(dashboardId: DashboardId) {+ return `${dataStudioDashboard(dashboardId)}/usage`;+}++export function dataStudioDashboardSubscriptions(+ dashboardId: DashboardId,+ subscriptionId?: DashboardSubscription["id"],+) {+ const baseUrl = `${dataStudioDashboard(dashboardId)}/subscriptions`;+ return subscriptionId != null ? `${baseUrl}/${subscriptionId}` : baseUrl;+}+export function dataStudioTable(tableId: TableId) {return `${dataStudioLibrary()}/tables/${tableId}`;}diff --git a/frontend/src/metabase/urls/data-studio.unit.spec.ts b/frontend/src/metabase/urls/data-studio.unit.spec.tsindex 5261330e9b8..f823e5bed1f 100644--- a/frontend/src/metabase/urls/data-studio.unit.spec.ts+++ b/frontend/src/metabase/urls/data-studio.unit.spec.ts@@ -1,5 +1,11 @@import {dataStudio,+ dataStudioDashboard,+ dataStudioDashboardContents,+ dataStudioDashboardDependencies,+ dataStudioDashboardSubscriptions,+ dataStudioDashboardUsage,+ dataStudioDashboards,dataStudioData,dataStudioDataModelSegment,dataStudioDataModelSegmentDependencies,@@ -107,6 +113,39 @@ describe("urls > data-studio", () => {});});+ describe("dataStudioDashboards", () => {+ it("should return the dashboards URL", () => {+ expect(dataStudioDashboards()).toBe("/data-studio/dashboards");+ });++ it("should carry expanded collection ids", () => {+ expect(dataStudioDashboards({ expandedIds: [1, 2] })).toBe(+ "/data-studio/dashboards?expandedId=1&expandedId=2",+ );+ });+ });++ describe("dataStudioDashboard", () => {+ it("should return the dashboard tab URLs", () => {+ expect(dataStudioDashboard(7)).toBe("/data-studio/dashboards/7");+ expect(dataStudioDashboardContents(7)).toBe(+ "/data-studio/dashboards/7/contents",+ );+ expect(dataStudioDashboardDependencies(7)).toBe(+ "/data-studio/dashboards/7/dependencies",+ );+ expect(dataStudioDashboardUsage(7)).toBe(+ "/data-studio/dashboards/7/usage",+ );+ expect(dataStudioDashboardSubscriptions(7)).toBe(+ "/data-studio/dashboards/7/subscriptions",+ );+ expect(dataStudioDashboardSubscriptions(7, 3)).toBe(+ "/data-studio/dashboards/7/subscriptions/3",+ );+ });+ });+describe("dataStudioTable", () => {it("should return table URL", () => {expect(dataStudioTable(42)).toBe("/data-studio/library/tables/42");diff --git a/frontend/src/metabase/urls/urls.unit.spec.ts b/frontend/src/metabase/urls/urls.unit.spec.tsindex 7af347669f6..5a64cca8e2a 100644--- a/frontend/src/metabase/urls/urls.unit.spec.ts+++ b/frontend/src/metabase/urls/urls.unit.spec.ts@@ -513,4 +513,17 @@ describe("urls", () => {});});});++ describe("dashboard", () => {+ it("opens the subscriptions sidebar or one subscription from the hash", () => {+ const entity = { id: 1, name: "Sales" };++ expect(dashboard(entity, { openSubscriptions: true })).toBe(+ "/dashboard/1-sales#subscriptions",+ );+ expect(dashboard(entity, { openSubscriptions: 12 })).toBe(+ "/dashboard/1-sales#subscriptions=12",+ );+ });+ });});diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.tsindex 4d11b4a85ae..3d14940bb03 100644--- a/frontend/test/__support__/server-mocks/collection.ts+++ b/frontend/test/__support__/server-mocks/collection.ts@@ -232,6 +232,12 @@ export function setupCollectionItemsEndpoint({collectionItems: CollectionItem[];models?: string[];}) {+ const itemsName = `collection-${collection.id}-items`;+ const metadataName = `collection-${collection.id}-items-metadata`;+ fetchMock.removeRoutes({+ names: [itemsName, metadataName],+ includeFallback: false,+ });fetchMock.get(`path:/api/collection/${collection.id}/items`,(call) => {@@ -241,12 +247,12 @@ export function setupCollectionItemsEndpoint({modelsParam,});},- { name: `collection-${collection.id}-items` },+ { name: itemsName },);fetchMock.get(`path:/api/collection/${collection.id}/items/metadata`,(call) => collectionItemsMetadata(call, collectionItems),- { name: `collection-${collection.id}-items-metadata` },+ { name: metadataName },);}diff --git a/frontend/test/__support__/server-mocks/dashboard.ts b/frontend/test/__support__/server-mocks/dashboard.tsindex b41637a04f2..7039f1e27aa 100644--- a/frontend/test/__support__/server-mocks/dashboard.ts+++ b/frontend/test/__support__/server-mocks/dashboard.ts@@ -10,14 +10,34 @@ import type {} from "metabase-types/api";import { createMockDashboard } from "metabase-types/api/mocks";-export function setupDashboardEndpoints(dashboard: Dashboard) {+type SetupDashboardEndpointsOpts = {+ /** What PUT responds with. By default it echoes the request body back. */+ updatedDashboard?: Dashboard;+};++export function setupDashboardEndpoints(+ dashboard: Dashboard,+ { updatedDashboard }: SetupDashboardEndpointsOpts = {},+) {fetchMock.get(`path:/api/dashboard/${dashboard.id}`, dashboard);fetchMock.put(`path:/api/dashboard/${dashboard.id}`, async (call) => {+ if (updatedDashboard != null) {+ return updatedDashboard;+ }const lastCall = fetchMock.callHistory.lastCall(call.url);return createMockDashboard(await lastCall?.request?.json());});}+export function setupUpdateDashboardEndpointWithError(+ dashboardId: DashboardId,+) {+ fetchMock.put(`path:/api/dashboard/${dashboardId}`, {+ status: 500,+ body: {},+ });+}+export function setupAutoDashboardEndpoints(dashboard: Dashboard,metadata: DashboardQueryMetadata,diff --git a/frontend/test/__support__/server-mocks/performance.ts b/frontend/test/__support__/server-mocks/performance.tsindex 60238057e3b..3723c628d57 100644--- a/frontend/test/__support__/server-mocks/performance.ts+++ b/frontend/test/__support__/server-mocks/performance.ts@@ -36,3 +36,7 @@ export function setupPerformanceEndpoints(cacheConfigs: CacheConfig[]) {return {};});}++export function setupPerformanceEndpointsError() {+ fetchMock.get("path:/api/cache", 500);+}diff --git a/frontend/test/__support__/server-mocks/pulse.ts b/frontend/test/__support__/server-mocks/pulse.tsindex 6d47bc6dd38..a3b11aa0e0d 100644--- a/frontend/test/__support__/server-mocks/pulse.ts+++ b/frontend/test/__support__/server-mocks/pulse.ts@@ -1,10 +1,29 @@import fetchMock from "fetch-mock";import type { DeepPartial } from "metabase/embedding-sdk/types/utils";-import type { ChannelApiResponse } from "metabase-types/api";+import type {+ ChannelApiResponse,+ DashboardId,+ DashboardSubscription,+} from "metabase-types/api";export const setupNotificationChannelsEndpoints = (channelData: DeepPartial<Required<ChannelApiResponse["channels"]>>,) => {fetchMock.get("path:/api/pulse/form_input", { channels: channelData });};++export const setupListSubscriptionsEndpoint = (+ subscriptions: DashboardSubscription[],+ { dashboardId }: { dashboardId?: DashboardId } = {},+) => {+ fetchMock.get({+ url: "path:/api/pulse",+ ...(dashboardId != null && { query: { dashboard_id: dashboardId } }),+ response: subscriptions,+ });+};++export const setupNotificationChannelsEndpointError = () => {+ fetchMock.get("path:/api/pulse/form_input", 500);+};diff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex e50f90cbe35..fcbf1640d2d 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -119,6 +119,7 @@[:series :can_write]:dashcard/action:dashcard/linkcard-info]+ :creator:can_restore:can_delete:tabsdiff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.cljindex fbdfa795a97..8a666751e31 100644--- a/test/metabase/dashboards_rest/api_test.clj+++ b/test/metabase/dashboards_rest/api_test.clj@@ -386,6 +386,14 @@:dashboard_id dashboard-id}](is (#'api.dashboard/get-dashboard dashboard-id)))))))+(deftest get-dashboard-creator-test+ (testing "GET /api/dashboard/:id includes the dashboard's creator"+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {:creator_id (mt/user->id :rasta)}]+ (is (=? {:creator {:id (mt/user->id :rasta)+ :email "[email protected]"+ :first_name "Rasta"}}+ (mt/user-http-request :crowberto :get 200 (str "dashboard/" dashboard-id)))))))+(deftest get-dashboard-param-fields-has-target-test(testing "param-fields for fk has target (#44231)"(mt/with-temp