Skip to content

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

Uxw 4246 bulk actions in the library (#76558)

Nick Fitzpatrickd6285436bfe7
diff --git a/e2e/support/helpers/e2e-data-studio-helpers.ts b/e2e/support/helpers/e2e-data-studio-helpers.ts
index c3ba92e23b4..1ac09958c62 100644
--- a/e2e/support/helpers/e2e-data-studio-helpers.ts
+++ b/e2e/support/helpers/e2e-data-studio-helpers.ts
@@ -158,9 +158,20 @@ export const DataStudio = {
DataStudio.Library.allTableItems().contains(name),
result: (name: string) =>
libraryPage().findByText(name).closest('[role="row"]'),
+ rowCheckbox: (name: string) =>
+ DataStudio.Library.result(name).findByRole("checkbox"),
+ selectRow: (name: string) => DataStudio.Library.rowCheckbox(name).check(),
newButton: () => libraryPage().findByRole("button", { name: /New/ }),
collectionItem: (name: string | RegExp) =>
libraryPage().findAllByTestId("collection-name").contains(name),
+ expandCollection: (name: string) =>
+ DataStudio.Library.result(name)
+ .findByRole("button", { name: "Expand" })
+ .click(),
+ collapseCollection: (name: string) =>
+ DataStudio.Library.result(name)
+ .findByRole("button", { name: "Collapse" })
+ .click(),
emptyStateRow: (description: string | RegExp) =>
libraryPage().contains('[data-testid="empty-state-row"]', description),
},
diff --git a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts
index 732638e4dd0..fbfbc26a2aa 100644
--- a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts
@@ -8,7 +8,7 @@ import {
} from "e2e/support/test-library-data";
import type { Collection } from "metabase-types/api";
-const { ORDERS_ID } = SAMPLE_DATABASE;
+const { ORDERS_ID, PRODUCTS_ID, PEOPLE_ID, REVIEWS_ID } = SAMPLE_DATABASE;
type LibraryResponse = Collection & {
effective_children?: Collection[];
@@ -272,7 +272,7 @@ describe("scenarios > data studio > library", () => {
expect(response?.statusCode).to.equal(200);
});
- expandLibraryCollection("Destination Collection");
+ H.DataStudio.Library.expandCollection("Destination Collection");
H.DataStudio.Library.result("Collection To Move")
.should("be.visible")
.and("have.attr", "aria-level", "3");
@@ -339,7 +339,7 @@ describe("scenarios > data studio > library", () => {
expect(response?.statusCode).to.equal(200);
});
- expandLibraryCollection("Table Destination Collection");
+ H.DataStudio.Library.expandCollection("Table Destination Collection");
H.DataStudio.Library.result("Orders")
.should("be.visible")
.and("have.attr", "aria-level", "3");
@@ -477,6 +477,237 @@ describe("scenarios > data studio > library", () => {
});
});
});
+
+ describe("bulk actions", () => {
+ it("selects, moves, and unpublishes library items in bulk", () => {
+ H.createLibrary();
+ getLibraryRootCollections().then(
+ ({ dataCollection, metricCollection }) => {
+ H.publishTables({
+ table_ids: [ORDERS_ID, PRODUCTS_ID, PEOPLE_ID, REVIEWS_ID],
+ });
+ H.createQuestion({ ...TRUSTED_ORDERS_METRIC }).then(
+ ({ body: card }) => {
+ cy.request("PUT", `/api/card/${card.id}`, {
+ collection_id: metricCollection.id,
+ });
+ },
+ );
+ createLibraryCollection({
+ name: "Folder A",
+ parent_id: dataCollection.id,
+ });
+ createLibraryCollection({
+ name: "Folder B",
+ parent_id: dataCollection.id,
+ });
+ createLibraryCollection({
+ name: "Folder C",
+ parent_id: dataCollection.id,
+ });
+ createLibraryCollection({
+ name: "Folder D",
+ parent_id: dataCollection.id,
+ });
+ },
+ );
+ H.DataStudio.Library.visit();
+
+ cy.log("Section-root checkbox selects every item in the section");
+ H.DataStudio.Library.selectRow("Data");
+ H.DataStudio.Library.rowCheckbox("Orders").should("be.checked");
+ H.DataStudio.Library.rowCheckbox("Reviews").should("be.checked");
+ H.DataStudio.Library.rowCheckbox("Folder A").should("be.checked");
+ bulkBar().findByRole("button", { name: "Clear" }).click();
+ bulkBar().should("not.exist");
+
+ cy.log("Selection is limited to one section, replacing across sections");
+ H.DataStudio.Library.selectRow("Orders");
+ bulkBar().findByText("1 item selected").should("be.visible");
+ // A table is selected, so Move to trash is hidden (tables are unpublished).
+ bulkBar().findByText("Move to trash").should("not.exist");
+ H.DataStudio.Library.selectRow(TRUSTED_ORDERS_METRIC.name);
+ bulkBar().findByText("1 item selected").should("be.visible");
+ H.DataStudio.Library.rowCheckbox("Orders").should("not.be.checked");
+ H.DataStudio.Library.rowCheckbox(TRUSTED_ORDERS_METRIC.name).should(
+ "be.checked",
+ );
+ bulkBar().findByRole("button", { name: "Clear" }).click();
+ bulkBar().should("not.exist");
+
+ cy.log(
+ "Bulk-move tables into a sub-collection (picker defaults to Library)",
+ );
+ H.DataStudio.Library.selectRow("Products");
+ H.DataStudio.Library.selectRow("People");
+ bulkBar().findByText("2 items selected").should("be.visible");
+ bulkBar().findByRole("button", { name: "Move" }).click();
+ // Folder A (a Data sub-collection) is visible without navigating, proving
+ // the picker opened inside the Library rather than at Our analytics.
+ H.entityPickerModalItem(2, "Folder A").should("be.visible").click();
+ H.entityPickerModal().button("Move").click();
+ H.DataStudio.Library.expandCollection("Folder A");
+ H.DataStudio.Library.result("Products").should(
+ "have.attr",
+ "aria-level",
+ "3",
+ );
+ H.DataStudio.Library.result("People").should(
+ "have.attr",
+ "aria-level",
+ "3",
+ );
+
+ cy.log("Bulk-move a collection — can't move into itself; no Unpublish");
+ H.DataStudio.Library.selectRow("Folder B");
+ bulkBar().findByText("1 item selected").should("be.visible");
+ bulkBar().findByText("Unpublish").should("not.exist");
+ bulkBar().findByRole("button", { name: "Move" }).click();
+ H.entityPickerModal().within(() => {
+ H.entityPickerModalItem(2, "Folder B").should(
+ "have.attr",
+ "data-disabled",
+ );
+ H.entityPickerModalItem(2, "Folder C").click();
+ cy.button("Move").click();
+ });
+ H.DataStudio.Library.expandCollection("Folder C");
+ H.DataStudio.Library.result("Folder B").should(
+ "have.attr",
+ "aria-level",
+ "3",
+ );
+
+ cy.log("Bulk-unpublish removes the selected tables from the Library");
+ H.DataStudio.Library.selectRow("Orders");
+ H.DataStudio.Library.selectRow("Reviews");
+ bulkBar().findByText("2 items selected").should("be.visible");
+ bulkBar().findByRole("button", { name: "Unpublish" }).click();
+ H.modal().within(() => {
+ cy.findByText("Unpublish these tables?").should("be.visible");
+ cy.button("Unpublish these tables").click();
+ });
+
+ // Gate on positive signals (bar cleared, Folder A re-rendered) so the
+ // checks don't pass against the transient post-unpublish loading state.
+ bulkBar().should("not.exist");
+ H.DataStudio.Library.collectionItem("Folder A").should("be.visible");
+ H.DataStudio.Library.libraryPage()
+ .findByText("Orders")
+ .should("not.exist");
+ H.DataStudio.Library.libraryPage()
+ .findByText("Reviews")
+ .should("not.exist");
+
+ cy.log("Move multiple collections to trash (confirm warns of unpublish)");
+ H.DataStudio.Library.selectRow("Folder A");
+ H.DataStudio.Library.selectRow("Folder C");
+ bulkBar().findByText("2 items selected").should("be.visible");
+ bulkBar().findByText("Unpublish").should("not.exist");
+ bulkBar().findByRole("button", { name: "Move to trash" }).click();
+ H.modal().within(() => {
+ cy.findByText("Move to trash?").should("be.visible");
+ // Plural wording, since multiple collections are selected.
+ cy.findByText(/these collections will also unpublish/).should(
+ "be.visible",
+ );
+ cy.button("Move to trash").click();
+ });
+
+ bulkBar().should("not.exist");
+ H.DataStudio.Library.collectionItem("Folder D").should("be.visible");
+ H.DataStudio.Library.collectionItem("Folder A").should("not.exist");
+ H.DataStudio.Library.collectionItem("Folder C").should("not.exist");
+ });
+
+ it("subsumes a collection's descendants so moving the parent preserves nesting", () => {
+ H.createLibrary();
+ getLibraryRootCollections().then(({ dataCollection }) => {
+ createLibraryCollection({
+ name: "Parent Folder",
+ parent_id: dataCollection.id,
+ }).then((parent) => {
+ H.publishTables({ table_ids: [ORDERS_ID], collection_id: parent.id });
+ createLibraryCollection({
+ name: "Child Folder",
+ parent_id: parent.id,
+ });
+ });
+ createLibraryCollection({
+ name: "Target Folder",
+ parent_id: dataCollection.id,
+ });
+ });
+ H.DataStudio.Library.visit();
+
+ cy.log("Selecting the parent collection subsumes its table and folder");
+ H.DataStudio.Library.expandCollection("Parent Folder");
+ H.DataStudio.Library.selectRow("Orders");
+ bulkBar().findByText("1 item selected").should("be.visible");
+ H.DataStudio.Library.selectRow("Parent Folder");
+
+ H.DataStudio.Library.rowCheckbox("Orders").should("be.checked");
+ H.DataStudio.Library.rowCheckbox("Orders").should("be.disabled");
+ H.DataStudio.Library.result("Orders").should(
+ "have.attr",
+ "data-disabled",
+ );
+ H.DataStudio.Library.rowCheckbox("Child Folder").should("be.checked");
+ H.DataStudio.Library.rowCheckbox("Child Folder").should("be.disabled");
+ // The count reflects only the top level items selected
+ bulkBar().findByText("1 item selected").should("be.visible");
+
+ cy.log("Collapsing the parent keeps its subsumed selection intact");
+ H.DataStudio.Library.collapseCollection("Parent Folder");
+ H.DataStudio.Library.libraryPage()
+ .findByText("Orders")
+ .should("not.exist");
+ bulkBar().findByText("1 item selected").should("be.visible");
+
+ cy.log(
+ "Moving the collapsed parent carries the descendants, keeping nesting",
+ );
+ bulkBar().findByRole("button", { name: "Move" }).click();
+ H.entityPickerModal().within(() => {
+ H.entityPickerModalItem(2, "Target Folder").click();
+ cy.button("Move").click();
+ });
+
+ H.DataStudio.Library.expandCollection("Target Folder");
+ H.DataStudio.Library.result("Parent Folder").should(
+ "have.attr",
+ "aria-level",
+ "3",
+ );
+ H.DataStudio.Library.expandCollection("Parent Folder");
+ H.DataStudio.Library.result("Orders").should(
+ "have.attr",
+ "aria-level",
+ "4",
+ );
+ H.DataStudio.Library.result("Child Folder").should(
+ "have.attr",
+ "aria-level",
+ "4",
+ );
+ });
+
+ it("offers no bulk selection on remote-sync read-only instances", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+ H.updateEnterpriseSettings({
+ "remote-sync-url": "file:///tmp/library-read-only",
+ "remote-sync-type": "read-only",
+ });
+ H.DataStudio.Library.visit();
+
+ cy.log("Tables render, but there are no checkboxes (no bulk actions)");
+ H.DataStudio.Library.tableItem("Orders").should("be.visible");
+ H.DataStudio.Library.libraryPage()
+ .findByRole("checkbox")
+ .should("not.exist");
+ });
+ });
});
function getLibraryRootCollections(): Cypress.Chainable<LibraryRootCollections> {
@@ -532,8 +763,6 @@ function openTableOptions(name: string) {
.click();
}
-function expandLibraryCollection(name: string) {
- H.DataStudio.Library.result(name)
- .findByRole("button", { name: "Expand" })
- .click();
+function bulkBar() {
+ return cy.findByTestId("toast-card");
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx
index 4afb81cbddb..11814971c9e 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx
@@ -1,5 +1,6 @@
import { useDisclosure } from "@mantine/hooks";
-import { useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { match } from "ts-pattern";
import { t } from "ttag";
import { useListCollectionsTreeQuery } from "metabase/api";
@@ -8,31 +9,29 @@ import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/Da
import { PaneHeader } from "metabase/common/data-studio/components/PaneHeader";
import { useHasTokenFeature } from "metabase/common/hooks";
import { SectionLayout } from "metabase/data-studio/app/components/SectionLayout";
-import type { TreeItem } from "metabase/data-studio/common/types";
import { LibraryUpsellPage } from "metabase/data-studio/upsells/pages";
-import { Link } from "metabase/router";
+import { useSelector } from "metabase/redux";
import {
Card,
Flex,
Icon,
- type RenderRowLink,
Stack,
TextInput,
TreeTable,
TreeTableSkeleton,
} from "metabase/ui";
+import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
+import type { CollectionId } from "metabase-types/api";
import { LibraryEmptyState } from "../components/LibraryEmptyState";
import { CreateMenu } from "./components/CreateMenu";
+import { LibraryBulkActions } from "./components/LibraryBulkActions";
import { PublishTableModal } from "./components/PublishTableModal";
import { useLibraryCollections, useLibraryTreeTableInstance } from "./hooks";
-import { getTreeRowHref, getWritableCollection } from "./utils";
-
-const renderTreeRowLink: RenderRowLink<TreeItem> = (row, props) => {
- const href = getTreeRowHref(row);
- return href ? <Link to={href} {...props} /> : props.children;
-};
+import type { LibrarySection } from "./hooks/library-bulk-selection.utils";
+import { useLibraryBulkSelection } from "./hooks/useLibraryBulkSelection";
+import { getWritableCollection } from "./utils";
export function LibraryPage() {
const hasLibraryFeature = useHasTokenFeature("library");
@@ -45,6 +44,7 @@ export function LibraryPage() {
}
function LibraryPageContent() {
+ const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
const [searchQuery, setSearchQuery] = useState("");
const [
showPublishTableModal,
@@ -56,15 +56,22 @@ function LibraryPageContent() {
"exclude-archived": true,
"include-library": true,
});
- const { treeTableInstance, isChildrenLoading, isLoading, emptyMessage } =
- useLibraryTreeTableInstance({
- collections,
- isLoadingCollections,
- searchQuery,
- onPublishTableClick: openPublishTableModal,
- });
+ const {
+ treeTableInstance,
+ allRows,
+ isChildrenLoading,
+ isLoading,
+ emptyMessage,
+ refreshTableCollections,
+ refreshMetricCollections,
+ } = useLibraryTreeTableInstance({
+ collections,
+ isLoadingCollections,
+ searchQuery,
+ onPublishTableClick: openPublishTableModal,
+ });
- const { libraryCollection, tableCollection } =
+ const { libraryCollection, tableCollection, metricCollection } =
useLibraryCollections(collections);
const writableMetricCollection = useMemo(
() =>
@@ -73,6 +80,40 @@ function LibraryPageContent() {
[libraryCollection],
);
+ const {
+ selectedItems,
+ selectionSection,
+ isAllTables,
+ getSelectionState,
+ getRowCovered,
+ onCheckboxClick,
+ clear: clearSelection,
+ } = useLibraryBulkSelection(allRows);
+
+ // Clear selection when changing search query
+ const trimmedSearch = searchQuery.trim();
+ useEffect(() => {
+ clearSelection();
+ }, [trimmedSearch, clearSelection]);
+
+ const moveDefaultCollectionId = match(selectionSection)
+ .with("data", () => tableCollection?.id)
+ .with("metrics", () => metricCollection?.id)
+ .otherwise(() => undefined);
+
+ const handleActionComplete = useCallback(
+ (section: LibrarySection, affectedCollectionIds: CollectionId[]) => {
+ if (section === "data") {
+ refreshTableCollections(affectedCollectionIds);
+ } else if (section === "metrics") {
+ refreshMetricCollections(affectedCollectionIds);
+ }
+ // Snippet sections refetch via RTK tag invalidation.
+ clearSelection();
+ },
+ [refreshTableCollections, refreshMetricCollections, clearSelection],
+ );
+
return (
<>
<SectionLayout>
@@ -116,6 +157,10 @@ function LibraryPageContent() {
) : (
<TreeTable
instance={treeTableInstance}
+ showCheckboxes={!isRemoteSyncReadOnly}
+ getSelectionState={getSelectionState}
+ isRowDisabled={getRowCovered}
+ onCheckboxClick={onCheckboxClick}
emptyState={
emptyMessage ? (
<ListEmptyState label={emptyMessage} />
@@ -128,9 +173,8 @@ function LibraryPageContent() {
if (row.getCanExpand()) {
row.toggleExpanded();
}
- // Navigation for leaf nodes is handled by the link
+ // Leaf navigation is handled by the name link in the cell
}}
- renderRowLink={renderTreeRowLink}
isChildrenLoading={isChildrenLoading}
/>
)}
@@ -144,6 +188,16 @@ function LibraryPageContent() {
onClose={closePublishTableModal}
onPublished={closePublishTableModal}
/>
+ {!isRemoteSyncReadOnly && (
+ <LibraryBulkActions
+ selectedItems={selectedItems}
+ selectionSection={selectionSection}
+ isAllTables={isAllTables}
+ defaultCollectionId={moveDefaultCollectionId}
+ onActionComplete={handleActionComplete}
+ onClear={clearSelection}
+ />
+ )}
</>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsx
new file mode 100644
index 00000000000..3077e62883b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsx
@@ -0,0 +1,276 @@
+import { useCallback, useMemo, useState } from "react";
+import { msgid, ngettext, t } from "ttag";
+
+import { useSetArchive } from "metabase/archive/hooks";
+import {
+ BulkActionBar,
+ BulkActionButton,
+ BulkActionDangerButton,
+} from "metabase/common/components/BulkActionBar";
+import {
+ CollectionPickerModal,
+ type OmniPickerItem,
+} from "metabase/common/components/Pickers";
+import { useConfirmation, useSetCollection } from "metabase/common/hooks";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import type { CollectionId, RegularCollectionId } from "metabase-types/api";
+
+import { UnpublishTablesModal } from "../../components/UnpublishTablesModal";
+import type {
+ LibrarySection,
+ SelectedItem,
+} from "../hooks/library-bulk-selection.utils";
+import {
+ getAffectedCollectionIds,
+ runLibraryItemUpdates,
+ selectedItemToArchivable,
+ selectedItemToMovable,
+} from "../hooks/library-item-updates";
+import { getArchiveLibraryCollectionsMessage } from "../utils";
+
+type BulkAction = "move" | "unpublish";
+
+type LibraryBulkActionsProps = {
+ selectedItems: SelectedItem[];
+ selectionSection: LibrarySection | null;
+ isAllTables: boolean;
+ defaultCollectionId: CollectionId | undefined;
+ onActionComplete: (
+ section: LibrarySection,
+ affectedCollectionIds: CollectionId[],
+ ) => void;
+ onClear: () => void;
+};
+
+export function LibraryBulkActions({
+ selectedItems,
+ selectionSection,
+ isAllTables,
+ defaultCollectionId,
+ onActionComplete,
+ onClear,
+}: LibraryBulkActionsProps) {
+ const [action, setAction] = useState<BulkAction>();
+ const setCollection = useSetCollection();
+ const setArchive = useSetArchive();
+ const { show: showConfirm, modalContent: confirmModal } = useConfirmation();
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
+
+ const count = selectedItems.length;
+ const message = ngettext(
+ msgid`${count} item selected`,
+ `${count} items selected`,
+ count,
+ );
+
+ const hasTables = selectedItems.some((item) => item.model === "table");
+
+ // A collection can't be moved into itself or one of its descendants.
+ const movingCollectionIds = useMemo(
+ () =>
+ selectedItems
+ .filter((item) => item.model === "collection")
+ .map((item) => String(item.entityId)),
+ [selectedItems],
+ );
+
+ 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,
+ );
+ if (failedCount > 0) {
+ sendErrorToast(toast.error(failedCount));
+ } else {
+ sendSuccessToast(toast.success);
+ }
+ onActionComplete(section, affectedCollectionIds);
+ };
+
+ const handleMove = async (destinationId: RegularCollectionId | null) => {
+ try {
+ await runBulkAction(
+ (item) =>
+ setCollection(
+ selectedItemToMovable(item),
+ { id: destinationId ?? "root" },
+ { notify: false },
+ ),
+ destinationId,
+ {
+ success: t`Moved`,
+ error: (failedCount) =>
+ t`Couldn't move ${failedCount} of ${count} items`,
+ },
+ );
+ } finally {
+ setAction(undefined);
+ }
+ };
+
+ const handleUnpublished = () => {
+ const section = selectionSection;
+ setAction(undefined);
+ if (section != null) {
+ onActionComplete(section, getAffectedCollectionIds(selectedItems, null));
+ }
+ };
+
+ const handleTrash = () =>
+ runBulkAction(
+ (item) =>
+ setArchive(selectedItemToArchivable(item), true, { notify: false }),
+ null,
+ {
+ success: t`Moved to trash`,
+ error: (failedCount) =>
+ t`Couldn't move ${failedCount} of ${count} items to trash`,
+ },
+ );
+
+ const confirmTrash = () => {
+ showConfirm({
+ title: t`Move to trash?`,
+ message:
+ selectionSection === "data"
+ ? getArchiveLibraryCollectionsMessage(count)
+ : undefined,
+ confirmButtonText: t`Move to trash`,
+ onConfirm: handleTrash,
+ });
+ };
+
+ return (
+ <>
+ <BulkActionBar opened={count > 0} message={message}>
+ <BulkActionButton onClick={() => setAction("move")}>
+ {t`Move`}
+ </BulkActionButton>
+ {!hasTables && (
+ <BulkActionButton onClick={confirmTrash}>
+ {t`Move to trash`}
+ </BulkActionButton>
+ )}
+ {isAllTables && (
+ <BulkActionDangerButton onClick={() => setAction("unpublish")}>
+ {t`Unpublish`}
+ </BulkActionDangerButton>
+ )}
+ <BulkActionButton onClick={onClear}>{t`Clear`}</BulkActionButton>
+ </BulkActionBar>
+ {action === "move" && selectionSection != null && (
+ <LibraryMoveModal
+ section={selectionSection}
+ initialCollectionId={
+ selectedItems[0]?.sourceCollectionId ?? defaultCollectionId ?? null
+ }
+ movingCollectionIds={movingCollectionIds}
+ onMove={handleMove}
+ onClose={() => setAction(undefined)}
+ />
+ )}
+ {action === "unpublish" && (
+ <UnpublishTablesModal
+ isOpened
+ tableIds={selectedItems.map((item) => item.entityId)}
+ onUnpublish={handleUnpublished}
+ onClose={() => setAction(undefined)}
+ />
+ )}
+ {confirmModal}
+ </>
+ );
+}
+
+export function isMoveDestinationDisabled(
+ item: OmniPickerItem,
+ movingCollectionIds: string[],
+): boolean {
+ if (item.model !== "collection" || movingCollectionIds.length === 0) {
+ return false;
+ }
+ const fullPath = (item.effective_location ?? item.location ?? "")
+ .split("/")
+ .filter(Boolean)
+ .concat(String(item.id));
+ return fullPath.some((id) => movingCollectionIds.includes(id));
+}
+
+type LibraryMoveModalProps = {
+ section: LibrarySection;
+ initialCollectionId: CollectionId | null;
+ movingCollectionIds: string[];
+ onMove: (destinationId: RegularCollectionId | null) => void;
+ onClose: () => void;
+};
+
+function LibraryMoveModal({
+ section,
+ initialCollectionId,
+ movingCollectionIds,
+ onMove,
+ onClose,
+}: LibraryMoveModalProps) {
+ const isDisabledItem = useCallback(
+ (item: OmniPickerItem) =>
+ isMoveDestinationDisabled(item, movingCollectionIds),
+ [movingCollectionIds],
+ );
+
+ if (section === "snippets") {
+ return (
+ <CollectionPickerModal
+ title={t`Move to…`}
+ value={undefined}
+ onChange={(destination) =>
+ onMove(destination.id === "root" ? null : destination.id)
+ }
+ onClose={onClose}
+ namespaces={["snippets"]}
+ isDisabledItem={isDisabledItem}
+ options={{
+ hasPersonalCollections: false,
+ canCreateCollections: true,
+ hasRootCollection: true,
+ hasSearch: false,
+ hasConfirmButtons: true,
+ hasRecents: false,
+ hasLibrary: false,
+ }}
+ />
+ );
+ }
+
+ return (
+ <CollectionPickerModal
+ title={t`Move to…`}
+ value={
+ initialCollectionId != null
+ ? { id: initialCollectionId, model: "collection" }
+ : undefined
+ }
+ onChange={(destination) => onMove(destination.id)}
+ onClose={onClose}
+ isDisabledItem={isDisabledItem}
+ options={{
+ hasLibrary: true,
+ hasRootCollection: false,
+ hasPersonalCollections: false,
+ hasSearch: true,
+ hasRecents: false,
+ hasConfirmButtons: true,
+ confirmButtonText: t`Move`,
+ }}
+ entityType={section === "data" ? "table" : "metric"}
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.unit.spec.tsx
new file mode 100644
index 00000000000..40bf2db690d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.unit.spec.tsx
@@ -0,0 +1,61 @@
+import { createMockCollectionItem } from "metabase-types/api/mocks";
+
+import { isMoveDestinationDisabled } from "./LibraryBulkActions";
+
+describe("isMoveDestinationDisabled", () => {
+ const moving = ["5"]; // collection 5 is being moved
+
+ it("disables the collection being moved (can't move into itself)", () => {
+ expect(
+ isMoveDestinationDisabled(
+ createMockCollectionItem({
+ id: 5,
+ model: "collection",
+ location: "/1/",
+ }),
+ moving,
+ ),
+ ).toBe(true);
+ });
+
+ it("disables a descendant of a collection being moved", () => {
+ expect(
+ isMoveDestinationDisabled(
+ createMockCollectionItem({
+ id: 7,
+ model: "collection",
+ location: "/1/5/",
+ }),
+ moving,
+ ),
+ ).toBe(true);
+ });
+
+ it("allows unrelated collections", () => {
+ expect(
+ isMoveDestinationDisabled(
+ createMockCollectionItem({
+ id: 8,
+ model: "collection",
+ location: "/1/",
+ }),
+ moving,
+ ),
+ ).toBe(false);
+ });
+
+ it("never disables non-collection items or when nothing is a collection", () => {
+ expect(
+ isMoveDestinationDisabled(
+ createMockCollectionItem({ id: 9, model: "table", location: "/1/5/" }),
+ moving,
+ ),
+ ).toBe(false);
+ expect(
+ isMoveDestinationDisabled(
+ createMockCollectionItem({ id: 5, model: "collection" }),
+ [],
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx
index 3be4aa23eec..a711ce76ebe 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx
@@ -1,10 +1,11 @@
import { useCallback } from "react";
-import { t } from "ttag";
import _ from "underscore";
import { CollectionRowMenu } from "metabase/common/collections/components/CollectionRowMenu";
import type { Collection, CollectionId } from "metabase-types/api";
+import { getArchiveLibraryCollectionsMessage } from "../utils";
+
type LibraryCollectionRowMenuProps = {
childCount: number;
collection: Collection;
@@ -52,7 +53,7 @@ export function LibraryCollectionRowMenu(props: LibraryCollectionRowMenuProps) {
}}
customArchiveMessage={
isLibraryDataCollection && childCount > 0
- ? t`Archiving this collection will also unpublish the tables inside it and archive any other child items.`
+ ? getArchiveLibraryCollectionsMessage(1)
: undefined
}
onArchiveSuccess={onArchiveSuccess}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx
index 18b82a364a1..e9da163fd80 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx
@@ -117,7 +117,7 @@ describe("LibraryCollectionRowMenu", () => {
expect(
screen.getByText(
- "Archiving this collection will also unpublish the tables inside it and archive any other child items.",
+ "Archiving this collection will also unpublish the tables inside it (and any tables that depend on them) and archive any other child items.",
),
).toBeInTheDocument();
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.ts
new file mode 100644
index 00000000000..79e7dfa67f2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.ts
@@ -0,0 +1,232 @@
+import {
+ canonicalCollectionId,
+ isRootCollection,
+} from "metabase/common/collections/utils";
+import type {
+ CollectionData,
+ TreeItem,
+} from "metabase/data-studio/common/types";
+import type { SelectionState } from "metabase/ui";
+import type {
+ CollectionId,
+ CollectionItem,
+ DatabaseId,
+} from "metabase-types/api";
+
+export type LibrarySection = "data" | "metrics" | "snippets";
+
+export type SelectableModel = "table" | "metric" | "snippet" | "collection";
+
+export type SelectedItem = {
+ key: string;
+ model: SelectableModel;
+ section: LibrarySection;
+ entityId: number;
+ sourceCollectionId: CollectionId | null;
+ databaseId?: DatabaseId;
+ canWrite: boolean;
+};
+
+const isCollectionRow = (
+ item: TreeItem,
+): item is TreeItem & { data: CollectionData } => item.model === "collection";
+
+const isLeafRow = (
+ item: TreeItem,
+): item is TreeItem & {
+ model: "table" | "metric" | "snippet";
+ data: CollectionItem;
+} =>
+ item.model === "table" || item.model === "metric" || item.model === "snippet";
+
+const keyOf = (item: TreeItem): string => item.id;
+
+export function getSelectedKeySet(selected: TreeItem[]): Set<string> {
+ return new Set(selected.map(keyOf));
+}
+
+export function getItemSection(item: TreeItem): LibrarySection | null {
+ if (item.model === "table") {
+ return "data";
+ }
+ if (item.model === "metric") {
+ return "metrics";
+ }
+ if (item.model === "snippet") {
+ return "snippets";
+ }
+ if (isCollectionRow(item)) {
+ const { data } = item;
+ if (data.namespace === "snippets") {
+ return "snippets";
+ }
+ if (data.type === "library-metrics") {
+ return "metrics";
+ }
+ if (data.type === "library-data") {
+ return "data";
+ }
+ }
+ return null;
+}
+
+export function isSectionRoot(item: TreeItem): boolean {
+ if (!isCollectionRow(item)) {
+ return false;
+ }
+ const { data } = item;
+ return data.is_library_root === true || isRootCollection({ id: data.id });
+}
+
+export function isSelectableItem(item: TreeItem): boolean {
+ if (getItemSection(item) === null) {
+ return false;
+ }
+ if (item.model === "collection") {
+ return !isSectionRoot(item);
+ }
+ return true;
+}
+
+function getSectionDirectSelectables(sectionRoot: TreeItem): TreeItem[] {
+ return (sectionRoot.children ?? []).filter(isSelectableItem);
+}
+
+export function getSelectionSection(
+ selected: TreeItem[],
+): LibrarySection | null {
+ return selected.length > 0 ? getItemSection(selected[0]) : null;
+}
+
+function unionByKey(base: TreeItem[], additions: TreeItem[]): TreeItem[] {
+ const keys = getSelectedKeySet(base);
+ return [...base, ...additions.filter((item) => !keys.has(item.id))];
+}
+
+export function getRowSelectionState(
+ item: TreeItem,
+ selectedKeys: Set<string>,
+): SelectionState {
+ if (isSectionRoot(item)) {
+ const selectables = getSectionDirectSelectables(item);
+ if (selectables.length === 0) {
+ return "none";
+ }
+ const count = selectables.filter((s) => selectedKeys.has(s.id)).length;
+ if (count === 0) {
+ return "none";
+ }
+ return count === selectables.length ? "all" : "some";
+ }
+ if (isSelectableItem(item)) {
+ return selectedKeys.has(item.id) ? "all" : "none";
+ }
+ return "none";
+}
+
+export function toggleItem(selected: TreeItem[], item: TreeItem): TreeItem[] {
+ const section = getItemSection(item);
+ const current = getSelectionSection(selected);
+ if (current !== null && current !== section) {
+ return [item];
+ }
+ return getSelectedKeySet(selected).has(item.id)
+ ? selected.filter((s) => s.id !== item.id)
+ : [...selected, item];
+}
+
+export function toggleSectionRoot(
+ selected: TreeItem[],
+ sectionRoot: TreeItem,
+): TreeItem[] {
+ const selectables = getSectionDirectSelectables(sectionRoot);
+ if (selectables.length === 0) {
+ return selected;
+ }
+ const section = getItemSection(sectionRoot);
+ const current = getSelectionSection(selected);
+ if (current !== null && current !== section) {
+ return selectables;
+ }
+ const keys = getSelectedKeySet(selected);
+ const allSelected = selectables.every((s) => keys.has(s.id));
+ if (allSelected) {
+ const sectionKeys = new Set(selectables.map(keyOf));
+ return selected.filter((s) => !sectionKeys.has(s.id));
+ }
+ return unionByKey(selected, selectables);
+}
+
+export function isAllTables(selected: TreeItem[]): boolean {
+ return (
+ selected.length > 0 && selected.every((item) => item.model === "table")
+ );
+}
+
+export function getCoveredKeys(
+ childrenByKey: Map<string, string[]>,
+ selectedKeys: Set<string>,
+): Set<string> {
+ const covered = new Set<string>();
+ const collectDescendants = (key: string) => {
+ for (const child of childrenByKey.get(key) ?? []) {
+ if (!covered.has(child)) {
+ covered.add(child);
+ collectDescendants(child);
+ }
+ }
+ };
+ for (const key of selectedKeys) {
+ collectDescendants(key);
+ }
+ return covered;
+}
+
+// Drops descendants whose ancestor collection is also selected, so bulk actions
+// apply only to the top-level parents and preserve the nesting underneath them.
+export function getEffectiveSelected(
+ selected: TreeItem[],
+ coveredKeys: Set<string>,
+): TreeItem[] {
+ if (coveredKeys.size === 0) {
+ return selected;
+ }
+ return selected.filter((item) => !coveredKeys.has(item.id));
+}
+
+export function deriveSelectedItems(selected: TreeItem[]): SelectedItem[] {
+ return selected.map((item): SelectedItem => {
+ const section = getItemSection(item);
+ if (section === null) {
+ throw new Error(`Cannot derive a selected item from row ${item.id}`);
+ }
+ if (isCollectionRow(item)) {
+ const { data } = item;
+ const entityId = canonicalCollectionId(data.id);
+ if (entityId === null) {
+ throw new Error(`Cannot derive a selected item from row ${item.id}`);
+ }
+ return {
+ key: item.id,
+ model: "collection",
+ section,
+ entityId,
+ sourceCollectionId: data.parent_id ?? null,
+ canWrite: data.can_write ?? false,
+ };
+ }
+ if (isLeafRow(item)) {
+ const { data } = item;
+ return {
+ key: item.id,
+ model: item.model,
+ section,
+ entityId: data.id,
+ sourceCollectionId: data.collection_id ?? null,
+ databaseId: data.database_id,
+ canWrite: data.can_write ?? false,
+ };
+ }
+ throw new Error(`Cannot derive a selected item from row ${item.id}`);
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.ts
new file mode 100644
index 00000000000..01e7051b1d5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.ts
@@ -0,0 +1,325 @@
+import type { TreeItem } from "metabase/data-studio/common/types";
+import type { CollectionId, CollectionType } from "metabase-types/api";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+} from "metabase-types/api/mocks";
+
+import {
+ type LibrarySection,
+ deriveSelectedItems,
+ getCoveredKeys,
+ getEffectiveSelected,
+ getItemSection,
+ getRowSelectionState,
+ getSelectedKeySet,
+ getSelectionSection,
+ isAllTables,
+ isSectionRoot,
+ isSelectableItem,
+ toggleItem,
+ toggleSectionRoot,
+} from "./library-bulk-selection.utils";
+
+const SECTION_TYPE: Record<LibrarySection, CollectionType | null> = {
+ data: "library-data",
+ metrics: "library-metrics",
+ snippets: null,
+};
+
+function tableItem(
+ id: number,
+ opts: { collectionId?: number | null; databaseId?: number } = {},
+): TreeItem {
+ return {
+ id: `table:${id}`,
+ name: `Table ${id}`,
+ icon: "table",
+ model: "table",
+ data: createMockCollectionItem({
+ id,
+ model: "table",
+ database_id: opts.databaseId ?? 1,
+ collection_id: opts.collectionId ?? null,
+ can_write: true,
+ }),
+ };
+}
+
+function metricItem(
+ id: number,
+ opts: { collectionId?: number | null } = {},
+): TreeItem {
+ return {
+ id: `metric:${id}`,
+ name: `Metric ${id}`,
+ icon: "metric",
+ model: "metric",
+ data: createMockCollectionItem({
+ id,
+ model: "metric",
+ collection_id: opts.collectionId ?? null,
+ can_write: true,
+ }),
+ };
+}
+
+function snippetItem(
+ id: number,
+ opts: { collectionId?: number | null } = {},
+): TreeItem {
+ return {
+ id: `snippet:${id}`,
+ name: `Snippet ${id}`,
+ icon: "snippet",
+ model: "snippet",
+ data: createMockCollectionItem({
+ id,
+ name: `Snippet ${id}`,
+ model: "snippet",
+ collection_id: opts.collectionId ?? null,
+ can_write: true,
+ }),
+ };
+}
+
+function subCollection(
+ id: number,
+ section: LibrarySection,
+ opts: {
+ parentId?: number | null;
+ children?: TreeItem[];
+ canWrite?: boolean;
+ } = {},
+): TreeItem {
+ return {
+ id: `collection:${id}`,
+ name: `Collection ${id}`,
+ icon: "folder",
+ model: "collection",
+ data: {
+ ...createMockCollection({
+ id,
+ type: SECTION_TYPE[section],
+ namespace: section === "snippets" ? "snippets" : null,
+ is_library_root: false,
+ parent_id: opts.parentId ?? null,
+ can_write: opts.canWrite ?? true,
+ }),
+ model: "collection",
+ },
+ children: opts.children,
+ };
+}
+
+function sectionRoot(section: LibrarySection, children: TreeItem[]): TreeItem {
+ const id: CollectionId = section === "snippets" ? "root" : 100;
+ return {
+ id: `collection:${id}`,
+ name: section,
+ icon: "folder",
+ model: "collection",
+ data: {
+ ...createMockCollection({
+ id,
+ type: SECTION_TYPE[section],
+ namespace: section === "snippets" ? "snippets" : null,
+ is_library_root: section !== "snippets",
+ }),
+ model: "collection",
+ },
+ children,
+ };
+}
+
+function emptyState(): TreeItem {
+ return {
+ id: "empty:data",
+ name: "empty",
+ icon: "table",
+ model: "empty-state",
+ data: {
+ model: "empty-state",
+ sectionType: "data",
+ description: "d",
+ actionLabel: "a",
+ },
+ };
+}
+
+const ids = (items: TreeItem[]) => items.map((item) => item.id);
+
+describe("library-bulk-selection.utils", () => {
+ describe("getItemSection", () => {
+ it("derives the section from model and collection type/namespace", () => {
+ expect(getItemSection(tableItem(1))).toBe("data");
+ expect(getItemSection(metricItem(1))).toBe("metrics");
+ expect(getItemSection(snippetItem(1))).toBe("snippets");
+ expect(getItemSection(subCollection(2, "data"))).toBe("data");
+ expect(getItemSection(subCollection(3, "metrics"))).toBe("metrics");
+ expect(getItemSection(subCollection(4, "snippets"))).toBe("snippets");
+ expect(getItemSection(emptyState())).toBeNull();
+ });
+ });
+
+ describe("isSectionRoot / isSelectableItem", () => {
+ it("treats section roots as non-selectable and content items as selectable", () => {
+ expect(isSectionRoot(sectionRoot("data", []))).toBe(true);
+ expect(isSectionRoot(sectionRoot("snippets", []))).toBe(true);
+ expect(isSectionRoot(subCollection(2, "data"))).toBe(false);
+
+ expect(isSelectableItem(tableItem(1))).toBe(true);
+ expect(isSelectableItem(metricItem(1))).toBe(true);
+ expect(isSelectableItem(snippetItem(1))).toBe(true);
+ expect(isSelectableItem(subCollection(2, "data"))).toBe(true);
+ expect(isSelectableItem(sectionRoot("data", []))).toBe(false);
+ expect(isSelectableItem(emptyState())).toBe(false);
+ });
+ });
+
+ describe("toggleItem", () => {
+ it("adds and removes within the same section", () => {
+ const t1 = tableItem(1);
+ const t2 = tableItem(2);
+ expect(ids(toggleItem([], t1))).toEqual(["table:1"]);
+ expect(ids(toggleItem([t1, t2], t1))).toEqual(["table:2"]);
+ });
+
+ it("allows mixing tables and sub-collections within one section", () => {
+ const t1 = tableItem(1);
+ const c1 = subCollection(5, "data");
+ expect(ids(toggleItem([t1], c1))).toEqual(["table:1", "collection:5"]);
+ });
+
+ it("replaces the selection when switching to a different section", () => {
+ const t1 = tableItem(1);
+ const m1 = metricItem(9);
+ expect(ids(toggleItem([t1], m1))).toEqual(["metric:9"]);
+ });
+ });
+
+ describe("toggleSectionRoot", () => {
+ it("selects all direct selectables, then deselects them", () => {
+ const t1 = tableItem(1);
+ const c1 = subCollection(5, "data");
+ const root = sectionRoot("data", [t1, c1, emptyState()]);
+
+ const selected = toggleSectionRoot([], root);
+ expect(ids(selected).sort()).toEqual(["collection:5", "table:1"]);
+ expect(toggleSectionRoot(selected, root)).toEqual([]);
+ });
+
+ it("switches section when the current selection is elsewhere", () => {
+ const metricsRoot = sectionRoot("metrics", [metricItem(7)]);
+ expect(ids(toggleSectionRoot([tableItem(1)], metricsRoot))).toEqual([
+ "metric:7",
+ ]);
+ });
+ });
+
+ describe("getRowSelectionState", () => {
+ it("reflects a selectable item's own state", () => {
+ const t1 = tableItem(1);
+ expect(getRowSelectionState(t1, getSelectedKeySet([t1]))).toBe("all");
+ expect(getRowSelectionState(t1, getSelectedKeySet([]))).toBe("none");
+ });
+
+ it("is tri-state for a section root over its direct selectables", () => {
+ const t1 = tableItem(1);
+ const t2 = tableItem(2);
+ const root = sectionRoot("data", [t1, t2]);
+ expect(getRowSelectionState(root, getSelectedKeySet([t1, t2]))).toBe(
+ "all",
+ );
+ expect(getRowSelectionState(root, getSelectedKeySet([t1]))).toBe("some");
+ expect(getRowSelectionState(root, getSelectedKeySet([]))).toBe("none");
+ });
+ });
+
+ describe("isAllTables", () => {
+ it("is true only when every selected item is a table", () => {
+ expect(isAllTables([tableItem(1), tableItem(2)])).toBe(true);
+ expect(isAllTables([tableItem(1), subCollection(5, "data")])).toBe(false);
+ expect(isAllTables([])).toBe(false);
+ });
+ });
+
+ describe("deriveSelectedItems", () => {
+ it("reads payload fields per model", () => {
+ const items = deriveSelectedItems([
+ tableItem(1, { collectionId: 10, databaseId: 3 }),
+ subCollection(5, "data", { parentId: 10 }),
+ ]);
+ expect(items).toEqual([
+ {
+ key: "table:1",
+ model: "table",
+ section: "data",
+ entityId: 1,
+ sourceCollectionId: 10,
+ databaseId: 3,
+ canWrite: true,
+ },
+ {
+ key: "collection:5",
+ model: "collection",
+ section: "data",
+ entityId: 5,
+ sourceCollectionId: 10,
+ canWrite: true,
+ },
+ ]);
+ });
+ });
+
+ describe("getSelectionSection", () => {
+ it("returns the shared section of the selection, or null when empty", () => {
+ expect(getSelectionSection([])).toBeNull();
+ expect(getSelectionSection([tableItem(1)])).toBe("data");
+ expect(getSelectionSection([metricItem(1)])).toBe("metrics");
+ });
+ });
+
+ describe("getCoveredKeys", () => {
+ // Tree: collection:10 ⊃ { table:1, collection:20 ⊃ table:2 }; table:3 is a sibling.
+ const childrenByKey = new Map<string, string[]>([
+ ["collection:10", ["table:1", "collection:20"]],
+ ["collection:20", ["table:2"]],
+ ]);
+
+ it("covers every descendant of a selected collection, tables and nested folders included", () => {
+ const covered = getCoveredKeys(childrenByKey, new Set(["collection:10"]));
+ expect([...covered].sort()).toEqual([
+ "collection:20",
+ "table:1",
+ "table:2",
+ ]);
+ });
+
+ it("does not cover the selected collection itself or unrelated siblings", () => {
+ const covered = getCoveredKeys(childrenByKey, new Set(["collection:10"]));
+ expect(covered.has("collection:10")).toBe(false);
+ expect(covered.has("table:3")).toBe(false);
+ });
+
+ it("is empty when nothing is selected", () => {
+ expect(getCoveredKeys(childrenByKey, new Set()).size).toBe(0);
+ });
+ });
+
+ describe("getEffectiveSelected", () => {
+ it("prunes covered descendants, keeping the top-level items", () => {
+ const selected = [subCollection(10, "data"), tableItem(1), tableItem(3)];
+ const coveredKeys = new Set(["table:1"]);
+ expect(ids(getEffectiveSelected(selected, coveredKeys))).toEqual([
+ "collection:10",
+ "table:3",
+ ]);
+ });
+
+ it("returns the selection unchanged when nothing is covered", () => {
+ const selected = [tableItem(1), tableItem(2)];
+ expect(getEffectiveSelected(selected, new Set())).toBe(selected);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.ts
new file mode 100644
index 00000000000..176f711510d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.ts
@@ -0,0 +1,86 @@
+import { match } from "ts-pattern";
+
+import type { ArchivableItem } from "metabase/archive/hooks";
+import type { MovableItem } from "metabase/common/hooks";
+import type { CollectionId } from "metabase-types/api";
+
+import type { SelectedItem } from "./library-bulk-selection.utils";
+
+export type LibraryItemUpdateResult = {
+ failedCount: number;
+ affectedCollectionIds: CollectionId[];
+};
+
+// Snippet-section folders map to `snippet-collection`; all others to `collection`.
+export function selectedItemToMovable(item: SelectedItem): MovableItem {
+ const { entityId: id } = item;
+ return match<SelectedItem, MovableItem>(item)
+ .with({ model: "table" }, () => ({ model: "table", id }))
+ .with({ model: "metric" }, () => ({ model: "metric", id }))
+ .with({ model: "snippet" }, () => ({ model: "snippet", id }))
+ .with({ model: "collection", section: "snippets" }, () => ({
+ model: "snippet-collection",
+ id,
+ }))
+ .with({ model: "collection" }, () => ({ model: "collection", id }))
+ .exhaustive();
+}
+
+export function selectedItemToArchivable(item: SelectedItem): ArchivableItem {
+ const { entityId: id, canWrite } = item;
+ return match<SelectedItem, ArchivableItem>(item)
+ .with({ model: "metric" }, () => ({
+ model: "metric",
+ id,
+ can_write: canWrite,
+ }))
+ .with({ model: "snippet" }, () => ({
+ model: "snippet",
+ id,
+ can_write: canWrite,
+ }))
+ .with({ model: "collection", section: "snippets" }, () => ({
+ model: "snippet-collection",
+ id,
+ can_write: canWrite,
+ }))
+ .with({ model: "collection" }, () => ({
+ model: "collection",
+ id,
+ can_write: canWrite,
+ }))
+ .with({ model: "table" }, () => {
+ throw new Error("Tables are unpublished, not moved to the trash");
+ })
+ .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> {
+ 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];
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.ts
new file mode 100644
index 00000000000..b9de015d9c9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.ts
@@ -0,0 +1,94 @@
+import type {
+ LibrarySection,
+ SelectedItem,
+} from "./library-bulk-selection.utils";
+import {
+ getAffectedCollectionIds,
+ selectedItemToArchivable,
+ selectedItemToMovable,
+} from "./library-item-updates";
+
+function item(
+ model: SelectedItem["model"],
+ entityId: number,
+ sourceCollectionId: number | null,
+ section?: LibrarySection,
+): SelectedItem {
+ return {
+ key: `${model}:${entityId}`,
+ model,
+ section:
+ section ??
+ (model === "metric"
+ ? "metrics"
+ : model === "snippet"
+ ? "snippets"
+ : "data"),
+ entityId,
+ sourceCollectionId,
+ canWrite: true,
+ };
+}
+
+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({
+ model: "table",
+ id: 1,
+ });
+ expect(selectedItemToMovable(item("metric", 2, 10))).toEqual({
+ model: "metric",
+ id: 2,
+ });
+ expect(selectedItemToMovable(item("snippet", 3, 10))).toEqual({
+ model: "snippet",
+ id: 3,
+ });
+ });
+
+ it("distinguishes snippet folders from data/metrics collections", () => {
+ expect(selectedItemToMovable(item("collection", 4, 10, "data"))).toEqual({
+ model: "collection",
+ id: 4,
+ });
+ expect(
+ selectedItemToMovable(item("collection", 5, 10, "snippets")),
+ ).toEqual({ model: "snippet-collection", id: 5 });
+ });
+});
+
+describe("selectedItemToArchivable", () => {
+ it("maps archivable models, carrying can_write through", () => {
+ expect(selectedItemToArchivable(item("metric", 2, 10))).toEqual({
+ model: "metric",
+ id: 2,
+ can_write: true,
+ });
+ expect(selectedItemToArchivable(item("snippet", 3, 10))).toEqual({
+ model: "snippet",
+ id: 3,
+ can_write: true,
+ });
+ expect(
+ selectedItemToArchivable(item("collection", 4, 10, "metrics")),
+ ).toEqual({ model: "collection", id: 4, can_write: true });
+ expect(
+ selectedItemToArchivable(item("collection", 5, 10, "snippets")),
+ ).toEqual({ model: "snippet-collection", id: 5, can_write: true });
+ });
+
+ it("refuses tables, which are unpublished rather than trashed", () => {
+ expect(() => selectedItemToArchivable(item("table", 1, 10))).toThrow();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryBulkSelection.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryBulkSelection.ts
new file mode 100644
index 00000000000..e6d1c7bf5df
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryBulkSelection.ts
@@ -0,0 +1,114 @@
+import type { Row } from "@tanstack/react-table";
+import { useCallback, useMemo, useState } from "react";
+
+import type { TreeItem } from "metabase/data-studio/common/types";
+import type { SelectionState } from "metabase/ui";
+
+import {
+ type LibrarySection,
+ type SelectedItem,
+ deriveSelectedItems,
+ getCoveredKeys,
+ getEffectiveSelected,
+ getRowSelectionState,
+ getSelectedKeySet,
+ getSelectionSection,
+ isAllTables,
+ isSectionRoot,
+ isSelectableItem,
+ toggleItem,
+ toggleSectionRoot,
+} from "./library-bulk-selection.utils";
+
+export type UseLibraryBulkSelectionResult = {
+ selectedItems: SelectedItem[];
+ selectionSection: LibrarySection | null;
+ isAllTables: boolean;
+ getSelectionState: (row: Row<TreeItem>) => SelectionState;
+ getRowCovered: (row: Row<TreeItem>) => boolean;
+ onCheckboxClick: (row: Row<TreeItem>) => void;
+ clear: () => void;
+};
+
+export function useLibraryBulkSelection(
+ rows: Row<TreeItem>[],
+): UseLibraryBulkSelectionResult {
+ const [selected, setSelected] = useState<TreeItem[]>([]);
+
+ const selectedKeys = useMemo(() => getSelectedKeySet(selected), [selected]);
+
+ const childrenByKey = useMemo(() => {
+ const map = new Map<string, string[]>();
+ for (const row of rows) {
+ if (row.subRows.length > 0) {
+ map.set(
+ row.id,
+ row.subRows.map((child) => child.id),
+ );
+ }
+ }
+ return map;
+ }, [rows]);
+
+ const coveredKeys = useMemo(
+ () => getCoveredKeys(childrenByKey, selectedKeys),
+ [childrenByKey, selectedKeys],
+ );
+
+ const getRowCovered = useCallback(
+ (row: Row<TreeItem>): boolean => coveredKeys.has(row.id),
+ [coveredKeys],
+ );
+
+ const getSelectionState = useCallback(
+ (row: Row<TreeItem>): SelectionState =>
+ coveredKeys.has(row.id)
+ ? "all"
+ : getRowSelectionState(row.original, selectedKeys),
+ [coveredKeys, selectedKeys],
+ );
+
+ const onCheckboxClick = useCallback((row: Row<TreeItem>) => {
+ const item = row.original;
+ if (isSectionRoot(item)) {
+ setSelected((prev) => toggleSectionRoot(prev, item));
+ return;
+ }
+ if (isSelectableItem(item)) {
+ setSelected((prev) => toggleItem(prev, item));
+ }
+ }, []);
+
+ const clear = useCallback(() => {
+ setSelected([]);
+ }, []);
+
+ // Actions run only on the top-level parents; a selected collection cascades to
+ // the descendants it subsumes, so those are pruned out here.
+ const effectiveSelected = useMemo(
+ () => getEffectiveSelected(selected, coveredKeys),
+ [selected, coveredKeys],
+ );
+ const selectedItems = useMemo(
+ () => deriveSelectedItems(effectiveSelected),
+ [effectiveSelected],
+ );
+ const selectionSection = useMemo(
+ () => getSelectionSection(effectiveSelected),
+ [effectiveSelected],
+ );
+ const allTables = useMemo(
+ () => isAllTables(effectiveSelected),
+ [effectiveSelected],
+ );
+
+ return {
+ selectedItems,
+ selectionSection,
+ isAllTables: allTables,
+ getSelectionState,
+ getRowCovered,
+ onCheckboxClick,
+ clear,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
index 7b682ad93c7..a417f4b3914 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
@@ -8,7 +8,7 @@ import { useBuildSnippetTree } from "metabase/data-studio/common/hooks/use-build
import type { TreeItem } from "metabase/data-studio/common/types";
import { isEmptyStateData } from "metabase/data-studio/common/utils";
import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { Link, useRouter } from "metabase/router";
import {
EntityNameCell,
Flex,
@@ -23,6 +23,7 @@ import type { Collection } from "metabase-types/api";
import { ActionCell } from "../components/ActionCell";
import { EmptyStateAction } from "../components/EmptyStateAction";
+import { getTreeRowHref } from "../utils";
import { useErrorHandling } from "./useErrorHandling";
import { useLibraryCollectionTree } from "./useLibraryCollectionTree";
@@ -147,7 +148,7 @@ export function useLibraryTreeTableInstance({
);
}
- return (
+ const nameCell = (
<EntityNameCell
data-testid={`${row.original.model}-name`}
icon={row.original.icon}
@@ -168,6 +169,25 @@ export function useLibraryTreeTableInstance({
}
/>
);
+
+ const href = getTreeRowHref(row);
+ if (href === null) {
+ return nameCell;
+ }
+ return (
+ <Link
+ to={href}
+ style={{
+ display: "flex",
+ flex: 1,
+ minWidth: 0,
+ textDecoration: "none",
+ color: "inherit",
+ }}
+ >
+ {nameCell}
+ </Link>
+ );
},
},
{
@@ -312,10 +332,15 @@ export function useLibraryTreeTableInstance({
emptyMessage = t`No results for "${searchQuery}"`;
}
+ const allRows = treeTableInstance.table.getCoreRowModel().flatRows;
+
return {
treeTableInstance,
+ allRows,
isChildrenLoading,
isLoading,
emptyMessage,
+ refreshTableCollections,
+ refreshMetricCollections,
};
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts
index dbb44418355..f4bca9d8b2e 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts
@@ -1,8 +1,18 @@
+import { msgid, ngettext } from "ttag";
+
import type { TreeItem } from "metabase/data-studio/common/types";
import { isEmptyStateData } from "metabase/data-studio/common/utils";
import * as Urls from "metabase/urls";
import type { Collection, CollectionType } from "metabase-types/api";
+export function getArchiveLibraryCollectionsMessage(count: number): string {
+ return ngettext(
+ msgid`Archiving this collection will also unpublish the tables inside it (and any tables that depend on them) and archive any other child items.`,
+ `Archiving these collections will also unpublish the tables inside them (and any tables that depend on them) and archive any other child items.`,
+ count,
+ );
+}
+
export function getAccessibleCollection(
rootCollection: Collection,
type: CollectionType,