import { UseFormReturn } from "react-hook-form"; import { FormGroup } from "./form-groups"; interface UseFormResetProps { methods: UseFormReturn; defaultData: T; minGroups: number; } /** * Hook for advanced form reset functionality * * @param props - Hook properties * @returns Object with reset methods */ export const useFormReset = >({ methods, defaultData, minGroups, }: UseFormResetProps) => { /** * Resets the form to its initial state or to provided default values */ const resetForm = ( defaultValues?: { groups: FormGroup[] }, options?: { keepDirty?: boolean; keepErrors?: boolean; keepValues?: boolean; keepIsSubmitted?: boolean; keepTouched?: boolean; } ) => { methods.reset(defaultValues, options); }; /** * Resets the form to a clean state with the specified number of groups * * @param groupCount - Number of groups to initialize (defaults to minGroups) */ const resetToCleanState = (groupCount: number = minGroups) => { const cleanGroups = Array.from({ length: groupCount }).map(() => ({ id: Math.random().toString(36).substr(2, 9), data: { ...defaultData }, })); methods.reset({ groups: cleanGroups as FormGroup[] }); }; /** * Resets a specific group to its default state * * @param index - Index of the group to reset */ const resetGroup = (index: number) => { const currentGroups = methods.getValues().groups; if (index >= 0 && index < currentGroups.length) { const updatedGroups = [...currentGroups]; updatedGroups[index] = { id: updatedGroups[index].id, data: { ...defaultData }, }; methods.reset({ groups: updatedGroups }); } }; return { resetForm, resetToCleanState, resetGroup, }; };