Select.tsx
2.88 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
import { useState } from 'react';
import type { ButtonHTMLAttributes, ReactNode } from 'react';
import styles from './Shared.module.css';
import { Icon } from './Icon';
import { cx, notifyPopupOpen, useExclusivePopup } from './utils';
const selectPopupOpenEvent = 'gl-select-popup-open';
export interface SelectOption {
label: ReactNode;
value: string;
disabled?: boolean;
}
export interface SelectProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> {
/** 可选项列表;禁用项保留展示但不会触发选择。 */
options: SelectOption[];
value?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string | undefined, option: SelectOption | undefined) => void;
}
export function Select({ allowClear, options, placeholder = '请选择', value, onChange, ...props }: SelectProps) {
const [open, setOpen] = useState(false);
const popupId = useExclusivePopup(selectPopupOpenEvent, setOpen);
const [innerValue, setInnerValue] = useState<string | undefined>(value);
const currentValue = value ?? innerValue;
const currentOption = options.find((option) => option.value === currentValue);
const label = props['aria-label'] ?? '选择框';
const commit = (nextValue: string | undefined, option: SelectOption | undefined) => {
if (value === undefined) {
setInnerValue(nextValue);
}
onChange?.(nextValue, option);
setOpen(false);
};
const toggleOpen = () => {
setOpen((nextOpen) => {
if (!nextOpen) notifyPopupOpen(selectPopupOpenEvent, popupId);
return !nextOpen;
});
};
return (
<span className={styles.selectWrapper}>
<button {...props} className={cx(styles.control, styles.fieldButton)} role="combobox" aria-expanded={open} type="button" onClick={toggleOpen}>
<span>{currentOption?.label ?? placeholder}</span>
<Icon className={styles.fieldIcon} name={open ? 'chevron-down' : 'chevron-right'} />
</button>
{allowClear && currentValue ? (
<button className={styles.plainButton} type="button" aria-label={`清空${label}`} onClick={() => commit(undefined, undefined)}>
清空
</button>
) : null}
{open ? (
<div className={cx(styles.popup, styles.selectPopup)} role="listbox">
{options.length === 0 ? <div className={styles.muted}>暂无数据</div> : null}
{options.map((option) => (
<div
key={option.value}
className={cx(styles.option, option.disabled && styles.disabled)}
role="option"
aria-disabled={option.disabled || undefined}
aria-selected={option.value === currentValue}
onClick={() => {
if (!option.disabled) commit(option.value, option);
}}
>
{option.label}
</div>
))}
</div>
) : null}
</span>
);
}