summaryrefslogtreecommitdiff
path: root/packages/exchange-backoffice-ui/src/forms/useField.ts
blob: 6f7b841122c1f75d57c59ec9fd94214d2822579e (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
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,
  } = useContext(FormContext);
  type P = typeof name;
  type V = T[P];
  const [isDirty, setDirty] = useState(false);
  const formState = computeFormState ? computeFormState(formValue) : {};

  const fieldValue = readField(formValue, String(name)) as V;
  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 {
    setDirty(true);
    return onUpdate((prev: any) => {
      return setValueDeeper(prev, String(name).split("."), value);
    });
  }

  return {
    value: fieldValue,
    onChange,
    isDirty,
    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) };
}