fix(select): 修复选择组件的状态管理和事件处理

This commit is contained in:
Jeff Gu committed 2026-04-10 13:17:37 +08:00
1 parent f0e3a349eb
commit 0d6983fda4
5 files changed
+175 -114

No files matched your search

+16 -1
View File
@@ -45,6 +45,7 @@ export const AutoCompleteInput = React.forwardRef<HTMLInputElement, AutoComplete
className,
dropdownClassName,
inputClassName,
onClick,
onFocus,
onBlur,
disabled,
@@ -54,6 +55,7 @@ export const AutoCompleteInput = React.forwardRef<HTMLInputElement, AutoComplete
) => {
const containerRef = React.useRef<HTMLDivElement | null>(null)
const [isOpen, setIsOpen] = React.useState(false)
const [searchQuery, setSearchQuery] = React.useState('')
React.useEffect(() => {
const handlePointerDown = (event: MouseEvent) => {
@@ -66,7 +68,13 @@ export const AutoCompleteInput = React.forwardRef<HTMLInputElement, AutoComplete
return () => document.removeEventListener('mousedown', handlePointerDown)
}, [])
const query = normalizeText(value)
React.useEffect(() => {
if (!isOpen) {
setSearchQuery('')
}
}, [isOpen])
const query = normalizeText(searchQuery)
const dedupedOptions = options.filter((option, index) => {
return options.findIndex((candidate) => candidate.value === option.value) === index
})
@@ -84,7 +92,13 @@ export const AutoCompleteInput = React.forwardRef<HTMLInputElement, AutoComplete
ref={ref}
disabled={disabled}
value={value}
onClick={(event) => {
setSearchQuery('')
setIsOpen(true)
onClick?.(event)
}}
onFocus={(event) => {
setSearchQuery('')
setIsOpen(true)
onFocus?.(event)
}}
@@ -93,6 +107,7 @@ export const AutoCompleteInput = React.forwardRef<HTMLInputElement, AutoComplete
}}
onChange={(event) => {
onChange(event.target.value)
setSearchQuery(event.target.value)
setIsOpen(true)
}}
className={inputClassName}
+148 -106
View File
@@ -1,71 +1,70 @@
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";
import * as React from 'react'
import { Check, ChevronDown } from 'lucide-react'
import { cn } from '@/lib/utils'
type NativeSelectProps = Omit<React.ComponentProps<"select">, "children" | "onChange" | "size">;
type NativeSelectProps = Omit<React.ComponentProps<'select'>, 'children' | 'onChange' | 'size'>
interface SelectProps extends NativeSelectProps {
children: React.ReactNode;
onChange?: (event: React.ChangeEvent<HTMLSelectElement>) => void;
placeholder?: string;
contentClassName?: string;
children: React.ReactNode
onChange?: (event: React.ChangeEvent<HTMLSelectElement>) => void
placeholder?: string
contentClassName?: string
}
interface SelectOption {
value: string;
label: React.ReactNode;
disabled?: boolean;
value: string
label: React.ReactNode
disabled?: boolean
}
const TRIGGER_BASE_CLASS =
"group relative flex h-10 w-full items-center rounded-lg border border-input/90 bg-card/90 px-3 py-2 pr-12 text-sm text-foreground shadow-sm outline-none transition-all duration-200 hover:border-primary/25 hover:bg-card focus-visible:border-primary/55 focus-visible:ring-4 focus-visible:ring-primary/10 disabled:cursor-not-allowed disabled:opacity-50 data-[placeholder]:text-muted-foreground";
'group relative flex h-10 w-full items-center rounded-lg border border-input bg-transparent px-3 py-2 pr-10 text-sm text-foreground shadow-sm outline-none transition-all duration-200 hover:border-muted-foreground/30 focus-visible:border-primary/50 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50'
const CONTENT_BASE_CLASS =
"z-50 max-h-72 min-w-[var(--radix-select-trigger-width)] overflow-hidden rounded-lg border border-border/70 bg-popover/95 p-1.5 text-popover-foreground shadow-md backdrop-blur-xl 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=top]:slide-in-from-bottom-2 dark:shadow-[0_24px_70px_-24px_hsl(0_0%_0%_/_0.8)]";
'absolute z-50 mt-1 w-full overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-lg'
const ITEM_BASE_CLASS =
"relative flex w-full select-none items-center rounded-lg px-3 py-2 pr-9 text-xs text-foreground outline-none transition-all duration-150 data-[disabled]:pointer-events-none data-[disabled]:opacity-45 data-[highlighted]:bg-primary/10 data-[highlighted]:text-foreground data-[state=checked]:bg-primary/8";
'relative flex w-full select-none items-center px-3 py-2 pr-9 text-left text-sm text-foreground outline-none transition-colors duration-150 hover:bg-muted/80 disabled:cursor-not-allowed disabled:opacity-45'
const isElementOfType = (
child: React.ReactNode,
type: "option" | "optgroup",
): child is React.ReactElement<React.HTMLAttributes<HTMLElement>> => React.isValidElement(child) && child.type === type;
type: 'option' | 'optgroup'
): child is React.ReactElement<React.HTMLAttributes<HTMLElement>> => React.isValidElement(child) && child.type === type
const extractOptions = (children: React.ReactNode): SelectOption[] => {
const options: SelectOption[] = [];
const options: SelectOption[] = []
React.Children.forEach(children, (child) => {
if (!child) return;
if (!child) return
if (React.isValidElement(child) && child.type === React.Fragment) {
options.push(...extractOptions(child.props.children));
return;
options.push(...extractOptions(child.props.children))
return
}
if (isElementOfType(child, "optgroup")) {
options.push(...extractOptions(child.props.children));
return;
if (isElementOfType(child, 'optgroup')) {
options.push(...extractOptions(child.props.children))
return
}
if (!isElementOfType(child, "option")) {
return;
if (!isElementOfType(child, 'option')) {
return
}
const rawValue = child.props.value;
const rawValue = child.props.value
if (rawValue == null) {
return;
return
}
options.push({
value: String(rawValue),
label: child.props.children,
disabled: Boolean(child.props.disabled),
});
});
})
})
return options;
};
return options
}
const Select = React.forwardRef<HTMLButtonElement, SelectProps>(
(
@@ -86,102 +85,145 @@ const Select = React.forwardRef<HTMLButtonElement, SelectProps>(
onBlur,
onFocus,
onKeyDown,
placeholder = "请选择",
"aria-label": ariaLabel,
"aria-describedby": ariaDescribedBy,
"aria-labelledby": ariaLabelledBy,
placeholder = '请选择',
'aria-label': ariaLabel,
'aria-describedby': ariaDescribedBy,
'aria-labelledby': ariaLabelledBy,
},
ref,
ref
) => {
const options = React.useMemo(() => extractOptions(children), [children]);
const containerRef = React.useRef<HTMLDivElement | null>(null)
const selectedOptionRef = React.useRef<HTMLButtonElement | null>(null)
const listboxId = React.useId()
const options = React.useMemo(() => extractOptions(children), [children])
const normalizedValue = typeof value === "string" || typeof value === "number" ? String(value) : undefined;
const normalizedValue = typeof value === 'string' || typeof value === 'number' ? String(value) : undefined
const normalizedDefaultValue =
typeof defaultValue === "string" || typeof defaultValue === "number" ? String(defaultValue) : undefined;
typeof defaultValue === 'string' || typeof defaultValue === 'number' ? String(defaultValue) : undefined
const isControlled = normalizedValue !== undefined
const [internalValue, setInternalValue] = React.useState(normalizedDefaultValue)
const selectedValue = isControlled ? normalizedValue : internalValue
const selectedOption = options.find((option) => option.value === selectedValue)
const hasValue = typeof selectedValue === 'string' && selectedValue.length > 0
const [isOpen, setIsOpen] = React.useState(false)
React.useEffect(() => {
const handlePointerDown = (event: MouseEvent) => {
if (!containerRef.current?.contains(event.target as Node)) {
setIsOpen(false)
}
}
document.addEventListener('mousedown', handlePointerDown)
return () => document.removeEventListener('mousedown', handlePointerDown)
}, [])
React.useEffect(() => {
if (disabled) {
setIsOpen(false)
}
}, [disabled])
React.useEffect(() => {
if (isOpen) {
selectedOptionRef.current?.scrollIntoView({ block: 'nearest' })
}
}, [isOpen, selectedValue])
const handleValueChange = React.useCallback(
(nextValue: string) => {
if (!onChange) return;
if (!isControlled) {
setInternalValue(nextValue)
}
const syntheticEvent = {
target: { value: nextValue, name },
currentTarget: { value: nextValue, name },
} as React.ChangeEvent<HTMLSelectElement>;
if (onChange) {
const syntheticEvent = {
target: { value: nextValue, name },
currentTarget: { value: nextValue, name },
} as React.ChangeEvent<HTMLSelectElement>
onChange(syntheticEvent);
onChange(syntheticEvent)
}
setIsOpen(false)
},
[name, onChange],
);
[isControlled, name, onChange]
)
return (
<SelectPrimitive.Root
value={normalizedValue}
defaultValue={normalizedDefaultValue}
onValueChange={handleValueChange}
disabled={disabled}
name={name}
autoComplete={autoComplete}
required={required}
form={form}
dir={dir}
>
<SelectPrimitive.Trigger
<div ref={containerRef} dir={dir} className="relative w-full">
{name && (
<input
type="hidden"
name={name}
value={selectedValue ?? ''}
form={form}
autoComplete={autoComplete}
disabled={disabled}
aria-hidden="true"
data-required={required ? 'true' : undefined}
/>
)}
<button
ref={ref}
id={id}
className={cn(TRIGGER_BASE_CLASS, className)}
type="button"
disabled={disabled}
className={cn(TRIGGER_BASE_CLASS, !hasValue && 'text-muted-foreground', className)}
aria-label={ariaLabel}
aria-describedby={ariaDescribedBy}
aria-labelledby={ariaLabelledBy}
aria-expanded={isOpen}
aria-haspopup="listbox"
aria-controls={listboxId}
onClick={() => setIsOpen((open) => !open)}
onBlur={onBlur}
onFocus={onFocus}
onKeyDown={onKeyDown}
>
<SelectPrimitive.Value placeholder={placeholder} />
<SelectPrimitive.Icon asChild>
<span className="pointer-events-none absolute right-2.5 top-1/2 flex h-6 w-6 -translate-y-1/2 items-center justify-center text-muted-foreground transition-all duration-200 ">
<ChevronDown className="h-5 w-5 transition-transform duration-200 group-data-[state=open]:rotate-180" />
</span>
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
<span className="truncate">{selectedOption ? selectedOption.label : placeholder}</span>
<span className="pointer-events-none absolute right-3 top-1/2 flex -translate-y-1/2 items-center justify-center text-muted-foreground transition-all duration-200">
<ChevronDown className={cn('h-4 w-4 transition-transform duration-200', isOpen && 'rotate-180')} />
</span>
</button>
<SelectPrimitive.Portal>
<SelectPrimitive.Content
className={cn(CONTENT_BASE_CLASS, contentClassName)}
position="popper"
sideOffset={10}
collisionPadding={12}
>
<SelectPrimitive.ScrollUpButton className="flex h-8 cursor-default items-center justify-center rounded-md text-muted-foreground">
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
{isOpen && !disabled && (
<div id={listboxId} role="listbox" className={cn(CONTENT_BASE_CLASS, contentClassName)}>
<div className="max-h-72 overflow-y-auto py-1">
{options.map((option) => {
const isSelected = option.value === selectedValue
<SelectPrimitive.Viewport className="p-0.5">
{options.map((option) => (
<SelectPrimitive.Item
key={option.value}
value={option.value}
disabled={option.disabled}
className={ITEM_BASE_CLASS}
textValue={typeof option.label === "string" ? option.label : option.value}
>
<SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator className="absolute right-3 inline-flex items-center justify-center text-primary">
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
))}
</SelectPrimitive.Viewport>
return (
<button
key={option.value}
ref={isSelected ? selectedOptionRef : undefined}
type="button"
role="option"
aria-selected={isSelected}
disabled={option.disabled}
className={cn(ITEM_BASE_CLASS, isSelected && 'bg-muted/80')}
onMouseDown={(event) => event.preventDefault()}
onClick={() => handleValueChange(option.value)}
>
<span className="truncate">{option.label}</span>
{isSelected && (
<span className="absolute right-3 inline-flex items-center justify-center text-primary">
<Check className="h-4 w-4" />
</span>
)}
</button>
)
})}
</div>
</div>
)}
</div>
)
}
)
<SelectPrimitive.ScrollDownButton className="flex h-8 cursor-default items-center justify-center rounded-md text-muted-foreground">
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
</SelectPrimitive.Root>
);
},
);
Select.displayName = 'Select'
Select.displayName = "Select";
export { Select };
export { Select }