diff --git a/plugins/search-react/api-report.md b/plugins/search-react/api-report.md index 5558fd3257..27279e09a9 100644 --- a/plugins/search-react/api-report.md +++ b/plugins/search-react/api-report.md @@ -7,6 +7,7 @@ import { ApiRef } from '@backstage/core-plugin-api'; import { AsyncState } from 'react-use/lib/useAsync'; +import { InputBaseProps } from '@material-ui/core'; import { JsonObject } from '@backstage/types'; import { PropsWithChildren } from 'react'; import { default as React_2 } from 'react'; @@ -62,6 +63,35 @@ export type SearchAutocompleteFilterProps = SearchFilterComponentProps & { multiple?: boolean; }; +// @public +export const SearchBar: ({ onChange, ...props }: SearchBarProps) => JSX.Element; + +// @public +export const SearchBarBase: ({ + onChange, + onKeyDown, + onSubmit, + debounceTime, + clearButton, + fullWidth, + value: defaultValue, + inputProps: defaultInputProps, + endAdornment: defaultEndAdornment, + ...props +}: SearchBarBaseProps) => JSX.Element; + +// @public +export type SearchBarBaseProps = Omit & { + debounceTime?: number; + clearButton?: boolean; + onClear?: () => void; + onSubmit?: () => void; + onChange: (value: string) => void; +}; + +// @public +export type SearchBarProps = Partial; + // @public export const SearchContextProvider: ( props: SearchContextProviderProps, @@ -135,6 +165,13 @@ export type SearchResultProps = { // @public (undocumented) export const SelectFilter: (props: SearchFilterComponentProps) => JSX.Element; +// @public +export const TrackSearch: ({ + children, +}: { + children: React_2.ReactChild; +}) => JSX.Element; + // @public export const useAsyncFilterValues: ( fn: ((partial: string) => Promise) | undefined, diff --git a/plugins/search/src/components/SearchBar/SearchBar.stories.tsx b/plugins/search-react/src/components/SearchBar/SearchBar.stories.tsx similarity index 93% rename from plugins/search/src/components/SearchBar/SearchBar.stories.tsx rename to plugins/search-react/src/components/SearchBar/SearchBar.stories.tsx index 9728101e97..88aed35f8d 100644 --- a/plugins/search/src/components/SearchBar/SearchBar.stories.tsx +++ b/plugins/search-react/src/components/SearchBar/SearchBar.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,14 @@ * limitations under the License. */ -import { Grid, makeStyles, Paper } from '@material-ui/core'; import React, { ComponentType } from 'react'; -import { - searchApiRef, - MockSearchApi, - SearchContextProvider, -} from '@backstage/plugin-search-react'; +import { Grid, makeStyles, Paper } from '@material-ui/core'; + import { TestApiProvider } from '@backstage/test-utils'; + +import { searchApiRef, MockSearchApi } from '../../api'; +import { SearchContextProvider } from '../../context'; + import { SearchBar } from './SearchBar'; export default { diff --git a/plugins/search-react/src/components/SearchBar/SearchBar.test.tsx b/plugins/search-react/src/components/SearchBar/SearchBar.test.tsx new file mode 100644 index 0000000000..4e2c4d7a5c --- /dev/null +++ b/plugins/search-react/src/components/SearchBar/SearchBar.test.tsx @@ -0,0 +1,352 @@ +/* + * 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, act } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { configApiRef, analyticsApiRef } from '@backstage/core-plugin-api'; +import { ApiProvider, ConfigReader } from '@backstage/core-app-api'; +import { MockAnalyticsApi, TestApiRegistry } from '@backstage/test-utils'; + +import { searchApiRef } from '../../api'; +import { SearchContextProvider } from '../../context'; +import { SearchBar } from './SearchBar'; + +jest.mock('@backstage/core-plugin-api', () => ({ + ...jest.requireActual('@backstage/core-plugin-api'), +})); + +describe('SearchBar', () => { + const initialState = { + term: '', + filters: {}, + types: ['*'], + pageCursor: '', + }; + + const query = jest.fn().mockResolvedValue({}); + const analyticsApiSpy = new MockAnalyticsApi(); + let apiRegistry: TestApiRegistry; + + apiRegistry = TestApiRegistry.from( + [ + configApiRef, + new ConfigReader({ + app: { title: 'Mock title' }, + }), + ], + [searchApiRef, { query }], + ); + + const name = 'Search'; + const term = 'term'; + + afterAll(() => { + jest.resetAllMocks(); + }); + + it('Renders without exploding', async () => { + render( + + + + + , + ); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toBeInTheDocument(); + expect( + screen.getByPlaceholderText('Search in Mock title'), + ).toBeInTheDocument(); + }); + }); + + it('Renders with custom placeholder', async () => { + render( + + + + + , + , + ); + + await waitFor(() => { + expect( + screen.getByPlaceholderText('This is a custom placeholder'), + ).toBeInTheDocument(); + }); + }); + + it('Renders based on initial search', async () => { + render( + + + + + , + , + ); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toHaveValue(term); + }); + }); + + it('Updates term state when text is entered', async () => { + const user = userEvent.setup({ delay: null }); + jest.useFakeTimers(); + const defaultDebounceTime = 200; + + render( + + + + + , + , + ); + + const textbox = screen.getByRole('textbox', { name }); + + const value = 'value'; + + await user.type(textbox, value); + + act(() => { + jest.advanceTimersByTime(defaultDebounceTime); + }); + + await waitFor(() => { + expect(textbox).toHaveValue(value); + }); + + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ term: value }), + ); + jest.useRealTimers(); + }); + + it('Clear button clears term state', async () => { + render( + + + + + , + ); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toHaveValue(term); + }); + + await userEvent.click(screen.getByRole('button', { name: 'Clear' })); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toHaveValue(''); + }); + + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ term: '' }), + ); + }); + + it('Should not show clear button', async () => { + render( + + + + + , + ); + + await waitFor(() => { + expect( + screen.queryByRole('button', { name: 'Clear' }), + ).not.toBeInTheDocument(); + }); + }); + + it('Adheres to provided debounceTime', async () => { + const user = userEvent.setup({ delay: null }); + jest.useFakeTimers(); + + const debounceTime = 600; + + render( + + + + + , + , + ); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toBeInTheDocument(); + }); + + const textbox = screen.getByRole('textbox', { name }); + + const value = 'value'; + + await user.type(textbox, value); + + expect(query).not.toHaveBeenLastCalledWith( + expect.objectContaining({ term: value }), + ); + + act(() => { + jest.advanceTimersByTime(debounceTime); + }); + expect(textbox).toHaveValue(value); + + expect(query).toHaveBeenLastCalledWith( + expect.objectContaining({ term: value }), + ); + jest.useRealTimers(); + }); + + it('does not capture analytics event if not enabled in app', async () => { + const user = userEvent.setup({ delay: null }); + jest.useFakeTimers(); + + const debounceTime = 600; + + render( + + + + + , + , + ); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toBeInTheDocument(); + }); + + const textbox = screen.getByRole('textbox', { name }); + + const value = 'value'; + + await user.type(textbox, value); + + act(() => { + jest.advanceTimersByTime(debounceTime); + }); + + await waitFor(() => expect(textbox).toHaveValue(value)); + + expect(analyticsApiSpy.getEvents()).toHaveLength(0); + jest.useRealTimers(); + }); + + it('captures analytics events if enabled in app', async () => { + const user = userEvent.setup({ delay: null }); + jest.useFakeTimers(); + + const debounceTime = 600; + + apiRegistry = TestApiRegistry.from( + [analyticsApiRef, analyticsApiSpy], + [ + configApiRef, + new ConfigReader({ + app: { + title: 'Mock title', + analytics: { + ga: { + trackingId: 'xyz123', + }, + }, + }, + }), + ], + [searchApiRef, { query }], + ); + + render( + + + + + , + ); + + await waitFor(() => { + expect(screen.getByRole('textbox', { name })).toBeInTheDocument(); + }); + + const textbox = screen.getByRole('textbox', { name }); + + const value = 'value'; + + await user.type(textbox, value); + + expect(analyticsApiSpy.getEvents()).toHaveLength(0); + + act(() => { + jest.advanceTimersByTime(debounceTime); + }); + + await waitFor(() => expect(textbox).toHaveValue(value)); + + expect(analyticsApiSpy.getEvents()).toHaveLength(1); + expect(analyticsApiSpy.getEvents()[0]).toEqual({ + action: 'search', + context: { + extension: 'App', + pluginId: 'root', + routeRef: 'unknown', + searchTypes: 'software-catalog,techdocs', + }, + subject: 'value', + }); + + await user.clear(textbox); + + // make sure new term is captured + await user.type(textbox, 'new value'); + + act(() => { + jest.advanceTimersByTime(debounceTime); + }); + + await waitFor(() => expect(textbox).toHaveValue('new value')); + + expect(analyticsApiSpy.getEvents()).toHaveLength(2); + expect(analyticsApiSpy.getEvents()[1]).toEqual({ + action: 'search', + context: { + extension: 'App', + pluginId: 'root', + routeRef: 'unknown', + searchTypes: 'software-catalog,techdocs', + }, + subject: 'new value', + }); + jest.useRealTimers(); + }); +}); diff --git a/plugins/search-react/src/components/SearchBar/SearchBar.tsx b/plugins/search-react/src/components/SearchBar/SearchBar.tsx new file mode 100644 index 0000000000..b3c8ec9fa5 --- /dev/null +++ b/plugins/search-react/src/components/SearchBar/SearchBar.tsx @@ -0,0 +1,179 @@ +/* + * 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, + KeyboardEvent, + useState, + useEffect, + useCallback, +} from 'react'; +import useDebounce from 'react-use/lib/useDebounce'; +import { + InputBase, + InputBaseProps, + InputAdornment, + IconButton, +} from '@material-ui/core'; +import SearchIcon from '@material-ui/icons/Search'; +import ClearButton from '@material-ui/icons/Clear'; + +import { configApiRef, useApi } from '@backstage/core-plugin-api'; + +import { + SearchContextProvider, + useSearch, + useSearchContextCheck, +} from '../../context'; +import { TrackSearch } from '../SearchTracker'; + +/** + * Props for {@link SearchBarBase}. + * + * @public + */ +export type SearchBarBaseProps = Omit & { + debounceTime?: number; + clearButton?: boolean; + onClear?: () => void; + onSubmit?: () => void; + onChange: (value: string) => void; +}; + +/** + * All search boxes exported by the search plugin are based on the , + * and this one is based on the component from Material UI. + * Recommended if you don't use Search Provider or Search Context. + * + * @public + */ +export const SearchBarBase = ({ + onChange, + onKeyDown, + onSubmit, + debounceTime = 200, + clearButton = true, + fullWidth = true, + value: defaultValue, + inputProps: defaultInputProps = {}, + endAdornment: defaultEndAdornment, + ...props +}: SearchBarBaseProps) => { + const configApi = useApi(configApiRef); + const [value, setValue] = useState(defaultValue as string); + const hasSearchContext = useSearchContextCheck(); + + useEffect(() => { + setValue(prevValue => + prevValue !== defaultValue ? (defaultValue as string) : prevValue, + ); + }, [defaultValue]); + + useDebounce(() => onChange(value), debounceTime, [value]); + + const handleChange = useCallback( + (e: ChangeEvent) => { + setValue(e.target.value); + }, + [setValue], + ); + + const handleKeyDown = useCallback( + (e: KeyboardEvent) => { + if (onKeyDown) onKeyDown(e); + if (onSubmit && e.key === 'Enter') { + onSubmit(); + } + }, + [onKeyDown, onSubmit], + ); + + const handleClear = useCallback(() => { + onChange(''); + }, [onChange]); + + const placeholder = `Search in ${ + configApi.getOptionalString('app.title') || 'Backstage' + }`; + + const startAdornment = ( + + + + + + ); + + const endAdornment = ( + + + + + + ); + + const searchBar = ( + + + + ); + + return hasSearchContext ? ( + searchBar + ) : ( + {searchBar} + ); +}; + +/** + * Props for {@link SearchBar}. + * + * @public + */ +export type SearchBarProps = Partial; + +/** + * Recommended search bar when you use the Search Provider or Search Context. + * + * @public + */ +export const SearchBar = ({ onChange, ...props }: SearchBarProps) => { + const { term, setTerm } = useSearch(); + + const handleChange = useCallback( + (newValue: string) => { + if (onChange) { + onChange(newValue); + } else { + setTerm(newValue); + } + }, + [onChange, setTerm], + ); + + return ; +}; diff --git a/plugins/search-react/src/components/SearchBar/index.tsx b/plugins/search-react/src/components/SearchBar/index.tsx new file mode 100644 index 0000000000..075a0c7dc2 --- /dev/null +++ b/plugins/search-react/src/components/SearchBar/index.tsx @@ -0,0 +1,18 @@ +/* + * 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 { SearchBar, SearchBarBase } from './SearchBar'; +export type { SearchBarProps, SearchBarBaseProps } from './SearchBar'; diff --git a/plugins/search/src/components/SearchTracker/SearchTracker.tsx b/plugins/search-react/src/components/SearchTracker/SearchTracker.tsx similarity index 91% rename from plugins/search/src/components/SearchTracker/SearchTracker.tsx rename to plugins/search-react/src/components/SearchTracker/SearchTracker.tsx index 35cfa1ec38..8ca7373298 100644 --- a/plugins/search/src/components/SearchTracker/SearchTracker.tsx +++ b/plugins/search-react/src/components/SearchTracker/SearchTracker.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. @@ -16,10 +16,12 @@ import React, { useEffect } from 'react'; import { useAnalytics } from '@backstage/core-plugin-api'; -import { useSearch } from '@backstage/plugin-search-react'; +import { useSearch } from '../../context'; /** * Capture search event on term change. + * + * @public */ export const TrackSearch = ({ children }: { children: React.ReactChild }) => { const analytics = useAnalytics(); diff --git a/plugins/search/src/components/SearchTracker/index.ts b/plugins/search-react/src/components/SearchTracker/index.ts similarity index 93% rename from plugins/search/src/components/SearchTracker/index.ts rename to plugins/search-react/src/components/SearchTracker/index.ts index 5e6a75aa25..9932f2eaec 100644 --- a/plugins/search/src/components/SearchTracker/index.ts +++ b/plugins/search-react/src/components/SearchTracker/index.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. diff --git a/plugins/search-react/src/components/index.ts b/plugins/search-react/src/components/index.ts index bfd65d471f..5b7767859e 100644 --- a/plugins/search-react/src/components/index.ts +++ b/plugins/search-react/src/components/index.ts @@ -18,3 +18,5 @@ export * from './HighlightedSearchResultText'; export * from './SearchFilter'; export * from './SearchResult'; export * from './SearchResultPager'; +export * from './SearchBar'; +export * from './SearchTracker'; diff --git a/plugins/search/api-report.md b/plugins/search/api-report.md index 25a7f40394..ea5f0b4d0d 100644 --- a/plugins/search/api-report.md +++ b/plugins/search/api-report.md @@ -87,10 +87,10 @@ export type SearchAutocompleteFilterProps = SearchFilterComponentProps_2 & { multiple?: boolean; }; -// @public +// @public @deprecated (undocumented) export const SearchBar: ({ onChange, ...props }: SearchBarProps) => JSX.Element; -// @public +// @public @deprecated (undocumented) export const SearchBarBase: ({ onChange, onKeyDown, @@ -104,7 +104,7 @@ export const SearchBarBase: ({ ...props }: SearchBarBaseProps) => JSX.Element; -// @public +// @public @deprecated (undocumented) export type SearchBarBaseProps = Omit & { debounceTime?: number; clearButton?: boolean; @@ -121,7 +121,7 @@ export const SearchBarNext: ({ ...props }: Partial) => JSX.Element; -// @public +// @public @deprecated (undocumented) 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) diff --git a/plugins/search/src/components/SearchBar/SearchBar.tsx b/plugins/search/src/components/SearchBar/SearchBar.tsx index b5d55fed8e..cb61089eb6 100644 --- a/plugins/search/src/components/SearchBar/SearchBar.tsx +++ b/plugins/search/src/components/SearchBar/SearchBar.tsx @@ -36,10 +36,12 @@ import { SearchContextProvider, useSearch, useSearchContextCheck, + TrackSearch, } from '@backstage/plugin-search-react'; -import { TrackSearch } from '../SearchTracker'; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * Props for {@link SearchBarBase}. * * @public @@ -53,6 +55,8 @@ export type SearchBarBaseProps = Omit & { }; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * All search boxes exported by the search plugin are based on the , * and this one is based on the component from Material UI. * Recommended if you don't use Search Provider or Search Context. @@ -149,6 +153,8 @@ export const SearchBarBase = ({ }; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * Props for {@link SearchBar}. * * @public @@ -156,6 +162,8 @@ export const SearchBarBase = ({ export type SearchBarProps = Partial; /** + * @deprecated Moved to `@backstage/plugin-search-react`. + * * Recommended search bar when you use the Search Provider or Search Context. * * @public