/
search.tsx
272 lines (257 loc) · 7.89 KB
/
search.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import React, {
ComponentProps,
ReactElement,
Fragment,
useCallback,
useState,
useEffect,
useRef
} from 'react'
import cn from 'clsx'
import { Transition } from '@headlessui/react'
import { SpinnerIcon } from 'nextra/icons'
import { useMounted } from 'nextra/hooks'
import { Input } from './input'
import { Anchor } from './anchor'
import { renderComponent, renderString } from '../utils'
import { useConfig, useMenu } from '../contexts'
import { useRouter } from 'next/router'
import { SearchResult } from '../types'
type SearchProps = {
className?: string
overlayClassName?: string
value: string
onChange: (newValue: string) => void
loading?: boolean
results: SearchResult[]
}
const INPUTS = ['input', 'select', 'button', 'textarea']
export function Search({
className,
overlayClassName,
value,
onChange,
loading,
results
}: SearchProps): ReactElement {
const [show, setShow] = useState(false)
const config = useConfig()
const [active, setActive] = useState(0)
const router = useRouter()
const { setMenu } = useMenu()
const input = useRef<HTMLInputElement>(null)
const ulRef = useRef<HTMLUListElement>(null)
useEffect(() => {
setActive(0)
}, [value])
useEffect(() => {
const down = (e: KeyboardEvent) => {
if (
input.current &&
document.activeElement &&
!INPUTS.includes(document.activeElement.tagName.toLowerCase())
) {
if (e.key === '/' || (e.key === 'k' && e.metaKey)) {
e.preventDefault()
input.current.focus()
} else if (e.key === 'Escape') {
setShow(false)
input.current.blur()
}
}
}
window.addEventListener('keydown', down)
return () => window.removeEventListener('keydown', down)
}, [])
const handleKeyDown = useCallback<
NonNullable<ComponentProps<'input'>['onKeyDown']>
>(
e => {
switch (e.key) {
case 'ArrowDown': {
e.preventDefault()
if (active + 1 < results.length) {
setActive(active + 1)
const activeElement = ulRef.current?.querySelector(
`li:nth-of-type(${active + 2}) > a`
)
activeElement?.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
})
}
break
}
case 'ArrowUp': {
e.preventDefault()
if (active - 1 >= 0) {
setActive(active - 1)
const activeElement = ulRef.current?.querySelector(
`li:nth-of-type(${active}) > a`
)
activeElement?.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
})
}
break
}
case 'Enter': {
router.push(results[active].route)
finishSearch()
break
}
case 'Escape': {
setShow(false)
input.current?.blur()
break
}
}
},
[active, results, router]
)
const finishSearch = () => {
input.current?.blur()
onChange('')
setShow(false)
setMenu(false)
}
const mounted = useMounted()
const renderList = show && Boolean(value)
const icon = (
<Transition
show={mounted && (!show || Boolean(value))}
as={React.Fragment}
enter="transition-opacity"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<kbd
className={cn(
'absolute ltr:right-1.5 rtl:left-1.5 my-1.5 select-none',
'rounded bg-white px-1.5 h-5 font-mono font-medium text-gray-500 text-[10px]',
'border dark:bg-dark/50 dark:border-gray-100/20',
'contrast-more:border-current contrast-more:text-current contrast-more:dark:border-current',
'items-center gap-1 transition-opacity',
value
? 'cursor-pointer hover:opacity-70 z-20 flex'
: 'hidden sm:flex pointer-events-none'
)}
title={value ? 'Clear' : undefined}
onClick={() => {
onChange('')
}}
>
{value
? 'ESC'
: mounted &&
(navigator.userAgent.includes('Macintosh') ? (
<>
<span className="text-xs">⌘</span>K
</>
) : (
'CTRL K'
))}
</kbd>
</Transition>
)
const handleMouseMove = useCallback<
NonNullable<ComponentProps<'a'>['onMouseMove']>
>(e => {
const { index } = e.currentTarget.dataset
setActive(Number(index))
}, [])
const handleFocusAndBlur = useCallback<
NonNullable<ComponentProps<'input'>['onFocus']>
>(e => {
const isFocus = e.type === 'focus'
setShow(isFocus)
}, [])
return (
<div className={cn('nextra-search relative md:w-64', className)}>
{renderList && (
<div className="fixed inset-0 z-10" onClick={() => setShow(false)} />
)}
<Input
ref={input}
value={value}
onChange={e => {
const { value } = e.target
onChange(value)
setShow(Boolean(value))
}}
type="search"
placeholder={renderString(config.search.placeholder)}
onKeyDown={handleKeyDown}
onFocus={handleFocusAndBlur}
onBlur={handleFocusAndBlur}
suffix={icon}
/>
<Transition
show={renderList}
as={Fragment}
leave="transition-opacity duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{/* Transition.Child is required here, otherwise popup will be still present in DOM after focus out */}
<Transition.Child>
<ul
className={cn(
// Using bg-white as background-color when the browser didn't support backdrop-filter
'bg-white text-gray-100 ring-1 ring-black/5',
'dark:bg-neutral-900 dark:ring-white/10',
'absolute top-full z-20 mt-2 overscroll-contain rounded-xl py-2.5 shadow-xl overflow-auto',
'max-h-[min(calc(50vh-11rem-env(safe-area-inset-bottom)),400px)]',
'md:max-h-[min(calc(100vh-5rem-env(safe-area-inset-bottom)),400px)]',
'right-0 left-0 ltr:md:left-auto rtl:md:right-auto',
'contrast-more:border contrast-more:border-gray-900 contrast-more:dark:border-gray-50',
overlayClassName
)}
ref={ulRef}
style={{
transition: 'max-height .2s ease' // don't work with tailwindcss
}}
>
{loading ? (
<span className="flex select-none justify-center p-8 text-center text-sm text-gray-400 gap-2">
<SpinnerIcon className="h-5 w-5 animate-spin" />
Loading...
</span>
) : results.length > 0 ? (
results.map(({ route, prefix, children, id }, i) => (
<Fragment key={id}>
{prefix}
<li
className={cn(
'mx-2.5 px-2.5 py-2 rounded-md break-words',
'contrast-more:border',
i === active
? 'bg-primary-500/10 text-primary-500 contrast-more:border-primary-500'
: 'text-gray-800 dark:text-gray-300 contrast-more:border-transparent'
)}
>
<Anchor
className="block scroll-m-12"
href={route}
data-index={i}
onMouseMove={handleMouseMove}
onClick={finishSearch}
>
{children}
</Anchor>
</li>
</Fragment>
))
) : (
renderComponent(config.search.emptyResult)
)}
</ul>
</Transition.Child>
</Transition>
</div>
)
}