index.tsx 6.28 KB
import { useMemo, type ChangeEvent, type CSSProperties, type ReactNode } from 'react';
import { UInput } from '../Input';
import { USelect } from '../Select';

export interface USelectInputOption {
  label: ReactNode;
  value: string | number;
}

/**
 * 「前置下拉 + 输入」组合筛选控件。
 *
 * 为什么单独做一个组件:过去 SearchForm 里两处(普通输入、日期区间)各自手写
 * flex 容器 + 两个 antd 控件拼接,视觉上是「两个控件挤在一起」——双边框、双圆角、
 * 中间接缝突兀,placeholder 与下拉文案还要在调用处各自维护。这里把它们收敛成一个
 * 一体化控件:统一外框、一条分隔线、聚焦环包住整体;宽度自适应、placeholder 联动、
 * 切换语义时清空输入都内聚在组件里。
 *
 * 受控设计:value/selectorValue 由调用方给出,组件不碰 Form store,因此既能塞进
 * antd Form(调用方用 Form.useWatch + setFieldValue 桥接),也能独立用在任何页面。
 * 右段传 children 即可替换为日期区间等自定义控件(见 SearchForm 的 dateRange)。
 */
export interface USelectInputProps {
  /** 前置下拉的选项。类型与设计系统的 FieldOption 结构兼容。 */
  options: USelectInputOption[];
  /**
   * 前置下拉当前值。不传 / undefined / null 时自动选中 options 第一项——
   * 维度选择器不允许出现空态(空态会让 placeholder 一起退化)。
   */
  selectorValue?: string | number;
  /** 前置下拉变化。切换语义时组件会同时回调 onChange('') 清空右段(可关闭)。 */
  onSelectorChange?: (value: string | number) => void;
  /** 右段输入值。 */
  value?: string;
  /** 右段输入变化,直接回传字符串,调用方不必读 event.target.value。 */
  onChange?: (value: string) => void;
  /** 输入占位符。不传时按当前下拉文案生成「请输入XX」。 */
  placeholder?: string;
  /** 前置下拉宽度。不传则按最长选项文案自适应(保底 112 / 封顶 160px)。 */
  selectorWidth?: number;
  /** 整体宽度,默认撑满父容器。 */
  width?: string | number;
  /** 尺寸档,与 antd 保持一致。 */
  size?: 'small' | 'middle';
  disabled?: boolean;
  /** 右段输入是否可清空,默认 true。 */
  allowClear?: boolean;
  /** 切换前置下拉时是否清空右段,默认 true,避免「账号 → 手机号」后语义错配。 */
  clearValueOnSelectorChange?: boolean;
  /** 自定义右段控件(如 UDatePicker.RangePicker)。传了就替代内置输入框。 */
  children?: ReactNode;
  /** 无障碍标签:不传时用「筛选字段」/ 解析后的 placeholder。 */
  selectorAriaLabel?: string;
  inputAriaLabel?: string;
  className?: string;
  style?: CSSProperties;
}

/**
 * 按最长选项文案估宽:中文 12px/字(small 档),ASCII 0.6 字;箭头 + 左右内边距约 40px。
 * 保底 112px 让「登录账号」这类 4 字文案完整显示;封顶 160px 避免长文案把输入框压没。
 */
function measureSelectorWidth(options: USelectInputOption[]): number {
  const chars = options.reduce((max, option) => {
    const label = typeof option.label === 'string' ? option.label : '';
    const width = [...label].reduce((sum, ch) => {
      const code = ch.codePointAt(0) ?? 0;
      // 等价于原 [\x00-\xff] 的 ASCII 宽度口径,但排除控制字符(no-control-regex)。
      return sum + (code > 31 && code < 256 ? 0.6 : 1);
    }, 0);
    return Math.max(max, width);
  }, 4);
  return Math.min(160, Math.max(112, Math.round(chars * 12 + 40)));
}

export function USelectInput({
  options,
  selectorValue,
  onSelectorChange,
  value,
  onChange,
  placeholder,
  selectorWidth,
  width = '100%',
  size = 'small',
  disabled = false,
  allowClear = true,
  clearValueOnSelectorChange = true,
  children,
  selectorAriaLabel,
  inputAriaLabel,
  className,
  style,
}: USelectInputProps) {
  const measuredWidth = useMemo(
    () => selectorWidth ?? measureSelectorWidth(options),
    [options, selectorWidth],
  );
  // 前置下拉是「按哪个字段筛」的维度选择,必须始终有一个确定值:
  // 调用方首帧还没从 Form 读到初值(useWatch 首帧 store 为空)时,不能让下拉空着,
  // 否则 placeholder 也跟着退化成「请输入」,用户会以为控件失效。
  // 约定:undefined / null 视为「调用方尚未给值」→ 回落第一项;空串是合法选项值(如「全部」),
  // 由调用方按需传,组件不改写。
  const resolvedSelectorValue =
    selectorValue === undefined || selectorValue === null
      ? (options[0]?.value ?? '')
      : selectorValue;
  const activeLabel = options.find((option) => option.value === resolvedSelectorValue)?.label;
  const resolvedPlaceholder =
    placeholder ??
    (typeof activeLabel === 'string' && activeLabel ? `请输入${activeLabel}` : '请输入');

  const classes = [
    'u-select-input',
    `u-select-input--${size}`,
    disabled ? 'is-disabled' : '',
    className ?? '',
  ]
    .filter(Boolean)
    .join(' ');

  return (
    <div className={classes} style={{ width, ...style }}>
      <USelect
        className="u-select-input__selector"
        variant="borderless"
        size={size}
        allowClear={false}
        disabled={disabled}
        value={resolvedSelectorValue}
        options={options}
        aria-label={selectorAriaLabel ?? '筛选字段'}
        style={{ width: measuredWidth, flex: `0 0 ${measuredWidth}px` }}
        onChange={(next) => {
          onSelectorChange?.(next as string | number);
          if (clearValueOnSelectorChange && next !== resolvedSelectorValue) onChange?.('');
        }}
      />
      <span className="u-select-input__divider" aria-hidden="true" />
      <div className="u-select-input__control">
        {children ?? (
          <UInput
            className="u-select-input__input"
            variant="borderless"
            size={size}
            allowClear={allowClear}
            disabled={disabled}
            value={value}
            placeholder={resolvedPlaceholder}
            aria-label={inputAriaLabel ?? resolvedPlaceholder}
            onChange={(event: ChangeEvent<HTMLInputElement>) => onChange?.(event.target.value)}
          />
        )}
      </div>
    </div>
  );
}

export default USelectInput;