Input.tsx 4.17 KB
import { forwardRef, useState } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';

import styles from './Input.module.css';
import { Icon } from './Icon';
import { cx } from './utils';

export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'prefix' | 'size'> {
  /** 左侧前缀,可用于金额、图标或字段上下文提示。 */
  prefix?: ReactNode;
  /** 右侧后缀,可用于单位、状态图标或补充信息。 */
  suffix?: ReactNode;
  /** 状态样式用于和 FormItem 校验信息协同展示。 */
  status?: 'default' | 'success' | 'warning' | 'error';
  /** 是否显示输入长度,默认使用简洁的当前值/上限格式。 */
  showCount?: boolean;
  /** 是否展示清空按钮,受控和非受控场景都通过字符串值回调给业务侧。 */
  allowClear?: boolean;
  onChange?: (value: string) => void;
  onClear?: () => void;
}

export interface SearchInputProps extends InputProps {
  /** 点击搜索按钮或按下 Enter 时触发,参数为当前输入值。 */
  onSearch?: (value: string) => void;
}

export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
  {
    allowClear = false,
    className,
    defaultValue,
    disabled,
    onChange,
    onClear,
    prefix,
    status = 'default',
    suffix,
    showCount = false,
    value,
    ...props
  },
  ref,
) {
  const [innerValue, setInnerValue] = useState(defaultValue?.toString() ?? '');
  const currentValue = value === undefined ? innerValue : String(value);

  const emitChange = (nextValue: string) => {
    if (value === undefined) {
      setInnerValue(nextValue);
    }
    onChange?.(nextValue);
  };

  const clearLabel = props['aria-label'] ? `清空${props['aria-label']}` : '清空输入';
  const countLabel = props.maxLength !== undefined ? `${currentValue.length}/${props.maxLength}` : String(currentValue.length);

  return (
    <span
      className={cx(
        styles.field,
        status === 'error' && styles.fieldError,
        status === 'warning' && styles.fieldWarning,
        status === 'success' && styles.fieldSuccess,
        disabled && styles.fieldDisabled,
        className,
      )}
    >
      {prefix ? <span className={styles.affix}>{prefix}</span> : null}
      <input
        {...props}
        ref={ref}
        className={styles.input}
        disabled={disabled}
        value={currentValue}
        aria-invalid={status === 'error' || undefined}
        onChange={(event) => emitChange(event.target.value)}
      />
      {showCount ? <span className={styles.counter}>{countLabel}</span> : null}
      {allowClear && currentValue ? (
        <button
          aria-label={clearLabel}
          className={styles.iconButton}
          disabled={disabled}
          type="button"
          onClick={() => {
            emitChange('');
            onClear?.();
          }}
        >
          ×
        </button>
      ) : null}
      {suffix ? <span className={styles.affix}>{suffix}</span> : null}
    </span>
  );
});

export const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(function SearchInput(
  { onChange, onClear, onKeyDown, onSearch, prefix = <Icon label="搜索图标" name="search" size={18} />, ...props },
  ref,
) {
  const [searchValue, setSearchValue] = useState(props.defaultValue?.toString() ?? props.value?.toString() ?? '');
  const currentValue = props.value === undefined ? searchValue : String(props.value);

  const handleSearch = () => {
    onSearch?.(currentValue);
  };

  return (
    <Input
      {...props}
      ref={ref}
      prefix={prefix}
      onChange={(nextValue) => {
        if (props.value === undefined) {
          setSearchValue(nextValue);
        }
        onChange?.(nextValue);
      }}
      onClear={() => {
        if (props.value === undefined) {
          setSearchValue('');
        }
        onClear?.();
      }}
      onKeyDown={(event) => {
        if (event.key === 'Enter') {
          onSearch?.(currentValue);
        }
        onKeyDown?.(event);
      }}
      suffix={
        <button className={cx(styles.iconButton, styles.searchButton)} type="button" onClick={handleSearch}>
          搜索
        </button>
      }
    />
  );
});