-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch.tsx
97 lines (84 loc) · 2.45 KB
/
Search.tsx
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { type ReactElement, useEffect, useState } from 'react'
import Fuse from 'fuse.js'
import { useStore } from '@nanostores/react'
import { isSearchOpen } from '@stores/search'
import SearchResults from './Results'
import styles from './Search.module.css'
import type { CollectionEntry } from 'astro:content'
import Input from '@components/Input'
export type Post = CollectionEntry<'articles' | 'links' | 'photos'>
// Configures fuse.js.
// https://fusejs.io/api/options.html
const fuseOptions = {
keys: ['data.title', 'data.lead', 'slug'],
includeMatches: true,
minMatchCharLength: 2,
threshold: 0.5
}
export default function Search(): ReactElement {
const $isSearchOpen = useStore(isSearchOpen)
const [query, setQuery] = useState('')
const [results, setResults] = useState<Post[]>()
const [allPosts, setAllPosts] = useState<Post[]>()
// Fetches all post data on open.
useEffect(() => {
if (!$isSearchOpen) return
fetch('/api/posts')
.then((res) => res.json())
.then((json) => setAllPosts(json))
}, [$isSearchOpen])
// Handles search and sets results.
const fuse = allPosts ? new Fuse(allPosts, fuseOptions) : null
useEffect(() => {
if (!query || query === '' || !fuse) {
setResults([])
return
}
const results = fuse
.search(query)
.map((result) => result.item)
.slice(0, 6)
setResults(results)
}, [query])
// Animates closing (search).
async function toggleSearch(): Promise<void> {
isSearchOpen.set(!$isSearchOpen)
}
return $isSearchOpen ? (
<>
<form className={styles.search}>
<Input
className={styles.searchInput}
type="search"
placeholder="Search for literally everything"
autoFocus
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button
type="button"
className={styles.searchInputClose}
onClick={toggleSearch}
title="Close search"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
</form>
<SearchResults query={query} results={results} />
</>
) : (
<></>
)
}