• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 1301920191

23 May 2024 07:13AM UTC coverage: 83.42% (-16.5%) from 99.964%
1301920191

Pull #4421

gitlab-ci

mzedel
fix: fixed an issue that sometimes prevented reopening paginated auditlog links

Ticket: None
Changelog: Title
Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4421: MEN-7034 - device information in auditlog entries

4456 of 6367 branches covered (69.99%)

34 of 35 new or added lines in 7 files covered. (97.14%)

1668 existing lines in 162 files now uncovered.

8473 of 10157 relevant lines covered (83.42%)

140.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.31
/src/js/components/common/forms/form.js
1
// Copyright 2016 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useEffect } from 'react';
15
import { FormProvider, useForm } from 'react-hook-form';
16

17
import { Button } from '@mui/material';
18

19
import validator from 'validator';
20

21
const getErrorMsg = (validateMethod, args) => {
17✔
22
  switch (validateMethod) {
189!
23
    case 'isLength':
24
      if (args[0] === 1) {
47!
UNCOV
25
        return 'This field is required';
×
26
      } else if (args[0] > 1) {
47!
27
        return `Must be at least ${args[0]} characters long`;
47✔
28
      }
UNCOV
29
      break;
×
30
    case 'isAlpha':
UNCOV
31
      return 'This field must contain only letters';
×
32
    case 'isAlphanumeric':
UNCOV
33
      return 'This field must contain only letters or numbers';
×
34
    case 'isNumeric':
UNCOV
35
      return 'Please enter a valid code';
×
36
    case 'isEmail':
37
      return 'Please enter a valid email address';
108✔
38
    case 'isNot':
39
      if (args[0] === args[1]) {
34!
UNCOV
40
        return `This field should have a value other than ${args[0]}`;
×
41
      }
42
      break;
34✔
43
    default:
UNCOV
44
      return 'There is an error with this field';
×
45
  }
46
};
47

48
const tryApplyValidations = (value, validations, initialValidationResult) =>
17✔
49
  validations.split(',').reduce((accu, validation) => {
433✔
50
    if (!accu.isValid || !validation) {
893✔
51
      return accu;
185✔
52
    }
53
    var args = validation.split(':');
708✔
54
    var validateMethod = args.shift();
708✔
55
    // We use JSON.parse to convert the string values passed to the
56
    // correct type. Ex. 'isLength:1' will make '1' actually a number
57
    args = args.map(arg => JSON.parse(JSON.stringify(arg)));
708✔
58

59
    var tmpArgs = args;
708✔
60
    // We then merge two arrays, ending up with the value
61
    // to pass first, then options, if any. ['valueFromInput', 5]
62
    args = [value].concat(args);
708✔
63
    try {
708✔
64
      // So the next line of code is actually:
65
      // validator.isLength('valueFromInput', 5)
66
      if (!validator[validateMethod].apply(validator, args)) {
708✔
67
        return { errortext: getErrorMsg(validateMethod, tmpArgs), isValid: false };
155✔
68
      }
69
    } catch {
70
      const errortext = getErrorMsg(validateMethod, args) || '';
34✔
71
      return { errortext, isValid: !errortext };
34✔
72
    }
73
    return accu;
519✔
74
  }, initialValidationResult);
75

76
const runPasswordValidations = ({ required, value, validations, isValid, errortext }) => {
17✔
77
  if (required && !value) {
233!
UNCOV
78
    return { isValid: false, errortext: 'Password is required' };
×
79
  } else if (required || value) {
233✔
80
    isValid = tryApplyValidations(value, validations, { isValid, errortext }).isValid;
213✔
81
    return { isValid, errortext: !isValid ? 'Password too weak' : errortext };
213✔
82
  }
83
  return { isValid, errortext };
20✔
84
};
85

86
export const runValidations = ({ required, value, id, validations }) => {
17✔
87
  let isValid = true;
485✔
88
  let errortext = '';
485✔
89
  if (id && id.includes('password')) {
485✔
90
    return runPasswordValidations({ required, value, validations, isValid, errortext });
233✔
91
  } else {
92
    if (value || required) {
252✔
93
      return tryApplyValidations(validations.includes('trim') ? value.trim() : value, validations, { isValid, errortext });
220✔
94
    }
95
  }
96
  return { isValid, errortext };
32✔
97
};
98

99
export const Form = ({
17✔
100
  autocomplete,
101
  buttonColor,
102
  children,
103
  className = '',
292✔
104
  defaultValues = {},
293✔
105
  handleCancel,
106
  id,
107
  initialValues = {},
313✔
108
  onSubmit,
109
  showButtons,
110
  submitLabel
111
}) => {
112
  const methods = useForm({ mode: 'onChange', defaultValues });
390✔
113
  const {
114
    handleSubmit,
115
    formState: { isValid },
116
    setValue
117
  } = methods;
390✔
118

119
  useEffect(() => {
390✔
120
    Object.entries(initialValues).map(([key, value]) => setValue(key, value));
26✔
121
    // eslint-disable-next-line react-hooks/exhaustive-deps
122
  }, [JSON.stringify(initialValues), setValue]);
123

124
  return (
390✔
125
    <FormProvider {...methods}>
126
      <form autoComplete={autocomplete} className={className} id={id} noValidate onSubmit={handleSubmit(onSubmit)}>
127
        {children}
128
        {!!showButtons && (
714✔
129
          <div className="flexbox" style={{ justifyContent: 'flex-end', height: 'min-content', marginTop: 32 }}>
130
            {!!handleCancel && (
394✔
131
              <Button key="cancel" onClick={handleCancel} style={{ marginRight: 10, display: 'inline-block' }}>
132
                Cancel
133
              </Button>
134
            )}
135
            <Button variant="contained" type="submit" disabled={!isValid} color={buttonColor}>
136
              {submitLabel}
137
            </Button>
138
          </div>
139
        )}
140
      </form>
141
    </FormProvider>
142
  );
143
};
144

145
export default Form;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc