File size: 11,059 Bytes
a21c316 | 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 | import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { ChevronDown, Check, Edit3 } from 'lucide-react';
import { cn } from '../../utils/cn';
export interface SelectOption {
value: string;
label: string;
group?: string;
}
interface GroupedSelectProps {
value: string;
onChange: (value: string) => void;
options: SelectOption[];
placeholder?: string;
className?: string;
disabled?: boolean;
allowCustomInput?: boolean; // 新增: 是否允许自定义输入
}
export default function GroupedSelect({
value,
onChange,
options,
placeholder = 'Select...',
className = '',
disabled = false,
allowCustomInput = false // 新增: 默认不允许自定义输入
}: GroupedSelectProps) {
const [isOpen, setIsOpen] = useState(false);
const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });
const [customInput, setCustomInput] = useState(''); // 新增: 自定义输入值
const containerRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null); // 新增: 下拉菜单引用
const customInputRef = useRef<HTMLInputElement>(null); // 新增: 自定义输入框引用
// 按组分组选项
const groupedOptions = options.reduce((acc, option) => {
const group = option.group || 'Other';
if (!acc[group]) {
acc[group] = [];
}
acc[group].push(option);
return acc;
}, {} as Record<string, SelectOption[]>);
// 获取当前选中项的标签
const selectedOption = options.find(opt => opt.value === value);
const selectedLabel = selectedOption?.label || value || placeholder;
// 更新下拉菜单位置
const updateDropdownPosition = () => {
if (buttonRef.current) {
const rect = buttonRef.current.getBoundingClientRect();
setDropdownPosition({
top: rect.bottom + window.scrollY + 4,
left: rect.left + window.scrollX,
width: Math.max(rect.width * 1.1, 220) // 增加宽度到 1.1 倍,最小 220px
});
}
};
// 点击外部关闭下拉菜单
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
// 修复: 检查点击是否在容器或下拉菜单内部
const target = event.target as Node;
const isClickInsideContainer = containerRef.current?.contains(target);
const isClickInsideDropdown = dropdownRef.current?.contains(target);
if (!isClickInsideContainer && !isClickInsideDropdown) {
setIsOpen(false);
}
};
if (isOpen) {
updateDropdownPosition();
document.addEventListener('mousedown', handleClickOutside);
window.addEventListener('scroll', updateDropdownPosition, true);
window.addEventListener('resize', updateDropdownPosition);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
window.removeEventListener('scroll', updateDropdownPosition, true);
window.removeEventListener('resize', updateDropdownPosition);
};
}, [isOpen]);
const handleSelect = (optionValue: string) => {
console.log('[GroupedSelect] handleSelect called:', optionValue);
onChange(optionValue);
setIsOpen(false);
};
const handleCustomInputSubmit = () => {
if (customInput.trim()) {
console.log('[GroupedSelect] Custom input submitted:', customInput.trim());
onChange(customInput.trim());
setCustomInput('');
setIsOpen(false);
}
};
const handleToggle = () => {
if (!disabled) {
setIsOpen(!isOpen);
if (!isOpen) {
updateDropdownPosition();
}
}
};
return (
<div ref={containerRef} className={cn('relative', className)}>
{/* 触发按钮 */}
<button
ref={buttonRef}
type="button"
onClick={handleToggle}
disabled={disabled}
className={cn(
'w-full px-3 py-2 text-left text-xs font-mono',
'bg-white dark:bg-gray-800',
'border border-gray-300 dark:border-gray-600',
'rounded-lg',
'flex items-center justify-between gap-2',
'transition-all duration-200',
'hover:border-blue-400 dark:hover:border-blue-500',
'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
disabled && 'opacity-50 cursor-not-allowed',
isOpen && 'ring-2 ring-blue-500 border-transparent'
)}
>
<span className="truncate text-gray-900 dark:text-gray-100">
{selectedLabel}
</span>
<ChevronDown
size={14}
className={cn(
'text-gray-500 dark:text-gray-400 transition-transform duration-200',
isOpen && 'rotate-180'
)}
/>
</button>
{/* 下拉菜单 - 使用 Portal 渲染到 body */}
{isOpen && createPortal(
<div
ref={dropdownRef}
style={{
position: 'absolute',
top: `${dropdownPosition.top}px`,
left: `${dropdownPosition.left}px`,
width: `${dropdownPosition.width}px`,
zIndex: 9999
}}
className={cn(
'bg-white dark:bg-gray-800',
'border border-gray-200 dark:border-gray-700',
'rounded-lg shadow-2xl',
'max-h-80 overflow-y-auto',
'animate-in fade-in-0 zoom-in-95 duration-100'
)}
>
{Object.entries(groupedOptions).map(([group, groupOptions]) => (
<div key={group}>
{/* 分组标题 */}
<div className="px-3 py-1.5 text-[9px] font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wider bg-gray-50 dark:bg-gray-900/50 sticky top-0 z-10">
{group}
</div>
{/* 分组选项 */}
{groupOptions.map((option) => (
<button
key={option.value}
type="button"
onClick={() => handleSelect(option.value)}
title={option.label}
className={cn(
'w-full px-3 py-1.5 text-left text-[10px] font-mono',
'flex items-center justify-between gap-2',
'transition-colors duration-150',
'hover:bg-blue-50 dark:hover:bg-blue-900/20',
option.value === value
? 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300'
: 'text-gray-900 dark:text-gray-100'
)}
>
<span className="truncate">{option.label}</span>
{option.value === value && (
<Check size={12} className="text-blue-600 dark:text-blue-400 flex-shrink-0" />
)}
</button>
))}
</div>
))}
{/* 自定义输入区域 */}
{allowCustomInput && (
<div className="border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 p-2">
<div className="flex items-center gap-1.5">
<Edit3 size={12} className="text-gray-400 dark:text-gray-500 flex-shrink-0" />
<input
ref={customInputRef}
type="text"
value={customInput}
onChange={(e) => setCustomInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleCustomInputSubmit();
}
}}
placeholder="输入自定义模型 ID..."
className={cn(
'flex-1 px-2 py-1 text-[10px] font-mono',
'bg-white dark:bg-gray-800',
'border border-gray-300 dark:border-gray-600',
'rounded focus:outline-none focus:ring-1 focus:ring-blue-500',
'text-gray-900 dark:text-gray-100',
'placeholder:text-gray-400 dark:placeholder:text-gray-500'
)}
/>
<button
type="button"
onClick={handleCustomInputSubmit}
disabled={!customInput.trim()}
className={cn(
'px-2 py-1 text-[10px] font-medium rounded',
'transition-colors duration-150',
customInput.trim()
? 'bg-blue-500 hover:bg-blue-600 text-white'
: 'bg-gray-200 dark:bg-gray-700 text-gray-400 dark:text-gray-500 cursor-not-allowed'
)}
>
确定
</button>
</div>
</div>
)}
</div>,
document.body
)}
</div>
);
}
|