Select.tsx 2.88 KB
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>
  );
}