@@ -44,6 +44,8 @@ export default function AlgoliaSearchModal({ cRef }) {
44
44
const [ useTime , setUseTime ] = useState ( 0 )
45
45
const [ activeIndex , setActiveIndex ] = useState ( 0 )
46
46
const [ isLoading , setIsLoading ] = useState ( false )
47
+ const [ isInputFocused , setIsInputFocused ] = useState ( false )
48
+
47
49
const inputRef = useRef ( null )
48
50
const router = useRouter ( )
49
51
@@ -54,53 +56,57 @@ export default function AlgoliaSearchModal({ cRef }) {
54
56
e . preventDefault ( )
55
57
setIsModalOpen ( true )
56
58
} )
57
- // 方向键调整选中
59
+ // 修改快捷键的使用逻辑
58
60
useHotkeys (
59
61
'down' ,
60
62
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
+ }
64
69
}
65
70
} ,
66
71
{ enableOnFormTags : true }
67
72
)
68
73
useHotkeys (
69
74
'up' ,
70
75
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
+ }
74
81
}
75
82
} ,
76
83
{ enableOnFormTags : true }
77
84
)
78
- // esc关闭
79
85
useHotkeys (
80
86
'esc' ,
81
87
e => {
82
- e . preventDefault ( )
83
- setIsModalOpen ( false )
88
+ if ( isInputFocused ) {
89
+ e . preventDefault ( )
90
+ setIsModalOpen ( false )
91
+ }
84
92
} ,
85
93
{ enableOnFormTags : true }
86
94
)
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跳转
95
95
useHotkeys (
96
96
'enter' ,
97
97
e => {
98
- if ( searchResults . length > 0 ) {
98
+ if ( isInputFocused && searchResults . length > 0 ) {
99
99
onJumpSearchResult ( index )
100
100
}
101
101
} ,
102
102
{ enableOnFormTags : true }
103
103
)
104
+ // 跳转Search结果
105
+ const onJumpSearchResult = ( ) => {
106
+ if ( searchResults . length > 0 ) {
107
+ window . location . href = `${ siteConfig ( 'SUB_PATH' , '' ) } /${ searchResults [ activeIndex ] . slug } `
108
+ }
109
+ }
104
110
105
111
const resetSearch = ( ) => {
106
112
setActiveIndex ( 0 )
@@ -261,6 +267,8 @@ export default function AlgoliaSearchModal({ cRef }) {
261
267
type = 'text'
262
268
placeholder = '在这里输入搜索关键词...'
263
269
onChange = { e => handleInputChange ( e ) }
270
+ onFocus = { ( ) => setIsInputFocused ( true ) } // 聚焦时
271
+ onBlur = { ( ) => setIsInputFocused ( false ) } // 失去焦点时
264
272
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'
265
273
ref = { inputRef }
266
274
/>
0 commit comments