1- import { useMemo } from 'react' ;
1+ import { useMemo , useCallback } from 'react' ;
22import { graphql , useStaticQuery } from 'gatsby' ;
33import { Index , SerialisedIndexData } from 'elasticlunr' ;
44import { compareTwoStrings } from 'string-similarity' ;
@@ -22,34 +22,38 @@ export const useSearchResults = () => {
2222 [ resultData ]
2323 ) ;
2424
25- return ( currentQuery : string ) => {
26- const currentResults = storeIndex
27- . search ( currentQuery , { expand : true } )
28- . map ( ( { ref } ) => storeIndex . documentStore . getDoc ( ref ) as SearchResult ) ;
29-
30- const mapResult = ( result : SearchResult ) => {
31- if ( result . tableOfContents ) {
32- const tableArray = result . tableOfContents . split ( '\n' ) ;
33-
34- const uniqueItems = new Set (
35- tableArray
36- . map ( replaceDataTagFromString )
37- . filter ( item => compareTwoStrings ( currentQuery , item ) > 0.3 )
38- ) ;
39-
40- return [ ...uniqueItems ] . map ( item => ( {
41- title : result . title ,
42- displayTitle : item . replace ( / ( ` | \( .* \) ) / g, '' ) ,
43- id : `${ result . id } -${ createSlug ( item ) } ` ,
44- slug : `${ result . slug } #${ createSlug ( item ) } ` ,
45- category : result . category ,
46- wrapInCode : item . startsWith ( '`' ) ,
47- } ) ) ;
48- }
49-
50- return result ;
51- } ;
52-
53- return currentResults . slice ( 0 , 20 ) . map ( mapResult ) . flat ( ) . slice ( 0 , 20 ) ;
54- } ;
25+ const searchResults = useCallback (
26+ ( currentQuery : string ) => {
27+ const currentResults = storeIndex
28+ . search ( currentQuery , { expand : true } )
29+ . map ( ( { ref } ) => storeIndex . documentStore . getDoc ( ref ) as SearchResult ) ;
30+
31+ const mapResult = ( result : SearchResult ) => {
32+ if ( result . tableOfContents ) {
33+ const tableArray = result . tableOfContents . split ( '\n' ) ;
34+
35+ const uniqueItems = new Set (
36+ tableArray
37+ . map ( replaceDataTagFromString )
38+ . filter ( item => compareTwoStrings ( currentQuery , item ) > 0.3 )
39+ ) ;
40+
41+ return [ ...uniqueItems ] . map ( item => ( {
42+ title : result . title ,
43+ displayTitle : item . replace ( / ( ` | \( .* \) ) / g, '' ) ,
44+ id : `${ result . id } -${ createSlug ( item ) } ` ,
45+ slug : `${ result . slug } #${ createSlug ( item ) } ` ,
46+ category : result . category ,
47+ wrapInCode : item . startsWith ( '`' ) ,
48+ } ) ) ;
49+ }
50+
51+ return result ;
52+ } ;
53+
54+ return currentResults . slice ( 0 , 20 ) . map ( mapResult ) . flat ( ) . slice ( 0 , 20 ) ;
55+ } ,
56+ [ storeIndex ]
57+ ) ;
58+ return searchResults ;
5559} ;
0 commit comments