index.tsx raw
1 import SearchBar, { TSearchBarRef } from '@/components/SearchBar'
2 import SearchResult from '@/components/SearchResult'
3 import PrimaryPageLayout, { TPrimaryPageLayoutRef } from '@/layouts/PrimaryPageLayout'
4 import { usePrimaryPage } from '@/PageManager'
5 import { TPageRef, TSearchParams } from '@/types'
6 import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
7
8 const SearchPage = forwardRef<TPageRef>((_, ref) => {
9 const { current, display } = usePrimaryPage()
10 const [input, setInput] = useState('')
11 const [searchParams, setSearchParams] = useState<TSearchParams | null>(null)
12 const isActive = useMemo(() => current === 'search' && display, [current, display])
13 const searchBarRef = useRef<TSearchBarRef>(null)
14 const layoutRef = useRef<TPrimaryPageLayoutRef>(null)
15
16 useImperativeHandle(
17 ref,
18 () => ({
19 scrollToTop: (behavior: ScrollBehavior = 'smooth') => layoutRef.current?.scrollToTop(behavior)
20 }),
21 []
22 )
23
24 useEffect(() => {
25 if (isActive && !searchParams) {
26 searchBarRef.current?.focus()
27 }
28 }, [isActive, searchParams])
29
30 const onSearch = (params: TSearchParams | null) => {
31 setSearchParams(params)
32 if (params?.input) {
33 setInput(params.input)
34 }
35 layoutRef.current?.scrollToTop('instant')
36 }
37
38 return (
39 <PrimaryPageLayout
40 ref={layoutRef}
41 pageName="search"
42 titlebar={
43 <SearchBar ref={searchBarRef} onSearch={onSearch} input={input} setInput={setInput} />
44 }
45 displayScrollToTopButton
46 >
47 <SearchResult searchParams={searchParams} />
48 </PrimaryPageLayout>
49 )
50 })
51 SearchPage.displayName = 'SearchPage'
52 export default SearchPage
53