Skip to content

Commit

Permalink
fix: keep search text (#684)
Browse files Browse the repository at this point in the history
  • Loading branch information
qiweiii authored Nov 22, 2022
1 parent 8b1988f commit 25ca1ed
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
21 changes: 18 additions & 3 deletions components/Search.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/router'
import Image from 'next/image'
import { OutlinedInput, InputAdornment, styled, InputBaseProps } from '@mui/material'
Expand Down Expand Up @@ -33,17 +33,32 @@ const StyledInputBase = styled((props: InputBaseProps) => <OutlinedInput {...pro
}))

const Search = () => {
const { push, asPath } = useRouter()
const { push, asPath, query } = useRouter()
const searchRef = useRef<HTMLInputElement | null>(null)
const [showClearBtn, setShowClearBtn] = useState(false)
const isHome = asPath === '/' || asPath === '/zh-CN'
const theme = useTheme()

useEffect(() => {
if (!searchRef.current) return
if (query.search) {
searchRef.current.value = (query.search as string) || ''
} else {
// on page refresh, next.js's query.search will always be null, so need this fallback
const queryValue = new URLSearchParams(window.location.search).get('search')
if (queryValue) {
searchRef.current.value = queryValue || ''
}
}
if (searchRef.current.value) {
setShowClearBtn(true)
}
}, [query, asPath])

const handleSearch = async (e: React.KeyboardEvent<HTMLInputElement>) => {
await handleSearchKeyPress(e, push)
if (e.key === 'Enter') {
searchRef.current?.blur()
searchRef.current.value = ''
setShowClearBtn(false)
}
}
Expand Down
2 changes: 1 addition & 1 deletion cypress/integration/search/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ context('Search', () => {
cy.get(`${ROOT_SELECTOR} input`).type(UNKNOWN_STRING)
cy.get(ROOT_SELECTOR).type('{enter}')
cy.url({ timeout: REDIRECT_TIMEOUT }).should('contain', `/tokens/native`)
cy.location('search').should('eq', `?name=${UNKNOWN_STRING}`)
cy.location('search').should('eq', `?name=${UNKNOWN_STRING}&search=${UNKNOWN_STRING}`)
})

it('404', () => {
Expand Down
2 changes: 1 addition & 1 deletion utils/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const handleSearchKeyPress = async (e: React.KeyboardEvent<HTMLInputEleme

if (Number.isNaN(+search)) {
// could be token name
push(`/tokens/native?name=${encodeURIComponent(search)}`)
push(`/tokens/native?name=${encodeURIComponent(search)}&search=${encodeURIComponent(search)}`)
return
}

Expand Down

0 comments on commit 25ca1ed

Please sign in to comment.