UNPKG

@docvhcmc/react-form-schema

Version:

A flexible React form schema manager with pluggable validation adapters (Zod, Yup, etc.)

176 lines (171 loc) 9.2 kB
import { V as ValidationRule, S as SchemaInput, F as FormErrorManager, a as ValidationError, U as UseFormSchemaReturn } from '../../UseFormSchemaReturn-DxsGrlkZ.js'; export { b as FieldError, c as ValidationCode } from '../../UseFormSchemaReturn-DxsGrlkZ.js'; import { z } from 'zod/v4'; type ZodTypeFactory = (s: typeof z) => z.ZodType; type FieldSchemasOptions<Output> = { [k in keyof Output]: z.ZodType | ZodTypeFactory; }; type SchemaOptions<O> = FieldSchemasOptions<O> | [FieldSchemasOptions<O>, ...ValidationRule<O>[]]; type AnyZodObject = z.ZodObject<any, any>; /** * Core class for managing form state, validation, and data transformation using **Zod**. * It encapsulates the Zod schema, raw input values, validation errors, and provides * methods for updating values, validating, parsing, and observing changes. * * @template O - Represents the inferred output type of the Zod schema. */ declare class FormSchema<O> { readonly schemaOptions: SchemaOptions<O>; private _rawInput; private _schema; private _refinedFields; private _fieldSchemas; private _setterCache; __outputType: O; private _errorsManager; private _subscribers; private _debug; /** * Constructs a new FormSchema instance. * @param schemaOptions The raw schema definitions for each form field, optionally followed by custom validation rules. * @param initialValues Optional initial values to pre-populate the form's raw input. * @param debug Optional. If true, enables debug logging for the form schema instance. */ constructor(schemaOptions: SchemaOptions<O>, initialValues?: Partial<SchemaInput<O>>, debug?: boolean); /** * Subscribes a callback function to listen for changes in the form's state (input or errors). * @param callback The function to call when the form state changes. */ subscribe(callback: () => void): void; /** * Unsubscribes a callback function. * @param callback The function to remove from the subscriber list. */ unsubscribe(callback: () => void): void; /** * Provides access to the FormErrorManager instance for detailed error handling. */ get errors(): FormErrorManager; /** * Indicates whether the form is currently valid (has no errors). */ get isValid(): boolean; /** * Retrieves the raw input value(s) from the form, without any Zod parsing or validation. * This is useful for displaying current input or performing immediate checks without schema logic. * @param field Optional. The name of the specific field to retrieve. * @returns The raw input value for the specified field, or the entire raw input object if no field is specified. */ getRawValue(): SchemaInput<O>; getRawValue<F extends keyof O>(field: F): SchemaInput<O>[F] | undefined; /** * Retrieves the parsed and validated value(s) from the form's internal state (`_rawInput`) using Zod. * This method performs asynchronous validation and transformation. * It throws a ValidationError if validation fails. * * Overload 1: Retrieves the entire parsed and validated form data. * Overload 2: Retrieves a specific field's parsed and validated value. * @param field Optional. The name of the specific field to retrieve. * @returns A promise that resolves to the parsed and validated value for the specified field, * or the entire parsed form object if no field is specified. * @throws ValidationError if validation fails. */ getValidatedValue(): Promise<O>; getValidatedValue<F extends keyof O>(field: F): Promise<O[F]>; /** * Parses and validates an external data object or FormData against the entire schema. * This method performs asynchronous validation and transformation. * It throws a ValidationError if validation fails. * @param data The external data object or FormData to parse. * @returns A promise that resolves to the parsed and validated data. * @throws ValidationError if validation fails. */ parse(data: SchemaInput<O> | FormData): Promise<O>; /** * Applies a custom refinement rule to the entire schema. * This allows for cross-field validation or complex asynchronous checks. * The rule definition includes the validation logic (`check`) and error details. * @param rule The `ValidationRule` object containing the validation logic, path, code, and optional message/params. * @returns The current FormSchema instance for chaining. */ applyRule(rule: ValidationRule<O>): this; /** * Overwrites the entire raw input state of the form with the new values. * This is useful for completely replacing the form's data, e.g., when loading * a new record from an API or clearing the form. * It also triggers a full form validation and updates error state. * @param newValues The new raw input values to set. */ setRawValue(newValues: SchemaInput<O>): void; /** * Merges the provided partial values into the existing raw input state. * Existing fields not present in `partialValues` will be retained. * This is useful for applying incremental updates to the form's data. * It also triggers a full form validation and updates error state. * @param partialValues The partial raw input values to merge. */ mergeRawValue(partialValues: SchemaInput<O>): void; /** * Returns a memoized setter function for a specific form field. * This setter updates the form's internal raw input state (`_rawInput`). * It also triggers field-specific validation and updates error state. * @param field The name of the field for which to create a setter. * @returns A function that takes a value (of SchemaInput type) and updates the corresponding field. */ setValueFor<F extends keyof O>(field: F): (value: SchemaInput<O>[F]) => void; /** * Resets the form's internal raw input state (`_rawInput`) to its initial state or an empty state. * This effectively overwrites the current state and clears all errors. * @param initialValues Optional. New initial values to reset the form to. If not provided, resets to empty. */ reset(initialValues?: SchemaInput<O>): void; /** * Validates input data (either internal _rawInput or external data) * and returns a ValidationError if invalid, or undefined if valid. * This method performs asynchronous validation but does NOT throw errors for validation failures. * It also updates the internal error state and notifies subscribers. * * Overload 1: Validates the entire internal _rawInput. * Overload 2: Validates a specific field from the internal _rawInput. * Overload 3: Validates an external rawInput object. * Overload 4: Validates a specific field with an external value. * * @param arg1 Optional. Can be a field name (string) or an external input object. * @param arg2 Optional. The value for a specific field when arg1 is a field name. * @returns A Promise that resolves to `undefined` if validation passes, * or a `ValidationError` instance if validation fails. */ validate(): Promise<undefined | ValidationError>; validate<F extends keyof O>(field: F): Promise<undefined | ValidationError>; validate(input: SchemaInput<O>): Promise<undefined | ValidationError>; validate<F extends keyof O>(field: F, value: SchemaInput<O>[F]): Promise<undefined | ValidationError>; /** * Provides direct access to the underlying Zod schema object. * @returns The ZodObject instance used for validation. */ get schema(): AnyZodObject; /** * Notifies all subscribed listeners about a state change, triggering React re-renders. */ private _notifySubscribers; /** * Updates the internal error state based on a ValidationError instance. * It clears existing errors and populates them with the new validation error issues. * @param validationError The ValidationError instance containing new errors, or undefined if no errors. */ private _updateErrors; } type FormSchemaOutput<S extends FormSchema<any>> = S['__outputType']; /** * React hook to create and manage a stable FormSchema instance. * Ensures that the FormSchema instance is memoized and only re-created * when its core dependencies (`fieldSchemas` or `initialValues` references) change. * This hook also manages the React state for errors and ensures components re-render * when the FormSchema instance's internal state (input values or errors) changes. * @param schemaOptions The schema definitions for the form fields. * @param initialValues Optional initial values for the form. * @param debug Optional. If true, enables debug logging for the form schema instance. * @returns An object containing form values, error management functions, and submission handlers. */ declare function useFormSchema<O>(schemaOptions: SchemaOptions<O>, initialValues?: SchemaInput<O>, debug?: boolean): UseFormSchemaReturn<O>; export { FormSchema, type FormSchemaOutput, type SchemaOptions, useFormSchema };