Skip to content

Commit 1b9073f

Browse files
authored
Merge pull request #2877 from tangly1024/fix/page-scroll-by-key
修复网页无法用上下按键翻页
2 parents ab21e1f + c07aef8 commit 1b9073f

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

components/AlgoliaSearchModal.js

+27-19
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ export default function AlgoliaSearchModal({ cRef }) {
4444
const [useTime, setUseTime] = useState(0)
4545
const [activeIndex, setActiveIndex] = useState(0)
4646
const [isLoading, setIsLoading] = useState(false)
47+
const [isInputFocused, setIsInputFocused] = useState(false)
48+
4749
const inputRef = useRef(null)
4850
const router = useRouter()
4951

@@ -54,53 +56,57 @@ export default function AlgoliaSearchModal({ cRef }) {
5456
e.preventDefault()
5557
setIsModalOpen(true)
5658
})
57-
// 方向键调整选中
59+
// 修改快捷键的使用逻辑
5860
useHotkeys(
5961
'down',
6062
e => {
61-
e.preventDefault()
62-
if (activeIndex < searchResults.length - 1) {
63-
setActiveIndex(activeIndex + 1)
63+
if (isInputFocused) {
64+
// 只有在聚焦时才触发
65+
e.preventDefault()
66+
if (activeIndex < searchResults.length - 1) {
67+
setActiveIndex(activeIndex + 1)
68+
}
6469
}
6570
},
6671
{ enableOnFormTags: true }
6772
)
6873
useHotkeys(
6974
'up',
7075
e => {
71-
e.preventDefault()
72-
if (activeIndex > 0) {
73-
setActiveIndex(activeIndex - 1)
76+
if (isInputFocused) {
77+
e.preventDefault()
78+
if (activeIndex > 0) {
79+
setActiveIndex(activeIndex - 1)
80+
}
7481
}
7582
},
7683
{ enableOnFormTags: true }
7784
)
78-
// esc关闭
7985
useHotkeys(
8086
'esc',
8187
e => {
82-
e.preventDefault()
83-
setIsModalOpen(false)
88+
if (isInputFocused) {
89+
e.preventDefault()
90+
setIsModalOpen(false)
91+
}
8492
},
8593
{ enableOnFormTags: true }
8694
)
87-
88-
// 跳转Search结果
89-
const onJumpSearchResult = () => {
90-
if (searchResults.length > 0) {
91-
window.location.href = `${siteConfig('SUB_PATH', '')}/${searchResults[activeIndex].slug}`
92-
}
93-
}
94-
// enter跳转
9595
useHotkeys(
9696
'enter',
9797
e => {
98-
if (searchResults.length > 0) {
98+
if (isInputFocused && searchResults.length > 0) {
9999
onJumpSearchResult(index)
100100
}
101101
},
102102
{ enableOnFormTags: true }
103103
)
104+
// 跳转Search结果
105+
const onJumpSearchResult = () => {
106+
if (searchResults.length > 0) {
107+
window.location.href = `${siteConfig('SUB_PATH', '')}/${searchResults[activeIndex].slug}`
108+
}
109+
}
104110

105111
const resetSearch = () => {
106112
setActiveIndex(0)
@@ -261,6 +267,8 @@ export default function AlgoliaSearchModal({ cRef }) {
261267
type='text'
262268
placeholder='在这里输入搜索关键词...'
263269
onChange={e => handleInputChange(e)}
270+
onFocus={() => setIsInputFocused(true)} // 聚焦时
271+
onBlur={() => setIsInputFocused(false)} // 失去焦点时
264272
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'
265273
ref={inputRef}
266274
/>

0 commit comments

Comments
 (0)