import { renderSelectionTags } from "../utils/selection-tags"; import { useValue } from "../utils/use-value"; import { resolveTheme, useFormAppearance } from "../config/use-config-appearance"; import clsx from "clsx"; import { createFormFieldComponent } from "../form/field-context"; import { ChevronDown, CircleX, Loading } from "kui-icons"; import React, { useContext, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react"; import Popup, { type PopupRef } from "../popup"; import { ConfigContext, DEFAULT_LOCALE } from "../config/config-context"; import Empty from "../empty"; import Icon, { type IconType } from "../icon"; import { isEmpty } from "../utils/number"; import { getChildren } from "../utils/react-node"; import Option, { type OptionSelectEvent } from "./option"; import VirtualList, { type VirtualListRef } from "../virtual-list"; import type { DropPlacementsType, ShapeType, SizeType, ThemeType } from "../const/types"; export interface SelectOption { label: string | number; value: string | number; disabled?: boolean; } export type SelectValue = string | number | (string | number)[] | undefined; type SelectPrimitive = string | number; const normalizeValue = (value: SelectValue): SelectPrimitive[] => { if (Array.isArray(value)) return value; if (isEmpty(value)) return []; return typeof value === "string" || typeof value === "number" ? [value] : []; }; // `Object.is` rather than `!==`: two NaN labels are the same retained label, and treating them as // different would make the render-phase sync below never settle. const isSameLabelMap = ( next: Map, previous: Map, ) => next.size === previous.size && [...next].every(([val, label]) => previous.has(val) && Object.is(previous.get(val), label)); export interface SelectProps extends Omit< React.HTMLAttributes, "onChange" | "onSelect" | "defaultValue" | "defaultChecked" > { placeholder?: string; size?: SizeType; placement?: DropPlacementsType; /** 关闭后是否销毁面板内容。默认销毁(重开时重新挂载);设为 false 可保留面板内的表单状态,代价是每个打开过的实例留一份隐藏 DOM。 */ destroyOnClose?: boolean; width?: number; maxTagCount?: number; value?: SelectValue; open?: boolean; clearable?: boolean; filterable?: boolean; /** Allow creating a new option from the search text in multiple mode. */ allowCreate?: boolean; block?: boolean; disabled?: boolean; readOnly?: boolean; multiple?: boolean; loading?: boolean; bordered?: boolean; extendWidth?: boolean; showArrow?: boolean; options?: SelectOption[]; theme?: ThemeType; emptyText?: string; loadingText?: string; icon?: IconType[]; shape?: ShapeType; virtual?: boolean; itemHeight?: number; overscan?: number; arrowIcon?: IconType[]; onSearch?: (e: React.ChangeEvent) => void; onChange?: (value: SelectValue) => void; onSelect?: (option: SelectOption & { selected: boolean }) => void; onClear?: () => void; onOpenChange?: (opened: boolean) => void; children?: React.ReactNode; } const Select: React.FC = ({ placeholder, size: sizeProp, placement = "bottom-left", destroyOnClose = true, width, maxTagCount, value, open: openProp, clearable = true, filterable = false, allowCreate = false, block = false, disabled = false, readOnly = false, multiple = false, loading = false, bordered = true, extendWidth = true, showArrow = true, options, theme: themeProp, emptyText, loadingText, icon, shape: shapeProp, virtual = false, itemHeight = 33, overscan = 5, arrowIcon, onSearch, onChange, onSelect, onClear: onClearCallback, onOpenChange, children, className = "", style, ...rest }) => { const inheritedAppearance = useFormAppearance(); const size = sizeProp ?? inheritedAppearance.size; const theme = resolveTheme(themeProp ?? inheritedAppearance.theme, "fill"); const shape = shapeProp ?? inheritedAppearance.shape; const config = useContext(ConfigContext); const locale = config?.locale || DEFAULT_LOCALE; const [innerVisible, setInnerVisible] = useValue(openProp, (next) => next ?? false); const visible = innerVisible; const setVisible = (next: boolean) => { setInnerVisible(next); }; const [currentValue, setInternalValue] = useValue(value, (next) => multiple ? (Array.isArray(next) ? next : []) : normalizeValue(next), ); const [queryInputVisible, setQueryInputVisible] = useState(false); const [queryKey, setQueryKey] = useState(""); const [createdOptions, setCreatedOptions] = useState([]); const popup = useRef(null); const [activeIndex, setActiveIndex] = useState(-1); const refPopper = useRef(null); const refSelection = useRef(null); const queryInputRef = useRef(null); const queryInputMirrorRef = useRef(null); const queryInputEventTimer = useRef | null>(null); const clearQueryTimer = useRef | null>(null); const virtualListRef = useRef(null); const hasSearchEvent = !!onSearch; const searchable = filterable || hasSearchEvent || (multiple && allowCreate); const updatePosition = useCallback(() => popup.current?.updatePosition(), []); useEffect( () => () => { if (queryInputEventTimer.current) clearTimeout(queryInputEventTimer.current); if (clearQueryTimer.current) clearTimeout(clearQueryTimer.current); }, [], ); const optionsData = useMemo(() => { if (loading) return []; let source: SelectOption[]; if (options && options.length > 0) { source = options; } else { source = []; getChildren(children).forEach((child) => { if (React.isValidElement>(child)) { const childProps = child.props; const { label, value: val, disabled: d } = childProps; const candidateLabel = label ?? childProps.children ?? val; source.push({ value: val, disabled: d, label: typeof candidateLabel === "string" || typeof candidateLabel === "number" ? candidateLabel : val, }); } }); } return [ ...source, ...createdOptions.filter( (created) => !source.some((option) => option.value === created.value), ), ]; }, [options, loading, children, createdOptions]); const scrollOptionIntoView = (index: number) => { if (virtual) { virtualListRef.current?.scrollToIndex(index, "auto"); return; } const containerEl = refPopper.current; if (!containerEl || !containerEl.children[0]) return; const optionEl = containerEl.querySelectorAll(".k-select-item")[index]; if (!optionEl) return; const optionTop = optionEl.offsetTop; const optionHeight = optionEl.offsetHeight; const containerHeight = containerEl.clientHeight; const targetScroll = optionTop - containerHeight / 2 + optionHeight / 2; containerEl.scrollTop = targetScroll; }; const [selectedLabels, setSelectedLabels] = useState( () => new Map(), ); // Search results are transient. Retain labels only for values that remain selected. const lookup = new Map( (loading && options ? options : optionsData).map((item) => [item.value, item.label]), ); const nextLabels = new Map( currentValue.map((val) => [val, lookup.get(val) ?? selectedLabels.get(val) ?? val]), ); // This sync runs during render, so React retries the component until the guard stops firing: // compare entries with `Object.is`, because `NaN !== NaN` would re-queue forever and React // throws "Too many re-renders". A `NaN` value or label is reachable via `Number(rawId)`. if (!isSameLabelMap(nextLabels, selectedLabels)) { setSelectedLabels(nextLabels); } const labelText = currentValue.map((val) => nextLabels.get(val)!); const isChecked = (val: string | number) => { if (multiple) { return currentValue.indexOf(val) >= 0; } else { return !isEmpty(currentValue) && currentValue[0] === val; } }; function clearQuery() { setActiveIndex(-1); if (searchable) { if (clearQueryTimer.current) clearTimeout(clearQueryTimer.current); clearQueryTimer.current = setTimeout(() => { setQueryKey(""); if (queryInputRef.current) { queryInputRef.current.value = ""; queryInputRef.current.style.width = ""; } setQueryInputVisible(false); }, 300); } } const onMouseenter = (index: number) => { setActiveIndex(index); }; function handleSelect(item: OptionSelectEvent) { if (disabled || readOnly) return; const { value: val, label: lbl } = item; let selected = true; let nextValue = [...currentValue]; if (multiple) { const idx = nextValue.indexOf(val); if (idx >= 0) { selected = false; nextValue = nextValue.filter((v) => v !== val); } else { nextValue.push(val); } setTimeout(updatePosition, 0); if (searchable) { if (queryInputRef.current) { queryInputRef.current.value = ""; queryInputRef.current.style.width = ""; } setQueryKey(""); setActiveIndex(optionsData.findIndex((option) => option.value === val)); showQuery(); } } else { nextValue = [val]; setVisible(false); onOpenChange?.(false); clearQuery(); setActiveIndex(-1); } setInternalValue(nextValue); const outputValue = multiple ? nextValue : nextValue[0]; onChange?.(outputValue); onSelect?.({ value: val, label: lbl, selected }); } const searchInput = (e: React.ChangeEvent) => { if (disabled || readOnly) return; const target = e.target; const v = target.value; setQueryKey(v); setActiveIndex(-1); if (hasSearchEvent) { if (queryInputEventTimer.current) clearTimeout(queryInputEventTimer.current); queryInputEventTimer.current = setTimeout(() => { setVisible(true); onOpenChange?.(true); onSearch?.(e); }, 500); } }; const emptyClick = () => { if (queryInputVisible) { setTimeout(() => { queryInputRef.current?.focus(); }); } }; const removeTag = (index: number) => { if (disabled || readOnly) return; const nextValue = [...currentValue]; nextValue.splice(index, 1); setInternalValue(nextValue); onChange?.(multiple ? nextValue : nextValue[0]); setTimeout(updatePosition, 0); }; const onClear = (e: React.SyntheticEvent) => { if (disabled || readOnly) return; e.stopPropagation(); const nextValue: (string | number)[] = []; setInternalValue(nextValue); onClearCallback?.(); onChange?.(multiple ? nextValue : undefined); clearQuery(); }; const showQuery = () => { if (searchable) { setQueryInputVisible(true); setTimeout(() => { queryInputRef.current?.focus(); }, 0); } }; function toggle(show: boolean | null = null) { if (disabled || readOnly) return; if (hasSearchEvent) { showQuery(); return; } const nextVisible = show ?? !visible; setVisible(nextVisible); onOpenChange?.(nextVisible); if (nextVisible) showQuery(); else clearQuery(); } function filterOptions() { const key = queryKey; const filter = filterable && key.trim() !== ""; return filter ? optionsData.filter((item) => String(item.label).toLowerCase().includes(key.toLowerCase())) : optionsData; } useLayoutEffect(() => { if (queryInputVisible && queryInputMirrorRef.current && queryInputRef.current) { const availableWidth = Math.max((refSelection.current?.clientWidth || 0) - 40, 7); const contentWidth = Math.max(queryInputMirrorRef.current.offsetWidth + 2, 7); queryInputRef.current.style.width = `${Math.min(contentWidth, availableWidth)}px`; } if (visible) updatePosition(); }, [visible, queryInputVisible, queryKey, optionsData, loading, updatePosition]); const moveActive = (direction: 1 | -1) => { const filtered = filterOptions(); if (!filtered.length) { setActiveIndex(-1); return; } let index = activeIndex; for (let count = 0; count < filtered.length; count += 1) { index = (index + direction + filtered.length) % filtered.length; if (!filtered[index]?.disabled) { setActiveIndex(index); setTimeout(() => scrollOptionIntoView(index), 0); return; } } }; const resetQueryInput = () => { setQueryKey(""); if (queryInputRef.current) { queryInputRef.current.value = ""; queryInputRef.current.style.width = ""; } }; const createFromQuery = () => { if (!multiple || !allowCreate) return false; const newValue = queryKey.trim(); if (!newValue) return false; const normalized = newValue.toLocaleLowerCase(); const existing = optionsData.find( (option) => String(option.value).trim().toLocaleLowerCase() === normalized || String(option.label).trim().toLocaleLowerCase() === normalized, ); if (existing) { if (!existing.disabled && !isChecked(existing.value)) handleSelect(existing); else { resetQueryInput(); setActiveIndex(optionsData.findIndex((option) => option.value === existing.value)); showQuery(); } return true; } const option = { label: newValue, value: newValue }; setCreatedOptions((current) => [...current, option]); handleSelect(option); return true; }; const closeDropdown = () => { if (!visible) return; setVisible(false); onOpenChange?.(false); clearQuery(); }; const onKeydown = (e: React.KeyboardEvent) => { if (disabled || readOnly) return; if (!visible) { if (["Enter", " ", "ArrowDown", "ArrowUp"].includes(e.key)) { toggle(true); if (e.key === "ArrowDown" || e.key === "ArrowUp") { setTimeout(() => moveActive(e.key === "ArrowDown" ? 1 : -1), 0); } e.preventDefault(); } return; } if (e.key === "ArrowDown" || e.key === "ArrowUp") { moveActive(e.key === "ArrowDown" ? 1 : -1); e.preventDefault(); } else if (e.key === "Enter") { const item = filterOptions()[activeIndex]; if (item && !item.disabled) { handleSelect(item); e.preventDefault(); } else if (createFromQuery()) e.preventDefault(); } else if (e.key === "Escape") { closeDropdown(); refSelection.current?.focus(); e.preventDefault(); } else if (e.key === "Tab") closeDropdown(); }; const renderOption = (item: SelectOption, index: number) => { const { label, value: val, disabled: optionDisabled } = item; return (