From 5ed02122548d602986218df9dc78b9845f18e626 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Fri, 23 May 2025 13:13:00 +0100 Subject: [PATCH] feat(frontend): add useForm hook --- frontend/src/hooks/useForm.ts | 69 +++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 frontend/src/hooks/useForm.ts diff --git a/frontend/src/hooks/useForm.ts b/frontend/src/hooks/useForm.ts new file mode 100644 index 00000000..58ce7658 --- /dev/null +++ b/frontend/src/hooks/useForm.ts @@ -0,0 +1,69 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { + FieldValues, + Path, + RegisterOptions, + UseFormProps, + UseFormRegister, + UseFormReturn, + useForm as useReactHookForm, +} from "react-hook-form"; + +import { useValidationRules } from "./useValidationRules"; + +export type TRegisterOption = + Record< + keyof TFieldValues, + RegisterOptions> | undefined + >; + +type TRegisterProps = Parameters< + UseFormRegister +>; + +type TRules = { + rules?: Partial>; +}; + +const useRegister = ( + register: UseFormRegister, + rules?: Partial>, +) => { + const defaultRules = useValidationRules(); + + return (...args: TRegisterProps) => { + const fieldName = args[0].split(".").at(-1) || ""; + const defaultOptions = (defaultRules[fieldName] || {}) as + | TFieldValues + | undefined; + const fieldOptions = args[1] || rules?.[fieldName]; + const mergedOptions = { ...defaultOptions, ...fieldOptions }; + + return register(args[0], mergedOptions); + }; +}; + +export const useForm = < + TFieldValues extends FieldValues = FieldValues, + TContext = any, + TTransformedValues extends FieldValues | undefined = undefined, + R = UseFormReturn, +>( + props?: UseFormProps & TRules, +): R => { + const { rules, ...restProps } = props || {}; + const { register, ...restMethods } = useReactHookForm< + TFieldValues, + TContext, + TTransformedValues + >(restProps); + + return { ...restMethods, register: useRegister(register, rules) } as R; +};