UNPKG

@matthew.ngo/reform

Version:

A flexible and powerful React form management library with advanced validation, state observation, and multi-group support

69 lines (68 loc) 2.77 kB
import { FieldPath, FieldValues, UseFormRegisterReturn } from "react-hook-form"; import { FormGroup } from "./core/form/form-groups"; import { ValidationResult } from "./core/validation"; export interface ReformGroupHandler<T extends FieldValues> { groups: FormGroup<T>[]; canAddGroup: boolean; canRemoveGroup: boolean; register: <K extends string>(index: number, field: K extends FieldPath<T> ? K : string, options?: any) => UseFormRegisterReturn; addGroup: () => Promise<ValidationResult>; removeGroup: (index: number) => Promise<ValidationResult>; duplicateGroup: (index: number) => Promise<ValidationResult>; moveGroup: (from: number, to: number) => Promise<ValidationResult>; /** * Get all form groups * * @returns Array of form groups */ getGroups: () => FormGroup<T>[]; /** * Set all form groups * * @param groups - New groups to set * @returns Promise with validation result */ setGroups: (groups: FormGroup<T>[]) => Promise<ValidationResult>; /** * Updates multiple form groups at once with the provided updater function. * * @param indices - Array of group indices to update * @param updater - Function that receives the current data and returns partial updates * @returns Promise resolving to a ValidationResult * * @example * // Update the name field for groups at indices 0, 2, and 3 * await batchUpdate([0, 2, 3], (data) => ({ name: data.name + " (Updated)" })); * * @example * // Set all selected groups to have the same email domain * await batchUpdate(selectedIndices, (data) => { * const [username] = data.email.split('@'); * return { email: `${username}@newdomain.com` }; * }); */ batchUpdate: (indices: number[], updater: (data: T) => Partial<T>) => Promise<ValidationResult>; /** * Removes multiple form groups at once. * Will fail if removing the groups would violate the minimum groups constraint. * * @param indices - Array of group indices to remove * @returns Promise resolving to a ValidationResult * * @example * // Remove groups at indices 1 and 3 * await batchRemove([1, 3]); * * @example * // Remove all selected groups * await batchRemove(selectedIndices); * * @example * // Remove all groups that match a certain condition * const indicesToRemove = groups * .map((group, index) => group.data.isArchived ? index : -1) * .filter(index => index !== -1); * await batchRemove(indicesToRemove); */ batchRemove: (indices: number[]) => Promise<ValidationResult>; }