The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add in-collection type filters with dynamic options (#79340)
Anderson767591451306
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.jsindex 5e69b379232..b552799cc2f 100644--- a/e2e/test/scenarios/collections/collections.cy.spec.js+++ b/e2e/test/scenarios/collections/collections.cy.spec.js@@ -1229,6 +1229,79 @@ describe("scenarios > collection items listing", () => {});});+ describe("type filters", () => {+ beforeEach(() => {+ archiveAll();++ H.createDashboard({+ name: "Revenue dashboard",+ collection_position: null,+ });+ H.createQuestion({+ name: "Customer question",+ collection_position: null,+ query: TEST_QUESTION_QUERY,+ });+ });++ it("should filter collection items by the available types", () => {+ cy.intercept(+ {+ method: "GET",+ pathname: "/api/collection/root/items",+ query: { pinned_state: "is_not_pinned" },+ },+ (request) => {+ const models = new URL(request.url).searchParams+ .getAll("models")+ .sort();++ if (models.join(",") === "card,collection") {+ request.alias = "getTypeFilteredCollectionItems";+ }+ },+ );+ visitRootCollection();++ 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.findByRole("button", { name: "Apply" }).should("not.exist");+ cy.findByLabelText("Dashboard").click();+ });++ cy.wait("@getTypeFilteredCollectionItems").then(({ request }) => {+ const searchParams = new URL(request.url).searchParams;++ expect(searchParams.getAll("models").sort()).to.deep.equal([+ "card",+ "collection",+ ]);+ expect(searchParams.get("offset")).to.equal("0");+ });+ cy.findByTestId("collection-table")+ .should("contain", "First collection")+ .and("contain", "Customer question")+ .and("not.contain", "Revenue dashboard");+ cy.findByTestId("type-filter-indicator")+ .find('[class*="Indicator-indicator"]')+ .should("exist");++ H.popover().findByLabelText("Dashboard").click();++ cy.findByTestId("collection-table")+ .should("contain", "Revenue dashboard")+ .and("contain", "Customer question");+ cy.findByTestId("type-filter-indicator")+ .find('[class*="Indicator-indicator"]')+ .should("not.exist");+ });+ });+describe("pagination", () => {const SUBCOLLECTIONS = 1;const ADDED_QUESTIONS = 15;diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.tsindex b50634c481f..bd00c2aa80a 100644--- a/frontend/src/metabase-types/api/collection.ts+++ b/frontend/src/metabase-types/api/collection.ts@@ -170,8 +170,9 @@ export type ListCollectionItemsSortColumn =export type ListCollectionItemsRequest = {id: CollectionId;- models?: CollectionItemModel[];+ models?: (CollectionItemModel | "no_models")[];q?: string;+ include_available_models?: boolean;archived?: boolean;pinned_state?: "all" | "is_pinned" | "is_not_pinned";namespace?: CollectionNamespace;@@ -184,6 +185,7 @@ export type ListCollectionItemsRequest = {export type ListCollectionItemsResponse = {data: CollectionItem[];models: CollectionItemModel[] | null;+ available_models?: string[];} & PaginationResponse;export interface UpdateCollectionRequest {diff --git a/frontend/src/metabase/api/collection.ts b/frontend/src/metabase/api/collection.tsindex 99b60eae88c..09e2f52b57e 100644--- a/frontend/src/metabase/api/collection.ts+++ b/frontend/src/metabase/api/collection.ts@@ -5,6 +5,7 @@ import {} from "metabase/schema";import type {Collection,+ CollectionItemModel,CollectionPermissionsGraph,CreateCollectionRequest,DeleteCollectionRequest,@@ -48,6 +49,13 @@ const collectionSchemaForRequest = (? SnippetCollectionSchema: CollectionSchema;+const getCollectionItemTagModels = (+ models: ListCollectionItemsRequest["models"],+): CollectionItemModel[] | undefined =>+ models?.filter(+ (model): model is CollectionItemModel => model !== "no_models",+ );+export const collectionApi = Api.injectEndpoints({endpoints: (builder) => ({/**@@ -99,7 +107,10 @@ export const collectionApi = Api.injectEndpoints({params,}),providesTags: (response, error, { models, id }) => [- ...provideCollectionItemListTags(response?.data ?? [], models),+ ...provideCollectionItemListTags(+ response?.data ?? [],+ getCollectionItemTagModels(models),+ ),{ type: "collection", id: `${id}-items` },],onQueryStarted: hydrateMetadataStore<ListCollectionItemsResponse>(diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.tsindex e54c4384579..1abf0317ff1 100644--- a/frontend/src/metabase/api/dashboard.ts+++ b/frontend/src/metabase/api/dashboard.ts@@ -169,7 +169,10 @@ export const dashboardApi = Api.injectEndpoints({}),listDashboardItems: builder.query<ListCollectionItemsResponse,- Omit<ListCollectionItemsRequest, "id" | "q"> & { id: DashboardId }+ Omit<+ ListCollectionItemsRequest,+ "id" | "q" | "include_available_models"+ > & { id: DashboardId }>({query: ({ id, ...body }) => ({method: "GET",diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsxindex 00329e31c6f..8868685f534 100644--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx@@ -69,6 +69,19 @@ 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"],+ };+};+export type CollectionItemsTableProps = {collectionId?: CollectionId;} & Partial<{@@ -109,11 +122,15 @@ const DefaultEmptyContentComponent = ({);};-const CollectionNoResults = () => (+const CollectionNoResults = ({ hasSearchText }: { hasSearchText: boolean }) => (<Box my="4rem" data-testid="collection-filter-empty-state"><EmptyStatetitle={t`Didn't find anything`}- message={t`There weren't any results for your search.`}+ message={+ hasSearchText+ ? t`There weren't any results for your search.`+ : t`No items of the selected types.`+ }illustrationElement={<img src={NoResultsImg} alt={t`No results`} />}/></Box>@@ -145,6 +162,14 @@ export const CollectionItemsTable = ({}: CollectionItemsTableProps) => {const [search, setSearch] = useState({ collectionId, value: "" });const searchText = search.collectionId === collectionId ? search.value : "";+ const [filterSelection, setFilterSelection] = useState<{+ collectionId?: CollectionId;+ value: CollectionItemModel[] | null;+ }>({ collectionId, value: null });+ const selectedFilters =+ filterSelection.collectionId === collectionId+ ? filterSelection.value+ : null;const debouncedSearchText = useDebouncedValue(searchText,SEARCH_DEBOUNCE_DURATION,@@ -163,6 +188,7 @@ export const CollectionItemsTable = ({useEffect(() => {resetPage();setSearch({ collectionId, value: "" });+ setFilterSelection({ collectionId, value: null });}, [collectionId, resetPage]);const handleSearchTextChange = useCallback(@@ -173,6 +199,14 @@ export const CollectionItemsTable = ({[collectionId, setPage],);+ const handleSelectedFiltersChange = useCallback(+ (nextFilters: CollectionItemModel[] | null) => {+ setFilterSelection({ collectionId, value: nextFilters });+ setPage(0);+ },+ [collectionId, setPage],+ );+const handleUnpinnedItemsSortingChange = useCallback((sortingOpts: SortingOptions<ListCollectionItemsSortColumn>) => {setUnpinnedItemsSorting(sortingOpts);@@ -201,6 +235,7 @@ export const CollectionItemsTable = ({page={page}pageSize={pageSize}searchText={searchText}+ selectedFilters={selectedFilters}selected={selected}selectOnlyTheseItems={selectOnlyTheseItems}showFilterBar={showFilterBar}@@ -211,7 +246,8 @@ export const CollectionItemsTable = ({? skipToken: {id: collectionId,- models,+ ...getQueryFilters(models, selectedFilters),+ ...(showFilterBar ? { include_available_models: true } : {}),limit: pageSize,offset: pageSize * page,...(showAllItems@@ -226,6 +262,7 @@ export const CollectionItemsTable = ({onNextPage={handleNextPage}onPreviousPage={handlePreviousPage}onSearchTextChange={handleSearchTextChange}+ onSelectedFiltersChange={handleSelectedFiltersChange}onUnpinnedItemsSortingChange={handleUnpinnedItemsSortingChange}/>);@@ -234,11 +271,13 @@ export const CollectionItemsTable = ({type CollectionItemsTableContentProps = CollectionItemsTableProps & {page: number;searchText: string;+ selectedFilters: CollectionItemModel[] | null;unpinnedItemsSorting: SortingOptions<ListCollectionItemsSortColumn>;unpinnedQuery: ListCollectionItemsRequest | typeof skipToken;onNextPage: () => void;onPreviousPage: () => void;onSearchTextChange: (searchText: string) => void;+ onSelectedFiltersChange: (filters: CollectionItemModel[] | null) => void;onUnpinnedItemsSortingChange: (unpinnedItemsSorting: SortingOptions<ListCollectionItemsSortColumn>,) => void;@@ -261,6 +300,7 @@ const CollectionItemsTableContent = ({page,pageSize = COLLECTION_PAGE_SIZE,searchText,+ selectedFilters,selected,selectOnlyTheseItems,showFilterBar,@@ -272,12 +312,14 @@ const CollectionItemsTableContent = ({onNextPage,onPreviousPage,onSearchTextChange,+ onSelectedFiltersChange,onUnpinnedItemsSortingChange,}: CollectionItemsTableContentProps) => {const { data, isFetching: fetchingUnpinnedItems } =useListCollectionItemsQuery(unpinnedQuery);const unpinnedItems = data?.data ?? [];+ const availableModels = data?.available_models ?? [];const total = data?.total;const visibleColumnsMap = useMemo(() => getVisibleColumnsMap(visibleColumns),@@ -298,7 +340,8 @@ const CollectionItemsTableContent = ({const loading = loadingPinnedItems || fetchingUnpinnedItems;const hasSearchQuery =unpinnedQuery !== skipToken && Boolean(unpinnedQuery.q?.trim());- const hasActiveFilters = searchText.trim().length > 0 || hasSearchQuery;+ const hasSearchText = searchText.trim().length > 0 || hasSearchQuery;+ const hasActiveFilters = hasSearchText || selectedFilters != null;const isSearching = fetchingUnpinnedItems && hasSearchQuery;const isEmpty =!loading &&@@ -319,12 +362,15 @@ const CollectionItemsTableContent = ({{showFilterBar && (<CollectionItemsToolbarsearchText={searchText}+ availableModels={availableModels}+ selectedFilters={selectedFilters}onSearchTextChange={onSearchTextChange}+ onSelectedFiltersChange={onSelectedFiltersChange}hasPinnedItems={hasPinnedItems}isSearching={isSearching}/>)}- {showNoResults && <CollectionNoResults />}+ {showNoResults && <CollectionNoResults hasSearchText={hasSearchText} />}{showTable && (<CollectionTable data-testid="collection-table"><ItemsTablediff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsxindex 13105140eee..2f2dfaf73da 100644--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx@@ -106,6 +106,20 @@ function getSearchCalls(collectionId: CollectionId = collection.id) {);}+function getItemsSearchParams() {+ return getItemsCalls().map((call) => new URL(call.url).searchParams);+}++function findItemsSearchParamsByModels(models: string[]) {+ const sortedModels = [...models].sort();++ return getItemsSearchParams().find(+ (searchParams) =>+ JSON.stringify(searchParams.getAll("models").sort()) ===+ JSON.stringify(sortedModels),+ );+}+function setupUserWithFakeTimers() {jest.useFakeTimers();return userEvent.setup({ advanceTimers: jest.advanceTimersByTime });@@ -162,6 +176,11 @@ describe("CollectionItemsTable", () => {expect(screen.queryByTestId("collection-items-toolbar"),).not.toBeInTheDocument();+ expect(+ getItemsCalls().some((call) =>+ new URL(call.url).searchParams.has("include_available_models"),+ ),+ ).toBe(false);});it("keeps the table mounted without showing a loader during a refetch with no search", async () => {@@ -474,7 +493,116 @@ describe("CollectionItemsTable", () => {expect(await screen.findByText("Revenue overview")).toBeInTheDocument();});- it("does not send the previous search to a new collection", async () => {+ it("shows filter options for the available item types", async () => {+ setup();++ await waitFor(() => {+ expect(+ getItemsSearchParams().some(+ (searchParams) =>+ searchParams.get("include_available_models") === "true",+ ),+ ).toBe(true);+ });+ 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("Model")).toBeChecked();+ expect(within(popover).getByLabelText("Question")).toBeChecked();+ expect(within(popover).queryByLabelText("Metric")).not.toBeInTheDocument();+ });++ it("filters by type and resets pagination", async () => {+ setup({ pageSize: 1 });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "Next page" }));+ expect(await screen.findByText("Customer 360")).toBeInTheDocument();+ await userEvent.click(+ await screen.findByTestId("collection-type-filter-button"),+ );+ await userEvent.click(screen.getByLabelText("Dashboard"));++ await waitFor(() => {+ expect(+ findItemsSearchParamsByModels(["dataset", "card"])?.get("offset"),+ ).toBe("0");+ });+ expect(screen.queryByText("Revenue overview")).not.toBeInTheDocument();+ expect(screen.getByText("Customer 360")).toBeInTheDocument();+ expect(screen.queryByText("Orders model")).not.toBeInTheDocument();+ });++ it("uses no_models and shows no results when every type is unchecked", async () => {+ setup();++ await userEvent.click(+ await screen.findByTestId("collection-type-filter-button"),+ );+ 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(await screen.findByText("Didn't find anything")).toBeInTheDocument();+ expect(+ screen.getByTestId("collection-filter-empty-state"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("No items of the selected types."),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("collection-table")).not.toBeInTheDocument();+ expect(popover).toBeInTheDocument();+ expect(+ within(popover).queryByRole("button", { name: "Apply" }),+ ).not.toBeInTheDocument();+ });++ it("keeps all type options while search has no results", async () => {+ const user = setupUserWithFakeTimers();+ setup();++ await user.click(+ 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();+ within(popover).getByLabelText("Dashboard").focus();+ await user.keyboard("{Escape}");+ await waitFor(() => {+ expect(+ screen.queryByTestId("collection-type-filter-popover"),+ ).not.toBeInTheDocument();+ });++ await user.type(+ await screen.findByPlaceholderText("Search by name or editor..."),+ "not found",+ );+ advanceSearchDebounce();+ expect(+ await screen.findByTestId("collection-filter-empty-state"),+ ).toBeInTheDocument();++ 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();+ });++ it("resets search and type filters before requesting a new collection", async () => {const nextCollection = createMockCollection({ id: 2, can_write: false });const nextCollectionItems = [createMockCollectionItem({@@ -491,6 +619,16 @@ describe("CollectionItemsTable", () => {{ withRouter: true, withDND: true },);+ await user.click(+ await screen.findByTestId("collection-type-filter-button"),+ );+ await user.click(screen.getByLabelText("Dashboard"));+ expect(+ screen.getByRole("button", { name: "Filter, filters applied" }),+ ).toBeInTheDocument();+ screen.getByLabelText("Dashboard").focus();+ await user.keyboard("{Escape}");+await user.type(await screen.findByPlaceholderText("Search by name or editor..."),"revenue",@@ -508,12 +646,23 @@ describe("CollectionItemsTable", () => {screen.getByRole("button", { name: "Open next collection" }),);+ expect(await screen.findByText("Inventory overview")).toBeInTheDocument();expect(screen.getByPlaceholderText("Search by name or editor..."),).toHaveValue("");- expect(await screen.findByText("Inventory overview")).toBeInTheDocument();expect(getItemsCalls(nextCollection.id).length).toBeGreaterThan(0);expect(getSearchCalls(nextCollection.id)).toHaveLength(0);+ expect(+ getItemsCalls(nextCollection.id).every((call) =>+ new URL(call.url).searchParams.getAll("models").includes("dashboard"),+ ),+ ).toBe(true);++ 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();advanceSearchDebounce();expect(getSearchCalls(nextCollection.id)).toHaveLength(0);@@ -529,4 +678,46 @@ describe("CollectionItemsTable", () => {screen.queryByTestId("collection-items-toolbar"),).not.toBeInTheDocument();});++ it("keeps official collections in the generic Collection filter", async () => {+ const regularCollection = createMockCollectionItem({+ id: 4,+ collection_id: collection.id,+ model: "collection",+ name: "Regular collection",+ authority_level: null,+ });+ const officialCollection = createMockCollectionItem({+ id: 5,+ collection_id: collection.id,+ model: "collection",+ name: "Official collection",+ authority_level: "official",+ });+ setup({+ collectionItems: [+ collectionItems[0],+ regularCollection,+ officialCollection,+ ],+ });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(screen.getByText("Regular collection")).toBeInTheDocument();+ expect(screen.getByText("Official collection")).toBeInTheDocument();++ await userEvent.click(screen.getByTestId("collection-type-filter-button"));+ await userEvent.click(screen.getByLabelText("Dashboard"));++ await waitFor(() => {+ const searchParams = findItemsSearchParamsByModels(["collection"]);+ expect(searchParams).toBeDefined();+ expect(searchParams?.has("authority_level")).toBe(false);+ });+ expect(screen.getByText("Regular collection")).toBeInTheDocument();+ expect(screen.getByText("Official collection")).toBeInTheDocument();+ await waitFor(() => {+ expect(screen.queryByText("Revenue overview")).not.toBeInTheDocument();+ });+ });});diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsxindex 97586625b1a..aca79ada7a7 100644--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsx+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsx@@ -1,19 +1,28 @@import { t } from "ttag";import { Flex, Icon, Input, Loader, TextInput } from "metabase/ui";+import type { CollectionItemModel } from "metabase-types/api";++import { CollectionTypeFilter } from "./CollectionTypeFilter";type CollectionItemsToolbarProps = {searchText: string;+ availableModels: string[];+ selectedFilters: CollectionItemModel[] | null;onSearchTextChange: (searchText: string) => void;hasPinnedItems?: boolean;isSearching: boolean;+ onSelectedFiltersChange: (filters: CollectionItemModel[] | null) => void;};export function CollectionItemsToolbar({searchText,+ availableModels,+ selectedFilters,onSearchTextChange,hasPinnedItems,isSearching,+ onSelectedFiltersChange,}: CollectionItemsToolbarProps) {const clearButton =searchText.length > 0 ? (@@ -43,6 +52,11 @@ export function CollectionItemsToolbar({rightSection={rightSection}aria-label={t`Search items in this collection`}/>+ <CollectionTypeFilter+ availableModels={availableModels}+ selectedFilters={selectedFilters}+ onSelectedFiltersChange={onSelectedFiltersChange}+ /></Flex>);}diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsxnew file mode 100644index 00000000000..6e6e604be7a--- /dev/null+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.tsx@@ -0,0 +1,105 @@+import { useDisclosure } from "@mantine/hooks";+import { useId } from "react";+import { t } from "ttag";++import { getTranslatedEntityName } from "metabase/common/utils/model-names";+import {+ Button,+ Checkbox,+ Icon,+ Indicator,+ Popover,+ Stack,+ Text,+} from "metabase/ui";+import type { CollectionItemModel } from "metabase-types/api";++import { TYPE_FILTER_MODELS } from "./constants";++type CollectionTypeFilterProps = {+ availableModels: string[];+ selectedFilters: CollectionItemModel[] | null;+ onSelectedFiltersChange: (filters: CollectionItemModel[] | null) => void;+};++export function CollectionTypeFilter({+ availableModels,+ selectedFilters,+ onSelectedFiltersChange,+}: CollectionTypeFilterProps) {+ const [opened, { close, toggle }] = useDisclosure(false);+ const headingId = useId();+ const options = TYPE_FILTER_MODELS.filter((model) =>+ availableModels.includes(model),+ ).map((model) => ({+ value: model,+ label: getTranslatedEntityName(model) ?? model,+ }));+ const optionValues = options.map(({ value }) => value);+ const checkedFilters = selectedFilters ?? optionValues;+ const isFiltering = selectedFilters != null;++ if (options.length === 0) {+ return null;+ }++ const handleToggle = (filter: CollectionItemModel) => {+ 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);+ };++ return (+ <Popover+ opened={opened}+ onDismiss={close}+ position="bottom-end"+ shadow="md"+ returnFocus+ >+ <Indicator+ disabled={!isFiltering}+ size={7}+ data-testid="type-filter-indicator"+ offset={12}+ >+ <Popover.Target>+ <Button+ variant="default"+ leftSection={<Icon name="filter" aria-hidden />}+ onClick={toggle}+ aria-label={isFiltering ? t`Filter, filters applied` : undefined}+ data-testid="collection-type-filter-button"+ >+ {t`Filter`}+ </Button>+ </Popover.Target>+ </Indicator>+ <Popover.Dropdown+ aria-labelledby={headingId}+ data-testid="collection-type-filter-popover"+ >+ <Stack gap="md" px="1.25rem" py="md" miw="11rem">+ <Text id={headingId} fw="bold">+ {t`Filter by type`}+ </Text>+ <Stack gap="0.75rem">+ {options.map(({ value, label }) => (+ <Checkbox+ key={value}+ value={value}+ label={label}+ checked={checkedFilters.includes(value)}+ onChange={() => handleToggle(value)}+ />+ ))}+ </Stack>+ </Stack>+ </Popover.Dropdown>+ </Popover>+ );+}diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsxnew file mode 100644index 00000000000..f695e27e046--- /dev/null+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionTypeFilter.unit.spec.tsx@@ -0,0 +1,107 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";+import type { CollectionItemModel } from "metabase-types/api";++import { CollectionTypeFilter } from "./CollectionTypeFilter";++type SetupOpts = {+ availableModels?: string[];+ selectedFilters?: CollectionItemModel[] | null;+};++function setup({+ availableModels = ["dashboard", "card"],+ selectedFilters = null,+}: SetupOpts = {}) {+ const onSelectedFiltersChange = jest.fn();+ const view = renderWithProviders(+ <CollectionTypeFilter+ availableModels={availableModels}+ selectedFilters={selectedFilters}+ onSelectedFiltersChange={onSelectedFiltersChange}+ />,+ );++ return { ...view, onSelectedFiltersChange };+}++describe("CollectionTypeFilter", () => {+ it("renders nothing when no supported models are available", () => {+ setup({ availableModels: ["timeline", "snippet"] });++ expect(+ screen.queryByTestId("collection-type-filter-button"),+ ).not.toBeInTheDocument();+ });++ it("shows only available options in display order, checked by default", async () => {+ setup({+ availableModels: [+ "metric",+ "card",+ "collection",+ "dataset",+ "dashboard",+ "exploration",+ ],+ });++ const filterButton = screen.getByTestId("collection-type-filter-button");+ expect(filterButton).toHaveAttribute("aria-expanded", "false");++ await userEvent.click(filterButton);++ expect(filterButton).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByText("Filter by type")).toBeInTheDocument();+ const checkboxes = screen.getAllByRole("checkbox");+ const labels = [+ "Collection",+ "Dashboard",+ "Model",+ "Question",+ "Metric",+ "Research",+ ];+ expect(checkboxes).toHaveLength(6);+ expect(checkboxes).toEqual(+ labels.map((label) => screen.getByLabelText(label)),+ );+ for (const label of labels) {+ expect(screen.getByLabelText(label)).toBeChecked();+ }+ });++ it("returns the remaining models when an option is unchecked", async () => {+ const { onSelectedFiltersChange } = setup();++ await userEvent.click(screen.getByTestId("collection-type-filter-button"));+ await userEvent.click(screen.getByLabelText("Dashboard"));++ expect(onSelectedFiltersChange).toHaveBeenCalledWith(["card"]);+ });++ it("clears the filter when all available options are checked", async () => {+ const { onSelectedFiltersChange } = setup({+ selectedFilters: ["dashboard"],+ });++ await userEvent.click(screen.getByTestId("collection-type-filter-button"));+ await userEvent.click(screen.getByLabelText("Question"));++ expect(onSelectedFiltersChange).toHaveBeenCalledWith(null);+ });++ it("announces the active state only while filtering", () => {+ const { unmount } = setup();++ expect(screen.getByRole("button", { name: "Filter" })).toBeInTheDocument();++ unmount();+ setup({ selectedFilters: ["dashboard"] });++ expect(+ screen.getByRole("button", { name: "Filter, filters applied" }),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/collections/components/CollectionContent/constants.ts b/frontend/src/metabase/collections/components/CollectionContent/constants.tsindex 23b8d8f961c..fe7ddf5f784 100644--- a/frontend/src/metabase/collections/components/CollectionContent/constants.ts+++ b/frontend/src/metabase/collections/components/CollectionContent/constants.ts@@ -19,3 +19,14 @@ export const ALL_MODELS: CollectionItemModel[] = ["table","exploration",];++export const TYPE_FILTER_MODELS = [+ "collection",+ "dashboard",+ "dataset",+ "card",+ "metric",+ "document",+ "exploration",+ "table",+] as const satisfies readonly CollectionItemModel[];diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.tsindex aaef11e548f..662f6aa1913 100644--- a/frontend/test/__support__/server-mocks/collection.ts+++ b/frontend/test/__support__/server-mocks/collection.ts@@ -167,12 +167,12 @@ function handleCollectionItemsResponse({const url = new URL(call.url);const models = modelsParam ?? url.searchParams.getAll("models");- // When the models filter is an empty array, return all items.- // In the API, omitting the `models` param returns all collection items.- const matchedItems =- models.length === 0- ? collectionItems- : collectionItems.filter(({ model }) => models.includes(model));+ // As in the API, requesting no models at all returns every item.+ const matchedItems: CollectionItem[] = models.includes("no_models")+ ? []+ : collectionItems.filter(+ ({ model }) => models.length === 0 || models.includes(model),+ );const q = url.searchParams.get("q")?.toLowerCase().trim();const searchedItems = q@@ -182,13 +182,24 @@ function handleCollectionItemsResponse({const limit = Number(url.searchParams.get("limit")) || searchedItems.length;const offset = Number(url.searchParams.get("offset")) || 0;- return {+ const response = {data: searchedItems.slice(offset, offset + limit),total: searchedItems.length,models,limit,offset,};++ if (url.searchParams.get("include_available_models") !== "true") {+ return response;+ }++ return {+ ...response,+ available_models: Array.from(+ new Set(collectionItems.map((item) => item.model)),+ ),+ };}export function setupCollectionItemsEndpoint({