From d7044784f0398298ceeb98fdddf44a0a8e062308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20N=C3=A4sman?= Date: Wed, 1 Jun 2022 14:55:10 +0200 Subject: [PATCH] Move SearchFilter from @backstage/plugin-search to @backstage/plugin-search-react and deprecate it in @backstage/plugin-search, and also remove SearchFilterNext MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Anders Näsman --- plugins/search-react/api-report.md | 82 ++++ plugins/search-react/package.json | 6 +- .../SearchFilter.Autocomplete.test.tsx | 361 +++++++++++++++ .../SearchFilter.Autocomplete.tsx | 120 +++++ .../SearchFilter/SearchFilter.stories.tsx | 13 +- .../SearchFilter/SearchFilter.test.tsx | 410 ++++++++++++++++++ .../components/SearchFilter/SearchFilter.tsx | 237 ++++++++++ .../components/SearchFilter/hooks.test.tsx | 8 +- .../src/components/SearchFilter/hooks.ts | 9 +- .../src/components/SearchFilter/index.ts | 24 + plugins/search-react/src/components/index.ts | 1 + plugins/search/api-report.md | 28 +- .../SearchFilter.Autocomplete.tsx | 15 +- .../components/SearchFilter/SearchFilter.tsx | 179 +------- .../src/components/SearchFilter/index.ts | 2 +- plugins/search/src/index.ts | 2 +- 16 files changed, 1296 insertions(+), 201 deletions(-) create mode 100644 plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.test.tsx create mode 100644 plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.tsx rename plugins/{search => search-react}/src/components/SearchFilter/SearchFilter.stories.tsx (95%) create mode 100644 plugins/search-react/src/components/SearchFilter/SearchFilter.test.tsx create mode 100644 plugins/search-react/src/components/SearchFilter/SearchFilter.tsx rename plugins/{search => search-react}/src/components/SearchFilter/hooks.test.tsx (98%) rename plugins/{search => search-react}/src/components/SearchFilter/hooks.ts (96%) create mode 100644 plugins/search-react/src/components/SearchFilter/index.ts diff --git a/plugins/search-react/api-report.md b/plugins/search-react/api-report.md index 9f61070854..00325d6f64 100644 --- a/plugins/search-react/api-report.md +++ b/plugins/search-react/api-report.md @@ -10,9 +10,18 @@ import { AsyncState } from 'react-use/lib/useAsync'; import { JsonObject } from '@backstage/types'; import { PropsWithChildren } from 'react'; import { default as React_2 } from 'react'; +import { ReactElement } from 'react'; import { SearchQuery } from '@backstage/plugin-search-common'; import { SearchResultSet } from '@backstage/plugin-search-common'; +// @public (undocumented) +export const AutocompleteFilter: ( + props: SearchAutocompleteFilterProps, +) => JSX.Element; + +// @public (undocumented) +export const CheckboxFilter: (props: SearchFilterComponentProps) => JSX.Element; + // @public (undocumented) export const HighlightedSearchResultText: ({ text, @@ -45,6 +54,13 @@ export interface SearchApi { // @public (undocumented) export const searchApiRef: ApiRef; +// @public (undocumented) +export type SearchAutocompleteFilterProps = SearchFilterComponentProps & { + filterSelectedOptions?: boolean; + limitTags?: number; + multiple?: boolean; +}; + // @public export const SearchContextProvider: ( props: SearchContextProviderProps, @@ -74,6 +90,72 @@ export type SearchContextValue = { fetchPreviousPage?: React_2.DispatchWithoutAction; } & SearchContextState; +// @public (undocumented) +export const SearchFilter: { + ({ component: Element, ...props }: SearchFilterWrapperProps): JSX.Element; + Checkbox( + props: Omit & + SearchFilterComponentProps, + ): JSX.Element; + Select( + props: Omit & + SearchFilterComponentProps, + ): JSX.Element; + Autocomplete(props: SearchAutocompleteFilterProps): JSX.Element; +}; + +// @public (undocumented) +export type SearchFilterComponentProps = { + className?: string; + name: string; + label?: string; + values?: string[] | ((partial: string) => Promise); + defaultValue?: string[] | string | null; + valuesDebounceMs?: number; +}; + +// @public (undocumented) +export type SearchFilterWrapperProps = SearchFilterComponentProps & { + component: (props: SearchFilterComponentProps) => ReactElement; + debug?: boolean; +}; + +// @public (undocumented) +export const SelectFilter: (props: SearchFilterComponentProps) => JSX.Element; + +// @public +export const useAsyncFilterValues: ( + fn: ((partial: string) => Promise) | undefined, + inputValue: string, + defaultValues?: string[], + debounce?: number, +) => + | { + loading: boolean; + error?: undefined; + value?: undefined; + } + | { + loading: false; + error: Error; + value?: undefined; + } + | { + loading: true; + error?: Error | undefined; + value?: string[] | undefined; + } + | { + loading: boolean; + value: string[]; + }; + +// @public +export const useDefaultFilterValue: ( + name: string, + defaultValue?: string | string[] | null | undefined, +) => void; + // @public export const useSearch: () => SearchContextValue; diff --git a/plugins/search-react/package.json b/plugins/search-react/package.json index 5646ce9ee1..ac8a43dee4 100644 --- a/plugins/search-react/package.json +++ b/plugins/search-react/package.json @@ -36,7 +36,8 @@ "@backstage/version-bridge": "^1.0.1", "react-use": "^17.3.2", "@backstage/types": "^1.0.0", - "@material-ui/core": "^4.12.2" + "@material-ui/core": "^4.12.2", + "@material-ui/lab": "4.0.0-alpha.57" }, "peerDependencies": { "@types/react": "^16.13.1 || ^17.0.0", @@ -47,7 +48,8 @@ "@backstage/test-utils": "^1.1.1-next.0", "@testing-library/react": "^12.1.3", "@testing-library/react-hooks": "^8.0.0", - "@testing-library/jest-dom": "^5.10.1" + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/user-event": "^14.0.0" }, "files": [ "dist" diff --git a/plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.test.tsx b/plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.test.tsx new file mode 100644 index 0000000000..14c8967b57 --- /dev/null +++ b/plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.test.tsx @@ -0,0 +1,361 @@ +/* + * Copyright 2021 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TestApiProvider } from '@backstage/test-utils'; +import { screen, render, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import React from 'react'; + +import { searchApiRef } from '../../api'; +import { SearchContextProvider, useSearch } from '../../context'; +import { SearchFilter } from './SearchFilter'; + +const SearchContextFilterSpy = ({ name }: { name: string }) => { + const { filters } = useSearch(); + const value = filters[name]; + return ( + + {Array.isArray(value) ? value.join(',') : value} + + ); +}; + +describe('SearchFilter.Autocomplete', () => { + const query = jest.fn().mockResolvedValue({}); + const emptySearchContext = { + term: '', + types: [], + filters: {}, + }; + + const name = 'field'; + const values = ['value1', 'value2']; + + it('renders as expected', async () => { + render( + + + + + , + ); + + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + await userEvent.click(input); + + await waitFor(() => { + screen.getByRole('listbox'); + }); + + expect(screen.getByRole('option', { name: values[0] })).toBeInTheDocument(); + expect(screen.getByRole('option', { name: values[1] })).toBeInTheDocument(); + }); + + it('renders as expected with async values', async () => { + render( + + + values} /> + + , + ); + + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + await userEvent.click(input); + + await waitFor(() => { + screen.getByRole('listbox'); + }); + + expect(screen.getByRole('option', { name: values[0] })).toBeInTheDocument(); + expect(screen.getByRole('option', { name: values[1] })).toBeInTheDocument(); + }); + + it('does not affect unrelated filter state', async () => { + render( + + + + + + + , + ); + + // The spy should show the initial value. + expect(screen.getByTestId('unrelated-filter-spy')).toHaveTextContent( + 'value', + ); + + // Select a value from the autocomplete filter. + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + await userEvent.click(input); + await waitFor(() => { + screen.getByRole('listbox'); + }); + await userEvent.click(screen.getByRole('option', { name: values[1] })); + + // Wait for the autocomplete filter's value to change. + await waitFor(() => { + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values[1], + ); + }); + + // Unrelated filter spy should maintain the same value. + expect(screen.getByTestId('unrelated-filter-spy')).toHaveTextContent( + 'value', + ); + }); + + describe('single', () => { + it('renders as expected with defaultValue', async () => { + render( + + + + + + , + ); + + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + + await waitFor(() => { + expect(input).toHaveValue(values[1]); + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values[1], + ); + }); + }); + + it('renders as expected with initial context', async () => { + render( + + + + + + , + ); + + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + + await waitFor(() => { + expect(input).toHaveValue(values[0]); + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values[0], + ); + }); + }); + + it('sets filter state when selecting a value', async () => { + render( + + + + + + , + ); + + // Select the first option in the autocomplete. + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + await userEvent.click(input); + await waitFor(() => { + screen.getByRole('listbox'); + }); + await userEvent.click(screen.getByRole('option', { name: values[0] })); + + // The value should be present in the context. + await waitFor(() => { + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values[0], + ); + }); + + // Click the "Clear" button to remove the value. + const clearButton = within(autocomplete).getByLabelText('Clear'); + await userEvent.click(clearButton); + + // That value should have been unset from the context. + await waitFor(() => { + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(''); + }); + }); + }); + + describe('multiple', () => { + it('renders as expected with defaultValue', async () => { + render( + + + + + + , + ); + + await waitFor(() => { + expect(screen.getByText(values[0])).toBeInTheDocument(); + expect(screen.getByText(values[1])).toBeInTheDocument(); + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values.join(','), + ); + }); + }); + + it('renders as expected with initial context', async () => { + render( + + + + + + , + ); + + await waitFor(() => { + expect(screen.getByText(values[0])).toBeInTheDocument(); + expect(screen.getByText(values[1])).toBeInTheDocument(); + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values.join(','), + ); + }); + }); + + it('respects tag limit configuration', async () => { + render( + + + + + , + ); + + const autocomplete = screen.getByRole('combobox'); + const input = within(autocomplete).getByRole('textbox'); + + // Select the second value. + await userEvent.click(input); + await waitFor(() => { + screen.getByRole('listbox'); + }); + await userEvent.click(screen.getByRole('option', { name: values[1] })); + await waitFor(() => { + expect( + screen.getByRole('button', { name: values[1] }), + ).toBeInTheDocument(); + }); + + // Select the first value. + await userEvent.click(input); + await waitFor(() => { + screen.getByRole('listbox'); + }); + await userEvent.click(screen.getByRole('option', { name: values[0] })); + await waitFor(() => { + expect( + screen.getByRole('button', { name: values[0] }), + ).toBeInTheDocument(); + }); + + // Blur the field and only one tag should be shown with a +1. + input.blur(); + expect( + screen.queryByRole('button', { name: values[0] }), + ).not.toBeInTheDocument(); + expect(screen.getByText('+1')).toBeInTheDocument(); + }); + + it('sets filter state when selecting a value', async () => { + render( + + + + + + , + ); + + const autocomplete = screen.getByRole('combobox'); + + // Select both values in the autocomplete. + const input = within(autocomplete).getByRole('textbox'); + await userEvent.click(input); + await waitFor(() => { + screen.getByRole('listbox'); + }); + await userEvent.click(screen.getByRole('option', { name: values[0] })); + await userEvent.click(input); + await waitFor(() => { + screen.getByRole('listbox'); + }); + await userEvent.click(screen.getByRole('option', { name: values[1] })); + + // Both options should be present in the context. + await waitFor(() => { + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent( + values.join(','), + ); + }); + + // Click the "Clear" button to remove the value. + const clearButton = within(autocomplete).getByLabelText('Clear'); + await userEvent.click(clearButton); + + // There should be no content in the filter context. + await waitFor(() => { + expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(''); + }); + }); + }); +}); diff --git a/plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.tsx b/plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.tsx new file mode 100644 index 0000000000..35d1f376e5 --- /dev/null +++ b/plugins/search-react/src/components/SearchFilter/SearchFilter.Autocomplete.tsx @@ -0,0 +1,120 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ChangeEvent, useState } from 'react'; +import { Chip, TextField } from '@material-ui/core'; +import { + Autocomplete, + AutocompleteGetTagProps, + AutocompleteRenderInputParams, +} from '@material-ui/lab'; + +import { useSearch } from '../../context'; +import { useAsyncFilterValues, useDefaultFilterValue } from './hooks'; +import { SearchFilterComponentProps } from './SearchFilter'; + +/** + * @public + */ +export type SearchAutocompleteFilterProps = SearchFilterComponentProps & { + filterSelectedOptions?: boolean; + limitTags?: number; + multiple?: boolean; +}; + +/** + * @public + */ +export const AutocompleteFilter = (props: SearchAutocompleteFilterProps) => { + const { + className, + defaultValue, + name, + values: givenValues, + valuesDebounceMs, + label, + filterSelectedOptions, + limitTags, + multiple, + } = props; + const [inputValue, setInputValue] = useState(''); + useDefaultFilterValue(name, defaultValue); + const asyncValues = + typeof givenValues === 'function' ? givenValues : undefined; + const defaultValues = + typeof givenValues === 'function' ? undefined : givenValues; + const { value: values, loading } = useAsyncFilterValues( + asyncValues, + inputValue, + defaultValues, + valuesDebounceMs, + ); + const { filters, setFilters } = useSearch(); + const filterValue = + (filters[name] as string | string[] | undefined) || (multiple ? [] : null); + + // Set new filter values on input change. + const handleChange = ( + _: ChangeEvent<{}>, + newValue: string | string[] | null, + ) => { + setFilters(prevState => { + const { [name]: filter, ...others } = prevState; + + if (newValue) { + return { ...others, [name]: newValue }; + } + return { ...others }; + }); + }; + + // Provide the input field. + const renderInput = (params: AutocompleteRenderInputParams) => ( + + ); + + // Render tags as primary-colored chips. + const renderTags = ( + tagValue: string[], + getTagProps: AutocompleteGetTagProps, + ) => + tagValue.map((option: string, index: number) => ( + + )); + + return ( + setInputValue(newValue)} + renderInput={renderInput} + renderTags={renderTags} + /> + ); +}; diff --git a/plugins/search/src/components/SearchFilter/SearchFilter.stories.tsx b/plugins/search-react/src/components/SearchFilter/SearchFilter.stories.tsx similarity index 95% rename from plugins/search/src/components/SearchFilter/SearchFilter.stories.tsx rename to plugins/search-react/src/components/SearchFilter/SearchFilter.stories.tsx index 7e8a7d585a..2c8a629f01 100644 --- a/plugins/search/src/components/SearchFilter/SearchFilter.stories.tsx +++ b/plugins/search-react/src/components/SearchFilter/SearchFilter.stories.tsx @@ -1,5 +1,5 @@ /* - * Copyright 2021 The Backstage Authors + * Copyright 2022 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,14 +14,13 @@ * limitations under the License. */ -import { Grid, Paper } from '@material-ui/core'; import React, { ComponentType } from 'react'; -import { - searchApiRef, - MockSearchApi, - SearchContextProvider, -} from '@backstage/plugin-search-react'; +import { Grid, Paper } from '@material-ui/core'; + import { TestApiProvider } from '@backstage/test-utils'; + +import { searchApiRef, MockSearchApi } from '../../api'; +import { SearchContextProvider } from '../../context'; import { SearchFilter } from './SearchFilter'; export default { diff --git a/plugins/search-react/src/components/SearchFilter/SearchFilter.test.tsx b/plugins/search-react/src/components/SearchFilter/SearchFilter.test.tsx new file mode 100644 index 0000000000..89a1818e8d --- /dev/null +++ b/plugins/search-react/src/components/SearchFilter/SearchFilter.test.tsx @@ -0,0 +1,410 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { screen, render, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { useApi } from '@backstage/core-plugin-api'; + +import { SearchContextProvider } from '../../context'; +import { SearchFilter } from './SearchFilter'; + +jest.mock('@backstage/core-plugin-api', () => ({ + ...jest.requireActual('@backstage/core-plugin-api'), + useApi: jest.fn().mockReturnValue({}), +})); + +describe('SearchFilter', () => { + const initialState = { + term: '', + filters: {}, + types: [], + }; + + const label = 'Field'; + const name = 'field'; + const values = ['value1', 'value2']; + const filters = { unrelated: 'unrelated' }; + + const query = jest.fn().mockResolvedValue({}); + (useApi as jest.Mock).mockReturnValue({ query: query }); + + afterAll(() => { + jest.resetAllMocks(); + }); + + it('Check that element was rendered and received props', async () => { + const CustomFilter = (props: { name: string }) =>
{props.name}
; + + render(); + + expect(screen.getByRole('heading', { name })).toBeInTheDocument(); + }); + + describe('Checkbox', () => { + it('Renders field name and values when provided as props', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + expect( + screen.getByRole('checkbox', { name: values[0] }), + ).toBeInTheDocument(); + expect( + screen.getByRole('checkbox', { name: values[1] }), + ).toBeInTheDocument(); + }); + + it('Renders correctly based on filter state', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + expect( + screen.getByRole('checkbox', { name: values[0] }), + ).not.toBeChecked(); + expect(screen.getByRole('checkbox', { name: values[1] })).toBeChecked(); + }); + + it('Renders correctly based on defaultValue', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + expect(screen.getByRole('checkbox', { name: values[0] })).toBeChecked(); + expect( + screen.getByRole('checkbox', { name: values[1] }), + ).not.toBeChecked(); + }); + + it('Checking / unchecking a value sets filter state', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + const checkBox = screen.getByRole('checkbox', { name: values[0] }); + + // Check the box. + await userEvent.click(checkBox); + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ filters: { field: [values[0]] } }), + ); + }); + + // Uncheck the box. + await userEvent.click(checkBox); + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ filters: {} }), + ); + }); + }); + + it('Checking / unchecking a value maintains unrelated filter state', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + const checkBox = screen.getByRole('checkbox', { name: values[0] }); + + // Check the box. + await userEvent.click(checkBox); + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ + filters: { ...filters, field: [values[0]] }, + }), + ); + }); + + // Uncheck the box. + await userEvent.click(checkBox); + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ filters }), + ); + }); + }); + }); + + describe('Select', () => { + it('Renders field name and values when provided as props', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('button')); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + expect( + screen.getByRole('option', { name: values[0] }), + ).toBeInTheDocument(); + expect( + screen.getByRole('option', { name: values[1] }), + ).toBeInTheDocument(); + }); + + it('Renders values when provided asynchronously', async () => { + render( + + values} + /> + , + ); + + await waitFor(() => { + expect(screen.getByRole('button')).toBeInTheDocument(); + expect( + screen.getByRole('button').getAttribute('aria-disabled'), + ).not.toBe('true'); + }); + + await userEvent.click(screen.getByRole('button')); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + expect( + screen.getByRole('option', { name: values[0] }), + ).toBeInTheDocument(); + expect( + screen.getByRole('option', { name: values[1] }), + ).toBeInTheDocument(); + }); + + it('Renders correctly based on filter state', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('button')); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + expect(screen.getByRole('option', { name: values[0] })).toHaveAttribute( + 'aria-selected', + 'true', + ); + expect( + screen.getByRole('option', { name: values[1] }), + ).not.toHaveAttribute('aria-selected'); + expect(screen.getByRole('option', { name: 'All' })).not.toHaveAttribute( + 'aria-selected', + ); + }); + + it('Renders correctly based on defaultValue', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('button')); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + expect(screen.getByRole('option', { name: values[0] })).toHaveAttribute( + 'aria-selected', + 'true', + ); + expect( + screen.getByRole('option', { name: values[1] }), + ).not.toHaveAttribute('aria-selected'); + expect(screen.getByRole('option', { name: 'All' })).not.toHaveAttribute( + 'aria-selected', + ); + }); + + it('Selecting a value sets filter state', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + const button = screen.getByRole('button'); + + await userEvent.click(button); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('option', { name: values[0] })); + + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ + filters: { [name]: values[0] }, + }), + ); + }); + + await userEvent.click(button); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('option', { name: 'All' })); + + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ + filters: {}, + }), + ); + }); + }); + + it('Selecting a value maintains unrelated filter state', async () => { + render( + + + , + ); + + await waitFor(() => { + expect(screen.getByText(label)).toBeInTheDocument(); + }); + + const button = screen.getByRole('button'); + + await userEvent.click(button); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('option', { name: values[0] })); + + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ + filters: { ...filters, [name]: values[0] }, + }), + ); + }); + + await userEvent.click(button); + + await waitFor(() => { + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + await userEvent.click(screen.getByRole('option', { name: 'All' })); + + await waitFor(() => { + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ filters }), + ); + }); + }); + }); +}); diff --git a/plugins/search-react/src/components/SearchFilter/SearchFilter.tsx b/plugins/search-react/src/components/SearchFilter/SearchFilter.tsx new file mode 100644 index 0000000000..2a6d7baafa --- /dev/null +++ b/plugins/search-react/src/components/SearchFilter/SearchFilter.tsx @@ -0,0 +1,237 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ReactElement, ChangeEvent } from 'react'; +import { + makeStyles, + FormControl, + FormControlLabel, + InputLabel, + Checkbox, + Select, + MenuItem, + FormLabel, +} from '@material-ui/core'; + +import { useSearch } from '../../context'; +import { + AutocompleteFilter, + SearchAutocompleteFilterProps, +} from './SearchFilter.Autocomplete'; +import { useAsyncFilterValues, useDefaultFilterValue } from './hooks'; + +const useStyles = makeStyles({ + label: { + textTransform: 'capitalize', + }, +}); + +/** + * @public + */ +export type SearchFilterComponentProps = { + className?: string; + name: string; + label?: string; + /** + * Either an array of values directly, or an async function to return a list + * of values to be used in the filter. In the autocomplete filter, the last + * input value is provided as an input to allow values to be filtered. This + * function is debounced and values cached. + */ + values?: string[] | ((partial: string) => Promise); + defaultValue?: string[] | string | null; + /** + * Debounce time in milliseconds, used when values is an async callback. + * Defaults to 250ms. + */ + valuesDebounceMs?: number; +}; + +/** + * @public + */ +export type SearchFilterWrapperProps = SearchFilterComponentProps & { + component: (props: SearchFilterComponentProps) => ReactElement; + debug?: boolean; +}; + +/** + * @public + */ +export const CheckboxFilter = (props: SearchFilterComponentProps) => { + const { + className, + defaultValue, + label, + name, + values: givenValues = [], + valuesDebounceMs, + } = props; + const classes = useStyles(); + const { filters, setFilters } = useSearch(); + useDefaultFilterValue(name, defaultValue); + const asyncValues = + typeof givenValues === 'function' ? givenValues : undefined; + const defaultValues = + typeof givenValues === 'function' ? undefined : givenValues; + const { value: values = [], loading } = useAsyncFilterValues( + asyncValues, + '', + defaultValues, + valuesDebounceMs, + ); + + const handleChange = (e: ChangeEvent) => { + const { + target: { value, checked }, + } = e; + + setFilters(prevFilters => { + const { [name]: filter, ...others } = prevFilters; + const rest = ((filter as string[]) || []).filter(i => i !== value); + const items = checked ? [...rest, value] : rest; + return items.length ? { ...others, [name]: items } : others; + }); + }; + + return ( + + {label ? {label} : null} + {values.map((value: string) => ( + + } + label={value} + /> + ))} + + ); +}; + +/** + * @public + */ +export const SelectFilter = (props: SearchFilterComponentProps) => { + const { + className, + defaultValue, + label, + name, + values: givenValues, + valuesDebounceMs, + } = props; + const classes = useStyles(); + useDefaultFilterValue(name, defaultValue); + const asyncValues = + typeof givenValues === 'function' ? givenValues : undefined; + const defaultValues = + typeof givenValues === 'function' ? undefined : givenValues; + const { value: values = [], loading } = useAsyncFilterValues( + asyncValues, + '', + defaultValues, + valuesDebounceMs, + ); + const { filters, setFilters } = useSearch(); + + const handleChange = (e: ChangeEvent<{ value: unknown }>) => { + const { + target: { value }, + } = e; + + setFilters(prevFilters => { + const { [name]: filter, ...others } = prevFilters; + return value ? { ...others, [name]: value as string } : others; + }); + }; + + return ( + + {label ? ( + + {label} + + ) : null} + + + ); +}; + +/** + * @public + */ +const SearchFilter = ({ + component: Element, + ...props +}: SearchFilterWrapperProps) => ; + +SearchFilter.Checkbox = ( + props: Omit & + SearchFilterComponentProps, +) => ; + +SearchFilter.Select = ( + props: Omit & + SearchFilterComponentProps, +) => ; + +/** + * A control surface for a given filter field name, rendered as an autocomplete + * textfield. A hard-coded list of values may be provided, or an async function + * which returns values may be provided instead. + * + * @public + */ +SearchFilter.Autocomplete = (props: SearchAutocompleteFilterProps) => ( + +); + +export { SearchFilter }; diff --git a/plugins/search/src/components/SearchFilter/hooks.test.tsx b/plugins/search-react/src/components/SearchFilter/hooks.test.tsx similarity index 98% rename from plugins/search/src/components/SearchFilter/hooks.test.tsx rename to plugins/search-react/src/components/SearchFilter/hooks.test.tsx index 14346a29eb..80c4a3a3a2 100644 --- a/plugins/search/src/components/SearchFilter/hooks.test.tsx +++ b/plugins/search-react/src/components/SearchFilter/hooks.test.tsx @@ -17,11 +17,9 @@ import React from 'react'; import { ApiProvider } from '@backstage/core-app-api'; import { TestApiRegistry } from '@backstage/test-utils'; import { renderHook } from '@testing-library/react-hooks'; -import { - SearchContextProvider, - useSearch, - searchApiRef, -} from '@backstage/plugin-search-react'; + +import { searchApiRef } from '../../api'; +import { SearchContextProvider, useSearch } from '../../context'; import { useDefaultFilterValue, useAsyncFilterValues } from './hooks'; jest.useFakeTimers(); diff --git a/plugins/search/src/components/SearchFilter/hooks.ts b/plugins/search-react/src/components/SearchFilter/hooks.ts similarity index 96% rename from plugins/search/src/components/SearchFilter/hooks.ts rename to plugins/search-react/src/components/SearchFilter/hooks.ts index da30466522..5771cc5288 100644 --- a/plugins/search/src/components/SearchFilter/hooks.ts +++ b/plugins/search-react/src/components/SearchFilter/hooks.ts @@ -1,5 +1,5 @@ /* - * Copyright 2021 The Backstage Authors + * Copyright 2022 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,14 @@ import { useEffect, useRef } from 'react'; import useAsyncFn from 'react-use/lib/useAsyncFn'; import useDebounce from 'react-use/lib/useDebounce'; -import { useSearch } from '@backstage/plugin-search-react'; + +import { useSearch } from '../../context'; /** * Utility hook for either asynchronously loading filter values from a given * function or synchronously providing a given list of default values. + * + * @public */ export const useAsyncFilterValues = ( fn: ((partial: string) => Promise) | undefined, @@ -75,6 +78,8 @@ export const useAsyncFilterValues = ( /** * Utility hook for applying a given default value to the search context. + * + * @public */ export const useDefaultFilterValue = ( name: string, diff --git a/plugins/search-react/src/components/SearchFilter/index.ts b/plugins/search-react/src/components/SearchFilter/index.ts new file mode 100644 index 0000000000..e159cff93d --- /dev/null +++ b/plugins/search-react/src/components/SearchFilter/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { CheckboxFilter, SearchFilter, SelectFilter } from './SearchFilter'; +export { AutocompleteFilter } from './SearchFilter.Autocomplete'; +export { useAsyncFilterValues, useDefaultFilterValue } from './hooks'; +export type { + SearchFilterComponentProps, + SearchFilterWrapperProps, +} from './SearchFilter'; +export type { SearchAutocompleteFilterProps } from './SearchFilter.Autocomplete'; diff --git a/plugins/search-react/src/components/index.ts b/plugins/search-react/src/components/index.ts index 679a254827..8e45c66fce 100644 --- a/plugins/search-react/src/components/index.ts +++ b/plugins/search-react/src/components/index.ts @@ -15,3 +15,4 @@ */ export * from './HighlightedSearchResultText'; +export * from './SearchFilter'; diff --git a/plugins/search/api-report.md b/plugins/search/api-report.md index 21b9df5dda..ec60569af4 100644 --- a/plugins/search/api-report.md +++ b/plugins/search/api-report.md @@ -12,7 +12,9 @@ import { ReactElement } from 'react'; import { ReactNode } from 'react'; import { ResultHighlight } from '@backstage/plugin-search-common'; import { RouteRef } from '@backstage/core-plugin-api'; +import { SearchAutocompleteFilterProps as SearchAutocompleteFilterProps_2 } from '@backstage/plugin-search-react'; import { SearchDocument } from '@backstage/plugin-search-common'; +import { SearchFilterComponentProps as SearchFilterComponentProps_2 } from '@backstage/plugin-search-react'; import { SearchResult as SearchResult_2 } from '@backstage/plugin-search-common'; // Warning: (ae-missing-release-tag) "DefaultResultListItem" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -78,8 +80,8 @@ export type HomePageSearchBarProps = Partial< // @public (undocumented) export const Router: () => JSX.Element; -// @public (undocumented) -export type SearchAutocompleteFilterProps = SearchFilterComponentProps & { +// @public @deprecated (undocumented) +export type SearchAutocompleteFilterProps = SearchFilterComponentProps_2 & { filterSelectedOptions?: boolean; limitTags?: number; multiple?: boolean; @@ -124,7 +126,7 @@ export type SearchBarProps = Partial; // Warning: (ae-missing-release-tag) "SearchFilter" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // -// @public (undocumented) +// @public @deprecated (undocumented) export const SearchFilter: { ({ component: Element, ...props }: SearchFilterWrapperProps): JSX.Element; Checkbox( @@ -135,10 +137,10 @@ export const SearchFilter: { props: Omit & SearchFilterComponentProps, ): JSX.Element; - Autocomplete(props: SearchAutocompleteFilterProps): JSX.Element; + Autocomplete(props: SearchAutocompleteFilterProps_2): JSX.Element; }; -// @public (undocumented) +// @public @deprecated (undocumented) export type SearchFilterComponentProps = { className?: string; name: string; @@ -148,23 +150,7 @@ export type SearchFilterComponentProps = { valuesDebounceMs?: number; }; -// Warning: (ae-missing-release-tag) "SearchFilterNext" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) -// // @public @deprecated (undocumented) -export const SearchFilterNext: { - ({ component: Element, ...props }: SearchFilterWrapperProps): JSX.Element; - Checkbox( - props: Omit & - SearchFilterComponentProps, - ): JSX.Element; - Select( - props: Omit & - SearchFilterComponentProps, - ): JSX.Element; - Autocomplete(props: SearchAutocompleteFilterProps): JSX.Element; -}; - -// @public (undocumented) export type SearchFilterWrapperProps = SearchFilterComponentProps & { component: (props: SearchFilterComponentProps) => ReactElement; debug?: boolean; diff --git a/plugins/search/src/components/SearchFilter/SearchFilter.Autocomplete.tsx b/plugins/search/src/components/SearchFilter/SearchFilter.Autocomplete.tsx index 03f4f28943..1a74decd31 100644 --- a/plugins/search/src/components/SearchFilter/SearchFilter.Autocomplete.tsx +++ b/plugins/search/src/components/SearchFilter/SearchFilter.Autocomplete.tsx @@ -21,11 +21,16 @@ import { AutocompleteGetTagProps, AutocompleteRenderInputParams, } from '@material-ui/lab'; -import { useSearch } from '@backstage/plugin-search-react'; -import { useAsyncFilterValues, useDefaultFilterValue } from './hooks'; -import { SearchFilterComponentProps } from './SearchFilter'; +import { + SearchFilterComponentProps, + useSearch, + useAsyncFilterValues, + useDefaultFilterValue, +} from '@backstage/plugin-search-react'; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * @public */ export type SearchAutocompleteFilterProps = SearchFilterComponentProps & { @@ -34,6 +39,10 @@ export type SearchAutocompleteFilterProps = SearchFilterComponentProps & { multiple?: boolean; }; +/** + * @deprecated Moved to `@backstage/plugin-search-react`. + * + */ export const AutocompleteFilter = (props: SearchAutocompleteFilterProps) => { const { className, diff --git a/plugins/search/src/components/SearchFilter/SearchFilter.tsx b/plugins/search/src/components/SearchFilter/SearchFilter.tsx index bfbab8531c..b88160f363 100644 --- a/plugins/search/src/components/SearchFilter/SearchFilter.tsx +++ b/plugins/search/src/components/SearchFilter/SearchFilter.tsx @@ -14,32 +14,18 @@ * limitations under the License. */ -import React, { ReactElement, ChangeEvent } from 'react'; -import { - makeStyles, - FormControl, - FormControlLabel, - InputLabel, - Checkbox, - Select, - MenuItem, - FormLabel, -} from '@material-ui/core'; +import React, { ReactElement } from 'react'; import { AutocompleteFilter, + CheckboxFilter, SearchAutocompleteFilterProps, -} from './SearchFilter.Autocomplete'; -import { useSearch } from '@backstage/plugin-search-react'; -import { useAsyncFilterValues, useDefaultFilterValue } from './hooks'; - -const useStyles = makeStyles({ - label: { - textTransform: 'capitalize', - }, -}); + SelectFilter, +} from '@backstage/plugin-search-react'; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * @public */ export type SearchFilterComponentProps = { @@ -62,6 +48,8 @@ export type SearchFilterComponentProps = { }; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * @public */ export type SearchFilterWrapperProps = SearchFilterComponentProps & { @@ -69,152 +57,33 @@ export type SearchFilterWrapperProps = SearchFilterComponentProps & { debug?: boolean; }; -const CheckboxFilter = (props: SearchFilterComponentProps) => { - const { - className, - defaultValue, - label, - name, - values: givenValues = [], - valuesDebounceMs, - } = props; - const classes = useStyles(); - const { filters, setFilters } = useSearch(); - useDefaultFilterValue(name, defaultValue); - const asyncValues = - typeof givenValues === 'function' ? givenValues : undefined; - const defaultValues = - typeof givenValues === 'function' ? undefined : givenValues; - const { value: values = [], loading } = useAsyncFilterValues( - asyncValues, - '', - defaultValues, - valuesDebounceMs, - ); - - const handleChange = (e: ChangeEvent) => { - const { - target: { value, checked }, - } = e; - - setFilters(prevFilters => { - const { [name]: filter, ...others } = prevFilters; - const rest = ((filter as string[]) || []).filter(i => i !== value); - const items = checked ? [...rest, value] : rest; - return items.length ? { ...others, [name]: items } : others; - }); - }; - - return ( - - {label ? {label} : null} - {values.map((value: string) => ( - - } - label={value} - /> - ))} - - ); -}; - -const SelectFilter = (props: SearchFilterComponentProps) => { - const { - className, - defaultValue, - label, - name, - values: givenValues, - valuesDebounceMs, - } = props; - const classes = useStyles(); - useDefaultFilterValue(name, defaultValue); - const asyncValues = - typeof givenValues === 'function' ? givenValues : undefined; - const defaultValues = - typeof givenValues === 'function' ? undefined : givenValues; - const { value: values = [], loading } = useAsyncFilterValues( - asyncValues, - '', - defaultValues, - valuesDebounceMs, - ); - const { filters, setFilters } = useSearch(); - - const handleChange = (e: ChangeEvent<{ value: unknown }>) => { - const { - target: { value }, - } = e; - - setFilters(prevFilters => { - const { [name]: filter, ...others } = prevFilters; - return value ? { ...others, [name]: value as string } : others; - }); - }; - - return ( - - {label ? ( - - {label} - - ) : null} - - - ); -}; - +/** + * @deprecated Moved to `@backstage/plugin-search-react`. + */ const SearchFilter = ({ component: Element, ...props }: SearchFilterWrapperProps) => ; +/** + * @deprecated Moved to `@backstage/plugin-search-react`. + */ SearchFilter.Checkbox = ( props: Omit & SearchFilterComponentProps, ) => ; +/** + * @deprecated Moved to `@backstage/plugin-search-react`. + */ SearchFilter.Select = ( props: Omit & SearchFilterComponentProps, ) => ; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * A control surface for a given filter field name, rendered as an autocomplete * textfield. A hard-coded list of values may be provided, or an async function * which returns values may be provided instead. @@ -224,12 +93,4 @@ SearchFilter.Autocomplete = (props: SearchAutocompleteFilterProps) => ( ); -/** - * @deprecated This component was used for rapid prototyping of the Backstage - * Search platform. Now that the API has stabilized, you should use the - * component instead. This component will be removed in an - * upcoming release. - */ -const SearchFilterNext = SearchFilter; - -export { SearchFilter, SearchFilterNext }; +export { SearchFilter }; diff --git a/plugins/search/src/components/SearchFilter/index.ts b/plugins/search/src/components/SearchFilter/index.ts index 86cd66ff6b..3050330038 100644 --- a/plugins/search/src/components/SearchFilter/index.ts +++ b/plugins/search/src/components/SearchFilter/index.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -export { SearchFilter, SearchFilterNext } from './SearchFilter'; +export { SearchFilter } from './SearchFilter'; export type { SearchFilterComponentProps, SearchFilterWrapperProps, diff --git a/plugins/search/src/index.ts b/plugins/search/src/index.ts index 1457ac781d..2eb2ed277b 100644 --- a/plugins/search/src/index.ts +++ b/plugins/search/src/index.ts @@ -28,7 +28,7 @@ export type { SearchBarBaseProps, SearchBarProps, } from './components/SearchBar'; -export { SearchFilter, SearchFilterNext } from './components/SearchFilter'; +export { SearchFilter } from './components/SearchFilter'; export type { SearchAutocompleteFilterProps, SearchFilterComponentProps,