import { AbsoluteTime, AmountJson, TranslatedString, } from "@gnu-taler/taler-util"; import { ComponentChildren, VNode, createContext, h } from "preact"; import { MutableRef, StateUpdater, useEffect, useRef, useState, } from "preact/hooks"; export interface FormType { value: MutableRef>; initialValue?: Partial; onUpdate?: StateUpdater; computeFormState?: (v: T) => FormState; } //@ts-ignore export const FormContext = createContext>({}); export type FormState = { [field in keyof T]?: T[field] extends AbsoluteTime ? Partial : T[field] extends AmountJson ? Partial : T[field] extends Array ? Partial> : T[field] extends (object | undefined) ? FormState : Partial; }; export interface InputFieldState { /* should show the error */ error?: TranslatedString; /* should not allow to edit */ readonly: boolean; /* should show as disable */ disabled: boolean; /* should not show */ hidden: boolean; } export interface InputArrayFieldState extends InputFieldState { elements: FormState[]; } export function FormProvider({ children, initialValue, onUpdate: notify, onSubmit, computeFormState, }: { initialValue?: Partial; onUpdate?: (v: Partial) => void; onSubmit?: (v: Partial, s: FormState | undefined) => void; computeFormState?: (v: Partial) => FormState; children: ComponentChildren; }): VNode { // const value = useRef(initialValue ?? {}); // useEffect(() => { // return function onUnload() { // value.current = initialValue ?? {}; // }; // }); // const onUpdate = notify const [state, setState] = useState>(initialValue ?? {}); const value = { current: state }; // console.log("RENDER", initialValue, value); const onUpdate = (v: typeof state) => { // console.log("updated"); setState(v); if (notify) notify(v); }; return (
{ e.preventDefault(); //@ts-ignore if (onSubmit) onSubmit( value.current, !computeFormState ? undefined : computeFormState(value.current), ); }} > {children}
); }