From 1548bfd8bc55f804e834599039bbed6c4ac0e3c9 Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Fri, 3 Mar 2023 00:03:24 -0500 Subject: [PATCH] fix(striker-ui): add hook useFormUtils --- striker-ui/hooks/useFormUtils.ts | 78 ++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 striker-ui/hooks/useFormUtils.ts diff --git a/striker-ui/hooks/useFormUtils.ts b/striker-ui/hooks/useFormUtils.ts new file mode 100644 index 00000000..8f71dfc3 --- /dev/null +++ b/striker-ui/hooks/useFormUtils.ts @@ -0,0 +1,78 @@ +import { + Dispatch, + MutableRefObject, + SetStateAction, + useCallback, + useMemo, + useState, +} from 'react'; + +import buildMapToMessageSetter from '../lib/buildMapToMessageSetter'; +import buildObjectStateSetterCallback from '../lib/buildObjectStateSetterCallback'; +import { MessageGroupForwardedRefContent } from '../components/MessageGroup'; + +type FormValidity = { + [K in keyof T]?: boolean; +}; + +const useFormUtils = < + U extends string, + I extends InputIds, + M extends MapToInputId, +>( + ids: I, + messageGroupRef: MutableRefObject, +): { + buildFinishInputTestBatchFunction: ( + key: keyof M, + ) => (result: boolean) => void; + buildInputFirstRenderFunction: ( + key: keyof M, + ) => ({ isRequired }: { isRequired: boolean }) => void; + formValidity: FormValidity; + isFormInvalid: boolean; + msgSetters: MapToMessageSetter; + setFormValidity: Dispatch>>; +} => { + const [formValidity, setFormValidity] = useState>({}); + + const buildFinishInputTestBatchFunction = useCallback( + (key: keyof M) => (result: boolean) => { + setFormValidity( + buildObjectStateSetterCallback>(key, result), + ); + }, + [], + ); + + const buildInputFirstRenderFunction = useCallback( + (key: keyof M) => + ({ isRequired }: { isRequired: boolean }) => { + setFormValidity( + buildObjectStateSetterCallback>(key, !isRequired), + ); + }, + [], + ); + + const isFormInvalid = useMemo( + () => Object.values(formValidity).some((isInputValid) => !isInputValid), + [formValidity], + ); + + const msgSetters = useMemo( + () => buildMapToMessageSetter(ids, messageGroupRef), + [ids, messageGroupRef], + ); + + return { + buildFinishInputTestBatchFunction, + buildInputFirstRenderFunction, + formValidity, + isFormInvalid, + msgSetters, + setFormValidity, + }; +}; + +export default useFormUtils;