Skip to content

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

Collection filters UX followup (#79863)

Andrei Chernykh5b705231d78d
diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.edn
index dfab7040c23..6e8f1022dab 100644
--- a/.clj-kondo/ratchets.edn
+++ b/.clj-kondo/ratchets.edn
@@ -29,8 +29,8 @@
:metabase/namespace-name 4
:metabase/prefer-with-dynamic-fn-redefs 28
:metabase/test-helpers-use-non-thread-safe-functions 18
- :metabase/validate-defendpoint-has-response-schema 439
- :metabase/validate-defendpoint-query-params-use-kebab-case 50
+ :metabase/validate-defendpoint-has-response-schema 427
+ :metabase/validate-defendpoint-query-params-use-kebab-case 48
:metabase/validate-defendpoint-route-uses-kebab-case 44
:metabase/validate-deftest 10
:missing-docstring 12
diff --git a/e2e/test/scenarios/collections/collection-pinned-overview.cy.spec.js b/e2e/test/scenarios/collections/collection-pinned-overview.cy.spec.js
index 82597adb807..82fbfe9c0ba 100644
--- a/e2e/test/scenarios/collections/collection-pinned-overview.cy.spec.js
+++ b/e2e/test/scenarios/collections/collection-pinned-overview.cy.spec.js
@@ -54,7 +54,7 @@ describe("scenarios > collection pinned items overview", () => {
cy.signInAsAdmin();
cy.intercept("POST", "/api/card/**/query").as("getCardQuery");
- cy.intercept("GET", "/api/**/items?pinned_state*").as("getPinnedItems");
+ cy.intercept("GET", "/api/**/items?pinned-state*").as("getPinnedItems");
cy.intercept("GET", "/api/**/items?models*").as("getCollectionItems");
});
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.js
index f692139d82c..4fe2d20562d 100644
--- a/e2e/test/scenarios/collections/collections.cy.spec.js
+++ b/e2e/test/scenarios/collections/collections.cy.spec.js
@@ -25,7 +25,7 @@ describe("scenarios > collection defaults", () => {
beforeEach(() => {
H.restore();
cy.signInAsAdmin();
- cy.intercept("GET", "/api/**/items?pinned_state*").as("getPinnedItems");
+ cy.intercept("GET", "/api/**/items?pinned-state*").as("getPinnedItems");
cy.intercept("GET", "/api/collection/tree**").as("getTree");
cy.intercept("GET", "/api/collection/*/items?**").as("getCollectionItems");
});
@@ -1208,6 +1208,14 @@ describe("scenarios > collection items listing", () => {
H.createCollection({
name: "Quarterly revenue",
});
+ // Enough items to keep the search input and type filters visible.
+ _.times(10, (i) =>
+ H.createQuestion({
+ name: `Extra question ${i + 1}`,
+ collection_position: null,
+ query: TEST_QUESTION_QUERY,
+ }),
+ );
cy.signIn("normal");
H.createQuestion({
@@ -1299,9 +1307,17 @@ describe("scenarios > collection items listing", () => {
collection_position: null,
query: TEST_QUESTION_QUERY,
});
+ // Enough items to keep the search input and type filters visible.
+ _.times(10, (i) =>
+ H.createQuestion({
+ name: `Extra question ${i + 1}`,
+ collection_position: null,
+ query: TEST_QUESTION_QUERY,
+ }),
+ );
});
- it("should filter collection items by the available types", () => {
+ it("should filter collection items by the checked types", () => {
cy.intercept(
{
method: "GET",
@@ -1321,13 +1337,15 @@ describe("scenarios > collection items listing", () => {
cy.findByRole("button", { name: "Filter" }).click();
H.popover().within(() => {
- cy.findAllByRole("checkbox").should("have.length", 3);
- cy.findByLabelText("Collection").should("be.checked");
- cy.findByLabelText("Dashboard").should("be.checked");
- cy.findByLabelText("Question").should("be.checked");
- cy.findByLabelText("Model").should("not.exist");
+ cy.findAllByRole("checkbox").should("have.length", 8);
+ cy.findByLabelText("Collection").should("not.be.checked");
+ cy.findByLabelText("Dashboard").should("not.be.checked");
+ cy.findByLabelText("Question").should("not.be.checked");
+ cy.findByLabelText("Model").should("be.disabled");
+ cy.findByLabelText("Metric").should("be.disabled");
cy.findByRole("button", { name: "Apply" }).should("not.exist");
- cy.findByLabelText("Dashboard").click();
+ cy.findByLabelText("Question").click();
+ cy.findByLabelText("Collection").click();
});
cy.wait("@getTypeFilteredCollectionItems").then(({ request }) => {
@@ -1347,7 +1365,8 @@ describe("scenarios > collection items listing", () => {
.find('[class*="Indicator-indicator"]')
.should("exist");
- H.popover().findByLabelText("Dashboard").click();
+ H.popover().findByLabelText("Question").click();
+ H.popover().findByLabelText("Collection").click();
cy.findByTestId("collection-table")
.should("contain", "Revenue dashboard")
diff --git a/e2e/test/scenarios/dashboard-filters/parameters.cy.spec.js b/e2e/test/scenarios/dashboard-filters/parameters.cy.spec.js
index 21b532ebfb1..d3148adb5ff 100644
--- a/e2e/test/scenarios/dashboard-filters/parameters.cy.spec.js
+++ b/e2e/test/scenarios/dashboard-filters/parameters.cy.spec.js
@@ -611,7 +611,7 @@ describe("scenarios > dashboard > parameters", () => {
});
it("should retain the last used value for a dashboard filter", () => {
- cy.intercept("GET", "/api/**/items?pinned_state*").as("getPinnedItems");
+ cy.intercept("GET", "/api/**/items?pinned-state*").as("getPinnedItems");
H.filterWidget().click();
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
index 4a7a6cb216a..e65f554c25b 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
@@ -37,15 +37,15 @@
(str "collection/" (u/the-id collection) "/items")
:archived true)]
(is (empty? (filter #(= "table" (:model %)) (:data items))))))
- (testing "tables don't appear when pinned_state=is_pinned"
+ (testing "tables don't appear when pinned-state=is_pinned"
(let [items (mt/user-http-request :crowberto :get 200
(str "collection/" (u/the-id collection) "/items")
- :pinned_state "is_pinned")]
+ :pinned-state "is_pinned")]
(is (empty? (filter #(= "table" (:model %)) (:data items))))))
- (testing "tables appear when pinned_state=is_not_pinned"
+ (testing "tables appear when pinned-state=is_not_pinned"
(let [items (mt/user-http-request :crowberto :get 200
(str "collection/" (u/the-id collection) "/items")
- :pinned_state "is_not_pinned")]
+ :pinned-state "is_not_pinned")]
(is (= 1 (count (filter #(= "table" (:model %)) (:data items)))))))))))
(deftest collection-items-table-permissions-test
diff --git a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx
index 8abd0b6b875..2a4a62c8c06 100644
--- a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx
+++ b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx
@@ -46,8 +46,8 @@ export const SavedEntityList = ({
? {
id: collectionId,
models: [CARD_INFO[type].model],
- sort_column: "name",
- sort_direction: "asc",
+ "sort-column": "name",
+ "sort-direction": "asc",
}
: skipToken,
);
diff --git a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.unit.spec.tsx b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.unit.spec.tsx
index c0aabd6240c..20603ea5b43 100644
--- a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.unit.spec.tsx
@@ -37,8 +37,8 @@ function mockCollectionItemsEndpoint() {
fetchMock.get({
url: "path:/api/collection/root/items",
query: {
- sort_column: "name",
- sort_direction: "asc",
+ "sort-column": "name",
+ "sort-direction": "asc",
},
response: {
total: 3,
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
index 16d07cfa1b8..75c9b80ae79 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
@@ -206,13 +206,13 @@ describe("CollectionBrowser", () => {
it("should hide dashboard questions by default", async () => {
await setup();
- expect(getLastItemsRequestParam("show_dashboard_questions")).toBe("false");
+ expect(getLastItemsRequestParam("show-dashboard-questions")).toBe("false");
});
it("should show dashboard questions when showDashboardQuestions is true", async () => {
await setup({ props: { showDashboardQuestions: true } });
- expect(getLastItemsRequestParam("show_dashboard_questions")).toBe("true");
+ expect(getLastItemsRequestParam("show-dashboard-questions")).toBe("true");
});
it("should resolve collectionId=tenant to user's tenant collection", async () => {
diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.ts
index 8b836a645c3..02cc9bad744 100644
--- a/frontend/src/metabase-types/api/collection.ts
+++ b/frontend/src/metabase-types/api/collection.ts
@@ -9,7 +9,7 @@ import type {
import type { CardId, CardType } from "./card";
import type { DatabaseId } from "./database";
-import type { SortingOptions } from "./sorting";
+import type { SortDirection } from "./sorting";
import type { TableId } from "./table";
import type { UserId, UserInfo } from "./user";
export type CollectionNamespace =
@@ -167,19 +167,23 @@ export type ListCollectionItemsSortColumn =
| "last_edited_by"
| "model";
+// Query params are kebab-case, matching the endpoint. The sort params are spelled out here rather than
+// intersecting `SortingOptions`, which stays snake_case for the endpoints that still expect that (`/api/task`,
+// `/api/ee/stale/:id`, `/api/notification/admin`).
export type ListCollectionItemsRequest = {
id: CollectionId;
models?: (CollectionItemModel | "no_models")[];
q?: string;
- include_available_models?: boolean;
+ "include-available-models"?: boolean;
archived?: boolean;
- pinned_state?: "all" | "is_pinned" | "is_not_pinned";
+ "pinned-state"?: "all" | "is_pinned" | "is_not_pinned";
namespace?: CollectionNamespace;
- collection_type?: CollectionType;
- show_dashboard_questions?: boolean;
- include_library?: boolean;
-} & PaginationRequest &
- Partial<SortingOptions<ListCollectionItemsSortColumn>>;
+ "collection-type"?: CollectionType;
+ "show-dashboard-questions"?: boolean;
+ "include-library"?: boolean;
+ "sort-column"?: ListCollectionItemsSortColumn;
+ "sort-direction"?: SortDirection;
+} & PaginationRequest;
export type ListCollectionItemsResponse = {
data: CollectionItem[];
@@ -187,6 +191,20 @@ export type ListCollectionItemsResponse = {
available_models?: string[];
} & PaginationResponse;
+export type GetCollectionItemsMetadataRequest = {
+ id: CollectionId;
+ models?: CollectionItemModel[];
+ "show-dashboard-questions"?: boolean;
+ namespace?: CollectionNamespace;
+ "include-library"?: boolean;
+};
+
+export type CollectionItemsMetadata = {
+ available_models: string[];
+ // The size of the whole list, unlike the `total` of a paged, filtered items response.
+ total_items: number;
+};
+
export interface UpdateCollectionRequest {
id: RegularCollectionId;
name?: string;
diff --git a/frontend/src/metabase/api/collection.ts b/frontend/src/metabase/api/collection.ts
index e6c9a2172a9..786353434b2 100644
--- a/frontend/src/metabase/api/collection.ts
+++ b/frontend/src/metabase/api/collection.ts
@@ -1,11 +1,13 @@
import type {
Collection,
CollectionItemModel,
+ CollectionItemsMetadata,
CollectionPermissionsGraph,
CreateCollectionRequest,
DeleteCollectionRequest,
GetCollectionDashboardQuestionCandidatesRequest,
GetCollectionDashboardQuestionCandidatesResult,
+ GetCollectionItemsMetadataRequest,
ListCollectionItemsRequest,
ListCollectionItemsResponse,
ListCollectionsRequest,
@@ -82,6 +84,21 @@ export const collectionApi = Api.injectEndpoints({
{ type: "collection", id: `${id}-items` },
],
}),
+ getCollectionItemsMetadata: builder.query<
+ CollectionItemsMetadata,
+ GetCollectionItemsMetadataRequest
+ >({
+ query: ({ id, ...params }) => ({
+ method: "GET",
+ url: `/api/collection/${id}/items/metadata`,
+ params,
+ }),
+ // The metadata describes items of every model, so any item change may invalidate it.
+ providesTags: (_response, _error, { id }) => [
+ ...provideCollectionItemListTags([]),
+ { type: "collection", id: `${id}-items` },
+ ],
+ }),
getCollection: builder.query<Collection, getCollectionRequest>({
query: ({ id, ignore_error, ...params }) => {
return {
@@ -211,6 +228,7 @@ export const {
useListCollectionsQuery,
useListCollectionsTreeQuery,
useListCollectionItemsQuery,
+ useGetCollectionItemsMetadataQuery,
useGetCollectionQuery,
useGetCollectionPermissionsGraphQuery,
useUpdateCollectionPermissionsGraphMutation,
diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.ts
index 1d305b79edc..cea63334c62 100644
--- a/frontend/src/metabase/api/dashboard.ts
+++ b/frontend/src/metabase/api/dashboard.ts
@@ -15,7 +15,6 @@ import type {
GetPublicDashboard,
GetRemappedDashboardParameterValueRequest,
GetValidDashboardFilterFieldsRequest,
- ListCollectionItemsRequest,
ListCollectionItemsResponse,
ListDashboardsRequest,
ListDashboardsResponse,
@@ -162,10 +161,7 @@ export const dashboardApi = Api.injectEndpoints({
}),
listDashboardItems: builder.query<
ListCollectionItemsResponse,
- Omit<
- ListCollectionItemsRequest,
- "id" | "q" | "include_available_models"
- > & { id: DashboardId }
+ { id: DashboardId }
>({
query: ({ id, ...body }) => ({
method: "GET",
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx
index dcb4478f668..7ec5b95d1e0 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentShortcuts.unit.spec.tsx
@@ -52,6 +52,19 @@ const nonArchivableCollection = createMockCollectionItem({
const defaultItems = [pinnedDashboard, tableQuestion];
+// Enough items to keep the search input and type filters visible.
+const toolbarItems = [
+ ...defaultItems,
+ ...Array.from({ length: 10 }, (_, index) =>
+ createMockCollectionItem({
+ id: 100 + index,
+ name: `Extra card ${index + 1}`,
+ model: "card",
+ collection_position: null,
+ }),
+ ),
+];
+
async function setup({
collection = defaultCollection,
collectionItems = defaultItems,
@@ -295,7 +308,7 @@ describe("CollectionContent selection shortcuts", () => {
);
it("closes the type filter with Escape and keeps the selection", async () => {
- await setup();
+ await setup({ collectionItems: toolbarItems });
await selectTableQuestion();
const popover = await openTypeFilter();
popover.focus();
@@ -313,7 +326,7 @@ describe("CollectionContent selection shortcuts", () => {
it.each(["Delete", "Backspace"])(
"does not open the trash confirmation with %s while the type filter is open",
async (key) => {
- await setup();
+ await setup({ collectionItems: toolbarItems });
await selectTableQuestion();
const popover = await openTypeFilter();
const filterCheckbox = within(popover).getByRole("checkbox", {
@@ -335,7 +348,7 @@ describe("CollectionContent selection shortcuts", () => {
);
it("does not open the confirmation from the collection search input", async () => {
- await setup();
+ await setup({ collectionItems: toolbarItems });
await selectTableQuestion();
const searchInput = screen.getByRole("textbox", {
name: "Search items in this collection",
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
index 35e0a1d7afe..2a99ac6212a 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
@@ -10,12 +10,17 @@ import { usePrevious } from "react-use";
import { t } from "ttag";
import NoResultsImg from "assets/img/no_results.svg";
-import { skipToken, useListCollectionItemsQuery } from "metabase/api";
+import {
+ skipToken,
+ useGetCollectionItemsMetadataQuery,
+ useListCollectionItemsQuery,
+} from "metabase/api";
import {
ALL_MODELS,
COLLECTION_PAGE_SIZE,
type CollectionContentTableColumn,
DEFAULT_VISIBLE_COLUMNS_LIST,
+ FILTERS_VISIBILITY_THRESHOLD,
} from "metabase/collections/components/CollectionContent/constants";
import CollectionEmptyState from "metabase/collections/components/CollectionEmptyState";
import { trackCollectionItemsFiltered } from "metabase/common/collections/analytics";
@@ -67,18 +72,15 @@ const getDefaultSortingOptions = (
};
};
-const getQueryFilters = (
- models: CollectionItemModel[],
- selectedFilters: CollectionItemModel[] | null,
-): Pick<ListCollectionItemsRequest, "models"> => {
- if (selectedFilters == null) {
- return { models };
- }
-
- return {
- models: selectedFilters.length > 0 ? selectedFilters : ["no_models"],
- };
-};
+// `itemsSorting` keeps the snake_case `SortingOptions` shape that `BaseItemsTable` emits, which is shared with
+// tables driving endpoints that still take snake_case (e.g. /api/ee/stale/:id). The collection items endpoint
+// takes kebab-case, so translate here rather than changing the shared UI type.
+const toItemsSortingParams = (
+ sorting: SortingOptions<ListCollectionItemsSortColumn>,
+) => ({
+ "sort-column": sorting.sort_column,
+ "sort-direction": sorting.sort_direction,
+});
export type CollectionItemsTableProps = {
collectionId?: CollectionId;
@@ -224,6 +226,26 @@ export const CollectionItemsTable = ({
(isEmbeddingSdk() || isRootTrashCollection(collection)) &&
showDashboardQuestions;
+ // `currentData` is per collection, so a previous collection's metadata never drives this one's toolbar.
+ const { currentData: itemsMetadata } = useGetCollectionItemsMetadataQuery(
+ collectionId === undefined || !showFilterBar
+ ? skipToken
+ : {
+ id: collectionId,
+ models,
+ "show-dashboard-questions": showDashboardQuestionsInList,
+ },
+ );
+ const availableModels = itemsMetadata?.available_models ?? [];
+ const totalItems = itemsMetadata?.total_items ?? 0;
+
+ const showToolbar =
+ Boolean(showFilterBar) && totalItems > FILTERS_VISIBILITY_THRESHOLD;
+ // The toolbar can disappear while a search or type filter is active, e.g. after
+ // archiving items; ignore the leftover selection rather than filtering a bare list.
+ const appliedSearchText = showToolbar ? trimmedSearchText : "";
+ const appliedFilters = showToolbar ? selectedFilters : null;
+
return (
<CollectionItemsTableContent
bookmarks={bookmarks}
@@ -239,11 +261,11 @@ export const CollectionItemsTable = ({
handleMove={handleMove}
page={page}
pageSize={pageSize}
- searchText={searchText}
- selectedFilters={selectedFilters}
+ searchText={showToolbar ? searchText : ""}
+ selectedFilters={appliedFilters}
selected={selected}
selectOnlyTheseItems={selectOnlyTheseItems}
- showFilterBar={showFilterBar}
+ showToolbar={showToolbar}
toggleItem={toggleItem}
itemsSorting={itemsSorting}
itemsQuery={
@@ -251,15 +273,15 @@ export const CollectionItemsTable = ({
? skipToken
: {
id: collectionId,
- ...getQueryFilters(models, selectedFilters),
- ...(showFilterBar ? { include_available_models: true } : {}),
+ models: appliedFilters ?? models,
limit: pageSize,
offset: pageSize * page,
- show_dashboard_questions: showDashboardQuestionsInList,
- ...itemsSorting,
- ...(trimmedSearchText.length > 0 ? { q: trimmedSearchText } : {}),
+ "show-dashboard-questions": showDashboardQuestionsInList,
+ ...toItemsSortingParams(itemsSorting),
+ ...(appliedSearchText.length > 0 ? { q: appliedSearchText } : {}),
}
}
+ availableModels={availableModels}
visibleColumns={visibleColumns}
onClick={onClick}
onNextPage={handleNextPage}
@@ -275,6 +297,8 @@ type CollectionItemsTableContentProps = CollectionItemsTableProps & {
page: number;
searchText: string;
selectedFilters: CollectionItemModel[] | null;
+ showToolbar: boolean;
+ availableModels: string[];
itemsSorting: SortingOptions<ListCollectionItemsSortColumn>;
itemsQuery: ListCollectionItemsRequest | typeof skipToken;
onNextPage: () => void;
@@ -304,7 +328,8 @@ const CollectionItemsTableContent = ({
selectedFilters,
selected,
selectOnlyTheseItems,
- showFilterBar,
+ showToolbar,
+ availableModels,
toggleItem,
itemsSorting,
itemsQuery,
@@ -316,18 +341,18 @@ const CollectionItemsTableContent = ({
onSelectedFiltersChange,
onItemsSortingChange,
}: CollectionItemsTableContentProps) => {
- const { data, isFetching: fetchingItems } =
- useListCollectionItemsQuery(itemsQuery);
+ const { data, isFetching } = useListCollectionItemsQuery(itemsQuery);
const items = data?.data ?? [];
- const availableModels = data?.available_models ?? [];
- const total = data?.total;
+ const totalMatchingItems = data?.total;
const visibleColumnsMap = useMemo(
() => getVisibleColumnsMap(visibleColumns),
[visibleColumns],
);
- const hasPagination: boolean = total ? total > pageSize : false;
+ const hasPagination: boolean = totalMatchingItems
+ ? totalMatchingItems > pageSize
+ : false;
const unselected = getIsSelected
? items.filter((item) => !getIsSelected(item))
@@ -342,20 +367,19 @@ const CollectionItemsTableContent = ({
itemsQuery !== skipToken && Boolean(itemsQuery.q?.trim());
const hasSearchText = searchText.trim().length > 0 || hasSearchQuery;
const hasActiveFilters = hasSearchText || selectedFilters != null;
- const isSearching = fetchingItems && hasSearchQuery;
- const isEmpty = !fetchingItems && items.length === 0 && !hasActiveFilters;
+ const isSearching = isFetching && hasSearchQuery;
+ const isEmpty = !isFetching && items.length === 0 && !hasActiveFilters;
if (isEmpty) {
return <EmptyContentComponent collection={collection} />;
}
- const showNoResults =
- !fetchingItems && hasActiveFilters && items.length === 0;
+ const showNoResults = !isFetching && hasActiveFilters && items.length === 0;
const showTable = !showNoResults;
return (
<>
- {showFilterBar && (
+ {showToolbar && (
<CollectionItemsToolbar
searchText={searchText}
availableModels={availableModels}
@@ -402,7 +426,7 @@ const CollectionItemsTableContent = ({
showTotal
page={page}
pageSize={pageSize}
- total={total}
+ total={totalMatchingItems}
itemsLength={items.length}
onNextPage={onNextPage}
onPreviousPage={onPreviousPage}
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx
index 8c8d0732d8e..40bb8addd0e 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx
@@ -25,8 +25,26 @@ import {
} from "metabase-types/api/mocks";
import { CollectionItemsTable } from "./CollectionItemsTable";
+import { ALL_MODELS } from "./constants";
const collection = createMockCollection({ id: 1, can_write: false });
+
+function createFillerItems(
+ count: number,
+ overrides: Partial<CollectionItem> = {},
+) {
+ const model = overrides.model ?? "card";
+ return Array.from({ length: count }, (_, index) =>
+ createMockCollectionItem({
+ collection_id: collection.id,
+ ...overrides,
+ id: 100 + index,
+ model,
+ name: `Extra ${model} ${index + 1}`,
+ }),
+ );
+}
+
const collectionItems = [
createMockCollectionItem({
id: 1,
@@ -46,6 +64,8 @@ const collectionItems = [
model: "dataset",
name: "Orders model",
}),
+ // Enough items to keep the search input and type filters visible.
+ ...createFillerItems(9),
];
type SetupOpts = {
@@ -101,6 +121,12 @@ function getItemsCalls(collectionId: CollectionId = collection.id) {
);
}
+function getMetadataCalls(collectionId: CollectionId = collection.id) {
+ return fetchMock.callHistory.calls(
+ `path:/api/collection/${collectionId}/items/metadata`,
+ );
+}
+
function getSearchCalls(collectionId: CollectionId = collection.id) {
return getItemsCalls(collectionId).filter((call) =>
new URL(call.url).searchParams.has("q"),
@@ -182,11 +208,124 @@ describe("CollectionItemsTable", () => {
expect(
screen.queryByTestId("collection-items-toolbar"),
).not.toBeInTheDocument();
+ expect(getMetadataCalls()).toHaveLength(0);
+ });
+
+ it("hides the search input and type filter when the list has 10 or fewer items", async () => {
+ const pinnedDashboards = [1, 2].map((position) =>
+ createMockCollectionItem({
+ id: 200 + position,
+ collection_id: collection.id,
+ model: "dashboard",
+ name: `Pinned dashboard ${position}`,
+ collection_position: position,
+ }),
+ );
+ setup({
+ collectionItems: [...createFillerItems(8), ...pinnedDashboards],
+ });
+
+ expect(await screen.findByText("Extra card 1")).toBeInTheDocument();
+ expect(screen.getByText("Pinned dashboard 1")).toBeInTheDocument();
expect(
- getItemsCalls().some((call) =>
- new URL(call.url).searchParams.has("include_available_models"),
- ),
- ).toBe(false);
+ screen.queryByTestId("collection-items-toolbar"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("ignores item types the list never shows when deciding to show the filters", async () => {
+ setup({
+ collectionItems: [
+ createMockCollectionItem({
+ id: 300,
+ collection_id: collection.id,
+ model: "collection",
+ name: "Visible child",
+ }),
+ // Transforms are a model the backend can list, but the collection page never asks for.
+ ...createFillerItems(10, { model: "transform" }),
+ ],
+ });
+
+ expect(await screen.findByText("Visible child")).toBeInTheDocument();
+ const metadataParams = new URL(getMetadataCalls()[0].url).searchParams;
+ expect(metadataParams.getAll("models")).toEqual(ALL_MODELS);
+ expect(
+ screen.queryByTestId("collection-items-toolbar"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the search input and type filter once the list exceeds 10 items, counting pinned ones", async () => {
+ const pinnedDashboards = [1, 2].map((position) =>
+ createMockCollectionItem({
+ id: 200 + position,
+ collection_id: collection.id,
+ model: "dashboard",
+ name: `Pinned dashboard ${position}`,
+ collection_position: position,
+ }),
+ );
+ setup({
+ collectionItems: [...createFillerItems(9), ...pinnedDashboards],
+ });
+
+ expect(
+ await screen.findByTestId("collection-items-toolbar"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText("Search by name or editor..."),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("collection-type-filter-button"),
+ ).toBeInTheDocument();
+ });
+
+ it("drops an active search when the collection shrinks below the filters threshold", async () => {
+ const user = setupUserWithFakeTimers();
+ const { store } = setup();
+
+ await user.type(
+ await screen.findByPlaceholderText("Search by name or editor..."),
+ "revenue",
+ );
+ advanceSearchDebounce();
+ await waitFor(() => {
+ expect(getSearchCalls()).toHaveLength(1);
+ });
+ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();
+
+ fetchMock.modifyRoute(`collection-${collection.id}-items`, {
+ response: {
+ data: collectionItems.slice(0, 3),
+ total: 3,
+ models: [],
+ limit: 25,
+ offset: 0,
+ },
+ });
+ fetchMock.modifyRoute(`collection-${collection.id}-items-metadata`, {
+ response: {
+ available_models: ["dashboard", "card", "dataset"],
+ total_items: 3,
+ },
+ });
+ act(() => {
+ store.dispatch(
+ Api.util.invalidateTags([
+ { type: "collection", id: `${collection.id}-items` },
+ ]),
+ );
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("collection-items-toolbar"),
+ ).not.toBeInTheDocument();
+ });
+ await waitFor(() => {
+ const itemsCalls = getItemsCalls();
+ const lastItemsCall = new URL(itemsCalls[itemsCalls.length - 1].url);
+ expect(lastItemsCall.searchParams.has("q")).toBe(false);
+ });
});
it("keeps the table mounted without showing a loader during a refetch with no search", async () => {
@@ -543,23 +682,105 @@ describe("CollectionItemsTable", () => {
setup();
await waitFor(() => {
- expect(
- getItemsSearchParams().some(
- (searchParams) =>
- searchParams.get("include_available_models") === "true",
- ),
- ).toBe(true);
+ expect(getMetadataCalls()).toHaveLength(1);
+ });
+ await userEvent.click(
+ await screen.findByTestId("collection-type-filter-button"),
+ );
+ const popover = screen.getByTestId("collection-type-filter-popover");
+
+ expect(within(popover).getAllByRole("checkbox")).toHaveLength(8);
+ for (const label of ["Dashboard", "Model", "Question"]) {
+ expect(within(popover).getByLabelText(label)).not.toBeChecked();
+ expect(within(popover).getByLabelText(label)).toBeEnabled();
+ }
+ expect(within(popover).getByLabelText("Metric")).toBeDisabled();
+ expect(within(popover).getByLabelText("Document")).toBeDisabled();
+ });
+
+ it("offers a type filter for a type that only exists as a pinned item", async () => {
+ setup({
+ collectionItems: [
+ collectionItems[1],
+ createMockCollectionItem({
+ id: 5,
+ collection_id: collection.id,
+ model: "dashboard",
+ name: "Pinned revenue overview",
+ collection_position: 1,
+ }),
+ ...createFillerItems(10),
+ ],
});
+
await userEvent.click(
await screen.findByTestId("collection-type-filter-button"),
);
const popover = screen.getByTestId("collection-type-filter-popover");
- expect(within(popover).getAllByRole("checkbox")).toHaveLength(3);
- expect(within(popover).getByLabelText("Dashboard")).toBeChecked();
+ expect(within(popover).getByLabelText("Dashboard")).toBeEnabled();
+ expect(within(popover).getByLabelText("Dashboard")).not.toBeChecked();
+ expect(within(popover).getByLabelText("Question")).toBeEnabled();
+ expect(within(popover).getByLabelText("Model")).toBeDisabled();
+ });
+
+ it("refreshes the available type options when collection content changes", async () => {
+ const { store } = setup();
+
+ await waitFor(() => {
+ expect(getMetadataCalls()).toHaveLength(1);
+ });
+
+ act(() => {
+ store.dispatch(
+ Api.util.invalidateTags([{ type: "dashboard", id: "LIST" }]),
+ );
+ });
+
+ await waitFor(() => {
+ expect(getMetadataCalls()).toHaveLength(2);
+ });
+ });
+
+ it("fetches the available type options once, out of scope of search, type filters and pagination", async () => {
+ const user = setupUserWithFakeTimers();
+ setup({ pageSize: 1 });
+
+ await waitFor(() => {
+ expect(getMetadataCalls()).toHaveLength(1);
+ });
+ const metadataParams = new URL(getMetadataCalls()[0].url).searchParams;
+ // The list's full model set, never the user's type selection.
+ expect(metadataParams.getAll("models")).toEqual(ALL_MODELS);
+ expect(metadataParams.has("q")).toBe(false);
+
+ await user.click(
+ await screen.findByTestId("collection-type-filter-button"),
+ );
+ await user.click(screen.getByLabelText("Model"));
+ await user.click(screen.getByLabelText("Question"));
+ await waitFor(() => {
+ expect(findItemsSearchParamsByModels(["dataset", "card"])).toBeDefined();
+ });
+ screen.getByLabelText("Question").focus();
+ await user.keyboard("{Escape}");
+
+ await user.type(
+ screen.getByPlaceholderText("Search by name or editor..."),
+ "orders",
+ );
+ advanceSearchDebounce();
+ await waitFor(() => {
+ expect(getSearchCalls()).toHaveLength(1);
+ });
+
+ expect(getMetadataCalls()).toHaveLength(1);
+ await user.click(screen.getByTestId("collection-type-filter-button"));
+ const popover = screen.getByTestId("collection-type-filter-popover");
+ expect(within(popover).getAllByRole("checkbox")).toHaveLength(8);
+ expect(within(popover).getByLabelText("Dashboard")).not.toBeChecked();
expect(within(popover).getByLabelText("Model")).toBeChecked();
expect(within(popover).getByLabelText("Question")).toBeChecked();
- expect(within(popover).queryByLabelText("Metric")).not.toBeInTheDocument();
});
it("filters by type and resets pagination", async () => {
@@ -571,12 +792,10 @@ describe("CollectionItemsTable", () => {
await userEvent.click(
await screen.findByTestId("collection-type-filter-button"),
);
- await userEvent.click(screen.getByLabelText("Dashboard"));
+ await userEvent.click(screen.getByLabelText("Question"));
await waitFor(() => {
- expect(
- findItemsSearchParamsByModels(["dataset", "card"])?.get("offset"),
- ).toBe("0");
+ expect(findItemsSearchParamsByModels(["card"])?.get("offset")).toBe("0");
});
expect(screen.queryByText("Revenue overview")).not.toBeInTheDocument();
expect(screen.getByText("Customer 360")).toBeInTheDocument();
@@ -613,7 +832,7 @@ describe("CollectionItemsTable", () => {
});
});
- it("uses no_models and shows no results when every type is unchecked", async () => {
+ it("restores the unfiltered list when every type is unchecked", async () => {
setup();
await userEvent.click(
@@ -621,24 +840,23 @@ describe("CollectionItemsTable", () => {
);
const popover = screen.getByTestId("collection-type-filter-popover");
await userEvent.click(within(popover).getByLabelText("Dashboard"));
- await userEvent.click(within(popover).getByLabelText("Model"));
- await userEvent.click(within(popover).getByLabelText("Question"));
await waitFor(() => {
- expect(findItemsSearchParamsByModels(["no_models"])).toBeDefined();
+ expect(findItemsSearchParamsByModels(["dashboard"])).toBeDefined();
});
- expect(await screen.findByText("Didn't find anything")).toBeInTheDocument();
- expect(
- screen.getByTestId("collection-filter-empty-state"),
- ).toBeInTheDocument();
+ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();
+ expect(screen.queryByText("Customer 360")).not.toBeInTheDocument();
expect(
- screen.getByText("No items of the selected types."),
+ screen.getByRole("button", { name: "Filter, filters applied" }),
).toBeInTheDocument();
- expect(screen.queryByTestId("collection-table")).not.toBeInTheDocument();
- expect(popover).toBeInTheDocument();
- expect(
- within(popover).queryByRole("button", { name: "Apply" }),
- ).not.toBeInTheDocument();
+
+ await userEvent.click(within(popover).getByLabelText("Dashboard"));
+
+ expect(await screen.findByText("Customer 360")).toBeInTheDocument();
+ expect(screen.getByText("Revenue overview")).toBeInTheDocument();
+ expect(screen.getByText("Orders model")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Filter" })).toBeInTheDocument();
+ expect(findItemsSearchParamsByModels(["no_models"])).toBeUndefined();
});
it("keeps all type options while search has no results", async () => {
@@ -649,10 +867,7 @@ describe("CollectionItemsTable", () => {
await screen.findByTestId("collection-type-filter-button"),
);
let popover = screen.getByTestId("collection-type-filter-popover");
- expect(within(popover).getAllByRole("checkbox")).toHaveLength(3);
- expect(within(popover).getByLabelText("Dashboard")).toBeChecked();
- expect(within(popover).getByLabelText("Model")).toBeChecked();
- expect(within(popover).getByLabelText("Question")).toBeChecked();
+ expect(within(popover).getAllByRole("checkbox")).toHaveLength(8);
within(popover).getByLabelText("Dashboard").focus();
await user.keyboard("{Escape}");
await waitFor(() => {
@@ -672,10 +887,10 @@ describe("CollectionItemsTable", () => {
await user.click(screen.getByTestId("collection-type-filter-button"));
popover = screen.getByTestId("collection-type-filter-popover");
- expect(within(popover).getAllByRole("checkbox")).toHaveLength(3);
- expect(within(popover).getByLabelText("Dashboard")).toBeChecked();
- expect(within(popover).getByLabelText("Model")).toBeChecked();
- expect(within(popover).getByLabelText("Question")).toBeChecked();
+ expect(within(popover).getAllByRole("checkbox")).toHaveLength(8);
+ expect(within(popover).getByLabelText("Dashboard")).toBeEnabled();
+ expect(within(popover).getByLabelText("Model")).toBeEnabled();
+ expect(within(popover).getByLabelText("Question")).toBeEnabled();
});
it("resets search and type filters before requesting a new collection", async () => {
@@ -687,6 +902,10 @@ describe("CollectionItemsTable", () => {
model: "dashboard",
name: "Inventory overview",
}),
+ ...createFillerItems(10, {
+ collection_id: nextCollection.id,
+ model: "dashboard",
+ }),
];
setupCollectionItemsEndpoint({ collection, collectionItems });
const user = setupUserWithFakeTimers();
@@ -737,13 +956,58 @@ describe("CollectionItemsTable", () => {
expect(screen.getByRole("button", { name: "Filter" })).toBeInTheDocument();
await user.click(screen.getByTestId("collection-type-filter-button"));
const popover = screen.getByTestId("collection-type-filter-popover");
- expect(within(popover).getAllByRole("checkbox")).toHaveLength(1);
- expect(within(popover).getByLabelText("Dashboard")).toBeChecked();
+ expect(within(popover).getByLabelText("Dashboard")).not.toBeChecked();
+ expect(within(popover).getByLabelText("Dashboard")).toBeEnabled();
+ expect(within(popover).getByLabelText("Question")).toBeDisabled();
advanceSearchDebounce();
expect(getSearchCalls(nextCollection.id)).toHaveLength(0);
});
+ it("does not show the previous collection's toolbar while a smaller collection loads", async () => {
+ const nextCollection = createMockCollection({ id: 2, can_write: false });
+ setupCollectionItemsEndpoint({ collection, collectionItems });
+ setupCollectionItemsEndpoint({
+ collection: nextCollection,
+ collectionItems: createFillerItems(3, {
+ collection_id: nextCollection.id,
+ }),
+ });
+ let resolveMetadata: (() => void) | undefined;
+ const metadataGate = new Promise<void>((resolve) => {
+ resolveMetadata = resolve;
+ });
+ fetchMock.modifyRoute(`collection-${nextCollection.id}-items-metadata`, {
+ response: async () => {
+ await metadataGate;
+ return { available_models: ["card"], total_items: 3 };
+ },
+ });
+ renderWithProviders(
+ <CollectionNavigationTest nextCollection={nextCollection} />,
+ { withRouter: true, withDND: true },
+ );
+ expect(
+ await screen.findByTestId("collection-items-toolbar"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Open next collection" }),
+ );
+
+ expect(await screen.findByText("Extra card 1")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("collection-items-toolbar"),
+ ).not.toBeInTheDocument();
+ await act(async () => {
+ resolveMetadata?.();
+ await fetchMock.callHistory.flush();
+ });
+ expect(
+ screen.queryByTestId("collection-items-toolbar"),
+ ).not.toBeInTheDocument();
+ });
+
it("shows the existing empty state without a toolbar for a truly empty collection", async () => {
setup({ collectionItems: [] });
@@ -775,6 +1039,7 @@ describe("CollectionItemsTable", () => {
collectionItems[0],
regularCollection,
officialCollection,
+ ...createFillerItems(9, { model: "collection" }),
],
});
@@ -783,7 +1048,7 @@ describe("CollectionItemsTable", () => {
expect(screen.getByText("Official collection")).toBeInTheDocument();
await userEvent.click(screen.getByTestId("collection-type-filter-button"));
- await userEvent.click(screen.getByLabelText("Dashboard"));
+ await userEvent.click(screen.getByLabelText("Collection"));
await waitFor(() => {
const searchParams = findItemsSearchParamsByModels(["collection"]);
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsx
index 59a6a30d11e..fe24bc2023b 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsx
@@ -29,17 +29,19 @@ export function CollectionTypeFilter({
}: CollectionTypeFilterProps) {
const [opened, { close, toggle }] = useDisclosure(false);
const headingId = useId();
- const options = TYPE_FILTER_MODELS.filter((model) =>
- availableModels.includes(model),
- ).map((model) => ({
+ // Nothing checked means no filter is applied and every type is listed.
+ const checkedFilters = selectedFilters ?? [];
+ // Types without items stay visible but disabled; a checked type stays
+ // enabled even after its last item is gone, so it can be unchecked.
+ const options = TYPE_FILTER_MODELS.map((model) => ({
value: model,
label: getTranslatedEntityName(model) ?? model,
+ disabled:
+ !availableModels.includes(model) && !checkedFilters.includes(model),
}));
- const optionValues = options.map(({ value }) => value);
- const checkedFilters = selectedFilters ?? optionValues;
- const isFiltering = selectedFilters != null;
+ const isFiltering = checkedFilters.length > 0;
- if (options.length === 0) {
+ if (options.every((option) => option.disabled)) {
return null;
}
@@ -47,10 +49,7 @@ export function CollectionTypeFilter({
const nextFilters = checkedFilters.includes(filter)
? checkedFilters.filter((checkedFilter) => checkedFilter !== filter)
: [...checkedFilters, filter];
- const coversAllOptions = options.every((option) =>
- nextFilters.includes(option.value),
- );
- onSelectedFiltersChange(coversAllOptions ? null : nextFilters);
+ onSelectedFiltersChange(nextFilters.length > 0 ? nextFilters : null);
};
return (
@@ -88,11 +87,12 @@ export function CollectionTypeFilter({
{t`Filter by type`}
</Text>
<Stack gap="0.75rem">
- {options.map(({ value, label }) => (
+ {options.map(({ value, label, disabled }) => (
<Checkbox
key={value}
value={value}
label={label}
+ disabled={disabled}
checked={checkedFilters.includes(value)}
onChange={() => handleToggle(value)}
/>
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsx
index f695e27e046..3edadeba5de 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsx
@@ -35,7 +35,7 @@ describe("CollectionTypeFilter", () => {
).not.toBeInTheDocument();
});
- it("shows only available options in display order, checked by default", async () => {
+ it("shows every type in display order, disabling those without items", async () => {
setup({
availableModels: [
"metric",
@@ -61,27 +61,50 @@ describe("CollectionTypeFilter", () => {
"Model",
"Question",
"Metric",
+ "Document",
"Research",
+ "Table",
];
- expect(checkboxes).toHaveLength(6);
+ expect(checkboxes).toHaveLength(8);
expect(checkboxes).toEqual(
labels.map((label) => screen.getByLabelText(label)),
);
for (const label of labels) {
- expect(screen.getByLabelText(label)).toBeChecked();
+ expect(screen.getByLabelText(label)).not.toBeChecked();
}
+ for (const label of ["Collection", "Dashboard", "Metric", "Research"]) {
+ expect(screen.getByLabelText(label)).toBeEnabled();
+ }
+ expect(screen.getByLabelText("Document")).toBeDisabled();
+ expect(screen.getByLabelText("Table")).toBeDisabled();
});
- it("returns the remaining models when an option is unchecked", async () => {
+ it("keeps a checked type enabled after its last item is gone", async () => {
+ const { onSelectedFiltersChange } = setup({
+ availableModels: ["card"],
+ selectedFilters: ["dashboard"],
+ });
+
+ await userEvent.click(screen.getByTestId("collection-type-filter-button"));
+ const dashboard = screen.getByLabelText("Dashboard");
+ expect(dashboard).toBeChecked();
+ expect(dashboard).toBeEnabled();
+
+ await userEvent.click(dashboard);
+
+ expect(onSelectedFiltersChange).toHaveBeenCalledWith(null);
+ });
+
+ it("applies a single type with one click", async () => {
const { onSelectedFiltersChange } = setup();
await userEvent.click(screen.getByTestId("collection-type-filter-button"));
await userEvent.click(screen.getByLabelText("Dashboard"));
- expect(onSelectedFiltersChange).toHaveBeenCalledWith(["card"]);
+ expect(onSelectedFiltersChange).toHaveBeenCalledWith(["dashboard"]);
});
- it("clears the filter when all available options are checked", async () => {
+ it("adds to the existing selection when another option is checked", async () => {
const { onSelectedFiltersChange } = setup({
selectedFilters: ["dashboard"],
});
@@ -89,6 +112,28 @@ describe("CollectionTypeFilter", () => {
await userEvent.click(screen.getByTestId("collection-type-filter-button"));
await userEvent.click(screen.getByLabelText("Question"));
+ expect(onSelectedFiltersChange).toHaveBeenCalledWith(["dashboard", "card"]);
+ });
+
+ it("removes a type from the selection when it is unchecked", async () => {
+ const { onSelectedFiltersChange } = setup({
+ selectedFilters: ["dashboard", "card"],
+ });
+
+ await userEvent.click(screen.getByTestId("collection-type-filter-button"));
+ await userEvent.click(screen.getByLabelText("Dashboard"));
+
+ expect(onSelectedFiltersChange).toHaveBeenCalledWith(["card"]);
+ });
+
+ it("clears the filter when the last checked option is unchecked", async () => {
+ const { onSelectedFiltersChange } = setup({
+ selectedFilters: ["dashboard"],
+ });
+
+ await userEvent.click(screen.getByTestId("collection-type-filter-button"));
+ await userEvent.click(screen.getByLabelText("Dashboard"));
+
expect(onSelectedFiltersChange).toHaveBeenCalledWith(null);
});
diff --git a/frontend/src/metabase/collections/components/CollectionContent/constants.ts b/frontend/src/metabase/collections/components/CollectionContent/constants.ts
index fe7ddf5f784..c6700eee0b2 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/constants.ts
+++ b/frontend/src/metabase/collections/components/CollectionContent/constants.ts
@@ -8,6 +8,9 @@ export { DEFAULT_VISIBLE_COLUMNS_LIST } from "metabase/common/collections/column
export const COLLECTION_PAGE_SIZE = 25;
+// Search and type filters appear once a collection has more items than this.
+export const FILTERS_VISIBILITY_THRESHOLD = 10;
+
export const ALL_MODELS: CollectionItemModel[] = [
"dashboard",
"dataset",
diff --git a/frontend/src/metabase/collections/components/PinnedItemsGrid/PinnedItemsGrid.tsx b/frontend/src/metabase/collections/components/PinnedItemsGrid/PinnedItemsGrid.tsx
index bcab828ec09..30909173f58 100644
--- a/frontend/src/metabase/collections/components/PinnedItemsGrid/PinnedItemsGrid.tsx
+++ b/frontend/src/metabase/collections/components/PinnedItemsGrid/PinnedItemsGrid.tsx
@@ -58,9 +58,9 @@ export function PinnedItemsGrid({
showPinnedItems
? {
id: collectionId,
- pinned_state: "is_pinned",
- sort_column: "name",
- sort_direction: "asc",
+ "pinned-state": "is_pinned",
+ "sort-column": "name",
+ "sort-direction": "asc",
}
: skipToken,
);
diff --git a/frontend/src/metabase/common/components/Pickers/utils.ts b/frontend/src/metabase/common/components/Pickers/utils.ts
index 23e57784662..d3db2c80166 100644
--- a/frontend/src/metabase/common/components/Pickers/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/utils.ts
@@ -63,6 +63,6 @@ export const getCollectionItemsOptions = ({
models: getValidCollectionItemModels(models),
// After a downgrade from EE to OSS, isEnabled is false, and we want to show
// the Library (if it exists) within Our Analytics.
- include_library: !PLUGIN_LIBRARY.isEnabled,
+ "include-library": !PLUGIN_LIBRARY.isEnabled,
};
};
diff --git a/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts
index 2931ae226b3..413474759aa 100644
--- a/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts
+++ b/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts
@@ -123,7 +123,7 @@ describe("getCollectionItemsOptions", () => {
it("should include library collections when the library plugin is disabled (metabase#73143)", () => {
expect(
- getCollectionItemsOptions({ models: ["card"] }).include_library,
+ getCollectionItemsOptions({ models: ["card"] })["include-library"],
).toBe(true);
});
@@ -134,7 +134,7 @@ describe("getCollectionItemsOptions", () => {
setupEnterpriseOnlyPlugin("library");
expect(
- getCollectionItemsOptions({ models: ["card"] }).include_library,
+ getCollectionItemsOptions({ models: ["card"] })["include-library"],
).toBe(false);
});
});
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts
index f402760ce1d..f490b647cfa 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts
@@ -48,8 +48,8 @@ export const useLastXrayDashboard = () => {
? {
id: autoGenCollection.id,
models: ["dashboard"],
- sort_column: "last_edited_at",
- sort_direction: "desc",
+ "sort-column": "last_edited_at",
+ "sort-direction": "desc",
}
: skipToken,
);
diff --git a/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityList.tsx b/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityList.tsx
index 05f252bac34..85c121f3613 100644
--- a/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityList.tsx
+++ b/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityList.tsx
@@ -42,8 +42,8 @@ export const SavedEntityList = ({
? {
id: collection.id,
models: [CARD_INFO[type].model],
- sort_column: "name",
- sort_direction: "asc",
+ "sort-column": "name",
+ "sort-direction": "asc",
}
: skipToken,
);
diff --git a/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityPicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityPicker.unit.spec.tsx
index b91690050b5..27c3379a9f5 100644
--- a/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityPicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/common/components/DataSelector/saved-entity-picker/SavedEntityPicker.unit.spec.tsx
@@ -37,8 +37,8 @@ function mockCollectionItemsEndpoint() {
fetchMock.get({
url: "path:/api/collection/root/items",
query: {
- sort_column: "name",
- sort_direction: "asc",
+ "sort-column": "name",
+ "sort-direction": "asc",
},
response: {
total: 3,
diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.ts
index 3dcf73ee2d8..4814ca83571 100644
--- a/frontend/test/__support__/server-mocks/collection.ts
+++ b/frontend/test/__support__/server-mocks/collection.ts
@@ -176,7 +176,7 @@ function handleCollectionItemsResponse({
}) {
const url = new URL(call.url);
const models = modelsParam ?? url.searchParams.getAll("models");
- const pinnedState = url.searchParams.get("pinned_state");
+ const pinnedState = url.searchParams.get("pinned-state");
// As in the API, requesting no models at all returns every item.
const matchedItems: CollectionItem[] = models.includes("no_models")
@@ -193,23 +193,32 @@ function handleCollectionItemsResponse({
const limit = Number(url.searchParams.get("limit")) || searchedItems.length;
const offset = Number(url.searchParams.get("offset")) || 0;
- const response = {
+ return {
data: searchedItems.slice(offset, offset + limit),
total: searchedItems.length,
models,
limit,
offset,
};
+}
- if (url.searchParams.get("include_available_models") !== "true") {
- return response;
- }
+// Mirrors GET /api/collection/:id/items/metadata: available models and the item
+// count for the requested models, independent of any search filter.
+function collectionItemsMetadata(
+ call: { url: string },
+ collectionItems: CollectionItem[],
+) {
+ const models = new URL(call.url).searchParams.getAll("models");
+ const requestedItems =
+ models.length === 0
+ ? collectionItems
+ : collectionItems.filter((item) => models.includes(item.model));
return {
- ...response,
available_models: Array.from(
- new Set(collectionItems.map((item) => item.model)),
+ new Set(requestedItems.map((item) => item.model)),
),
+ total_items: requestedItems.length,
};
}
@@ -233,6 +242,11 @@ export function setupCollectionItemsEndpoint({
},
{ name: `collection-${collection.id}-items` },
);
+ fetchMock.get(
+ `path:/api/collection/${collection.id}/items/metadata`,
+ (call) => collectionItemsMetadata(call, collectionItems),
+ { name: `collection-${collection.id}-items-metadata` },
+ );
}
export function setupTenantCollectionItemsEndpoint({
diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.clj
index 5de8599972c..4d797b261c2 100644
--- a/src/metabase/collections_rest/api.clj
+++ b/src/metabase/collections_rest/api.clj
@@ -30,7 +30,7 @@
[metabase.transforms.feature-gating :as transforms.gating]
[metabase.upload.core :as upload]
[metabase.util :as u]
- [metabase.util.i18n :refer [tru]]
+ [metabase.util.i18n :as i18n :refer [tru]]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
@@ -43,6 +43,40 @@
(declare root-collection)
+(mr/def ::CollectionId
+ "A Collection's ID: an integer for a real row, or the string \"root\" for the virtual Root Collection."
+ [:or ms/PositiveInt :string])
+
+(mr/def ::Collection
+ "A Collection as the REST API returns it. Deliberately open: which hydrated keys come back varies by endpoint and
+ by what the Collection is. `POST /` returns the freshly inserted row with no permission flags; `/root` describes a
+ virtual Collection with a string id and none of the database-backed columns; `/tree` nests `:children`. Only `:id`
+ and `:name` are present in every case, so only those are required here."
+ [:map
+ [:id ::CollectionId]
+ ;; The virtual Trash collection carries a deferred-i18n name, and responses are validated before they are
+ ;; encoded to JSON, so the raw value reaching this schema is not always a plain string.
+ [:name [:or :string i18n/LocalizedString]]])
+
+(mr/def ::CollectionTreeNode
+ "A Collection in the `/tree` response. `:children` are nested tree nodes, except under `?shallow=true`, where the
+ endpoint returns only the requested level and `:children` degrades to a boolean saying whether any exist."
+ [:map
+ [:id ::CollectionId]
+ [:name [:or :string i18n/LocalizedString]]
+ [:children {:optional true} [:or :boolean [:sequential [:ref ::CollectionTreeNode]]]]])
+
+(mr/def ::ItemsResponse
+ "A page of a Collection's items. `:available_models` is present only when the request asked for it, and
+ `:limit`/`:offset` are dropped entirely in the `snippets` namespace, which is not paginated."
+ [:map
+ [:total ms/IntGreaterThanOrEqualToZero]
+ [:data [:sequential :map]]
+ [:models [:maybe [:sequential :any]]]
+ [:limit {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:offset {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:available_models {:optional true} [:sequential :any]]])
+
(defn- remove-other-users-personal-subcollections
[user-id collections]
(let [personal-ids (set (collections-rest.db/other-users-personal-collection-ids user-id))
@@ -73,11 +107,7 @@
exclude-other-user-collections
(remove-other-users-personal-subcollections api/*current-user-id*)))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/"
+(api.macros/defendpoint :get "/" :- [:sequential ::Collection]
"Fetch a list of all Collections that the current user has read permissions for (`:can_write` is returned as an
additional property of each Collection so you can tell which of these you have write permissions for.)
@@ -152,11 +182,7 @@
(collection/collections->tree nil)
(map (fn [coll] (update coll :children #(boolean (seq %)))))))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/tree"
+(api.macros/defendpoint :get "/tree" :- [:sequential ::CollectionTreeNode]
"Similar to `GET /`, but returns Collections in a tree structure, e.g.
```
@@ -528,28 +554,31 @@
(defn- collection-children*
[collection models options]
- (let [models (sort (map keyword models))
- limit (request/limit)
- offset (request/offset)
+ (let [models (sort (map keyword models))
+ limit (request/limit)
+ offset (request/offset)
+ ;; A limit of 0 asks for the count alone rather than for a page.
+ count-only? (= limit 0)
;; We didn't implement collection pagination for snippets namespace for root/items
- ;; Rip out the limit for now and put it back in when we want it
- page (when-not (or (nil? limit)
- (nil? offset)
- (= (:collection-namespace options) "snippets"))
- ;; If limit is 0, we still execute the query with a limit of 1 so that we fetch a :total_count
- {:limit (if (zero? limit) 1 limit)
- :offset offset})
- rows (tracing/with-span :db-app "db-app.collection-items-query" {:collection/id (:id collection)}
- (collections-rest.db/collection-children-rows collection models options page))
- res {:total (total-count rows collection models options offset)
- :data (if (= limit 0)
- []
- (tracing/with-span :db-app "db-app.collection-items-post-process" {:collection/id (:id collection)}
- (post-process-rows options collection rows)))
- :models models}
- limit-res (assoc res
- :limit (request/limit)
- :offset (request/offset))]
+ ;; Rip out the limit for now and put it back in when we want it.
+ page (when-not (or (nil? limit)
+ (nil? offset)
+ (and (= (:collection-namespace options) "snippets")
+ (not count-only?)))
+ ;; If limit is 0, we still execute the query with a limit of 1 so that we fetch a :total_count
+ {:limit (if count-only? 1 limit)
+ :offset offset})
+ rows (tracing/with-span :db-app "db-app.collection-items-query" {:collection/id (:id collection)}
+ (collections-rest.db/collection-children-rows collection models options page))
+ res {:total (total-count rows collection models options offset)
+ :data (if count-only?
+ []
+ (tracing/with-span :db-app "db-app.collection-items-post-process" {:collection/id (:id collection)}
+ (post-process-rows options collection rows)))
+ :models models}
+ limit-res (assoc res
+ :limit (request/limit)
+ :offset (request/offset))]
(if (= (:collection-namespace options) "snippets")
res
limit-res)))
@@ -580,6 +609,13 @@
:offset (request/offset)
:models valid-models})))
+(defn- filterable-models
+ "The models that can appear as a filterable item of `collection`. Snippets are never included: they are not a
+ filterable type. When present, `restrict-models` limits the set."
+ [collection restrict-models]
+ (cond->> (remove #{:snippet} (valid-collection-models (:namespace collection)))
+ (seq restrict-models) (filter restrict-models)))
+
(mu/defn- collection-filter-metadata :- [:map
[:available_models [:sequential :string]]]
"Return the models that have at least one visible item in `collection`. Respect the requested scope and visibility,
@@ -588,8 +624,7 @@
[collection :- collection/CollectionWithLocationAndIDOrRoot
restrict-models :- [:maybe [:set :keyword]]
options :- children-query/CollectionChildrenOptions]
- (let [candidates (cond->> (remove #{:snippet} (valid-collection-models (:namespace collection)))
- (seq restrict-models) (filter restrict-models))
+ (let [candidates (filterable-models collection restrict-models)
options (-> options
(dissoc :models :search-text)
(assoc :collection-namespace (:namespace collection)))]
@@ -606,6 +641,30 @@
sort
vec)}))))
+(mr/def ::ItemsMetadata
+ [:map
+ [:available_models [:sequential :string]]
+ ;; Named apart from the `total` of a paged, filtered items response: this is the size of the whole list.
+ [:total_items ms/IntGreaterThanOrEqualToZero]])
+
+(mu/defn- collection-items-metadata :- ::ItemsMetadata
+ "Metadata about the items list of `collection`, independent of the search filter that the items endpoints accept:
+ the models with at least one visible item and the number of items in the whole list. `restrict-models`, when
+ present, limits both to those models, and `options` carries the rest of the scope (archived, pinned state, ...),
+ so the metadata describes the list a client actually shows. Both halves count the same models, so a type that is
+ never reported -- a snippet -- is never counted either."
+ [collection :- collection/CollectionWithLocationAndIDOrRoot
+ restrict-models :- [:maybe [:set :keyword]]
+ options :- children-query/CollectionChildrenOptions]
+ (let [options (dissoc options :models :search-text)
+ models (set (filterable-models collection restrict-models))]
+ (assoc (collection-filter-metadata collection restrict-models options)
+ ;; An empty model set means "nothing to count"; `collection-children` would read it as "no restriction".
+ :total_items (if (empty? models)
+ 0
+ (request/with-limit-and-offset 0 0
+ (:total (collection-children collection (assoc options :models models))))))))
+
(mu/defn- collection-detail
"Add a standard set of details to `collection`, including things like `effective_location`.
Works for either a normal Collection or the Root Collection."
@@ -614,11 +673,7 @@
prep-collection-for-export
(t2/hydrate :parent_id :effective_location [:effective_ancestors :can_write] :can_write :is_personal :can_restore :can_delete)))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/trash"
+(api.macros/defendpoint :get "/trash" :- ::Collection
"Fetch the trash collection, as in `/api/collection/:trash-id`"
[]
(collection-detail (api/read-check (collection/trash-collection))))
@@ -731,11 +786,7 @@
(defn- root-collection [collection-namespace]
(collection-detail (collection/root-collection-with-ui-details collection-namespace)))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/root"
+(api.macros/defendpoint :get "/root" :- ::Collection
"Return the 'Root' Collection object with standard details added"
[_route-params
{:keys [namespace]} :- [:map
@@ -765,15 +816,7 @@
Otherwise, we'll just show you collections."
#{nil "snippets" "transforms"})
-;; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest
-;; of the REST API
-;;
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-case
- :metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/root/items"
+(api.macros/defendpoint :get "/root/items" :- ::ItemsResponse
"Fetch objects that the current user should see at their root level. As mentioned elsewhere, the 'Root' Collection
doesn't actually exist as a row in the application DB: it's simply a virtual Collection where things with no
`collection_id` exist. It does, however, have its own set of Permissions.
@@ -788,30 +831,31 @@
By default, this will show the 'normal' Collections namespace; to view a different Collections namespace, such as
`snippets`, you can pass the `?namespace=` parameter.
- By default, library collections are excluded from the results; to include them, pass `?include_library=true`.
+ By default, library collections are excluded from the results; to include them, pass `?include-library=true`.
- Pass `?q=` to filter items by name or last editor. Pass `?include_available_models=true` to include the models that
+ Pass `?q=` to filter items by name or last editor. Pass `?include-available-models=true` to include the models that
have at least one visible item in the requested scope.
Note that this endpoint should return results in a similar shape to `/api/dashboard/:id/items`, so if this is
changed, that should too."
[_route-params
- {:keys [models archived namespace pinned_state sort_column sort_direction official_collections_first
- include_library collection_type show_dashboard_questions
- q include_available_models show_exploration_documents]} :- [:map
- [:models {:optional true} [:maybe Models]]
- [:collection_type {:optional true} children-query/CollectionType]
- [:archived {:default false} [:maybe ms/BooleanValue]]
- [:namespace {:optional true} [:maybe ms/NonBlankString]]
- [:include_library {:default false} [:maybe ms/BooleanValue]]
- [:pinned_state {:optional true} [:maybe (into [:enum] children-query/valid-pinned-state-values)]]
- [:sort_column {:optional true} [:maybe (into [:enum] children-query/valid-sort-columns)]]
- [:sort_direction {:optional true} [:maybe (into [:enum] children-query/valid-sort-directions)]]
- [:official_collections_first {:optional true} [:maybe ms/MaybeBooleanValue]]
- [:show_dashboard_questions {:optional true} [:maybe ms/MaybeBooleanValue]]
- [:q {:optional true} [:maybe :string]]
- [:include_available_models {:default false} [:maybe ms/BooleanValue]]
- [:show_exploration_documents {:optional true} [:maybe ms/MaybeBooleanValue]]]]
+ {:keys [models archived namespace pinned-state sort-column sort-direction official-collections-first
+ include-library collection-type
+ show-dashboard-questions show-exploration-documents
+ q include-available-models]} :- [:map
+ [:models {:optional true} [:maybe Models]]
+ [:collection-type {:optional true} children-query/CollectionType]
+ [:archived {:default false} [:maybe ms/BooleanValue]]
+ [:namespace {:optional true} [:maybe ms/NonBlankString]]
+ [:include-library {:default false} [:maybe ms/BooleanValue]]
+ [:pinned-state {:optional true} [:maybe (into [:enum] children-query/valid-pinned-state-values)]]
+ [:sort-column {:optional true} [:maybe (into [:enum] children-query/valid-sort-columns)]]
+ [:sort-direction {:optional true} [:maybe (into [:enum] children-query/valid-sort-directions)]]
+ [:official-collections-first {:optional true} [:maybe ms/MaybeBooleanValue]]
+ [:show-dashboard-questions {:optional true} [:maybe ms/MaybeBooleanValue]]
+ [:show-exploration-documents {:optional true} [:maybe ms/MaybeBooleanValue]]
+ [:q {:optional true} [:maybe :string]]
+ [:include-available-models {:default false} [:maybe ms/BooleanValue]]]]
;; Return collection contents, including Collections that have an effective location of being in the Root
;; Collection for the Current User.
(let [root-collection (assoc collection/root-collection :namespace namespace)
@@ -821,24 +865,53 @@
(not (mi/can-read? root-collection)))
#{:collection})
options {:archived? (boolean archived)
- :show-dashboard-questions? (boolean show_dashboard_questions)
- :show-exploration-documents? (boolean show_exploration_documents)
- :collection-type collection_type
- :include-library? include_library
+ :show-dashboard-questions? (boolean show-dashboard-questions)
+ :show-exploration-documents? (boolean show-exploration-documents)
+ :collection-type collection-type
+ :include-library? include-library
:models (if-not (contains? namespaces-holding-non-collection-types namespace)
#{:collection}
model-kwds)
- :pinned-state (keyword pinned_state)
+ :pinned-state (keyword pinned-state)
:search-text q
- :sort-info {:sort-column (or (some-> sort_column children-query/normalize-sort-choice) :name)
- :sort-direction (or (some-> sort_direction children-query/normalize-sort-choice) :asc)
+ :sort-info {:sort-column (or (some-> sort-column children-query/normalize-sort-choice) :name)
+ :sort-direction (or (some-> sort-direction children-query/normalize-sort-choice) :asc)
;; default to sorting official collections first, but provide the option not to
- :official-collections-first? (or (nil? official_collections_first)
- (boolean official_collections_first))}}]
+ :official-collections-first? (or (nil? official-collections-first)
+ (boolean official-collections-first))}}]
(cond-> (collection-children root-collection options)
- include_available_models
+ include-available-models
(merge (collection-filter-metadata root-collection restrict-models options)))))
+(api.macros/defendpoint :get "/root/items/metadata" :- ::ItemsMetadata
+ "Metadata about the Root Collection's items list: the models with at least one visible item plus the item count.
+ Unlike `GET /api/collection/root/items`, the result does not depend on search text; pass that endpoint's other
+ scope params so the metadata describes the list being shown."
+ [_route-params
+ {:keys [models archived namespace pinned-state collection-type include-library
+ show-dashboard-questions show-exploration-documents]} :- [:map
+ [:models {:optional true} [:maybe Models]]
+ [:archived {:default false} [:maybe ms/BooleanValue]]
+ [:namespace {:optional true} [:maybe ms/NonBlankString]]
+ [:pinned-state {:optional true} [:maybe (into [:enum] children-query/valid-pinned-state-values)]]
+ [:collection-type {:optional true} children-query/CollectionType]
+ [:include-library {:default false} [:maybe ms/BooleanValue]]
+ [:show-dashboard-questions {:default false} [:maybe ms/BooleanValue]]
+ [:show-exploration-documents {:default false} [:maybe ms/BooleanValue]]]]
+ (let [root-collection (assoc collection/root-collection :namespace namespace)
+ model-set (set (map keyword (u/one-or-many models)))
+ restrict-models (visible-model-kwds root-collection model-set)]
+ (collection-items-metadata root-collection restrict-models
+ {:archived? (boolean archived)
+ :show-dashboard-questions? (boolean show-dashboard-questions)
+ :show-exploration-documents? (boolean show-exploration-documents)
+ :collection-type collection-type
+ :include-library? include-library
+ :pinned-state (keyword pinned-state)
+ :sort-info {:sort-column :name
+ :sort-direction :asc
+ :official-collections-first? false}})))
+
;;; ----------------------------------------- Creating/Editing a Collection ------------------------------------------
;; Create-collection business logic lives in `metabase.collections.create` so that non-REST
@@ -847,11 +920,7 @@
;; `metabase.collections.core` as `create-collection!`, `apply-defaults-to-collection`,
;; `validate-new-tenant-collection!`, etc.
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/"
+(api.macros/defendpoint :post "/" :- ::Collection
"Create a new Collection."
[_route-params
_query-params
@@ -924,18 +993,6 @@
;;; ------------------------------------------------ GRAPH ENDPOINTS -------------------------------------------------
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/graph"
- "Fetch a graph of all Collection Permissions."
- [_route-params
- {:keys [namespace]} :- [:map
- [:namespace {:optional true} [:maybe ms/NonBlankString]]]]
- (api/check-superuser)
- (perms/graph namespace))
-
(def CollectionID "an id for a [[Collection]]."
[pos-int? {:title "Collection ID"}])
@@ -963,6 +1020,14 @@
[:revision {:optional true} [:maybe int?]]
[:groups [:map-of GroupID GroupPermissionsGraph]]])
+(api.macros/defendpoint :get "/graph" :- PermissionsGraph
+ "Fetch a graph of all Collection Permissions."
+ [_route-params
+ {:keys [namespace]} :- [:map
+ [:namespace {:optional true} [:maybe ms/NonBlankString]]]]
+ (api/check-superuser)
+ (perms/graph namespace))
+
(def ^:private graph-decoder
"Building it this way is a lot faster then calling mc/decode <value> <schema> <transformer>"
(mc/decoder PermissionsGraph (mtx/string-transformer)))
@@ -979,11 +1044,7 @@
{:revision (perms/latest-collection-permissions-revision-id)}
(perms/graph namespace)))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :put "/graph"
+(api.macros/defendpoint :put "/graph" :- [:map [:revision {:optional true} [:maybe :int]]]
"Do a batch update of Collections Permissions by passing in a modified graph. Will overwrite parts of the graph that
are present in the request, and leave the rest unchanged.
@@ -1008,22 +1069,14 @@
;;; ------------------------------------------ Fetching a single Collection -------------------------------------------
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/:id"
+(api.macros/defendpoint :get "/:id" :- ::Collection
"Fetch a specific Collection with standard details added"
[{:keys [id]} :- [:map
[:id [:or ms/PositiveInt ms/NanoIdString]]]]
(let [resolved-id (eid-translation/->id-or-404 :collection id)]
(collection-detail (api/read-check :model/Collection resolved-id))))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :put "/:id"
+(api.macros/defendpoint :put "/:id" :- ::Collection
"Modify an existing Collection, including archiving or unarchiving it, or moving it."
[{:keys [id]} :- [:map
[:id ms/PositiveInt]]
@@ -1057,11 +1110,8 @@
;; finally, return the updated object
(collection-detail (collections-rest.db/collection id)))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :delete "/:id"
+;; Returns the number of Collection rows deleted, which `t2/delete!` hands back -- 1 whenever the checks above pass.
+(api.macros/defendpoint :delete "/:id" :- ms/IntGreaterThanOrEqualToZero
"Deletes a collection permanently"
[{:keys [id]} :- [:map
[:id ms/PositiveInt]]]
@@ -1083,61 +1133,81 @@
;; Now we can safely delete this collection and anything left under it.
(collections-rest.db/delete-collection! id))))
-;; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest
-;; of the REST API
-;;
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-case
- :metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/:id/items"
+(api.macros/defendpoint :get "/:id/items" :- ::ItemsResponse
"Fetch a specific Collection's items with the following options:
* `models` - only include objects of a specific set of `models`. If unspecified, returns objects of all models
* `archived` - when `true`, return archived objects *instead* of unarchived ones. Defaults to `false`.
- * `pinned_state` - when `is_pinned`, return pinned objects only.
+ * `pinned-state` - when `is_pinned`, return pinned objects only.
when `is_not_pinned`, return non pinned objects only.
when `all`, return everything. By default returns everything.
* `q` - filter items by name or last editor. Blank or whitespace-only values are ignored.
- * `include_available_models` - include the models that have at least one visible item in the requested scope.
+ * `include-available-models` - include the models that have at least one visible item in the requested scope.
Note that this endpoint should return results in a similar shape to `/api/dashboard/:id/items`, so if this is
changed, that should too."
[{:keys [id]} :- [:map
[:id [:or ms/PositiveInt ms/NanoIdString]]]
- {:keys [models archived pinned_state sort_column sort_direction official_collections_first
- show_dashboard_questions q include_available_models
- show_exploration_documents]} :- [:map
+ {:keys [models archived pinned-state sort-column sort-direction official-collections-first
+ show-dashboard-questions show-exploration-documents
+ q include-available-models]} :- [:map
[:models {:optional true} [:maybe Models]]
[:archived {:default false} [:maybe ms/BooleanValue]]
- [:pinned_state {:optional true} [:maybe (into [:enum] children-query/valid-pinned-state-values)]]
- [:sort_column {:optional true} [:maybe (into [:enum] children-query/valid-sort-columns)]]
- [:sort_direction {:optional true} [:maybe (into [:enum] children-query/valid-sort-directions)]]
- [:official_collections_first {:optional true} [:maybe ms/MaybeBooleanValue]]
- [:show_dashboard_questions {:default false} [:maybe ms/BooleanValue]]
- [:show_exploration_documents {:default false} [:maybe ms/BooleanValue]]
+ [:pinned-state {:optional true} [:maybe (into [:enum] children-query/valid-pinned-state-values)]]
+ [:sort-column {:optional true} [:maybe (into [:enum] children-query/valid-sort-columns)]]
+ [:sort-direction {:optional true} [:maybe (into [:enum] children-query/valid-sort-directions)]]
+ [:official-collections-first {:optional true} [:maybe ms/MaybeBooleanValue]]
+ [:show-dashboard-questions {:default false} [:maybe ms/BooleanValue]]
+ [:show-exploration-documents {:default false} [:maybe ms/BooleanValue]]
[:q {:optional true} [:maybe :string]]
- [:include_available_models {:default false} [:maybe ms/BooleanValue]]]]
+ [:include-available-models {:default false} [:maybe ms/BooleanValue]]]]
(let [resolved-id (eid-translation/->id-or-404 :collection id)
model-kwds (set (map keyword (u/one-or-many models)))
collection (api/read-check :model/Collection resolved-id)
- options {:show-dashboard-questions? show_dashboard_questions
- :show-exploration-documents? show_exploration_documents
+ options {:show-dashboard-questions? show-dashboard-questions
+ :show-exploration-documents? show-exploration-documents
:models model-kwds
:include-library? true
:archived? (or archived (:archived collection) (collection/is-trash? collection))
- :pinned-state (keyword pinned_state)
+ :pinned-state (keyword pinned-state)
:search-text q
- :sort-info {:sort-column (or (some-> sort_column children-query/normalize-sort-choice) :name)
- :sort-direction (or (some-> sort_direction children-query/normalize-sort-choice) :asc)
+ :sort-info {:sort-column (or (some-> sort-column children-query/normalize-sort-choice) :name)
+ :sort-direction (or (some-> sort-direction children-query/normalize-sort-choice) :asc)
;; default to sorting official collections first, except for the trash.
- :official-collections-first? (if (and (nil? official_collections_first)
+ :official-collections-first? (if (and (nil? official-collections-first)
(not (collection/is-trash? collection)))
true
- (boolean official_collections_first))}}
+ (boolean official-collections-first))}}
children (cond-> (collection-children collection options)
- include_available_models
+ include-available-models
(merge (collection-filter-metadata collection nil options)))]
(events/publish-event! :event/collection-read {:object collection :user-id api/*current-user-id*})
children))
+
+(api.macros/defendpoint :get "/:id/items/metadata" :- ::ItemsMetadata
+ "Metadata about the collection's items list: the models with at least one visible item plus the item count. Unlike
+ `GET /api/collection/:id/items`, the result does not depend on search text; pass that endpoint's other scope
+ params -- `models`, `archived`, `pinned-state`, `show-dashboard-questions`, `show-exploration-documents` -- so the
+ metadata describes the list being shown."
+ [{:keys [id]} :- [:map
+ [:id [:or ms/PositiveInt ms/NanoIdString]]]
+ {:keys [models archived pinned-state
+ show-dashboard-questions show-exploration-documents]} :- [:map
+ [:models {:optional true} [:maybe Models]]
+ [:archived {:default false} [:maybe ms/BooleanValue]]
+ [:pinned-state {:optional true} [:maybe (into [:enum] children-query/valid-pinned-state-values)]]
+ [:show-dashboard-questions {:default false} [:maybe ms/BooleanValue]]
+ [:show-exploration-documents {:default false} [:maybe ms/BooleanValue]]]]
+ (let [resolved-id (eid-translation/->id-or-404 :collection id)
+ collection (api/read-check :model/Collection resolved-id)]
+ (collection-items-metadata collection (set (map keyword (u/one-or-many models)))
+ {:archived? (boolean (or archived
+ (:archived collection)
+ (collection/is-trash? collection)))
+ :show-dashboard-questions? (boolean show-dashboard-questions)
+ :show-exploration-documents? (boolean show-exploration-documents)
+ :pinned-state (keyword pinned-state)
+ :include-library? true
+ :sort-info {:sort-column :name
+ :sort-direction :asc
+ :official-collections-first? false}})))
diff --git a/src/metabase/collections_rest/children_query.clj b/src/metabase/collections_rest/children_query.clj
index 7cfb7020814..b9374211410 100644
--- a/src/metabase/collections_rest/children_query.clj
+++ b/src/metabase/collections_rest/children_query.clj
@@ -36,17 +36,17 @@
"measure"})
(def valid-pinned-state-values
- "Valid values for the `?pinned_state` param accepted by endpoints in this namespace."
+ "Valid values for the `?pinned-state` param accepted by endpoints in this namespace."
#{"all" "is_pinned" "is_not_pinned"})
(def valid-sort-columns
- "Valid values for the `?sort_column` param accepted by endpoints in this module."
+ "Valid values for the `?sort-column` param accepted by endpoints in this module."
#{"name" "last_edited_at" "last_edited_by" "model" "description"})
(def valid-sort-directions
- "Valid values for the `?sort_direction` param accepted by endpoints in this module."
+ "Valid values for the `?sort-direction` param accepted by endpoints in this module."
#{"asc" "desc"})
(defn normalize-sort-choice
- "The keyword for a `?sort_column`/`?sort_direction` param value, e.g. `\"last_edited_at\"` -> `:last-edited-at`."
+ "The keyword for a `?sort-column`/`?sort-direction` param value, e.g. `\"last_edited_at\"` -> `:last-edited-at`."
[w]
(when w (keyword (str/replace w #"_" "-"))))
diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.clj
index 08a140eafad..2b995d4a113 100644
--- a/test/metabase/collections_rest/api_test.clj
+++ b/test/metabase/collections_rest/api_test.clj
@@ -5,6 +5,7 @@
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer :all]
+ [metabase.app-db.core :as mdb]
[metabase.collections-rest.api :as api.collection]
[metabase.collections-rest.children-query :as children-query]
[metabase.collections.models.collection :as collection]
@@ -18,6 +19,7 @@
[metabase.permissions.models.collection.graph-test :as graph.test]
[metabase.queries-rest.api.card-test :as api.card-test]
[metabase.queries.models.card :as card]
+ [metabase.request.core :as request]
[metabase.revisions.models.revision :as revision]
[metabase.test :as mt]
[metabase.test.data.users :as test.users]
@@ -896,7 +898,7 @@
(letfn [(fetch [pin-state]
(:data (mt/user-http-request :crowberto :get 200
(str "collection/" (u/the-id collection) "/items")
- :pinned_state pin-state)))]
+ :pinned-state pin-state)))]
(is (= #{"pinned-1" "pinned-2"}
(->> (fetch "is_pinned")
(map :name)
@@ -942,7 +944,7 @@
(testing "combines search with the pinned-state filter"
(is (= #{["collection" "Old revenue stuff"]
["dashboard" "Revenue overview"]}
- (item-identities (fetch :q "revenue" :pinned_state "is_not_pinned")))))
+ (item-identities (fetch :q "revenue" :pinned-state "is_not_pinned")))))
(testing "trims search text and treats blank search text as absent"
(let [all-items (item-identities (fetch))]
(is (= (item-identities (fetch :q "revenue"))
@@ -1041,11 +1043,11 @@
:crowberto :get 200 (str "collection/" (u/the-id collection) "/items") params))]
(let [all-models ["card" "collection" "dashboard" "metric" "timeline"]
unpinned-models ["card" "collection" "dashboard" "timeline"]
- all-response (fetch :include_available_models true)
- unpinned-response (fetch :include_available_models true :pinned_state "is_not_pinned")
- pinned-response (fetch :include_available_models true :pinned_state "is_pinned")
- search-response (fetch :include_available_models true :q "zzz")
- models-response (fetch :include_available_models true :models "card")]
+ all-response (fetch :include-available-models true)
+ unpinned-response (fetch :include-available-models true :pinned-state "is_not_pinned")
+ pinned-response (fetch :include-available-models true :pinned-state "is_pinned")
+ search-response (fetch :include-available-models true :q "zzz")
+ models-response (fetch :include-available-models true :models "card")]
(testing "is absent unless explicitly requested"
(let [response (fetch)]
(is (not (contains? response :available_models)))))
@@ -1073,9 +1075,165 @@
(testing "reports explorations so they can be filtered on"
(let [response (mt/user-http-request :crowberto :get 200
(str "collection/" (u/the-id collection) "/items")
- :include_available_models true)]
+ :include-available-models true)]
(is (= ["card" "exploration"] (:available_models response))))))))
+(deftest collection-items-metadata-test
+ (testing "GET /api/collection/:id/items/metadata"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card _ {:name "Question" :collection_id (u/the-id collection)}
+ :model/Dashboard _ {:name "Dashboard" :collection_id (u/the-id collection)}
+ :model/Card _ {:name "Metric"
+ :type :metric
+ :collection_id (u/the-id collection)
+ :collection_position 1}
+ :model/Collection _ {:name "Child collection"
+ :location (collection/children-location collection)}
+ :model/Timeline _ {:name "Timeline" :collection_id (u/the-id collection)}]
+ (let [url (str "collection/" (u/the-id collection) "/items/metadata")]
+ (testing "counts every model by default"
+ (is (= {:available_models ["card" "collection" "dashboard" "metric" "timeline"]
+ :total_items 5}
+ (mt/user-http-request :crowberto :get 200 url))))
+ (testing "counts only the requested models, so hidden types stay out of the list metadata"
+ (is (= {:available_models ["card" "collection" "dashboard" "metric"]
+ :total_items 4}
+ (mt/user-http-request :crowberto :get 200 url
+ :models "card" :models "dataset" :models "metric"
+ :models "dashboard" :models "collection"))))
+ (testing "ignores search text"
+ (is (= {:available_models ["card" "collection" "dashboard" "metric" "timeline"]
+ :total_items 5}
+ (mt/user-http-request :crowberto :get 200 url :q "zzz"))))
+ (testing "accepts an entity id"
+ (is (= {:available_models ["card" "collection" "dashboard" "metric" "timeline"]
+ :total_items 5}
+ (mt/user-http-request :crowberto :get 200
+ (str "collection/" (:entity_id collection) "/items/metadata")))))))
+ (testing "requires read access to the collection"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403
+ (str "collection/" (u/the-id collection) "/items/metadata")))))))))
+
+(deftest collection-items-metadata-matches-items-list-test
+ (testing "GET /api/collection/:id/items/metadata describes the same list as GET /api/collection/:id/items"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card _ {:name "Question" :collection_id (u/the-id collection)}
+ :model/Card _ {:name "Pinned metric"
+ :type :metric
+ :collection_id (u/the-id collection)
+ :collection_position 1}
+ :model/Timeline _ {:name "Timeline" :collection_id (u/the-id collection)}
+ :model/Dashboard _ {:name "Trashed dashboard"
+ :collection_id (u/the-id collection)
+ :archived true
+ :archived_directly true}]
+ (doseq [params [[]
+ [:archived true]
+ [:pinned-state "is_pinned"]
+ [:pinned-state "is_not_pinned"]
+ [:archived true :pinned-state "is_not_pinned"]]]
+ (testing (pr-str params)
+ (let [metadata (apply mt/user-http-request :crowberto :get 200
+ (str "collection/" (u/the-id collection) "/items/metadata")
+ params)
+ listed (apply mt/user-http-request :crowberto :get 200
+ (str "collection/" (u/the-id collection) "/items")
+ :include-available-models true
+ params)]
+ (is (= (:total listed) (:total_items metadata)))
+ (is (= (:available_models listed) (:available_models metadata)))))))))
+
+(deftest collection-items-metadata-trash-test
+ (testing "GET /api/collection/:id/items/metadata"
+ (testing "describes the trash when asked about the trash collection"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card _ {:name "Trashed question"
+ :collection_id (u/the-id collection)
+ :archived true
+ :archived_directly true}]
+ (let [url (str "collection/" (collection/trash-collection-id) "/items/metadata")
+ metadata (mt/user-http-request :crowberto :get 200 url :models "card")
+ listed (mt/user-http-request :crowberto :get 200
+ (str "collection/" (collection/trash-collection-id) "/items")
+ :models "card")]
+ (is (= ["card"] (:available_models metadata)))
+ ;; Other trashed cards may exist in a shared app DB; what matters is that the count
+ ;; matches the items list for the same scope.
+ (is (pos? (:total_items metadata)))
+ (is (= (:total listed) (:total_items metadata))))))))
+
+(deftest collection-items-metadata-dashboard-questions-test
+ (testing "GET /api/collection/:id/items/metadata"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Dashboard dashboard {:name "Dashboard" :collection_id (u/the-id collection)}
+ :model/Card _ {:name "Dashboard question"
+ :collection_id (u/the-id collection)
+ :dashboard_id (u/the-id dashboard)}]
+ (let [url (str "collection/" (u/the-id collection) "/items/metadata")]
+ (testing "hides dashboard questions by default"
+ (is (= {:available_models ["dashboard"] :total_items 1}
+ (mt/user-http-request :crowberto :get 200 url))))
+ (testing "counts dashboard questions when show-dashboard-questions is set"
+ (is (= {:available_models ["card" "dashboard"] :total_items 2}
+ (mt/user-http-request :crowberto :get 200 url :show-dashboard-questions true))))))))
+
+(deftest root-collection-items-metadata-test
+ (testing "GET /api/collection/root/items/metadata"
+ (testing "describes the same list as GET /api/collection/root/items"
+ (mt/with-temp [:model/Card _ {:name "UXW5016 root question" :collection_id nil}
+ :model/Dashboard _ {:name "UXW5016 root dashboard" :collection_id nil}]
+ (let [metadata (mt/user-http-request :crowberto :get 200 "collection/root/items/metadata")
+ listed (mt/user-http-request :crowberto :get 200 "collection/root/items"
+ :include-available-models true)]
+ (is (set/subset? #{"card" "dashboard"} (set (:available_models metadata))))
+ (is (= (:available_models listed) (:available_models metadata)))
+ (is (= (:total listed) (:total_items metadata))))))
+ (testing "restricts to the models valid for the requested namespace"
+ (mt/with-temp [:model/Collection _ {:name "UXW5016 currency child" :namespace "currency" :location "/"}]
+ (is (= ["collection"]
+ (:available_models (mt/user-http-request :crowberto :get 200 "collection/root/items/metadata"
+ :namespace "currency"))))))
+ (testing "never counts snippets, which are not a filterable type"
+ (mt/with-temp [:model/NativeQuerySnippet _ {:name "UXW5016 root snippet"}]
+ (let [metadata (mt/user-http-request :crowberto :get 200 "collection/root/items/metadata"
+ :namespace "snippets")
+ listed (mt/user-http-request :crowberto :get 200 "collection/root/items"
+ :namespace "snippets")]
+ (is (some #(= (:model %) "snippet") (:data listed))
+ "sanity check: the items list itself does return snippets")
+ (is (not (contains? (set (:available_models metadata)) "snippet")))
+ (is (= (count (remove #(= (:model %) "snippet") (:data listed)))
+ (:total_items metadata))))))
+ (testing "excludes library collections unless include-library is set"
+ (mt/with-premium-features #{:library}
+ (mt/with-temp [:model/Collection _ {:name "UXW5016 library" :type "library-data" :location "/"}]
+ (let [without (mt/user-http-request :crowberto :get 200 "collection/root/items/metadata"
+ :models "collection")
+ with (mt/user-http-request :crowberto :get 200 "collection/root/items/metadata"
+ :models "collection" :include-library true)]
+ (is (= (inc (:total_items without)) (:total_items with)))))))
+ (testing "restricts a user without root read permission to collections, like the items list"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Card _ {:name "Root question"}
+ :model/Collection visible-collection {}]
+ (perms/grant-collection-read-permissions! (perms/all-users-group) visible-collection)
+ (let [response (mt/user-http-request :rasta :get 200 "collection/root/items/metadata"
+ :models "card" :models "collection")
+ listed (mt/user-http-request :rasta :get 200 "collection/root/items"
+ :models "card" :models "collection")]
+ (is (= ["collection"] (:available_models response)))
+ ;; Other visible root collections may exist in a shared app DB; what matters is
+ ;; that the count matches the items list for the same restricted user.
+ (is (pos? (:total_items response)))
+ (is (= (:total listed) (:total_items response))))
+ (testing "and reports nothing when only other models are requested"
+ (is (= {:available_models [] :total_items 0}
+ (mt/user-http-request :rasta :get 200 "collection/root/items/metadata"
+ :models "card")))))))))
+
(deftest collection-items-available-models-library-test
(testing "GET /api/collection/:id/items"
(mt/with-temp [:model/Collection collection {:type "library-data"}
@@ -1084,7 +1242,7 @@
(letfn [(fetch []
(mt/user-http-request :crowberto :get 200
(str "collection/" (u/the-id collection) "/items")
- :include_available_models true))]
+ :include-available-models true))]
(testing "excludes tables when the library feature is disabled"
(mt/with-premium-features #{}
(let [response (fetch)]
@@ -1108,7 +1266,7 @@
(letfn [(fetch []
(mt/user-http-request :rasta :get 200
(str "collection/" (u/the-id parent-collection) "/items")
- :include_available_models true))]
+ :include-available-models true))]
(testing "does not include a child collection the user cannot read"
(let [response (fetch)]
(is (not (contains? (set (:available_models response)) "collection")))
@@ -1134,7 +1292,7 @@
(str "collection/" (u/the-id collection) "/items")
:archived true
:q "revenue"
- :include_available_models true)]
+ :include-available-models true)]
(is (= 1 (:total response)))
(is (= #{["card" "Old revenue"]}
(set (map (juxt :model :name) (:data response)))))
@@ -1158,7 +1316,7 @@
(let [response (mt/user-http-request :crowberto :get 200
(str "collection/" (collection/trash-collection-id) "/items")
:q "quarterly revenue"
- :include_available_models true)]
+ :include-available-models true)]
(is (= 1 (:total response)))
(is (= #{[(:id matching-card) "Trashed quarterly revenue"]}
(set (map (juxt :id :name) (:data response)))))
@@ -1176,7 +1334,7 @@
(testing "searches root items and reports models before search filtering"
(let [response (mt/user-http-request :crowberto :get 200 "collection/root/items"
:q "UXW4950 ROOT revenue"
- :include_available_models true)]
+ :include-available-models true)]
(is (= 1 (:total response)))
(is (= #{["card" "UXW4950 root revenue"]}
(set (map (juxt :model :name) (:data response)))))
@@ -1185,13 +1343,13 @@
(testing "restricts metadata to namespace-valid models"
(let [response (mt/user-http-request :crowberto :get 200 "collection/root/items"
:namespace "currency"
- :include_available_models true)]
+ :include-available-models true)]
(is (= ["collection"] (:available_models response)))
(is (some #(= (:id currency-collection) (:id %)) (:data response)))))
(testing "never reports snippets in available models"
(let [response (mt/user-http-request :crowberto :get 200 "collection/root/items"
:namespace "snippets"
- :include_available_models true)]
+ :include-available-models true)]
(is (some #(= (:model %) "snippet") (:data response)))
(is (not (contains? (set (:available_models response)) "snippet")))))
(testing "restricts metadata to collections for a user without root read permission"
@@ -1199,7 +1357,7 @@
(perms/grant-collection-read-permissions! (perms/all-users-group) visible-collection)
(let [response (mt/user-http-request :rasta :get 200 "collection/root/items"
:q "UXW4950 ROOT revenue"
- :include_available_models true)
+ :include-available-models true)
available-models (set (:available_models response))]
(is (= [] (:data response)))
(is (= #{"collection"} available-models))))))))
@@ -1420,24 +1578,24 @@
(testing "Results can be ordered by last-edited-at"
(testing "ascending"
(is (= ["Card with history 1" "Card with history 2" "AA" "ZZ"]
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort_column=last_edited_at&sort_direction=asc"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort-column=last_edited_at&sort-direction=asc"))
:data
(map :name)))))
(testing "descending"
(is (= ["Card with history 2" "Card with history 1" "AA" "ZZ"]
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort_column=last_edited_at&sort_direction=desc"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort-column=last_edited_at&sort-direction=desc"))
:data
(map :name))))))
(testing "Results can be ordered by last-edited-by"
(testing "ascending"
;; card with history 2 has user Test AAAA, history 1 user Test ZZZZ
(is (= ["Card with history 2" "Card with history 1" "AA" "ZZ"]
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort_column=last_edited_by&sort_direction=asc"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort-column=last_edited_by&sort-direction=asc"))
:data
(map :name)))))
(testing "descending"
(is (= ["Card with history 1" "Card with history 2" "AA" "ZZ"]
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort_column=last_edited_by&sort_direction=desc"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort-column=last_edited_by&sort-direction=desc"))
:data
(map :name))))))))))
@@ -1453,12 +1611,12 @@
:model/Pulse _ {:name "AA" :collection_id collection-id}]
(testing "sort direction asc"
(is (= [["dashboard" "AA"] ["dashboard" "ZZ"] ["pulse" "AA"] ["pulse" "ZZ"] ["card" "AA"] ["card" "ZZ"]]
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort_column=model&sort_direction=asc"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort-column=model&sort-direction=asc"))
:data
(map (juxt :model :name))))))
(testing "sort direction desc"
(is (= [["card" "AA"] ["card" "ZZ"] ["pulse" "AA"] ["pulse" "ZZ"] ["dashboard" "AA"] ["dashboard" "ZZ"]]
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort_column=model&sort_direction=desc"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" collection-id "/items?sort-column=model&sort-direction=desc"))
:data
(map (juxt :model :name))))))))))
@@ -1471,7 +1629,7 @@
:model/Dashboard _ {:name "ZZ" :collection_id (u/the-id parent)}]
(is (= "collection"
(-> (mt/user-http-request :rasta :get 200
- (str "collection/" (u/the-id parent) "/items?sort_column=model&sort_direction=desc"))
+ (str "collection/" (u/the-id parent) "/items?sort-column=model&sort-direction=desc"))
:data first :model)))))))
(deftest collection-items-include-latest-revision-test
@@ -1729,6 +1887,29 @@
(map #(select-keys % [:id :name]))
(:data (mt/user-http-request :rasta :get 200 (format "collection/%d/items" (:id collection)))))))))))))
+(deftest snippet-collection-items-count-only-test
+ (testing "The snippets namespace is unpaginated, but a count-only request still keeps its LIMIT"
+ (mt/with-temp [:model/NativeQuerySnippet _ {:name "UXW5016 root snippet"}]
+ (mt/with-test-user :crowberto
+ (let [queries (atom [])
+ real-query mdb/query
+ this-thread (Thread/currentThread)]
+ ;; `with-redefs` is global, so only record what this thread asks for.
+ (with-redefs [mdb/query (fn [query & args]
+ (when (identical? this-thread (Thread/currentThread))
+ (swap! queries conj query))
+ (apply real-query query args))]
+ (request/with-limit-and-offset 0 0
+ (is (pos? (:total (#'api.collection/collection-children
+ (assoc collection/root-collection :namespace "snippets")
+ {:archived? false
+ :show-dashboard-questions? false
+ :show-exploration-documents? false
+ :models #{:snippet}
+ :sort-info {:sort-column :name :sort-direction :asc}}))))))
+ (is (= [1] (mapv :limit @queries))
+ "the row query is bounded instead of fetching every snippet just to read the count"))))))
+
;;; --------------------------------- Fetching Personal Collections (Ours & Others') ---------------------------------
(defn- lucky-personal-collection []
@@ -2002,7 +2183,7 @@
all-types (map :type (:data response))]
(is (not-any? #{collection/library-collection-type} all-types))))
(testing "Can choose to include include library items"
- (let [response (mt/user-http-request :rasta :get 200 "collection/root/items" :include_library true)
+ (let [response (mt/user-http-request :rasta :get 200 "collection/root/items" :include-library true)
all-types (map :type (:data response))]
(is (some #{collection/library-collection-type} all-types))))))))
@@ -2722,8 +2903,8 @@
(deftest fetch-root-items-collection-type-filter-test
(testing "GET /api/collection/root/items"
- (testing "collection_type parameter filters collections to only those with matching type"
- (testing "collection_type=remote-synced returns only remote-synced collections"
+ (testing "collection-type parameter filters collections to only those with matching type"
+ (testing "collection-type=remote-synced returns only remote-synced collections"
(mt/with-temp [:model/Collection _ {:name "Normal Collection"}
:model/Collection _ {:name "Remote Synced Collection"
:is_remote_synced true}
@@ -2731,7 +2912,7 @@
:is_remote_synced true}
:model/Collection _ {:name "Second Normal Collection"}]
(let [response (mt/user-http-request :crowberto :get 200 "collection/root/items"
- :collection_type "remote-synced")
+ :collection-type "remote-synced")
collections (->> (:data response)
(filter #(= (:model %) "collection")))
collection-names (set (map :name collections))]
@@ -2745,7 +2926,7 @@
(doseq [coll collections]
(is (true? (:is_remote_synced coll))
(str "Collection " (:name coll) " should have is_remote_synced=true")))))))
- (testing "without collection_type parameter, all collections are returned"
+ (testing "without collection-type parameter, all collections are returned"
(mt/with-temp [:model/Collection _ {:name "Normal Collection Test"}
:model/Collection _ {:name "Remote Synced Collection Test"
:is_remote_synced true}]
@@ -3569,7 +3750,7 @@
[dash-id "dashboard"]}
(set (map (juxt :id :model)
(:data
- (mt/user-http-request :rasta :get 200 (str "collection/" coll-id "/items?show_dashboard_questions=true")))))))))
+ (mt/user-http-request :rasta :get 200 (str "collection/" coll-id "/items?show-dashboard-questions=true")))))))))
(mt/with-temp [:model/Collection {parent-id :id :as parent} {}
:model/Collection {coll-id :id} {:location (collection/children-location parent)}
:model/Dashboard {dash-id :id} {:collection_id coll-id}
@@ -3581,7 +3762,7 @@
(is (= ["dashboard" "card"]
(:here
(first
- (:data (mt/user-http-request :rasta :get 200 (str "collection/" parent-id "/items?show_dashboard_questions=true")))))))))))
+ (:data (mt/user-http-request :rasta :get 200 (str "collection/" parent-id "/items?show-dashboard-questions=true")))))))))))
(deftest dashboard-questions-have-dashboard-hydrated
(mt/with-temp [:model/Collection {coll-id :id} {}
@@ -3592,7 +3773,7 @@
(is (= {:name dash-name
:id dash-id
:moderation_status nil}
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" coll-id "/items?show_dashboard_questions=true"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" coll-id "/items?show-dashboard-questions=true"))
:data
(filter #(= (:model %) "card"))
first
@@ -3604,7 +3785,7 @@
:moderator_id (mt/user->id :rasta)
:most_recent true}]
(is (= {:name dash-name :id dash-id :moderation_status "verified"}
- (->> (mt/user-http-request :rasta :get 200 (str "collection/" coll-id "/items?show_dashboard_questions=true"))
+ (->> (mt/user-http-request :rasta :get 200 (str "collection/" coll-id "/items?show-dashboard-questions=true"))
:data
(filter #(= (:model %) "card"))
first
@@ -3895,7 +4076,7 @@
(is (not (some #(= (:id e) (:id %)) items)))))))
(deftest exploration-pinning-test
- (testing "explorations with collection_position appear under ?pinned_state=is_pinned"
+ (testing "explorations with collection_position appear under ?pinned-state=is_pinned"
(mt/with-temp [:model/User owner {}
:model/Collection coll {}
:model/Exploration pinned {:name "Pinned"
@@ -3906,7 +4087,7 @@
:creator_id (:id owner)
:collection_id (:id coll)}]
(let [pinned-items (->> (:data (mt/user-http-request :crowberto :get 200
- (str "collection/" (:id coll) "/items?pinned_state=is_pinned")))
+ (str "collection/" (:id coll) "/items?pinned-state=is_pinned")))
(filter #(= "exploration" (:model %)))
(map :id)
set)]
diff --git a/test/metabase/documents/api/collection_test.clj b/test/metabase/documents/api/collection_test.clj
index 42eee7555d3..608cd5befe4 100644
--- a/test/metabase/documents/api/collection_test.clj
+++ b/test/metabase/documents/api/collection_test.clj
@@ -18,12 +18,12 @@
(set (map (juxt :id :model)
(:data (mt/user-http-request :rasta :get 200
(str "collection/" coll-id "/items"))))))))
- (testing "Even with show_dashboard_questions=true, in_document cards do not appear"
+ (testing "Even with show-dashboard-questions=true, in_document cards do not appear"
(is (= #{[normal-card-id "card"]
[dash-id "dashboard"]}
(set (map (juxt :id :model)
(:data (mt/user-http-request :rasta :get 200
- (str "collection/" coll-id "/items?show_dashboard_questions=true")))))))))))
+ (str "collection/" coll-id "/items?show-dashboard-questions=true")))))))))))
(deftest document-cards-do-not-appear-in-root-items
(testing "GET /api/collection/root/items excludes cards with document_id"
@@ -42,8 +42,8 @@
(is (= #{[normal-card-id "card"]
[dash-id "dashboard"]}
(set (map (juxt :id :model) root-test-items))))))
- (testing "Even with show_dashboard_questions=true, in_document cards do not appear"
- (let [items (mt/user-http-request :rasta :get 200 "collection/root/items?show_dashboard_questions=true")
+ (testing "Even with show-dashboard-questions=true, in_document cards do not appear"
+ (let [items (mt/user-http-request :rasta :get 200 "collection/root/items?show-dashboard-questions=true")
root-test-items (filter #(#{normal-card-id dash-id in-document-card-id} (:id %))
(:data items))]
(is (= #{[normal-card-id "card"]
@@ -114,7 +114,7 @@
(deftest archived-exploration-documents-appear-in-trash-with-flag
(testing "Exploration documents are hidden from collection listings by default,"
- (testing "but appear in the Trash when show_exploration_documents=true (mirrors dashboard-questions behavior)."
+ (testing "but appear in the Trash when show-exploration-documents=true (mirrors dashboard-questions behavior)."
(mt/with-temp [:model/Exploration {expl-id :id} {:creator_id (mt/user->id :rasta)
:name "Test Exploration"}
:model/Document {expl-doc-id :id} {:collection_id nil
@@ -127,9 +127,9 @@
(let [items (mt/user-http-request :rasta :get 200
(format "collection/%d/items" trash-id))]
(is (not (some #(= expl-doc-id (:id %)) (:data items))))))
- (testing "With show_exploration_documents=true, it appears with restore/delete affordances"
+ (testing "With show-exploration-documents=true, it appears with restore/delete affordances"
(let [items (mt/user-http-request :rasta :get 200
- (format "collection/%d/items?show_exploration_documents=true" trash-id))
+ (format "collection/%d/items?show-exploration-documents=true" trash-id))
hit (first (filter #(= expl-doc-id (:id %)) (:data items)))]
(is (some? hit))
(is (= "document" (:model hit)))
@@ -151,15 +151,33 @@
ids (set (map :id (:data items)))]
(is (contains? ids plain-doc-id))
(is (not (contains? ids expl-doc-id)))))
- (testing "With show_exploration_documents=true, both are listed"
+ (testing "With show-exploration-documents=true, both are listed"
(let [items (mt/user-http-request :rasta :get 200
- (format "collection/%d/items?show_exploration_documents=true" coll-id))
+ (format "collection/%d/items?show-exploration-documents=true" coll-id))
ids (set (map :id (:data items)))]
(is (contains? ids plain-doc-id))
(is (contains? ids expl-doc-id)))))))
+(deftest exploration-documents-metadata-test
+ (testing "GET /api/collection/:id/items/metadata"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Exploration {expl-id :id} {:creator_id (mt/user->id :rasta)
+ :name "Metadata Exploration"}
+ :model/Document _ {:collection_id coll-id
+ :name "Plain Doc"}
+ :model/Document _ {:collection_id coll-id
+ :name "Exploration Doc"
+ :exploration_id expl-id}]
+ (let [url (format "collection/%d/items/metadata" coll-id)]
+ (testing "hides exploration documents by default, like the items list does"
+ (is (= {:available_models ["document"] :total_items 1}
+ (mt/user-http-request :rasta :get 200 url))))
+ (testing "counts them when show-exploration-documents is set"
+ (is (= {:available_models ["document"] :total_items 2}
+ (mt/user-http-request :rasta :get 200 url :show-exploration-documents true))))))))
+
(deftest document-pinning-collection-items
- (testing "GET /api/collection/:id/items supports pinned_state parameter for documents"
+ (testing "GET /api/collection/:id/items supports pinned-state parameter for documents"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {pinned-doc-id :id} {:collection_id coll-id
:name "Pinned Document"
@@ -173,25 +191,25 @@
:model/Card {unpinned-card-id :id} {:collection_id coll-id
:name "Unpinned Card"
:collection_position nil}]
- (testing "pinned_state=is_pinned returns only pinned documents and cards"
+ (testing "pinned-state=is_pinned returns only pinned documents and cards"
(let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" coll-id "/items?pinned_state=is_pinned")))
+ (str "collection/" coll-id "/items?pinned-state=is_pinned")))
item-ids (set (map (juxt :model :id) items))]
(is (contains? item-ids ["document" pinned-doc-id]))
(is (contains? item-ids ["card" pinned-card-id]))
(is (not (contains? item-ids ["document" unpinned-doc-id])))
(is (not (contains? item-ids ["card" unpinned-card-id])))))
- (testing "pinned_state=is_not_pinned returns only unpinned documents and cards"
+ (testing "pinned-state=is_not_pinned returns only unpinned documents and cards"
(let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" coll-id "/items?pinned_state=is_not_pinned")))
+ (str "collection/" coll-id "/items?pinned-state=is_not_pinned")))
item-ids (set (map (juxt :model :id) items))]
(is (not (contains? item-ids ["document" pinned-doc-id])))
(is (not (contains? item-ids ["card" pinned-card-id])))
(is (contains? item-ids ["document" unpinned-doc-id]))
(is (contains? item-ids ["card" unpinned-card-id]))))
- (testing "pinned_state=all returns all documents and cards"
+ (testing "pinned-state=all returns all documents and cards"
(let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" coll-id "/items?pinned_state=all")))
+ (str "collection/" coll-id "/items?pinned-state=all")))
item-ids (set (map (juxt :model :id) items))]
(is (contains? item-ids ["document" pinned-doc-id]))
(is (contains? item-ids ["card" pinned-card-id]))
@@ -199,7 +217,7 @@
(is (contains? item-ids ["card" unpinned-card-id])))))))
(deftest document-pinning-root-items
- (testing "GET /api/collection/root/items supports pinned_state parameter for documents"
+ (testing "GET /api/collection/root/items supports pinned-state parameter for documents"
(mt/with-temp [:model/Document {pinned-doc-id :id} {:collection_id nil
:name "Pinned Root Document"
:collection_position 1}
@@ -212,15 +230,15 @@
:model/Card {unpinned-card-id :id} {:collection_id nil
:name "Unpinned Root Card"
:collection_position nil}]
- (testing "pinned_state=is_pinned returns only pinned root documents and cards"
- (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items?pinned_state=is_pinned"))
+ (testing "pinned-state=is_pinned returns only pinned root documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items?pinned-state=is_pinned"))
test-item-ids (set (map (juxt :model :id) items))]
(is (contains? test-item-ids ["document" pinned-doc-id]))
(is (contains? test-item-ids ["card" pinned-card-id]))
(is (not (contains? test-item-ids ["document" unpinned-doc-id])))
(is (not (contains? test-item-ids ["card" unpinned-card-id])))))
- (testing "pinned_state=is_not_pinned returns only unpinned root documents and cards"
- (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items?pinned_state=is_not_pinned"))
+ (testing "pinned-state=is_not_pinned returns only unpinned root documents and cards"
+ (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items?pinned-state=is_not_pinned"))
test-item-ids (set (map (juxt :model :id) items))]
(is (not (contains? test-item-ids ["document" pinned-doc-id])))
(is (not (contains? test-item-ids ["card" pinned-card-id])))
@@ -251,7 +269,7 @@
(is (some #(= 3 %) doc-positions))))
(testing "Pinned documents have higher collection_position values and appear before unpinned"
(let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" coll-id "/items?pinned_state=is_pinned")))
+ (str "collection/" coll-id "/items?pinned-state=is_pinned")))
pinned-docs (filter #(= "document" (:model %)) items)]
(is (= 2 (count pinned-docs)))
;; Verify all pinned docs have non-nil collection_position