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
Render row menu modals outside table rows (#84076)
Alexander Polyankin5d4e2bdae7a8
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/ActionCell/ActionCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/ActionCell/ActionCell.tsxindex 0c9eb67f394..3bb1b83dc19 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/ActionCell/ActionCell.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/ActionCell/ActionCell.tsx@@ -1,7 +1,4 @@-import {- type LibrarySection,- getItemSection,-} from "metabase/data-studio/common/hooks/use-library-bulk-selection";+import type { CollectionRowModalState } from "metabase/common/collections/components/CollectionRowModal";import type { TreeItem } from "metabase/data-studio/common/types";import {isCollectionData,@@ -10,19 +7,21 @@ import {} from "metabase/data-studio/common/utils";import { PLUGIN_LIBRARY } from "metabase/plugins";import { TableMoreMenu } from "metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu";-import type { CollectionId } from "metabase-types/api";+import type { TableModalState } from "metabase-enterprise/data-studio/library/tables/components/TableModal";import { LibraryCollectionRowMenu } from "../LibraryCollectionRowMenu";type ActionCellProps = {treeItem: TreeItem;- refreshSection: (- section: LibrarySection,- collectionIds: CollectionId[],- ) => void;+ onOpenCollectionModal: (modal: CollectionRowModalState) => void;+ onOpenTableModal: (modal: TableModalState) => void;};-export function ActionCell({ treeItem, refreshSection }: ActionCellProps) {+export function ActionCell({+ treeItem,+ onOpenCollectionModal,+ onOpenTableModal,+}: ActionCellProps) {const { data, children } = treeItem;if (isEmptyStateData(data)) {@@ -30,15 +29,10 @@ export function ActionCell({ treeItem, refreshSection }: ActionCellProps) {}if (isTableData(data)) {- return (- <TableMoreMenu- table={data}- onMoved={(collectionIds) => refreshSection("data", collectionIds)}- />- );+ return <TableMoreMenu table={data} onOpenModal={onOpenTableModal} />;}- if (!isCollectionData(data) || data.model !== "collection") {+ if (!isCollectionData(data)) {return null;}@@ -46,16 +40,12 @@ export function ActionCell({ treeItem, refreshSection }: ActionCellProps) {PLUGIN_LIBRARY.isLibrarySubCollectionType(data.type) &&!data.is_library_root;- const section = getItemSection(treeItem);-- if (isLibraryCollection && section != null) {+ if (isLibraryCollection) {return (<LibraryCollectionRowMenuchildCount={children?.length ?? 0}collection={data}- refreshCollections={(collectionIds) =>- refreshSection(section, collectionIds)- }+ onOpenModal={onOpenCollectionModal}/>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.tsxindex f7e5c3e5708..dbff455370f 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.tsx@@ -1,61 +1,32 @@-import { useCallback } from "react";-import _ from "underscore";-import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";-import type { Collection, CollectionId } from "metabase-types/api";+import type { CollectionRowModalState } from "metabase/common/collections/components/CollectionRowModal";+import type { Collection } from "metabase-types/api";import { getArchiveLibraryCollectionsMessage } from "../utils";type LibraryCollectionRowMenuProps = {childCount: number;collection: Collection;- refreshCollections: (collectionIds: CollectionId[]) => void;+ onOpenModal: (modal: CollectionRowModalState) => void;};-export function LibraryCollectionRowMenu(props: LibraryCollectionRowMenuProps) {- const { childCount, collection, refreshCollections } = props;+export function LibraryCollectionRowMenu({+ childCount,+ collection,+ onOpenModal,+}: LibraryCollectionRowMenuProps) {const isLibraryDataCollection =collection.type === "library-data" && !collection.is_library_root;- const onArchiveSuccess = useCallback(() => {- const parentId = getParentCollectionId(collection);-- if (parentId == null) {- return;- }-- refreshCollections([parentId]);- }, [collection, refreshCollections]);-return (<CollectionRowMenucollection={collection}- onSave={(details) => {- refreshCollections(getAffectedCollectionIds(details));- }}+ onOpenModal={onOpenModal}customArchiveMessage={isLibraryDataCollection && childCount > 0? getArchiveLibraryCollectionsMessage(1): undefined}- onArchiveSuccess={onArchiveSuccess}/>);}--const getAffectedCollectionIds = ({- previousParentId,- newParentId,-}: {- previousParentId: CollectionId | null;- newParentId: CollectionId | null;-}) => _.uniq([previousParentId, newParentId]).filter(_.isNumber);--const getParentCollectionId = (collection: Collection) => {- const parentId =- "collection_id" in collection- ? collection.collection_id- : collection.parent_id;-- return typeof parentId === "number" ? parentId : null;-};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.unit.spec.tsxindex 95ac54331ef..274ce673273 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryCollectionRowMenu/LibraryCollectionRowMenu.unit.spec.tsx@@ -1,47 +1,49 @@import userEvent from "@testing-library/user-event";+import { type ComponentProps, useState } from "react";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";-import {- setupCollectionByIdEndpoint,- setupUpdateCollectionEndpoint,-} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { renderWithProviders, screen } from "__support__/ui";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "metabase/common/collections/components/CollectionRowModal";import {createMockCollection,createMockTokenFeatures,createMockUser,} from "metabase-types/api/mocks";-import { LibraryCollectionRowMenu } from ".";+import { LibraryCollectionRowMenu } from "./LibraryCollectionRowMenu";++function LibraryCollectionRowMenuWithModal(+ props: Omit<ComponentProps<typeof LibraryCollectionRowMenu>, "onOpenModal">,+) {+ const [modal, setModal] = useState<CollectionRowModalState>();+ return (+ <>+ <LibraryCollectionRowMenu {...props} onOpenModal={setModal} />+ <CollectionRowModal modal={modal} onClose={() => setModal(undefined)} />+ </>+ );+}function setup({collection = createMockCollection({id: 1,name: "Library Data Collection",type: "library-data",- parent_id: 22,}),childCount = 0,}: Partial<Parameters<typeof LibraryCollectionRowMenu>[0]> = {}) {- const refreshCollections = jest.fn();- const parentCollection = createMockCollection({- id: 22,- name: "Data",- type: "library-data",- });-setupEnterpriseOnlyPlugin("library");setupEnterpriseOnlyPlugin("remote_sync");- setupUpdateCollectionEndpoint(collection);- setupCollectionByIdEndpoint({ collections: [parentCollection] });renderWithProviders(- <LibraryCollectionRowMenu+ <LibraryCollectionRowMenuWithModalchildCount={childCount}collection={collection}- refreshCollections={refreshCollections}/>,{storeInitialState: createMockState({@@ -55,28 +57,9 @@ function setup({}),},);-- return { refreshCollections };}describe("LibraryCollectionRowMenu", () => {- it("refreshes the parent collection after saving", async () => {- const { refreshCollections } = setup();-- await userEvent.click(- screen.getByRole("button", { name: "Collection options" }),- );- await userEvent.click(- screen.getByRole("menuitem", { name: /Edit collection details/ }),- );- await userEvent.type(screen.getByLabelText("Name"), " Updated");- await userEvent.click(screen.getByRole("button", { name: "Save" }));-- await waitFor(() => {- expect(refreshCollections).toHaveBeenCalledWith([22]);- });- });-it("shows a table unpublish warning when archiving a non-empty Library Data collection", async () => {setup({ childCount: 1 });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 0f41e17f486..fb757e79ec2 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@@ -4,13 +4,20 @@ import { useCallback, useMemo, useState } from "react";import { t } from "ttag";import { useListCollectionsTreeQuery } from "metabase/api";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "metabase/common/collections/components/CollectionRowModal";import { useHasTokenFeature } from "metabase/common/hooks";import { LibraryTreePage } from "metabase/data-studio/common/components/LibraryTreePage";import { useErrorHandling } from "metabase/data-studio/common/hooks/use-error-handling";import type { LibrarySection } from "metabase/data-studio/common/hooks/use-library-bulk-selection";import type { TreeItem } from "metabase/data-studio/common/types";import { LibraryUpsellPage } from "metabase/data-studio/upsells/pages/LibraryUpsellPage";-import type { CollectionId } from "metabase-types/api";+import {+ TableModal,+ type TableModalState,+} from "metabase-enterprise/data-studio/library/tables/components/TableModal";import { ActionCell } from "./ActionCell";import { CreateLibraryDashboardModal } from "./CreateLibraryDashboardModal";@@ -48,6 +55,9 @@ export function LibraryPage() {function LibraryPageContent() {const [searchQuery, setSearchQuery] = useState("");+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();+ const [tableModal, setTableModal] = useState<TableModalState>();const [showPublishTableModal,{ open: openPublishTableModal, close: closePublishTableModal },@@ -81,7 +91,6 @@ function LibraryPageContent() {error: tablesError,watchRows: watchTableRows,isChildrenLoading: isTableChildrenLoading,- refreshCollections: refreshTableCollections,} = useLibraryCollectionTree(tableCollection, "data");const {tree: metricsTree,@@ -89,7 +98,6 @@ function LibraryPageContent() {error: metricsError,watchRows: watchMetricRows,isChildrenLoading: isMetricChildrenLoading,- refreshCollections: refreshMetricCollections,} = useLibraryCollectionTree(metricCollection,"metrics",@@ -101,7 +109,6 @@ function LibraryPageContent() {error: dashboardsError,watchRows: watchDashboardRows,isChildrenLoading: isDashboardChildrenLoading,- refreshCollections: refreshDashboardCollections,} = useLibraryCollectionTree(dashboardCollection, "dashboards");const {tree: searchTree,@@ -140,27 +147,15 @@ function LibraryPageContent() {[openPublishTableModal, openCreateDashboardModal],);- const refreshSection = useCallback(- (section: LibrarySection, collectionIds: CollectionId[]) => {- if (section === "data") {- refreshTableCollections(collectionIds);- } else if (section === "metrics") {- refreshMetricCollections(collectionIds);- } else if (section === "dashboards") {- refreshDashboardCollections(collectionIds);- }- },- [- refreshTableCollections,- refreshMetricCollections,- refreshDashboardCollections,- ],- );const renderRowMenu = useCallback((item: TreeItem) => (- <ActionCell treeItem={item} refreshSection={refreshSection} />+ <ActionCell+ treeItem={item}+ onOpenCollectionModal={setCollectionModal}+ onOpenTableModal={setTableModal}+ />),- [refreshSection],+ [],);const handleRowsChange = useCallback((rows: Row<TreeItem>[]) => {@@ -220,7 +215,6 @@ function LibraryPageContent() {onRowsChange={handleRowsChange}onSearchQueryChange={setSearchQuery}getTrashMessage={getTrashMessage}- onBulkActionComplete={refreshSection}><PublishTableModalopened={showPublishTableModal}@@ -234,6 +228,11 @@ function LibraryPageContent() {onClose={closeCreateDashboardModal}/>)}+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}+ />+ <TableModal modal={tableModal} onClose={() => setTableModal(undefined)} /></LibraryTreePage>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsxnew file mode 100644index 00000000000..8d6d5790336--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsx@@ -0,0 +1,258 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ setupCollectionItemsEndpoint,+ setupCollectionsEndpoints,+ setupTableEndpoints,+ setupUnauthorizedCollectionEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { createMockState } from "__support__/state";+import {+ act,+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { collectionApi } from "metabase/api";+import { listTag } from "metabase/api/tags";+import type { CollectionPickerModalProps } from "metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal";+import { Route } from "metabase/router";+import type {+ Collection,+ CollectionId,+ CollectionItem,+} from "metabase-types/api";+import {+ createMockCollection,+ createMockCollectionItem,+ createMockTable,+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";++import { LibraryPage } from "./LibraryPage";++jest.mock("metabase/common/components/Pickers", () => ({+ ...jest.requireActual("metabase/common/components/Pickers"),+ CollectionPickerModal: ({ onChange }: CollectionPickerModalProps) => (+ <button+ onClick={() =>+ onChange({+ id: 6,+ name: "Finance folder",+ model: "collection",+ can_write: true,+ })+ }+ >+ Destination+ </button>+ ),+}));++const DATA_COLLECTION = createMockCollection({+ id: 2,+ name: "Data",+ type: "library-data",+ can_write: true,+});++const LIBRARY_COLLECTION = createMockCollection({+ id: 1,+ name: "Library",+ type: "library",+ children: [DATA_COLLECTION],+});++const FOLDER = createMockCollectionItem({+ id: 5,+ name: "Sales folder",+ model: "collection",+ type: "library-data",+ here: ["table"],+});++const DESTINATION_FOLDER = createMockCollectionItem({+ id: 6,+ name: "Finance folder",+ model: "collection",+ type: "library-data",+});++const createTableItem = (+ id: number,+ name: string,+ collectionId: CollectionId = FOLDER.id,+) =>+ createMockCollectionItem({+ id,+ name,+ model: "table",+ database_id: 1,+ collection_id: collectionId,+ });++const ORDERS = createTableItem(10, "Orders");++function setupItems(+ collection: Pick<Collection, "id">,+ collectionItems: CollectionItem[],+) {+ fetchMock.removeRoute(`collection-${collection.id}-items`);+ fetchMock.removeRoute(`collection-${collection.id}-items-metadata`);+ setupCollectionItemsEndpoint({ collection, collectionItems });+}++function setupFolderItems(collectionItems: CollectionItem[]) {+ setupItems(FOLDER, collectionItems);+}++type SetupOpts = {+ destinationItems?: CollectionItem[];+ isFolderReadable?: boolean;+};++function setup({+ destinationItems = [],+ isFolderReadable = true,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 1000 });+ setupCollectionsEndpoints({ collections: [LIBRARY_COLLECTION] });+ setupItems(DATA_COLLECTION, [+ FOLDER,+ {+ ...DESTINATION_FOLDER,+ here: destinationItems.length > 0 ? ["table"] : [],+ },+ ]);+ if (isFolderReadable) {+ setupFolderItems([ORDERS]);+ } else {+ setupUnauthorizedCollectionEndpoints(+ createMockCollection({ id: FOLDER.id }),+ );+ }+ setupItems(DESTINATION_FOLDER, destinationItems);+ setupTableEndpoints(createMockTable({ id: ORDERS.id }));+ const state = createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures({ library: true }),+ }),+ currentUser: createMockUser({ is_superuser: true }),+ });+ setupEnterprisePlugins();++ return renderWithProviders(<Route path="/" element={<LibraryPage />} />, {+ withRouter: true,+ storeInitialState: state,+ });+}++function setupMovedOrders(destinationItems: CollectionItem[]) {+ setupItems(DATA_COLLECTION, [+ { ...FOLDER, here: [] },+ { ...DESTINATION_FOLDER, here: ["table"] },+ ]);+ setupFolderItems([]);+ setupItems(DESTINATION_FOLDER, [+ ...destinationItems,+ createTableItem(ORDERS.id, ORDERS.name, DESTINATION_FOLDER.id),+ ]);+}++describe("LibraryPage", () => {+ it("updates an expanded folder when its items change", async () => {+ const { store } = setup();++ await userEvent.click(await screen.findByText("Sales folder"));+ expect(await screen.findByText("Orders")).toBeInTheDocument();++ setupFolderItems([createTableItem(11, "Invoices")]);+ act(() => {+ store.dispatch(collectionApi.util.invalidateTags([listTag("table")]));+ });++ expect(await screen.findByText("Invoices")).toBeInTheDocument();+ expect(screen.queryByText("Orders")).not.toBeInTheDocument();+ });++ it("shows tables moved in bulk into an expanded folder", async () => {+ const invoices = createTableItem(11, "Invoices", DESTINATION_FOLDER.id);+ setup({ destinationItems: [invoices] });++ await userEvent.click(await screen.findByText("Finance folder"));+ expect(await screen.findByText("Invoices")).toBeInTheDocument();+ await userEvent.click(screen.getByText("Sales folder"));+ await userEvent.click(+ within(await screen.findByRole("row", { name: /Orders/ })).getByRole(+ "checkbox",+ ),+ );+ await userEvent.click(screen.getByText("Sales folder"));+ expect(screen.queryByText("Orders")).not.toBeInTheDocument();++ setupMovedOrders([invoices]);+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Move",+ }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Destination" }),+ );++ expect(await screen.findByText("Orders")).toBeInTheDocument();+ });++ it("shows a table moved into an empty folder", async () => {+ setup();++ await userEvent.click(await screen.findByText("Sales folder"));+ await userEvent.click(+ await screen.findByRole("button", { name: "Show table options" }),+ );+ setupMovedOrders([]);+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Move/ }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Destination" }),+ );++ await userEvent.click(+ await screen.findByRole("button", { name: "Expand" }),+ );+ expect(await screen.findByText("Orders")).toBeInTheDocument();+ });++ it("stops loading a folder whose items fail to load", async () => {+ setup({ isFolderReadable: false });++ await userEvent.click(await screen.findByText("Sales folder"));++ await waitFor(() =>+ expect(+ fetchMock.callHistory.called(`path:/api/collection/${FOLDER.id}/items`),+ ).toBe(true),+ );+ await waitFor(() =>+ expect(screen.queryByLabelText("Loading")).not.toBeInTheDocument(),+ );+ });++ it("requests the items of an expanded folder once", async () => {+ setup();++ await userEvent.click(await screen.findByText("Sales folder"));+ expect(await screen.findByText("Orders")).toBeInTheDocument();++ expect(+ fetchMock.callHistory.calls(`collection-${FOLDER.id}-items`),+ ).toHaveLength(1);+ });+});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 4c6b49de9ed..fe287ab6361 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,5 +1,6 @@import type { Row } from "@tanstack/react-table";import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { shallowEqual } from "react-redux";import { t } from "ttag";import {@@ -14,12 +15,10 @@ import type {LibrarySectionType,TreeItem,} from "metabase/data-studio/common/types";-import {- createEmptyStateItem,- isEmptyStateData,-} from "metabase/data-studio/common/utils";+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 { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";import type {Collection,@@ -75,6 +74,17 @@ const SECTION_ITEM_MODELS: Record<LibrarySectionType, CollectionItemModel[]> = {actions: ["action", "collection"],};+const NO_ITEMS: CollectionItem[] = [];++const getCollectionItemsRequest = (+ collectionId: CollectionId,+ models: CollectionItemModel[],+) => ({+ id: collectionId,+ models,+ archived: false,+});+export function useLibraryCollectionTree(collection: Collection | undefined,sectionType: LibrarySectionType,@@ -90,61 +100,82 @@ export function useLibraryCollectionTree(isLoading,error,} = useListCollectionItemsQuery(- collection- ? {- id: collection.id,- models,- archived: false,- }- : skipToken,+ collection ? getCollectionItemsRequest(collection.id, models) : skipToken,);const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);- // 2. Lazy-loaded subcollection items- const [loadedCollections, setLoadedCollections] = useState<- Map<CollectionId, CollectionItem[]>- >(new Map());- const loadingIds = useRef(new Set<string>());+ // 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(() => {- setLoadedCollections(new Map());- loadingIds.current = new Set();- }, [collection]);-- const loadCollectionItems = useCallback(- async (collectionId: CollectionId) => {- const key = String(collectionId);- if (loadingIds.current.has(key)) {- return;+ 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);}- loadingIds.current.add(key);-- const result = await dispatch(- collectionApi.endpoints.listCollectionItems.initiate(- {- id: collectionId,- models,- archived: false,- },- { forceRefetch: true },+ });+ }, [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),),- );- const items = (result.data?.data ?? []).filter((item) => !item.archived);- setLoadedCollections((prev) => new Map([...prev, [collectionId, items]]));- },- [dispatch, models],+ ),+ [expandedCollectionIds, models],);- const refreshCollections = useCallback(- async (collectionIds: CollectionId[]) => {- for (const id of collectionIds) {- const key = String(id);- loadingIds.current.delete(key);- }- await Promise.all(collectionIds.map(loadCollectionItems));- },- [loadCollectionItems],+ 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 tree@@ -189,25 +220,38 @@ export function useLibraryCollectionTree(isRemoteSyncReadOnly,]);- // 4. Watch rows for expanded-but-empty collections → trigger fetch+ // 4. Watch rows for expanded-but-empty collections → subscribe to their items+ const sectionRowId = tree[0]?.id;const watchRows = useCallback((rows: Row<TreeItem>[]) => {- for (const row of rows) {+ const collectionIdsToLoad = rows.flatMap((row) => {const { original } = row;- if (+ const isExpandedWithoutChildren =row.getIsExpanded() &&row.getCanExpand() &&original.model === "collection" &&- original.children?.length === 0 &&- !isEmptyStateData(original.data) &&- "id" in original.data- ) {- // Unjustified type cast. FIXME- loadCollectionItems(original.data.id as number);- }+ 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;+ });},- [loadCollectionItems],+ [sectionRowId],);// 5. isChildrenLoading for the spinner@@ -225,7 +269,6 @@ export function useLibraryCollectionTree(error,watchRows,isChildrenLoading,- refreshCollections,};}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableHeader.tsxindex fb5b83c7e78..0c25ba9aafd 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableHeader.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableHeader.tsx@@ -1,3 +1,5 @@+import { useState } from "react";+import { Link } from "metabase/common/components/Link/Link";import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";import {@@ -9,6 +11,8 @@ import { getLibraryCollectionDisplayName } from "metabase/data-studio/common/utiimport * as Urls from "metabase/urls";import type { Table } from "metabase-types/api";+import { TableModal, type TableModalState } from "../TableModal";+import { TableMoreMenu } from "./TableMoreMenu";import { TableNameInput } from "./TableNameInput";import { TableTabs } from "./TableTabs";@@ -21,29 +25,34 @@ export function TableHeader({ table, ...rest }: TableHeaderProps) {const { path, isLoadingPath } = useCollectionPath({collectionId: table.collection_id,});+ const [tableModal, setTableModal] = useState<TableModalState>();+return (- <PaneHeader- data-testid="table-pane-header"- title={<TableNameInput table={table} />}- icon="table"- menu={<TableMoreMenu table={table} />}- tabs={<TableTabs table={table} />}- {...rest}- breadcrumbs={- <DataStudioBreadcrumbs loading={isLoadingPath}>- {path?.map((collection, i) => (- <Link- key={collection.id}- to={Urls.dataStudioLibrary({- expandedIds: path.slice(1, i + 1).map((c) => c.id),- })}- >- {getLibraryCollectionDisplayName(collection)}- </Link>- ))}- <span>{table.display_name}</span>- </DataStudioBreadcrumbs>- }- />+ <>+ <PaneHeader+ data-testid="table-pane-header"+ title={<TableNameInput table={table} />}+ icon="table"+ menu={<TableMoreMenu table={table} onOpenModal={setTableModal} />}+ tabs={<TableTabs table={table} />}+ {...rest}+ breadcrumbs={+ <DataStudioBreadcrumbs loading={isLoadingPath}>+ {path?.map((collection, i) => (+ <Link+ key={collection.id}+ to={Urls.dataStudioLibrary({+ expandedIds: path.slice(1, i + 1).map((c) => c.id),+ })}+ >+ {getLibraryCollectionDisplayName(collection)}+ </Link>+ ))}+ <span>{table.display_name}</span>+ </DataStudioBreadcrumbs>+ }+ />+ <TableModal modal={tableModal} onClose={() => setTableModal(undefined)} />+ </>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsxindex 44a1b31a3a7..2599d1fbe8c 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx@@ -1,63 +1,25 @@-import { useState } from "react";import { c, t } from "ttag";-import { collectionApi } from "metabase/api";import { ForwardRefLink } from "metabase/common/components/Link";-import { CollectionPickerModal } from "metabase/common/components/Pickers";-import { useSetCollection } from "metabase/common/hooks/use-set-collection";-import { PLUGIN_LIBRARY, PLUGIN_REMOTE_SYNC } from "metabase/plugins";-import { useDispatch, useSelector } from "metabase/redux";-import { useNavigate } from "metabase/router";+import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import { useSelector } from "metabase/redux";import { ActionIcon, Box, FixedSizeIcon, Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";-import type { CollectionId, CollectionItem, Table } from "metabase-types/api";-type TableModalType = "unpublish" | "move";+import type { TableModalState, TableModalTable } from "../../TableModal";export type TableMoreMenuProps = {- table:- | Pick<CollectionItem, "id" | "database_id" | "collection_id">- | Pick<Table, "id" | "db_id" | "collection_id">;- onMoved?: (collectionIds: CollectionId[]) => void;+ table: TableModalTable;+ onOpenModal: (modal: TableModalState) => void;};-export function TableMoreMenu({ table, onMoved }: TableMoreMenuProps) {- const dispatch = useDispatch();- const navigate = useNavigate();- const [modalType, setModalType] = useState<TableModalType>();- const setCollection = useSetCollection();+export function TableMoreMenu({ table, onOpenModal }: TableMoreMenuProps) {const remoteSyncReadOnly = useSelector(PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,);const dbId = "db_id" in table ? table.db_id : table.database_id;- const handleUnpublish = () => {- setModalType(undefined);- navigate(Urls.dataStudioLibrary());- };-- const handleMove = async (newCollection: { id: CollectionId }) => {- const sourceCollectionId = table.collection_id;- await setCollection(- { model: "table", id: table.id },- { id: newCollection.id },- { notify: false },- );- dispatch(- collectionApi.util.invalidateTags([- { type: "collection", id: `${sourceCollectionId}-items` },- { type: "collection", id: `${newCollection.id}-items` },- ]),- );- const affectedIds: CollectionId[] = [newCollection.id];- if (sourceCollectionId != null) {- affectedIds.push(sourceCollectionId);- }- onMoved?.(affectedIds);- setModalType(undefined);- };-return (<BoxonClick={(event) => {@@ -92,7 +54,7 @@ export function TableMoreMenu({ table, onMoved }: TableMoreMenuProps) {<Menu.ItemleftSection={<Icon name="move" />}onClick={(event) => {- setModalType("move");+ onOpenModal({ type: "move", table });event.preventDefault();event.stopPropagation();}}@@ -102,7 +64,7 @@ export function TableMoreMenu({ table, onMoved }: TableMoreMenuProps) {<Menu.ItemleftSection={<Icon name="unpublish" />}onClick={(event) => {- setModalType("unpublish");+ onOpenModal({ type: "unpublish", table });event.preventDefault();event.stopPropagation();}}@@ -113,33 +75,6 @@ export function TableMoreMenu({ table, onMoved }: TableMoreMenuProps) {)}</Menu.Dropdown></Menu>- <PLUGIN_LIBRARY.UnpublishTablesModal- isOpened={modalType === "unpublish"}- tableIds={[table.id]}- onUnpublish={handleUnpublish}- onClose={() => setModalType(undefined)}- />- {modalType === "move" && (- <CollectionPickerModal- title={t`Move table to…`}- value={{- id: table.collection_id ?? "root",- model: "collection",- }}- onChange={handleMove}- onClose={() => setModalType(undefined)}- options={{- hasLibrary: true,- hasRootCollection: false,- hasPersonalCollections: false,- hasSearch: true,- hasRecents: false,- hasConfirmButtons: true,- confirmButtonText: t`Move`,- }}- entityType="table"- />- )}</Box>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsxindex 5ca0d48b8a9..9a9e732f27c 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx@@ -1,5 +1,6 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";+import { type ComponentProps, useState } from "react";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import type { ENTERPRISE_PLUGIN_NAME } from "__support__/enterprise-typed";@@ -24,8 +25,22 @@ import {createMockTokenFeatures,} from "metabase-types/api/mocks";+import { TableModal, type TableModalState } from "../../TableModal";+import { TableMoreMenu, type TableMoreMenuProps } from "./TableMoreMenu";+function TableMoreMenuWithModal(+ props: Omit<ComponentProps<typeof TableMoreMenu>, "onOpenModal">,+) {+ const [modal, setModal] = useState<TableModalState>();+ return (+ <>+ <TableMoreMenu {...props} onOpenModal={setModal} />+ <TableModal modal={modal} onClose={() => setModal(undefined)} />+ </>+ );+}+// Mocking picker modal to limit overhead (picker functionality is tested in e2e tests)jest.mock("metabase/common/components/Pickers", () => ({CollectionPickerModal: ({ onChange }: CollectionPickerModalProps) => (@@ -47,7 +62,6 @@ jest.mock("metabase/common/components/Pickers", () => ({type SetupOpts = {table?: TableMoreMenuProps["table"];remoteSyncType?: EnterpriseSettings["remote-sync-type"];- onMoved?: TableMoreMenuProps["onMoved"];};const dataCollection = createMockCollection({@@ -66,7 +80,7 @@ const destinationCollection = createMockCollection({location: "/6464/10/",});-const setup = ({ table, remoteSyncType, onMoved }: SetupOpts = {}) => {+const setup = ({ table, remoteSyncType }: SetupOpts = {}) => {const tableData =table ??createMockTable({@@ -153,10 +167,7 @@ const setup = ({ table, remoteSyncType, onMoved }: SetupOpts = {}) => {setupTableEndpoints(createMockTable({ id: tableData.id }));renderWithProviders(- <Route- path="/"- element={<TableMoreMenu table={tableData} onMoved={onMoved} />}- />,+ <Route path="/" element={<TableMoreMenuWithModal table={tableData} />} />,{withRouter: true,storeInitialState: state,@@ -238,7 +249,6 @@ describe("TableMoreMenu", () => {});it("moves a table to another Library Data collection", async () => {- const onMoved = jest.fn();const table = createMockCollectionItem({id: 42,model: "table",@@ -248,7 +258,7 @@ describe("TableMoreMenu", () => {collection_id: dataCollection.id as number,});- setup({ table, onMoved });+ setup({ table });await userEvent.click(screen.getByRole("button", { name: "Show table options" }),);@@ -258,9 +268,15 @@ describe("TableMoreMenu", () => {await screen.findByRole("button", { name: "Destination" }),);- await waitFor(() => expect(onMoved).toHaveBeenCalledWith([11, 10]));+ await waitFor(() =>+ expect(fetchMock.callHistory.called("table-42-put")).toBe(true),+ );const request = fetchMock.callHistory.lastCall("table-42-put")?.request;expect(await request?.json()).toEqual({ collection_id: 11 });- expect(screen.queryByTestId("entity-picker-modal")).not.toBeInTheDocument();+ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "Destination" }),+ ).not.toBeInTheDocument(),+ );});});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableModal/TableModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableModal/TableModal.tsxnew file mode 100644index 00000000000..575c6217539--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableModal/TableModal.tsx@@ -0,0 +1,112 @@+import { useLatest } from "react-use";+import { match } from "ts-pattern";+import { t } from "ttag";++import { CollectionPickerModal } from "metabase/common/components/Pickers";+import { useSetCollection } from "metabase/common/hooks/use-set-collection";+import { PLUGIN_LIBRARY } from "metabase/plugins";+import { useNavigate } from "metabase/router";+import * as Urls from "metabase/urls";+import type { CollectionId, CollectionItem, Table } from "metabase-types/api";++export type TableModalTable =+ | Pick<CollectionItem, "id" | "database_id" | "collection_id">+ | Pick<Table, "id" | "db_id" | "collection_id">;++type MoveTableModalState = {+ type: "move";+ table: TableModalTable;+};++type UnpublishTableModalState = {+ type: "unpublish";+ table: TableModalTable;+};++export type TableModalState = MoveTableModalState | UnpublishTableModalState;++type TableModalProps = {+ modal: TableModalState | undefined;+ onClose: () => void;+};++export function TableModal({ modal, onClose }: TableModalProps) {+ const currentModalRef = useLatest(modal);++ if (modal === undefined) {+ return null;+ }++ const handleClose = () => {+ if (currentModalRef.current === modal) {+ onClose();+ }+ };++ return match(modal)+ .with({ type: "move" }, ({ table }) => (+ <MoveTableModal table={table} onClose={handleClose} />+ ))+ .with({ type: "unpublish" }, ({ table }) => (+ <UnpublishTableModal table={table} onClose={handleClose} />+ ))+ .exhaustive();+}++type TableModalContentProps = {+ table: TableModalTable;+ onClose: () => void;+};++function MoveTableModal({ table, onClose }: TableModalContentProps) {+ const setCollection = useSetCollection();++ const handleMove = async (newCollection: { id: CollectionId }) => {+ await setCollection(+ { model: "table", id: table.id },+ { id: newCollection.id },+ { notify: false },+ );+ onClose();+ };++ return (+ <CollectionPickerModal+ title={t`Move table to…`}+ value={{+ id: table.collection_id ?? "root",+ model: "collection",+ }}+ onChange={handleMove}+ onClose={onClose}+ options={{+ hasLibrary: true,+ hasRootCollection: false,+ hasPersonalCollections: false,+ hasSearch: true,+ hasRecents: false,+ hasConfirmButtons: true,+ confirmButtonText: t`Move`,+ }}+ entityType="table"+ />+ );+}++function UnpublishTableModal({ table, onClose }: TableModalContentProps) {+ const navigate = useNavigate();++ const handleUnpublish = () => {+ onClose();+ navigate(Urls.dataStudioLibrary());+ };++ return (+ <PLUGIN_LIBRARY.UnpublishTablesModal+ isOpened+ tableIds={[table.id]}+ onUnpublish={handleUnpublish}+ onClose={onClose}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableModal/index.tsnew file mode 100644index 00000000000..00bad7517a7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableModal/index.ts@@ -0,0 +1,2 @@+export type { TableModalState, TableModalTable } from "./TableModal";+export { TableModal } from "./TableModal";diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.tsxindex d7adf6afeff..1bf45f32278 100644--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.tsx+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.tsx@@ -1,6 +1,11 @@import cx from "classnames";+import { useState } from "react";import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "metabase/common/collections/components/CollectionRowModal";import CS from "metabase/css/core/index.css";import { Ellipsified, Icon } from "metabase/ui";import type { Collection, CollectionId } from "metabase-types/api";@@ -16,34 +21,45 @@ export function CollectionRow({item: collection,setSnippetCollectionId,}: CollectionRowProps) {+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();const onSelectCollection = () => {setSnippetCollectionId?.(collection.id);};return (- <div- className={cx(- { [cx(CS.bgLightHover, CS.cursorPointer)]: !collection.archived },- CS.hoverParent,- CS.hoverVisibility,- CS.flex,- CS.alignCenter,- CS.py1,- CS.px3,- CS.textBrand,- )}- {...(collection.archived ? undefined : { onClick: onSelectCollection })}- >- <Icon- name="folder"- size={ICON_SIZE}- style={{ opacity: 0.25 }}- className={CS.flexNoShrink}+ <>+ <div+ className={cx(+ { [cx(CS.bgLightHover, CS.cursorPointer)]: !collection.archived },+ CS.hoverParent,+ CS.hoverVisibility,+ CS.flex,+ CS.alignCenter,+ CS.py1,+ CS.px3,+ CS.textBrand,+ )}+ {...(collection.archived ? undefined : { onClick: onSelectCollection })}+ >+ <Icon+ name="folder"+ size={ICON_SIZE}+ style={{ opacity: 0.25 }}+ className={CS.flexNoShrink}+ />+ <Ellipsified className={cx(CS.flexFull, CS.ml1, CS.textBold)} flex={1}>+ {collection.name}+ </Ellipsified>+ <CollectionRowMenu+ collection={collection}+ onOpenModal={setCollectionModal}+ />+ </div>+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}/>- <Ellipsified className={cx(CS.flexFull, CS.ml1, CS.textBold)} flex={1}>- {collection.name}- </Ellipsified>- <CollectionRowMenu collection={collection} />- </div>+ </>);}diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionHeaderMenu/SnippetCollectionHeaderMenu.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionHeaderMenu/SnippetCollectionHeaderMenu.tsxnew file mode 100644index 00000000000..eb7ee1c0a38--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionHeaderMenu/SnippetCollectionHeaderMenu.tsx@@ -0,0 +1,32 @@+import { useState } from "react";++import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "metabase/common/collections/components/CollectionRowModal";+import type { Collection } from "metabase-types/api";++type SnippetCollectionHeaderMenuProps = {+ collection: Collection;+};++export function SnippetCollectionHeaderMenu({+ collection,+}: SnippetCollectionHeaderMenuProps) {+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();++ return (+ <>+ <CollectionRowMenu+ collection={collection}+ onOpenModal={setCollectionModal}+ />+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}+ />+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionHeaderMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionHeaderMenu/index.tsnew file mode 100644index 00000000000..db771a0aa3b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionHeaderMenu/index.ts@@ -0,0 +1 @@+export { SnippetCollectionHeaderMenu } from "./SnippetCollectionHeaderMenu";diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/index.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/index.tsxindex 8e8e5ee3a17..7a224c2656a 100644--- a/enterprise/frontend/src/metabase-enterprise/snippets/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/snippets/index.tsx@@ -1,6 +1,5 @@import { t } from "ttag";-import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";import { canonicalCollectionId } from "metabase/common/collections/utils";import {PLUGIN_SNIPPET_FOLDERS,@@ -13,6 +12,7 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";import { CollectionRow } from "./components/CollectionRow";import { MoveSnippetModal } from "./components/MoveSnippetModal";+import { SnippetCollectionHeaderMenu } from "./components/SnippetCollectionHeaderMenu";import { SnippetCollectionPermissionsModal } from "./components/SnippetCollectionPermissionsModal";import { SnippetCollectionPickerModal } from "./components/SnippetCollectionPickerModal";@@ -55,7 +55,7 @@ export function initializePlugin() {PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.push((snippetSidebar) => {const collection = snippetSidebar.props.snippetCollection;return (- <CollectionRowMenu+ <SnippetCollectionHeaderMenukey="snippet-collection-row-menu"collection={collection}/>diff --git a/frontend/src/metabase/api/table.ts b/frontend/src/metabase/api/table.tsindex abef3551d53..46114d691b2 100644--- a/frontend/src/metabase/api/table.ts+++ b/frontend/src/metabase/api/table.ts@@ -76,13 +76,14 @@ export const tableApi = Api.injectEndpoints({url: `/api/table/${id}`,body,}),- invalidatesTags: (_, error, { id }) =>+ invalidatesTags: (_, error, { id, collection_id }) =>invalidateTags(error, [idTag("table", id),tag("database"),tag("card"),tag("dataset"),listTag("erd"),+ ...(collection_id !== undefined ? [listTag("table")] : []),]),onQueryStarted: async ({ id, ...body },diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsx b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsxindex f2b65dd28fa..9b2d786e06c 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsx@@ -1,25 +1,14 @@-import { useDisclosure } from "@mantine/hooks";import { match } from "ts-pattern";import { t } from "ttag";-import {- actionApi,- collectionApi,- snippetApi,- transformApi,- useUpdateCollectionMutation,-} from "metabase/api";-import { listTag } from "metabase/api/tags";import { isRootCollection } from "metabase/common/collections/utils";-import { useConfirmation, useMetadataToasts } from "metabase/common/hooks";import { getUserIsAdmin } from "metabase/current-user";import {PLUGIN_LIBRARY,PLUGIN_REMOTE_SYNC,PLUGIN_SNIPPET_FOLDERS,} from "metabase/plugins";-import { useDispatch, useSelector } from "metabase/redux";-import { addUndo } from "metabase/redux/undo";+import { useSelector } from "metabase/redux";import {ActionIcon,Box,@@ -28,34 +17,26 @@ import {Menu,Tooltip,} from "metabase/ui";-import type { Collection, CollectionId } from "metabase-types/api";+import type { Collection } from "metabase-types/api";-import { EditCollectionModal } from "./EditCollectionModal";+import type { CollectionRowModalState } from "../CollectionRowModal";+import { UnarchiveCollectionButton } from "../UnarchiveCollectionButton";type CollectionRowMenuProps = {collection: Collection;- onSave?: (details: {- previousParentId: CollectionId | null;- newParentId: CollectionId | null;- }) => void;- onArchiveSuccess?: () => void;+ onOpenModal: (modal: CollectionRowModalState) => void;customArchiveMessage?: string;};-export function CollectionRowMenu(props: CollectionRowMenuProps) {- const { collection, onArchiveSuccess, onSave, customArchiveMessage } = props;- const dispatch = useDispatch();-+export function CollectionRowMenu({+ collection,+ onOpenModal,+ customArchiveMessage,+}: CollectionRowMenuProps) {const isAdmin = useSelector(getUserIsAdmin);- const [updateCollection] = useUpdateCollectionMutation();const remoteSyncReadOnly = useSelector(PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,);- const { show, modalContent: confirmationModal } = useConfirmation();- const [isEditModalOpen, { toggle: toggleEditModal }] = useDisclosure(false);- const [isPermissionsModalOpen, { toggle: togglePermissionsModal }] =- useDisclosure(false);- const { sendSuccessToast, sendErrorToast } = useMetadataToasts();const showPermissionsOption =isAdmin &&@@ -68,82 +49,8 @@ export function CollectionRowMenu(props: CollectionRowMenuProps) {return null;}- const invalidateTags = () => {- if (collection.namespace === "snippets") {- dispatch(snippetApi.util.invalidateTags([listTag("snippet")]));- } else if (collection.namespace === "transforms") {- dispatch(transformApi.util.invalidateTags([listTag("transform")]));- } else if (collection.namespace === "data-actions") {- dispatch(actionApi.util.invalidateTags([listTag("action")]));- dispatch(collectionApi.util.invalidateTags([listTag("collection")]));- } else {- dispatch(collectionApi.util.invalidateTags([listTag("collection")]));- }- };-- const handleArchive = async () => {- try {- await updateCollection({ id: collection.id, archived: true }).unwrap();- sendSuccessToast(t`"${collection.name}" has been archived`);- invalidateTags();- onArchiveSuccess?.();- } catch {- sendErrorToast(t`"${collection.name}" could not be archived`);- }- };-- const onArchiveClick = () => {- show({- title: t`Archive "${collection.name}"?`,- message: customArchiveMessage,- confirmButtonText: t`Archive`,- onConfirm: handleArchive,- });- };-if (collection.archived) {- const handleUnarchive = async () => {- try {- await updateCollection({ id: collection.id, archived: false }).unwrap();- void dispatch(- addUndo({- message: t`"${collection.name}" has been unarchived`,- action: async () => {- await updateCollection({ id: collection.id, archived: true });- invalidateTags();- },- }),- );- invalidateTags();- } catch (error) {- void dispatch(- addUndo({- message: t`"${collection.name}" could not be unarchived`,- icon: "warning",- }),- );- }- };-- const label = match(collection.namespace)- .with("snippets", () => t`Unarchive snippet folder`)- .with("data-actions", () => t`Unarchive folder`)- .otherwise(() => t`Unarchive collection`);-- return (- <Tooltip label={label}>- <ActionIcon- aria-label={label}- size="md"- onClick={(event) => {- event.stopPropagation();- void handleUnarchive();- }}- >- <FixedSizeIcon name="unarchive" c="text-primary" />- </ActionIcon>- </Tooltip>- );+ return <UnarchiveCollectionButton collection={collection} />;}const optionsLabel = match(collection.namespace)@@ -172,7 +79,7 @@ export function CollectionRowMenu(props: CollectionRowMenuProps) {{!isRoot && (<Menu.ItemleftSection={<Icon name="pencil" />}- onClick={toggleEditModal}+ onClick={() => onOpenModal({ type: "edit", collection })}>{isFolder ? t`Edit folder details` : t`Edit collection details`}</Menu.Item>@@ -180,7 +87,7 @@ export function CollectionRowMenu(props: CollectionRowMenuProps) {{showPermissionsOption && (<Menu.ItemleftSection={<Icon name="lock" />}- onClick={togglePermissionsModal}+ onClick={() => onOpenModal({ type: "permissions", collection })}>{t`Change permissions`}</Menu.Item>@@ -188,7 +95,13 @@ export function CollectionRowMenu(props: CollectionRowMenuProps) {{!isRoot && (<Menu.ItemleftSection={<Icon name="archive" />}- onClick={onArchiveClick}+ onClick={() =>+ onOpenModal({+ type: "archive",+ collection,+ customArchiveMessage,+ })+ }c="feedback-negative">{t`Archive`}@@ -196,28 +109,6 @@ export function CollectionRowMenu(props: CollectionRowMenuProps) {)}</Menu.Dropdown></Menu>- {confirmationModal}- {isEditModalOpen && (- <EditCollectionModal- collection={collection}- onSave={onSave}- onClose={toggleEditModal}- />- )}- {collection.namespace === "snippets" ? (- <PLUGIN_SNIPPET_FOLDERS.CollectionPermissionsModal- opened={isPermissionsModalOpen}- collectionId={collection.id}- onClose={togglePermissionsModal}- />- ) : (- <PLUGIN_LIBRARY.CollectionPermissionsModal- opened={isPermissionsModalOpen}- collectionId={collection.id}- namespace={collection.namespace}- onClose={togglePermissionsModal}- />- )}</Box>);}diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsxindex 39cfa52121f..5c06cca11ad 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx@@ -1,11 +1,16 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";+import { useState } from "react";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";-import { setupUpdateCollectionEndpoint } from "__support__/server-mocks";+import {+ setupCollectionByIdEndpoint,+ setupUpdateCollectionEndpoint,+ setupUpdateCollectionEndpointWithError,+} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state/state";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";import type { Collection, EnterpriseSettings } from "metabase-types/api";import {createMockCollection,@@ -13,21 +18,51 @@ import {createMockUser,} from "metabase-types/api/mocks";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "../CollectionRowModal";+import { CollectionRowMenu } from "./CollectionRowMenu";+type CollectionRowMenusWithModalProps = {+ collections: Collection[];+ customArchiveMessage?: string;+};++function CollectionRowMenusWithModal({+ collections,+ customArchiveMessage,+}: CollectionRowMenusWithModalProps) {+ const [modal, setModal] = useState<CollectionRowModalState>();+ return (+ <>+ {collections.map((collection) => (+ <CollectionRowMenu+ key={collection.id}+ collection={collection}+ customArchiveMessage={customArchiveMessage}+ onOpenModal={setModal}+ />+ ))}+ <CollectionRowModal modal={modal} onClose={() => setModal(undefined)} />+ </>+ );+}+interface SetupOptions {remoteSyncType?: EnterpriseSettings["remote-sync-type"];collection?: Partial<Collection>;+ otherCollection?: Partial<Collection>;isAdmin?: boolean;- onArchiveSuccess?: () => void;customArchiveMessage?: string;}const setup = ({remoteSyncType,collection,+ otherCollection,isAdmin = true,- onArchiveSuccess,customArchiveMessage,}: SetupOptions = {}) => {const state = createMockState({@@ -45,13 +80,16 @@ const setup = ({setupEnterpriseOnlyPlugin("remote_sync");return renderWithProviders(- <CollectionRowMenu- collection={createMockCollection(collection)}+ <CollectionRowMenusWithModal+ collections={[+ createMockCollection(collection),+ ...(otherCollection ? [createMockCollection(otherCollection)] : []),+ ]}customArchiveMessage={customArchiveMessage}- onArchiveSuccess={onArchiveSuccess}/>,{storeInitialState: state,+ withUndos: true,},);};@@ -112,12 +150,10 @@ describe("CollectionRowMenu", () => {it("archives a collection after confirmation", async () => {const collection = createMockCollection({ id: 1, name: "Archived soon" });- const onArchiveSuccess = jest.fn();setupUpdateCollectionEndpoint(collection);setup({collection,customArchiveMessage: "Custom archive warning",- onArchiveSuccess,});await openMenu();@@ -129,7 +165,9 @@ describe("CollectionRowMenu", () => {expect(screen.getByText("Custom archive warning")).toBeInTheDocument();await userEvent.click(screen.getByRole("button", { name: "Archive" }));- await waitFor(() => expect(onArchiveSuccess).toHaveBeenCalled());+ await waitFor(() =>+ expect(fetchMock.callHistory.called("update-collection-1")).toBe(true),+ );const request = fetchMock.callHistory.lastCall("update-collection-1",)?.request;@@ -157,6 +195,66 @@ describe("CollectionRowMenu", () => {)?.request;expect(await request?.json()).toEqual({ archived: false });});++ it("keeps a modal opened for another collection when an earlier edit finishes", async () => {+ const collection = createMockCollection({ id: 1, name: "First" });+ let finishUpdate: (collection: Collection) => void = () => undefined;+ setupUpdateCollectionEndpoint(+ collection,+ new Promise((resolve) => {+ finishUpdate = resolve;+ }),+ );+ setupCollectionByIdEndpoint({+ collections: [+ createMockCollection({ id: "root", name: "Our analytics" }),+ ],+ });+ setup({ collection, otherCollection: { id: 2, name: "Second" } });++ const [firstMenu, secondMenu] = screen.getAllByRole("button", {+ name: "Collection options",+ });+ await userEvent.click(firstMenu);+ await userEvent.click(getMenuItem(/Edit collection details/));+ await userEvent.type(screen.getByLabelText("Name"), " renamed");+ await userEvent.click(screen.getByRole("button", { name: "Save" }));+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await userEvent.click(secondMenu);+ await userEvent.click(getMenuItem(/Archive/));+ expect(screen.getByText('Archive "Second"?')).toBeInTheDocument();++ await act(async () => {+ finishUpdate(collection);+ await fetchMock.callHistory.flush(true);+ });++ expect(screen.getByText('Archive "Second"?')).toBeInTheDocument();+ });++ it("reports a failed undo of an unarchive", async () => {+ const collection = createMockCollection({+ id: 1,+ name: "Archived collection",+ archived: true,+ });+ setupUpdateCollectionEndpoint(collection);+ setup({ collection });++ await userEvent.click(+ screen.getByRole("button", { name: "Unarchive collection" }),+ );+ expect(+ await screen.findByText('"Archived collection" has been unarchived'),+ ).toBeInTheDocument();+ fetchMock.removeRoute(`update-collection-${collection.id}`);+ setupUpdateCollectionEndpointWithError(collection.id);+ await userEvent.click(screen.getByRole("button", { name: "Undo" }));++ expect(+ await screen.findByText('"Archived collection" could not be archived'),+ ).toBeInTheDocument();+ });});const openMenu = async () => {diff --git a/frontend/src/metabase/common/collections/components/CollectionRowModal/CollectionRowModal.tsx b/frontend/src/metabase/common/collections/components/CollectionRowModal/CollectionRowModal.tsxnew file mode 100644index 00000000000..1befd41cf7a--- /dev/null+++ b/frontend/src/metabase/common/collections/components/CollectionRowModal/CollectionRowModal.tsx@@ -0,0 +1,139 @@+import { useLatest } from "react-use";+import { match } from "ts-pattern";+import { t } from "ttag";++import { useUpdateCollectionMutation } from "metabase/api";+import { useInvalidateCollectionItems } from "metabase/common/collections/hooks";+import { ConfirmModal } from "metabase/common/components/ConfirmModal";+import { useMetadataToasts } from "metabase/common/hooks";+import { PLUGIN_LIBRARY, PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";+import type { Collection } from "metabase-types/api";++import { EditCollectionModal } from "./EditCollectionModal";++type EditCollectionModalState = {+ type: "edit";+ collection: Collection;+};++type CollectionPermissionsModalState = {+ type: "permissions";+ collection: Collection;+};++type ArchiveCollectionModalState = {+ type: "archive";+ collection: Collection;+ customArchiveMessage?: string;+};++export type CollectionRowModalState =+ | EditCollectionModalState+ | CollectionPermissionsModalState+ | ArchiveCollectionModalState;++type CollectionRowModalProps = {+ modal: CollectionRowModalState | undefined;+ onClose: () => void;+};++export function CollectionRowModal({+ modal,+ onClose,+}: CollectionRowModalProps) {+ const currentModalRef = useLatest(modal);++ if (modal === undefined) {+ return null;+ }++ const handleClose = () => {+ if (currentModalRef.current === modal) {+ onClose();+ }+ };++ return match(modal)+ .with({ type: "edit" }, ({ collection }) => (+ <EditCollectionModal collection={collection} onClose={handleClose} />+ ))+ .with({ type: "permissions" }, ({ collection }) => (+ <PermissionsModal collection={collection} onClose={handleClose} />+ ))+ .with({ type: "archive" }, ({ collection, customArchiveMessage }) => (+ <ArchiveCollectionModal+ collection={collection}+ customArchiveMessage={customArchiveMessage}+ onClose={handleClose}+ />+ ))+ .exhaustive();+}++type PermissionsModalProps = {+ collection: Collection;+ onClose: () => void;+};++function PermissionsModal({ collection, onClose }: PermissionsModalProps) {+ if (collection.namespace === "snippets") {+ return (+ <PLUGIN_SNIPPET_FOLDERS.CollectionPermissionsModal+ opened+ collectionId={collection.id}+ onClose={onClose}+ />+ );+ }++ return (+ <PLUGIN_LIBRARY.CollectionPermissionsModal+ opened+ collectionId={collection.id}+ namespace={collection.namespace}+ onClose={onClose}+ />+ );+}++type ArchiveCollectionModalProps = {+ collection: Collection;+ customArchiveMessage?: string;+ onClose: () => void;+};++function ArchiveCollectionModal({+ collection,+ customArchiveMessage,+ onClose,+}: ArchiveCollectionModalProps) {+ const [updateCollection] = useUpdateCollectionMutation();+ const invalidateCollectionItems = useInvalidateCollectionItems();+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();++ const handleArchive = async () => {+ onClose();+ const request = updateCollection({ id: collection.id, archived: true });+ try {+ await request.unwrap();+ sendSuccessToast(t`"${collection.name}" has been archived`);+ invalidateCollectionItems(collection);+ } catch {+ sendErrorToast(t`"${collection.name}" could not be archived`);+ } finally {+ request.reset();+ }+ };++ return (+ <ConfirmModal+ opened+ data-testid="confirm-modal"+ title={t`Archive "${collection.name}"?`}+ message={customArchiveMessage}+ confirmButtonText={t`Archive`}+ onConfirm={handleArchive}+ onClose={onClose}+ />+ );+}diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx b/frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/EditCollectionModal.tsxsimilarity index 90%rename from frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsxrename to frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/EditCollectionModal.tsxindex b441341f6f8..9f3334e3814 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/EditCollectionModal.tsx@@ -22,19 +22,11 @@ import {FormTextarea,} from "metabase/forms";import { Button, Group, Modal, Stack } from "metabase/ui";-import type {- Collection,- CollectionId,- CollectionItem,-} from "metabase-types/api";+import type { Collection, CollectionItem } from "metabase-types/api";type EditCollectionModalProps = {collection: Collection | CollectionItem;onClose: () => void;- onSave?: (details: {- previousParentId: CollectionId | null;- newParentId: CollectionId | null;- }) => void;};const isCollectionItem = (@@ -44,7 +36,7 @@ const isCollectionItem = (};export function EditCollectionModal(props: EditCollectionModalProps) {- const { collection, onClose, onSave } = props;+ const { collection, onClose } = props;const [updateCollection] = useUpdateCollectionMutation();const initialValues = useMemo<CollectionFormValues>(() => {const parentId = isCollectionItem(collection)@@ -65,13 +57,9 @@ export function EditCollectionModal(props: EditCollectionModalProps) {description: values.description ?? undefined,parent_id: values.parent_id,}).unwrap();- onSave?.({- previousParentId: initialValues.parent_id,- newParentId: values.parent_id,- });onClose();},- [collection.id, initialValues.parent_id, updateCollection, onSave, onClose],+ [collection.id, updateCollection, onClose],);const shouldDisableItem = useCallback(diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.unit.spec.tsx b/frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/EditCollectionModal.unit.spec.tsxsimilarity index 82%rename from frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.unit.spec.tsxrename to frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/EditCollectionModal.unit.spec.tsxindex 5762183e91d..244cf24c719 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.unit.spec.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/EditCollectionModal.unit.spec.tsx@@ -29,7 +29,6 @@ const itemParentCollection = createMockCollection({function setup(collection: Collection | CollectionItem) {const onClose = jest.fn();- const onSave = jest.fn();// Unjustified type cast. FIXMEsetupUpdateCollectionEndpoint(collection as Collection);@@ -38,17 +37,13 @@ function setup(collection: Collection | CollectionItem) {});renderWithProviders(- <EditCollectionModal- collection={collection}- onClose={onClose}- onSave={onSave}- />,+ <EditCollectionModal collection={collection} onClose={onClose} />,{storeInitialState: createMockState({}),},);- return { onClose, onSave };+ return { onClose };}describe("EditCollectionModal", () => {@@ -59,7 +54,7 @@ describe("EditCollectionModal", () => {description: "Original description",parent_id: parentCollection.id,});- const { onClose, onSave } = setup(collection);+ const { onClose } = setup(collection);await userEvent.clear(screen.getByLabelText("Name"));await userEvent.type(screen.getByLabelText("Name"), "Updated name");@@ -71,10 +66,6 @@ describe("EditCollectionModal", () => {await userEvent.click(screen.getByRole("button", { name: "Save" }));await waitFor(() => expect(onClose).toHaveBeenCalled());- expect(onSave).toHaveBeenCalledWith({- previousParentId: parentCollection.id,- newParentId: parentCollection.id,- });const request = fetchMock.callHistory.lastCall("update-collection-1",)?.request;@@ -93,17 +84,13 @@ describe("EditCollectionModal", () => {// Unjustified type cast. FIXMEcollection_id: itemParentCollection.id as number,});- const { onSave } = setup(collectionItem);+ const { onClose } = setup(collectionItem);await userEvent.clear(screen.getByLabelText("Name"));await userEvent.type(screen.getByLabelText("Name"), "Updated item name");await userEvent.click(screen.getByRole("button", { name: "Save" }));- await waitFor(() => expect(onSave).toHaveBeenCalled());- expect(onSave).toHaveBeenCalledWith({- previousParentId: itemParentCollection.id,- newParentId: itemParentCollection.id,- });+ await waitFor(() => expect(onClose).toHaveBeenCalled());const request = fetchMock.callHistory.lastCall("update-collection-2",)?.request;diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/index.ts b/frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/index.tssimilarity index 100%rename from frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/index.tsrename to frontend/src/metabase/common/collections/components/CollectionRowModal/EditCollectionModal/index.tsdiff --git a/frontend/src/metabase/common/collections/components/CollectionRowModal/index.ts b/frontend/src/metabase/common/collections/components/CollectionRowModal/index.tsnew file mode 100644index 00000000000..103bd3a43bf--- /dev/null+++ b/frontend/src/metabase/common/collections/components/CollectionRowModal/index.ts@@ -0,0 +1,2 @@+export type { CollectionRowModalState } from "./CollectionRowModal";+export { CollectionRowModal } from "./CollectionRowModal";diff --git a/frontend/src/metabase/common/collections/components/UnarchiveCollectionButton/UnarchiveCollectionButton.tsx b/frontend/src/metabase/common/collections/components/UnarchiveCollectionButton/UnarchiveCollectionButton.tsxnew file mode 100644index 00000000000..5fba8c39e12--- /dev/null+++ b/frontend/src/metabase/common/collections/components/UnarchiveCollectionButton/UnarchiveCollectionButton.tsx@@ -0,0 +1,84 @@+import { match } from "ts-pattern";+import { t } from "ttag";++import { useUpdateCollectionMutation } from "metabase/api";+import { useInvalidateCollectionItems } from "metabase/common/collections/hooks";+import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import { useDispatch, useSelector } from "metabase/redux";+import { addUndo } from "metabase/redux/undo";+import { ActionIcon, FixedSizeIcon, Tooltip } from "metabase/ui";+import type { Collection } from "metabase-types/api";++type UnarchiveCollectionButtonProps = {+ collection: Collection;+};++export function UnarchiveCollectionButton({+ collection,+}: UnarchiveCollectionButtonProps) {+ const dispatch = useDispatch();+ const [updateCollection] = useUpdateCollectionMutation();+ const invalidateCollectionItems = useInvalidateCollectionItems();+ const remoteSyncReadOnly = useSelector(+ PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,+ );++ const handleUnarchive = async () => {+ try {+ await updateCollection({ id: collection.id, archived: false }).unwrap();+ void dispatch(+ addUndo({+ message: t`"${collection.name}" has been unarchived`,+ action: async () => {+ const { error } = await updateCollection({+ id: collection.id,+ archived: true,+ });+ if (error) {+ void dispatch(+ addUndo({+ message: t`"${collection.name}" could not be archived`,+ icon: "warning",+ }),+ );+ } else {+ invalidateCollectionItems(collection);+ }+ },+ }),+ );+ invalidateCollectionItems(collection);+ } catch (error) {+ void dispatch(+ addUndo({+ message: t`"${collection.name}" could not be unarchived`,+ icon: "warning",+ }),+ );+ }+ };++ if (!collection.can_write || remoteSyncReadOnly) {+ return null;+ }++ const label = match(collection.namespace)+ .with("snippets", () => t`Unarchive snippet folder`)+ .with("data-actions", () => t`Unarchive folder`)+ .otherwise(() => t`Unarchive collection`);++ return (+ <Tooltip label={label}>+ <ActionIcon+ aria-label={label}+ size="md"+ onClick={(event) => {+ event.stopPropagation();+ void handleUnarchive();+ }}+ >+ <FixedSizeIcon name="unarchive" c="text-primary" />+ </ActionIcon>+ </Tooltip>+ );+}diff --git a/frontend/src/metabase/common/collections/components/UnarchiveCollectionButton/index.ts b/frontend/src/metabase/common/collections/components/UnarchiveCollectionButton/index.tsnew file mode 100644index 00000000000..0f6d2a7ef0c--- /dev/null+++ b/frontend/src/metabase/common/collections/components/UnarchiveCollectionButton/index.ts@@ -0,0 +1 @@+export { UnarchiveCollectionButton } from "./UnarchiveCollectionButton";diff --git a/frontend/src/metabase/common/collections/hooks.ts b/frontend/src/metabase/common/collections/hooks.tsindex e242729ab7a..5f23c4ac1fd 100644--- a/frontend/src/metabase/common/collections/hooks.ts+++ b/frontend/src/metabase/common/collections/hooks.ts@@ -1,10 +1,17 @@-import { useMemo } from "react";+import { useCallback, useMemo } from "react";-import { skipToken, useGetCollectionQuery } from "metabase/api";+import {+ actionApi,+ skipToken,+ snippetApi,+ transformApi,+ useGetCollectionQuery,+} from "metabase/api";+import { listTag } from "metabase/api/tags";import { ROOT_COLLECTION } from "metabase/common/collections/constants";import { getUser, getUserPersonalCollectionId } from "metabase/current-user";import { PLUGIN_COLLECTIONS } from "metabase/plugins";-import { useSelector } from "metabase/redux";+import { useDispatch, useSelector } from "metabase/redux";import type { Location } from "metabase/router";import * as Urls from "metabase/urls/collections";import type { Collection, CollectionId } from "metabase-types/api";@@ -124,3 +131,20 @@ export const useGetDefaultCollectionId = (// eslint-disable-next-line react-hooks/rules-of-hooks -- this won't change at runtime, so it's safereturn useOSSGetDefaultCollectionId(sourceCollectionId, options);};++export function useInvalidateCollectionItems() {+ const dispatch = useDispatch();++ return useCallback(+ (collection: Pick<Collection, "namespace">) => {+ if (collection.namespace === "snippets") {+ dispatch(snippetApi.util.invalidateTags([listTag("snippet")]));+ } else if (collection.namespace === "transforms") {+ dispatch(transformApi.util.invalidateTags([listTag("transform")]));+ } else if (collection.namespace === "data-actions") {+ dispatch(actionApi.util.invalidateTags([listTag("action")]));+ }+ },+ [dispatch],+ );+}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsxindex 94b67852a09..b6d8afeb9a8 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx@@ -2,6 +2,10 @@ import { 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 { ForwardRefLink } from "metabase/common/components/Link";import { LibraryTreePage } from "metabase/data-studio/common/components/LibraryTreePage";import { useErrorHandling } from "metabase/data-studio/common/hooks/use-error-handling";@@ -28,6 +32,8 @@ import { RootDataActionsMenu } from "./RootDataActionsMenu";export function ActionListPage() {const [searchQuery, setSearchQuery] = useState("");+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();const isRemoteSyncReadOnly = useSelector(PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,);@@ -55,6 +61,12 @@ export function ActionListPage() {() => tree.slice(0, 1).map((node) => node.id),[tree],);+ const renderRowMenu = useCallback(+ (item: TreeItem) => (+ <ActionRowMenu item={item} onOpenModal={setCollectionModal} />+ ),+ [],+ );return (<LibraryTreePage@@ -66,20 +78,30 @@ export function ActionListPage() {emptyMessage={t`No actions yet`}defaultExpandedIds={defaultExpandedIds}createMenu={canCreate && <ActionsCreateMenu />}- renderRowMenu={renderActionRowMenu}+ renderRowMenu={renderRowMenu}onSearchQueryChange={setSearchQuery}- />+ >+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}+ />+ </LibraryTreePage>);}-function renderActionRowMenu({ data }: TreeItem) {+type ActionRowMenuProps = {+ item: TreeItem;+ onOpenModal: (modal: CollectionRowModalState) => void;+};++function ActionRowMenu({ item: { data }, onOpenModal }: ActionRowMenuProps) {if (!isCollectionData(data)) {return null;}if (data.id === "root") {- return <RootDataActionsMenu />;+ return <RootDataActionsMenu collection={data} onOpenModal={onOpenModal} />;}- return <CollectionRowMenu collection={data} />;+ return <CollectionRowMenu collection={data} onOpenModal={onOpenModal} />;}function ActionsCreateMenu() {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 6d6a3029da6..67a6c038e01 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@@ -113,4 +113,24 @@ 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.tsxindex 944904c186a..08329ef81de 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/RootDataActionsMenu.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/RootDataActionsMenu/RootDataActionsMenu.tsx@@ -1,22 +1,29 @@-import { useDisclosure } from "@mantine/hooks";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";-export function RootDataActionsMenu() {+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 [isPermissionsModalOpen, { toggle: togglePermissionsModal }] =- useDisclosure(false);const optionsLabel = t`Data action options`;return (@@ -32,14 +39,11 @@ export function RootDataActionsMenu() {</ActionIcon></Tooltip></Menu.Target>- <Menu.Dropdown>+ <Menu.Dropdown onClick={(event) => event.stopPropagation()}>{canChangePermissions && (<Menu.ItemleftSection={<FixedSizeIcon name="lock" />}- onClick={(event) => {- event.stopPropagation();- togglePermissionsModal();- }}+ onClick={() => onOpenModal({ type: "permissions", collection })}>{t`Change permissions`}</Menu.Item>@@ -52,12 +56,6 @@ export function RootDataActionsMenu() {{t`View archived actions`}</Menu.Item></Menu.Dropdown>- <PLUGIN_LIBRARY.CollectionPermissionsModal- opened={isPermissionsModalOpen}- collectionId="root"- namespace="data-actions"- onClose={togglePermissionsModal}- /></Menu>);}diff --git a/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsxindex 746f5e63939..b0bef561e6f 100644--- a/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsx@@ -3,7 +3,7 @@ import { t } from "ttag";import { useUpdateActionMutation } from "metabase/api";import { getErrorMessage } from "metabase/api/utils";-import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";+import { UnarchiveCollectionButton } from "metabase/common/collections/components/UnarchiveCollectionButton";import { Link } from "metabase/common/components/Link";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";@@ -173,7 +173,7 @@ function ArchivedItemMenu({}if (isCollectionData(data)) {- return <CollectionRowMenu collection={data} />;+ return <UnarchiveCollectionButton collection={data} />;}return (diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsxindex d5886420e89..e1733af96a0 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsx+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsx@@ -24,7 +24,6 @@ import { PLUGIN_LIBRARY } from "metabase/plugins";import type { CollectionId, RegularCollectionId } from "metabase-types/api";import {- getAffectedCollectionIds,runLibraryItemUpdates,selectedItemToArchivable,selectedItemToMovable,@@ -37,10 +36,6 @@ type LibraryBulkActionsProps = {selectionSection: LibrarySection | null;isAllTables: boolean;defaultCollectionId: CollectionId | undefined;- onActionComplete: (- section: LibrarySection,- affectedCollectionIds: CollectionId[],- ) => void;getTrashMessage?: (section: LibrarySection,count: number,@@ -53,7 +48,6 @@ export function LibraryBulkActions({selectionSection,isAllTables,defaultCollectionId,- onActionComplete,getTrashMessage,onClear,}: LibraryBulkActionsProps) {@@ -83,24 +77,15 @@ export function LibraryBulkActions({const runBulkAction = async (applyToItem: (item: SelectedItem) => Promise<unknown>,- destinationId: CollectionId | null,toast: { success: string; error: (failedCount: number) => string },) => {- const section = selectionSection;- if (section == null) {- return;- }- const { failedCount, affectedCollectionIds } = await runLibraryItemUpdates(- selectedItems,- applyToItem,- destinationId,- );+ const failedCount = await runLibraryItemUpdates(selectedItems, applyToItem);if (failedCount > 0) {sendErrorToast(toast.error(failedCount));} else {sendSuccessToast(toast.success);}- onActionComplete(section, affectedCollectionIds);+ onClear();};const handleMove = async (destinationId: RegularCollectionId | null) => {@@ -112,7 +97,6 @@ export function LibraryBulkActions({{ id: destinationId ?? "root" },{ notify: false },),- destinationId,{success: t`Moved`,error: (failedCount) =>@@ -125,18 +109,14 @@ export function LibraryBulkActions({};const handleUnpublished = () => {- const section = selectionSection;setAction(undefined);- if (section != null) {- onActionComplete(section, getAffectedCollectionIds(selectedItems, null));- }+ onClear();};const handleTrash = () =>runBulkAction((item) =>setArchive(selectedItemToArchivable(item), true, { notify: false }),- null,{success: t`Moved to trash`,error: (failedCount) =>diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.ts b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.tsindex aa9c23cb8d6..a93bb141841 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.ts+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.ts@@ -3,12 +3,6 @@ import { match } from "ts-pattern";import type { ArchivableItem } from "metabase/archive/hooks";import type { MovableItem } from "metabase/common/hooks";import type { SelectedItem } from "metabase/data-studio/common/hooks/use-library-bulk-selection";-import type { CollectionId } from "metabase-types/api";--export type LibraryItemUpdateResult = {- failedCount: number;- affectedCollectionIds: CollectionId[];-};// Snippet-section folders map to `snippet-collection`; all others to `collection`.export function selectedItemToMovable(item: SelectedItem): MovableItem {@@ -66,32 +60,10 @@ export function selectedItemToArchivable(item: SelectedItem): ArchivableItem {.exhaustive();}-// Returns the touched collections so the caller can refresh subcollections held-// in local state; RTK tags already refresh the subscribed section-root lists.export async function runLibraryItemUpdates(items: SelectedItem[],applyToItem: (item: SelectedItem) => Promise<unknown>,- destinationId: CollectionId | null,-): Promise<LibraryItemUpdateResult> {+): Promise<number> {const results = await Promise.allSettled(items.map(applyToItem));- return {- failedCount: results.filter((r) => r.status === "rejected").length,- affectedCollectionIds: getAffectedCollectionIds(items, destinationId),- };-}--export function getAffectedCollectionIds(- items: SelectedItem[],- destinationId: CollectionId | null,-): CollectionId[] {- const ids = new Set<CollectionId>();- if (destinationId != null) {- ids.add(destinationId);- }- for (const item of items) {- if (item.sourceCollectionId != null) {- ids.add(item.sourceCollectionId);- }- }- return [...ids];+ return results.filter((result) => result.status === "rejected").length;}diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.unit.spec.ts b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.unit.spec.tsindex d882b3a75ef..018c2bda580 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.unit.spec.ts+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/utils.unit.spec.ts@@ -3,11 +3,7 @@ import type {SelectedItem,} from "metabase/data-studio/common/hooks/use-library-bulk-selection";-import {- getAffectedCollectionIds,- selectedItemToArchivable,- selectedItemToMovable,-} from "./utils";+import { selectedItemToArchivable, selectedItemToMovable } from "./utils";function item(model: SelectedItem["model"],@@ -31,17 +27,6 @@ function item(};}-describe("getAffectedCollectionIds", () => {- it("unions sources and destination, de-duplicated and excluding null", () => {- expect(- getAffectedCollectionIds(- [item("table", 1, 10), item("metric", 2, 11), item("snippet", 3, null)],- 99,- ).sort(),- ).toEqual([10, 11, 99]);- });-});-describe("selectedItemToMovable", () => {it("maps each model to the matching movable model, by id", () => {expect(selectedItemToMovable(item("table", 1, 10))).toEqual({diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsxindex 7678b643440..4855311f87c 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsx+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryTreePage.tsx@@ -1,5 +1,5 @@import type { Row } from "@tanstack/react-table";-import { type ReactNode, useCallback, useEffect } from "react";+import { type ReactNode, useEffect } from "react";import { t } from "ttag";import { ListEmptyState } from "metabase/common/components/ListEmptyState";@@ -51,10 +51,6 @@ type LibraryTreePageProps = {section: LibrarySection,count: number,) => string | undefined;- onBulkActionComplete?: (- section: LibrarySection,- affectedCollectionIds: CollectionId[],- ) => void;};export function LibraryTreePage({@@ -75,7 +71,6 @@ export function LibraryTreePage({onSearchQueryChange,emptyStateActions,getTrashMessage,- onBulkActionComplete,}: LibraryTreePageProps) {const isRemoteSyncReadOnly = useSelector(PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,@@ -111,14 +106,6 @@ export function LibraryTreePage({onRowsChange?.(treeTableInstance.rows);}, [treeTableInstance.rows, onRowsChange]);- const handleBulkActionComplete = useCallback(- (section: LibrarySection, affectedCollectionIds: CollectionId[]) => {- onBulkActionComplete?.(section, affectedCollectionIds);- clearSelection();- },- [onBulkActionComplete, clearSelection],- );-return (<><SectionLayout>@@ -186,7 +173,6 @@ export function LibraryTreePage({? defaultMoveCollectionIds?.[selectionSection]: undefined}- onActionComplete={handleBulkActionComplete}getTrashMessage={getTrashMessage}onClear={clearSelection}/>diff --git a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/index.ts b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/index.tsindex 0232c0cc78b..852f95b5fe0 100644--- a/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/index.ts+++ b/frontend/src/metabase/data-studio/common/hooks/use-library-bulk-selection/index.ts@@ -1,3 +1,2 @@export { useLibraryBulkSelection } from "./use-library-bulk-selection";export type { LibrarySection, SelectedItem } from "./utils";-export { getItemSection } from "./utils";diff --git a/frontend/src/metabase/data-studio/snippets/pages/ArchivedSnippetListPage/hooks.tsx b/frontend/src/metabase/data-studio/snippets/pages/ArchivedSnippetListPage/hooks.tsxindex 6b01adc0d6e..e3ebd474e24 100644--- a/frontend/src/metabase/data-studio/snippets/pages/ArchivedSnippetListPage/hooks.tsx+++ b/frontend/src/metabase/data-studio/snippets/pages/ArchivedSnippetListPage/hooks.tsx@@ -1,7 +1,7 @@import { useMemo } from "react";import { t } from "ttag";-import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";+import { UnarchiveCollectionButton } from "metabase/common/collections/components/UnarchiveCollectionButton";import type { TreeItem } from "metabase/data-studio/common/types";import {isCollectionData,@@ -54,7 +54,7 @@ export const useColumnDef = ({ handleUnarchiveClick }: ColumnDefProps) => {}if (isCollectionData(data)) {- return <CollectionRowMenu collection={data} />;+ return <UnarchiveCollectionButton collection={data} />;}return (diff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsx b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsxindex 0b8dcda99ed..ec86526ca5b 100644--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsx+++ b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/RootSnippetsCollectionMenu/RootSnippetsCollectionMenu.tsx@@ -1,29 +1,29 @@-import { useDisclosure } from "@mantine/hooks";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 { CollectionId } from "metabase-types/api";+import type { Collection } from "metabase-types/api";-type RootSnippetsCollectionMenu = {- collectionId: CollectionId;+type RootSnippetsCollectionMenuProps = {+ collection: Collection;+ onOpenModal: (modal: CollectionRowModalState) => void;};export const RootSnippetsCollectionMenu = ({- collectionId,-}: RootSnippetsCollectionMenu) => {+ collection,+ onOpenModal,+}: RootSnippetsCollectionMenuProps) => {const isAdmin = useSelector(getUserIsAdmin);const remoteSyncReadOnly = useSelector(PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,);const canChangePermissions =PLUGIN_SNIPPET_FOLDERS.isEnabled && isAdmin && !remoteSyncReadOnly;- const [showPermissionsModal, { toggle: togglePermissionsModal }] =- useDisclosure(false);const optionsLabel = t`Snippet collection options`;@@ -40,14 +40,11 @@ export const RootSnippetsCollectionMenu = ({</ActionIcon></Tooltip></Menu.Target>- <Menu.Dropdown>+ <Menu.Dropdown onClick={(e) => e.stopPropagation()}>{canChangePermissions && (<Menu.ItemleftSection={<FixedSizeIcon name="lock" />}- onClick={(e) => {- e.stopPropagation();- togglePermissionsModal();- }}+ onClick={() => onOpenModal({ type: "permissions", collection })}>{t`Change permissions`}</Menu.Item>@@ -60,11 +57,6 @@ export const RootSnippetsCollectionMenu = ({{t`View archived snippets`}</Menu.Item></Menu.Dropdown>- <PLUGIN_SNIPPET_FOLDERS.CollectionPermissionsModal- opened={showPermissionsModal}- collectionId={collectionId}- onClose={togglePermissionsModal}- /></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.tsxindex fe794d291f8..1118bc5bfa4 100644--- 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.tsx@@ -1,4 +1,5 @@import userEvent from "@testing-library/user-event";+import { useState } from "react";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import {@@ -9,10 +10,14 @@ import {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 { EnterpriseSettings } from "metabase-types/api";+import type { Collection, EnterpriseSettings } from "metabase-types/api";import {createMockCollection,createMockTokenFeatures,@@ -21,13 +26,34 @@ import {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" });+const collection = createMockCollection({+ id: "root",+ name: "SQL Snippets",+ namespace: "snippets",+});const setup = ({isEnterprise = true,@@ -59,7 +85,9 @@ const setup = ({<><Routepath="/"- element={<RootSnippetsCollectionMenu collectionId={collection.id} />}+ element={+ <RootSnippetsCollectionMenuWithModal collection={collection} />+ }/><Routepath={dataStudioArchivedSnippets()}diff --git a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsx b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsxindex a0f8bb02829..b40ad496377 100644--- a/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsx+++ b/frontend/src/metabase/data-studio/snippets/pages/SnippetListPage/SnippetListPage.tsx@@ -2,6 +2,10 @@ import { 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 { ForwardRefLink } from "metabase/common/components/Link";import { canUserCreateNativeQueries } from "metabase/current-user";import { LibraryTreePage } from "metabase/data-studio/common/components/LibraryTreePage";@@ -33,6 +37,8 @@ const SNIPPET_COLLECTION_PICKER_OPTIONS = {export function SnippetListPage() {const [searchQuery, setSearchQuery] = useState("");+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();const { tree, isLoading, error } = useBuildSnippetTree();useErrorHandling(error);@@ -45,6 +51,12 @@ export function SnippetListPage() {() => tree.slice(0, 1).map((node) => node.id),[tree],);+ const renderRowMenu = useCallback(+ (item: TreeItem) => (+ <SnippetRowMenu item={item} onOpenModal={setCollectionModal} />+ ),+ [],+ );return (<LibraryTreePage@@ -56,20 +68,32 @@ export function SnippetListPage() {emptyMessage={t`No snippets yet`}defaultExpandedIds={defaultExpandedIds}createMenu={<SnippetsCreateMenu />}- renderRowMenu={renderSnippetRowMenu}+ renderRowMenu={renderRowMenu}onSearchQueryChange={setSearchQuery}- />+ >+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}+ />+ </LibraryTreePage>);}-function renderSnippetRowMenu({ data }: TreeItem) {+type SnippetRowMenuProps = {+ item: TreeItem;+ onOpenModal: (modal: CollectionRowModalState) => void;+};++function SnippetRowMenu({ item: { data }, onOpenModal }: SnippetRowMenuProps) {if (!isCollectionData(data)) {return null;}if (data.id === "root") {- return <RootSnippetsCollectionMenu collectionId={data.id} />;+ return (+ <RootSnippetsCollectionMenu collection={data} onOpenModal={onOpenModal} />+ );}- return <CollectionRowMenu collection={data} />;+ return <CollectionRowMenu collection={data} onOpenModal={onOpenModal} />;}function SnippetsCreateMenu() {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 47f116b5303..c79b441dd28 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@@ -2,7 +2,9 @@ import userEvent from "@testing-library/user-event";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import {+ setupCollectionPermissionsGraphEndpoint,setupCollectionsEndpoints,+ setupGroupsEndpoint,setupNativeQuerySnippetEndpoints,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";@@ -132,4 +134,40 @@ describe("SnippetListPage", () => {screen.queryByRole("button", { name: /New/ }),).not.toBeInTheDocument();});++ it("keeps the root row expanded when clicking inside the permissions modal it opened", async () => {+ setupGroupsEndpoint([]);+ setupCollectionPermissionsGraphEndpoint({ revision: 1, groups: {} });+ setup({+ isEnterprise: true,+ 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 userEvent.click(+ screen.getByRole("menuitem", { name: /Change permissions/ }),+ );+ await userEvent.click(+ await within(screen.getByRole("dialog")).findByRole("heading", {+ name: /Permissions for/,+ }),+ );++ expect(screen.getByText("Orders filter")).toBeInTheDocument();+ });++ it("keeps the root row expanded when clicking inside the root options menu", async () => {+ setup({});++ expect(await screen.findByText("Orders filter")).toBeInTheDocument();+ await userEvent.click(+ screen.getByRole("button", { name: "Snippet collection options" }),+ );+ await userEvent.click(await screen.findByRole("menu"));++ expect(screen.getByText("Orders filter")).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/transforms/components/JobMoreMenu/DeleteJobModal/DeleteJobModal.tsx b/frontend/src/metabase/transforms/components/JobMoreMenu/DeleteJobModal/DeleteJobModal.tsxindex ac414d00d98..cb1106df7f9 100644--- a/frontend/src/metabase/transforms/components/JobMoreMenu/DeleteJobModal/DeleteJobModal.tsx+++ b/frontend/src/metabase/transforms/components/JobMoreMenu/DeleteJobModal/DeleteJobModal.tsx@@ -22,13 +22,7 @@ export function DeleteJobModal({onClose,}: DeleteJobModalProps) {return (- <Modal- title={t`Delete this job?`}- opened- padding="xxl"- onClose={onClose}- onClick={(event) => event.stopPropagation()}- >+ <Modal title={t`Delete this job?`} opened padding="xxl" onClose={onClose}><FocusTrap.InitialFocus /><DeleteJobForm job={job} onDelete={onDelete} onClose={onClose} /></Modal>diff --git a/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.tsx b/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.tsxindex 10025448144..46f0ece3cc8 100644--- a/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.tsx+++ b/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.tsx@@ -1,4 +1,4 @@-import { type MouseEvent, useState } from "react";+import type { MouseEvent } from "react";import { t } from "ttag";import { useUpdateTransformJobMutation } from "metabase/api";@@ -9,14 +9,20 @@ import * as Urls from "metabase/urls";import type { TransformJob } from "metabase-types/api";import { DeleteJobModal } from "./DeleteJobModal";-import type { JobMoreMenuModalType } from "./types";++type DeleteJobModalState = {+ type: "delete";+ job: TransformJob;+};++export type JobModalState = DeleteJobModalState;type JobMoreMenuProps = {job: TransformJob;+ onOpenModal: (modal: JobModalState) => void;};-export function JobMoreMenu({ job }: JobMoreMenuProps) {- const [modalType, setModalType] = useState<JobMoreMenuModalType>();+export function JobMoreMenu({ job, onOpenModal }: JobMoreMenuProps) {const [updateJob] = useUpdateTransformJobMutation();const { sendErrorToast, sendSuccessToast } = useMetadataToasts();@@ -33,30 +39,25 @@ export function JobMoreMenu({ job }: JobMoreMenuProps) {};return (- <>- <JobMenu- isDisabled={!job.active}- onOpenModal={setModalType}- onToggleDisabled={handleToggleDisabled}- />- {modalType != null && (- <JobModal- job={job}- modalType={modalType}- onClose={() => setModalType(undefined)}- />- )}- </>+ <JobMenu+ isDisabled={!job.active}+ onDeleteClick={() => onOpenModal({ type: "delete", job })}+ onToggleDisabled={handleToggleDisabled}+ />);}type JobMenuProps = {isDisabled: boolean;- onOpenModal: (modalType: JobMoreMenuModalType) => void;+ onDeleteClick: () => void;onToggleDisabled: () => void;};-function JobMenu({ isDisabled, onOpenModal, onToggleDisabled }: JobMenuProps) {+function JobMenu({+ isDisabled,+ onDeleteClick,+ onToggleDisabled,+}: JobMenuProps) {const handleIconClick = (event: MouseEvent) => {event.preventDefault();event.stopPropagation();@@ -76,10 +77,7 @@ function JobMenu({ isDisabled, onOpenModal, onToggleDisabled }: JobMenuProps) {>{isDisabled ? t`Re-enable` : t`Disable`}</Menu.Item>- <Menu.Item- leftSection={<Icon name="trash" />}- onClick={() => onOpenModal("delete")}- >+ <Menu.Item leftSection={<Icon name="trash" />} onClick={onDeleteClick}>{t`Delete`}</Menu.Item></Menu.Dropdown>@@ -88,27 +86,25 @@ function JobMenu({ isDisabled, onOpenModal, onToggleDisabled }: JobMenuProps) {}type JobModalProps = {- job: TransformJob;- modalType: JobMoreMenuModalType;+ modal: JobModalState | undefined;onClose: () => void;};-function JobModal({ job, modalType, onClose }: JobModalProps) {+export function JobModal({ modal, onClose }: JobModalProps) {const { sendSuccessToast } = useMetadataToasts();const navigate = useNavigate();+ if (modal === undefined) {+ return null;+ }+const handleDelete = () => {sendSuccessToast(t`Job deleted`);navigate(Urls.transformJobList());onClose();};- switch (modalType) {- case "delete":- return (- <DeleteJobModal job={job} onDelete={handleDelete} onClose={onClose} />- );- default:- return null;- }+ return (+ <DeleteJobModal job={modal.job} onDelete={handleDelete} onClose={onClose} />+ );}diff --git a/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.unit.spec.tsx b/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.unit.spec.tsxindex 3fc91d200f9..445a506a4f1 100644--- a/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.unit.spec.tsx+++ b/frontend/src/metabase/transforms/components/JobMoreMenu/JobMoreMenu.unit.spec.tsx@@ -1,18 +1,29 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";+import { useState } from "react";import { setupUpdateTransformJobEndpoint } from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";import type { TransformJob } from "metabase-types/api";import { createMockTransformJob } from "metabase-types/api/mocks";-import { JobMoreMenu } from "./JobMoreMenu";+import { JobModal, type JobModalState, JobMoreMenu } from "./JobMoreMenu";++function JobMoreMenuWithModal({ job }: { job: TransformJob }) {+ const [modal, setModal] = useState<JobModalState>();+ return (+ <>+ <JobMoreMenu job={job} onOpenModal={setModal} />+ <JobModal modal={modal} onClose={() => setModal(undefined)} />+ </>+ );+}function setup({job = createMockTransformJob(),}: { job?: TransformJob } = {}) {setupUpdateTransformJobEndpoint(job);- renderWithProviders(<JobMoreMenu job={job} />);+ renderWithProviders(<JobMoreMenuWithModal job={job} />);return { job };}diff --git a/frontend/src/metabase/transforms/components/JobMoreMenu/index.ts b/frontend/src/metabase/transforms/components/JobMoreMenu/index.tsindex 15c97ca8b46..e75fff0f9e2 100644--- a/frontend/src/metabase/transforms/components/JobMoreMenu/index.ts+++ b/frontend/src/metabase/transforms/components/JobMoreMenu/index.ts@@ -1 +1,2 @@-export * from "./JobMoreMenu";+export type { JobModalState } from "./JobMoreMenu";+export { JobModal, JobMoreMenu } from "./JobMoreMenu";diff --git a/frontend/src/metabase/transforms/components/JobMoreMenu/types.ts b/frontend/src/metabase/transforms/components/JobMoreMenu/types.tsdeleted file mode 100644index 45d964e3c3a..00000000000--- a/frontend/src/metabase/transforms/components/JobMoreMenu/types.ts+++ /dev/null@@ -1 +0,0 @@-export type JobMoreMenuModalType = "delete";diff --git a/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.tsx b/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.tsxindex 24b3f03c83c..690e750b498 100644--- a/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.tsx+++ b/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.tsx@@ -31,11 +31,16 @@ import * as Urls from "metabase/urls";import type { TransformJob } from "metabase-types/api";import { JobListMoreMenu } from "../../components/JobListMoreMenu";-import { JobMoreMenu } from "../../components/JobMoreMenu";+import {+ JobModal,+ type JobModalState,+ JobMoreMenu,+} from "../../components/JobMoreMenu";export const JobListPage = () => {const navigate = useNavigate();const [searchQuery, setSearchQuery] = useState("");+ const [jobModal, setJobModal] = useState<JobModalState>();const isAdmin = useSelector(getUserIsAdmin);@@ -89,7 +94,9 @@ export const JobListPage = () => {id: "actions",header: "",width: 48,- cell: ({ row }) => <JobMoreMenu job={row.original} />,+ cell: ({ row }) => (+ <JobMoreMenu job={row.original} onOpenModal={setJobModal} />+ ),},] satisfies TreeTableColumnDef<TransformJob>[]): []),@@ -156,6 +163,7 @@ export const JobListPage = () => {</Card></Flex></Stack>+ <JobModal modal={jobModal} onClose={() => setJobModal(undefined)} /></PageContainer>);};diff --git a/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsx b/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsxindex 0d3e53807c7..fa302d25382 100644--- a/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsx+++ b/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsx@@ -191,6 +191,23 @@ describe("JobListPage", () => {expect(visited.some((path) => path.includes("/jobs/1"))).toBe(false);});+ it("does not open the job when clicking inside its delete modal", async () => {+ const { router } = await setup({+ jobs: [createMockTransformJob({ id: 1, name: "Job", active: true })],+ isAdmin: true,+ });++ const row = await findRow(1);+ await userEvent.click(within(row).getByLabelText("ellipsis icon"));+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Delete/ }),+ );+ await userEvent.click(await screen.findByText("Delete this job?"));++ expect(screen.getByRole("dialog")).toBeInTheDocument();+ expect(router?.location.pathname).toBe(Urls.transformJobList());+ });+it("hides the row action menu for non-admin users", async () => {await setup({jobs: [createMockTransformJob({ id: 1, name: "Job", active: true })],diff --git a/frontend/src/metabase/transforms/pages/JobPage/JobPage.tsx b/frontend/src/metabase/transforms/pages/JobPage/JobPage.tsxindex 3504374bcc7..6077459eef8 100644--- a/frontend/src/metabase/transforms/pages/JobPage/JobPage.tsx+++ b/frontend/src/metabase/transforms/pages/JobPage/JobPage.tsx@@ -21,7 +21,11 @@ import type {} from "metabase-types/api";import { JobEditor } from "../../components/JobEditor";-import { JobMoreMenu } from "../../components/JobMoreMenu";+import {+ JobModal,+ type JobModalState,+ JobMoreMenu,+} from "../../components/JobMoreMenu";import { JobTabs } from "../../components/JobTabs";import { POLLING_INTERVAL } from "../../constants";@@ -87,6 +91,7 @@ function JobPageBody({onNameChange,}: JobPageBodyProps) {const [updateJob] = useUpdateTransformJobMutation();+ const [jobModal, setJobModal] = useState<JobModalState>();const { sendErrorToast, sendSuccessToast, sendUndoToast } =useMetadataToasts();@@ -133,16 +138,19 @@ function JobPageBody({};return (- <JobEditor- job={job}- menu={!readOnly && <JobMoreMenu job={job} />}- tabs={<JobTabs jobId={job.id} />}- readOnly={readOnly}- isCheckingPermissions={isCheckingPermissions}- onNameChange={onNameChange}- onScheduleChange={handleScheduleChange}- onTagListChange={handleTagListChange}- />+ <>+ <JobEditor+ job={job}+ menu={!readOnly && <JobMoreMenu job={job} onOpenModal={setJobModal} />}+ tabs={<JobTabs jobId={job.id} />}+ readOnly={readOnly}+ isCheckingPermissions={isCheckingPermissions}+ onNameChange={onNameChange}+ onScheduleChange={handleScheduleChange}+ onTagListChange={handleTagListChange}+ />+ <JobModal modal={jobModal} onClose={() => setJobModal(undefined)} />+ </>);}diff --git a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsxindex c7d67d64dea..6f09e0166ac 100644--- a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx+++ b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.tsx@@ -27,7 +27,11 @@ import {} from "metabase-types/api";import { JobHeader } from "../../components/JobHeader";-import { JobMoreMenu } from "../../components/JobMoreMenu";+import {+ JobModal,+ type JobModalState,+ JobMoreMenu,+} from "../../components/JobMoreMenu";import { JobTabs } from "../../components/JobTabs";import S from "./JobRunListPage.module.css";@@ -53,6 +57,7 @@ export function JobRunListPage() {TransformJobRunId | undefined>();const [isPolling, setIsPolling] = useState(false);+ const [jobModal, setJobModal] = useState<JobModalState>();const navigate = useNavigate();const { data: job } = useGetTransformJobQuery(jobId ?? skipToken);@@ -161,7 +166,9 @@ export function JobRunListPage() {{job !== undefined && (<JobHeaderjob={job}- menu={!readOnly && <JobMoreMenu job={job} />}+ menu={+ !readOnly && <JobMoreMenu job={job} onOpenModal={setJobModal} />+ }tabs={<JobTabs jobId={job.id} />}readOnly={readOnly}onNameChange={onNameChange}@@ -247,6 +254,7 @@ export function JobRunListPage() {onClose={() => setSelectedRunId(undefined)}/>)}+ <JobModal modal={jobModal} onClose={() => setJobModal(undefined)} /></Flex>);}diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsxindex 5d5041b90dc..6794cd1a4b5 100644--- a/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx+++ b/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx@@ -1,19 +1,22 @@import { msgid, ngettext, t } from "ttag";import { CollectionRowMenu as BaseCollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";+import type { CollectionRowModalState } from "metabase/common/collections/components/CollectionRowModal";import type { Collection } from "metabase-types/api";type CollectionRowMenuProps = {collection: Collection;transformCount: number;+ onOpenModal: (modal: CollectionRowModalState) => void;};export function CollectionRowMenu(props: CollectionRowMenuProps) {- const { collection, transformCount } = props;+ const { collection, transformCount, onOpenModal } = props;return (<BaseCollectionRowMenucollection={collection}+ onOpenModal={onOpenModal}customArchiveMessage={transformCount > 0? ngettext(diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsxindex f1835a1628c..befc2777869 100644--- a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx+++ b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx@@ -8,6 +8,10 @@ import {useListCollectionsTreeQuery,useListTransformsQuery,} from "metabase/api";+import {+ CollectionRowModal,+ type CollectionRowModalState,+} from "metabase/common/collections/components/CollectionRowModal";import { DateTime } from "metabase/common/components/DateTime";import { Link } from "metabase/common/components/Link";import { ListEmptyState } from "metabase/common/components/ListEmptyState";@@ -124,6 +128,8 @@ export const TransformListPage = () => {) ?? null;const hasScrolledRef = useRef(false);const [searchQuery, setSearchQuery] = useState("");+ const [collectionModal, setCollectionModal] =+ useState<CollectionRowModalState>();const hasPythonTransformsFeature = useHasTokenFeature("transforms-python");const isMeterLocked = useSetting("transforms-meter-locked");@@ -275,6 +281,7 @@ export const TransformListPage = () => {<CollectionRowMenucollection={row.original.collection}transformCount={countTransforms(row.original)}+ onOpenModal={setCollectionModal}/>) : null,},@@ -361,6 +368,10 @@ export const TransformListPage = () => {)}</Card></Stack>+ <CollectionRowModal+ modal={collectionModal}+ onClose={() => setCollectionModal(undefined)}+ /><Outlet /></PageContainer>);diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts b/frontend/src/metabase/transforms/pages/TransformListPage/utils.tsindex 685185f4bef..bacaf34d097 100644--- a/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts+++ b/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts@@ -90,8 +90,8 @@ export function useGetTransformWarnings(transforms: Transform[] | undefined) {// `columnDefs` (and therefore the TanStack TreeTable's column model) stays// stable across `metadata` reference churn. Without this, fetching a single// collection (e.g. opening the edit-collection modal) recomputes `metadata`,- // which propagates a new column reference, remounts row cells, and tears- // down any modal that lives inside `CollectionRowMenu`.+ // which propagates a new column reference, remounts row cells, and closes+ // any open row menu.const warningsRef = useRef(computedWarningsByTransformId);if (warningsRef.current !== computedWarningsByTransformId &&diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.tsindex 4814ca83571..4d11b4a85ae 100644--- a/frontend/test/__support__/server-mocks/collection.ts+++ b/frontend/test/__support__/server-mocks/collection.ts@@ -10,6 +10,7 @@ import {import type {Card,Collection,+ CollectionId,CollectionItem,Dashboard,DashboardQuestionCandidate,@@ -453,12 +454,23 @@ export function setupCreateCollectionEndpoint(});}-export function setupUpdateCollectionEndpoint(collection: Collection) {- fetchMock.put(`path:/api/collection/${collection.id}`, collection, {+export function setupUpdateCollectionEndpoint(+ collection: Collection,+ response: Collection | Promise<Collection> = collection,+) {+ fetchMock.put(`path:/api/collection/${collection.id}`, response, {name: `update-collection-${collection.id}`,});}+export function setupUpdateCollectionEndpointWithError(+ collectionId: CollectionId,+) {+ fetchMock.put(`path:/api/collection/${collectionId}`, 500, {+ name: `update-collection-${collectionId}`,+ });+}+export function setupDeleteCollectionEndpoint(collectionId: number) {fetchMock.delete(`path:/api/collection/${collectionId}`,