import { useForm } from "@tanstack/react-form"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { toast } from "sonner"; import { type ReactNode } from "react"; interface FormBuilderProps> { defaultValues: T; onSubmit: (values: T) => Promise | void; submitLabel?: string; cancelLabel?: string; onCancel?: () => void; showCancel?: boolean; children: (form: any) => ReactNode; } export function FormBuilder>({ defaultValues, onSubmit, submitLabel = "Submit", cancelLabel = "Hủy", onCancel, showCancel = false, children, }: FormBuilderProps) { const form = useForm({ defaultValues, onSubmit: async ({ value }) => { try { await onSubmit(value as T); } catch (error) { console.error("Submit error:", error); toast.error("Có lỗi xảy ra!"); } }, }); return (
{ e.preventDefault(); form.handleSubmit(); }} > {children(form)}
{showCancel && onCancel && ( )}
); } interface FormFieldProps { form: any; name: K; label: string; type?: string; placeholder?: string; required?: boolean; } export function FormField, K extends keyof T>({ form, name, label, type = "text", placeholder, required, }: FormFieldProps) { return ( {(field: any) => (
field.handleChange(e.target.value)} placeholder={placeholder} />
)}
); } export function FormTextarea, K extends keyof T>({ form, name, label, placeholder, required, }: Omit, "type">) { return ( {(field: any) => (