formhero/lib/index.ts

100 lines
3.7 KiB
TypeScript
Raw Permalink Normal View History

2023-01-31 00:30:31 +00:00
import * as React from 'react'
2023-03-03 22:08:54 +00:00
import { useMemo, useState } from 'react'
2019-09-26 19:13:27 +00:00
2023-03-03 22:08:54 +00:00
// Possible future ideas
// TODO: Scroll to error field
// TODO: Focus on error field
export type FieldOptions<G extends string = 'onChange', S extends string = 'value', T = any> = {
extractor?: useFormExtractor<T> | null
getter?: G
setter?: S
2019-09-26 19:13:27 +00:00
}
2023-01-31 00:26:27 +00:00
type RuleFunctionReturn = boolean | string
2023-03-03 22:08:54 +00:00
type RuleFunction<I, F> = (value: I, data: F) => RuleFunctionReturn | Promise<RuleFunctionReturn>
type Rule<I, F> = RuleFunction<I, F> | RegExp
type RuleObject<I, F> = Rule<I, F> | { rule: Rule<I, F>; message: string }
type RuleSet<I, F> = RuleObject<I, F> | RuleObject<I, F>[]
2019-09-26 19:13:27 +00:00
2023-03-03 22:08:54 +00:00
function isSimpleRule<I, F>(obj: RuleObject<I, F>): obj is Rule<I, F> {
2023-01-31 00:26:27 +00:00
return obj instanceof RegExp || typeof obj === 'function'
2019-09-26 19:13:27 +00:00
}
2023-03-03 22:08:54 +00:00
export type useFormExtractor<T = any> = (from: any) => T
export const NoExtractor: useFormExtractor = (v: unknown) => v
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
2023-01-31 00:26:27 +00:00
export type FormOptions<R> = {
rules: R
2019-09-28 17:00:49 +00:00
}
2023-03-03 22:08:54 +00:00
// F = Type of form
2023-01-31 00:26:27 +00:00
// R = Rules, derived from F
// E = Errors, derived from F
2023-03-03 22:08:54 +00:00
export const useForm = <F extends object, R extends { [K in keyof F]?: RuleSet<F[K], F> }, E extends { [key in keyof R]?: RuleFunctionReturn }>(init: F, options?: FormOptions<R>) => {
2023-01-31 00:26:27 +00:00
const validators: R = options?.rules ?? ({} as R)
2019-10-19 06:36:50 +00:00
2023-03-03 22:08:54 +00:00
const [form, setForm] = useState<F>(init)
2023-01-31 00:26:27 +00:00
const [errors, setErrors] = useState<E>({} as E)
2023-03-03 22:08:54 +00:00
const isValid = useMemo(() => {
return !Object.values(errors).reduce((acc, cur) => acc || cur !== undefined, false)
2019-10-19 06:36:50 +00:00
}, [errors])
2023-03-03 22:08:54 +00:00
const setField = <A extends keyof F>(key: A, value: F[A]) => {
2019-10-19 06:36:50 +00:00
setForm({
...form,
[key]: value,
})
}
2023-03-03 22:08:54 +00:00
async function applyRule<I>(value: any, rule: Rule<I, F>): Promise<RuleFunctionReturn> {
if (typeof rule === 'function') return await rule(value, form)
2023-01-31 00:26:27 +00:00
if (rule instanceof RegExp) return rule.test(value)
throw new Error(`Unsupported validator: ${rule}`)
2019-10-19 06:36:50 +00:00
}
2023-03-03 22:08:54 +00:00
async function validate<K extends keyof F>(key: K, value: F[K]) {
const set: RuleSet<F[K], F> | undefined = validators[key] as any
2023-01-31 00:26:27 +00:00
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
}
2019-10-19 06:36:50 +00:00
}
2023-01-31 00:26:27 +00:00
setErrors({
...errors,
[key]: newValue,
})
2019-10-19 06:36:50 +00:00
}
2023-03-03 22:08:54 +00:00
// Internal use
function update<A extends keyof F>(key: A, extractor?: useFormExtractor<F[A]> | null) {
return (value: any) => {
const extracted = extractor ? extractor(value) : extractor === undefined ? HTMLInputExtractor(value) : value
2023-01-31 00:26:27 +00:00
setField(key, extracted)
validate(key, extracted)
}
2019-10-19 06:36:50 +00:00
}
2023-03-03 22:08:54 +00:00
type FieldReturn<K extends keyof F, G extends string, S extends string> = { [getter in G]: ReturnType<typeof update<K>> } & { [setter in S]: F[K] }
function field<K extends keyof F>(key: K): FieldReturn<K, 'onChange', 'value'>
function field<K extends keyof F, G extends string, S extends string>(key: K, opts: FieldOptions<G, S, F[K]>): FieldReturn<K, G, S>
function field<K extends keyof F, G extends string, S extends string>(key: K, opts?: FieldOptions<G, S, F[K]>): FieldReturn<K, G, S> {
2023-01-31 00:26:27 +00:00
return {
[opts?.getter || 'onChange']: update<K>(key, opts?.extractor),
[opts?.setter || 'value']: form[key],
} as FieldReturn<K, G, S>
}
2019-10-19 06:36:50 +00:00
2023-01-31 00:26:27 +00:00
return { form, field, errors, isValid, setForm, setErrors, setField }
2019-10-19 06:36:50 +00:00
}