diff --git a/plugins/search/src/components/SearchModal/SearchModal.test.tsx b/plugins/search/src/components/SearchModal/SearchModal.test.tsx
index 842f5fb401..3ef9291585 100644
--- a/plugins/search/src/components/SearchModal/SearchModal.test.tsx
+++ b/plugins/search/src/components/SearchModal/SearchModal.test.tsx
@@ -21,7 +21,10 @@ import userEvent from '@testing-library/user-event';
import { configApiRef } from '@backstage/core-plugin-api';
import { ApiProvider, ConfigReader } from '@backstage/core-app-api';
import { rootRouteRef } from '../../plugin';
-import { searchApiRef } from '@backstage/plugin-search-react';
+import {
+ searchApiRef,
+ SearchContextProvider,
+} from '@backstage/plugin-search-react';
import { SearchModal } from './SearchModal';
@@ -55,6 +58,52 @@ describe('SearchModal', () => {
expect(query).toHaveBeenCalledTimes(1);
});
+ it('Should use parent search context if defined', async () => {
+ const initialState = {
+ term: 'term',
+ filters: { filter: '' },
+ types: ['type'],
+ pageCursor: 'page cursor',
+ };
+
+ await renderInTestApp(
+
+
+
+
+ ,
+ {
+ mountedRoutes: {
+ '/search': rootRouteRef,
+ },
+ },
+ );
+
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ expect(query).toHaveBeenCalledWith(initialState);
+ });
+
+ it('Should create a local search context if a parent is not defined', async () => {
+ await renderInTestApp(
+
+
+ ,
+ {
+ mountedRoutes: {
+ '/search': rootRouteRef,
+ },
+ },
+ );
+
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ expect(query).toHaveBeenCalledWith({
+ term: '',
+ filters: {},
+ types: [],
+ pageCursor: undefined,
+ });
+ });
+
it('Should render a custom Modal correctly', async () => {
await renderInTestApp(
diff --git a/plugins/search/src/components/SearchModal/SearchModal.tsx b/plugins/search/src/components/SearchModal/SearchModal.tsx
index 6c37f20001..aaee7667dd 100644
--- a/plugins/search/src/components/SearchModal/SearchModal.tsx
+++ b/plugins/search/src/components/SearchModal/SearchModal.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import React from 'react';
+import React, { PropsWithChildren } from 'react';
import {
Dialog,
DialogActions,
@@ -170,6 +170,17 @@ export const Modal = ({ toggleModal }: SearchModalProps) => {
);
};
+const Context = ({ children }: PropsWithChildren<{}>) => {
+ // Checks if there is a parent context already defined and, if not, creates a new local context.
+ try {
+ // Throws an exception if there is no parent context already defined
+ useSearch();
+ return <>{children}>;
+ } catch {
+ return {children};
+ }
+};
+
/**
* @public
*/
@@ -194,11 +205,11 @@ export const SearchModal = ({
hidden={hidden}
>
{open && (
-
+
{(children && children({ toggleModal })) ?? (
)}
-
+
)}
);