diff --git a/scripts/searchIndex.js b/scripts/searchIndex.js index ce24ffac..cc844525 100644 --- a/scripts/searchIndex.js +++ b/scripts/searchIndex.js @@ -37,6 +37,11 @@ const normalizePath = (path) => const normalizeText = (text) => text.replace(/\r?\n|\r/g, " ").replace(/<\/?[^>]+(>|$)/g, ""); +const keyPathMap = {}; + +const keyPathMapper = (path) => + (keyPathMap[path] ||= Object.keys(keyPathMap).length); + const createSearchIndex = (path) => { const directoryContents = readdirSync(path); const normalizedPath = normalizePath(path); @@ -46,7 +51,7 @@ const createSearchIndex = (path) => { indexData.push({ name, - path: normalizedPath, + path: keyPathMapper(normalizedPath), text: normalizeText( [ name, @@ -88,12 +93,14 @@ const createSearchIndex = (path) => { } } + const name = basename(keyPath, extname(keyPath)); + indexData.push({ - name: basename(keyPath, extname(keyPath)), - path: keyPath, + name, + path: keyPathMapper(keyPath), text: SEARCH_EXTENSIONS.index.includes(extname(entry).toLowerCase()) - ? normalizeText(readFileSync(fullPath, "utf8")) - : undefined, + ? `${name} ${normalizeText(readFileSync(fullPath, "utf8"))}` + : name, }); } }); @@ -113,9 +120,13 @@ if (!existsSync(join(PUBLIC_PATH, ".index"))) { mkdirSync(join(PUBLIC_PATH, ".index")); } +const searchJson = searchIndex.toJSON(); + +searchJson.paths = Object.keys(keyPathMap); + writeFileSync( join(PUBLIC_PATH, ".index/search.lunr.json"), - JSON.stringify(searchIndex.toJSON()), + JSON.stringify(searchJson), { flag: "w", } diff --git a/utils/search.ts b/utils/search.ts index 9ed815ee..77f3c511 100644 --- a/utils/search.ts +++ b/utils/search.ts @@ -26,6 +26,11 @@ export const SEARCH_INPUT_PROPS = { export const SEARCH_LIBS = ["/System/lunr/lunr.min.js"]; let baseIndex = Object.create(null) as Index; +let basePaths = [] as string[]; + +type ResponseIndex = Index & { + paths: string[]; +}; const search = async ( searchTerm: string, @@ -36,13 +41,17 @@ const search = async ( const response = await fetch(FILE_INDEX, HIGH_PRIORITY_REQUEST); try { - baseIndex = window.lunr?.Index.load( - JSON.parse(await response.text()) as Index - ); + const { paths, ...responseIndex } = JSON.parse( + await response.text() + ) as ResponseIndex; + + baseIndex = window.lunr?.Index.load(responseIndex); + basePaths = paths; } catch { // Failed to parse text data to JSON } } + const searchIndex = index ?? baseIndex; let results: Index.Result[] = []; const normalizedSearchTerm = searchTerm @@ -62,7 +71,14 @@ const search = async ( // Ignore search errors } - return results ?? []; + if (results) { + return results.map((result) => ({ + ...result, + ref: basePaths[result.ref as unknown as number], + })); + } + + return []; }; interface IWritableFs extends Omit {