In some scenarios, we need to customize the search function, such as:
Faced with these flexible custom requirements, we provide corresponding interfaces to extend the search components of the default theme, making it easy for you to customize the search function.
searchHooks
In the Rspress config, we provide a search.searchHooks
config item for configuring the hook functions of the search components, as follows:
The value of the search.searchHooks
config item is a file path. This file will export the corresponding hook logic, such as onSearch
, so that you can customize the capabilities of the search at run time. We can call this file a searchHooks
module.
Next, let us introduce the hook functions in searchHooks, namely beforeSearch
, onSearch
, afterRender
and render
.
In the searchHooks module, you only need to export the hook functions you need, instead of necessarily exporting all the hook functions.
The beforeSearch
hook function will be executed before the search starts, you can use it to process the search keywords, such as removing sensitive words, or reporting the search keywords.
This hook supports asynchronous operations.
Here is an example of usage:
The onSearch
hook function will be executed after the default full-text search logic is finished. You can use this hook function to filter or report the search results, or you can add a custom search data source in this hook function.
This hook supports asynchronous operations.
Here is an example of how to use it:
Note that the return value of the onSearch
hook function is an array, each item in the array is a search source result, and each item has the following structure:
The result
is the search result, you can customize its internal structure. The renderType
is the type of the search result, which can be RenderType.Default
or RenderType.Custom
. If it is RenderType.Default
, the default search result rendering logic will be used; if it is RenderType.Custom
, the render
function will be used to render the search result.
The afterSearch
hook function will be executed after the search result is rendered. You can get the final search keywords and search results in this hook.
This hook supports asynchronous operations.
Here is an example of usage:
The render
function will render the custom search source data in your onSearch
hook. Therefore, it generally needs to be used together with onSearch
. Here's how to use it:
The result is as follows: