index.tsx 3.34 KB
import type { CSSProperties, ReactNode } from 'react';
import type { FormInstance, FormProps } from 'antd';
import { UCascader, 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>[];
  form?: FormInstance<T>;
  initialValues?: Partial<T>;
  onSubmit?: (values: T) => void;
  layout?: FormProps['layout'];
  formStyle?: CSSProperties;
  sectionContentStyle?: CSSProperties;
  renderSectionTitle?: (title: string) => ReactNode;
  renderControl?: (
    field: FieldSchema<T>,
    form: FormInstance<T>,
    values: T,
  ) => ReactNode | undefined;
}
export function CombiForm<T extends Record<string, unknown>>({
  mode,
  fields,
  form: externalForm,
  initialValues,
  onSubmit,
  layout,
  formStyle,
  sectionContentStyle,
  renderSectionTitle,
  renderControl,
}: CombiFormProps<T>) {
  const [innerForm] = UForm.useForm<T>();
  const form = externalForm ?? innerForm;
  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] ?? '—'),
        }))}
      />
    );
  const sections = visible.reduce<{ title?: string; fields: FieldSchema<T>[] }[]>(
    (groups, field) => {
      const last = groups.at(-1);
      if (last && last.title === field.section) last.fields.push(field);
      else groups.push({ title: field.section, fields: [field] });
      return groups;
    },
    [],
  );
  const defaultControl = (field: FieldSchema<T>) => {
    if (field.type === 'cascader')
      return <UCascader options={field.options} style={{ width: '100%' }} />;
    if (field.type === 'select' || field.type === 'selectMultiple')
      return (
        <USelect
          options={field.options}
          mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
          style={{ width: '100%' }}
        />
      );
    if (field.type === 'switch') return <USwitch />;
    if (field.type === 'textarea') return <UInput.TextArea />;
    return <UInput />;
  };
  return (
    <UForm
      form={form}
      initialValues={initialValues}
      layout={layout}
      style={formStyle}
      onFinish={(next) => onSubmit?.(next as T)}
    >
      {sections.map((section, sectionIndex) => (
        <section key={`${section.title ?? 'default'}-${sectionIndex}`}>
          {section.title ? renderSectionTitle?.(section.title) : null}
          <div style={sectionContentStyle}>
            {section.fields.map((field) => (
              <UFormItem
                key={field.name}
                name={field.name as string}
                label={field.label}
                rules={field.rules}
                style={field.itemStyle}
              >
                {renderControl?.(field, form, data) ?? defaultControl(field)}
              </UFormItem>
            ))}
          </div>
        </section>
      ))}
    </UForm>
  );
}