index.tsx
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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>
);
}