forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombobox-input.tsx
More file actions
253 lines (232 loc) · 7.9 KB
/
Copy pathcombobox-input.tsx
File metadata and controls
253 lines (232 loc) · 7.9 KB
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
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Check, ChevronsUpDown } from 'lucide-react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
export type ComboboxInputOption = {
value: string
label: string
icon?: React.ReactNode
}
interface ComboboxInputProps {
options: ComboboxInputOption[]
value?: string
onValueChange: (value: string) => void
placeholder?: string
emptyText?: string
className?: string
id?: string
allowCustomValue?: boolean
openOnFocus?: boolean
}
export function ComboboxInput({
options,
value = '',
onValueChange,
placeholder = 'Select or type...',
emptyText = 'No option found.',
className,
id,
allowCustomValue = false,
openOnFocus = true,
}: ComboboxInputProps) {
const { t } = useTranslation()
const [open, setOpen] = React.useState(false)
const [searchValue, setSearchValue] = React.useState('')
const [highlightedIndex, setHighlightedIndex] = React.useState(-1)
const containerRef = React.useRef<HTMLDivElement>(null)
const inputRef = React.useRef<HTMLInputElement>(null)
const listRef = React.useRef<HTMLUListElement>(null)
const pointerFocusRef = React.useRef(false)
const selectedOption = React.useMemo(
() => options.find((option) => option.value === value),
[options, value]
)
const displayValue = open ? searchValue : (selectedOption?.label ?? value)
const filteredOptions = React.useMemo(() => {
if (!searchValue.trim()) return options
const search = searchValue.toLowerCase().trim()
return options.filter(
(option) =>
option.label.toLowerCase().includes(search) ||
option.value.toLowerCase().includes(search)
)
}, [options, searchValue])
// Reset highlight when filtered options change
React.useEffect(() => {
setHighlightedIndex(-1)
}, [filteredOptions])
// Handle click outside to close
React.useEffect(() => {
if (!open) return
const handleClickOutside = (e: MouseEvent) => {
if (
containerRef.current &&
!containerRef.current.contains(e.target as Node)
) {
setOpen(false)
setSearchValue('')
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [open])
const handleSelect = (selectedValue: string) => {
onValueChange(selectedValue)
setOpen(false)
setSearchValue('')
inputRef.current?.focus()
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
setOpen(true)
return
}
if (!open) return
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
setHighlightedIndex((prev) =>
prev < filteredOptions.length - 1 ? prev + 1 : 0
)
break
case 'ArrowUp':
e.preventDefault()
setHighlightedIndex((prev) =>
prev > 0 ? prev - 1 : filteredOptions.length - 1
)
break
case 'Enter':
e.preventDefault()
if (highlightedIndex >= 0 && filteredOptions[highlightedIndex]) {
handleSelect(filteredOptions[highlightedIndex].value)
} else if (allowCustomValue && searchValue.trim()) {
handleSelect(searchValue.trim())
} else {
// No highlighted option, just close the dropdown and keep current value
setOpen(false)
setSearchValue('')
}
break
case 'Escape':
e.preventDefault()
setOpen(false)
setSearchValue('')
break
}
}
// Scroll highlighted item into view
React.useEffect(() => {
if (highlightedIndex < 0 || !listRef.current) return
const item = listRef.current.children[highlightedIndex] as HTMLElement
item?.scrollIntoView({ block: 'nearest' })
}, [highlightedIndex])
const showDropdown =
open &&
(filteredOptions.length > 0 || (allowCustomValue && searchValue.trim()))
return (
<div ref={containerRef} className='relative'>
<Input
ref={inputRef}
id={id}
type='text'
role='combobox'
aria-expanded={open}
aria-haspopup='listbox'
aria-autocomplete='list'
autoComplete='off'
placeholder={placeholder}
value={displayValue}
onChange={(e) => {
const nextValue = e.target.value
setSearchValue(nextValue)
if (allowCustomValue) {
onValueChange(nextValue)
}
if (!open) setOpen(true)
}}
onPointerDown={() => {
pointerFocusRef.current = true
if (document.activeElement === inputRef.current && !open) {
setOpen(true)
}
}}
onFocus={() => {
setSearchValue(allowCustomValue && !selectedOption ? value : '')
if (openOnFocus || pointerFocusRef.current) {
setOpen(true)
}
pointerFocusRef.current = false
}}
onKeyDown={handleKeyDown}
className={cn('pr-9', className)}
/>
<ChevronsUpDown className='pointer-events-none absolute top-1/2 right-3 size-4 shrink-0 -translate-y-1/2 opacity-50' />
{showDropdown && (
<div className='bg-popover text-popover-foreground absolute top-full z-100 mt-1 w-full rounded-md border shadow-md'>
{filteredOptions.length > 0 ? (
<ul
ref={listRef}
role='listbox'
className='max-h-[200px] overflow-y-auto p-1'
>
{filteredOptions.map((option, index) => (
<li
key={option.value}
role='option'
aria-selected={value === option.value}
data-highlighted={index === highlightedIndex}
className={cn(
'relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm select-none',
index === highlightedIndex &&
'bg-accent text-accent-foreground',
value === option.value && 'font-medium'
)}
onMouseEnter={() => setHighlightedIndex(index)}
onMouseDown={(e) => {
e.preventDefault() // Prevent blur
handleSelect(option.value)
}}
>
<Check
className={cn(
'size-4 shrink-0',
value === option.value ? 'opacity-100' : 'opacity-0'
)}
/>
{option.icon && <span>{option.icon}</span>}
<span className='truncate'>{option.label}</span>
</li>
))}
</ul>
) : (
<div className='px-2 py-6 text-center text-sm'>
{t(emptyText)}
{allowCustomValue && searchValue.trim() && (
<div className='text-muted-foreground mt-1 text-xs'>
{t('Press Enter to use "{{value}}"', {
value: searchValue.trim(),
})}
</div>
)}
</div>
)}
</div>
)}
</div>
)
}