summaryrefslogtreecommitdiff
path: root/packages/web-util/src/forms/useField.ts
blob: eed8cebeaed29b09fd2f3d68b4a83b250053f059 (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
92
93
import { useContext, useState } from "preact/compat";
import { FieldUIOptions, FormContext } from "./FormProvider.js";

export interface InputFieldHandler<Type> {
  value: Type;
  onChange: (s: Type) => void;
  state: FieldUIOptions;
  isDirty: boolean;
}

export function useField<T extends object, K extends keyof T>(
  name: K,
): InputFieldHandler<T[K]> {
  const {
    value: formValue,
    computeFormState,
    onUpdate: notifyUpdate,
    readOnly: readOnlyForm,
  } = 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;
  // console.log("USE FIELD", String(name), formValue.current, fieldValue);
  const [currentValue, setCurrentValue] = useState<any | undefined>(fieldValue);
  const fieldState =
    readField<Partial<FieldUIOptions>>(formState, String(name)) ?? {};

  //compute default state
  const state = {
    disabled: readOnlyForm ? true : (fieldState.disabled ?? false),
    hidden: fieldState.hidden ?? false,
    error: fieldState.error,
    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,
    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,
  debug?: boolean,
): T | undefined {
  return name.split(".").reduce((prev, current) => {
    if (debug) {
      console.log(
        "READ",
        name,
        prev,
        current,
        prev ? prev[current] : undefined,
      );
    }
    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) };
}