From c680f5aa71b08e978444df07f93c381f9d47ab82 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Mon, 5 Jun 2023 10:04:09 -0300 Subject: rename aml --- .../src/handlers/FormProvider.tsx | 99 ++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 packages/aml-backoffice-ui/src/handlers/FormProvider.tsx (limited to 'packages/aml-backoffice-ui/src/handlers/FormProvider.tsx') diff --git a/packages/aml-backoffice-ui/src/handlers/FormProvider.tsx b/packages/aml-backoffice-ui/src/handlers/FormProvider.tsx new file mode 100644 index 000000000..a195c2051 --- /dev/null +++ b/packages/aml-backoffice-ui/src/handlers/FormProvider.tsx @@ -0,0 +1,99 @@ +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 + ? 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} +
+
+ ); +} -- cgit v1.2.3