index.tsx 1.73 KB
import { UDescriptions, UForm, UFormItem, UInput, USelect, USwitch } from '@uj/ui';
import type { FieldSchema } from '../formSchema';

export interface CombiFormProps<T extends Record<string, unknown>> {
  mode: 'form' | 'detail';
  fields: FieldSchema<T>[];
  initialValues?: Partial<T>;
  onSubmit?: (values: T) => void;
}
export function CombiForm<T extends Record<string, unknown>>({
  mode,
  fields,
  initialValues,
  onSubmit,
}: CombiFormProps<T>) {
  const [form] = UForm.useForm();
  const values = UForm.useWatch([], form) as T | undefined;
  const data = (values ?? initialValues ?? {}) as T;
  const visible = fields.filter(
    (field) => !(typeof field.hidden === 'function' ? field.hidden(data) : field.hidden),
  );
  if (mode === 'detail')
    return (
      <UDescriptions
        column={1}
        items={visible.map((field) => ({
          key: field.name,
          label: field.label,
          children: field.render
            ? field.render(data[field.name], data)
            : String(data[field.name] ?? '—'),
        }))}
      />
    );
  return (
    <UForm form={form} initialValues={initialValues} onFinish={(next) => onSubmit?.(next as T)}>
      {visible.map((field) => (
        <UFormItem key={field.name} name={field.name as string} label={field.label}>
          {field.type === 'select' || field.type === 'selectMultiple' ? (
            <USelect
              options={field.options}
              mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
            />
          ) : field.type === 'switch' ? (
            <USwitch />
          ) : field.type === 'textarea' ? (
            <UInput.TextArea />
          ) : (
            <UInput />
          )}
        </UFormItem>
      ))}
    </UForm>
  );
}