Skip to content

Commit

Permalink
fix: refine search context, support hideSearchBarWithNoSearchContext
Browse files Browse the repository at this point in the history
  • Loading branch information
weareoutman committed Oct 17, 2022
1 parent 0884889 commit 38908ed
Show file tree
Hide file tree
Showing 10 changed files with 149 additions and 93 deletions.
52 changes: 26 additions & 26 deletions README.md

Large diffs are not rendered by default.

20 changes: 15 additions & 5 deletions docusaurus-search-local/src/client/theme/SearchBar/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
docsPluginIdForPreferredVersion,
indexDocs,
searchContextByPaths,
hideSearchBarWithNoSearchContext,
} from "../../utils/proxiedGenerated";
import LoadingRing from "../LoadingRing/LoadingRing";

Expand Down Expand Up @@ -110,25 +111,33 @@ export default function SearchBar({
let nextSearchContext = "";
if (location.pathname.startsWith(versionUrl)) {
const uri = location.pathname.substring(versionUrl.length);
const matchedPath = searchContextByPaths.find(path => uri === path || uri.startsWith(`${path}/`));
const matchedPath = searchContextByPaths.find(
(path) => uri === path || uri.startsWith(`${path}/`)
);
if (matchedPath) {
nextSearchContext = matchedPath;
}
}
if (prevSearchContext.current !== nextSearchContext) {
// Reset index state map once search context is changed.
indexStateMap.current.delete(nextSearchContext);
prevSearchContext.current = nextSearchContext;
}
setSearchContext(nextSearchContext);
}, [location, setSearchContext, versionUrl]);
}, [location.pathname, versionUrl]);

const hidden =
!!hideSearchBarWithNoSearchContext &&
Array.isArray(searchContextByPaths) &&
searchContext === "";

const loadIndex = useCallback(async () => {
if (indexStateMap.current.get(searchContext)) {
if (hidden || indexStateMap.current.get(searchContext)) {
// Do not load the index (again) if its already loaded or in the process of being loaded.
return;
}
indexStateMap.current.set(searchContext, "loading");
search.current?.destroy();
search.current?.autocomplete.destroy();
setLoading(true);

const [{ wrappedIndexes, zhDictionary }, autoComplete] = await Promise.all([
Expand Down Expand Up @@ -231,7 +240,7 @@ export default function SearchBar({
}
input.focus();
}
}, [versionUrl, searchContext, baseUrl, history]);
}, [hidden, searchContext, versionUrl, baseUrl, history]);

useEffect(() => {
if (!Mark) {
Expand Down Expand Up @@ -338,6 +347,7 @@ export default function SearchBar({
[styles.searchIndexLoading]: loading && inputChanged,
[styles.focused]: focused,
})}
hidden={hidden}
>
<input
placeholder={translate({
Expand Down
1 change: 1 addition & 0 deletions docusaurus-search-local/src/declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ declare module "*/generated.js" {
export const docsPluginIdForPreferredVersion: string;
export const indexDocs: boolean;
export const searchContextByPaths: string[];
export const hideSearchBarWithNoSearchContext: boolean;
// These below are for mocking only.
export const __setLanguage: (value: string[]) => void;
export const __setRemoveDefaultStopWordFilter: (value: boolean) => void;
Expand Down
11 changes: 11 additions & 0 deletions docusaurus-search-local/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,15 @@ export interface PluginOptions {
* It will create multiple search indexes by these paths.
*/
searchContextByPaths?: string[];

/**
* Whether to hide the search bar when no search context was matched.
*
* By default, if `searchContextByPaths` is set, pages which are not matched with it will be considered
* as with a search context of ROOT. By setting `hideSearchBarWithNoSearchContext` to false, these pages
* will be considered as with NO search context, and the search bar will be hidden.
*
* @default false
*/
hideSearchBarWithNoSearchContext?: boolean;
}
6 changes: 6 additions & 0 deletions docusaurus-search-local/src/server/utils/generate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ describe("generate", () => {
"export const docsPluginIdForPreferredVersion = undefined;",
"export const indexDocs = true;",
"export const searchContextByPaths = null;",
"export const hideSearchBarWithNoSearchContext = false;",
],
],
[
Expand All @@ -57,6 +58,7 @@ describe("generate", () => {
"export const docsPluginIdForPreferredVersion = undefined;",
"export const indexDocs = true;",
"export const searchContextByPaths = null;",
"export const hideSearchBarWithNoSearchContext = false;",
],
],
[
Expand All @@ -83,6 +85,7 @@ describe("generate", () => {
"export const docsPluginIdForPreferredVersion = undefined;",
"export const indexDocs = true;",
"export const searchContextByPaths = null;",
"export const hideSearchBarWithNoSearchContext = false;",
],
],
[
Expand Down Expand Up @@ -112,6 +115,7 @@ describe("generate", () => {
"export const docsPluginIdForPreferredVersion = undefined;",
"export const indexDocs = true;",
"export const searchContextByPaths = null;",
"export const hideSearchBarWithNoSearchContext = false;",
],
],
[
Expand Down Expand Up @@ -139,6 +143,7 @@ describe("generate", () => {
"export const docsPluginIdForPreferredVersion = undefined;",
"export const indexDocs = true;",
"export const searchContextByPaths = null;",
"export const hideSearchBarWithNoSearchContext = false;",
],
],
[
Expand Down Expand Up @@ -169,6 +174,7 @@ describe("generate", () => {
"export const docsPluginIdForPreferredVersion = undefined;",
"export const indexDocs = true;",
"export const searchContextByPaths = null;",
"export const hideSearchBarWithNoSearchContext = false;",
],
],
])("generate({ language: %j }, dir) should work", (language, contents) => {
Expand Down
6 changes: 6 additions & 0 deletions docusaurus-search-local/src/server/utils/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export function generate(config: ProcessedPluginOptions, dir: string): string {
docsPluginIdForPreferredVersion,
indexDocs,
searchContextByPaths,
hideSearchBarWithNoSearchContext,
} = config;
const indexHash = getIndexHash(config);
const contents: string[] = [
Expand Down Expand Up @@ -130,6 +131,11 @@ export function generate(config: ProcessedPluginOptions, dir: string): string {
: null
)};`
);
contents.push(
`export const hideSearchBarWithNoSearchContext = ${JSON.stringify(
!!hideSearchBarWithNoSearchContext
)};`
);

fs.writeFileSync(path.join(dir, "generated.js"), contents.join("\n"));

Expand Down
18 changes: 13 additions & 5 deletions docusaurus-search-local/src/server/utils/postBuildFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,22 @@ export function postBuildFactory(
debugInfo("building index");

const docsByDirMap = new Map<string, SearchDocument[][]>();
if (config.searchContextByPaths) {
const { searchContextByPaths, hideSearchBarWithNoSearchContext } = config;
if (searchContextByPaths) {
const { baseUrl } = buildData;
const rootAllDocs: SearchDocument[][] = [];
docsByDirMap.set("", rootAllDocs);
if (!hideSearchBarWithNoSearchContext) {
docsByDirMap.set("", rootAllDocs);
}
let docIndex = 0;
for (const documents of allDocuments) {
rootAllDocs[docIndex] = [];
for (const doc of documents) {
if (doc.u.startsWith(baseUrl)) {
const uri = doc.u.substring(baseUrl.length);
const matchedPath = config.searchContextByPaths.find(path => uri === path || uri.startsWith(`${path}/`));
const matchedPath = searchContextByPaths.find(
(path) => uri === path || uri.startsWith(`${path}/`)
);
if (matchedPath) {
let dirAllDocs = docsByDirMap.get(matchedPath);
if (!dirAllDocs) {
Expand All @@ -61,7 +66,7 @@ export function postBuildFactory(
docIndex++;
}
for (const [k, v] of docsByDirMap) {
const docsNotEmpty = v.filter(d => !!d);
const docsNotEmpty = v.filter((d) => !!d);
if (docsNotEmpty.length < v.length) {
docsByDirMap.set(k, docsNotEmpty);
}
Expand All @@ -78,7 +83,10 @@ export function postBuildFactory(
await writeFileAsync(
path.join(
versionData.outDir,
searchIndexFilename.replace("{dir}", k === "" ? "" : `-${k.replace(/\//g, "-")}`)
searchIndexFilename.replace(
"{dir}",
k === "" ? "" : `-${k.replace(/\//g, "-")}`
)
),
JSON.stringify(searchIndex),
{ encoding: "utf8" }
Expand Down
14 changes: 13 additions & 1 deletion docusaurus-search-local/src/server/utils/validateOptions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ describe("validateOptions", () => {
Required<
Omit<
PluginOptions,
"docsPluginIdForPreferredVersion" | "zhUserDict" | "zhUserDictPath" | "searchContextByPaths"
| "docsPluginIdForPreferredVersion"
| "zhUserDict"
| "zhUserDictPath"
| "searchContextByPaths"
>
>
]
Expand All @@ -42,6 +45,7 @@ describe("validateOptions", () => {
language: ["en"],
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: false,
searchResultLimits: 8,
explicitSearchResultPath: false,
Expand All @@ -66,6 +70,7 @@ describe("validateOptions", () => {
language: ["en"],
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: false,
searchResultLimits: 8,
explicitSearchResultPath: false,
Expand All @@ -90,6 +95,7 @@ describe("validateOptions", () => {
language: ["en"],
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: false,
searchResultLimits: 8,
explicitSearchResultPath: false,
Expand All @@ -114,6 +120,7 @@ describe("validateOptions", () => {
language: ["en", "zh"],
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: false,
searchResultLimits: 8,
explicitSearchResultPath: false,
Expand All @@ -129,6 +136,7 @@ describe("validateOptions", () => {
docsDir: "src/docs",
blogDir: "src/blog",
language: "en",
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: true,
searchResultLimits: 5,
explicitSearchResultPath: false,
Expand All @@ -147,6 +155,7 @@ describe("validateOptions", () => {
language: "en",
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: true,
searchResultLimits: 5,
explicitSearchResultPath: false,
Expand Down Expand Up @@ -176,6 +185,7 @@ describe("validateOptions", () => {
language: ["en"],
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: false,
highlightSearchTermsOnTargetPage: false,
searchResultLimits: 8,
explicitSearchResultPath: false,
Expand All @@ -194,6 +204,7 @@ describe("validateOptions", () => {
hashed: "filename",
searchBarPosition: "left",
searchContextByPaths: ["docs", "community"],
hideSearchBarWithNoSearchContext: true,
},
{
blogRouteBasePath: ["/dev/blog"],
Expand All @@ -207,6 +218,7 @@ describe("validateOptions", () => {
language: ["en"],
removeDefaultStopWordFilter: false,
removeDefaultStemmer: false,
hideSearchBarWithNoSearchContext: true,
highlightSearchTermsOnTargetPage: false,
searchResultLimits: 8,
explicitSearchResultPath: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const schema = Joi.object<PluginOptions>({
zhUserDict: Joi.string(),
zhUserDictPath: Joi.string(),
searchContextByPaths: Joi.array().items(Joi.string()),
hideSearchBarWithNoSearchContext: Joi.boolean().default(false),
});

export function validateOptions({
Expand Down
Loading

0 comments on commit 38908ed

Please sign in to comment.