Skip to content

Commit

Permalink
修复网页无法用上下按键翻页
Browse files Browse the repository at this point in the history
  • Loading branch information
tangly1024 committed Oct 22, 2024
1 parent ab21e1f commit c07aef8
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions components/AlgoliaSearchModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export default function AlgoliaSearchModal({ cRef }) {
const [useTime, setUseTime] = useState(0)
const [activeIndex, setActiveIndex] = useState(0)
const [isLoading, setIsLoading] = useState(false)
const [isInputFocused, setIsInputFocused] = useState(false)

const inputRef = useRef(null)
const router = useRouter()

Expand All @@ -54,53 +56,57 @@ export default function AlgoliaSearchModal({ cRef }) {
e.preventDefault()
setIsModalOpen(true)
})
// 方向键调整选中
// 修改快捷键的使用逻辑
useHotkeys(
'down',
e => {
e.preventDefault()
if (activeIndex < searchResults.length - 1) {
setActiveIndex(activeIndex + 1)
if (isInputFocused) {
// 只有在聚焦时才触发
e.preventDefault()
if (activeIndex < searchResults.length - 1) {
setActiveIndex(activeIndex + 1)
}
}
},
{ enableOnFormTags: true }
)
useHotkeys(
'up',
e => {
e.preventDefault()
if (activeIndex > 0) {
setActiveIndex(activeIndex - 1)
if (isInputFocused) {
e.preventDefault()
if (activeIndex > 0) {
setActiveIndex(activeIndex - 1)
}
}
},
{ enableOnFormTags: true }
)
// esc关闭
useHotkeys(
'esc',
e => {
e.preventDefault()
setIsModalOpen(false)
if (isInputFocused) {
e.preventDefault()
setIsModalOpen(false)
}
},
{ enableOnFormTags: true }
)

// 跳转Search结果
const onJumpSearchResult = () => {
if (searchResults.length > 0) {
window.location.href = `${siteConfig('SUB_PATH', '')}/${searchResults[activeIndex].slug}`
}
}
// enter跳转
useHotkeys(
'enter',
e => {
if (searchResults.length > 0) {
if (isInputFocused && searchResults.length > 0) {
onJumpSearchResult(index)
}
},
{ enableOnFormTags: true }
)
// 跳转Search结果
const onJumpSearchResult = () => {
if (searchResults.length > 0) {
window.location.href = `${siteConfig('SUB_PATH', '')}/${searchResults[activeIndex].slug}`
}
}

const resetSearch = () => {
setActiveIndex(0)
Expand Down Expand Up @@ -261,6 +267,8 @@ export default function AlgoliaSearchModal({ cRef }) {
type='text'
placeholder='在这里输入搜索关键词...'
onChange={e => handleInputChange(e)}
onFocus={() => setIsInputFocused(true)} // 聚焦时
onBlur={() => setIsInputFocused(false)} // 失去焦点时
className='text-black dark:text-gray-200 bg-gray-50 dark:bg-gray-600 outline-blue-500 w-full px-4 my-2 py-1 mb-4 border rounded-md'
ref={inputRef}
/>
Expand Down

0 comments on commit c07aef8

Please sign in to comment.