import type { MutableRefObject } from 'react' import { createContext, useContext } from 'react' import type { FieldValidator } from 'final-form' export type Validators = Record> export type FormContextProps = { getValidators: () => Validators setValidators: (fieldName: string, validator: FieldValidator) => void clearValidators: (fieldName: string) => void } export const createFormContext = (): FormContextProps => { const validators: Validators = {} return { getValidators: () => validators, setValidators: (fieldName, validator) => { validators[fieldName] = validator }, clearValidators: fieldName => { delete validators[fieldName] }, } } export const FormContext = createContext | null>(null) export const useFormContext = () => { const context = useContext(FormContext) if (!context) { throw new Error('Form Field cannot be rendered outside Form component') } return context.current }