'use client'; import { useState } from 'react'; import { Button } from '@kit/ui/button'; import type { CmsFieldType } from '../schema/module.schema'; import { FieldRenderer } from './field-renderer'; interface FieldDefinition { name: string; display_name: string; field_type: CmsFieldType; is_required: boolean; placeholder?: string | null; help_text?: string | null; is_readonly: boolean; select_options?: Array<{ label: string; value: string }> | null; section: string; sort_order: number; show_in_form: boolean; width: string; } interface ModuleFormProps { fields: FieldDefinition[]; initialData?: Record; onSubmit: (data: Record) => Promise; isLoading?: boolean; errors?: Array<{ field: string; message: string }>; } /** * Dynamic form component driven by module field definitions. * Replaces the legacy my_modulklasse form rendering. */ export function ModuleForm({ fields, initialData = {}, onSubmit, isLoading = false, errors = [], }: ModuleFormProps) { const [formData, setFormData] = useState>(initialData); const visibleFields = fields .filter((f) => f.show_in_form) .sort((a, b) => a.sort_order - b.sort_order); // Group fields by section const sections = new Map(); for (const field of visibleFields) { const section = field.section || 'default'; if (!sections.has(section)) { sections.set(section, []); } sections.get(section)!.push(field); } const handleFieldChange = (fieldName: string, value: unknown) => { setFormData((prev) => ({ ...prev, [fieldName]: value })); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); await onSubmit(formData); }; const getFieldError = (fieldName: string) => { return errors.find((e) => e.field === fieldName)?.message; }; const getWidthClass = (width: string) => { switch (width) { case 'half': return 'col-span-1'; case 'third': return 'col-span-1'; case 'quarter': return 'col-span-1'; default: return 'col-span-full'; } }; return (
{Array.from(sections.entries()).map(([sectionName, sectionFields]) => (
{sectionName !== 'default' && (

{sectionName}

)}
{sectionFields.map((field) => (
handleFieldChange(field.name, value)} placeholder={field.placeholder ?? undefined} helpText={field.help_text ?? undefined} required={field.is_required} readonly={field.is_readonly} error={getFieldError(field.name)} selectOptions={field.select_options ?? undefined} />
))}
))}
); }