Select.tsx 6.83 KB
import { useCallback, useEffect, useRef, useState } from 'react';

/* ---------- Single Select (searchable) ---------- */

interface SelectOption {
  value: string;
  label: string;
  subtitle?: string;
  disabled?: boolean;
}

interface SelectProps {
  options: SelectOption[];
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  searchable?: boolean;
  loading?: boolean;
  error?: string | null;
  onRetry?: () => void;
  mono?: boolean;
}

export function Select({
  options,
  value,
  onChange,
  placeholder = '请选择',
  searchable = false,
  loading = false,
  error = null,
  onRetry,
  mono = false,
}: SelectProps) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');
  const ref = useRef<HTMLDivElement>(null);

  const selected = options.find((o) => o.value === value);

  const filtered = searchable
    ? options.filter(
        (o) =>
          o.label.toLowerCase().includes(search.toLowerCase()) ||
          o.subtitle?.toLowerCase().includes(search.toLowerCase()),
      )
    : options;

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
        setSearch('');
      }
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const handleSelect = useCallback(
    (opt: SelectOption) => {
      if (opt.disabled) return;
      onChange(opt.value);
      setOpen(false);
      setSearch('');
    },
    [onChange],
  );

  return (
    <div className={`custom-select${mono ? ' mono' : ''}`} ref={ref}>
      <div
        className={`select-trigger${open ? ' open' : ''}${value ? ' has-value' : ''}`}
        onClick={() => !loading && !error && setOpen(!open)}
      >
        <span className={`select-value${!selected ? ' placeholder' : ''}`}>
          {loading ? '加载中...' : error ? '加载失败' : selected ? selected.label : placeholder}
        </span>
        <span className="select-arrow">▾</span>
      </div>
      {open && (
        <div className="select-dropdown">
          {loading && <div className="select-status">加载中...</div>}
          {error && (
            <div className="select-actions">
              <span className="select-error-msg">{error}</span>
              {onRetry && (
                <button className="select-retry-btn" onClick={onRetry}>
                  重试
                </button>
              )}
            </div>
          )}
          {!loading && !error && searchable && (
            <div className="select-search-box">
              <input
                className="select-search-input"
                placeholder="搜索..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                autoFocus
              />
            </div>
          )}
          {!loading && !error && filtered.length === 0 && (
            <div className="select-status">无匹配选项</div>
          )}
          {!loading &&
            !error &&
            filtered.map((opt) => (
              <div
                key={opt.value}
                className={`select-option${opt.value === value ? ' selected' : ''}${opt.disabled ? ' disabled' : ''}`}
                onClick={() => handleSelect(opt)}
              >
                <div className="select-option-label">{opt.label}</div>
                {opt.subtitle && <div className="select-option-sub">{opt.subtitle}</div>}
              </div>
            ))}
        </div>
      )}
    </div>
  );
}

/* ---------- Multi Select (checkbox dropdown) ---------- */

interface MultiSelectOption {
  value: string;
  label: string;
  subtitle?: string;
}

interface MultiSelectProps {
  options: MultiSelectOption[];
  value: string[];
  onChange: (value: string[]) => void;
  placeholder?: string;
  loading?: boolean;
  error?: string | null;
  onRetry?: () => void;
}

export function MultiSelect({
  options,
  value,
  onChange,
  placeholder = '请选择',
  loading = false,
  error = null,
  onRetry,
}: MultiSelectProps) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  const selectedLabels = options
    .filter((o) => value.includes(o.value))
    .map((o) => o.label);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  function toggle(optValue: string) {
    if (value.includes(optValue)) {
      onChange(value.filter((v) => v !== optValue));
    } else {
      onChange([...value, optValue]);
    }
  }

  return (
    <div className="custom-select multi" ref={ref}>
      <div
        className={`select-trigger${open ? ' open' : ''}${value.length > 0 ? ' has-value' : ''}`}
        onClick={() => !loading && !error && setOpen(!open)}
      >
        <span className={`select-value${value.length === 0 ? ' placeholder' : ''}`}>
          {loading
            ? '加载中...'
            : error
              ? '加载失败'
              : value.length === 0
                ? placeholder
                : `已选 ${value.length} 项`}
        </span>
        <span className="select-arrow">▾</span>
      </div>
      {open && (
        <div className="select-dropdown">
          {loading && <div className="select-status">加载中...</div>}
          {error && (
            <div className="select-actions">
              <span className="select-error-msg">{error}</span>
              {onRetry && (
                <button className="select-retry-btn" onClick={onRetry}>
                  重试
                </button>
              )}
            </div>
          )}
          {!loading && !error && options.length === 0 && (
            <div className="select-status">暂无数据</div>
          )}
          {!loading &&
            !error &&
            options.map((opt) => (
              <label key={opt.value} className="select-option multi-option">
                <input
                  type="checkbox"
                  checked={value.includes(opt.value)}
                  onChange={() => toggle(opt.value)}
                />
                <div className="multi-option-content">
                  <div className="select-option-label">{opt.label}</div>
                  {opt.subtitle && <div className="select-option-sub">{opt.subtitle}</div>}
                </div>
              </label>
            ))}
        </div>
      )}
      {value.length > 0 && !open && (
        <div className="select-tags">
          {selectedLabels.map((label) => (
            <span key={label} className="select-tag">
              {label}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}