forked from kremalicious/blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
71 lines (63 loc) · 1.87 KB
/
index.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
import React, { useState, useEffect, ReactElement } from 'react'
import { LazyMotion, domAnimation, m, useReducedMotion } from 'framer-motion'
import SearchInput from './SearchInput'
import SearchButton from './SearchButton'
import SearchResults from './SearchResults'
import * as styles from './index.module.css'
import { getAnimationProps, moveInTop } from '../../atoms/Transitions'
export default function Search(): ReactElement {
const shouldReduceMotion = useReducedMotion()
const [searchOpen, setSearchOpen] = useState(false)
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
useEffect(() => {
if (!query || !window.__LUNR__) {
setResults([])
return
}
const lunrIndex = window.__LUNR__['en']
const searchResults = lunrIndex.index.search(query)
setResults(
searchResults.map(({ ref }) => {
return lunrIndex.store[ref]
})
)
}, [query])
useEffect(() => {
if (searchOpen) {
document.body.classList.add('hasSearchOpen')
} else {
document.body.classList.remove('hasSearchOpen')
}
}, [searchOpen])
function toggleSearch(): void {
setSearchOpen(!searchOpen)
}
return (
<>
<SearchButton onClick={toggleSearch} />
{searchOpen && (
<>
<LazyMotion features={domAnimation}>
<m.section
variants={moveInTop}
{...getAnimationProps(shouldReduceMotion)}
className={styles.search}
>
<SearchInput
value={query}
onChange={(e: any) => setQuery(e.target.value)}
onToggle={toggleSearch}
/>
</m.section>
</LazyMotion>
<SearchResults
searchQuery={query}
results={results}
toggleSearch={toggleSearch}
/>
</>
)}
</>
)
}