Skip to content

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

Adapt the collection bulk action bar to pinned, unpinned, and mixed selections (#79857)

Andersonf6e9cd0a5809
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.js
index 5eaa47f1cbd..f692139d82c 100644
--- a/e2e/test/scenarios/collections/collections.cy.spec.js
+++ b/e2e/test/scenarios/collections/collections.cy.spec.js
@@ -924,10 +924,8 @@ describe("scenarios > collection defaults", () => {
cy.visit("/collection/root");
selectItemUsingCheckbox("Orders");
- cy.findByTestId("toast-card")
- .parent()
- .button("Move to trash")
- .click();
+ cy.findByTestId("toast-card").findByLabelText("More actions").click();
+ H.popover().findByText("Move to trash").click();
H.modal().button("Move to trash").click();
H.getUnpinnedSection().findByText("Orders").should("not.exist");
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
index 3077e62883b..e397edead1c 100644
--- 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
@@ -5,7 +5,6 @@ import { useSetArchive } from "metabase/archive/hooks";
import {
BulkActionBar,
BulkActionButton,
- BulkActionDangerButton,
} from "metabase/common/components/BulkActionBar";
import {
CollectionPickerModal,
@@ -161,9 +160,9 @@ export function LibraryBulkActions({
</BulkActionButton>
)}
{isAllTables && (
- <BulkActionDangerButton onClick={() => setAction("unpublish")}>
+ <BulkActionButton danger onClick={() => setAction("unpublish")}>
{t`Unpublish`}
- </BulkActionDangerButton>
+ </BulkActionButton>
)}
<BulkActionButton onClick={onClear}>{t`Clear`}</BulkActionButton>
</BulkActionBar>
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx
index ffbe705a751..b261c648651 100644
--- a/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx
@@ -8,10 +8,7 @@ import {
useSetArchive,
} from "metabase/archive/hooks";
import { isRootTrashCollection } from "metabase/common/collections/utils";
-import {
- BulkActionButton,
- BulkActionDangerButton,
-} from "metabase/common/components/BulkActionBar";
+import { BulkActionButton } from "metabase/common/components/BulkActionBar";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { canMoveItem } from "metabase/common/hooks";
import { useDispatch } from "metabase/redux";
@@ -128,12 +125,13 @@ export const ArchivedBulkActions = ({
<BulkActionButton onClick={handleBulkMoveStart} disabled={!canMove}>
{t`Move`}
</BulkActionButton>
- <BulkActionDangerButton
+ <BulkActionButton
+ danger
onClick={handleBulkDeletePermanentlyStart}
disabled={!canDeleteAll}
>
{t`Delete permanently`}
- </BulkActionDangerButton>
+ </BulkActionButton>
{/* This should probably be external so that we can hide
the bar when any other modals are displayed */}
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx
index cedfac545e3..a0d10502820 100644
--- a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx
@@ -20,7 +20,7 @@ import {
type RegisterShortcutProps,
useRegisterShortcut,
} from "metabase/palette/hooks/useRegisterShortcut";
-import type { Collection, CollectionItem } from "metabase-types/api";
+import type { Bookmark, Collection, CollectionItem } from "metabase-types/api";
import { ArchivedBulkActions } from "./ArchivedBulkActions";
import { UnarchivedBulkActions } from "./UnarchivedBulkActions";
@@ -38,6 +38,7 @@ function hasBlockingOverlay() {
type CollectionBulkActionsProps = {
selected: CollectionItem[];
collection: Collection;
+ bookmarks?: Bookmark[];
selectedItems: CollectionItem[] | null;
setSelectedItems: (items: CollectionItem[] | null) => void;
selectedAction: string | null;
@@ -49,6 +50,7 @@ export const CollectionBulkActions = memo(
({
selected,
collection,
+ bookmarks,
selectedItems,
setSelectedItems,
selectedAction,
@@ -210,6 +212,10 @@ export const CollectionBulkActions = memo(
/>
) : (
<UnarchivedBulkActions
+ selected={selected}
+ collection={collection}
+ bookmarks={bookmarks ?? []}
+ clearSelected={clearSelected}
onRequestMove={canMove ? handleBulkMoveStart : undefined}
onRequestTrash={canArchive ? openTrashConfirm : undefined}
/>
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.unit.spec.tsx
new file mode 100644
index 00000000000..5dfbaf9166b
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.unit.spec.tsx
@@ -0,0 +1,549 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+import { useState } from "react";
+
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import type { Bookmark, Collection, CollectionItem } from "metabase-types/api";
+import {
+ createMockBookmark,
+ createMockCollection,
+ createMockCollectionItem,
+ createMockDashboard,
+ createMockDocument,
+} from "metabase-types/api/mocks";
+
+import { CollectionBulkActions } from "./CollectionBulkActions";
+
+const writableCollection = createMockCollection({
+ id: 1,
+ name: "Writable collection",
+ can_write: true,
+});
+
+const pinnedDashboard = createMockCollectionItem({
+ id: 1,
+ name: "Pinned dashboard",
+ model: "dashboard",
+ collection_position: 1,
+});
+
+const pinnedQuestion = createMockCollectionItem({
+ id: 2,
+ name: "Pinned question",
+ model: "card",
+ collection_position: 2,
+});
+
+const tableQuestion = createMockCollectionItem({
+ id: 3,
+ name: "Table question",
+ model: "card",
+ collection_position: null,
+});
+
+const tableDashboard = createMockCollectionItem({
+ id: 4,
+ name: "Table dashboard",
+ model: "dashboard",
+ collection_position: null,
+});
+
+const childCollection = createMockCollectionItem({
+ id: 5,
+ name: "Child collection",
+ model: "collection",
+ collection_position: null,
+});
+
+const tableModel = createMockCollectionItem({
+ id: 7,
+ name: "Table model",
+ model: "dataset",
+ collection_position: null,
+});
+
+const physicalTable = createMockCollectionItem({
+ id: 8,
+ name: "Physical table",
+ model: "table",
+ collection_position: null,
+});
+
+const tableDocument = createMockCollectionItem({
+ id: 9,
+ name: "Table document",
+ model: "document",
+ collection_position: null,
+});
+
+function TestComponent({
+ selected,
+ collection,
+ bookmarks,
+ clearSelected,
+}: {
+ selected: CollectionItem[];
+ collection: Collection;
+ bookmarks: Bookmark[];
+ clearSelected: () => void;
+}) {
+ const [selectedItems, setSelectedItems] = useState<CollectionItem[] | null>(
+ null,
+ );
+ const [selectedAction, setSelectedAction] = useState<string | null>(null);
+
+ return (
+ <CollectionBulkActions
+ selected={selected}
+ collection={collection}
+ bookmarks={bookmarks}
+ selectedItems={selectedItems}
+ setSelectedItems={setSelectedItems}
+ selectedAction={selectedAction}
+ setSelectedAction={setSelectedAction}
+ clearSelected={clearSelected}
+ />
+ );
+}
+
+function setup({
+ selected,
+ collection = writableCollection,
+ bookmarks = [],
+}: {
+ selected: CollectionItem[];
+ collection?: Collection;
+ bookmarks?: Bookmark[];
+}) {
+ const clearSelected = jest.fn();
+
+ renderWithProviders(
+ <TestComponent
+ selected={selected}
+ collection={collection}
+ bookmarks={bookmarks}
+ clearSelected={clearSelected}
+ />,
+ { withUndos: true },
+ );
+
+ return { clearSelected };
+}
+
+async function openOverflowMenu() {
+ await userEvent.click(screen.getByRole("button", { name: "More actions" }));
+ return await screen.findByRole("menu");
+}
+
+function getRequests(matcher: string) {
+ return fetchMock.callHistory.calls(matcher);
+}
+
+function getLastRequestBody(matcher: string) {
+ const call = fetchMock.callHistory.lastCall(matcher);
+ // request bodies sent by the component are always JSON strings
+ return JSON.parse(call?.options.body as string);
+}
+
+function getMenuItem(name: string) {
+ return screen.getByRole("menuitem", { name });
+}
+
+describe("CollectionBulkActions", () => {
+ describe("selection composition", () => {
+ it("keeps Move primary and offers Pin all for an unpinned-only selection", async () => {
+ setup({ selected: [tableQuestion, tableDashboard] });
+
+ expect(screen.getByRole("button", { name: "Move" })).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Move to trash" }),
+ ).not.toBeInTheDocument();
+
+ const menu = await openOverflowMenu();
+ const itemLabels = within(menu)
+ .getAllByRole("menuitem")
+ .map((item) => item.textContent);
+ expect(itemLabels).toEqual([
+ "Pin all",
+ "Bookmark",
+ "Duplicate",
+ "Deselect all",
+ "Move to trash",
+ ]);
+ });
+
+ it("makes Unpin all the primary action for a pinned-only selection", async () => {
+ setup({ selected: [pinnedDashboard, pinnedQuestion] });
+
+ expect(
+ screen.getByRole("button", { name: "Unpin all" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Move" }),
+ ).not.toBeInTheDocument();
+
+ const menu = await openOverflowMenu();
+ const itemLabels = within(menu)
+ .getAllByRole("menuitem")
+ .map((item) => item.textContent);
+ expect(itemLabels).toEqual([
+ "Move",
+ "Bookmark",
+ "Duplicate",
+ "Deselect all",
+ "Move to trash",
+ ]);
+ });
+
+ it("keeps Move primary and offers both pin actions for a mixed selection", async () => {
+ setup({ selected: [pinnedDashboard, tableQuestion] });
+
+ expect(screen.getByRole("button", { name: "Move" })).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Unpin all" }),
+ ).not.toBeInTheDocument();
+
+ const menu = await openOverflowMenu();
+ const itemLabels = within(menu)
+ .getAllByRole("menuitem")
+ .map((item) => item.textContent);
+ expect(itemLabels).toEqual([
+ "Pin all",
+ "Unpin all",
+ "Bookmark",
+ "Duplicate",
+ "Deselect all",
+ "Move to trash",
+ ]);
+ });
+ });
+
+ describe("pinning", () => {
+ it("pins only the unpinned items with Pin all", async () => {
+ fetchMock.put("path:/api/card/3", {});
+ fetchMock.put("path:/api/dashboard/4", {});
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, tableQuestion, tableDashboard],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Pin all"));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/card/3")).toHaveLength(1);
+ });
+ expect(getRequests("path:/api/dashboard/4")).toHaveLength(1);
+ expect(getRequests("path:/api/dashboard/1")).toHaveLength(0);
+
+ expect(getLastRequestBody("path:/api/card/3")).toEqual({
+ collection_position: 1,
+ });
+
+ await waitFor(() => {
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ it("unpins only the pinned items with Unpin all", async () => {
+ fetchMock.put("path:/api/dashboard/1", {});
+ fetchMock.put("path:/api/card/2", {});
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, pinnedQuestion, tableQuestion],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Unpin all"));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/dashboard/1")).toHaveLength(1);
+ });
+ expect(getRequests("path:/api/card/2")).toHaveLength(1);
+ expect(getRequests("path:/api/card/3")).toHaveLength(0);
+
+ expect(getLastRequestBody("path:/api/dashboard/1")).toEqual({
+ collection_position: null,
+ });
+
+ await waitFor(() => {
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ it("unpins a pinned-only selection with the primary Unpin all button", async () => {
+ fetchMock.put("path:/api/dashboard/1", {});
+ fetchMock.put("path:/api/card/2", {});
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, pinnedQuestion],
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "Unpin all" }));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/dashboard/1")).toHaveLength(1);
+ });
+ expect(getRequests("path:/api/card/2")).toHaveLength(1);
+ expect(getLastRequestBody("path:/api/card/2")).toEqual({
+ collection_position: null,
+ });
+
+ await waitFor(() => {
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ it("shows an error message when pinning fails", async () => {
+ fetchMock.put("path:/api/card/3", 500);
+ setup({ selected: [tableQuestion] });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Pin all"));
+
+ expect(
+ await screen.findByText("There was an error pinning these items."),
+ ).toBeInTheDocument();
+ });
+
+ it("shows an error message when unpinning fails", async () => {
+ fetchMock.put("path:/api/card/2", 500);
+ setup({ selected: [pinnedQuestion] });
+
+ await userEvent.click(screen.getByRole("button", { name: "Unpin all" }));
+
+ expect(
+ await screen.findByText("There was an error unpinning these items."),
+ ).toBeInTheDocument();
+ });
+
+ it("disables Pin all but not Unpin all when an unpinnable item is among the unpinned", async () => {
+ setup({ selected: [pinnedDashboard, childCollection] });
+ await openOverflowMenu();
+
+ expect(getMenuItem("Pin all")).toHaveAttribute("data-disabled", "true");
+ expect(getMenuItem("Unpin all")).not.toHaveAttribute(
+ "data-disabled",
+ "true",
+ );
+ });
+ });
+
+ describe("bookmarking", () => {
+ it("bookmarks the selected items", async () => {
+ fetchMock.post("path:/api/bookmark/dashboard/1", {});
+ fetchMock.post("path:/api/bookmark/card/3", {});
+ fetchMock.post("path:/api/bookmark/card/7", {});
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, tableQuestion, tableModel],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Bookmark"));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/bookmark/dashboard/1")).toHaveLength(1);
+ });
+ expect(getRequests("path:/api/bookmark/card/3")).toHaveLength(1);
+ expect(getRequests("path:/api/bookmark/card/7")).toHaveLength(1);
+
+ await waitFor(() => {
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ it("skips items that are already bookmarked", async () => {
+ fetchMock.post("path:/api/bookmark/dashboard/1", {});
+ setup({
+ selected: [pinnedDashboard, tableQuestion],
+ bookmarks: [createMockBookmark({ type: "card", item_id: 3 })],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Bookmark"));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/bookmark/dashboard/1")).toHaveLength(1);
+ });
+ expect(getRequests("path:/api/bookmark/card/3")).toHaveLength(0);
+ });
+
+ it("disables Bookmark when the selection has an item that cannot be bookmarked", async () => {
+ setup({ selected: [pinnedDashboard, physicalTable] });
+ await openOverflowMenu();
+
+ expect(getMenuItem("Bookmark")).toHaveAttribute("data-disabled", "true");
+ });
+
+ it("disables Bookmark when every selected item is already bookmarked", async () => {
+ setup({
+ selected: [pinnedDashboard, tableQuestion],
+ bookmarks: [
+ createMockBookmark({ type: "dashboard", item_id: 1 }),
+ createMockBookmark({ type: "card", item_id: 3 }),
+ ],
+ });
+ await openOverflowMenu();
+
+ expect(getMenuItem("Bookmark")).toHaveAttribute("data-disabled", "true");
+ });
+
+ it("shows an error message when bookmarking fails", async () => {
+ fetchMock.post("path:/api/bookmark/card/3", 500);
+ setup({ selected: [tableQuestion] });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Bookmark"));
+
+ expect(
+ await screen.findByText("There was an error bookmarking these items."),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("duplicating", () => {
+ it("duplicates the selected items into the current collection", async () => {
+ fetchMock.post("path:/api/dashboard/1/copy", createMockDashboard());
+ fetchMock.post("path:/api/dashboard/4/copy", createMockDashboard());
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, tableDashboard],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Duplicate"));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/dashboard/1/copy")).toHaveLength(1);
+ });
+ expect(getLastRequestBody("path:/api/dashboard/1/copy")).toEqual({
+ name: "Pinned dashboard - Duplicate",
+ collection_id: 1,
+ is_deep_copy: false,
+ });
+
+ expect(
+ await screen.findByText("2 items have been duplicated."),
+ ).toBeInTheDocument();
+ expect(clearSelected).toHaveBeenCalled();
+ });
+
+ it("duplicates documents through the document copy endpoint", async () => {
+ fetchMock.post("path:/api/dashboard/1/copy", createMockDashboard());
+ fetchMock.post(
+ "path:/api/document/9/copy",
+ createMockDocument({ id: 9 }),
+ );
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, tableDocument],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Duplicate"));
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/document/9/copy")).toHaveLength(1);
+ });
+ expect(getRequests("path:/api/dashboard/1/copy")).toHaveLength(1);
+ expect(getLastRequestBody("path:/api/document/9/copy")).toEqual({
+ name: "Table document - Duplicate",
+ collection_id: 1,
+ });
+
+ await waitFor(() => {
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ it("disables Duplicate when the selection has an item that cannot be duplicated", async () => {
+ setup({ selected: [pinnedDashboard, tableQuestion] });
+ await openOverflowMenu();
+
+ expect(getMenuItem("Duplicate")).toHaveAttribute("data-disabled", "true");
+ });
+ });
+
+ describe("deselecting", () => {
+ it("clears the selection with Deselect all", async () => {
+ const { clearSelected } = setup({
+ selected: [pinnedDashboard, tableQuestion],
+ });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Deselect all"));
+
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ describe("moving to trash", () => {
+ it("confirms before moving the selection to trash from the overflow menu", async () => {
+ fetchMock.put("path:/api/card/3", {});
+ const { clearSelected } = setup({ selected: [tableQuestion] });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Move to trash"));
+
+ const confirmation = await screen.findByTestId(
+ "move-to-trash-confirmation",
+ );
+ expect(
+ within(confirmation).getByText("Move 1 item to trash?"),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ within(confirmation).getByRole("button", { name: "Move to trash" }),
+ );
+
+ await waitFor(() => {
+ expect(getRequests("path:/api/card/3")).toHaveLength(1);
+ });
+ expect(getLastRequestBody("path:/api/card/3")).toMatchObject({
+ archived: true,
+ });
+
+ await waitFor(() => {
+ expect(clearSelected).toHaveBeenCalled();
+ });
+ });
+
+ it("keeps the selection when the trash confirmation is cancelled", async () => {
+ const { clearSelected } = setup({ selected: [tableQuestion] });
+
+ await openOverflowMenu();
+ await userEvent.click(getMenuItem("Move to trash"));
+
+ const confirmation = await screen.findByTestId(
+ "move-to-trash-confirmation",
+ );
+ await userEvent.click(
+ within(confirmation).getByRole("button", { name: "Cancel" }),
+ );
+
+ expect(clearSelected).not.toHaveBeenCalled();
+ expect(getRequests("path:/api/card/3")).toHaveLength(0);
+ });
+
+ it("disables the overflow actions in a read-only collection", async () => {
+ setup({
+ selected: [pinnedQuestion],
+ collection: createMockCollection({
+ ...writableCollection,
+ can_write: false,
+ }),
+ });
+
+ expect(screen.getByRole("button", { name: "Unpin all" })).toBeDisabled();
+
+ await openOverflowMenu();
+ expect(getMenuItem("Move to trash")).toHaveAttribute(
+ "data-disabled",
+ "true",
+ );
+ expect(getMenuItem("Move")).toHaveAttribute("data-disabled", "true");
+ });
+ });
+
+ describe("moving", () => {
+ it("enables the Move button for a movable selection", () => {
+ setup({ selected: [pinnedDashboard, tableQuestion] });
+
+ expect(screen.getByRole("button", { name: "Move" })).toBeEnabled();
+ });
+ });
+});
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx
index 2ebd1b0b454..d5e0bf581e3 100644
--- a/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx
@@ -1,26 +1,142 @@
-import { t } from "ttag";
+import { c, t } from "ttag";
import { BulkActionButton } from "metabase/common/components/BulkActionBar";
+import { Icon, Menu } from "metabase/ui";
+import type { Bookmark, Collection, CollectionItem } from "metabase-types/api";
+
+import { useBulkBookmark } from "./use-bulk-bookmark";
+import { useBulkDuplicate } from "./use-bulk-duplicate";
+import { useBulkPin } from "./use-bulk-pin";
type UnarchivedBulkActionsProps = {
+ selected: CollectionItem[];
+ collection: Collection;
+ bookmarks: Bookmark[];
+ clearSelected: () => void;
onRequestMove?: () => void;
onRequestTrash?: () => void;
};
export const UnarchivedBulkActions = ({
+ selected,
+ collection,
+ bookmarks,
+ clearSelected,
onRequestMove,
onRequestTrash,
}: UnarchivedBulkActionsProps) => {
+ const {
+ hasPinned,
+ hasUnpinned,
+ canPinAll,
+ canUnpinAll,
+ pinSelected,
+ unpinSelected,
+ } = useBulkPin(selected, collection);
+ const { canBookmark, bookmarkSelected } = useBulkBookmark(
+ selected,
+ bookmarks,
+ );
+ const { canDuplicate, duplicateSelected } = useBulkDuplicate(
+ selected,
+ collection,
+ );
+
+ const handlePinAll = () => {
+ pinSelected().finally(clearSelected);
+ };
+
+ const handleUnpinAll = () => {
+ unpinSelected().finally(clearSelected);
+ };
+
+ const handleBookmark = () => {
+ bookmarkSelected().finally(clearSelected);
+ };
+
+ const handleDuplicate = () => {
+ duplicateSelected().finally(clearSelected);
+ };
+
+ const isPinnedOnly = hasPinned && !hasUnpinned;
+ const isMixed = hasPinned && hasUnpinned;
+
return (
<>
- <BulkActionButton
- disabled={onRequestMove == null}
- onClick={onRequestMove}
- >{t`Move`}</BulkActionButton>
- <BulkActionButton
- disabled={onRequestTrash == null}
- onClick={onRequestTrash}
- >{t`Move to trash`}</BulkActionButton>
+ {isPinnedOnly ? (
+ <BulkActionButton
+ disabled={!canUnpinAll}
+ onClick={handleUnpinAll}
+ >{t`Unpin all`}</BulkActionButton>
+ ) : (
+ <BulkActionButton
+ disabled={onRequestMove == null}
+ onClick={onRequestMove}
+ >{t`Move`}</BulkActionButton>
+ )}
+ <Menu position="top-end">
+ <Menu.Target>
+ <BulkActionButton aria-label={t`More actions`} px="sm">
+ <Icon name="ellipsis" />
+ </BulkActionButton>
+ </Menu.Target>
+ <Menu.Dropdown data-testid="bulk-actions-menu">
+ {isPinnedOnly && (
+ <Menu.Item
+ leftSection={<Icon name="move" aria-hidden />}
+ disabled={onRequestMove == null}
+ onClick={onRequestMove}
+ >
+ {t`Move`}
+ </Menu.Item>
+ )}
+ {hasUnpinned && (
+ <Menu.Item
+ leftSection={<Icon name="pin" aria-hidden />}
+ disabled={!canPinAll}
+ onClick={handlePinAll}
+ >
+ {t`Pin all`}
+ </Menu.Item>
+ )}
+ {isMixed && (
+ <Menu.Item
+ leftSection={<Icon name="unpin" aria-hidden />}
+ disabled={!canUnpinAll}
+ onClick={handleUnpinAll}
+ >
+ {t`Unpin all`}
+ </Menu.Item>
+ )}
+ <Menu.Item
+ leftSection={<Icon name="bookmark" aria-hidden />}
+ disabled={!canBookmark}
+ onClick={handleBookmark}
+ >
+ {c("Verb").t`Bookmark`}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="clone" aria-hidden />}
+ disabled={!canDuplicate}
+ onClick={handleDuplicate}
+ >
+ {c("Verb").t`Duplicate`}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="close" aria-hidden />}
+ onClick={clearSelected}
+ >
+ {t`Deselect all`}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="trash" aria-hidden />}
+ disabled={onRequestTrash == null}
+ onClick={onRequestTrash}
+ >
+ {t`Move to trash`}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
</>
);
};
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-bookmark.ts b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-bookmark.ts
new file mode 100644
index 00000000000..0d8e069fbf5
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-bookmark.ts
@@ -0,0 +1,48 @@
+import { useCallback, useMemo } from "react";
+import { t } from "ttag";
+
+import { useCreateBookmarkMutation } from "metabase/api";
+import { trackCollectionItemBookmarked } from "metabase/common/collections/analytics";
+import {
+ canBookmarkItem,
+ getItemBookmarkType,
+ isItemBookmarked,
+} from "metabase/common/collections/utils";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import type { Bookmark, CollectionItem } from "metabase-types/api";
+
+export const useBulkBookmark = (
+ selected: CollectionItem[],
+ bookmarks: Bookmark[],
+) => {
+ const { sendErrorToast } = useMetadataToasts();
+ const [createBookmark] = useCreateBookmarkMutation();
+
+ const itemsToBookmark = useMemo(
+ () => selected.filter((item) => !isItemBookmarked(item, bookmarks)),
+ [selected, bookmarks],
+ );
+
+ const canBookmark = useMemo(
+ () => itemsToBookmark.length > 0 && selected.every(canBookmarkItem),
+ [itemsToBookmark, selected],
+ );
+
+ const bookmarkSelected = useCallback(async () => {
+ try {
+ await Promise.all(
+ itemsToBookmark.map(async (item) => {
+ await createBookmark({
+ id: item.id,
+ type: getItemBookmarkType(item),
+ }).unwrap();
+ trackCollectionItemBookmarked(item);
+ }),
+ );
+ } catch {
+ sendErrorToast(t`There was an error bookmarking these items.`);
+ }
+ }, [itemsToBookmark, createBookmark, sendErrorToast]);
+
+ return { canBookmark, bookmarkSelected };
+};
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-duplicate.ts b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-duplicate.ts
new file mode 100644
index 00000000000..55ecce38544
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-duplicate.ts
@@ -0,0 +1,68 @@
+import { useCallback, useMemo } from "react";
+import { match } from "ts-pattern";
+import { msgid, ngettext, t } from "ttag";
+
+import {
+ useCopyDashboardMutation,
+ useCopyDocumentMutation,
+} from "metabase/api";
+import {
+ canCopyItem,
+ canonicalCollectionId,
+} from "metabase/common/collections/utils";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import type { Collection, CollectionItem } from "metabase-types/api";
+
+export const useBulkDuplicate = (
+ selected: CollectionItem[],
+ collection: Collection,
+) => {
+ const { sendErrorToast, sendSuccessToast } = useMetadataToasts();
+ const [copyDashboard] = useCopyDashboardMutation();
+ const [copyDocument] = useCopyDocumentMutation();
+
+ const canDuplicate = useMemo(() => selected.every(canCopyItem), [selected]);
+
+ const duplicateSelected = useCallback(async () => {
+ const collectionId = canonicalCollectionId(collection.id);
+ const itemsToCopy = selected.filter(canCopyItem);
+ try {
+ await Promise.all(
+ itemsToCopy.map((item) => {
+ const name = `${item.name} - ${t`Duplicate`}`;
+ return match(item)
+ .with({ model: "dashboard" }, ({ id }) =>
+ copyDashboard({
+ id,
+ name,
+ collection_id: collectionId,
+ is_deep_copy: false,
+ }).unwrap(),
+ )
+ .with({ model: "document" }, ({ id }) =>
+ copyDocument({ id, name, collection_id: collectionId }).unwrap(),
+ )
+ .exhaustive();
+ }),
+ );
+ sendSuccessToast(
+ ngettext(
+ msgid`${itemsToCopy.length} item has been duplicated.`,
+ `${itemsToCopy.length} items have been duplicated.`,
+ itemsToCopy.length,
+ ),
+ );
+ } catch {
+ sendErrorToast(t`There was an error duplicating these items.`);
+ }
+ }, [
+ selected,
+ collection.id,
+ copyDashboard,
+ copyDocument,
+ sendSuccessToast,
+ sendErrorToast,
+ ]);
+
+ return { canDuplicate, duplicateSelected };
+};
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-pin.ts b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-pin.ts
new file mode 100644
index 00000000000..dc5d501ac71
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-pin.ts
@@ -0,0 +1,64 @@
+import { useCallback, useMemo } from "react";
+import { t } from "ttag";
+
+import { isItemPinned } from "metabase/common/collections/utils";
+import { canPinItem, isPinnable, useSetPinned } from "metabase/common/hooks";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import type { Collection, CollectionItem } from "metabase-types/api";
+
+export const useBulkPin = (
+ selected: CollectionItem[],
+ collection: Collection,
+) => {
+ const { sendErrorToast } = useMetadataToasts();
+ const setPinned = useSetPinned();
+
+ const pinnedItems = useMemo(() => selected.filter(isItemPinned), [selected]);
+ const unpinnedItems = useMemo(
+ () => selected.filter((item) => !isItemPinned(item)),
+ [selected],
+ );
+
+ const canPinAll = useMemo(
+ () => unpinnedItems.every((item) => canPinItem(item, collection)),
+ [unpinnedItems, collection],
+ );
+
+ const canUnpinAll = useMemo(
+ () => pinnedItems.every((item) => canPinItem(item, collection)),
+ [pinnedItems, collection],
+ );
+
+ const pinSelected = useCallback(async () => {
+ try {
+ await Promise.all(
+ unpinnedItems
+ .filter(isPinnable)
+ .map((item) => setPinned(item, true).unwrap()),
+ );
+ } catch {
+ sendErrorToast(t`There was an error pinning these items.`);
+ }
+ }, [unpinnedItems, setPinned, sendErrorToast]);
+
+ const unpinSelected = useCallback(async () => {
+ try {
+ await Promise.all(
+ pinnedItems
+ .filter(isPinnable)
+ .map((item) => setPinned(item, false).unwrap()),
+ );
+ } catch {
+ sendErrorToast(t`There was an error unpinning these items.`);
+ }
+ }, [pinnedItems, setPinned, sendErrorToast]);
+
+ return {
+ hasPinned: pinnedItems.length > 0,
+ hasUnpinned: unpinnedItems.length > 0,
+ canPinAll,
+ canUnpinAll,
+ pinSelected,
+ unpinSelected,
+ };
+};
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentSelection.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentSelection.unit.spec.tsx
index 5c6a45ee883..90c64ec002b 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentSelection.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentSelection.unit.spec.tsx
@@ -336,6 +336,49 @@ describe("CollectionContent selection", () => {
expect(await screen.findByText("1 item selected")).toBeInTheDocument();
});
+ it("should adapt the bulk action bar to the selection composition", async () => {
+ await setup();
+
+ await userEvent.click(getRowSelectionButton(tableQuestion.name));
+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Move to trash" }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(screen.getByRole("button", { name: "More actions" }));
+ expect(
+ await screen.findByRole("menuitem", { name: "Pin all" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("menuitem", { name: "Unpin all" }),
+ ).not.toBeInTheDocument();
+ await userEvent.keyboard("{Escape}");
+
+ await userEvent.click(getPinnedCard(pinnedDashboard.name));
+ expect(screen.getByRole("button", { name: "Move" })).toBeInTheDocument();
+ await userEvent.click(
+ await screen.findByRole("button", { name: "More actions" }),
+ );
+ expect(
+ await screen.findByRole("menuitem", { name: "Pin all" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: "Unpin all" }),
+ ).toBeInTheDocument();
+ await userEvent.keyboard("{Escape}");
+
+ await userEvent.click(getRowSelectionButton(tableQuestion.name));
+ expect(
+ await screen.findByRole("button", { name: "Unpin all" }),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByRole("button", { name: "More actions" }));
+ expect(
+ await screen.findByRole("menuitem", { name: "Move" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("menuitem", { name: "Pin all" }),
+ ).not.toBeInTheDocument();
+ });
+
it("should open a row menu without selecting on shift+click", async () => {
await setup();
const row = screen.getByRole("row", {
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
index 20ab3334b3e..e420c4c8ce7 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
@@ -315,6 +315,7 @@ export const CollectionContentView = ({
/>
<CollectionBulkActions
collection={collection}
+ bookmarks={bookmarks}
selected={selected}
clearSelected={clear}
selectedItems={selectedItems}
diff --git a/frontend/src/metabase/common/collections/components/ActionMenu/ActionMenu.tsx b/frontend/src/metabase/common/collections/components/ActionMenu/ActionMenu.tsx
index a425efbdf79..55dda1ab1d6 100644
--- a/frontend/src/metabase/common/collections/components/ActionMenu/ActionMenu.tsx
+++ b/frontend/src/metabase/common/collections/components/ActionMenu/ActionMenu.tsx
@@ -22,6 +22,8 @@ import {
canArchiveItem,
canBookmarkItem,
canCopyItem,
+ getItemBookmarkType,
+ isItemBookmarked,
isItemPinned,
} from "metabase/common/collections/utils";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
@@ -63,23 +65,6 @@ interface ActionMenuStateProps {
isXrayEnabled: boolean;
}
-function getIsBookmarked(item: CollectionItem, bookmarks: Bookmark[]) {
- const normalizedItemModel = normalizeItemModel(item);
-
- return bookmarks.some(
- (bookmark) =>
- bookmark.type === normalizedItemModel && bookmark.item_id === item.id,
- );
-}
-
-// If item.model is `dataset`, that is, this is a Model in a product sense,
-// let’s call it "card" because `card` and `dataset` are treated the same in the back-end.
-function normalizeItemModel(item: CollectionItem) {
- return item.model === "dataset" || item.model === "metric"
- ? "card"
- : item.model;
-}
-
function mapStateToProps(state: State): ActionMenuStateProps {
return {
isXrayEnabled: getSetting(state, "enable-xrays"),
@@ -104,7 +89,7 @@ function ActionMenuInner({
const deleteItem = useDeleteItem();
const setPinned = useSetPinned();
const [modalOpened, { open: openModal, close: closeModal }] = useDisclosure();
- const isBookmarked = bookmarks && getIsBookmarked(item, bookmarks);
+ const isBookmarked = bookmarks && isItemBookmarked(item, bookmarks);
const canBookmark = canBookmarkItem(item);
const canPin = canPinItem(item, collection);
const canMove = canMoveItem(item, collection);
@@ -145,8 +130,7 @@ function ActionMenuInner({
if (!isBookmarked) {
trackCollectionItemBookmarked(item);
}
- const normalizedModel = normalizeItemModel(item);
- toggleBookmark?.({ id: item.id, type: normalizedModel });
+ toggleBookmark?.({ id: item.id, type: getItemBookmarkType(item) });
};
return handler;
}, [createBookmark, deleteBookmark, isBookmarked, item]);
diff --git a/frontend/src/metabase/common/collections/utils.ts b/frontend/src/metabase/common/collections/utils.ts
index d8593fd4a45..901a97f8444 100644
--- a/frontend/src/metabase/common/collections/utils.ts
+++ b/frontend/src/metabase/common/collections/utils.ts
@@ -11,6 +11,7 @@ import type { IconProps } from "metabase/ui";
import { color } from "metabase/ui/colors";
import type { ColorName } from "metabase/ui/colors/types";
import {
+ type Bookmark,
type CardType,
type Collection,
type CollectionContentModel,
@@ -233,6 +234,26 @@ export function isReadOnlyCollection(collection: CollectionItem) {
return isItemCollection(collection) && !collection.can_write;
}
+/**
+ * If item.model is `dataset` or `metric`, that is, a Model or a Metric in a
+ * product sense, call it "card" because they are treated the same in the
+ * back-end bookmark API.
+ */
+export function getItemBookmarkType(item: CollectionItem) {
+ return item.model === "dataset" || item.model === "metric"
+ ? "card"
+ : item.model;
+}
+
+export function isItemBookmarked(item: CollectionItem, bookmarks: Bookmark[]) {
+ const bookmarkType = getItemBookmarkType(item);
+
+ return bookmarks.some(
+ (bookmark) =>
+ bookmark.type === bookmarkType && bookmark.item_id === item.id,
+ );
+}
+
export function canBookmarkItem({ model, type, archived }: CollectionItem) {
if (archived) {
return false;
@@ -267,7 +288,9 @@ export function canArchiveItem(item: CollectionItem, collection?: Collection) {
);
}
-export function canCopyItem(item: CollectionItem) {
+export type CopyableItem = CollectionItem & { model: "dashboard" | "document" };
+
+export function canCopyItem(item: CollectionItem): item is CopyableItem {
return (
(item.model === "dashboard" || item.model === "document") && !item.archived
);
diff --git a/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.module.css b/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.module.css
index 5e5ed70795a..d30baeceec9 100644
--- a/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.module.css
+++ b/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.module.css
@@ -1,4 +1,4 @@
-.BulkActionButton:not([data-css-specificity-hack="🤣"]) {
+.BulkActionButton {
color: var(--mb-color-text-primary-inverse);
border-color: color-mix(
in srgb,
@@ -25,7 +25,8 @@
);
}
- &:disabled {
+ &:disabled,
+ &:disabled:hover {
color: var(--mb-color-text-disabled-inverse);
border-color: color-mix(
in srgb,
@@ -36,7 +37,7 @@
}
}
-.BulkActionDangerButton:not([data-css-specificity-hack="🤣"]) {
+.BulkActionDangerButton {
&:hover {
color: var(--mb-color-text-primary-inverse);
border-color: color-mix(
@@ -61,3 +62,7 @@
);
}
}
+
+.BulkActionButtonLabel {
+ display: inline-flex;
+}
diff --git a/frontend/src/metabase/common/components/BulkActionBar/BulkActionButton.tsx b/frontend/src/metabase/common/components/BulkActionBar/BulkActionButton.tsx
index 7d33b29cf49..9be4c2f64f2 100644
--- a/frontend/src/metabase/common/components/BulkActionBar/BulkActionButton.tsx
+++ b/frontend/src/metabase/common/components/BulkActionBar/BulkActionButton.tsx
@@ -1,26 +1,33 @@
import cx from "classnames";
+import { forwardRef } from "react";
import { Button, type ButtonProps } from "metabase/ui";
import S from "./BulkActionBar.module.css";
-type BulkActionButtonProps = ButtonProps & {
- classname?: string;
+type BulkActionButtonProps = Omit<ButtonProps, "variant"> & {
+ danger?: boolean;
};
-export const BulkActionButton = ({
- classname,
- ...props
-}: BulkActionButtonProps) => (
- <Button className={cx(S.BulkActionButton, classname)} {...props} />
-);
-
-export const BulkActionDangerButton = ({
- classname,
- ...props
-}: BulkActionButtonProps) => (
- <Button
- className={cx(S.BulkActionButton, S.BulkActionDangerButton, classname)}
- {...props}
- />
-);
+export const BulkActionButton = forwardRef<
+ HTMLButtonElement,
+ BulkActionButtonProps
+>(function BulkActionButton({ className, danger = false, ...props }, ref) {
+ return (
+ <Button
+ {...props}
+ ref={ref}
+ variant="transparent"
+ classNames={{
+ root: cx(
+ S.BulkActionButton,
+ {
+ [S.BulkActionDangerButton]: danger,
+ },
+ className,
+ ),
+ label: S.BulkActionButtonLabel,
+ }}
+ />
+ );
+});
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
index b21be388e35..d2cfd88b862 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
@@ -11,7 +11,6 @@ import {
import {
BulkActionBar,
BulkActionButton,
- BulkActionDangerButton,
} from "metabase/common/components/BulkActionBar";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { PaginationControls } from "metabase/common/components/PaginationControls";
@@ -405,12 +404,13 @@ export const NotificationsAdminPage = () => {
: t`${selectedCount} alerts selected`
}
>
- <BulkActionDangerButton
+ <BulkActionButton
+ danger
onClick={handleDeleteBulk}
disabled={isBulkLoading}
>
{t`Delete`}
- </BulkActionDangerButton>
+ </BulkActionButton>
<BulkActionButton
onClick={() => setIsChangeOwnerOpened(true)}
disabled={isBulkLoading}