-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.tsx
More file actions
255 lines (241 loc) · 10.8 KB
/
select.tsx
File metadata and controls
255 lines (241 loc) · 10.8 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
254
255
import { Popover } from '@radix-ui/react-popover';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import { Check as DefaultCheckIcon, ChevronDown as DefaultChevronIcon } from 'lucide-react';
import * as React from 'react';
import { useOverlayTriggerState } from 'react-stately';
import { PopoverTrigger } from './popover';
import { cn } from './utils';
export interface SelectOption {
label: string;
value: string;
}
export interface SelectUIComponents {
Trigger?: React.ComponentType<React.ButtonHTMLAttributes<HTMLButtonElement> & React.RefAttributes<HTMLButtonElement>>;
Item?: React.ComponentType<
React.ButtonHTMLAttributes<HTMLButtonElement> & { selected?: boolean } & React.RefAttributes<HTMLButtonElement>
>;
SearchInput?: React.ComponentType<
React.InputHTMLAttributes<HTMLInputElement> & React.RefAttributes<HTMLInputElement>
>;
CheckIcon?: React.ComponentType<React.SVGProps<SVGSVGElement>>;
ChevronIcon?: React.ComponentType<React.SVGProps<SVGSVGElement>>;
}
export interface SelectProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'value' | 'onChange'> {
options: SelectOption[];
value?: string;
onValueChange?: (value: string) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
contentClassName?: string;
itemClassName?: string;
components?: Partial<SelectUIComponents>;
}
export function Select({
options,
value,
onValueChange,
placeholder = 'Select an option',
disabled = false,
className,
contentClassName,
itemClassName,
components,
...buttonProps
}: SelectProps) {
const popoverState = useOverlayTriggerState({});
const listboxId = React.useId();
const [query, setQuery] = React.useState('');
const [activeIndex, setActiveIndex] = React.useState(0);
const [isInitialized, setIsInitialized] = React.useState(false);
const triggerRef = React.useRef<HTMLButtonElement>(null);
const popoverRef = React.useRef<HTMLDivElement>(null);
const selectedItemRef = React.useRef<HTMLButtonElement>(null);
const listContainerRef = React.useRef<HTMLUListElement>(null);
// No need for JavaScript width measurement - Radix provides --radix-popover-trigger-width CSS variable
// Scroll to selected item when dropdown opens
React.useEffect(() => {
if (popoverState.isOpen && selectedItemRef.current) {
// Use setTimeout to ensure the DOM is fully rendered
setTimeout(() => {
selectedItemRef.current?.scrollIntoView({ block: 'nearest' });
}, 0);
}
}, [popoverState.isOpen]);
const selectedOption = options.find((o) => o.value === value);
const filtered = React.useMemo(
() => (query ? options.filter((o) => `${o.label}`.toLowerCase().includes(query.trim().toLowerCase())) : options),
[options, query],
);
// Reset activeIndex when filtered items change or dropdown opens
React.useEffect(() => {
if (popoverState.isOpen) {
setActiveIndex(0);
// Add a small delay to ensure the component is fully initialized
const timer = setTimeout(() => {
setIsInitialized(true);
}, 100);
return () => clearTimeout(timer);
} else {
setIsInitialized(false);
}
}, [filtered, popoverState.isOpen]);
// Scroll active item into view when activeIndex changes
React.useEffect(() => {
if (popoverState.isOpen && listContainerRef.current && filtered.length > 0) {
const activeElement = listContainerRef.current.querySelector(`[data-index="${activeIndex}"]`) as HTMLElement;
if (activeElement) {
activeElement.scrollIntoView({ block: 'nearest' });
}
}
}, [activeIndex, popoverState.isOpen, filtered.length]);
const Trigger =
components?.Trigger ||
React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement>>((props, ref) => (
<button ref={ref} type="button" {...props} />
));
Trigger.displayName = Trigger.displayName || 'SelectTrigger';
const Item =
components?.Item ||
React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement> & { selected?: boolean }>(
(props, ref) => <button ref={ref} type="button" {...props} />,
);
Item.displayName = Item.displayName || 'SelectItem';
const SearchInput =
components?.SearchInput ||
React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>((props, ref) => (
<input ref={ref} {...props} />
));
SearchInput.displayName = SearchInput.displayName || 'SelectSearchInput';
const CheckIcon = components?.CheckIcon || DefaultCheckIcon;
const ChevronIcon = components?.ChevronIcon || DefaultChevronIcon;
return (
<Popover open={popoverState.isOpen} onOpenChange={popoverState.setOpen}>
<PopoverTrigger asChild>
<Trigger
ref={triggerRef}
disabled={disabled}
className={cn(
'flex items-center justify-between w-full sm:text-base rounded-md border border-input bg-background px-3 py-2 h-10 text-sm ring-offset-background',
'placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
// biome-ignore lint/a11y/useAriaPropsForRole: using <button> for PopoverTrigger to ensure keyboard accessibility and focus management
// biome-ignore lint/a11y/useSemanticElements: using <button> for PopoverTrigger to ensure keyboard accessibility and focus management
role="combobox"
aria-haspopup="listbox"
aria-expanded={popoverState.isOpen}
aria-controls={listboxId}
{...buttonProps}
>
{selectedOption?.label || placeholder}
<ChevronIcon className="w-4 h-4 opacity-50" />
</Trigger>
</PopoverTrigger>
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={popoverRef}
align="start"
sideOffset={4}
className={cn(
'z-50 rounded-md border bg-popover text-popover-foreground shadow-md outline-none',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2',
'data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'p-0 shadow-md border-0',
contentClassName
)}
// biome-ignore lint/a11y/useSemanticElements: using <div> for PopoverContent to ensure keyboard accessibility and focus management
role="listbox"
id={listboxId}
style={{ width: 'var(--radix-popover-trigger-width)' }}
data-slot="popover-content"
>
<div className="bg-white p-1.5 rounded-md focus:outline-none sm:text-sm w-full">
<div className="px-1.5 pb-1.5">
<SearchInput
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
ref={(el) => {
if (el) queueMicrotask(() => el.focus());
}}
aria-activedescendant={filtered.length > 0 ? `${listboxId}-option-${activeIndex}` : undefined}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
const toSelect = filtered[activeIndex];
if (toSelect) {
onValueChange?.(toSelect.value);
setQuery('');
popoverState.close();
triggerRef.current?.focus();
}
} else if (e.key === 'Escape') {
e.preventDefault();
setQuery('');
popoverState.close();
triggerRef.current?.focus();
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (filtered.length === 0) return;
setActiveIndex((prev) => Math.min(prev + 1, filtered.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (filtered.length === 0) return;
setActiveIndex((prev) => Math.max(prev - 1, 0));
}
}}
className="w-full h-9 rounded-md bg-white px-2 text-sm leading-none focus:ring-0 focus:outline-none border-0"
/>
</div>
<ul ref={listContainerRef} className="max-h-[200px] overflow-y-auto rounded-md w-full">
{filtered.length === 0 && <li className="px-3 py-2 text-sm text-gray-500">No results.</li>}
{filtered.map((option, index) => {
const isSelected = option.value === value;
const isActive = index === activeIndex;
return (
<li key={option.value} className="list-none">
<Item
ref={isSelected ? selectedItemRef : undefined}
onClick={() => {
onValueChange?.(option.value);
setQuery('');
popoverState.close();
}}
className={cn(
'w-full text-left cursor-pointer select-none py-3 px-3 transition-colors duration-150 flex items-center gap-2 rounded',
'text-gray-900',
isSelected ? 'bg-gray-100' : 'hover:bg-gray-100',
isActive && !isSelected && 'bg-gray-50',
itemClassName,
)}
// biome-ignore lint/a11y/useSemanticElements: using <button> for PopoverTrigger to ensure keyboard accessibility and focus management
// biome-ignore lint/a11y/useAriaPropsForRole: using <button> for PopoverTrigger to ensure keyboard accessibility and focus management
role="option"
aria-selected={isSelected}
id={`${listboxId}-option-${index}`}
data-selected={isSelected ? 'true' : 'false'}
data-active={isActive ? 'true' : 'false'}
data-index={index}
data-value={option.value}
data-testid={`select-option-${option.value}`}
selected={isSelected}
>
{isSelected && <CheckIcon className="h-4 w-4 flex-shrink-0" />}
<span className={cn('block truncate', !isSelected && 'ml-6', isSelected && 'font-semibold')}>
{option.label}
</span>
</Item>
</li>
);
})}
</ul>
</div>
</PopoverPrimitive.Content>
</PopoverPrimitive.Portal>
</Popover>
);
}