import * as React from 'react' import { useMemo, useState } from 'react' // Possible future ideas // TODO: Scroll to error field // TODO: Focus on error field export type FieldOptions = { extractor?: useFormExtractor | null getter?: G setter?: S } type RuleFunctionReturn = boolean | string type RuleFunction = (value: I, data: F) => RuleFunctionReturn | Promise type Rule = RuleFunction | RegExp type RuleObject = Rule | { rule: Rule; message: string } type RuleSet = RuleObject | RuleObject[] function isSimpleRule(obj: RuleObject): obj is Rule { return obj instanceof RegExp || typeof obj === 'function' } export type useFormExtractor = (from: any) => T export const NoExtractor: useFormExtractor = (v: unknown) => v export const HTMLInputExtractor: useFormExtractor = (e: React.FormEvent) => e.currentTarget.value export const HTMLCheckboxExtractor: useFormExtractor = (e: React.FormEvent) => e.currentTarget.checked export type FormOptions = { rules: R } // F = Type of form // R = Rules, derived from F // E = Errors, derived from F export const useForm = }, E extends { [key in keyof R]?: RuleFunctionReturn }>(init: F, options?: FormOptions) => { const validators: R = options?.rules ?? ({} as R) const [form, setForm] = useState(init) const [errors, setErrors] = useState({} as E) const isValid = useMemo(() => { return !Object.values(errors).reduce((acc, cur) => acc || cur !== undefined, false) }, [errors]) const setField = (key: A, value: F[A]) => { setForm({ ...form, [key]: value, }) } async function applyRule(value: any, rule: Rule): Promise { if (typeof rule === 'function') return await rule(value, form) if (rule instanceof RegExp) return rule.test(value) throw new Error(`Unsupported validator: ${rule}`) } async function validate(key: K, value: F[K]) { const set: RuleSet | undefined = validators[key] as any if (!set) return const rules = Array.isArray(set) ? set : [set] let newValue = undefined for (const rule of rules) { const simple = isSimpleRule(rule) const fn = simple ? rule : rule.rule const result = await applyRule(value, fn) if (result !== true) { newValue = simple ? (typeof result === 'string' ? result : true) : rule.message break } } setErrors({ ...errors, [key]: newValue, }) } // Internal use function update(key: A, extractor?: useFormExtractor | null) { return (value: any) => { const extracted = extractor ? extractor(value) : extractor === undefined ? HTMLInputExtractor(value) : value setField(key, extracted) validate(key, extracted) } } type FieldReturn = { [getter in G]: ReturnType> } & { [setter in S]: F[K] } function field(key: K): FieldReturn function field(key: K, opts: FieldOptions): FieldReturn function field(key: K, opts?: FieldOptions): FieldReturn { return { [opts?.getter || 'onChange']: update(key, opts?.extractor), [opts?.setter || 'value']: form[key], } as FieldReturn } return { form, field, errors, isValid, setForm, setErrors, setField } }