All files / packages/hooks/src request.ts

94.23% Statements 49/52
85.71% Branches 18/21
92.3% Functions 12/13
94.23% Lines 49/52

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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172                                                      1x                     13x 13x     13x 13x 12x       13x 1x     13x 7x 5x     2x 2x     13x   4x   4x 4x       4x 4x 4x     4x         13x 1x           13x   7x   7x 1x 1x     6x 6x 4x 4x     2x                   13x 1x 1x 1x         13x   1x 1x       1x 1x   1x         1x             13x   1x               13x   4x                 13x                
import { useCallback, useEffect, useRef } from "react";
import { FieldErrors, FieldValues, Path, UseFormReturn } from "react-hook-form";
import { DateType } from "react-native-ui-datepicker";
 
import { isDisabledDate } from "@repo/utils/date";
 
type ValidationFieldPath<T extends FieldValues> =
  | Path<T>
  | `${Path<T>}.${string}`
  | "root";
 
interface ValidationResult<T extends FieldValues> {
  isValid: boolean;
  fieldErrors: Partial<Record<ValidationFieldPath<T>, string>>;
}
 
interface UseRequestFormParams<T extends FieldValues> {
  onBack: () => void;
  onSubmit: (data: T) => void;
  onScreenBlur?: (closeModals: () => void) => void;
  closeModals: () => void;
  methods: UseFormReturn<T>;
  holidays?: string[];
  makeUpWorkdays?: string[];
  validateBeforeSubmit?: (data: T) => ValidationResult<T>;
}
 
export const useRequestForm = <T extends FieldValues>({
  onBack,
  onSubmit,
  onScreenBlur,
  closeModals,
  methods,
  holidays = [],
  makeUpWorkdays = [],
  validateBeforeSubmit,
}: UseRequestFormParams<T>) => {
  const { clearErrors, getValues, handleSubmit, setError, setValue, watch } =
    methods;
  const manualValidationFieldsRef = useRef<Path<T>[]>([]);
 
  // Register close function with parent component (host app)
  useEffect(() => {
    if (onScreenBlur) {
      onScreenBlur(closeModals);
    }
  }, [onScreenBlur, closeModals]);
 
  const handlePressBack = useCallback(() => {
    onBack();
  }, [onBack]);
 
  const clearManualValidationErrors = useCallback(() => {
    if (manualValidationFieldsRef.current.length === 0) {
      return;
    }
 
    clearErrors(manualValidationFieldsRef.current);
    manualValidationFieldsRef.current = [];
  }, [clearErrors]);
 
  const applyManualValidationErrors = useCallback(
    (fieldErrors: ValidationResult<T>["fieldErrors"]) => {
      const manualFields: Path<T>[] = [];
 
      for (const [field, message] of Object.entries(fieldErrors)) {
        Iif (!message) {
          continue;
        }
 
        const fieldPath = field as Path<T>;
        manualFields.push(fieldPath);
        setError(fieldPath, { type: "manual", message });
      }
 
      manualValidationFieldsRef.current = manualFields;
    },
    [setError],
  );
 
  const removeManualValidationField = useCallback((field: Path<T>) => {
    manualValidationFieldsRef.current =
      manualValidationFieldsRef.current.filter(
        (errorField) => errorField !== field,
      );
  }, []);
 
  const handleSendRequest = useCallback(
    (data: T) => {
      clearManualValidationErrors();
 
      if (!validateBeforeSubmit) {
        onSubmit(data);
        return;
      }
 
      const validationResult = validateBeforeSubmit(data);
      if (!validationResult.isValid) {
        applyManualValidationErrors(validationResult.fieldErrors);
        return;
      }
 
      onSubmit(data);
    },
    [
      applyManualValidationErrors,
      clearManualValidationErrors,
      onSubmit,
      validateBeforeSubmit,
    ],
  );
 
  const createClearErrorCallback = useCallback(
    (field: Path<T>) => () => {
      clearErrors(field);
      removeManualValidationField(field);
    },
    [clearErrors, removeManualValidationField],
  );
 
  const handleInvalidSubmit = useCallback(
    (errors: FieldErrors<T>) => {
      for (const field of Object.keys(errors)) {
        Iif (field === "root") {
          continue;
        }
 
        const fieldPath = field as Path<T>;
        const currentValue = getValues(fieldPath);
 
        Eif (
          typeof currentValue === "string" &&
          currentValue.length > 0 &&
          currentValue.trim().length === 0
        ) {
          setValue(fieldPath, "" as never, { shouldDirty: true });
        }
      }
    },
    [getValues, setValue],
  );
 
  const disabledDates = useCallback(
    (date: DateType) =>
      isDisabledDate({
        date: date as Date,
        holidays,
        makeUpWorkdays,
      }),
    [holidays, makeUpWorkdays],
  );
 
  const disabledDatesFromStart = useCallback(
    (date: DateType) =>
      isDisabledDate({
        date: date as Date,
        holidays,
        makeUpWorkdays,
        startDate: watch("startDate" as Path<T>) || undefined,
      }),
    [holidays, makeUpWorkdays, watch],
  );
 
  return {
    handlePressBack,
    handleSendRequest: handleSubmit(handleSendRequest, handleInvalidSubmit),
    createClearErrorCallback,
    disabledDates,
    disabledDatesFromStart,
  };
};