-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Initial frontend search proof of concept with Fuse.js (#3435)
Co-authored-by: Ian Jones <[email protected]>
- Loading branch information
1 parent
3c7a772
commit c0990ca
Showing
7 changed files
with
364 additions
and
117 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import Fuse, { IFuseOptions } from "fuse.js"; | ||
import { useEffect, useMemo, useState } from "react"; | ||
|
||
interface UseSearchProps<T extends object> { | ||
list: T[]; | ||
keys: string[]; | ||
} | ||
|
||
export interface SearchResult<T extends object> { | ||
item: T; | ||
key: string; | ||
matchIndices?: [number, number][]; | ||
} | ||
|
||
export type SearchResults<T extends object> = SearchResult<T>[]; | ||
|
||
export const useSearch = <T extends object>({ | ||
list, | ||
keys, | ||
}: UseSearchProps<T>) => { | ||
const [pattern, setPattern] = useState(""); | ||
const [results, setResults] = useState<SearchResults<T>>([]); | ||
|
||
const fuseOptions: IFuseOptions<T> = useMemo( | ||
() => ({ | ||
useExtendedSearch: true, | ||
includeMatches: true, | ||
minMatchCharLength: 3, | ||
keys, | ||
}), | ||
[keys], | ||
); | ||
|
||
const fuse = useMemo( | ||
() => new Fuse<T>(list, fuseOptions), | ||
[list, fuseOptions], | ||
); | ||
|
||
useEffect(() => { | ||
const fuseResults = fuse.search(pattern); | ||
setResults( | ||
fuseResults.map((result) => ({ | ||
item: result.item, | ||
key: result.matches?.[0].key || "", | ||
// We only display the first match | ||
matchIndices: | ||
(result.matches?.[0].indices as [number, number][]) || undefined, | ||
})), | ||
); | ||
}, [pattern]); | ||
|
||
return { results, search: setPattern }; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.