import * as React from 'react'; import { Box, TextField, Button, FormControl, InputLabel, Select, MenuItem, FormControlLabel, Checkbox, Typography, Divider, } from '@mui/material'; import { ResourceConfig, ResourceField } from '../types/config'; import { useUpload } from '../providers/UploadProvider'; import ImageUploadField from './fields/ImageUploadField'; interface GenericFormProps { config: ResourceConfig; initialData?: any; onSave: (data: any) => Promise; onCancel: () => void; loading?: boolean; readOnly?: boolean; onEditClick?: () => void; } import { ConfigContext } from '../App'; export default function GenericForm({ config, initialData = {}, onSave, onCancel, loading: saving, readOnly = false, onEditClick, }: GenericFormProps) { initialData = initialData || {}; const [formData, setFormData] = React.useState(initialData); const { uploadFile, uploading } = useUpload(); const appConfig = React.useContext(ConfigContext); const handleChange = (key: string, value: any) => { if (readOnly) return; setFormData((prev: any) => ({ ...prev, [key]: value })); }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (readOnly) return; onSave(formData); }; const getTitle = () => { if (readOnly) return `View ${config.label}`; return initialData[config.primaryKey] ? `Edit ${config.label}` : `New ${config.label}`; }; return ( {getTitle()} {Object.entries(config.fields).map(([key, field]) => ( handleChange(key, val)} disabled={readOnly || field.readOnly} uploadFile={uploadFile} uploading={uploading} baseUrl={appConfig?.baseUrl || ""} /> ))} {readOnly ? ( ) : ( )} ); } function FormField({ name, field, value, onChange, disabled, uploadFile, uploading, baseUrl }: any) { const label = field.label; if (field.type === 'image') { return ( { const url = await uploadFile(file); if (url) onChange(url); }} uploading={uploading} baseUrl={baseUrl} /> ); } if (field.type === 'boolean') { return ( onChange(e.target.checked)} disabled={disabled} /> } label={label} /> ); } if (field.type === 'enum' && field.options) { return ( {label} ); } if (field.type === 'datetime') { return ( onChange(e.target.value)} disabled={disabled} required={field.required} /> ); } if (field.type === 'date') { return ( onChange(e.target.value)} disabled={disabled} required={field.required} /> ); } if (field.type === 'markdown' || field.type === 'string') { return ( onChange(e.target.value)} disabled={disabled} required={field.required} /> ); } if (field.type === 'number') { return ( onChange(Number(e.target.value))} disabled={disabled} required={field.required} /> ); } return ( ); }