Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 329x 311x 311x 311x 311x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 18x 18x 18x 18x 15x 15x 15x 18x 3x 3x 3x 3x 3x 371x 371x 371x 371x 371x 371x 371x 371x 371x 311x 311x 311x 311x 311x 311x 311x 371x 371x 371x 371x 371x 277x 277x 371x 371x 371x 371x 371x 371x 371x 20x 20x 16x 16x 371x 371x 371x 371x 371x 371x 6x 371x 371x 371x 371x 17x 17x 11x 11x 17x 6x 6x 6x 14x 14x 10x 10x 6x 6x 6x 6x 6x 371x 371x 371x 371x 371x 322x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 10x 10x 10x 10x 1x 1x 1x 1x 1x 10x 14x 322x 371x 371x 371x 371x 371x 371x 4x 4x 4x 4x 4x 371x 371x 371x 371x 127x 127x 371x 371x 371x 371x 311x 311x 311x 371x 371x 371x 371x 371x 1071x 1071x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 1071x 1071x 1071x 371x 371x 371x 371x 371x 371x 371x 2x 2x 2x 2x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 371x 1x 1x | 'use client';
/**
* useForm Hook
*
* A comprehensive form management hook with Zod validation,
* debounced field validation, and submission handling.
*/
import { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import { z } from 'zod';
import { clientLogger } from '@/lib/logging/clientLogger';
/**
* Simple debounce utility
*/
function debounce<T extends (...args: Parameters<T>) => ReturnType<T>>(
fn: T,
delay: number
): T & { cancel: () => void } {
let timeoutId: NodeJS.Timeout | null = null;
const debouncedFn = ((...args: Parameters<T>) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn(...args);
timeoutId = null;
}, delay);
}) as T & { cancel: () => void };
debouncedFn.cancel = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
return debouncedFn;
}
/**
* Options for the useForm hook
*/
export interface UseFormOptions<T extends z.ZodObject<z.ZodRawShape>> {
/** Zod schema for validation */
schema: T;
/** Initial form values */
initialValues: z.infer<T>;
/** Validate on change (default: true) */
validateOnChange?: boolean;
/** Validate on blur (default: true) */
validateOnBlur?: boolean;
/** Debounce delay in ms for onChange validation (default: 300) */
debounceMs?: number;
/** Callback when form is submitted successfully */
onSubmitSuccess?: () => void;
/** Callback when form submission fails */
onSubmitError?: (error: Error) => void;
}
/**
* Return type for the useForm hook
*/
export interface UseFormReturn<T extends z.ZodObject<z.ZodRawShape>> {
/** Current form values */
values: z.infer<T>;
/** Validation errors by field */
errors: Record<keyof z.infer<T>, string | null>;
/** Touched state by field */
touched: Record<keyof z.infer<T>, boolean>;
/** Whether form is currently submitting */
isSubmitting: boolean;
/** Whether all fields are valid */
isValid: boolean;
/** Whether any field has been modified */
isDirty: boolean;
/** Set a field value */
setValue: (field: keyof z.infer<T>, value: unknown) => void;
/** Mark a field as touched */
setTouched: (field: keyof z.infer<T>) => void;
/** Set a field error manually */
setError: (field: keyof z.infer<T>, error: string | null) => void;
/** Validate a single field */
validateField: (field: keyof z.infer<T>) => Promise<string | null>;
/** Validate the entire form */
validateForm: () => Promise<boolean>;
/** Reset form to initial values */
resetForm: () => void;
/** Handle form submission */
handleSubmit: (onSubmit: (values: z.infer<T>) => Promise<void>) => (e: React.FormEvent) => void;
/** Get common field props for an input */
getFieldProps: (field: keyof z.infer<T>) => {
value: z.infer<T>[keyof z.infer<T>];
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
onBlur: () => void;
'aria-invalid': boolean;
};
/** Get field state for a specific field */
getFieldState: (field: keyof z.infer<T>) => {
value: z.infer<T>[keyof z.infer<T>];
error: string | null;
touched: boolean;
isDirty: boolean;
};
}
/**
* useForm Hook
*
* Provides comprehensive form state management with validation.
*
* @example
* ```tsx
* const { values, errors, handleSubmit, getFieldProps } = useForm({
* schema: z.object({
* email: z.string().email(),
* password: z.string().min(8)
* }),
* initialValues: { email: '', password: '' }
* });
*
* return (
* <form onSubmit={handleSubmit(async (values) => { ... })}>
* <input {...getFieldProps('email')} />
* {errors.email && <span>{errors.email}</span>}
* </form>
* );
* ```
*/
export function useForm<T extends z.ZodObject<z.ZodRawShape>>({
schema,
initialValues,
validateOnChange = true,
validateOnBlur = true,
debounceMs = 300,
onSubmitSuccess,
onSubmitError
}: UseFormOptions<T>): UseFormReturn<T> {
type FormValues = z.infer<T>;
type FieldName = keyof FormValues;
// State
const [values, setValues] = useState<FormValues>(initialValues);
const [errors, setErrors] = useState<Record<FieldName, string | null>>(
{} as Record<FieldName, string | null>
);
const [touched, setTouched] = useState<Record<FieldName, boolean>>(
{} as Record<FieldName, boolean>
);
const [isSubmitting, setIsSubmitting] = useState(false);
// Store initial values for dirty checking (captured once on mount)
const [storedInitialValues] = useState<FormValues>(() => initialValues);
// Validate a single field
const validateField = useCallback(
async (field: FieldName): Promise<string | null> => {
try {
const fieldSchema = schema.shape[field as string] as z.ZodTypeAny | undefined;
if (fieldSchema) {
await fieldSchema.parseAsync(values[field]);
}
setErrors((prev) => ({ ...prev, [field]: null }));
return null;
} catch (error) {
if (error instanceof z.ZodError) {
const message = error.issues[0]?.message || 'Invalid value';
setErrors((prev) => ({ ...prev, [field]: message }));
return message;
}
return null;
}
},
[schema, values]
);
// Create debounced validation function
type DebouncedValidateFn = ((field: FieldName) => void) & { cancel: () => void };
const debouncedValidateRef = useRef<DebouncedValidateFn | null>(null);
useEffect(() => {
debouncedValidateRef.current = debounce(
(field: FieldName) => { validateField(field); },
debounceMs
) as DebouncedValidateFn;
return () => {
debouncedValidateRef.current?.cancel();
};
}, [validateField, debounceMs]);
// Set a field value
const setValue = useCallback(
(field: FieldName, value: unknown) => {
setValues((prev) => ({ ...prev, [field]: value }));
if (validateOnChange && touched[field]) {
debouncedValidateRef.current?.(field);
}
},
[validateOnChange, touched]
);
// Mark a field as touched
const markTouched = useCallback(
(field: FieldName) => {
setTouched((prev) => ({ ...prev, [field]: true }));
if (validateOnBlur) {
validateField(field);
}
},
[validateOnBlur, validateField]
);
// Set a field error manually
const setError = useCallback((field: FieldName, error: string | null) => {
setErrors((prev) => ({ ...prev, [field]: error }));
}, []);
// Validate the entire form
const validateForm = useCallback(async (): Promise<boolean> => {
try {
await schema.parseAsync(values);
setErrors({} as Record<FieldName, string | null>);
return true;
} catch (error) {
if (error instanceof z.ZodError) {
const newErrors: Record<string, string | null> = {};
error.issues.forEach((issue) => {
const field = issue.path[0] as string;
if (!newErrors[field]) {
newErrors[field] = issue.message;
}
});
setErrors(newErrors as Record<FieldName, string | null>);
}
return false;
}
}, [schema, values]);
// Handle form submission
const handleSubmit = useCallback(
(onSubmit: (values: FormValues) => Promise<void>) => {
return async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
// Cancel any pending debounced validations
debouncedValidateRef.current?.cancel();
// Mark all fields as touched
const allTouched = Object.keys(initialValues).reduce(
(acc, key) => ({ ...acc, [key]: true }),
{} as Record<FieldName, boolean>
);
setTouched(allTouched);
const isValid = await validateForm();
if (isValid) {
try {
await onSubmit(values);
onSubmitSuccess?.();
} catch (error) {
clientLogger.error('Form submission error', error instanceof Error ? error : undefined, {
category: 'SYSTEM',
});
onSubmitError?.(error instanceof Error ? error : new Error('Submission failed'));
}
}
setIsSubmitting(false);
};
},
[values, validateForm, initialValues, onSubmitSuccess, onSubmitError]
);
// Reset form to initial values
const resetForm = useCallback(() => {
setValues(initialValues);
setErrors({} as Record<FieldName, string | null>);
setTouched({} as Record<FieldName, boolean>);
setIsSubmitting(false);
debouncedValidateRef.current?.cancel();
}, [initialValues]);
// Calculate if form is valid
const isValid = useMemo(() => {
const errorValues = Object.values(errors);
return errorValues.length === 0 || errorValues.every((e) => e === null);
}, [errors]);
// Calculate if form is dirty
const isDirty = useMemo(() => {
return Object.keys(values).some(
(key) => values[key as FieldName] !== storedInitialValues[key as FieldName]
);
}, [values, storedInitialValues]);
// Get common field props for binding to inputs
const getFieldProps = useCallback(
(field: FieldName) => ({
value: values[field],
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const target = e.target;
let newValue: unknown;
if (target.type === 'checkbox') {
newValue = (target as HTMLInputElement).checked;
} else if (target.type === 'number') {
newValue = target.value === '' ? '' : Number(target.value);
} else {
newValue = target.value;
}
setValue(field, newValue);
},
onBlur: () => markTouched(field),
'aria-invalid': !!(touched[field] && errors[field])
}),
[values, touched, errors, setValue, markTouched]
);
// Get field state for a specific field
const getFieldState = useCallback(
(field: FieldName) => ({
value: values[field],
error: errors[field] || null,
touched: touched[field] || false,
isDirty: values[field] !== storedInitialValues[field]
}),
[values, errors, touched, storedInitialValues]
);
return {
values,
errors,
touched,
isSubmitting,
isValid,
isDirty,
setValue,
setTouched: markTouched,
setError,
validateField,
validateForm,
resetForm,
handleSubmit,
getFieldProps,
getFieldState
};
}
export default useForm;
|