Passed
Push — task/update-profile-experience ( 897bfe...e35027 )
by Tristan
06:27
created

resources/assets/js/helpers/forms.ts   A

Complexity

Total Complexity 5
Complexity/F 0

Size

Lines of Code 66
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 37
mnd 5
bc 5
fnc 0
dl 0
loc 66
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { FormikProps, FormikValues } from "formik";
2
import isEmpty from "lodash/isEmpty";
3
import { RefObject } from "react";
4
import { notEmpty } from "./queries";
5
6
/**
7
 * Focuses on a element with given id.
8
 * @param id
9
 */
10
export const focusOnElement = (elementId: string): void => {
11
  const element = document.getElementById(elementId);
12
  if (element) {
13
    element.focus();
14
  }
15
};
16
17
/**
18
 * Toggle accordion with given id.
19
 * @param id
20
 */
21
export const toggleAccordion = (elementId: string): void => {
22
  const element = document.getElementById(elementId);
23
  if (element) {
24
    element.classList.toggle("active");
25
    const { firstElementChild } = element;
26
    if (firstElementChild) {
27
      firstElementChild.setAttribute("aria-expanded", "true");
28
    }
29
  }
30
};
31
32
/**
33
 * Runs validation on all forms, then returns true if they are all valid.
34
 * TODO: Figure out how to focus the first (or last) invalid input, if any.
35
 * @param refs
36
 */
37
export const validateAllForms = (
38
  refs: RefObject<FormikProps<FormikValues>>[],
39
): Promise<boolean> => {
40
  return Promise.all(
41
    refs
42
      .filter(notEmpty)
43
      .map(
44
        (ref: RefObject<FormikProps<FormikValues>>): Promise<any> =>
45
          ref.current !== null ? ref.current.validateForm() : Promise.resolve(),
46
      ),
47
  ).then((errors) => errors.every(isEmpty));
48
};
49
50
/**
51
 * Submits all forms.
52
 * @param refs
53
 */
54
export const submitAllForms = (
55
  refs: React.RefObject<FormikProps<FormikValues>>[],
56
): Promise<void[]> => {
57
  return Promise.all(
58
    refs.filter(notEmpty).map((ref: RefObject<FormikProps<FormikValues>>) => {
59
      // TODO: Might need to make one mass submission by combining all values into an array.
60
      return ref.current !== null
61
        ? ref.current.submitForm()
62
        : Promise.resolve();
63
    }),
64
  );
65
};
66