31 lines
975 B
TypeScript
31 lines
975 B
TypeScript
import { DOMEvent } from "@/helpers";
|
|
|
|
type UpdatingEvent = "onBlur" | "onChange" | "onInput";
|
|
type FormFieldHelperOptions<T> = {
|
|
event: UpdatingEvent,
|
|
property: string,
|
|
}
|
|
|
|
export function formFieldProps<T>(subject: T, update: (value: T) => void, options: Partial<FormFieldHelperOptions<T>> = {}) {
|
|
const {
|
|
event = "onChange",
|
|
property = "value",
|
|
} = options;
|
|
|
|
return <P extends keyof T, TArgs extends any[]>(
|
|
field: P,
|
|
extractor: (...args: TArgs) => T[P] = ((event: DOMEvent<HTMLInputElement>) => event.target.value as unknown as T[P]) as any
|
|
): any => ({
|
|
[property]: subject[field],
|
|
[event]: (...args: TArgs) => update({
|
|
...subject,
|
|
[field]: extractor(...args),
|
|
} as T)
|
|
})
|
|
}
|
|
|
|
|
|
export type BoundProperty<T, TEvent extends string = 'onChange', TProperty extends string = 'value'> =
|
|
{ [property in TProperty]: T; } &
|
|
{ [event in TEvent]: (value: T) => void; }
|