forked from nodejs/nodejs.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSearchResults.ts
More file actions
75 lines (62 loc) · 2.3 KB
/
Copy pathuseSearchResults.ts
File metadata and controls
75 lines (62 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { useMemo, useCallback } from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import { Index, SerialisedIndexData } from 'elasticlunr';
import { useLocalization } from 'gatsby-theme-i18n';
import { compareTwoStrings } from 'string-similarity';
import { replaceDataTagFromString } from '../util/replaceDataTag';
import createSlug from '../../util-node/createSlug';
import { SearchResult } from '../types';
export const useSearchResults = () => {
const { locale } = useLocalization();
const { siteSearchIndex } = useStaticQuery(graphql`
query localSearchLearnPages {
siteSearchIndex {
index
}
}
`);
const resultData = siteSearchIndex.index as SerialisedIndexData<SearchResult>;
const storeIndex = useMemo(
() => Index.load<SearchResult>(resultData),
[resultData]
);
const searchResults = useCallback(
(currentQuery: string) => {
const localeResults: SearchResult[] = [];
const fallbackResults: SearchResult[] = [];
storeIndex.search(currentQuery, { expand: true }).forEach(({ ref }) => {
const result = storeIndex.documentStore.getDoc(ref) as SearchResult;
if (result.locale === locale) {
localeResults.push(result);
} else if (result.locale === 'en') {
fallbackResults.push(result);
}
});
const currentResults =
localeResults.length > 0 ? localeResults : fallbackResults;
const mapResult = (result: SearchResult) => {
if (result.tableOfContents) {
const tableArray = result.tableOfContents.split('\n');
const uniqueItems = new Set(
tableArray
.map(replaceDataTagFromString)
.filter(item => compareTwoStrings(currentQuery, item) > 0.3)
);
return [...uniqueItems].map(item => ({
title: result.title,
displayTitle: item.replace(/(`|\(.*\))/g, ''),
id: `${result.id}-${createSlug(item)}`,
slug: `${result.slug}#${createSlug(item)}`,
category: result.category,
wrapInCode: item.startsWith('`'),
locale: result.locale,
}));
}
return result;
};
return currentResults.slice(0, 20).map(mapResult).flat().slice(0, 20);
},
[storeIndex]
);
return searchResults;
};