import type { RefObject } from 'react'; /** * Represents all possible types of values that can be stored and managed within a form field. * This union type encompasses primitive values like strings, numbers, and booleans, as well as * complex types like arrays and file objects that are commonly used in form inputs. */ export type FormValue = Date | Date[] | File | FileList | number[] | string[] | boolean | number | string; /** * Represents the complete set of form field values in a form state structure. * This type defines a record where each key corresponds to a form field name and * each value represents the current state of that field using the FormValue type. * It serves as the primary data structure for managing and accessing all form values within the application. */ export type FormValues = Record; /** * A type definition for validation functions used within form components to validate field values. * This function type accepts a form value and optional form data, then returns an array of error messages or null if validation passes. * The validation function is commonly used in form field components to provide real-time validation feedback to users. * * @param value The current value of the form field being validated. * @param formData Optional object containing all form field values for cross-field validation. * @returns An array of error message strings if validation fails, or null if validation passes. * * @example * ```tsx * const emailValidator: ValidationFunc = (value, formData) => { * const email = value as string; * if (!email) return ['Email is required']; * if (!/\S+@\S+\.\S+/.test(email)) return ['Invalid email format']; * return null; * }; * ``` */ export type ValidationFunc = (value: FormValue, formData?: FormValues) => string[] | null; /** * Represents a form field element that extends the standard HTMLElement interface with custom validation capabilities. * This type is used to define form elements that can display custom validation error messages to users. * It combines the standard HTML element functionality with the ability to set custom validation states. */ export type FormField = HTMLElement & { setCustomValidity(error: string): void; }; /** * Interface defining the structure and methods for managing form state in a React form component. * This interface provides a comprehensive API for handling form field registration, validation, value management, and error tracking. * It serves as the core contract for form state management, enabling dynamic form behavior and real-time validation feedback. */ export interface FormState { /** * Registers a new form field with its default and initial values along with optional validation logic. * This method establishes a field in the form state and sets up its validation rules for future use. * The field becomes part of the form's managed state and can be accessed through other form methods. * * @param name The unique identifier name for the form field. * @param defaultValue The default value to use when the field is reset to its original state. * @param initialValue The initial value that the field should display when first rendered. * @param validation Optional validation function to apply to this field's value. */ addField(name: string, defaultValue: FormValue, initialValue: FormValue, validation: ValidationFunc | undefined): void; /** * Associates a React ref object with a specific form field for direct DOM element access. * This method enables the form state to interact with the actual HTML form elements for validation and focus management. * The ref is stored and can be used later for programmatic field manipulation and validation feedback. * * @param name The name of the form field to associate the ref with. * @param fieldRef React ref object pointing to the form field element. */ addFieldRef(name: string, fieldRef: RefObject): void; /** * Updates the validation function for an existing form field with new validation logic. * This method allows dynamic changes to field validation rules during the form's lifecycle. * The new validation function will be applied to future validation operations on the specified field. * * @param name The name of the form field to update validation for. * @param validation New validation function to apply, or undefined to remove validation. */ changeValidation(name: string, validation: ValidationFunc | undefined): void; /** * Updates the current value of a specific form field and triggers any associated validation. * This method is the primary way to programmatically change field values and maintain form state consistency. * The new value is stored and the form's validation state is updated accordingly. * * @param name The name of the form field to update. * @param value The new value to assign to the form field. */ changeValue(name: string, value: FormValue): void; /** * Completely removes a form field from the form state including its value, validation, and references. * This method performs cleanup when a field is no longer needed in the form structure. * All associated data for the field is permanently deleted from the form state. * * @param name The name of the form field to remove from the form state. */ deleteValue(name: string): void; /** * Record containing validation error messages for each form field, indexed by field name. */ errors: Record; /** * Record storing React ref objects for each form field element, enabling direct DOM manipulation. */ fields: Record>; /** * Boolean flag indicating whether the form currently has any validation errors across all fields. */ hasErrors: boolean; /** * Record containing the initial values for all form fields, used for resetting the form to its original state. */ initialValues: FormValues; /** * Resets a specific form field to its initial value and clears any associated validation errors. * This method restores the field to its original state as it was when first added to the form. * The field's validation state is also reset, removing any error messages. * * @param name The name of the form field to reset to its initial value. */ resetValue(name: string): void; /** * Resets all form fields to their initial values and clears all validation errors across the entire form. * This method provides a complete form reset functionality, restoring the form to its original state. * All field values and error states are cleared, returning the form to a pristine condition. */ resetValues(): void; /** * Triggers validation for all registered form fields and updates the error state accordingly. * This method runs through all field validation functions and collects any validation errors. * The form's error state and hasErrors flag are updated based on the validation results. */ validateFields(): void; /** * Record storing validation functions for each form field, indexed by field name. */ validations: Record; /** * Record containing the current values for all form fields, representing the live form state. */ values: FormValues; } /** * Interface defining the structure of the React context value used for form state management. * This interface represents the context type that provides access to a specific form's state and identifier within a React application. * It enables form components to access and interact with form data through React's context API, facilitating communication between parent and child components. */ export interface FormContextType { /** * The complete form state object containing all form data, validation rules, and management methods. */ form: FormState; /** * Unique string identifier for the specific form instance within the application context. */ formId: string; } /** * A type definition for form submission handler functions that process form data and provide validation feedback. * This function type is designed to handle the complete form submission workflow, including access to form context, native FormData, and typed values. * The handler can perform asynchronous operations like API calls and return validation errors if the submission fails, enabling comprehensive form processing with server-side validation support. * * @param props The form submission properties object. * @param props.ctx The complete form state context containing all form management methods and current state. * @param props.getForm Function that returns a native FormData object containing all form field values. * @param props.values Typed object containing all current form field values for type-safe access. * @returns Promise that resolves to a record of field validation errors or void if submission succeeds. * * @template T The type of the form values object, defaults to any for maximum flexibility. * * @example * ```tsx * const submitHandler: HandleFormSubmit<{email: string; password: string}> = async ({ ctx, getForm, values }) => { * try { * await api.login(values.email, values.password); * } catch (error) { * return { email: ['Invalid credentials'] }; * } * }; * ``` */ export type HandleFormSubmit = (props: { ctx: FormState; getForm(): FormData; values: T; }) => Promise | void>; /** * Interface defining the structure and methods for managing multiple form states within a global form data context. * This interface provides a comprehensive API for storing, retrieving, and managing form state instances across an entire application. * It serves as the central registry for all form instances, enabling form state persistence and cross-component form data access. */ export interface FormDataContextType { /** * Removes a form instance and all its associated data from the global form data registry. * This method performs complete cleanup of the specified form, including all field values, validation states, and references. * The form data is permanently deleted and cannot be recovered after this operation. * * @param formId The unique identifier of the form instance to delete from the registry. */ deleteFormData(formId: string): void; /** * Record containing all registered form state instances, indexed by their unique form identifiers. */ forms: Record; /** * Retrieves the form state instance for a specific form identifier from the global registry. * This method provides safe access to form data with null return for non-existent forms. * The returned form state can be used to access form values, validation states, and management methods. * * @param formId The unique identifier of the form instance to retrieve. * @returns The form state instance if found, or null if no form exists with the given identifier. */ getFormData(formId: string): FormState | null; /** * Resets all fields in the specified form instance to their initial values and clears validation errors. * This method delegates to the form's own reset functionality while maintaining the form's registration in the global context. * The form remains in the registry but returns to its original pristine state. * * @param formId The unique identifier of the form instance to reset to its initial state. */ resetFormData(formId: string): void; /** * Registers or updates a form state instance in the global form data registry with the specified identifier. * This method establishes the form in the global context, making it accessible to other components. * If a form with the same identifier already exists, it will be replaced with the new form state. * * @param formId The unique identifier to associate with the form state instance. * @param formState The complete form state object to store in the registry. */ setFormData(formId: string, formState: FormState): void; }