import { useEffect, useRef } from 'react'
import { useLocation } from 'react-router-dom'
const SEARCH_FIELDS = ['name', 'title', 'q']
const getSearchValue = (filter) => {
for (const field of SEARCH_FIELDS) {
if (filter[field]) return filter[field]
}
return ''
}
export const useSearchRefocus = () => {
const location = useLocation()
const prevSearchValue = useRef(null)
useEffect(() => {
const params = new URLSearchParams(location.search)
const filterStr = params.get('filter') || '{}'
let filter = {}
try {
filter = JSON.parse(filterStr)
} catch (e) {
}
const searchValue = getSearchValue(filter)
if (prevSearchValue.current && !searchValue) {
requestAnimationFrame(() => {
const input = document.querySelector('[class*="RaSearchInput"] input')
if (input) {
input.focus()
}
})
}
prevSearchValue.current = searchValue
}, [location.search])
}