All files / Form Form.tsx

26.67% Statements 8/30
35% Branches 7/20
15.38% Functions 2/13
26.67% Lines 8/30

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 173                                                                                      2x 2x   2x                                       2x           2x                   2x             6x               6x                                                                                                                                                      
import React, { memo, useEffect, useState, ReactNode } from 'react';
import isEmpty from 'lodash/isEmpty';
import isEqual from 'lodash/isEqual';
 
import Grid from '@material-ui/core/Grid';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField, { StandardTextFieldProps } from '@material-ui/core/TextField';
import MenuItem from '@material-ui/core/MenuItem';
 
import Button from './../Button';
 
import './Form.css';
 
/**
 * We can improve this component in two way:
 * 	1. Export IField interface (many app already use a copy of it, make code redundant)
 * 	2. Improve type: we have too much "any" in the code!
 */
 
interface IField extends StandardTextFieldProps {
  fieldName: string;
  icon?: ReactNode;
  autocomplete?: boolean;
  items?: any; // TODO: improve it
}
 
export interface IProps {
  fields: IField[];
  onSubmit?: (fields: any) => any;
  submitLabel?: string;
  onValidate?: (fields: any) => any;
  onChange?: (fields: any) => any;
  children: ReactNode;
}
 
export function Form({
  fields,
  onSubmit,
  submitLabel,
  onValidate,
  onChange,
  children
}: IProps) {
  const [fieldsState, changeFieldsState] = useState<any>({});
  const [isValid, changeIsValid] = useState<boolean>(true);
 
  useEffect(() => {
    let newFields = { ...fieldsState };
 
    fields.forEach((f) => {
      newFields = {
        ...newFields,
        [f.fieldName]: f.value
      };
    });
 
    /**
     * If doesn't exist any difference, i don't need state update
     */
    if (isEqual(newFields, fieldsState)) {
      return;
    }
 
    changeFieldsState(newFields);
  }, [fields]);
 
  useEffect(() => {
    if (onValidate) {
      changeIsValid(onValidate(fieldsState));
    }
  }, [fieldsState]);
 
  const handleSubmit = (e: any) => {
    e.preventDefault()
    
    if (!onSubmit || !isValid) {
      return
    }
 
    onSubmit(fieldsState)
  }
 
  return (
    <form onSubmit={handleSubmit}>
    <Grid container direction='column' spacing={1}>
      <Grid item>
        <Grid container spacing={3}>
          {fields?.map(
            ({ fieldName, autocomplete, items, fullWidth, ...rest }) => {
              const commonProps: any = {
                ...rest,
                variant: 'outlined',
                InputLabelProps: { shrink: true },
                fullWidth: true,
                value: fieldsState[fieldName]
              };
 
              return (
                <Grid item key={fieldName} xs={12} md={fullWidth ? 12 : 6}>
                  {!isEmpty(items) && autocomplete ? (
                    <Autocomplete
                      onChange={(_: any, target: any) =>
                        changeFieldsState({
                          ...fieldsState,
                          [fieldName]: target?.value
                        })
                      }
                      options={items}
                      getOptionLabel={(option) => option.label}
                      value={{
                        ...items.find(
                          (i: any) => i.value === fieldsState[fieldName]
                        )
                      }}
                      renderInput={(params: any) => (
                        <TextField {...params} {...commonProps} />
                      )}
                      disableClearable
                    />
                  ) : (
                    <TextField
                      {...commonProps}
                      select={!isEmpty(items)}
                      onChange={(e: any) => {
                        const newFields = {
                          ...fieldsState,
                          [fieldName]: e.target.value
                        };
                        changeFieldsState(newFields);
 
                        if (onChange) {
                          onChange(newFields);
                        }
                      }}
                    >
                      {items?.map((item: any) => (
                        <MenuItem key={item.value} value={item.value}>
                          {item.label}
                        </MenuItem>
                      ))}
                    </TextField>
                  )}
                </Grid>
              );
            }
          )}
          {children}
        </Grid>
      </Grid>
      {onSubmit && (
        <Grid item>
          <Grid container spacing={1} justify='flex-end'>
            <Grid item>
              <Button
              type='submit'
                className='Form__submit'
                disabled={!isValid}
                onClick={() => onSubmit(fieldsState)}
                color='primary'
              >
                {submitLabel ?? 'Salva'}
              </Button>
            </Grid>
          </Grid>
        </Grid>
      )}
    </Grid>
    </form>
  );
}
 
export default memo(Form);