index.tsx 2.19 KB
import { UButton, UDatePicker, UForm, UFormItem, UInput, URadio, USelect } from '@uj/ui';
import type { FieldSchema } from '../formSchema';

export interface SearchFormProps<T extends Record<string, unknown>> {
  fields: FieldSchema<T>[];
  initialValues?: Partial<T>;
  onSearch: (values: T) => void;
  onReset?: (values: Partial<T>) => void;
}
export function SearchForm<T extends Record<string, unknown>>({
  fields,
  initialValues,
  onSearch,
  onReset,
}: SearchFormProps<T>) {
  const [form] = UForm.useForm();
  const control = (field: FieldSchema<T>) => {
    const common = {
      disabled: typeof field.disabled === 'boolean' ? field.disabled : false,
      placeholder: field.placeholder,
    };
    const width = field.width ?? (field.type === 'input' || field.type === 'textarea' ? 260 : 160);
    if (field.type === 'select' || field.type === 'selectMultiple')
      return (
        <USelect
          {...common}
          allowClear={false}
          style={{ width }}
          options={field.options}
          mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
        />
      );
    if (field.type === 'date') return <UDatePicker {...common} style={{ width }} />;
    if (field.type === 'dateRange')
      return <UDatePicker.RangePicker disabled={common.disabled} style={{ width }} />;
    if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />;
    return field.type === 'textarea' ? (
      <UInput.TextArea {...common} style={{ width }} />
    ) : (
      <UInput {...common} style={{ width }} />
    );
  };
  return (
    <UForm
      form={form}
      initialValues={initialValues}
      layout="inline"
      onFinish={(values) => onSearch(values as T)}
    >
      {fields.map((field) => (
        <UFormItem key={field.name} name={field.name as string} label={field.label}>
          {control(field)}
        </UFormItem>
      ))}
      <UFormItem>
        <UButton htmlType="submit">查询</UButton>
        <UButton
          type="default"
          onClick={() => {
            form.setFieldsValue(initialValues);
            onReset?.(initialValues ?? {});
          }}
        >
          重置
        </UButton>
      </UFormItem>
    </UForm>
  );
}