All files / react-app/src/components/RHF/utils initializer.ts

100% Statements 42/42
100% Branches 21/21
100% Functions 8/8
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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        107x 7x 7x       107x 17x 24x   24x 2x 2x 2x     24x 7x 1x           6x     24x   1x   1x 1x   1x 1x 1x   1x 1x 1x   2x 2x   1x 1x   1x 1x       1x 1x           15x 15x     24x     107x 5x 10x 10x      
import { FormGroup, FormSchema, RHFOption, RHFSlotProps } from "shared-types/forms";
 
type GL = Record<string, unknown>;
 
export const formGroupInitializer = (parentId?: string) => (ACC: GL, FORM: FormGroup) => {
  FORM.slots.reduce(slotInitializer(parentId), ACC);
  return ACC;
};
 
export const slotInitializer =
  (parentId?: string) =>
  (ACC: GL, SLOT: RHFSlotProps): GL => {
    const adjustedName = `${parentId ?? ""}${SLOT.name}`;
 
    const optionReducer = (OPT: RHFOption) => {
      if (OPT.form) OPT.form.reduce(formGroupInitializer(parentId), ACC);
      if (OPT.slots) OPT.slots.reduce(slotInitializer(parentId), ACC);
      return ACC;
    };
 
    const fieldInitializer = (ACC1: GL, SLOTC: RHFSlotProps): GL => {
      if (SLOTC.rhf === "FieldArray") {
        return {
          ...ACC1,
          [SLOTC.name]: [SLOTC.fields?.reduce(fieldInitializer, {})],
        };
      }
 
      return { ...ACC1, ...slotInitializer()(ACC1, SLOTC) };
    };
 
    switch (SLOT.rhf) {
      case "TextDisplay":
        break;
      case "Switch":
        ACC[adjustedName] = false;
        break;
      case "Checkbox":
        SLOT.props?.options.forEach(optionReducer);
        ACC[adjustedName] = [];
        break;
      case "Radio":
        SLOT.props?.options.forEach(optionReducer);
        ACC[adjustedName] = "";
        break;
      case "FieldArray":
        ACC[adjustedName] = [SLOT.fields?.reduce(fieldInitializer, {})];
        break;
      case "WrappedGroup":
        ACC = { ...ACC, ...SLOT.fields?.reduce(fieldInitializer, {}) };
        break;
      case "Upload":
        ACC[adjustedName] = [];
        break;
      // If switching from undefined to a Date causes an error from RHF,
      // DatePickerProps in inputs.ts may need to be adjusted:
      case "DatePicker":
        ACC[adjustedName] = undefined;
        break;
      case "Input":
      case "Select":
      case "Multiselect":
      case "Textarea":
      default:
        ACC[adjustedName] = "";
        break;
    }
 
    return ACC;
  };
 
export const documentInitializer = (document: FormSchema) => {
  return document.sections.reduce((ACC, SEC) => {
    SEC.form.reduce(formGroupInitializer(`${document.formId}_${SEC.sectionId}_`), ACC);
    return ACC;
  }, {});
};