1
0
Fork 0
blog/src/components/molecules/Search/index.tsx

72 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-01-29 22:58:19 +01:00
import React, { ReactElement, useEffect, useState } from 'react'
import { LazyMotion, domAnimation, m, useReducedMotion } from 'framer-motion'
2023-01-29 22:58:19 +01:00
import { getAnimationProps, moveInTop } from '../../atoms/Transitions'
2019-10-02 20:48:59 +02:00
import SearchButton from './SearchButton'
2023-01-29 22:58:19 +01:00
import SearchInput from './SearchInput'
2019-10-02 20:48:59 +02:00
import SearchResults from './SearchResults'
2021-03-06 01:35:05 +01:00
import * as styles from './index.module.css'
2019-10-02 20:48:59 +02:00
2020-05-22 14:38:19 +02:00
export default function Search(): ReactElement {
const shouldReduceMotion = useReducedMotion()
2019-10-02 20:48:59 +02:00
const [searchOpen, setSearchOpen] = useState(false)
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
2019-11-23 13:16:39 +01:00
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])
2022-11-19 16:09:13 +01:00
useEffect(() => {
if (searchOpen) {
document.body.classList.add('hasSearchOpen')
} else {
document.body.classList.remove('hasSearchOpen')
}
}, [searchOpen])
2021-03-15 21:01:55 +01:00
function toggleSearch(): void {
2019-10-02 20:48:59 +02:00
setSearchOpen(!searchOpen)
}
return (
<>
<SearchButton onClick={toggleSearch} />
{searchOpen && (
<>
<LazyMotion features={domAnimation}>
<m.section
variants={moveInTop}
{...getAnimationProps(shouldReduceMotion)}
className={styles.search}
>
2019-10-02 20:48:59 +02:00
<SearchInput
value={query}
2019-11-23 13:16:39 +01:00
onChange={(e: any) => setQuery(e.target.value)}
2019-10-02 20:48:59 +02:00
onToggle={toggleSearch}
/>
</m.section>
</LazyMotion>
2019-10-02 20:48:59 +02:00
<SearchResults
searchQuery={query}
results={results}
toggleSearch={toggleSearch}
/>
</>
)}
</>
)
}