Skip to content

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

Allow drag-and-drop into sub-collections shown in the collection items table (#78839)

Andersonfa991d5496d2
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.js
index 79ac3a7933c..a690ed0a9ea 100644
--- a/e2e/test/scenarios/collections/collections.cy.spec.js
+++ b/e2e/test/scenarios/collections/collections.cy.spec.js
@@ -512,6 +512,116 @@ describe("scenarios > collection defaults", () => {
cy.findByText("Orders");
});
+ it("should be able to drag an item into a sub-collection shown in the items table (metabase#37329)", () => {
+ H.createDocument({
+ name: "Quarterly Notes",
+ collection_id: null,
+ document: {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "Notes" }],
+ attrs: { _id: "1" },
+ },
+ ],
+ },
+ });
+ H.createQuestion({
+ name: "Count of orders",
+ type: "metric",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ display: "scalar",
+ });
+
+ visitRootCollection();
+
+ cy.log("Drag a question into the sub-collection row");
+ cy.findByTestId("collection-table").within(() => {
+ cy.findByText("Orders").as("dragSubject");
+ cy.findByText("First collection").as("dropTarget");
+ });
+
+ H.dragAndDrop("dragSubject", "dropTarget");
+
+ // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
+ cy.findByText("Moved question");
+ cy.findByTestId("collection-table")
+ .findByText("Orders")
+ .should("not.exist");
+
+ cy.log("Drag a document into the sub-collection row");
+ cy.findByTestId("collection-table").within(() => {
+ cy.findByText("Quarterly Notes").as("documentDragSubject");
+ cy.findByText("First collection").as("documentDropTarget");
+ });
+
+ H.dragAndDrop("documentDragSubject", "documentDropTarget");
+
+ cy.findByTestId("collection-table")
+ .findByText("Quarterly Notes")
+ .should("not.exist");
+
+ cy.log("Drag a metric into the sub-collection row");
+ cy.findByTestId("collection-table").within(() => {
+ cy.findByText("Count of orders").as("metricDragSubject");
+ cy.findByText("First collection").as("metricDropTarget");
+ });
+
+ H.dragAndDrop("metricDragSubject", "metricDropTarget");
+
+ cy.findByTestId("collection-table")
+ .findByText("Count of orders")
+ .should("not.exist");
+
+ H.visitCollection(FIRST_COLLECTION_ID);
+ cy.findByTestId("collection-table").findByText("Orders");
+ cy.findByTestId("collection-table").findByText("Quarterly Notes");
+ cy.findByTestId("collection-table").findByText("Count of orders");
+ });
+
+ it("should reject dragging a subcollection directly or in a mixed selection (metabase#37329)", () => {
+ H.createCollection({ name: "Destination collection" });
+ visitRootCollection();
+
+ cy.intercept(
+ "PUT",
+ /\/api\/(card|collection)\/\d+$/,
+ cy.spy().as("moveRequest"),
+ );
+
+ cy.log("Subcollections cannot initiate a drag");
+ cy.findByTestId("collection-table")
+ .findByText("First collection")
+ .closest("a")
+ .should("have.attr", "draggable", "false");
+ cy.findByTestId("items-drag-preview").should("not.exist");
+ cy.findByTestId("collection-table")
+ .findByText("First collection")
+ .should("be.visible");
+ cy.get("@moveRequest").should("not.have.been.called");
+
+ cy.log("A mixed selection is rejected as one operation");
+ cy.findByTestId("collection-table").within(() => {
+ selectItemUsingCheckbox("Orders");
+ selectItemUsingCheckbox("First collection");
+ cy.findByText("Orders").as("dragSubject");
+ cy.findByText("Destination collection").as("dropTarget");
+ });
+
+ H.dragAndDrop("dragSubject", "dropTarget");
+
+ cy.findByTestId("collection-table").within(() => {
+ cy.findByText("Orders").should("be.visible");
+ cy.findByText("First collection").should("be.visible");
+ cy.findByText("Destination collection").should("be.visible");
+ });
+ cy.get("@moveRequest").should("not.have.been.called");
+ });
+
describe("nested collections with revoked parent access", () => {
const { first_name, last_name } = nocollection;
const revokedUsersPersonalCollectionName = `${first_name} ${last_name}'s Personal Collection`;
diff --git a/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionTable.tsx b/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionTable.tsx
index 72626c3c206..7f031f9ac12 100644
--- a/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionTable.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionTable.tsx
@@ -56,7 +56,7 @@ export const CleanupCollectionTable = ({
{/* Select */}
<Columns.Select.Col />
{/* Name */}
- <Columns.Name.Col isInDragLayer={false} />
+ <Columns.Name.Col />
{/* Collection */}
<TableColumn width="280px" />
{/* Last used at */}
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
index 5ccfce97626..31218a34bf4 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
@@ -1,5 +1,5 @@
import { useDisclosure } from "@mantine/hooks";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { type FileRejection, useDropzone } from "react-dropzone";
import { usePrevious } from "react-use";
import { match } from "ts-pattern";
@@ -15,10 +15,6 @@ import { listTag } from "metabase/api/tags";
import { ArchivedEntityBanner } from "metabase/archive/components/ArchivedEntityBanner";
import { useSetArchive } from "metabase/archive/hooks";
import { CollectionBulkActions } from "metabase/collections/components/CollectionBulkActions";
-import {
- type CollectionContentTableColumn,
- DEFAULT_VISIBLE_COLUMNS_LIST,
-} from "metabase/collections/components/CollectionContent/constants";
import PinnedItemOverview from "metabase/collections/components/PinnedItemOverview";
import Header from "metabase/collections/containers/CollectionHeader";
import { trackCollectionBookmarked } from "metabase/common/collections/analytics";
@@ -34,7 +30,6 @@ import {
isRootTrashCollection,
isTrashedCollection,
} from "metabase/common/collections/utils";
-import { getVisibleColumnsMap } from "metabase/common/components/ItemsTable/utils";
import { ItemsDragLayer } from "metabase/common/components/dnd/ItemsDragLayer";
import { useSetCollection, useToast } from "metabase/common/hooks";
import { useListSelect } from "metabase/common/hooks/use-list-select";
@@ -70,7 +65,6 @@ export const CollectionContentView = ({
uploadFile,
uploadsEnabled,
canCreateUploadInDb,
- visibleColumns = DEFAULT_VISIBLE_COLUMNS_LIST,
}: {
databases?: Database[];
bookmarks?: Bookmark[];
@@ -82,7 +76,6 @@ export const CollectionContentView = ({
uploadFile: UploadFile;
uploadsEnabled: boolean;
canCreateUploadInDb: boolean;
- visibleColumns?: CollectionContentTableColumn[];
}) => {
const dispatch = useDispatch();
const navigate = useNavigate();
@@ -155,11 +148,6 @@ export const CollectionContentView = ({
const setCollection = useSetCollection();
const [sendToast] = useToast();
- const visibleColumnsMap = useMemo(
- () => getVisibleColumnsMap(visibleColumns),
- [visibleColumns],
- );
-
const handleFileRejections = useCallback(
(rejected: FileRejection[]) => {
if (!rejected.length) {
@@ -351,12 +339,7 @@ export const CollectionContentView = ({
/>
</ErrorBoundary>
</CollectionMain>
- <ItemsDragLayer
- selectedItems={selected}
- pinnedItems={pinnedItems}
- collection={collection}
- visibleColumnsMap={visibleColumnsMap}
- />
+ <ItemsDragLayer />
</CollectionRoot>
);
};
diff --git a/frontend/src/metabase/common/collections/utils.ts b/frontend/src/metabase/common/collections/utils.ts
index d7dec76a60a..b788f417186 100644
--- a/frontend/src/metabase/common/collections/utils.ts
+++ b/frontend/src/metabase/common/collections/utils.ts
@@ -79,7 +79,7 @@ export function isPersonalCollection(
}
export function isRootTrashCollection(
- collection?: Pick<Collection, "type">,
+ collection?: Pick<Collection, "type"> | Pick<CollectionItem, "type">,
): boolean {
return collection?.type === "trash";
}
diff --git a/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.module.css b/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.module.css
new file mode 100644
index 00000000000..596d027b9e6
--- /dev/null
+++ b/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.module.css
@@ -0,0 +1,24 @@
+tr.draggedRow td {
+ background-color: var(--mb-color-background_surface-brand-subtle);
+}
+
+tr.dropTargetRow td {
+ background-color: var(--mb-color-background_surface-brand-subtle-hover);
+}
+
+tr.disabledRow {
+ opacity: 0.5;
+}
+
+tr.disabledRow:hover td {
+ background-color: var(--mb-color-background_page-primary);
+}
+
+tr.disabledRow:hover td > * {
+ color: inherit;
+}
+
+tr.disabledRow:hover td,
+tr.disabledRow:hover td * {
+ cursor: default;
+}
diff --git a/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.tsx b/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.tsx
index 90c2761667e..2766f04d2bc 100644
--- a/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.tsx
+++ b/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.tsx
@@ -1,10 +1,47 @@
+import cx from "classnames";
import type { PropsWithChildren } from "react";
import type { BaseItemsTableProps } from "metabase/common/components/ItemsTable/BaseItemsTable";
import { DefaultItemRenderer } from "metabase/common/components/ItemsTable/DefaultItemRenderer";
+import {
+ type CollectionDropTargetRenderProps,
+ CollectionRowDropTarget,
+} from "metabase/common/components/dnd/CollectionDropTarget";
import { ItemDragSource } from "metabase/common/components/dnd/ItemDragSource";
import type { CollectionItem } from "metabase-types/api";
+import S from "./BaseItemTableRow.module.css";
+
+export type ItemTableRowDndState =
+ | "idle"
+ | "dragged"
+ | "disabled"
+ | "drop-target"
+ | "drop-target-hovered";
+
+export function getItemTableRowDndState({
+ isDragActive,
+ isDragged,
+ highlighted,
+ hovered,
+}: Omit<
+ CollectionDropTargetRenderProps,
+ "connectDropTarget"
+>): ItemTableRowDndState {
+ switch (true) {
+ case !isDragActive:
+ return "idle";
+ case isDragged:
+ return "dragged";
+ case hovered:
+ return "drop-target-hovered";
+ case highlighted:
+ return "drop-target";
+ default:
+ return "disabled";
+ }
+}
+
type BaseItemTableRowProps = PropsWithChildren<
{
testIdPrefix: string;
@@ -83,24 +120,28 @@ export const ItemDragSourceTableRow = ({
onToggleSelected,
item,
isSelected,
- itemKey,
collection,
onClick,
selectedItems,
onDrop,
visibleColumnsMap,
}: BaseItemTableRowProps) => {
- return (
- <ItemDragSource
- item={item}
- collection={collection}
- isSelected={isSelected}
- selected={selectedItems}
- onDrop={onDrop}
- key={`item-drag-source-${itemKey}`}
- >
- {/* We can't use <TableRow> due to React DnD throwing an error: Only native element nodes can now be passed to React DnD connectors. */}
- <tr key={itemKey} data-testid={testIdPrefix} style={{ height: 48 }}>
+ const renderDraggableRow = (
+ dropTargetProps: CollectionDropTargetRenderProps,
+ ) => {
+ const dndState = getItemTableRowDndState(dropTargetProps);
+ const row = (
+ // We can't use <TableRow> due to React DnD throwing an error: Only native element nodes can now be passed to React DnD connectors.
+ <tr
+ data-dnd-state={dndState}
+ data-testid={testIdPrefix}
+ style={{ height: 48 }}
+ className={cx({
+ [S.draggedRow]: dndState === "dragged",
+ [S.disabledRow]: dndState === "disabled",
+ [S.dropTargetRow]: dndState === "drop-target-hovered",
+ })}
+ >
<ItemComponent
testIdPrefix={testIdPrefix}
item={item}
@@ -118,6 +159,36 @@ export const ItemDragSourceTableRow = ({
visibleColumnsMap={visibleColumnsMap}
/>
</tr>
- </ItemDragSource>
+ );
+ const dropTargetRow = dropTargetProps.connectDropTarget(row);
+
+ if (item.model === "collection") {
+ return dropTargetRow;
+ }
+
+ return (
+ <ItemDragSource
+ item={item}
+ collection={collection}
+ isSelected={isSelected}
+ selected={selectedItems}
+ onDrop={onDrop}
+ >
+ {dropTargetRow}
+ </ItemDragSource>
+ );
+ };
+
+ const isDroppableCollectionRow =
+ item.model === "collection" && !item.archived;
+
+ return (
+ <CollectionRowDropTarget
+ collection={item}
+ isDropTarget={isDroppableCollectionRow}
+ item={item}
+ >
+ {renderDraggableRow}
+ </CollectionRowDropTarget>
);
};
diff --git a/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.unit.spec.ts b/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.unit.spec.ts
new file mode 100644
index 00000000000..fd1cf64ae0a
--- /dev/null
+++ b/frontend/src/metabase/common/components/ItemsTable/BaseItemTableRow.unit.spec.ts
@@ -0,0 +1,54 @@
+import { getItemTableRowDndState } from "./BaseItemTableRow";
+
+describe("getItemTableRowDndState", () => {
+ it.each([
+ {
+ expected: "idle",
+ isDragActive: false,
+ isDragged: false,
+ highlighted: false,
+ hovered: false,
+ },
+ {
+ expected: "dragged",
+ isDragActive: true,
+ isDragged: true,
+ highlighted: false,
+ hovered: false,
+ },
+ {
+ expected: "disabled",
+ isDragActive: true,
+ isDragged: false,
+ highlighted: false,
+ hovered: false,
+ },
+ {
+ expected: "drop-target",
+ isDragActive: true,
+ isDragged: false,
+ highlighted: true,
+ hovered: false,
+ },
+ {
+ expected: "drop-target-hovered",
+ isDragActive: true,
+ isDragged: false,
+ highlighted: true,
+ hovered: true,
+ },
+ ])("should return $expected", ({ expected, ...state }) => {
+ expect(getItemTableRowDndState(state)).toBe(expected);
+ });
+
+ it("should prioritize the dragged state over destination states", () => {
+ expect(
+ getItemTableRowDndState({
+ isDragActive: true,
+ isDragged: true,
+ highlighted: true,
+ hovered: true,
+ }),
+ ).toBe("dragged");
+ });
+});
diff --git a/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable.styled.tsx b/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable.styled.tsx
index 2dc3479c52b..77a2d53a7a9 100644
--- a/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable.styled.tsx
+++ b/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable.styled.tsx
@@ -19,18 +19,9 @@ import { FixedSizeIcon, Text } from "metabase/ui";
import type { ResponsiveProps } from "./utils";
import { getContainerQuery } from "./utils";
-type TableProps = TableHTMLAttributes<HTMLTableElement> & {
- isInDragLayer?: boolean;
-};
-
-export const Table = styled(
- (props: TableProps) => (
- <table {...props} className={cx(props.className, AdminS.ContentTable)} />
- ),
- {
- shouldForwardProp: (prop) => prop !== "isInDragLayer",
- },
-)`
+export const Table = styled((props: TableHTMLAttributes<HTMLTableElement>) => (
+ <table {...props} className={cx(props.className, AdminS.ContentTable)} />
+))`
background-color: var(--mb-color-background_page-primary);
table-layout: fixed;
border-collapse: unset;
@@ -52,8 +43,6 @@ export const Table = styled(
}
}
}
-
- ${(props) => (props.isInDragLayer ? `width: 50vw;` : "")}
`;
export const hideResponsively = ({
diff --git a/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable/BaseItemsTable.tsx b/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable/BaseItemsTable.tsx
index 59a8343784e..e96a95151ea 100644
--- a/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable/BaseItemsTable.tsx
+++ b/frontend/src/metabase/common/components/ItemsTable/BaseItemsTable/BaseItemsTable.tsx
@@ -118,11 +118,7 @@ export type BaseItemsTableProps = {
onMove?: OnMove;
onDrop?: () => void;
getIsSelected?: (item: any) => boolean;
- /** Used for dragging */
- headless?: boolean;
- isInDragLayer?: boolean;
ItemComponent?: (props: ItemRendererProps) => JSX.Element;
- includeColGroup?: boolean;
onClick?: (item: CollectionItem) => void;
visibleColumnsMap: CollectionContentTableColumnsMap;
} & Partial<Omit<HTMLAttributes<HTMLTableElement>, "onCopy" | "onClick">>;
@@ -146,10 +142,7 @@ export const BaseItemsTable = ({
onSelectAll,
onSelectNone,
getIsSelected = () => false,
- headless = false,
- isInDragLayer = false,
ItemComponent = DefaultItemRenderer,
- includeColGroup = true,
visibleColumnsMap,
onClick,
...props
@@ -158,75 +151,67 @@ export const BaseItemsTable = ({
const isTrashed = !!collection && isTrashedCollection(collection);
return (
- <Table isInDragLayer={isInDragLayer} {...props}>
- {includeColGroup && (
- <colgroup>
- {canSelect && <Columns.Select.Col />}
- {visibleColumnsMap["type"] && <Columns.Type.Col />}
+ <Table {...props}>
+ <colgroup>
+ {canSelect && <Columns.Select.Col />}
+ {visibleColumnsMap["type"] && <Columns.Type.Col />}
+ {visibleColumnsMap["name"] && <Columns.Name.Col />}
+ {visibleColumnsMap["description"] && <Columns.Description.Col />}
+ {visibleColumnsMap["lastEditedBy"] && <Columns.LastEditedBy.Col />}
+ {visibleColumnsMap["lastEditedAt"] && <Columns.LastEditedAt.Col />}
+ {visibleColumnsMap["actionMenu"] && <Columns.ActionMenu.Col />}
+ {visibleColumnsMap["archive"] && <Columns.Archive.Col />}
+ <Columns.RightEdge.Col />
+ </colgroup>
+ <thead
+ data-testid={isPinned ? "pinned-items-table-head" : "items-table-head"}
+ >
+ <tr>
+ {canSelect && (
+ <Columns.Select.Header
+ selectedItems={selectedItems}
+ hasUnselected={hasUnselected}
+ onSelectAll={onSelectAll}
+ onSelectNone={onSelectNone}
+ />
+ )}
+ {visibleColumnsMap["type"] && (
+ <Columns.Type.Header
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ />
+ )}
{visibleColumnsMap["name"] && (
- <Columns.Name.Col isInDragLayer={isInDragLayer} />
+ <Columns.Name.Header
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ />
+ )}
+ {visibleColumnsMap["description"] && (
+ <Columns.Description.Header
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ />
+ )}
+ {visibleColumnsMap["lastEditedBy"] && (
+ <Columns.LastEditedBy.Header
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ isTrashed={isTrashed}
+ />
+ )}
+ {visibleColumnsMap["lastEditedAt"] && (
+ <Columns.LastEditedAt.Header
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ isTrashed={isTrashed}
+ />
)}
- {visibleColumnsMap["description"] && <Columns.Description.Col />}
- {visibleColumnsMap["lastEditedBy"] && <Columns.LastEditedBy.Col />}
- {visibleColumnsMap["lastEditedAt"] && <Columns.LastEditedAt.Col />}
- {visibleColumnsMap["actionMenu"] && <Columns.ActionMenu.Col />}
- {visibleColumnsMap["archive"] && <Columns.Archive.Col />}
- <Columns.RightEdge.Col />
- </colgroup>
- )}
- {!headless && (
- <thead
- data-testid={
- isPinned ? "pinned-items-table-head" : "items-table-head"
- }
- >
- <tr>
- {canSelect && (
- <Columns.Select.Header
- selectedItems={selectedItems}
- hasUnselected={hasUnselected}
- onSelectAll={onSelectAll}
- onSelectNone={onSelectNone}
- />
- )}
- {visibleColumnsMap["type"] && (
- <Columns.Type.Header
- sortingOptions={sortingOptions}
- onSortingOptionsChange={onSortingOptionsChange}
- />
- )}
- {visibleColumnsMap["name"] && (
- <Columns.Name.Header
- sortingOptions={sortingOptions}
- onSortingOptionsChange={onSortingOptionsChange}
- />
- )}
- {visibleColumnsMap["description"] && (
- <Columns.Description.Header
- sortingOptions={sortingOptions}
- onSortingOptionsChange={onSortingOptionsChange}
- />
- )}
- {visibleColumnsMap["lastEditedBy"] && (
- <Columns.LastEditedBy.Header
- sortingOptions={sortingOptions}
- onSortingOptionsChange={onSortingOptionsChange}
- isTrashed={isTrashed}
- />
- )}
- {visibleColumnsMap["lastEditedAt"] && (
- <Columns.LastEditedAt.Header
- sortingOptions={sortingOptions}
- onSortingOptionsChange={onSortingOptionsChange}
- isTrashed={isTrashed}
- />
- )}
- {visibleColumnsMap["actionMenu"] && <Columns.ActionMenu.Header />}
- {visibleColumnsMap["archive"] && <Columns.Archive.Header />}
- <Columns.RightEdge.Header />
- </tr>
- </thead>
- )}
+ {visibleColumnsMap["actionMenu"] && <Columns.ActionMenu.Header />}
+ {visibleColumnsMap["archive"] && <Columns.Archive.Header />}
+ <Columns.RightEdge.Header />
+ </tr>
+ </thead>
<BaseItemsTableBody
items={items}
getIsSelected={getIsSelected}
diff --git a/frontend/src/metabase/common/components/ItemsTable/Columns.tsx b/frontend/src/metabase/common/components/ItemsTable/Columns.tsx
index d1db802cd78..2d182e11534 100644
--- a/frontend/src/metabase/common/components/ItemsTable/Columns.tsx
+++ b/frontend/src/metabase/common/components/ItemsTable/Columns.tsx
@@ -53,7 +53,11 @@ const ItemLinkComponent = ({
}
return (
- <ItemLink to={modelToUrl(item)} onClick={() => onClick?.(item)}>
+ <ItemLink
+ draggable={item.model !== "collection"}
+ to={modelToUrl(item)}
+ onClick={() => onClick?.(item)}
+ >
{children}
</ItemLink>
);
@@ -142,9 +146,7 @@ export const Columns = {
),
},
Name: {
- Col: ({ isInDragLayer }: { isInDragLayer: boolean }) => (
- <col style={{ width: isInDragLayer ? "10rem" : undefined }} />
- ),
+ Col: () => <col />,
Header: ({ sortingOptions, onSortingOptionsChange }: HeaderProps) => (
<SortableColumnHeader
name="name"
diff --git a/frontend/src/metabase/common/components/dnd/CollectionDropTarget.tsx b/frontend/src/metabase/common/components/dnd/CollectionDropTarget.tsx
index 0d4825ece27..b7f03b2539b 100644
--- a/frontend/src/metabase/common/components/dnd/CollectionDropTarget.tsx
+++ b/frontend/src/metabase/common/components/dnd/CollectionDropTarget.tsx
@@ -1,52 +1,187 @@
-import type { DropTargetMonitor } from "react-dnd";
+import type { ComponentType, ReactElement } from "react";
+import { Component } from "react";
+import type {
+ ConnectDropTarget,
+ DropTargetConnector,
+ DropTargetMonitor,
+} from "react-dnd";
import { DropTarget } from "react-dnd";
import {
+ canPlaceEntityInCollection,
canonicalCollectionId,
isRootTrashCollection,
} from "metabase/common/collections/utils";
+import { isMovable } from "metabase/common/hooks";
import type { Collection, CollectionItem } from "metabase-types/api";
import { DropArea } from "./DropArea";
-import { MoveableDragTypes } from ".";
+import { MoveableDragTypes, isItemDragPayload } from ".";
+
+const EMPTY_DRAGGED_ITEMS: CollectionItem[] = [];
+
+export type DropTargetCollection = Pick<Collection, "id"> &
+ Partial<Pick<CollectionItem, "type" | "can_write">>;
interface CollectionDropTargetOwnProps {
- collection: Collection;
+ collection: DropTargetCollection;
+ isDropTarget?: boolean;
+}
+
+/** Strips card subtypes from the overloaded `CollectionItem.type` field. */
+function getDropTargetCollectionType(
+ collection: DropTargetCollection,
+): Collection["type"] {
+ if (
+ collection.type === "metric" ||
+ collection.type === "model" ||
+ collection.type === "question"
+ ) {
+ return undefined;
+ }
+ return collection.type;
+}
+
+export function canDropItemsIntoCollection({
+ items,
+ collection,
+}: CollectionDropTargetOwnProps & { items: CollectionItem[] }): boolean {
+ if (items.length === 0) {
+ return false;
+ }
+
+ const isTrashCollection = isRootTrashCollection(collection);
+ if (!isTrashCollection && collection.can_write === false) {
+ return false;
+ }
+
+ return items.every((item) => {
+ const droppingToTrashFromTrash = isTrashCollection && item.archived;
+ const droppingToSameCollection =
+ canonicalCollectionId(item.collection_id) ===
+ canonicalCollectionId(collection.id);
+
+ return (
+ isMovable(item) &&
+ item.model !== "collection" &&
+ canPlaceEntityInCollection(
+ item.model,
+ getDropTargetCollectionType(collection),
+ ) &&
+ !droppingToSameCollection &&
+ !droppingToTrashFromTrash
+ );
+ });
}
+const dropTargetSpec = {
+ drop(props: CollectionDropTargetOwnProps) {
+ return { collection: props.collection };
+ },
+ canDrop(props: CollectionDropTargetOwnProps, monitor: DropTargetMonitor) {
+ if (props.isDropTarget === false) {
+ return false;
+ }
+
+ const payload = monitor.getItem();
+ if (!isItemDragPayload(payload)) {
+ return false;
+ }
+ return canDropItemsIntoCollection({
+ items: payload.items,
+ collection: props.collection,
+ });
+ },
+};
+
+const collectDropTarget = (
+ connect: DropTargetConnector,
+ monitor: DropTargetMonitor,
+) => ({
+ highlighted: monitor.canDrop(),
+ hovered: monitor.isOver() && monitor.canDrop(),
+ connectDropTarget: connect.dropTarget(),
+});
+
+const collectCollectionRowDropTarget = (
+ connect: DropTargetConnector,
+ monitor: DropTargetMonitor,
+) => {
+ const payload = monitor.getItem();
+ const isDragActive = isItemDragPayload(payload);
+
+ return {
+ ...collectDropTarget(connect, monitor),
+ draggedItems: isDragActive ? payload.items : EMPTY_DRAGGED_ITEMS,
+ isDragActive,
+ };
+};
+
export const CollectionDropTarget = DropTarget(
MoveableDragTypes,
- {
- drop(props: CollectionDropTargetOwnProps) {
- return { collection: props.collection };
- },
- canDrop(props: CollectionDropTargetOwnProps, monitor: DropTargetMonitor) {
- const { collection } = props;
- // Unjustified type cast. FIXME
- const { item } = monitor.getItem() as { item: CollectionItem };
- if (
- !isRootTrashCollection(collection) &&
- collection.can_write === false
- ) {
- return false;
- }
- const droppingToTrashFromTrash =
- isRootTrashCollection(collection) && item.archived;
- const droppingToSameCollection =
- canonicalCollectionId(item.collection_id) ===
- canonicalCollectionId(collection.id);
- return (
- item.model !== "collection" &&
- !droppingToSameCollection &&
- !droppingToTrashFromTrash
- );
- },
- },
- (connect, monitor) => ({
- highlighted: monitor.canDrop(),
- hovered: monitor.isOver() && monitor.canDrop(),
- connectDropTarget: connect.dropTarget(),
- }),
- // react-dnd v7 HOC types can't express the own/collected props split
+ dropTargetSpec,
+ collectDropTarget,
+ // react-dnd v4 HOC types can't express the own/collected props split
)(DropArea as any);
+
+export interface CollectionDropTargetRenderProps {
+ connectDropTarget: ConnectDropTarget;
+ hovered: boolean;
+ highlighted: boolean;
+ isDragged: boolean;
+ isDragActive: boolean;
+}
+
+interface CollectionRowDropTargetProps extends CollectionDropTargetOwnProps {
+ item: CollectionItem;
+ children: (props: CollectionDropTargetRenderProps) => ReactElement;
+}
+
+interface CollectionRowDropTargetCollectedProps extends Omit<
+ CollectionDropTargetRenderProps,
+ "isDragged"
+> {
+ draggedItems: CollectionItem[];
+}
+
+class CollectionRowDropTargetInner extends Component<
+ CollectionRowDropTargetProps & CollectionRowDropTargetCollectedProps
+> {
+ render() {
+ const {
+ children,
+ connectDropTarget,
+ draggedItems,
+ hovered,
+ highlighted,
+ isDragActive,
+ item,
+ } = this.props;
+ const isDragged = draggedItems.some(
+ (draggedItem) =>
+ draggedItem.model === item.model && draggedItem.id === item.id,
+ );
+
+ return children({
+ connectDropTarget,
+ hovered,
+ highlighted,
+ isDragged,
+ isDragActive,
+ });
+ }
+}
+
+/**
+ * Renders no markup of its own: `children` must attach the received
+ * `connectDropTarget` to a native element. Usable where `DropArea`'s
+ * wrapper `<div>` would be invalid markup, such as around a table `<tr>`.
+ */
+export const CollectionRowDropTarget: ComponentType<CollectionRowDropTargetProps> =
+ DropTarget(
+ MoveableDragTypes,
+ dropTargetSpec,
+ collectCollectionRowDropTarget,
+ // react-dnd v4 HOC types can't express the own/collected props split
+ )(CollectionRowDropTargetInner as any);
diff --git a/frontend/src/metabase/common/components/dnd/CollectionDropTarget.unit.spec.ts b/frontend/src/metabase/common/components/dnd/CollectionDropTarget.unit.spec.ts
new file mode 100644
index 00000000000..d94d05c6094
--- /dev/null
+++ b/frontend/src/metabase/common/components/dnd/CollectionDropTarget.unit.spec.ts
@@ -0,0 +1,195 @@
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import { mockSettings } from "__support__/settings";
+import {
+ createMockCollectionItem,
+ createMockTokenFeatures,
+} from "metabase-types/api/mocks";
+
+import { canDropItemsIntoCollection } from "./CollectionDropTarget";
+
+describe("canDropItemsIntoCollection", () => {
+ beforeEach(() => {
+ mockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ });
+ setupEnterpriseOnlyPlugin("library");
+ });
+
+ it("should allow dropping movable items into another writable collection (metabase#37329)", () => {
+ const items = [
+ createMockCollectionItem({
+ id: 1,
+ model: "card",
+ collection_id: null,
+ }),
+ createMockCollectionItem({
+ id: 2,
+ model: "document",
+ collection_id: null,
+ }),
+ createMockCollectionItem({
+ id: 3,
+ model: "metric",
+ collection_id: null,
+ }),
+ ];
+ const collection = createMockCollectionItem({
+ id: 4,
+ model: "collection",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(true);
+ });
+
+ it("should not allow dropping into a read-only collection", () => {
+ const items = [createMockCollectionItem({ id: 1, collection_id: null })];
+ const collection = createMockCollectionItem({
+ id: 2,
+ model: "collection",
+ can_write: false,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(false);
+ });
+
+ it("should not allow dropping when any item is already in the target collection", () => {
+ const items = [
+ createMockCollectionItem({ id: 1, collection_id: null }),
+ createMockCollectionItem({ id: 2, collection_id: 3 }),
+ ];
+ const collection = createMockCollectionItem({
+ id: 3,
+ model: "collection",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(false);
+ });
+
+ it("should not allow dropping when any dragged item is a collection", () => {
+ const items = [
+ createMockCollectionItem({ id: 1, collection_id: null }),
+ createMockCollectionItem({
+ id: 2,
+ model: "collection",
+ collection_id: null,
+ }),
+ ];
+ const collection = createMockCollectionItem({
+ id: 3,
+ model: "collection",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(false);
+ });
+
+ it("should not allow dropping into a collection in the dragged set (metabase#37329)", () => {
+ const collection = createMockCollectionItem({
+ id: 2,
+ model: "collection",
+ can_write: true,
+ });
+ const items = [
+ createMockCollectionItem({ id: 1, collection_id: null }),
+ collection,
+ ];
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(false);
+ });
+
+ it("should not allow dropping when any selected item is not movable", () => {
+ const items = [
+ createMockCollectionItem({ id: 1, collection_id: null }),
+ createMockCollectionItem({
+ id: 2,
+ model: "indexed-entity",
+ collection_id: null,
+ }),
+ ];
+ const collection = createMockCollectionItem({
+ id: 3,
+ model: "collection",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(false);
+ });
+
+ it("should require every item to be valid for the collection type", () => {
+ const items = [
+ createMockCollectionItem({
+ id: 1,
+ model: "metric",
+ collection_id: null,
+ }),
+ createMockCollectionItem({
+ id: 2,
+ model: "card",
+ collection_id: null,
+ }),
+ ];
+ const collection = createMockCollectionItem({
+ id: 3,
+ model: "collection",
+ type: "library-metrics",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection })).toBe(false);
+ expect(canDropItemsIntoCollection({ items: [items[0]], collection })).toBe(
+ true,
+ );
+ });
+
+ it("should allow moving unarchived items to the trash without write access", () => {
+ const items = [
+ createMockCollectionItem({ id: 1, collection_id: null }),
+ createMockCollectionItem({
+ id: 2,
+ model: "document",
+ collection_id: null,
+ }),
+ ];
+ const trash = createMockCollectionItem({
+ id: 3,
+ model: "collection",
+ type: "trash",
+ can_write: false,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection: trash })).toBe(true);
+ });
+
+ it("should not allow moving any already archived item to the trash again", () => {
+ const items = [
+ createMockCollectionItem({ id: 1, collection_id: null }),
+ createMockCollectionItem({
+ id: 2,
+ collection_id: null,
+ archived: true,
+ }),
+ ];
+ const trash = createMockCollectionItem({
+ id: 3,
+ model: "collection",
+ type: "trash",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items, collection: trash })).toBe(
+ false,
+ );
+ });
+
+ it("should not allow an empty drag payload", () => {
+ const collection = createMockCollectionItem({
+ id: 1,
+ model: "collection",
+ can_write: true,
+ });
+
+ expect(canDropItemsIntoCollection({ items: [], collection })).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/common/components/dnd/ItemDragSource.tsx b/frontend/src/metabase/common/components/dnd/ItemDragSource.tsx
index 25e60306e8b..1ad5e90486d 100644
--- a/frontend/src/metabase/common/components/dnd/ItemDragSource.tsx
+++ b/frontend/src/metabase/common/components/dnd/ItemDragSource.tsx
@@ -21,7 +21,7 @@ import {
} from "metabase/common/hooks";
import type { Collection, CollectionItem } from "metabase-types/api";
-import { dragTypeForItem } from ".";
+import { type ItemDragPayload, dragTypeForItem, isItemDragPayload } from ".";
interface ItemDragSourceInnerProps {
connectDragSource: ConnectDragSource;
@@ -72,7 +72,11 @@ interface DragSourceOwnProps {
const DragSourceComponent = DragSource(
(props: DragSourceOwnProps) => dragTypeForItem(props.item),
{
- canDrag({ isSelected, selected, collection }: DragSourceOwnProps) {
+ canDrag({ item, isSelected, selected, collection }: DragSourceOwnProps) {
+ if (item.model === "collection") {
+ return false;
+ }
+
// can't drag if can't write the parent collection
if (
collection &&
@@ -87,42 +91,44 @@ const DragSourceComponent = DragSource(
return isSelected || numSelected === 0;
},
beginDrag(props: DragSourceOwnProps) {
- return { item: props.item };
+ const items =
+ props.isSelected && props.selected?.length
+ ? [...props.selected]
+ : [props.item];
+
+ return { items } satisfies ItemDragPayload;
},
async endDrag(
- {
- selected,
- onDrop,
- onMoveError,
- setPinned,
- setCollection,
- }: DragSourceOwnProps,
+ { onDrop, onMoveError, setPinned, setCollection }: DragSourceOwnProps,
monitor: DragSourceMonitor,
) {
if (!monitor.didDrop()) {
return;
}
- // Unjustified type cast. FIXME
- const { item } = monitor.getItem() as { item: CollectionItem };
+ const payload = monitor.getItem();
+ if (!isItemDragPayload(payload)) {
+ return;
+ }
+ const { items } = payload;
// Unjustified type cast. FIXME
const { collection, pinIndex } = monitor.getDropResult() as {
collection?: Collection;
pinIndex?: number;
};
- if (item) {
- const items = selected && selected.length > 0 ? selected : [item];
+ if (items.length > 0) {
try {
if (collection !== undefined) {
+ if (!items.every(isMovable)) {
+ return;
+ }
await Promise.all(
- items
- .filter(isMovable)
- // Unjustified type cast. FIXME
- .map((i) => setCollection(i as MovableItem, collection)),
+ items.map((item) => setCollection(item, collection)),
);
} else if (pinIndex !== undefined) {
- await Promise.all(
- items.filter(isPinnable).map((i) => setPinned(i, pinIndex)),
- );
+ if (!items.every(isPinnable)) {
+ return;
+ }
+ await Promise.all(items.map((item) => setPinned(item, pinIndex)));
}
onDrop?.();
@@ -137,7 +143,7 @@ const DragSourceComponent = DragSource(
connectDragPreview: connect.dragPreview(),
isDragging: monitor.isDragging(),
}),
- // react-dnd v7 HOC types can't express the own/collected props split
+ // react-dnd v4 HOC types can't express the own/collected props split
)(ItemDragSourceInner as any);
interface ItemDragSourceProps {
diff --git a/frontend/src/metabase/common/components/dnd/ItemsDragLayer.module.css b/frontend/src/metabase/common/components/dnd/ItemsDragLayer.module.css
new file mode 100644
index 00000000000..38f886e8e28
--- /dev/null
+++ b/frontend/src/metabase/common/components/dnd/ItemsDragLayer.module.css
@@ -0,0 +1,14 @@
+.dragLayer {
+ position: fixed;
+ top: 0;
+ left: 0;
+ pointer-events: none;
+ z-index: 999;
+}
+
+.preview {
+ display: flex;
+ align-items: center;
+ width: 14.5rem;
+ min-height: 3.25rem;
+}
diff --git a/frontend/src/metabase/common/components/dnd/ItemsDragLayer.tsx b/frontend/src/metabase/common/components/dnd/ItemsDragLayer.tsx
index 96435e51466..e1f0319ce76 100644
--- a/frontend/src/metabase/common/components/dnd/ItemsDragLayer.tsx
+++ b/frontend/src/metabase/common/components/dnd/ItemsDragLayer.tsx
@@ -1,61 +1,58 @@
import { Component } from "react";
import { DragLayer, type XYCoord } from "react-dnd";
-import _ from "underscore";
+import { msgid, ngettext } from "ttag";
-import type { CollectionContentTableColumnsMap } from "metabase/common/collections/columns";
-import PinnedItemCard from "metabase/common/collections/components/PinnedItemCard";
-import { BaseItemsTable } from "metabase/common/components/ItemsTable/BaseItemsTable";
-import type { ItemRendererProps } from "metabase/common/components/ItemsTable/DefaultItemRenderer";
-import { Box, Portal } from "metabase/ui";
-import type { Collection, CollectionItem } from "metabase-types/api";
+import { Box, Paper, Portal, Text } from "metabase/ui";
+
+import S from "./ItemsDragLayer.module.css";
+
+import { isItemDragPayload } from ".";
interface ItemsDragLayerInnerProps {
isDragging: boolean;
currentOffset: XYCoord | null;
- selectedItems: CollectionItem[];
- pinnedItems: CollectionItem[];
- item: { item: CollectionItem } | null;
- collection: Collection;
- visibleColumnsMap: CollectionContentTableColumnsMap;
+ payload: unknown;
+}
+
+export function MoveItemsDragPreview({ count }: { count: number }) {
+ return (
+ <Paper
+ bg="background_surface-brand-subtle"
+ className={S.preview}
+ data-testid="items-drag-preview"
+ px="md"
+ py="sm"
+ radius="sm"
+ shadow="md"
+ withBorder
+ >
+ <Text fw={700}>
+ {ngettext(msgid`Move ${count} item`, `Move ${count} items`, count)}
+ </Text>
+ </Paper>
+ );
}
-class ItemsDragLayerInner extends Component<ItemsDragLayerInnerProps> {
+export class ItemsDragLayerInner extends Component<ItemsDragLayerInnerProps> {
render() {
- const {
- isDragging,
- currentOffset,
- selectedItems,
- pinnedItems,
- item,
- collection,
- visibleColumnsMap,
- } = this.props;
- if (!isDragging || !currentOffset) {
+ const { isDragging, currentOffset, payload } = this.props;
+
+ if (!isDragging || !currentOffset || !isItemDragPayload(payload)) {
return null;
}
- const items = selectedItems.length > 0 ? selectedItems : [item!.item];
- const x = currentOffset.x + window.scrollX;
- const y = currentOffset.y + window.scrollY;
+
return (
<Portal>
<Box
- pos="absolute"
- left={0}
- top={0}
- opacity={0.65}
+ aria-hidden
+ className={S.dragLayer}
style={{
- transform: `translate(${x}px, ${y}px)`,
- pointerEvents: "none",
- zIndex: 999,
+ transform: `translate3d(${currentOffset.x + 12}px, ${
+ currentOffset.y + 12
+ }px, 0)`,
}}
>
- <DraggedItems
- items={items}
- draggedItem={item!.item}
- pinnedItems={pinnedItems}
- collection={collection}
- visibleColumnsMap={visibleColumnsMap}
- />
+ <MoveItemsDragPreview count={payload.items.length} />
</Box>
</Portal>
);
@@ -63,89 +60,8 @@ class ItemsDragLayerInner extends Component<ItemsDragLayerInnerProps> {
}
export const ItemsDragLayer = DragLayer((monitor) => ({
- item: monitor.getItem(),
- // itemType: monitor.getItemType(),
- initialOffset: monitor.getInitialSourceClientOffset(),
- currentOffset: monitor.getSourceClientOffset(),
+ payload: monitor.getItem(),
+ currentOffset: monitor.getClientOffset(),
isDragging: monitor.isDragging(),
- // react-dnd v7 HOC types can't express the own/collected props split
+ // react-dnd v4 HOC types can't express the own/collected props split
}))(ItemsDragLayerInner as any);
-
-interface DraggedItemsProps {
- items: CollectionItem[];
- draggedItem: CollectionItem;
- pinnedItems: CollectionItem[];
- collection: Collection;
- visibleColumnsMap: CollectionContentTableColumnsMap;
-}
-
-class DraggedItems extends Component<DraggedItemsProps> {
- shouldComponentUpdate(nextProps: DraggedItemsProps) {
- // necessary for decent drag performance
- return (
- nextProps.items.length !== this.props.items.length ||
- nextProps.pinnedItems.length !== this.props.pinnedItems.length ||
- nextProps.draggedItem !== this.props.draggedItem
- );
- }
-
- checkIsPinned = (item: CollectionItem) => {
- const { pinnedItems } = this.props;
- const index = pinnedItems.findIndex(
- (i) => i.model === item.model && i.id === item.id,
- );
- return index >= 0;
- };
-
- renderItem = ({ item, ...itemProps }: ItemRendererProps) => {
- const isPinned = this.checkIsPinned(item);
- const key = `${item.model}-${item.id}`;
-
- if (isPinned) {
- return (
- <td style={{ padding: 0 }}>
- <PinnedItemCard
- key={key}
- item={item}
- collection={this.props.collection}
- onCopy={_.noop}
- onMove={_.noop}
- />
- </td>
- );
- }
- return (
- <BaseItemsTable.Item
- key={key}
- {...itemProps}
- item={item}
- isPinned={false}
- draggable={false}
- />
- );
- };
-
- render() {
- const { items, draggedItem, visibleColumnsMap } = this.props;
- const index = _.findIndex(items, draggedItem);
- const allPinned = items.every((item) => this.checkIsPinned(item));
- return (
- <div
- style={{
- position: "absolute",
- transform: index > 0 ? `translate(0px, ${-index * 72}px)` : undefined,
- }}
- >
- <BaseItemsTable
- items={items}
- ItemComponent={(props) => this.renderItem(props)}
- headless
- isInDragLayer
- style={{ width: allPinned ? 400 : undefined }}
- includeColGroup={!allPinned}
- visibleColumnsMap={visibleColumnsMap}
- />
- </div>
- );
- }
-}
diff --git a/frontend/src/metabase/common/components/dnd/ItemsDragLayer.unit.spec.tsx b/frontend/src/metabase/common/components/dnd/ItemsDragLayer.unit.spec.tsx
new file mode 100644
index 00000000000..db74341bc05
--- /dev/null
+++ b/frontend/src/metabase/common/components/dnd/ItemsDragLayer.unit.spec.tsx
@@ -0,0 +1,35 @@
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { ItemsDragLayerInner, MoveItemsDragPreview } from "./ItemsDragLayer";
+
+describe("ItemsDragLayerInner", () => {
+ it("should ignore native drag payloads (UXW-233)", () => {
+ renderWithProviders(
+ <ItemsDragLayerInner
+ currentOffset={{ x: 0, y: 0 }}
+ isDragging
+ payload={{ urls: ["https://example.com"] }}
+ />,
+ );
+
+ expect(screen.queryByTestId("items-drag-preview")).not.toBeInTheDocument();
+ });
+});
+
+describe("MoveItemsDragPreview", () => {
+ it("should describe a single dragged item", () => {
+ renderWithProviders(<MoveItemsDragPreview count={1} />);
+
+ expect(screen.getByTestId("items-drag-preview")).toHaveTextContent(
+ "Move 1 item",
+ );
+ });
+
+ it("should describe multiple dragged items", () => {
+ renderWithProviders(<MoveItemsDragPreview count={2} />);
+
+ expect(screen.getByTestId("items-drag-preview")).toHaveTextContent(
+ "Move 2 items",
+ );
+ });
+});
diff --git a/frontend/src/metabase/common/components/dnd/PinDropTarget.tsx b/frontend/src/metabase/common/components/dnd/PinDropTarget.tsx
index 6d2a7e8a2b5..395b5262982 100644
--- a/frontend/src/metabase/common/components/dnd/PinDropTarget.tsx
+++ b/frontend/src/metabase/common/components/dnd/PinDropTarget.tsx
@@ -2,11 +2,11 @@ import type { DropTargetMonitor } from "react-dnd";
import { DropTarget } from "react-dnd";
import { isItemPinned } from "metabase/common/collections/utils";
-import type { CollectionItem } from "metabase-types/api";
+import { isPinnable } from "metabase/common/hooks";
import { DropArea } from "./DropArea";
-import { PinnableDragTypes } from ".";
+import { PinnableDragTypes, isItemDragPayload } from ".";
interface PinDropTargetOwnProps {
variant: "pin" | "unpin";
@@ -23,15 +23,18 @@ export const PinDropTarget = DropTarget(
}
},
canDrop(props: PinDropTargetOwnProps, monitor: DropTargetMonitor) {
- // Unjustified type cast. FIXME
- const { item } = monitor.getItem() as { item: CollectionItem };
+ const payload = monitor.getItem();
+ if (!isItemDragPayload(payload)) {
+ return false;
+ }
+ const { items } = payload;
const { variant } = props;
// NOTE: not necessary to check collection permission here since we
// enforce it when beginning to drag and item within the same collection
if (variant === "pin") {
- return !isItemPinned(item);
+ return items.every((item) => isPinnable(item) && !isItemPinned(item));
} else if (variant === "unpin") {
- return isItemPinned(item);
+ return items.every((item) => isPinnable(item) && isItemPinned(item));
}
return false;
@@ -42,5 +45,5 @@ export const PinDropTarget = DropTarget(
hovered: monitor.isOver() && monitor.canDrop(),
connectDropTarget: connect.dropTarget(),
}),
- // react-dnd v7 HOC types can't express the own/collected props split
+ // react-dnd v4 HOC types can't express the own/collected props split
)(DropArea as any);
diff --git a/frontend/src/metabase/common/components/dnd/PinnedItemSortDropTarget.tsx b/frontend/src/metabase/common/components/dnd/PinnedItemSortDropTarget.tsx
index d6c648cc2d7..c32b9ccf3ea 100644
--- a/frontend/src/metabase/common/components/dnd/PinnedItemSortDropTarget.tsx
+++ b/frontend/src/metabase/common/components/dnd/PinnedItemSortDropTarget.tsx
@@ -2,11 +2,11 @@ import type { DropTargetMonitor } from "react-dnd";
import { DropTarget } from "react-dnd";
import { isItemPinned } from "metabase/common/collections/utils";
-import type { CollectionItem } from "metabase-types/api";
+import { isPinnable } from "metabase/common/hooks";
import { DropArea } from "./DropArea";
-import { PinnableDragTypes } from ".";
+import { PinnableDragTypes, isItemDragPayload } from ".";
interface PinnedItemSortDropTargetOwnProps {
isFrontTarget: boolean;
@@ -28,32 +28,39 @@ export const PinnedItemSortDropTarget = DropTarget(
props: PinnedItemSortDropTargetOwnProps,
monitor: DropTargetMonitor,
) {
- // Unjustified type cast. FIXME
- const { item } = monitor.getItem() as { item: CollectionItem };
+ const payload = monitor.getItem();
+ if (!isItemDragPayload(payload)) {
+ return false;
+ }
+ const { items } = payload;
const { isFrontTarget, isBackTarget, itemModel, pinIndex } = props;
// NOTE: not necessary to check collection permission here since we
// enforce it when beginning to drag and item within the same collection
- if (!isItemPinned(item)) {
+ if (!items.every((item) => isPinnable(item) && isItemPinned(item))) {
+ return false;
+ }
+
+ if (itemModel != null && items.some((item) => item.model !== itemModel)) {
return false;
}
- if (itemModel != null && item.model !== itemModel) {
+ if (pinIndex == null) {
return false;
}
if (isFrontTarget) {
- const isInFrontOfItem =
- pinIndex != null &&
- item.collection_position != null &&
- pinIndex < item.collection_position;
- return isInFrontOfItem;
+ return items.every(
+ (item) =>
+ item.collection_position != null &&
+ pinIndex < item.collection_position,
+ );
} else if (isBackTarget) {
- const isBehindItem =
- pinIndex != null &&
- item.collection_position != null &&
- pinIndex > item.collection_position;
- return isBehindItem;
+ return items.every(
+ (item) =>
+ item.collection_position != null &&
+ pinIndex > item.collection_position,
+ );
}
return false;
@@ -64,5 +71,5 @@ export const PinnedItemSortDropTarget = DropTarget(
hovered: monitor.isOver() && monitor.canDrop(),
connectDropTarget: connect.dropTarget(),
}),
- // react-dnd v7 HOC types can't express the own/collected props split
+ // react-dnd v4 HOC types can't express the own/collected props split
)(DropArea as any);
diff --git a/frontend/src/metabase/common/components/dnd/index.ts b/frontend/src/metabase/common/components/dnd/index.ts
index b0d687ef26f..dcf5dfd50e8 100644
--- a/frontend/src/metabase/common/components/dnd/index.ts
+++ b/frontend/src/metabase/common/components/dnd/index.ts
@@ -1,6 +1,21 @@
// NOTE: we currently use object's `model` property for the drag type
import type { CollectionItem } from "metabase-types/api";
+export interface ItemDragPayload {
+ items: CollectionItem[];
+}
+
+export function isItemDragPayload(
+ payload: unknown,
+): payload is ItemDragPayload {
+ return (
+ typeof payload === "object" &&
+ payload !== null &&
+ "items" in payload &&
+ Array.isArray(payload.items)
+ );
+}
+
export function dragTypeForItem(item: CollectionItem) {
return item.model;
}
@@ -13,6 +28,8 @@ export const DragTypes = {
COLLECTION: "collection",
PULSE: "pulse",
DATASET: "dataset",
+ METRIC: "metric",
+ DOCUMENT: "document",
};
export const PinnableDragTypes = [
@@ -20,6 +37,8 @@ export const PinnableDragTypes = [
DragTypes.DASHBOARD,
DragTypes.PULSE,
DragTypes.DATASET,
+ DragTypes.METRIC,
+ DragTypes.DOCUMENT,
];
export const MoveableDragTypes = [
@@ -28,4 +47,6 @@ export const MoveableDragTypes = [
DragTypes.COLLECTION,
DragTypes.PULSE,
DragTypes.DATASET,
+ DragTypes.METRIC,
+ DragTypes.DOCUMENT,
];