Skip to content

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

Add Escape and Delete shortcuts for collection item selection (#79670)

Anderson32a179075c70
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.js
index 691959bb021..5eaa47f1cbd 100644
--- a/e2e/test/scenarios/collections/collections.cy.spec.js
+++ b/e2e/test/scenarios/collections/collections.cy.spec.js
@@ -882,6 +882,25 @@ describe("scenarios > collection defaults", () => {
.should("be.visible");
});
+ it("should clear the selection with Escape and trash it with Delete", () => {
+ cy.visit("/collection/root");
+ selectItemUsingCheckbox("Orders");
+ cy.findByTestId("toast-card")
+ .findByText("1 item selected")
+ .should("be.visible");
+
+ cy.realPress("Escape");
+ H.getUnpinnedSection().findByText("Orders").should("be.visible");
+ cy.findByTestId("toast-card").should("not.exist");
+
+ selectItemUsingCheckbox("Orders");
+ cy.realPress("Delete");
+ H.modal().button("Move to trash").click();
+
+ H.getUnpinnedSection().findByText("Orders").should("not.exist");
+ cy.findByTestId("toast-card").should("not.exist");
+ });
+
it("should clean up selection when opening another collection (metabase#16491)", () => {
cy.request("PUT", `/api/card/${ORDERS_QUESTION_ID}`, {
collection_id: ADMIN_PERSONAL_COLLECTION_ID,
@@ -909,6 +928,7 @@ describe("scenarios > collection defaults", () => {
.parent()
.button("Move to trash")
.click();
+ H.modal().button("Move to trash").click();
H.getUnpinnedSection().findByText("Orders").should("not.exist");
cy.findByTestId("toast-card").should("not.exist");
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx
index 7b0882720a0..cedfac545e3 100644
--- a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx
@@ -1,6 +1,5 @@
-import { memo, useMemo, useState } from "react";
-import { msgid, ngettext } from "ttag";
-import _ from "underscore";
+import { memo, useCallback, useMemo, useState } from "react";
+import { msgid, ngettext, t } from "ttag";
import CollectionCopyEntityModal from "metabase/collections/components/CollectionCopyEntityModal";
import {
@@ -9,20 +8,35 @@ import {
} from "metabase/common/collections/components/QuestionMoveConfirmModal";
import { isTrashedCollection } from "metabase/common/collections/utils";
import { BulkActionBar } from "metabase/common/components/BulkActionBar";
+import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import type { OmniPickerItem } from "metabase/common/components/Pickers";
import { BulkMoveModal } from "metabase/common/components/Pickers/MoveModal/MoveModal";
import {
- type MovableItem,
+ canMoveItem,
isMovable,
useSetCollection,
} from "metabase/common/hooks";
+import {
+ type RegisterShortcutProps,
+ useRegisterShortcut,
+} from "metabase/palette/hooks/useRegisterShortcut";
import type { Collection, CollectionItem } from "metabase-types/api";
import { ArchivedBulkActions } from "./ArchivedBulkActions";
import { UnarchivedBulkActions } from "./UnarchivedBulkActions";
+import { useBulkArchive } from "./use-bulk-archive";
+
+const BLOCKING_OVERLAY_SELECTOR =
+ '[role="dialog"], [data-element-id="mantine-popover"]';
+
+function hasBlockingOverlay() {
+ return Array.from(
+ document.querySelectorAll<HTMLElement>(BLOCKING_OVERLAY_SELECTOR),
+ ).some((element) => element.style.display !== "none");
+}
type CollectionBulkActionsProps = {
- selected: any[];
+ selected: CollectionItem[];
collection: Collection;
selectedItems: CollectionItem[] | null;
setSelectedItems: (items: CollectionItem[] | null) => void;
@@ -44,14 +58,67 @@ export const CollectionBulkActions = memo(
const [rememberedDestination, setRememberedDestination] =
useState<Destination | null>(null);
const setCollection = useSetCollection();
+ const { canArchive, archiveSelected } = useBulkArchive(
+ selected,
+ collection,
+ );
+ const isTrashed = isTrashedCollection(collection);
+ const isTrashConfirmOpen = selectedAction === "trash";
+ const openTrashConfirm = useCallback(
+ () => setSelectedAction("trash"),
+ [setSelectedAction],
+ );
+ const closeTrashConfirm = useCallback(
+ () => setSelectedAction(null),
+ [setSelectedAction],
+ );
+
+ const hasBlockingDialog = selectedAction !== null;
+
+ const canRunSelectionShortcut = useCallback(() => {
+ return selected.length > 0 && !hasBlockingDialog && !hasBlockingOverlay();
+ }, [hasBlockingDialog, selected.length]);
+
+ const handleTrashShortcut = useCallback(() => {
+ if (canRunSelectionShortcut() && canArchive) {
+ openTrashConfirm();
+ }
+ }, [canArchive, canRunSelectionShortcut, openTrashConfirm]);
+
+ const handleClearSelectionShortcut = useCallback(() => {
+ if (canRunSelectionShortcut()) {
+ clearSelected();
+ }
+ }, [canRunSelectionShortcut, clearSelected]);
+
+ useBulkActionsShortcuts(
+ handleTrashShortcut,
+ handleClearSelectionShortcut,
+ isTrashed,
+ );
+
+ const handleConfirmTrash = async () => {
+ closeTrashConfirm();
+ try {
+ await archiveSelected();
+ } finally {
+ clearSelected();
+ }
+ };
const isVisible = selected.length > 0 && selectedAction !== "confirm-move";
- const hasSelectedItems = useMemo(
- () => !!selectedItems && !_.isEmpty(selectedItems),
- [selectedItems],
+ const hasSelectedItems = selectedItems !== null && selectedItems.length > 0;
+ const canMove = useMemo(
+ () => selected.every((item) => canMoveItem(item, collection)),
+ [selected, collection],
);
+ const handleBulkMoveStart = useCallback(() => {
+ setSelectedItems([...selected]);
+ setSelectedAction("move");
+ }, [selected, setSelectedAction, setSelectedItems]);
+
const handleCloseModal = () => {
setSelectedItems(null);
setSelectedAction(null);
@@ -65,9 +132,6 @@ export const CollectionBulkActions = memo(
setRememberedDestination(null);
};
- const tryOrClear = (promise: Promise<any>) =>
- promise.finally(() => clearSelected());
-
const handleConfirmedBulkQuestionMove = async () => {
if (rememberedDestination) {
handleCloseModal();
@@ -77,14 +141,11 @@ export const CollectionBulkActions = memo(
const doMove = async (destination: Destination) => {
if (selectedItems) {
- await tryOrClear(
- Promise.all(
- selectedItems
- .filter(isMovable)
- // Unjustified type cast. FIXME
- .map((item) => setCollection(item as MovableItem, destination)),
- ),
- );
+ await Promise.all(
+ selectedItems
+ .filter(isMovable)
+ .map((item) => setCollection(item, destination)),
+ ).finally(clearSelected);
}
handleCloseModal();
};
@@ -137,7 +198,7 @@ export const CollectionBulkActions = memo(
return (
<>
<BulkActionBar message={actionMessage} opened={isVisible}>
- {isTrashedCollection(collection) ? (
+ {isTrashed ? (
<ArchivedBulkActions
collection={collection}
selectedItems={selectedItems}
@@ -149,38 +210,47 @@ export const CollectionBulkActions = memo(
/>
) : (
<UnarchivedBulkActions
- selected={selected}
- collection={collection}
- clearSelected={clearSelected}
- setSelectedItems={setSelectedItems}
- setSelectedAction={setSelectedAction}
+ onRequestMove={canMove ? handleBulkMoveStart : undefined}
+ onRequestTrash={canArchive ? openTrashConfirm : undefined}
/>
)}
</BulkActionBar>
- {selectedItems && hasSelectedItems && selectedAction === "copy" && (
+ <ConfirmModal
+ opened={isTrashConfirmOpen}
+ data-testid="move-to-trash-confirmation"
+ title={ngettext(
+ msgid`Move ${selected.length} item to trash?`,
+ `Move ${selected.length} items to trash?`,
+ selected.length,
+ )}
+ message={t`You can restore items from the trash.`}
+ confirmButtonText={t`Move to trash`}
+ onConfirm={handleConfirmTrash}
+ onClose={closeTrashConfirm}
+ />
+
+ {hasSelectedItems && selectedAction === "copy" && (
<CollectionCopyEntityModal
- entityObject={selectedItems?.[0]}
+ entityObject={selectedItems[0]}
onClose={handleCloseModal}
onSaved={handleCloseModal}
/>
)}
- {selectedItems && hasSelectedItems && selectedAction === "move" && (
+ {hasSelectedItems && selectedAction === "move" && (
<BulkMoveModal
selectedItems={selectedItems}
onClose={handleCancelModal}
onMove={handleBulkMove}
- initialCollectionId={
- isTrashedCollection(collection) ? "root" : collection.id
- }
+ initialCollectionId={isTrashed ? "root" : collection.id}
recentAndSearchFilter={recentAndSearchFilter}
/>
)}
{hasSelectedItems && selectedAction === "confirm-move" && (
<QuestionMoveConfirmModal
- selectedItems={selectedItems || []}
+ selectedItems={selectedItems}
onConfirm={handleConfirmedBulkQuestionMove}
onClose={handleCloseModal}
destination={rememberedDestination}
@@ -191,4 +261,30 @@ export const CollectionBulkActions = memo(
},
);
+function useBulkActionsShortcuts(
+ handleTrashShortcut: () => void,
+ handleClearSelectionShortcut: () => void,
+ isTrashed: boolean,
+) {
+ const shortcutsToRegister: RegisterShortcutProps[] = useMemo(() => {
+ const shortcuts: RegisterShortcutProps[] = [
+ {
+ id: "collection-clear-selection",
+ perform: handleClearSelectionShortcut,
+ },
+ ];
+
+ if (!isTrashed) {
+ shortcuts.push({
+ id: "collection-send-items-to-trash",
+ perform: handleTrashShortcut,
+ });
+ }
+
+ return shortcuts;
+ }, [handleClearSelectionShortcut, handleTrashShortcut, isTrashed]);
+
+ useRegisterShortcut(shortcutsToRegister, [shortcutsToRegister]);
+}
+
CollectionBulkActions.displayName = "CollectionBulkActions";
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx
index 0083474d4ee..2ebd1b0b454 100644
--- a/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/UnarchivedBulkActions.tsx
@@ -1,82 +1,25 @@
-import { useMemo } from "react";
import { t } from "ttag";
-import { archiveAndTrack } from "metabase/archive/analytics";
-import { useSetArchive } from "metabase/archive/hooks";
-import { canArchiveItem } from "metabase/common/collections/utils";
import { BulkActionButton } from "metabase/common/components/BulkActionBar";
-import { canMoveItem } from "metabase/common/hooks";
-import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
-import type { Collection, CollectionItem } from "metabase-types/api";
type UnarchivedBulkActionsProps = {
- selected: any[];
- collection: Collection;
- clearSelected: () => void;
- setSelectedItems: (items: CollectionItem[] | null) => void;
- setSelectedAction: (action: string) => void;
+ onRequestMove?: () => void;
+ onRequestTrash?: () => void;
};
export const UnarchivedBulkActions = ({
- selected,
- collection,
- clearSelected,
- setSelectedItems,
- setSelectedAction,
+ onRequestMove,
+ onRequestTrash,
}: UnarchivedBulkActionsProps) => {
- const archive = useSetArchive();
-
- // archive
- const canArchive = useMemo(() => {
- return selected.every((item) => canArchiveItem(item, collection));
- }, [selected, collection]);
-
- const handleBulkArchive = async () => {
- const actions = selected.map((item) => {
- return archiveAndTrack({
- archive: async () => {
- await archive(item, true, { notify: false });
- },
- model: item.model,
- modelId: item.id,
- triggeredFrom: "collection",
- });
- });
-
- Promise.all(actions).finally(() => clearSelected());
- };
-
- // move
- const canMove = useMemo(() => {
- return selected.every((item) => canMoveItem(item, collection));
- }, [selected, collection]);
-
- const handleBulkMoveStart = () => {
- setSelectedItems(selected);
- setSelectedAction("move");
- };
-
- useRegisterShortcut(
- [
- {
- id: "collection-send-items-to-trash",
- perform: () => {
- handleBulkArchive();
- },
- },
- ],
- [selected],
- );
-
return (
<>
<BulkActionButton
- disabled={!canMove}
- onClick={handleBulkMoveStart}
+ disabled={onRequestMove == null}
+ onClick={onRequestMove}
>{t`Move`}</BulkActionButton>
<BulkActionButton
- disabled={!canArchive}
- onClick={handleBulkArchive}
+ disabled={onRequestTrash == null}
+ onClick={onRequestTrash}
>{t`Move to trash`}</BulkActionButton>
</>
);
diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-archive.ts b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-archive.ts
new file mode 100644
index 00000000000..d126b0c7b33
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/use-bulk-archive.ts
@@ -0,0 +1,66 @@
+import { useCallback, useMemo } from "react";
+
+import { archiveAndTrack } from "metabase/archive/analytics";
+import {
+ type ArchivableItem,
+ type ArchivableModel,
+ useSetArchive,
+} from "metabase/archive/hooks";
+import { canArchiveItem } from "metabase/common/collections/utils";
+import type {
+ Collection,
+ CollectionItem,
+ CollectionItemModel,
+} from "metabase-types/api";
+
+const ARCHIVABLE_MODELS: ReadonlySet<CollectionItemModel> = new Set([
+ "card",
+ "metric",
+ "dataset",
+ "snippet",
+ "document",
+ "dashboard",
+ "collection",
+ "exploration",
+] satisfies Extract<CollectionItemModel, ArchivableModel>[]);
+
+const isArchivableItem = (
+ item: CollectionItem,
+): item is CollectionItem & ArchivableItem => ARCHIVABLE_MODELS.has(item.model);
+
+export const useBulkArchive = (
+ selected: CollectionItem[],
+ collection: Collection,
+) => {
+ const archive = useSetArchive();
+ const archivableSelected = useMemo(
+ () => selected.filter(isArchivableItem),
+ [selected],
+ );
+
+ const canArchive = useMemo(
+ () =>
+ archivableSelected.length === selected.length &&
+ archivableSelected.every((item) => canArchiveItem(item, collection)),
+ [archivableSelected, selected.length, collection],
+ );
+
+ const archiveSelected = useCallback(
+ () =>
+ Promise.all(
+ archivableSelected.map((item) =>
+ archiveAndTrack({
+ archive: async () => {
+ await archive(item, true, { notify: false });
+ },
+ model: item.model,
+ modelId: item.id,
+ triggeredFrom: "collection",
+ }),
+ ),
+ ),
+ [archive, archivableSelected],
+ );
+
+ return { canArchive, archiveSelected };
+};
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx
new file mode 100644
index 00000000000..dcb4478f668
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx
@@ -0,0 +1,371 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupBookmarksEndpoints,
+ setupCollectionByIdEndpoint,
+ setupCollectionItemsEndpoint,
+ setupCollectionsEndpoints,
+ setupDashboardQuestionCandidatesEndpoint,
+ setupDatabasesEndpoints,
+ setupNullGetUserKeyValueEndpoints,
+ setupSearchEndpoints,
+ setupUserMetabotPermissionsEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { Route } from "metabase/router";
+import type { Collection, CollectionItem } from "metabase-types/api";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+} from "metabase-types/api/mocks";
+
+import { CollectionContent } from "./CollectionContent";
+
+const defaultCollection = createMockCollection({
+ id: 1,
+ name: "Shortcut collection",
+ can_write: true,
+});
+
+const pinnedDashboard = createMockCollectionItem({
+ id: 1,
+ name: "Pinned dashboard",
+ model: "dashboard",
+ collection_position: 1,
+});
+
+const tableQuestion = createMockCollectionItem({
+ id: 3,
+ name: "Table question",
+ model: "card",
+ collection_position: null,
+});
+
+const nonArchivableCollection = createMockCollectionItem({
+ id: 4,
+ name: "Read-only nested collection",
+ model: "collection",
+ can_write: false,
+ collection_position: null,
+});
+
+const defaultItems = [pinnedDashboard, tableQuestion];
+
+async function setup({
+ collection = defaultCollection,
+ collectionItems = defaultItems,
+}: {
+ collection?: Collection;
+ collectionItems?: CollectionItem[];
+} = {}) {
+ setupCollectionByIdEndpoint({ collections: [collection] });
+ setupCollectionsEndpoints({ collections: [collection] });
+ setupCollectionItemsEndpoint({ collection, collectionItems });
+ setupBookmarksEndpoints([]);
+ setupDatabasesEndpoints([]);
+ setupSearchEndpoints([]);
+ setupNullGetUserKeyValueEndpoints();
+ setupDashboardQuestionCandidatesEndpoint([]);
+ setupUserMetabotPermissionsEndpoint();
+
+ fetchMock.put(`path:/api/card/${tableQuestion.id}`, tableQuestion);
+ fetchMock.put(`path:/api/dashboard/${pinnedDashboard.id}`, pinnedDashboard);
+
+ renderWithProviders(
+ <Route
+ path="/"
+ element={<CollectionContent collectionId={collection.id} />}
+ />,
+ { withRouter: true, withDND: true, withKBar: true },
+ );
+
+ if (collection.type !== "trash") {
+ await screen.findByTestId("pinned-items");
+ }
+ await screen.findByText(tableQuestion.name);
+}
+
+function getRowSelectionButton(itemName: string) {
+ const row = screen.getByRole("row", { name: new RegExp(itemName) });
+ const selectionCell = within(row).getByTestId("collection-entry-check");
+ return within(selectionCell).getByRole("button");
+}
+
+function getPinnedSection() {
+ return within(screen.getByTestId("pinned-items"));
+}
+
+async function selectTableQuestion() {
+ await userEvent.click(getRowSelectionButton(tableQuestion.name));
+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();
+}
+
+async function openTableQuestionActions() {
+ const row = screen.getByRole("row", { name: new RegExp(tableQuestion.name) });
+ await userEvent.click(within(row).getByRole("button", { name: "Actions" }));
+ expect(await screen.findByRole("menu")).toBeInTheDocument();
+}
+
+async function openTypeFilter() {
+ await userEvent.click(screen.getByTestId("collection-type-filter-button"));
+ const popover = await screen.findByTestId("collection-type-filter-popover");
+ expect(popover).toBeInTheDocument();
+ return popover;
+}
+
+describe("CollectionContent selection shortcuts", () => {
+ it("clears a mixed selection with Escape", async () => {
+ await setup();
+ await selectTableQuestion();
+ await userEvent.click(
+ getPinnedSection().getByRole("checkbox", { name: pinnedDashboard.name }),
+ );
+ expect(await screen.findByText("2 items selected")).toBeInTheDocument();
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(screen.queryByText(/items? selected/)).not.toBeInTheDocument();
+ expect(
+ getPinnedSection().getByRole("link", {
+ name: new RegExp(pinnedDashboard.name),
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it("does nothing when Escape is pressed without a selection", async () => {
+ await setup();
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(screen.queryByText(/items? selected/)).not.toBeInTheDocument();
+ });
+
+ it("opens the trash confirmation with Delete", async () => {
+ await setup();
+ await selectTableQuestion();
+
+ await userEvent.keyboard("{Delete}");
+
+ expect(
+ await screen.findByTestId("move-to-trash-confirmation"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Move 1 item to trash?")).toBeInTheDocument();
+ const modal = screen.getByTestId("move-to-trash-confirmation");
+ expect(
+ within(modal).getByRole("button", { name: "Move to trash" }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it("opens the trash confirmation with Backspace", async () => {
+ await setup();
+ await selectTableQuestion();
+
+ await userEvent.keyboard("{Backspace}");
+
+ expect(
+ await screen.findByTestId("move-to-trash-confirmation"),
+ ).toBeInTheDocument();
+ });
+
+ it.each(["Delete", "Backspace"])(
+ "opens the trash confirmation with %s after selecting all",
+ async (key) => {
+ await setup();
+ const selectAll = screen.getByLabelText("Select all items");
+ await userEvent.click(selectAll);
+ expect(selectAll).toHaveFocus();
+
+ await userEvent.keyboard(`{${key}}`);
+
+ expect(
+ await screen.findByTestId("move-to-trash-confirmation"),
+ ).toBeInTheDocument();
+ },
+ );
+
+ it("clears a select-all selection with Escape while the checkbox is focused", async () => {
+ await setup();
+ const selectAll = screen.getByLabelText("Select all items");
+ await userEvent.click(selectAll);
+ expect(selectAll).toHaveFocus();
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(screen.queryByText(/items? selected/)).not.toBeInTheDocument();
+ });
+
+ it("does not open the trash confirmation for non-archivable items", async () => {
+ await setup({
+ collectionItems: [...defaultItems, nonArchivableCollection],
+ });
+ await userEvent.click(getRowSelectionButton(nonArchivableCollection.name));
+ expect(await screen.findByText("1 item selected")).toBeInTheDocument();
+
+ await userEvent.keyboard("{Delete}");
+
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it("archives the selection after confirmation", async () => {
+ await setup();
+ await selectTableQuestion();
+ await userEvent.keyboard("{Delete}");
+
+ const modal = await screen.findByTestId("move-to-trash-confirmation");
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Move to trash" }),
+ );
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls(`path:/api/card/${tableQuestion.id}`, {
+ method: "PUT",
+ }),
+ ).toHaveLength(1);
+ });
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText(/items? selected/)).not.toBeInTheDocument();
+ });
+
+ it("keeps the selection after cancelling", async () => {
+ await setup();
+ await selectTableQuestion();
+ await userEvent.keyboard("{Delete}");
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Cancel" }),
+ );
+
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it("closes the confirmation with Escape and keeps the selection", async () => {
+ await setup();
+ await selectTableQuestion();
+ await userEvent.keyboard("{Delete}");
+ expect(
+ await screen.findByTestId("move-to-trash-confirmation"),
+ ).toBeInTheDocument();
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it("closes an open item menu with Escape and keeps the selection", async () => {
+ await setup();
+ await selectTableQuestion();
+ await openTableQuestionActions();
+
+ await userEvent.keyboard("{Escape}");
+
+ await waitFor(() => {
+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();
+ });
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it.each(["Delete", "Backspace"])(
+ "does not open the trash confirmation with %s while an item menu is open",
+ async (key) => {
+ await setup();
+ await selectTableQuestion();
+ await openTableQuestionActions();
+
+ await userEvent.keyboard(`{${key}}`);
+
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ },
+ );
+
+ it("closes the type filter with Escape and keeps the selection", async () => {
+ await setup();
+ await selectTableQuestion();
+ const popover = await openTypeFilter();
+ popover.focus();
+
+ await userEvent.keyboard("{Escape}");
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("collection-type-filter-popover"),
+ ).not.toBeInTheDocument();
+ });
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it.each(["Delete", "Backspace"])(
+ "does not open the trash confirmation with %s while the type filter is open",
+ async (key) => {
+ await setup();
+ await selectTableQuestion();
+ const popover = await openTypeFilter();
+ const filterCheckbox = within(popover).getByRole("checkbox", {
+ name: "Dashboard",
+ });
+ filterCheckbox.focus();
+ expect(filterCheckbox).toHaveFocus();
+
+ await userEvent.keyboard(`{${key}}`);
+
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("collection-type-filter-popover"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ },
+ );
+
+ it("does not open the confirmation from the collection search input", async () => {
+ await setup();
+ await selectTableQuestion();
+ const searchInput = screen.getByRole("textbox", {
+ name: "Search items in this collection",
+ });
+ await userEvent.type(searchInput, "test");
+
+ await userEvent.keyboard("{Delete}");
+
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+ });
+
+ it("does not bind trash shortcuts in the trash collection", async () => {
+ await setup({
+ collection: createMockCollection({
+ ...defaultCollection,
+ type: "trash",
+ }),
+ });
+ await selectTableQuestion();
+
+ await userEvent.keyboard("{Delete}");
+ expect(
+ screen.queryByTestId("move-to-trash-confirmation"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("1 item selected")).toBeInTheDocument();
+
+ await userEvent.keyboard("{Escape}");
+ expect(screen.queryByText(/items? selected/)).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/common/components/ItemsTable/Columns.tsx b/frontend/src/metabase/common/components/ItemsTable/Columns.tsx
index 6370e0071da..15353268609 100644
--- a/frontend/src/metabase/common/components/ItemsTable/Columns.tsx
+++ b/frontend/src/metabase/common/components/ItemsTable/Columns.tsx
@@ -13,6 +13,7 @@ import { PLUGIN_MODERATION } from "metabase/plugins";
import { Checkbox, Ellipsified, type IconProps, Tooltip } from "metabase/ui";
import { modelToUrl } from "metabase/urls";
import { isTouchDevice } from "metabase/utils/browser";
+import { isPlainKey } from "metabase/utils/keyboard";
import { getUserName } from "metabase/utils/user";
import type {
CollectionItem,
@@ -84,6 +85,16 @@ export const Columns = {
checked={!!selectedItems?.length}
indeterminate={!!selectedItems?.length && !!hasUnselected}
onChange={hasUnselected ? onSelectAll : onSelectNone}
+ onKeyDown={(event) => {
+ if (
+ // Blurs the checkbox when these keys are pressed so that shortcuts can work
+ isPlainKey(event, "Escape") ||
+ isPlainKey(event, "Delete") ||
+ isPlainKey(event, "Backspace")
+ ) {
+ event.currentTarget.blur();
+ }
+ }}
aria-label={t`Select all items`}
/>
</BulkSelectWrapper>
diff --git a/frontend/src/metabase/palette/shortcuts/collection.ts b/frontend/src/metabase/palette/shortcuts/collection.ts
index 5abbce621f5..0d4eb888033 100644
--- a/frontend/src/metabase/palette/shortcuts/collection.ts
+++ b/frontend/src/metabase/palette/shortcuts/collection.ts
@@ -1,11 +1,23 @@
import { t } from "ttag";
+import type { ShortcutGroup } from "../types";
+
+const shortcutGroup: ShortcutGroup = "collection";
+
export const collectionShortcuts = {
"collection-send-items-to-trash": {
get name() {
- return t`Move collection items to trash`;
+ return t`Move selected items to trash`;
+ },
+ shortcut: ["(Delete|Backspace)"],
+ shortcutDisplay: ["Delete", "Backspace"],
+ shortcutGroup,
+ },
+ "collection-clear-selection": {
+ get name() {
+ return t`Clear selection`;
},
- shortcut: ["$mod+backspace"],
- shortcutGroup: "collection" as const,
+ shortcut: ["Escape"],
+ shortcutGroup,
},
};