aboutsummaryrefslogtreecommitdiff
path: root/packages/exchange-backoffice-ui/src/forms/useField.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/exchange-backoffice-ui/src/forms/useField.ts')
-rw-r--r--packages/exchange-backoffice-ui/src/forms/useField.ts77
1 files changed, 0 insertions, 77 deletions
diff --git a/packages/exchange-backoffice-ui/src/forms/useField.ts b/packages/exchange-backoffice-ui/src/forms/useField.ts
deleted file mode 100644
index f54dc7465..000000000
--- a/packages/exchange-backoffice-ui/src/forms/useField.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { TargetedEvent, useContext, useState } from "preact/compat";
-import { FormContext, InputFieldState } from "./FormProvider.js";
-
-export interface InputFieldHandler<Type> {
- value: Type;
- onChange: (s: Type) => void;
- state: InputFieldState;
- isDirty: boolean;
-}
-
-export function useField<T>(name: keyof T): InputFieldHandler<T[keyof T]> {
- const {
- initialValue,
- value: formValue,
- computeFormState,
- onUpdate: notifyUpdate,
- } = useContext(FormContext);
- type P = typeof name;
- type V = T[P];
- const formState = computeFormState ? computeFormState(formValue.current) : {};
-
- const fieldValue = readField(formValue.current, String(name)) as V;
- const [currentValue, setCurrentValue] = useState<any | undefined>(undefined);
- const fieldState = readField<Partial<InputFieldState>>(
- formState,
- String(name),
- );
-
- //default state
- const state: InputFieldState = {
- disabled: fieldState?.disabled ?? false,
- readonly: fieldState?.readonly ?? false,
- hidden: fieldState?.hidden ?? false,
- error: fieldState?.error,
- };
-
- function onChange(value: V): void {
- setCurrentValue(value);
- formValue.current = setValueDeeper(
- formValue.current,
- String(name).split("."),
- value,
- );
- if (notifyUpdate) {
- notifyUpdate(formValue.current);
- }
- }
-
- return {
- value: fieldValue,
- onChange,
- isDirty: currentValue !== undefined,
- state,
- };
-}
-
-/**
- * read the field of an object an support accessing it using '.'
- *
- * @param object
- * @param name
- * @returns
- */
-function readField<T>(object: any, name: string): T | undefined {
- return name
- .split(".")
- .reduce((prev, current) => prev && prev[current], object);
-}
-
-function setValueDeeper(object: any, names: string[], value: any): any {
- if (names.length === 0) return value;
- const [head, ...rest] = names;
- if (object === undefined) {
- return { [head]: setValueDeeper({}, rest, value) };
- }
- return { ...object, [head]: setValueDeeper(object[head] ?? {}, rest, value) };
-}