formhero/lib/index.ts

107 lines
3.5 KiB
TypeScript
Raw Normal View History

2019-09-28 17:00:49 +00:00
import React, { useState, useEffect } from 'react'
2019-09-26 19:13:27 +00:00
export type useFormExtractor = (from: any) => any
export type useFormOptions = {
extractor?: useFormExtractor,
getter?: string,
setter?: string,
2019-09-26 19:13:27 +00:00
}
export type useFormValidatorFunction = ((s: any) => boolean | Promise<boolean>)
export type useFormValidatorMethod = useFormValidatorFunction | RegExp
export type useFormValidatorObject = {
validator: useFormValidatorMethod,
message?: string,
}
export type useFormValidator = useFormValidatorMethod | useFormValidatorObject
2019-09-28 17:00:49 +00:00
export type useFormValidatorParameter = useFormValidator | useFormValidator[]
2019-09-26 19:13:27 +00:00
export const HTMLInputExtractor: useFormExtractor = (e: React.FormEvent<HTMLInputElement>) => e.currentTarget.value
export const HTMLCheckboxExtractor: useFormExtractor = (e: React.FormEvent<HTMLInputElement>) => e.currentTarget.checked
2019-09-28 17:00:49 +00:00
function isFormValidatorObject(validator: useFormValidatorMethod | useFormValidatorObject): validator is useFormValidatorObject {
return validator.constructor.name === 'Object'
}
const defaultErrorMessage = (key: any) => `Error in ${key}`
export const useForm = <T, U extends { [key in keyof T]: useFormValidatorParameter }, E extends { [key in keyof U]?: string }>(init: T, validators: Partial<U> = {}, options: useFormOptions = {}) => {
2019-09-26 19:13:27 +00:00
const [form, setForm] = useState<T>(init)
const [errors, setErrors] = useState<Partial<E>>({})
2019-09-28 17:00:49 +00:00
const [isValid, setIsValid] = useState(true);
useEffect(() => {
setIsValid(!Object.values(errors).reduce((acc, cur) => acc || cur !== undefined, false))
}, [errors])
2019-09-26 19:13:27 +00:00
const _set = (key: keyof T, value: any) => {
setForm({
...form,
[key]: value,
})
}
2019-09-28 17:00:49 +00:00
const _validateAll = async (value: any, object: useFormValidator): Promise<boolean> => {
const validator = isFormValidatorObject(object) ? object.validator : object
if (validator.constructor.name === 'Function')
2019-09-26 19:13:27 +00:00
return (validator as useFormValidatorFunction)(value)
2019-09-28 17:00:49 +00:00
else if (validator.constructor.name === 'AsyncFunction')
return await (validator as useFormValidatorFunction)(value)
2019-09-26 19:13:27 +00:00
else if (validator.constructor.name === 'RegExp')
return (validator as RegExp).test(value)
else return false
}
const _validate = (key: keyof T, value: any) => {
2019-09-28 17:00:49 +00:00
const validator: useFormValidatorParameter | undefined = validators[key]
2019-09-26 19:13:27 +00:00
if (!validator) return
2019-09-28 17:00:49 +00:00
if (Array.isArray(validator)) {
Promise.all(validator.map(v => _validateAll(value, v)))
.then(result => {
const index = result.indexOf(false)
setErrors({
...errors,
[key]: index === -1
? undefined
: isFormValidatorObject(validator[index]) && (validator[index] as useFormValidatorObject).message
? (validator[index] as useFormValidatorObject).message
: defaultErrorMessage(key)
})
})
} else {
_validateAll(value, validator)
.then(valid => {
setErrors({
...errors,
[key]: valid
? undefined
: isFormValidatorObject(validator) && validator.message
? validator.message
: defaultErrorMessage(key)
})
2019-09-26 19:13:27 +00:00
})
2019-09-28 17:00:49 +00:00
}
2019-09-26 19:13:27 +00:00
}
const update = (key: keyof T, extractor = options.extractor) => (value: any) => {
const extracted = extractor ? extractor(value) : HTMLInputExtractor(value)
_set(key, extracted)
_validate(key, extracted)
}
const auto = (key: keyof T, opts: useFormOptions = {}) => ({
[opts.getter || options.getter || 'onChange']: update(key, opts.extractor),
[opts.setter || options.setter || 'value']: form[key] as any,
2019-09-26 19:13:27 +00:00
})
2019-09-28 17:00:49 +00:00
return { form, update, auto, errors, isValid }
2019-09-26 19:13:27 +00:00
}