summaryrefslogtreecommitdiff
path: root/packages/web-util/src/forms/useField.ts
blob: d30962c6fb4039f4abfa7ca92e4a199626a4b709 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { useContext } from "preact/compat";
import { FieldUIOptions, FormContext } from "./FormProvider.js";
import { TranslatedString } from "@gnu-taler/taler-util";

export interface InputFieldHandler<Type> {
  value: Type;
  onChange: (s: Type) => void;
  state: FieldUIOptions;
  error?: TranslatedString | undefined;
}

/**
 * @depreacted removing this so we don't depend on context to create a form
 * @param name 
 * @returns 
 */
export function useField<T extends object, K extends keyof T>(
  name: K,
): InputFieldHandler<T[K]> | undefined {
  const ctx = useContext(FormContext);
  if (!ctx) {
    //no context, can't be used
    return undefined;
  }
  const {
    value: formValue,
    computeFormState,
    onUpdate: notifyUpdate,
    readOnly: readOnlyForm,
  } = ctx

  type P = typeof name;
  type V = T[P];
  const formState = computeFormState ? computeFormState(formValue.current) : {};

  const fieldValue = readField(formValue.current, String(name)) as V;

  const fieldState =
    readField<Partial<FieldUIOptions>>(formState, String(name)) ?? {};

  //compute default state
  const state = {
    disabled: readOnlyForm ? true : (fieldState.disabled ?? false),
    hidden: fieldState.hidden ?? false,
    help: fieldState.help,
    elements: "elements" in fieldState ? fieldState.elements ?? [] : [],
  };

  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,
    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) => {
    return prev ? prev[current] : undefined;
  }, 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) };
}