mirror of
https://github.com/facebook/docusaurus.git
synced 2025-04-29 18:27:56 +02:00
refactor(algolia): simplify SearchBar component (#10801)
This commit is contained in:
parent
e8ad3923ea
commit
cc97d66dbb
1 changed files with 99 additions and 77 deletions
|
@ -34,6 +34,7 @@ import type {
|
||||||
DocSearchModalProps,
|
DocSearchModalProps,
|
||||||
StoredDocSearchHit,
|
StoredDocSearchHit,
|
||||||
DocSearchTransformClient,
|
DocSearchTransformClient,
|
||||||
|
DocSearchHit,
|
||||||
} from '@docsearch/react';
|
} from '@docsearch/react';
|
||||||
|
|
||||||
import type {AutocompleteState} from '@algolia/autocomplete-core';
|
import type {AutocompleteState} from '@algolia/autocomplete-core';
|
||||||
|
@ -50,6 +51,85 @@ type DocSearchProps = Omit<
|
||||||
|
|
||||||
let DocSearchModal: typeof DocSearchModalType | null = null;
|
let DocSearchModal: typeof DocSearchModalType | null = null;
|
||||||
|
|
||||||
|
function importDocSearchModalIfNeeded() {
|
||||||
|
if (DocSearchModal) {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
return Promise.all([
|
||||||
|
import('@docsearch/react/modal') as Promise<
|
||||||
|
typeof import('@docsearch/react')
|
||||||
|
>,
|
||||||
|
import('@docsearch/react/style'),
|
||||||
|
import('./styles.css'),
|
||||||
|
]).then(([{DocSearchModal: Modal}]) => {
|
||||||
|
DocSearchModal = Modal;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function useNavigator({
|
||||||
|
externalUrlRegex,
|
||||||
|
}: Pick<DocSearchProps, 'externalUrlRegex'>) {
|
||||||
|
const history = useHistory();
|
||||||
|
const [navigator] = useState<DocSearchModalProps['navigator']>(() => {
|
||||||
|
return {
|
||||||
|
navigate(params) {
|
||||||
|
// Algolia results could contain URL's from other domains which cannot
|
||||||
|
// be served through history and should navigate with window.location
|
||||||
|
if (isRegexpStringMatch(externalUrlRegex, params.itemUrl)) {
|
||||||
|
window.location.href = params.itemUrl;
|
||||||
|
} else {
|
||||||
|
history.push(params.itemUrl);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return navigator;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useTransformSearchClient(): DocSearchModalProps['transformSearchClient'] {
|
||||||
|
const {
|
||||||
|
siteMetadata: {docusaurusVersion},
|
||||||
|
} = useDocusaurusContext();
|
||||||
|
return useCallback(
|
||||||
|
(searchClient: DocSearchTransformClient) => {
|
||||||
|
searchClient.addAlgoliaAgent('docusaurus', docusaurusVersion);
|
||||||
|
return searchClient;
|
||||||
|
},
|
||||||
|
[docusaurusVersion],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useTransformItems(props: Pick<DocSearchProps, 'transformItems'>) {
|
||||||
|
const processSearchResultUrl = useSearchResultUrlProcessor();
|
||||||
|
const [transformItems] = useState<DocSearchModalProps['transformItems']>(
|
||||||
|
() => {
|
||||||
|
return (items: DocSearchHit[]) =>
|
||||||
|
props.transformItems
|
||||||
|
? // Custom transformItems
|
||||||
|
props.transformItems(items)
|
||||||
|
: // Default transformItems
|
||||||
|
items.map((item) => ({
|
||||||
|
...item,
|
||||||
|
url: processSearchResultUrl(item.url),
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return transformItems;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useResultsFooterComponent({
|
||||||
|
closeModal,
|
||||||
|
}: {
|
||||||
|
closeModal: () => void;
|
||||||
|
}): DocSearchProps['resultsFooterComponent'] {
|
||||||
|
return useMemo(
|
||||||
|
() =>
|
||||||
|
({state}) =>
|
||||||
|
<ResultsFooter state={state} onClose={closeModal} />,
|
||||||
|
[closeModal],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function Hit({
|
function Hit({
|
||||||
hit,
|
hit,
|
||||||
children,
|
children,
|
||||||
|
@ -79,19 +159,15 @@ function ResultsFooter({state, onClose}: ResultsFooterProps) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function mergeFacetFilters(f1: FacetFilters, f2: FacetFilters): FacetFilters {
|
function useSearchParameters({
|
||||||
const normalize = (f: FacetFilters): FacetFilters =>
|
|
||||||
typeof f === 'string' ? [f] : f;
|
|
||||||
return [...normalize(f1), ...normalize(f2)];
|
|
||||||
}
|
|
||||||
|
|
||||||
function DocSearch({
|
|
||||||
contextualSearch,
|
contextualSearch,
|
||||||
externalUrlRegex,
|
|
||||||
...props
|
...props
|
||||||
}: DocSearchProps) {
|
}: DocSearchProps): DocSearchProps['searchParameters'] {
|
||||||
const {siteMetadata} = useDocusaurusContext();
|
function mergeFacetFilters(f1: FacetFilters, f2: FacetFilters): FacetFilters {
|
||||||
const processSearchResultUrl = useSearchResultUrlProcessor();
|
const normalize = (f: FacetFilters): FacetFilters =>
|
||||||
|
typeof f === 'string' ? [f] : f;
|
||||||
|
return [...normalize(f1), ...normalize(f2)];
|
||||||
|
}
|
||||||
|
|
||||||
const contextualSearchFacetFilters =
|
const contextualSearchFacetFilters =
|
||||||
useAlgoliaContextualFacetFilters() as FacetFilters;
|
useAlgoliaContextualFacetFilters() as FacetFilters;
|
||||||
|
@ -105,37 +181,27 @@ function DocSearch({
|
||||||
: // ... or use config facetFilters
|
: // ... or use config facetFilters
|
||||||
configFacetFilters;
|
configFacetFilters;
|
||||||
|
|
||||||
// We let user override default searchParameters if she wants to
|
// We let users override default searchParameters if they want to
|
||||||
const searchParameters: DocSearchProps['searchParameters'] = {
|
return {
|
||||||
...props.searchParameters,
|
...props.searchParameters,
|
||||||
facetFilters,
|
facetFilters,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function DocSearch({externalUrlRegex, ...props}: DocSearchProps) {
|
||||||
|
const navigator = useNavigator({externalUrlRegex});
|
||||||
|
const searchParameters = useSearchParameters({...props});
|
||||||
|
const transformItems = useTransformItems(props);
|
||||||
|
const transformSearchClient = useTransformSearchClient();
|
||||||
|
|
||||||
const history = useHistory();
|
|
||||||
const searchContainer = useRef<HTMLDivElement | null>(null);
|
const searchContainer = useRef<HTMLDivElement | null>(null);
|
||||||
// TODO remove after React 19 upgrade?
|
// TODO remove "as any" after React 19 upgrade
|
||||||
const searchButtonRef = useRef<HTMLButtonElement>(null as any);
|
const searchButtonRef = useRef<HTMLButtonElement>(null as any);
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [initialQuery, setInitialQuery] = useState<string | undefined>(
|
const [initialQuery, setInitialQuery] = useState<string | undefined>(
|
||||||
undefined,
|
undefined,
|
||||||
);
|
);
|
||||||
|
|
||||||
const importDocSearchModalIfNeeded = useCallback(() => {
|
|
||||||
if (DocSearchModal) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all([
|
|
||||||
import('@docsearch/react/modal') as Promise<
|
|
||||||
typeof import('@docsearch/react')
|
|
||||||
>,
|
|
||||||
import('@docsearch/react/style'),
|
|
||||||
import('./styles.css'),
|
|
||||||
]).then(([{DocSearchModal: Modal}]) => {
|
|
||||||
DocSearchModal = Modal;
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const prepareSearchContainer = useCallback(() => {
|
const prepareSearchContainer = useCallback(() => {
|
||||||
if (!searchContainer.current) {
|
if (!searchContainer.current) {
|
||||||
const divElement = document.createElement('div');
|
const divElement = document.createElement('div');
|
||||||
|
@ -147,7 +213,7 @@ function DocSearch({
|
||||||
const openModal = useCallback(() => {
|
const openModal = useCallback(() => {
|
||||||
prepareSearchContainer();
|
prepareSearchContainer();
|
||||||
importDocSearchModalIfNeeded().then(() => setIsOpen(true));
|
importDocSearchModalIfNeeded().then(() => setIsOpen(true));
|
||||||
}, [importDocSearchModalIfNeeded, prepareSearchContainer]);
|
}, [prepareSearchContainer]);
|
||||||
|
|
||||||
const closeModal = useCallback(() => {
|
const closeModal = useCallback(() => {
|
||||||
setIsOpen(false);
|
setIsOpen(false);
|
||||||
|
@ -169,51 +235,7 @@ function DocSearch({
|
||||||
[openModal],
|
[openModal],
|
||||||
);
|
);
|
||||||
|
|
||||||
const navigator = useRef({
|
const resultsFooterComponent = useResultsFooterComponent({closeModal});
|
||||||
navigate({itemUrl}: {itemUrl?: string}) {
|
|
||||||
// Algolia results could contain URL's from other domains which cannot
|
|
||||||
// be served through history and should navigate with window.location
|
|
||||||
if (isRegexpStringMatch(externalUrlRegex, itemUrl)) {
|
|
||||||
window.location.href = itemUrl!;
|
|
||||||
} else {
|
|
||||||
history.push(itemUrl!);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}).current;
|
|
||||||
|
|
||||||
const transformItems = useRef<DocSearchModalProps['transformItems']>(
|
|
||||||
(items) =>
|
|
||||||
props.transformItems
|
|
||||||
? // Custom transformItems
|
|
||||||
props.transformItems(items)
|
|
||||||
: // Default transformItems
|
|
||||||
items.map((item) => ({
|
|
||||||
...item,
|
|
||||||
url: processSearchResultUrl(item.url),
|
|
||||||
})),
|
|
||||||
).current;
|
|
||||||
|
|
||||||
// @ts-expect-error: TODO fix lib issue after React 19, using JSX.Element
|
|
||||||
const resultsFooterComponent: DocSearchProps['resultsFooterComponent'] =
|
|
||||||
useMemo(
|
|
||||||
() =>
|
|
||||||
// eslint-disable-next-line react/no-unstable-nested-components
|
|
||||||
(footerProps: Omit<ResultsFooterProps, 'onClose'>): ReactNode =>
|
|
||||||
<ResultsFooter {...footerProps} onClose={closeModal} />,
|
|
||||||
[closeModal],
|
|
||||||
);
|
|
||||||
|
|
||||||
const transformSearchClient = useCallback(
|
|
||||||
(searchClient: DocSearchTransformClient) => {
|
|
||||||
searchClient.addAlgoliaAgent(
|
|
||||||
'docusaurus',
|
|
||||||
siteMetadata.docusaurusVersion,
|
|
||||||
);
|
|
||||||
|
|
||||||
return searchClient;
|
|
||||||
},
|
|
||||||
[siteMetadata.docusaurusVersion],
|
|
||||||
);
|
|
||||||
|
|
||||||
useDocSearchKeyboardEvents({
|
useDocSearchKeyboardEvents({
|
||||||
isOpen,
|
isOpen,
|
||||||
|
|
Loading…
Add table
Reference in a new issue