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
Implement in-collection text search (#79333)
Anderson28160265ecc0
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.jsindex bca98c2de5c..5e69b379232 100644--- a/e2e/test/scenarios/collections/collections.cy.spec.js+++ b/e2e/test/scenarios/collections/collections.cy.spec.js@@ -1133,6 +1133,102 @@ describe("scenarios > collection items listing", () => {const PAGE_SIZE = 25;+ describe("search", () => {+ function interceptSearch(query, alias) {+ cy.intercept({+ method: "GET",+ pathname: "/api/collection/root/items",+ query: {+ pinned_state: "is_not_pinned",+ q: query,+ },+ }).as(alias);+ }++ beforeEach(() => {+ archiveAll();++ H.createCollection({+ name: "Quarterly revenue",+ });++ cy.signIn("normal");+ H.createQuestion({+ name: "Customer health",+ collection_position: null,+ query: TEST_QUESTION_QUERY,+ });+ cy.signInAsAdmin();+ });++ it("should search by item name and last editor name, clear results, and show an empty state", () => {+ visitRootCollection();++ interceptSearch("revenue", "searchByName");+ cy.findByLabelText("Search items in this collection")+ .should("have.value", "")+ .type("revenue")+ .should("have.value", "revenue");+ cy.wait("@searchByName").then(({ request }) => {+ const searchParams = new URL(request.url).searchParams;++ expect(searchParams.get("q")).to.equal("revenue");+ expect(searchParams.get("offset")).to.equal("0");+ });++ cy.findByTestId("collection-table")+ .should("contain", "Quarterly revenue")+ .and("not.contain", "Customer health");++ cy.findByLabelText("Clear search").click();+ cy.findByLabelText("Search items in this collection").should(+ "have.value",+ "",+ );+ cy.findByTestId("collection-table")+ .should("contain", "Quarterly revenue")+ .and("contain", "Customer health");++ interceptSearch("Robert", "searchByEditor");+ cy.findByLabelText("Search items in this collection")+ .type("Robert")+ .should("have.value", "Robert");+ cy.wait("@searchByEditor").then(({ request }) => {+ const searchParams = new URL(request.url).searchParams;++ expect(searchParams.get("q")).to.equal("Robert");+ expect(searchParams.get("offset")).to.equal("0");+ });++ cy.findByTestId("collection-table")+ .should("contain", "Customer health")+ .and("not.contain", "Quarterly revenue");++ cy.findByLabelText("Clear search").click();+ cy.findByLabelText("Search items in this collection").should(+ "have.value",+ "",+ );++ interceptSearch("nothing matches this", "searchWithoutResults");+ cy.findByLabelText("Search items in this collection")+ .type("nothing matches this")+ .should("have.value", "nothing matches this");+ cy.wait("@searchWithoutResults").then(({ request }) => {+ expect(new URL(request.url).searchParams.get("q")).to.equal(+ "nothing matches this",+ );+ });++ cy.findByTestId("collection-filter-empty-state").within(() => {+ cy.findByText("Didn't find anything").should("be.visible");+ cy.findByText("There weren't any results for your search.").should(+ "be.visible",+ );+ });+ });+ });+describe("pagination", () => {const SUBCOLLECTIONS = 1;const ADDED_QUESTIONS = 15;diff --git a/e2e/test/scenarios/collections/trash.cy.spec.js b/e2e/test/scenarios/collections/trash.cy.spec.jsindex 18b124bc1e6..9f062ea8348 100644--- a/e2e/test/scenarios/collections/trash.cy.spec.js+++ b/e2e/test/scenarios/collections/trash.cy.spec.js@@ -404,12 +404,7 @@ describe("scenarios > collections > trash", () => {archiveBanner().should("not.exist");cy.visit("/trash");-- collectionTable().within(() => {- cy.findByText("Collection A").should("not.exist");- cy.findByText("Dashboard A").should("not.exist");- cy.findByText("Question A").should("not.exist");- });+ cy.findByTestId("collection-empty-state").should("be.visible");cy.visit(`/collection/${FIRST_COLLECTION_ID}`);@@ -494,9 +489,7 @@ describe("scenarios > collections > trash", () => {archiveBanner().findByText("Delete permanently").click();H.modal().findByText("Delete Question B permanently?").should("exist");H.modal().findByText("Delete permanently").click();- collectionTable().within(() => {- cy.findByText("Question B").should("not.exist");- });+ cy.findByTestId("collection-empty-state").should("be.visible");});describe("bulk actions", () => {diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.tsindex 6f49b419bf0..b50634c481f 100644--- a/frontend/src/metabase-types/api/collection.ts+++ b/frontend/src/metabase-types/api/collection.ts@@ -171,6 +171,7 @@ export type ListCollectionItemsSortColumn =export type ListCollectionItemsRequest = {id: CollectionId;models?: CollectionItemModel[];+ q?: string;archived?: boolean;pinned_state?: "all" | "is_pinned" | "is_not_pinned";namespace?: CollectionNamespace;diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.tsindex 7ad451281f3..e54c4384579 100644--- a/frontend/src/metabase/api/dashboard.ts+++ b/frontend/src/metabase/api/dashboard.ts@@ -169,7 +169,7 @@ export const dashboardApi = Api.injectEndpoints({}),listDashboardItems: builder.query<ListCollectionItemsResponse,- Omit<ListCollectionItemsRequest, "id"> & { id: DashboardId }+ Omit<ListCollectionItemsRequest, "id" | "q"> & { id: DashboardId }>({query: ({ id, ...body }) => ({method: "GET",diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsxindex 63b15a5b3a9..2ca1c124e95 100644--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx@@ -322,6 +322,7 @@ export const CollectionContentView = ({deleteBookmark={deleteBookmark}loadingPinnedItems={loading}hasPinnedItems={hasPinnedItems}+ showFilterBarselected={selected}toggleItem={toggleItem}clear={clear}diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsxindex a202dcc71aa..00329e31c6f 100644--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx@@ -6,7 +6,9 @@ import {useMemo,useState,} from "react";+import { t } from "ttag";+import NoResultsImg from "assets/img/no_results.svg";import { skipToken, useListCollectionItemsQuery } from "metabase/api";import {ALL_MODELS,@@ -20,12 +22,16 @@ import type {DeleteBookmark,} from "metabase/common/collections/types";import { isRootTrashCollection } from "metabase/common/collections/utils";+import { EmptyState } from "metabase/common/components/EmptyState";import { ItemsTable } from "metabase/common/components/ItemsTable";import { getVisibleColumnsMap } from "metabase/common/components/ItemsTable/utils";import { PaginationControls } from "metabase/common/components/PaginationControls";+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";import { usePagination } from "metabase/common/hooks/use-pagination";import CS from "metabase/css/core/index.css";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";+import { Box } from "metabase/ui";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";import type Database from "metabase-lib/v1/metadata/Database";import type {Bookmark,@@ -42,6 +48,12 @@ import {CollectionEmptyContent,CollectionTable,} from "./CollectionContent.styled";+import { CollectionItemsToolbar } from "./CollectionItemsToolbar";++const shouldDebounceSearchText = (+ _lastSearchText: string,+ nextSearchText: string,+) => nextSearchText.trim().length > 0;const getDefaultSortingOptions = (collection: Collection | undefined,@@ -79,6 +91,7 @@ export type CollectionItemsTableProps = {showDashboardQuestions: boolean;selected: CollectionItem[];selectOnlyTheseItems: (items: CollectionItem[]) => void;+ showFilterBar: boolean;toggleItem: (item: CollectionItem) => void;visibleColumns?: CollectionContentTableColumn[];onClick: (item: CollectionItem) => void;@@ -96,6 +109,16 @@ const DefaultEmptyContentComponent = ({);};+const CollectionNoResults = () => (+ <Box my="4rem" data-testid="collection-filter-empty-state">+ <EmptyState+ title={t`Didn't find anything`}+ message={t`There weren't any results for your search.`}+ illustrationElement={<img src={NoResultsImg} alt={t`No results`} />}+ />+ </Box>+);+export const CollectionItemsTable = ({bookmarks,collection,@@ -112,6 +135,7 @@ export const CollectionItemsTable = ({loadingPinnedItems,models = ALL_MODELS,pageSize = COLLECTION_PAGE_SIZE,+ showFilterBar,showDashboardQuestions = true,selected,selectOnlyTheseItems,@@ -119,6 +143,16 @@ export const CollectionItemsTable = ({visibleColumns = DEFAULT_VISIBLE_COLUMNS_LIST,onClick,}: CollectionItemsTableProps) => {+ const [search, setSearch] = useState({ collectionId, value: "" });+ const searchText = search.collectionId === collectionId ? search.value : "";+ const debouncedSearchText = useDebouncedValue(+ searchText,+ SEARCH_DEBOUNCE_DURATION,+ shouldDebounceSearchText,+ );+ const trimmedSearchText =+ searchText.trim().length > 0 ? debouncedSearchText.trim() : "";+const [unpinnedItemsSorting, setUnpinnedItemsSorting] = useState<SortingOptions<ListCollectionItemsSortColumn>>(() => getDefaultSortingOptions(collection));@@ -127,11 +161,18 @@ export const CollectionItemsTable = ({usePagination();useEffect(() => {- if (collectionId) {- resetPage();- }+ resetPage();+ setSearch({ collectionId, value: "" });}, [collectionId, resetPage]);+ const handleSearchTextChange = useCallback(+ (value: string) => {+ setSearch({ collectionId, value });+ setPage(0);+ },+ [collectionId, setPage],+ );+const handleUnpinnedItemsSortingChange = useCallback((sortingOpts: SortingOptions<ListCollectionItemsSortColumn>) => {setUnpinnedItemsSorting(sortingOpts);@@ -159,8 +200,10 @@ export const CollectionItemsTable = ({loadingPinnedItems={loadingPinnedItems}page={page}pageSize={pageSize}+ searchText={searchText}selected={selected}selectOnlyTheseItems={selectOnlyTheseItems}+ showFilterBar={showFilterBar}toggleItem={toggleItem}unpinnedItemsSorting={unpinnedItemsSorting}unpinnedQuery={@@ -175,12 +218,14 @@ export const CollectionItemsTable = ({? { show_dashboard_questions: showDashboardQuestions }: { pinned_state: "is_not_pinned" }),...unpinnedItemsSorting,+ ...(trimmedSearchText.length > 0 ? { q: trimmedSearchText } : {}),}}visibleColumns={visibleColumns}onClick={onClick}onNextPage={handleNextPage}onPreviousPage={handlePreviousPage}+ onSearchTextChange={handleSearchTextChange}onUnpinnedItemsSortingChange={handleUnpinnedItemsSortingChange}/>);@@ -188,10 +233,12 @@ export const CollectionItemsTable = ({type CollectionItemsTableContentProps = CollectionItemsTableProps & {page: number;+ searchText: string;unpinnedItemsSorting: SortingOptions<ListCollectionItemsSortColumn>;unpinnedQuery: ListCollectionItemsRequest | typeof skipToken;onNextPage: () => void;onPreviousPage: () => void;+ onSearchTextChange: (searchText: string) => void;onUnpinnedItemsSortingChange: (unpinnedItemsSorting: SortingOptions<ListCollectionItemsSortColumn>,) => void;@@ -213,8 +260,10 @@ const CollectionItemsTableContent = ({loadingPinnedItems,page,pageSize = COLLECTION_PAGE_SIZE,+ searchText,selected,selectOnlyTheseItems,+ showFilterBar,toggleItem,unpinnedItemsSorting,unpinnedQuery,@@ -222,9 +271,10 @@ const CollectionItemsTableContent = ({onClick,onNextPage,onPreviousPage,+ onSearchTextChange,onUnpinnedItemsSortingChange,}: CollectionItemsTableContentProps) => {- const { data, isLoading: loadingUnpinnedItems } =+ const { data, isFetching: fetchingUnpinnedItems } =useListCollectionItemsQuery(unpinnedQuery);const unpinnedItems = data?.data ?? [];@@ -245,56 +295,81 @@ const CollectionItemsTableContent = ({selectOnlyTheseItems?.(unpinnedItems);};- const loading = loadingPinnedItems || loadingUnpinnedItems;- const isEmpty = !loading && !hasPinnedItems && unpinnedItems.length === 0;+ const loading = loadingPinnedItems || fetchingUnpinnedItems;+ const hasSearchQuery =+ unpinnedQuery !== skipToken && Boolean(unpinnedQuery.q?.trim());+ const hasActiveFilters = searchText.trim().length > 0 || hasSearchQuery;+ const isSearching = fetchingUnpinnedItems && hasSearchQuery;+ const isEmpty =+ !loading &&+ !hasPinnedItems &&+ unpinnedItems.length === 0 &&+ !hasActiveFilters;- if (isEmpty && !loadingUnpinnedItems) {+ if (isEmpty) {return <EmptyContentComponent collection={collection} />;}+ const showNoResults =+ !fetchingUnpinnedItems && hasActiveFilters && unpinnedItems.length === 0;+ const showTable = !showNoResults;+return (- <CollectionTable data-testid="collection-table">- <ItemsTable- databases={databases}- bookmarks={bookmarks}- createBookmark={createBookmark}- deleteBookmark={deleteBookmark}- items={unpinnedItems}- collection={collection}- sortingOptions={unpinnedItemsSorting}- onSortingOptionsChange={onUnpinnedItemsSortingChange}- selectedItems={selected}- hasUnselected={hasUnselected}- getIsSelected={getIsSelected}- onToggleSelected={toggleItem}- onDrop={clear}- onMove={handleMove}- onCopy={handleCopy}- onSelectAll={handleSelectAll}- onSelectNone={clear}- onClick={onClick}- visibleColumnsMap={visibleColumnsMap}- />- <div- className={cx(- CS.flex,- CS.justifyEnd,- CS.my3,- CS.syncStatusAwarePagination,- )}- >- {hasPagination && (- <PaginationControls- showTotal- page={page}- pageSize={pageSize}- total={total}- itemsLength={unpinnedItems.length}- onNextPage={onNextPage}- onPreviousPage={onPreviousPage}+ <>+ {showFilterBar && (+ <CollectionItemsToolbar+ searchText={searchText}+ onSearchTextChange={onSearchTextChange}+ hasPinnedItems={hasPinnedItems}+ isSearching={isSearching}+ />+ )}+ {showNoResults && <CollectionNoResults />}+ {showTable && (+ <CollectionTable data-testid="collection-table">+ <ItemsTable+ databases={databases}+ bookmarks={bookmarks}+ createBookmark={createBookmark}+ deleteBookmark={deleteBookmark}+ items={unpinnedItems}+ collection={collection}+ sortingOptions={unpinnedItemsSorting}+ onSortingOptionsChange={onUnpinnedItemsSortingChange}+ selectedItems={selected}+ hasUnselected={hasUnselected}+ getIsSelected={getIsSelected}+ onToggleSelected={toggleItem}+ onDrop={clear}+ onMove={handleMove}+ onCopy={handleCopy}+ onSelectAll={handleSelectAll}+ onSelectNone={clear}+ onClick={onClick}+ visibleColumnsMap={visibleColumnsMap}/>- )}- </div>- </CollectionTable>+ <div+ className={cx(+ CS.flex,+ CS.justifyEnd,+ CS.my3,+ CS.syncStatusAwarePagination,+ )}+ >+ {hasPagination && (+ <PaginationControls+ showTotal+ page={page}+ pageSize={pageSize}+ total={total}+ itemsLength={unpinnedItems.length}+ onNextPage={onNextPage}+ onPreviousPage={onPreviousPage}+ />+ )}+ </div>+ </CollectionTable>+ )}+ </>);};diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsxnew file mode 100644index 00000000000..13105140eee--- /dev/null+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx@@ -0,0 +1,532 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import { useState } from "react";++import { setupCollectionItemsEndpoint } from "__support__/server-mocks";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Api } from "metabase/api";+import { Route } from "metabase/router";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";+import type {+ Collection,+ CollectionId,+ CollectionItem,+} from "metabase-types/api";+import {+ createMockCollection,+ createMockCollectionItem,+} from "metabase-types/api/mocks";++import { CollectionItemsTable } from "./CollectionItemsTable";++const collection = createMockCollection({ id: 1, can_write: false });+const collectionItems = [+ createMockCollectionItem({+ id: 1,+ collection_id: collection.id,+ model: "dashboard",+ name: "Revenue overview",+ }),+ createMockCollectionItem({+ id: 2,+ collection_id: collection.id,+ model: "card",+ name: "Customer 360",+ }),+ createMockCollectionItem({+ id: 3,+ collection_id: collection.id,+ model: "dataset",+ name: "Orders model",+ }),+];++type SetupOpts = {+ collection?: Collection;+ collectionItems?: CollectionItem[];+ pageSize?: number;+ showFilterBar?: boolean;+};++function getTable({+ collection: currentCollection = collection,+ pageSize,+ showFilterBar = true,+}: Omit<SetupOpts, "collectionItems"> = {}) {+ return (+ <Route+ path="/"+ element={+ <CollectionItemsTable+ collection={currentCollection}+ collectionId={currentCollection.id}+ pageSize={pageSize}+ showFilterBar={showFilterBar}+ />+ }+ />+ );+}++function setup({+ collection: currentCollection = collection,+ collectionItems: items = collectionItems,+ pageSize,+ showFilterBar = true,+}: SetupOpts = {}) {+ setupCollectionItemsEndpoint({+ collection: currentCollection,+ collectionItems: items,+ });++ return renderWithProviders(+ getTable({ collection: currentCollection, pageSize, showFilterBar }),+ {+ withRouter: true,+ withDND: true,+ },+ );+}++function getItemsCalls(collectionId: CollectionId = collection.id) {+ return fetchMock.callHistory.calls(+ `path:/api/collection/${collectionId}/items`,+ );+}++function getSearchCalls(collectionId: CollectionId = collection.id) {+ return getItemsCalls(collectionId).filter((call) =>+ new URL(call.url).searchParams.has("q"),+ );+}++function setupUserWithFakeTimers() {+ jest.useFakeTimers();+ return userEvent.setup({ advanceTimers: jest.advanceTimersByTime });+}++function advanceSearchDebounce(duration = SEARCH_DEBOUNCE_DURATION) {+ act(() => {+ jest.advanceTimersByTime(duration);+ });+}++function CollectionNavigationTest({+ nextCollection,+}: {+ nextCollection: Collection;+}) {+ const [currentCollection, setCurrentCollection] = useState(collection);++ return (+ <>+ <button onClick={() => setCurrentCollection(nextCollection)}>+ Open next collection+ </button>+ <CollectionItemsTable+ collection={currentCollection}+ collectionId={currentCollection.id}+ showFilterBar+ />+ </>+ );+}++describe("CollectionItemsTable", () => {+ afterEach(() => {+ jest.useRealTimers();+ });++ it("renders the search toolbar when enabled", async () => {+ setup();++ expect(+ await screen.findByPlaceholderText("Search by name or editor..."),+ ).toBeInTheDocument();+ expect(screen.getByTestId("collection-items-toolbar")).toBeInTheDocument();+ });++ it("does not render the search toolbar when it is not enabled", async () => {+ setup({ showFilterBar: false });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(+ screen.queryByPlaceholderText("Search by name or editor..."),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("collection-items-toolbar"),+ ).not.toBeInTheDocument();+ });++ it("keeps the table mounted without showing a loader during a refetch with no search", async () => {+ const { store } = setup();++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ let resolveRequest: (() => void) | undefined;+ const requestGate = new Promise<void>((resolve) => {+ resolveRequest = resolve;+ });+ fetchMock.modifyRoute(`collection-${collection.id}-items`, {+ response: async () => {+ await requestGate;+ return {+ data: collectionItems,+ total: collectionItems.length,+ models: [],+ limit: 25,+ offset: 0,+ };+ },+ });++ act(() => {+ store.dispatch(+ Api.util.invalidateTags([+ { type: "collection", id: `${collection.id}-items` },+ ]),+ );+ });+ await waitFor(() => {+ expect(getItemsCalls()).toHaveLength(2);+ });++ const tableWasMounted = screen.queryByTestId("collection-table") != null;+ const cachedItemWasVisible = screen.queryByText("Revenue overview") != null;+ const loadingWasVisible =+ within(screen.getByTestId("collection-items-toolbar")).queryByTestId(+ "loading-indicator",+ ) != null;+ await act(async () => {+ resolveRequest?.();+ await fetchMock.callHistory.flush();+ });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(tableWasMounted).toBe(true);+ expect(cachedItemWasVisible).toBe(true);+ expect(loadingWasVisible).toBe(false);+ });++ it("does not show the empty state while refetching an empty collection", async () => {+ const { store } = setup({ collectionItems: [], showFilterBar: false });++ expect(+ await screen.findByTestId("collection-empty-state"),+ ).toBeInTheDocument();+ let resolveRequest: (() => void) | undefined;+ const requestGate = new Promise<void>((resolve) => {+ resolveRequest = resolve;+ });+ fetchMock.modifyRoute(`collection-${collection.id}-items`, {+ response: async () => {+ await requestGate;+ return {+ data: [],+ total: 0,+ models: [],+ limit: 25,+ offset: 0,+ };+ },+ });++ act(() => {+ store.dispatch(+ Api.util.invalidateTags([+ { type: "collection", id: `${collection.id}-items` },+ ]),+ );+ });+ await waitFor(() => {+ expect(getItemsCalls()).toHaveLength(2);+ });++ const tableWasMounted = screen.queryByTestId("collection-table") != null;+ const emptyStateWasVisible =+ screen.queryByTestId("collection-empty-state") != null;+ await act(async () => {+ resolveRequest?.();+ await fetchMock.callHistory.flush();+ });++ expect(+ await screen.findByTestId("collection-empty-state"),+ ).toBeInTheDocument();+ expect(tableWasMounted).toBe(true);+ expect(emptyStateWasVisible).toBe(false);+ });++ it("sends search text and shows only matching items", async () => {+ const user = setupUserWithFakeTimers();+ setup();++ await user.type(+ await screen.findByPlaceholderText("Search by name or editor..."),+ "revenue",+ );++ expect(getSearchCalls()).toHaveLength(0);+ advanceSearchDebounce();+ await waitFor(() => {+ expect(getSearchCalls()).toHaveLength(1);+ });+ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(screen.queryByText("Customer 360")).not.toBeInTheDocument();+ expect(screen.queryByText("Orders model")).not.toBeInTheDocument();+ expect(new URL(getSearchCalls()[0].url).searchParams.get("q")).toBe(+ "revenue",+ );+ });++ it("debounces search requests", async () => {+ const user = setupUserWithFakeTimers();+ setup();++ await user.type(+ await screen.findByPlaceholderText("Search by name or editor..."),+ "rev",+ );++ expect(getSearchCalls()).toHaveLength(0);+ advanceSearchDebounce(SEARCH_DEBOUNCE_DURATION - 1);+ expect(getSearchCalls()).toHaveLength(0);++ advanceSearchDebounce(1);+ await waitFor(() => {+ expect(getSearchCalls()).toHaveLength(1);+ });+ expect(new URL(getSearchCalls()[0].url).searchParams.get("q")).toBe("rev");+ });++ it("clears the search and restores the unfiltered list", async () => {+ const user = setupUserWithFakeTimers();+ setup();+ const searchInput = await screen.findByPlaceholderText(+ "Search by name or editor...",+ );++ expect(+ screen.queryByRole("button", { name: "Clear search" }),+ ).not.toBeInTheDocument();+ await user.type(searchInput, "customer");+ advanceSearchDebounce();+ expect(+ await screen.findByRole("button", { name: "Clear search" }),+ ).toBeInTheDocument();+ expect(await screen.findByText("Customer 360")).toBeInTheDocument();+ expect(screen.queryByText("Revenue overview")).not.toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Clear search" }));++ expect(searchInput).toHaveValue("");+ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ expect(screen.getByText("Customer 360")).toBeInTheDocument();+ expect(screen.getByText("Orders model")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Clear search" }),+ ).not.toBeInTheDocument();+ });++ it("resets pagination when searching", async () => {+ const user = setupUserWithFakeTimers();+ setup({ pageSize: 1 });++ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Next page" }));+ expect(await screen.findByText("Customer 360")).toBeInTheDocument();++ await user.type(+ screen.getByPlaceholderText("Search by name or editor..."),+ "orders",+ );++ advanceSearchDebounce();+ await waitFor(() => {+ expect(getSearchCalls()).toHaveLength(1);+ });+ const searchParams = new URL(getSearchCalls()[0].url).searchParams;+ expect(searchParams.get("q")).toBe("orders");+ expect(searchParams.get("offset")).toBe("0");+ expect(await screen.findByText("Orders model")).toBeInTheDocument();+ });++ it("shows a loader in the search input while keeping the table mounted during a search request", async () => {+ const user = setupUserWithFakeTimers();+ setup();+ const searchInput = await screen.findByPlaceholderText(+ "Search by name or editor...",+ );+ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ let resolveRequest: (() => void) | undefined;+ const requestGate = new Promise<void>((resolve) => {+ resolveRequest = resolve;+ });+ fetchMock.modifyRoute(`collection-${collection.id}-items`, {+ response: async () => {+ await requestGate;+ return {+ data: [collectionItems[1]],+ total: 1,+ models: [],+ limit: 25,+ offset: 0,+ };+ },+ });++ await user.type(searchInput, "customer");+ advanceSearchDebounce();+ await waitFor(() => {+ expect(getSearchCalls()).toHaveLength(1);+ });++ const toolbar = screen.getByTestId("collection-items-toolbar");+ const loaderWasVisible =+ within(toolbar).queryByTestId("loading-indicator") != null;+ const clearButtonWasVisible =+ within(toolbar).queryByRole("button", { name: "Clear search" }) != null;+ const tableWasMounted = screen.queryByTestId("collection-table") != null;+ const cachedItemWasVisible = screen.queryByText("Revenue overview") != null;++ await act(async () => {+ resolveRequest?.();+ await fetchMock.callHistory.flush();+ });++ expect(loaderWasVisible).toBe(true);+ expect(clearButtonWasVisible).toBe(false);+ expect(tableWasMounted).toBe(true);+ expect(cachedItemWasVisible).toBe(true);+ expect(searchInput).toHaveValue("customer");+ expect(await screen.findByText("Customer 360")).toBeInTheDocument();+ expect(+ within(toolbar).queryByTestId("loading-indicator"),+ ).not.toBeInTheDocument();+ expect(+ within(toolbar).getByRole("button", { name: "Clear search" }),+ ).toBeInTheDocument();+ });++ it("does not show the filtered empty state while a search request is in flight", async () => {+ const user = setupUserWithFakeTimers();+ setup();++ await user.type(+ await screen.findByPlaceholderText("Search by name or editor..."),+ "not found",+ );+ advanceSearchDebounce();++ expect(+ within(screen.getByTestId("collection-items-toolbar")).getByTestId(+ "loading-indicator",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("collection-filter-empty-state"),+ ).not.toBeInTheDocument();++ expect(await screen.findByText("Didn't find anything")).toBeInTheDocument();+ });++ it("shows a filtered empty state when search has no matches", async () => {+ const user = setupUserWithFakeTimers();+ setup();++ await user.type(+ await screen.findByPlaceholderText("Search by name or editor..."),+ "not found",+ );+ advanceSearchDebounce();++ expect(await screen.findByText("Didn't find anything")).toBeInTheDocument();+ expect(+ screen.getByTestId("collection-filter-empty-state"),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("collection-table")).not.toBeInTheDocument();+ });++ it("does not show the collection empty state while clearing a search", async () => {+ const user = setupUserWithFakeTimers();+ setup();++ 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.getByRole("button", { name: "Clear search" }));++ expect(screen.getByTestId("collection-items-toolbar")).toBeInTheDocument();+ expect(+ screen.queryByTestId("collection-empty-state"),+ ).not.toBeInTheDocument();+ expect(await screen.findByText("Revenue overview")).toBeInTheDocument();+ });++ it("does not send the previous search to a new collection", async () => {+ const nextCollection = createMockCollection({ id: 2, can_write: false });+ const nextCollectionItems = [+ createMockCollectionItem({+ id: 4,+ collection_id: nextCollection.id,+ model: "dashboard",+ name: "Inventory overview",+ }),+ ];+ setupCollectionItemsEndpoint({ collection, collectionItems });+ const user = setupUserWithFakeTimers();+ renderWithProviders(+ <CollectionNavigationTest nextCollection={nextCollection} />,+ { withRouter: true, withDND: true },+ );++ await user.type(+ await screen.findByPlaceholderText("Search by name or editor..."),+ "revenue",+ );+ advanceSearchDebounce();+ await waitFor(() => {+ expect(getSearchCalls()).toHaveLength(1);+ });++ setupCollectionItemsEndpoint({+ collection: nextCollection,+ collectionItems: nextCollectionItems,+ });+ await user.click(+ screen.getByRole("button", { name: "Open next collection" }),+ );++ 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);++ advanceSearchDebounce();+ expect(getSearchCalls(nextCollection.id)).toHaveLength(0);+ });++ it("shows the existing empty state without a toolbar for a truly empty collection", async () => {+ setup({ collectionItems: [] });++ expect(+ await screen.findByTestId("collection-empty-state"),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("collection-items-toolbar"),+ ).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsxnew file mode 100644index 00000000000..97586625b1a--- /dev/null+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsToolbar.tsx@@ -0,0 +1,48 @@+import { t } from "ttag";++import { Flex, Icon, Input, Loader, TextInput } from "metabase/ui";++type CollectionItemsToolbarProps = {+ searchText: string;+ onSearchTextChange: (searchText: string) => void;+ hasPinnedItems?: boolean;+ isSearching: boolean;+};++export function CollectionItemsToolbar({+ searchText,+ onSearchTextChange,+ hasPinnedItems,+ isSearching,+}: CollectionItemsToolbarProps) {+ const clearButton =+ searchText.length > 0 ? (+ <Input.ClearButton+ aria-label={t`Clear search`}+ onClick={() => onSearchTextChange("")}+ c="text-secondary"+ />+ ) : undefined;+ const rightSection = isSearching ? <Loader size="xs" /> : clearButton;++ return (+ <Flex+ mb="md"+ gap="0.75rem"+ mt={hasPinnedItems ? "xl" : 0}+ data-testid="collection-items-toolbar"+ >+ <TextInput+ flex="1"+ bdrs="md"+ value={searchText}+ onChange={(event) => onSearchTextChange(event.target.value)}+ placeholder={t`Search by name or editor...`}+ leftSection={<Icon name="search" aria-hidden />}+ rightSectionPointerEvents={isSearching ? "none" : "all"}+ rightSection={rightSection}+ aria-label={t`Search items in this collection`}+ />+ </Flex>+ );+}diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.tsindex b2f2423f4cd..aaef11e548f 100644--- a/frontend/test/__support__/server-mocks/collection.ts+++ b/frontend/test/__support__/server-mocks/collection.ts@@ -174,12 +174,17 @@ function handleCollectionItemsResponse({? collectionItems: collectionItems.filter(({ model }) => models.includes(model));- const limit = Number(url.searchParams.get("limit")) || matchedItems.length;+ const q = url.searchParams.get("q")?.toLowerCase().trim();+ const searchedItems = q+ ? matchedItems.filter(({ name }) => name.toLowerCase().includes(q))+ : matchedItems;++ const limit = Number(url.searchParams.get("limit")) || searchedItems.length;const offset = Number(url.searchParams.get("offset")) || 0;return {- data: matchedItems.slice(offset, offset + limit),- total: matchedItems.length,+ data: searchedItems.slice(offset, offset + limit),+ total: searchedItems.length,models,limit,offset,