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

CSCfi / metadata-submitter-frontend / 16641888896

31 Jul 2025 06:42AM UTC coverage: 57.816% (+0.2%) from 57.653%
16641888896

push

github

Hang Le
Remove most of prefilled DOI form fields (merge commit)

Merge branch 'feature/remove-prefilled' into 'main'
* Remove schemeUri, affiliationIdentifierScheme, fullName from prefilled form text fields

Closes #1008
See merge request https://gitlab.ci.csc.fi/sds-dev/sd-submit/metadata-submitter-frontend/-/merge_requests/1138

Approved-by: Hang Le <lhang@csc.fi>
Co-authored-by: Monika Radaviciute <mradavic@csc.fi>
Merged by Hang Le <lhang@csc.fi>

658 of 929 branches covered (70.83%)

Branch coverage included in aggregate %.

9 of 13 new or added lines in 1 file covered. (69.23%)

1 existing line in 1 file now uncovered.

6173 of 10886 relevant lines covered (56.71%)

4.99 hits per line

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

66.47
/src/components/SubmissionWizard/WizardForms/WizardJSONSchemaParser.tsx
1
import * as React from "react"
1✔
2

3
import AddIcon from "@mui/icons-material/Add"
1✔
4
import ClearIcon from "@mui/icons-material/Clear"
1✔
5
import HelpOutlineIcon from "@mui/icons-material/HelpOutline"
1✔
6
import LaunchIcon from "@mui/icons-material/Launch"
1✔
7
import RemoveIcon from "@mui/icons-material/Remove"
1✔
8
import { FormControl } from "@mui/material"
1✔
9
import Autocomplete from "@mui/material/Autocomplete"
1✔
10
import Box from "@mui/material/Box"
1✔
11
import Button from "@mui/material/Button"
1✔
12
import Checkbox from "@mui/material/Checkbox"
1✔
13
import Chip from "@mui/material/Chip"
1✔
14
import CircularProgress from "@mui/material/CircularProgress"
1✔
15
import FormControlLabel from "@mui/material/FormControlLabel"
1✔
16
import FormGroup from "@mui/material/FormGroup"
1✔
17
import FormHelperText from "@mui/material/FormHelperText"
1✔
18
import Grid from "@mui/material/Grid"
1✔
19
import IconButton from "@mui/material/IconButton"
1✔
20
import Paper from "@mui/material/Paper"
1✔
21
import { styled } from "@mui/material/styles"
1✔
22
import { TypographyVariant } from "@mui/material/styles/createTypography"
23
import TextField from "@mui/material/TextField"
1✔
24
import Tooltip, { TooltipProps } from "@mui/material/Tooltip"
1✔
25
import Typography from "@mui/material/Typography"
1✔
26
import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"
1✔
27
import { DatePicker } from "@mui/x-date-pickers/DatePicker"
1✔
28
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"
1✔
29
import { get, flatten, uniq, debounce } from "lodash"
1✔
30
import moment from "moment"
1✔
31
import { useFieldArray, useFormContext, useForm, Controller, useWatch } from "react-hook-form"
1✔
32
import { useTranslation } from "react-i18next"
1✔
33

34
import { DisplayObjectTypes, ObjectTypes } from "constants/wizardObject"
1✔
35
import { setAutocompleteField } from "features/autocompleteSlice"
1✔
36
import { useAppSelector, useAppDispatch } from "hooks"
1✔
37
import rorAPIService from "services/rorAPI"
1✔
38
import { ConnectFormChildren, ConnectFormMethods, FormObject, NestedField } from "types"
39
import { pathToName, traverseValues, getPathName } from "utils/JSONSchemaUtils"
1✔
40

41
/*
42
 * Highlight style for required fields
43
 */
44
const highlightStyle = theme => {
1✔
45
  return {
×
46
    borderColor: theme.palette.primary.main,
×
47
    borderWidth: 2,
×
48
  }
×
49
}
×
50

51
const BaselineDiv = styled("div")({
1✔
52
  display: "flex",
1✔
53
  alignItems: "baseline",
1✔
54
})
1✔
55

56
const FieldTooltip = styled(({ className, ...props }: TooltipProps) => (
1✔
57
  <Tooltip {...props} classes={{ popper: className }} />
44✔
58
))(({ theme }) => ({
1✔
59
  "& .MuiTooltip-tooltip": {
44✔
60
    padding: "2rem",
44✔
61
    backgroundColor: theme.palette.common.white,
44✔
62
    color: theme.palette.secondary.main,
44✔
63
    fontSize: "1.4rem",
44✔
64
    boxShadow: theme.shadows[1],
44✔
65
    border: `0.1rem solid ${theme.palette.primary.main}`,
44✔
66
    maxWidth: "25rem",
44✔
67
  },
44✔
68
  "& .MuiTooltip-arrow": {
44✔
69
    "&:before": {
44✔
70
      border: `0.1rem solid ${theme.palette.primary.main}`,
44✔
71
    },
44✔
72
    color: theme.palette.common.white,
44✔
73
  },
44✔
74
}))
1✔
75

76
const TooltipIcon = styled(HelpOutlineIcon)(({ theme }) => ({
1✔
77
  color: theme.palette.primary.main,
48✔
78
  marginLeft: "1rem",
48✔
79
}))
1✔
80

81
/*
82
 * Clean up form values from empty strings and objects, translate numbers inside strings to numbers.
83
 */
84
const cleanUpFormValues = (data: unknown) => {
1✔
85
  const cleanedData = JSON.parse(JSON.stringify(data))
5✔
86
  return traverseFormValuesForCleanUp(cleanedData)
5✔
87
}
5✔
88

89
// Array is populated in traverseFields method.
90
const integerFields: Array<string> = []
1✔
91

92
const traverseFormValuesForCleanUp = (data: Record<string, unknown>) => {
1✔
93
  Object.keys(data).forEach(key => {
17✔
94
    const property = data[key] as Record<string, unknown> | string | null
70✔
95

96
    if (typeof property === "object" && !Array.isArray(property)) {
70✔
97
      if (property !== null) {
12✔
98
        data[key] = traverseFormValuesForCleanUp(property)
12✔
99
        if (Object.keys(property).length === 0) delete data[key]
12✔
100
      }
12✔
101
    }
12✔
102
    if (property === "") {
70✔
103
      delete data[key]
48✔
104
    }
48✔
105
    // Integer typed fields are considered as string like ID's which are numbers.
106
    // Therefore these fields need to be handled as string in the form and cast as number
107
    // for backend operations. Eg. "1234" is converted to 1234 so it passes backend validation
108
    else if (integerFields.indexOf(key) > -1) {
22✔
109
      data[key] = Number(data[key])
1✔
110
    }
1✔
111
  })
17✔
112
  return data
17✔
113
}
17✔
114

115
/*
116
 * Build react-hook-form fields based on given schema
117
 */
118
const buildFields = (schema: FormObject) => {
1✔
119
  try {
26✔
120
    return traverseFields(schema, [])
26✔
121
  } catch (error) {
26!
122
    console.error(error)
×
123
  }
×
124
}
26✔
125

126
/*
127
 * Allow children components inside ConnectForm to pull react-hook-form objects and methods from context
128
 */
129
const ConnectForm = ({ children }: ConnectFormChildren) => {
1✔
130
  const methods = useFormContext()
234✔
131
  return children({ ...(methods as ConnectFormMethods) })
234✔
132
}
234✔
133

134
/*
135
 * Get defaultValue for options in a form. Used when rendering a saved/submitted form
136
 */
137
const getDefaultValue = (name: string, nestedField?: Record<string, unknown>) => {
1✔
138
  if (nestedField) {
62✔
139
    let result
1✔
140
    const path = name.split(".")
1✔
141
    // E.g. Case of DOI form - Formats's fields
142
    if (path[0] === "formats") {
1!
143
      const k = path[0]
×
144
      if (k in nestedField) {
×
145
        result = nestedField[k]
×
146
      } else {
×
147
        return
×
148
      }
×
149
    } else {
1✔
150
      for (let i = 1, n = path.length; i < n; ++i) {
1✔
151
        const k = path[i]
1✔
152

153
        if (nestedField && k in nestedField) {
1!
154
          result = nestedField[k]
×
155
        } else {
1✔
156
          return
1✔
157
        }
1✔
158
      }
1!
159
    }
×
160
    return result
×
161
  } else {
62✔
162
    return ""
61✔
163
  }
61✔
164
}
62✔
165

166
/*
167
 * Traverse fields recursively, return correct fields for given object or log error, if object type is not supported.
168
 */
169
const traverseFields = (
1✔
170
  object: FormObject,
160✔
171
  path: string[],
160✔
172
  requiredProperties?: string[],
160✔
173
  requireFirst?: boolean,
160✔
174
  nestedField?: NestedField
160✔
175
) => {
160✔
176
  const name = pathToName(path)
160✔
177
  const [lastPathItem] = path.slice(-1)
160✔
178
  const label = object.title ?? lastPathItem
160!
179
  const required = !!requiredProperties?.includes(lastPathItem) || requireFirst || false
160✔
180
  const description = object.description
160✔
181
  const autoCompleteIdentifiers = ["organisation", "name of the place of affiliation"]
160✔
182

183
  if (object.oneOf)
160✔
184
    return (
160✔
185
      <FormSection key={name} name={name} label={label} level={path.length}>
6✔
186
        <FormOneOfField key={name} path={path} object={object} required={required} />
6✔
187
      </FormSection>
6✔
188
    )
189

190
  switch (object.type) {
154✔
191
    case "object": {
160✔
192
      const properties =
68✔
193
        label === DisplayObjectTypes.dataset && path.length === 0
68!
194
          ? { title: object.properties["title"], description: object.properties["description"] }
×
195
          : object.properties
68✔
196

197
      return (
68✔
198
        <FormSection
68✔
199
          key={name}
68✔
200
          name={name}
68✔
201
          label={label}
68✔
202
          level={path.length}
68✔
203
          description={description}
68✔
204
          isTitleShown
68✔
205
        >
206
          {Object.keys(properties).map(propertyKey => {
68✔
207
            const property = properties[propertyKey] as FormObject
132✔
208
            const required = object?.else?.required ?? object.required
132!
209
            let requireFirstItem = false
132✔
210

211
            if (
132✔
212
              path.length === 0 &&
132✔
213
              propertyKey === "title" &&
49!
214
              !object.title.includes("DAC - Data Access Committee")
×
215
            ) {
132!
216
              requireFirstItem = true
×
217
            }
×
218
            // Require first field of section if parent section is a required property
219
            if (
132✔
220
              requireFirst ||
132✔
221
              requiredProperties?.includes(name) ||
131✔
222
              requiredProperties?.includes(Object.keys(properties)[0])
109✔
223
            ) {
132✔
224
              const parentProperty = Object.values(properties)[0] as { title: string }
23✔
225
              requireFirstItem = parentProperty.title === property.title ? true : false
23✔
226
            }
23✔
227

228
            return traverseFields(
132✔
229
              property,
132✔
230
              [...path, propertyKey],
132✔
231
              required,
132✔
232
              requireFirstItem,
132✔
233
              nestedField
132✔
234
            )
132✔
235
          })}
68✔
236
        </FormSection>
68✔
237
      )
238
    }
68✔
239
    case "string": {
160✔
240
      return object["enum"] ? (
52✔
241
        <FormSection key={name} name={name} label={label} level={path.length}>
6✔
242
          <FormSelectField
6✔
243
            key={name}
6✔
244
            name={name}
6✔
245
            label={label}
6✔
246
            options={object.enum}
6✔
247
            required={required}
6✔
248
            description={description}
6✔
249
          />
250
        </FormSection>
6✔
251
      ) : object.title === "Date" ? (
46!
252
        <FormDatePicker
×
253
          key={name}
×
254
          name={name}
×
255
          label={label}
×
256
          required={required}
×
257
          description={description}
×
258
        />
259
      ) : autoCompleteIdentifiers.some(value => label.toLowerCase().includes(value)) ? (
46✔
260
        <FormAutocompleteField
5✔
261
          key={name}
5✔
262
          name={name}
5✔
263
          label={label}
5✔
264
          required={required}
5✔
265
          description={description}
5✔
266
        />
1✔
267
      ) : name.includes("keywords") ? (
41!
268
        <FormSection key={name} name={name} label={label} level={path.length}>
×
269
          <FormTagField
×
270
            key={name}
×
271
            name={name}
×
272
            label={label}
×
273
            required={required}
×
274
            description={description}
×
275
          />
276
        </FormSection>
×
277
      ) : (
278
        <FormSection key={name} name={name} label={label} level={path.length}>
41✔
279
          <FormTextField
41✔
280
            key={name}
41✔
281
            name={name}
41✔
282
            label={label}
41✔
283
            required={required}
41✔
284
            description={description}
41✔
285
            nestedField={nestedField}
41✔
286
          />
287
        </FormSection>
41✔
288
      )
289
    }
52✔
290
    case "integer": {
160✔
291
      // List fields with integer type in schema. List is used as helper when cleaning up fields for backend.
292
      const fieldName = name.split(".").pop()
10✔
293
      if (fieldName && integerFields.indexOf(fieldName) < 0) integerFields.push(fieldName)
10✔
294

295
      return (
10✔
296
        <FormSection key={name} name={name} label={label} level={path.length}>
10✔
297
          <FormTextField
10✔
298
            key={name}
10✔
299
            name={name}
10✔
300
            label={label}
10✔
301
            required={required}
10✔
302
            description={description}
10✔
303
          />
304
        </FormSection>
10✔
305
      )
306
    }
10✔
307
    case "number": {
160✔
308
      return (
6✔
309
        <FormTextField
6✔
310
          key={name}
6✔
311
          name={name}
6✔
312
          label={label}
6✔
313
          required={required}
6✔
314
          description={description}
6✔
315
          type="number"
6✔
316
        />
317
      )
318
    }
6✔
319
    case "boolean": {
160✔
320
      return (
6✔
321
        <FormBooleanField
6✔
322
          key={name}
6✔
323
          name={name}
6✔
324
          label={label}
6✔
325
          required={required}
6✔
326
          description={description}
6✔
327
        />
328
      )
329
    }
6✔
330
    case "array": {
160✔
331
      return object.items.enum ? (
12✔
332
        <FormSection key={name} name={name} label={label} level={path.length}>
6✔
333
          <FormCheckBoxArray
6✔
334
            key={name}
6✔
335
            name={name}
6✔
336
            label=""
6✔
337
            options={object.items.enum}
6✔
338
            required={required}
6✔
339
            description={description}
6✔
340
          />
341
        </FormSection>
6✔
342
      ) : (
343
        <FormArray
6✔
344
          key={name}
6✔
345
          object={object}
6✔
346
          path={path}
6✔
347
          required={required}
6✔
348
          description={description}
6✔
349
        />
350
      )
351
    }
12✔
352
    case "null": {
160!
353
      return null
×
354
    }
×
355
    default: {
160!
356
      console.error(`
×
357
      No field parsing support for type ${object.type} yet.
×
358

359
      Pretty printed version of object with unsupported type:
360
      ${JSON.stringify(object, null, 2)}
×
361
      `)
×
362
      return null
×
363
    }
×
364
  }
160✔
365
}
160✔
366

367
const DisplayDescription = ({
1✔
368
  description,
5✔
369
  children,
5✔
370
}: {
371
  description: string
372
  children?: React.ReactElement<unknown>
373
}) => {
5✔
374
  const { t } = useTranslation()
5✔
375
  const [isReadMore, setIsReadMore] = React.useState(description.length > 60)
5✔
376

377
  const toggleReadMore = () => {
5✔
378
    setIsReadMore(!isReadMore)
2✔
379
  }
2✔
380

381
  const ReadmoreText = styled("span")(({ theme }) => ({
5✔
382
    fontWeight: 700,
3✔
383
    textDecoration: "underline",
3✔
384
    display: "block",
3✔
385
    marginTop: "0.5rem",
3✔
386
    color: theme.palette.primary.main,
3✔
387
    "&:hover": { cursor: "pointer" },
3✔
388
  }))
5✔
389

390
  return (
5✔
391
    <p>
5✔
392
      {isReadMore ? `${description.slice(0, 60)}...` : description}
5✔
393
      {!isReadMore && children}
5✔
394
      {description?.length >= 60 && (
5✔
395
        <ReadmoreText onClick={toggleReadMore}>
4✔
396
          {isReadMore ? t("showMore") : t("showLess")}
4✔
397
        </ReadmoreText>
4✔
398
      )}
399
    </p>
5✔
400
  )
401
}
5✔
402

403
type FormSectionProps = {
404
  name: string
405
  label: string
406
  level: number
407
  isTitleShown?: boolean
408
  children?: React.ReactNode
409
}
410

411
const FormSectionTitle = styled(Paper, { shouldForwardProp: prop => prop !== "level" })<{
1✔
412
  level: number
413
}>(({ theme, level }) => ({
1✔
414
  display: "flex",
70✔
415
  flexDirection: "column",
70✔
416
  justifyContent: "start",
70✔
417
  alignItems: "start",
70✔
418
  backgroundColor: level === 1 ? theme.palette.primary.light : theme.palette.common.white,
70✔
419
  height: "100%",
70✔
420
  marginLeft: level <= 1 ? "5rem" : 0,
70!
421
  marginRight: "3rem",
70✔
422
  padding: level === 0 ? "4rem 0 3rem 0" : level === 1 ? "2rem" : 0,
70!
423
}))
1✔
424

425
/*
426
 * FormSection is rendered for properties with type object
427
 */
428
const FormSection = ({
1✔
429
  name,
137✔
430
  label,
137✔
431
  level,
137✔
432
  children,
137✔
433
  description,
137✔
434
  isTitleShown,
137✔
435
}: FormSectionProps & { description?: string }) => {
137✔
436
  const splittedPath = name.split(".") // Have a fully splitted path for names such as "studyLinks.0", "dacLinks.0"
137✔
437

438
  const heading = (
137✔
439
    <Grid size={{ xs: 12, md: level === 0 ? 12 : level === 1 ? 4 : 8 }}>
137✔
440
      {(level <= 1 || ((level === 3 || level === 2) && isTitleShown)) && label && (
137✔
441
        <FormSectionTitle square={true} elevation={0} level={level}>
70✔
442
          <Typography
70✔
443
            key={`${name}-header`}
70✔
444
            variant={level === 0 ? "h4" : ("subtitle1" as TypographyVariant)}
70✔
445
            role="heading"
70✔
446
            color="secondary"
70✔
447
          >
448
            {label} {name.includes("keywords") ? "*" : ""}
70!
449
            {description && level === 1 && (
70✔
450
              <FieldTooltip
11✔
451
                title={<DisplayDescription description={description} />}
11✔
452
                placement="top"
11✔
453
                arrow
11✔
454
                describeChild
11✔
455
              >
456
                <TooltipIcon />
11✔
457
              </FieldTooltip>
11✔
458
            )}
459
          </Typography>
70✔
460
        </FormSectionTitle>
70✔
461
      )}
462
    </Grid>
137✔
463
  )
464

465
  return (
137✔
466
    <ConnectForm>
137✔
467
      {({ errors }: ConnectFormMethods) => {
137✔
468
        const error = get(errors, name)
137✔
469
        return (
137✔
470
          <>
137✔
471
            <Grid
137✔
472
              container
137✔
473
              key={`${name}-section`}
137✔
474
              sx={{ mb: level <= 1 && splittedPath.length <= 1 ? "3rem" : 0 }}
137✔
475
            >
476
              {heading}
137✔
477
              <Grid size={{ xs: 12, md: level === 1 && label ? 8 : 12 }}>{children}</Grid>
137✔
478
            </Grid>
137✔
479
            <div>
137✔
480
              {error ? (
137!
481
                <FormControl error>
×
482
                  <FormHelperText>
×
483
                    {label} {error?.message}
×
484
                  </FormHelperText>
×
485
                </FormControl>
×
486
              ) : null}
137✔
487
            </div>
137✔
488
          </>
137✔
489
        )
490
      }}
137✔
491
    </ConnectForm>
137✔
492
  )
493
}
137✔
494

495
/*
496
 * FormOneOfField is rendered if property can be choosed from many possible.
497
 */
498

499
const FormOneOfField = ({
1✔
500
  path,
9✔
501
  object,
9✔
502
  nestedField,
9✔
503
  required,
9✔
504
}: {
505
  path: string[]
506
  object: FormObject
507
  nestedField?: NestedField
508
  required?: boolean
509
}) => {
9✔
510
  const options = object.oneOf
9✔
511
  const [lastPathItem] = path.slice(-1)
9✔
512
  const description = object.description
9✔
513
  // Get the fieldValue when rendering a saved/submitted form
514
  // For e.g. obj.required is ["label", "url"] and nestedField is {id: "sth1", label: "sth2", url: "sth3"}
515
  // Get object from state and set default values if child of oneOf field has values
516
  // Fetching current object values from state rather than via getValues() method gets values on first call. The getValues method results in empty object on first call
517
  const currentObject = useAppSelector(state => state.currentObject) || {}
9!
518
  const values = currentObject[path.toString()]
9!
519
    ? currentObject
×
520
    : currentObject[
9✔
521
        Object.keys(currentObject)
9✔
522
          .filter(item => path.includes(item))
9✔
523
          .toString()
9✔
524
      ] || {}
9✔
525

526
  let fieldValue: string | number | undefined
9✔
527

528
  const flattenObject = (obj: { [x: string]: never }, prefix = "") =>
9✔
529
    Object.keys(obj).reduce(
×
530
      (acc, k) => {
×
531
        const pre = prefix.length ? prefix + "." : ""
×
532
        if (typeof obj[k] === "object") Object.assign(acc, flattenObject(obj[k], pre + k))
×
533
        else acc[pre + k] = obj[k]
×
534
        return acc
×
535
      },
×
536
      {} as Record<string, string>
×
537
    )
×
538

539
  if (Object.keys(values).length > 0 && lastPathItem !== "prevStepIndex") {
9!
540
    for (const item of path) {
×
541
      if (values[item]) {
×
542
        const itemValues = values[item]
×
543
        const parentPath = Object.keys(itemValues) ? Object.keys(itemValues).toString() : ""
×
544
        // Match key from currentObject to option property.
545
        // Field key can be deeply nested and therefore we need to have multiple cases for finding correct value.
546
        if (isNaN(Number(parentPath[0]))) {
×
547
          fieldValue = (
×
548
            options.find(option => option.properties[parentPath])
×
549
              ? // Eg. Sample > Sample Names > Sample Data Type
550
                options.find(option => option.properties[parentPath])
×
551
              : // Eg. Run > Run Type > Reference Alignment
552
                options.find(
×
553
                  option =>
×
554
                    option.properties[
×
555
                      Object.keys(flattenObject(itemValues))[0].split(".").slice(-1)[0]
×
556
                    ]
557
                )
×
558
          )?.title as string
×
559
        } else {
×
560
          // Eg. Experiment > Expected Base Call Table > Processing > Single Processing
561
          if (typeof itemValues === "string") {
×
562
            fieldValue = options.find(option => option.type === "string")?.title
×
563
          }
×
564
          // Eg. Experiment > Expected Base Call Table > Processing > Complex Processing
565
          else {
×
566
            const fieldKey = Object.keys(values[item][0])[0]
×
567
            fieldValue = options?.find(option => option.items?.properties[fieldKey])?.title
×
568
          }
×
569
        }
×
570
      }
×
571
    }
×
572
  }
×
573

574
  // Eg. Study > Study Links
575
  if (nestedField) {
9✔
576
    for (const option of options) {
2✔
577
      option.required.every(
4✔
578
        (val: string) =>
4✔
579
          nestedField.fieldValues && Object.keys(nestedField.fieldValues).includes(val)
4!
580
      )
4!
581
        ? (fieldValue = option.title)
×
582
        : ""
4✔
583
    }
4✔
584
  }
2✔
585

586
  // Special handling for Expected Base Call Table > Processing > Complex Processing > Pipeline > Pipe Section > Prev Step Index
587
  // Can be extended to other fields if needed
588
  const itemValue = get(currentObject, pathToName(path))
9✔
589

590
  if (itemValue) {
9!
591
    switch (lastPathItem) {
×
592
      case "prevStepIndex":
×
593
        {
×
594
          fieldValue = "String value"
×
595
        }
×
596
        break
×
597
    }
×
598
  }
×
599

600
  const name = pathToName(path)
9✔
601

602
  const label = object.title ?? lastPathItem
9!
603

604
  type ChildObject = { properties: Record<string, unknown>; required: boolean }
605

606
  const getChildObjects = (obj?: ChildObject) => {
9✔
607
    if (obj) {
×
608
      let childProps
×
609
      for (const key in obj) {
×
610
        // Check if object has nested "properties"
611
        if (key === "properties") {
×
612
          childProps = obj.properties
×
613
          const childPropsValues = Object.values(childProps)[0]
×
614
          if (Object.hasOwnProperty.call(childPropsValues, "properties")) {
×
615
            getChildObjects(childPropsValues as ChildObject)
×
616
          }
×
617
        }
×
618
      }
×
619

620
      const firstProp = childProps ? Object.keys(childProps)[0] : ""
×
621
      return { obj, firstProp }
×
622
    }
×
623
    return {}
×
624
  }
×
625

626
  const [field, setField] = React.useState(fieldValue)
9✔
627
  const clearForm = useAppSelector(state => state.clearForm)
9✔
628

629
  return (
9✔
630
    <ConnectForm>
9✔
631
      {({ errors, unregister, setValue, getValues, reset }: ConnectFormMethods) => {
9✔
632
        if (clearForm) {
9!
633
          // Clear the field and "clearForm" is true
634
          setField("")
×
635
          unregister(name)
×
636
        }
×
637

638
        const error = get(errors, name)
9✔
639
        // Option change handling
640
        const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
9✔
641
          const val = event.target.value
2✔
642
          setField(val)
2✔
643

644
          // Get fieldValues of current path
645
          const currentFieldValues = getValues(name)
2✔
646
          // Unregister if selecting "Complex Processing", "Null value" in Experiment form
647
          if (val === "Complex Processing") unregister(name)
2!
648
          if (val === "Null value") setValue(name, null)
2!
649
          // Remove previous values of the same path
650
          if (
2✔
651
            val !== "Complex Processing" &&
2✔
652
            val !== "Null value" &&
2✔
653
            currentFieldValues !== undefined
2✔
654
          ) {
2!
655
            reset({ ...getValues(), [name]: "" })
×
656
          }
×
657
        }
2✔
658

659
        // Selected option
660
        const selectedOption =
9✔
661
          options?.filter((option: { title: string }) => option.title === field)[0]?.properties ||
9✔
662
          {}
7✔
663
        const selectedOptionValues = Object.values(selectedOption)
9✔
664

665
        let childObject
9✔
666
        let requiredProp: string
9✔
667

668
        // If selectedOption has many nested "properties"
669
        if (
9✔
670
          selectedOptionValues.length > 0 &&
9✔
671
          Object.hasOwnProperty.call(selectedOptionValues[0], "properties")
2✔
672
        ) {
9!
673
          const { obj, firstProp } = getChildObjects(
×
674
            Object.values(selectedOption)[0] as ChildObject
×
675
          )
×
676
          childObject = obj
×
677
          requiredProp = firstProp || ""
×
678
        }
×
679
        // Else if selectedOption has no nested "properties"
680
        else {
9✔
681
          childObject = options?.filter((option: { title: string }) => option.title === field)[0]
9✔
682
          requiredProp = childObject?.required?.toString() || Object.keys(selectedOption)[0]
9✔
683
        }
9✔
684

685
        let child
9✔
686
        if (field) {
9✔
687
          const fieldObject = options?.filter(
2✔
688
            (option: { title: string }) => option.title === field
2✔
689
          )[0]
2✔
690
          child = traverseFields(
2✔
691
            { ...fieldObject, title: "" },
2✔
692
            path,
2✔
693
            required && requiredProp ? requiredProp.split(",") : [],
2!
694
            childObject?.required ? false : true,
2✔
695
            nestedField
2✔
696
          )
2✔
697
        } else child = null
9✔
698

699
        return (
9✔
700
          <>
9✔
701
            <BaselineDiv>
9✔
702
              <TextField
9✔
703
                name={name}
9✔
704
                label={label}
9✔
705
                id={name}
9✔
706
                role="listbox"
9✔
707
                value={field || ""}
9✔
708
                select
9✔
709
                SelectProps={{ native: true }}
9✔
710
                onChange={event => {
9✔
711
                  handleChange(event)
2✔
712
                }}
2✔
713
                error={!!error}
9✔
714
                helperText={error?.message}
9!
715
                required={required}
9✔
716
                inputProps={{ "data-testid": name }}
9✔
717
                sx={{ mb: "1rem" }}
9✔
718
              >
719
                <option aria-label="None" value="" disabled />
9✔
720
                {options?.map((optionObject: { title: string }) => {
9✔
721
                  const option = optionObject.title
18✔
722
                  return (
18✔
723
                    <option key={`${name}-${option}`} value={option}>
18✔
724
                      {option}
18✔
725
                    </option>
18✔
726
                  )
727
                })}
9✔
728
              </TextField>
9✔
729
              {description && (
9!
730
                <FieldTooltip
×
731
                  title={<DisplayDescription description={description} />}
×
732
                  placement="right"
×
733
                  arrow
×
734
                  describeChild
×
735
                >
736
                  <TooltipIcon />
×
737
                </FieldTooltip>
×
738
              )}
739
            </BaselineDiv>
9✔
740
            {child}
9✔
741
          </>
9✔
742
        )
743
      }}
9✔
744
    </ConnectForm>
9✔
745
  )
746
}
9✔
747

748
type FormFieldBaseProps = {
749
  name: string
750
  label: string
751
  required: boolean
752
}
753

754
type FormSelectFieldProps = FormFieldBaseProps & { options: string[] }
755

756
/*
757
 * FormTextField is the most usual type, rendered for strings, integers and numbers.
758
 */
759
const FormTextField = ({
1✔
760
  name,
62✔
761
  label,
62✔
762
  required,
62✔
763
  description,
62✔
764
  type = "string",
62✔
765
  nestedField,
62✔
766
}: FormFieldBaseProps & { description: string; type?: string; nestedField?: NestedField }) => {
62✔
767
  const objectType = useAppSelector(state => state.objectType)
62✔
768
  const isDOIForm = objectType === ObjectTypes.datacite
62✔
769
  const autocompleteField = useAppSelector(state => state.autocompleteField)
62✔
770
  const path = name.split(".")
62✔
771
  const [lastPathItem] = path.slice(-1)
62✔
772

773
  // Default Value of input
774
  const defaultValue = getDefaultValue(name, nestedField)
62✔
775
  // useWatch to watch any changes in form's fields
776
  const watchValues = useWatch()
62✔
777

778
  // Case: DOI form - Affilation identifier to be prefilled and hidden
779
  const prefilledHiddenFields = ["affiliationIdentifier"]
62✔
780
  const isPrefilledHiddenField = isDOIForm && prefilledHiddenFields.includes(lastPathItem)
62!
781

782
  /*
783
   * Handle DOI form values
784
   */
785
  const { setValue, getValues } = useFormContext()
62✔
786
  const watchAutocompleteFieldName = isPrefilledHiddenField ? getPathName(path, "name") : null
62!
787
  const prefilledValue = watchAutocompleteFieldName
62!
NEW
788
    ? get(watchValues, watchAutocompleteFieldName)
×
789
    : null
62✔
790

791
  // Check value of current name path
792
  const val = getValues(name)
62✔
793

794
  React.useEffect(() => {
62✔
795
    if (!isPrefilledHiddenField) return
28!
796
    if (prefilledValue && !val) {
28!
797
      // Set value for prefilled field if autocompleteField exists
NEW
798
      setValue(name, autocompleteField)
×
NEW
799
    } else if (prefilledValue === undefined && val) {
×
800
      // Remove values if autocompleteField is deleted
NEW
801
      setValue(name, "")
×
UNCOV
802
    }
×
803
  }, [autocompleteField, prefilledValue])
62✔
804

805
  return (
62✔
806
    <ConnectForm>
62✔
807
      {({ control }: ConnectFormMethods) => {
62✔
808
        const multiLineRowIdentifiers = ["abstract", "description", "policy text"]
62✔
809

810
        return (
62✔
811
          <Controller
62✔
812
            render={({ field, fieldState: { error } }) => {
62✔
813
              const inputValue =
63✔
814
                (watchAutocompleteFieldName && typeof val !== "object" && val) ||
63!
815
                (typeof field.value !== "object" && field.value) ||
63✔
816
                ""
60✔
817

818
              const handleChange = (e: { target: { value: string | number } }) => {
63✔
819
                const { value } = e.target
2✔
820
                const parsedValue =
2✔
821
                  type === "string" && typeof value === "number" ? value.toString() : value
2!
822
                field.onChange(parsedValue) // Helps with Cypress change detection
2✔
823
                setValue(name, parsedValue) // Enables update of nested fields, eg. DAC contact
2✔
824
              }
2✔
825

826
              return (
63✔
827
                <div style={{ marginBottom: "1rem" }}>
63✔
828
                  <BaselineDiv style={isPrefilledHiddenField ? { display: "none" } : {}}>
63!
829
                    <TextField
63✔
830
                      {...field}
63✔
831
                      slotProps={{ htmlInput: { "data-testid": name } }}
63✔
832
                      label={label}
63✔
833
                      id={name}
63✔
834
                      role="textbox"
63✔
835
                      error={!!error}
63✔
836
                      helperText={error?.message}
63✔
837
                      required={required}
63✔
838
                      type={type}
63✔
839
                      multiline={multiLineRowIdentifiers.some(value =>
63✔
840
                        label.toLowerCase().includes(value)
178✔
841
                      )}
63✔
842
                      rows={5}
63✔
843
                      value={inputValue}
63✔
844
                      onChange={handleChange}
63✔
845
                      disabled={defaultValue !== "" && name.includes("formats")}
63✔
846
                    />
847
                    {description && (
63✔
848
                      <FieldTooltip
33✔
849
                        title={<DisplayDescription description={description} />}
33✔
850
                        placement="right"
33✔
851
                        arrow
33✔
852
                        describeChild
33✔
853
                      >
854
                        <TooltipIcon />
33✔
855
                      </FieldTooltip>
33✔
856
                    )}
857
                  </BaselineDiv>
63✔
858
                </div>
63✔
859
              )
860
            }}
63✔
861
            name={name}
62✔
862
            control={control}
62✔
863
            defaultValue={defaultValue}
62✔
864
            rules={{ required: required }}
62✔
865
          />
866
        )
867
      }}
62✔
868
    </ConnectForm>
62✔
869
  )
870
}
62✔
871

872
/*
873
 * FormSelectField is rendered for selection from options where it's possible to choose many options
874
 */
875

876
const FormSelectField = ({
1✔
877
  name,
6✔
878
  label,
6✔
879
  required,
6✔
880
  options,
6✔
881
  description,
6✔
882
}: FormSelectFieldProps & { description: string }) => (
6✔
883
  <ConnectForm>
6✔
884
    {({ control }: ConnectFormMethods) => {
6✔
885
      return (
6✔
886
        <Controller
6✔
887
          name={name}
6✔
888
          control={control}
6✔
889
          render={({ field, fieldState: { error } }) => {
6✔
890
            return (
7✔
891
              <BaselineDiv>
7✔
892
                <TextField
7✔
893
                  {...field}
7✔
894
                  label={label}
7✔
895
                  id={name}
7✔
896
                  value={field.value || ""}
7✔
897
                  error={!!error}
7✔
898
                  helperText={error?.message}
7!
899
                  required={required}
7✔
900
                  select
7✔
901
                  SelectProps={{ native: true }}
7✔
902
                  onChange={e => {
7✔
903
                    let val = e.target.value
×
904
                    // Case: linkingAccessionIds which include "AccessionId + Form's title", we need to return only accessionId as value
905
                    if (val?.includes("Title")) {
×
906
                      const hyphenIndex = val.indexOf("-")
×
907
                      val = val.slice(0, hyphenIndex - 1)
×
908
                    }
×
909
                    return field.onChange(val)
×
910
                  }}
×
911
                  inputProps={{ "data-testid": name }}
7✔
912
                  sx={{ mb: "1rem" }}
7✔
913
                >
914
                  <option aria-label="None" value="" disabled />
7✔
915
                  {options.map(option => (
7✔
916
                    <option key={`${name}-${option}`} value={option} data-testid={`${name}-option`}>
21✔
917
                      {option}
21✔
918
                    </option>
21✔
919
                  ))}
7✔
920
                </TextField>
7✔
921
                {description && (
7!
922
                  <FieldTooltip
×
923
                    title={<DisplayDescription description={description} />}
×
924
                    placement="right"
×
925
                    arrow
×
926
                    describeChild
×
927
                  >
928
                    <TooltipIcon />
×
929
                  </FieldTooltip>
×
930
                )}
931
              </BaselineDiv>
7✔
932
            )
933
          }}
7✔
934
        />
935
      )
936
    }}
6✔
937
  </ConnectForm>
6✔
938
)
939

940
/*
941
 * FormDatePicker used for selecting date or date rage in DOI form
942
 */
943

944
const StyledDatePicker = styled(DatePicker)(({ theme }) => ({
1✔
945
  "& .MuiIconButton-root": {
×
946
    color: theme.palette.primary.main,
×
947
    "&:hover": {
×
948
      backgroundColor: theme.palette.action.hover,
×
949
    },
×
950
  },
×
951
}))
1✔
952

953
const FormDatePicker = ({
1✔
954
  name,
×
955
  required,
×
956
  description,
×
957
}: FormFieldBaseProps & { description: string }) => {
×
958
  const { t } = useTranslation()
×
959
  const { getValues } = useFormContext()
×
960
  const defaultValue = getValues(name) || ""
×
961

962
  const getStartEndDates = (date: string) => {
×
963
    const [startInput, endInput] = date?.split("/")
×
964
    if (startInput && endInput) return [moment(startInput), moment(endInput)]
×
965
    else if (startInput) return [moment(startInput), null]
×
966
    else if (endInput) return [null, moment(endInput)]
×
967
    else return [null, null]
×
968
  }
×
969

970
  const [startDate, setStartDate] = React.useState<moment.Moment | null>(
×
971
    getStartEndDates(defaultValue)[0]
×
972
  )
×
973
  const [endDate, setEndDate] = React.useState<moment.Moment | null>(
×
974
    getStartEndDates(defaultValue)[1]
×
975
  )
×
976
  const [startError, setStartError] = React.useState<string | null>(null)
×
977
  const [endError, setEndError] = React.useState<string | null>(null)
×
978
  const clearForm = useAppSelector(state => state.clearForm)
×
979

980
  React.useEffect(() => {
×
981
    if (clearForm) {
×
982
      setStartDate(null)
×
983
      setEndDate(null)
×
984
    }
×
985
  }, [clearForm])
×
986

987
  const format = "YYYY-MM-DD"
×
988
  const formatDate = (date: moment.Moment) => moment(date).format(format)
×
989

990
  const makeValidDateString = (start: moment.Moment | null, end: moment.Moment | null) => {
×
991
    let dateStr = ""
×
992
    if (start && start?.isValid()) {
×
993
      dateStr = formatDate(start)
×
994
      if (end && end?.isValid() && formatDate(end) !== dateStr) {
×
995
        dateStr += `/${formatDate(end)}`
×
996
      }
×
997
    }
×
998
    return dateStr
×
999
  }
×
1000

1001
  return (
×
1002
    <ConnectForm>
×
1003
      {({ setValue }: ConnectFormMethods) => {
×
1004
        const handleChangeStartDate = (newValue: moment.Moment | null) => {
×
1005
          setStartDate(newValue)
×
1006
          setValue(name, makeValidDateString(newValue, endDate))
×
1007
        }
×
1008

1009
        const handleChangeEndDate = (newValue: moment.Moment | null) => {
×
1010
          setEndDate(newValue)
×
1011
          setValue(name, makeValidDateString(startDate, newValue))
×
1012
        }
×
1013

1014
        return (
×
1015
          <LocalizationProvider dateAdapter={AdapterMoment}>
×
1016
            <Box
×
1017
              sx={{
×
1018
                width: "95%",
×
1019
                display: "flex",
×
1020
                flexDirection: "row",
×
1021
                alignItems: "baseline",
×
1022
                marginBottom: "1rem",
×
1023
              }}
×
1024
            >
1025
              <StyledDatePicker
×
1026
                label={t("datacite.startDate")}
×
1027
                value={startDate}
×
1028
                format={format}
×
1029
                onChange={handleChangeStartDate}
×
1030
                onError={setStartError}
×
1031
                shouldDisableDate={day => !!endDate && moment(day).isAfter(endDate)}
×
1032
                slotProps={{
×
1033
                  field: { clearable: true },
×
1034
                  textField: {
×
1035
                    required,
×
1036
                    error: !!startError,
×
1037
                    helperText: startError
×
1038
                      ? startError === "shouldDisableDate"
×
1039
                        ? t("datacite.error.range")
×
1040
                        : t("datacite.error.date")
×
1041
                      : "",
×
1042
                  },
×
1043
                  nextIconButton: { color: "primary" },
×
1044
                  previousIconButton: { color: "primary" },
×
1045
                  switchViewIcon: { color: "primary" },
×
1046
                }}
×
1047
              />
1048
              <span>–</span>
×
1049
              <StyledDatePicker
×
1050
                label={t("datacite.endDate")}
×
1051
                value={endDate}
×
1052
                format={format}
×
1053
                onChange={handleChangeEndDate}
×
1054
                onError={setEndError}
×
1055
                shouldDisableDate={day => !!startDate && moment(day).isBefore(startDate)}
×
1056
                slotProps={{
×
1057
                  field: { clearable: true },
×
1058
                  textField: {
×
1059
                    error: !!endError,
×
1060
                    helperText: endError
×
1061
                      ? endError === "shouldDisableDate"
×
1062
                        ? t("datacite.error.range")
×
1063
                        : t("datacite.error.date")
×
1064
                      : "",
×
1065
                  },
×
1066
                  nextIconButton: { color: "primary" },
×
1067
                  previousIconButton: { color: "primary" },
×
1068
                  switchViewIcon: { color: "primary" },
×
1069
                }}
×
1070
              />
1071
              {description && (
×
1072
                <FieldTooltip
×
1073
                  title={<DisplayDescription description={description} />}
×
1074
                  placement="right"
×
1075
                  arrow
×
1076
                  describeChild
×
1077
                >
1078
                  <TooltipIcon />
×
1079
                </FieldTooltip>
×
1080
              )}
1081
            </Box>
×
1082
          </LocalizationProvider>
×
1083
        )
1084
      }}
×
1085
    </ConnectForm>
×
1086
  )
1087
}
×
1088

1089
/*
1090
 * FormAutocompleteField uses ROR API to fetch organisations
1091
 */
1092
type RORItem = {
1093
  name: string
1094
  id: string
1095
}
1096

1097
const StyledAutocomplete = styled(Autocomplete)(() => ({
1✔
1098
  flex: "auto",
8✔
1099
  alignSelf: "flex-start",
8✔
1100
  "& + svg": {
8✔
1101
    marginTop: 1,
8✔
1102
  },
8✔
1103
})) as typeof Autocomplete
1✔
1104

1105
const FormAutocompleteField = ({
1✔
1106
  name,
9✔
1107
  label,
9✔
1108
  required,
9✔
1109
  description,
9✔
1110
}: FormFieldBaseProps & { description: string }) => {
9✔
1111
  const dispatch = useAppDispatch()
9✔
1112

1113
  const { setValue, getValues } = useFormContext()
9✔
1114

1115
  const defaultValue = getValues(name) || ""
9✔
1116
  const [selection, setSelection] = React.useState<RORItem | null>(null)
9✔
1117
  const [open, setOpen] = React.useState(false)
9✔
1118
  const [options, setOptions] = React.useState([])
9✔
1119
  const [inputValue, setInputValue] = React.useState("")
9✔
1120
  const [loading, setLoading] = React.useState(false)
9✔
1121
  const clearForm = useAppSelector(state => state.clearForm)
9✔
1122

1123
  const fetchOrganisations = async (searchTerm: string) => {
9✔
1124
    // Check if searchTerm includes non-word char, for e.g. "(", ")", "-" because the api does not work with those chars
1125
    const isContainingNonWordChar = searchTerm.match(/\W/g)
1✔
1126
    const response =
1✔
1127
      isContainingNonWordChar === null ? await rorAPIService.getOrganisations(searchTerm) : null
1!
1128

1129
    if (response) setLoading(false)
1✔
1130

1131
    if (response?.ok) {
1✔
1132
      const mappedOrganisations = response.data.items.map((org: RORItem) => ({
1✔
1133
        name: org.name,
1✔
1134
        id: org.id,
1✔
1135
      }))
1✔
1136
      setOptions(mappedOrganisations)
1✔
1137
    }
1✔
1138
  }
1✔
1139

1140
  const debouncedSearch = debounce((newInput: string) => {
9✔
1141
    if (newInput.length > 0) fetchOrganisations(newInput)
1✔
1142
  }, 150)
9✔
1143

1144
  React.useEffect(() => {
9✔
1145
    let active = true
4✔
1146

1147
    if (inputValue === "") {
4✔
1148
      setOptions([])
2✔
1149
      return undefined
2✔
1150
    }
2✔
1151

1152
    if (active && open) {
4✔
1153
      setLoading(true)
1✔
1154
      debouncedSearch(inputValue)
1✔
1155
    }
1✔
1156

1157
    return () => {
2✔
1158
      active = false
2✔
1159
      setLoading(false)
2✔
1160
    }
2✔
1161
  }, [selection, inputValue])
9✔
1162

1163
  React.useEffect(() => {
9✔
1164
    if (clearForm) {
2!
1165
      setSelection(null)
×
1166
      setInputValue("")
×
1167
    }
×
1168
  }, [clearForm])
9✔
1169

1170
  return (
9✔
1171
    <ConnectForm>
9✔
1172
      {({ errors, control }: ConnectFormMethods) => {
9✔
1173
        const error = get(errors, name)
8✔
1174

1175
        const handleAutocompleteValueChange = (_event: unknown, option: RORItem) => {
8✔
1176
          setSelection(option)
1✔
1177
          setValue(name, option?.name)
1✔
1178
          option?.id ? dispatch(setAutocompleteField(option.id)) : null
1!
1179
        }
1✔
1180

1181
        const handleInputChange = (_event: unknown, newInputValue: string, reason: string) => {
8✔
1182
          setInputValue(newInputValue)
3✔
1183
          switch (reason) {
3✔
1184
            case "input":
3✔
1185
            case "clear":
3✔
1186
              setInputValue(newInputValue)
1✔
1187
              break
1✔
1188
            case "reset":
3✔
1189
              selection ? setInputValue(selection?.name) : null
1!
1190
              break
1✔
1191
            default:
3✔
1192
              break
1✔
1193
          }
3✔
1194
        }
3✔
1195

1196
        return (
8✔
1197
          <Controller
8✔
1198
            render={() => (
8✔
1199
              <StyledAutocomplete
8✔
1200
                freeSolo
8✔
1201
                open={open}
8✔
1202
                onOpen={() => {
8✔
1203
                  setOpen(true)
1✔
1204
                }}
1✔
1205
                onClose={() => {
8✔
1206
                  setOpen(false)
1✔
1207
                }}
1✔
1208
                options={options}
8✔
1209
                getOptionLabel={option => option.name || ""}
8✔
1210
                disableClearable={inputValue.length === 0}
8✔
1211
                renderInput={params => (
8✔
1212
                  <BaselineDiv>
8✔
1213
                    <TextField
8✔
1214
                      {...params}
8✔
1215
                      label={label}
8✔
1216
                      id={name}
8✔
1217
                      name={name}
8✔
1218
                      variant="outlined"
8✔
1219
                      error={!!error}
8✔
1220
                      required={required}
8✔
1221
                      InputProps={{
8✔
1222
                        ...params.InputProps,
8✔
1223
                        endAdornment: (
8✔
1224
                          <React.Fragment>
8✔
1225
                            {loading ? <CircularProgress color="inherit" size={20} /> : null}
8✔
1226
                            {params.InputProps.endAdornment}
8✔
1227
                          </React.Fragment>
8✔
1228
                        ),
1229
                      }}
8✔
1230
                      inputProps={{ ...params.inputProps, "data-testid": `${name}-inputField` }}
8✔
1231
                      sx={[
8✔
1232
                        {
8✔
1233
                          "&.MuiAutocomplete-endAdornment": {
8✔
1234
                            top: 0,
8✔
1235
                          },
8✔
1236
                        },
8✔
1237
                      ]}
8✔
1238
                    />
1239
                    {description && (
8!
1240
                      <FieldTooltip
×
1241
                        title={
×
1242
                          <DisplayDescription description={description}>
×
1243
                            <>
×
1244
                              <br />
×
1245
                              {"Organisations provided by "}
×
1246
                              <a href="https://ror.org/" target="_blank" rel="noreferrer">
×
1247
                                {"ror.org"}
×
1248
                                <LaunchIcon sx={{ fontSize: "1rem", mb: -1 }} />
×
1249
                              </a>
×
1250
                            </>
×
1251
                          </DisplayDescription>
×
1252
                        }
1253
                        placement="right"
×
1254
                        arrow
×
1255
                        describeChild
×
1256
                      >
1257
                        <TooltipIcon />
×
1258
                      </FieldTooltip>
×
1259
                    )}
1260
                  </BaselineDiv>
8✔
1261
                )}
1262
                onChange={handleAutocompleteValueChange}
8✔
1263
                onInputChange={handleInputChange}
8✔
1264
                value={defaultValue}
8✔
1265
                inputValue={inputValue || defaultValue}
8✔
1266
              />
1267
            )}
1268
            name={name}
8✔
1269
            control={control}
8✔
1270
          />
1271
        )
1272
      }}
8✔
1273
    </ConnectForm>
9✔
1274
  )
1275
}
9✔
1276

1277
const ValidationTagField = styled(TextField)(({ theme }) => ({
1✔
1278
  "& .MuiOutlinedInput-root.MuiInputBase-root": { flexWrap: "wrap" },
×
1279
  "& input": { flex: 1, minWidth: "2rem" },
×
1280
  "& label": { color: theme.palette.primary.main },
×
1281
  "& .MuiOutlinedInput-notchedOutline, div:hover .MuiOutlinedInput-notchedOutline":
×
1282
    highlightStyle(theme),
×
1283
}))
1✔
1284

1285
const FormTagField = ({
1✔
1286
  name,
×
1287
  label,
×
1288
  required,
×
1289
  description,
×
1290
}: FormFieldBaseProps & { description: string }) => {
×
1291
  const savedValues = useWatch({ name })
×
1292
  const [inputValue, setInputValue] = React.useState("")
×
1293
  const [tags, setTags] = React.useState<Array<string>>([])
×
1294

1295
  React.useEffect(() => {
×
1296
    // update tags when value becomes available or changes
1297
    const updatedTags = savedValues ? savedValues.split(",") : []
×
1298
    setTags(updatedTags)
×
1299
  }, [savedValues])
×
1300

1301
  const handleInputChange = e => {
×
1302
    setInputValue(e.target.value)
×
1303
  }
×
1304

1305
  const clearForm = useAppSelector(state => state.clearForm)
×
1306

1307
  React.useEffect(() => {
×
1308
    if (clearForm) {
×
1309
      setTags([])
×
1310
      setInputValue("")
×
1311
    }
×
1312
  }, [clearForm])
×
1313

1314
  return (
×
1315
    <ConnectForm>
×
1316
      {({ control }: ConnectFormMethods) => {
×
1317
        return (
×
1318
          <Controller
×
1319
            name={name}
×
1320
            control={control}
×
1321
            defaultValue=""
×
1322
            render={({ field }) => {
×
1323
              const handleKeywordAsTag = (keyword: string) => {
×
1324
                // newTags with unique values
1325
                const newTags = !tags.includes(keyword) ? [...tags, keyword] : tags
×
1326
                setInputValue("")
×
1327
                // Convert tags to string for hidden registered input's values
1328
                field.onChange(newTags.join(","))
×
1329
              }
×
1330

1331
              const handleKeyDown = e => {
×
1332
                const { key } = e
×
1333
                const trimmedInput = inputValue.trim()
×
1334
                // Convert to tags if users press "," OR "Enter"
1335
                if ((key === "," || key === "Enter") && trimmedInput.length > 0) {
×
1336
                  e.preventDefault()
×
1337
                  handleKeywordAsTag(trimmedInput)
×
1338
                }
×
1339
              }
×
1340

1341
              // Convert to tags when user clicks outside of input field
1342
              const handleOnBlur = () => {
×
1343
                const trimmedInput = inputValue.trim()
×
1344
                if (trimmedInput.length > 0) {
×
1345
                  handleKeywordAsTag(trimmedInput)
×
1346
                }
×
1347
              }
×
1348

1349
              const handleTagDelete = item => () => {
×
1350
                const newTags = tags.filter(tag => tag !== item)
×
1351
                field.onChange(newTags.join(","))
×
1352
              }
×
1353

1354
              return (
×
1355
                <BaselineDiv>
×
1356
                  <input
×
1357
                    {...field}
×
1358
                    required={required}
×
1359
                    style={{ width: 0, opacity: 0, transform: "translate(8rem, 2rem)" }}
×
1360
                  />
1361
                  <ValidationTagField
×
1362
                    slotProps={{
×
1363
                      htmlInput: { "data-testid": name },
×
1364
                      input: {
×
1365
                        startAdornment:
×
1366
                          tags.length > 0
×
1367
                            ? tags.map(item => (
×
1368
                                <Chip
×
1369
                                  key={item}
×
1370
                                  tabIndex={-1}
×
1371
                                  label={item}
×
1372
                                  onDelete={handleTagDelete(item)}
×
1373
                                  color="primary"
×
1374
                                  deleteIcon={<ClearIcon fontSize="small" />}
×
1375
                                  data-testid={item}
×
1376
                                  sx={{ fontSize: "1.4rem", m: "0.5rem" }}
×
1377
                                />
1378
                              ))
×
1379
                            : null,
×
1380
                      },
×
1381
                    }}
×
1382
                    label={label}
×
1383
                    id={name}
×
1384
                    value={inputValue}
×
1385
                    onChange={handleInputChange}
×
1386
                    onKeyDown={handleKeyDown}
×
1387
                    onBlur={handleOnBlur}
×
1388
                  />
1389

1390
                  {description && (
×
1391
                    <FieldTooltip
×
1392
                      title={<DisplayDescription description={description} />}
×
1393
                      placement="right"
×
1394
                      arrow
×
1395
                      describeChild
×
1396
                    >
1397
                      <TooltipIcon />
×
1398
                    </FieldTooltip>
×
1399
                  )}
1400
                </BaselineDiv>
×
1401
              )
1402
            }}
×
1403
          />
1404
        )
1405
      }}
×
1406
    </ConnectForm>
×
1407
  )
1408
}
×
1409

1410
/*
1411
 * Highlight required Checkbox
1412
 */
1413
const ValidationFormControlLabel = styled(FormControlLabel)(({ theme }) => ({
1✔
1414
  label: {
6✔
1415
    "& span": { color: theme.palette.primary.main },
6✔
1416
  },
6✔
1417
}))
1✔
1418

1419
const FormBooleanField = ({
1✔
1420
  name,
6✔
1421
  label,
6✔
1422
  required,
6✔
1423
  description,
6✔
1424
}: FormFieldBaseProps & { description: string }) => {
6✔
1425
  return (
6✔
1426
    <ConnectForm>
6✔
1427
      {({ register, errors, getValues }: ConnectFormMethods) => {
6✔
1428
        const error = get(errors, name)
6✔
1429

1430
        const { ref, ...rest } = register(name)
6✔
1431
        // DAC form: "values" of MainContact checkbox
1432
        const values = getValues(name)
6✔
1433
        return (
6✔
1434
          <Box display="inline" px={1}>
6✔
1435
            <FormControl error={!!error} required={required}>
6✔
1436
              <FormGroup>
6✔
1437
                <BaselineDiv>
6✔
1438
                  <ValidationFormControlLabel
6✔
1439
                    control={
6✔
1440
                      <Checkbox
6✔
1441
                        id={name}
6✔
1442
                        {...rest}
6✔
1443
                        name={name}
6✔
1444
                        required={required}
6✔
1445
                        inputRef={ref}
6✔
1446
                        color="primary"
6✔
1447
                        checked={values || false}
6✔
1448
                        inputProps={
6✔
1449
                          { "data-testid": name } as React.InputHTMLAttributes<HTMLInputElement>
6✔
1450
                        }
6✔
1451
                      />
1452
                    }
1453
                    label={
6✔
1454
                      <label>
6✔
1455
                        {label}
6✔
1456
                        <span>{required ? ` * ` : ""}</span>
6!
1457
                      </label>
6✔
1458
                    }
6✔
1459
                  />
1460
                  {description && (
6!
1461
                    <FieldTooltip
×
1462
                      title={<DisplayDescription description={description} />}
×
1463
                      placement="right"
×
1464
                      arrow
×
1465
                      describeChild
×
1466
                    >
1467
                      <TooltipIcon />
×
1468
                    </FieldTooltip>
×
1469
                  )}
1470
                </BaselineDiv>
6✔
1471

1472
                <FormHelperText>{error?.message}</FormHelperText>
6!
1473
              </FormGroup>
6✔
1474
            </FormControl>
6✔
1475
          </Box>
6✔
1476
        )
1477
      }}
6✔
1478
    </ConnectForm>
6✔
1479
  )
1480
}
6✔
1481

1482
const FormCheckBoxArray = ({
1✔
1483
  name,
6✔
1484
  label,
6✔
1485
  required,
6✔
1486
  options,
6✔
1487
  description,
6✔
1488
}: FormSelectFieldProps & { description: string }) => (
6✔
1489
  <Box px={1}>
6✔
1490
    <p>{label} Check from following options</p>
6✔
1491
    <ConnectForm>
6✔
1492
      {({ register, errors, getValues }: ConnectFormMethods) => {
6✔
1493
        const values = getValues()[name]
6✔
1494

1495
        const error = get(errors, name)
6✔
1496

1497
        const { ref, ...rest } = register(name)
6✔
1498

1499
        return (
6✔
1500
          <FormControl error={!!error} required={required}>
6✔
1501
            <FormGroup aria-labelledby={name}>
6✔
1502
              {options.map(option => (
6✔
1503
                <React.Fragment key={option}>
12✔
1504
                  <FormControlLabel
12✔
1505
                    key={option}
12✔
1506
                    control={
12✔
1507
                      <Checkbox
12✔
1508
                        {...rest}
12✔
1509
                        inputRef={ref}
12✔
1510
                        name={name}
12✔
1511
                        value={option}
12✔
1512
                        checked={values && values?.includes(option) ? true : false}
12!
1513
                        color="primary"
12✔
1514
                        defaultValue=""
12✔
1515
                        inputProps={
12✔
1516
                          { "data-testid": name } as React.InputHTMLAttributes<HTMLInputElement>
12✔
1517
                        }
12✔
1518
                      />
1519
                    }
1520
                    label={option}
12✔
1521
                  />
1522
                  {description && (
12!
1523
                    <FieldTooltip
×
1524
                      title={<DisplayDescription description={description} />}
×
1525
                      placement="right"
×
1526
                      arrow
×
1527
                      describeChild
×
1528
                    >
1529
                      <TooltipIcon />
×
1530
                    </FieldTooltip>
×
1531
                  )}
1532
                </React.Fragment>
12✔
1533
              ))}
6✔
1534
              <FormHelperText>{error?.message}</FormHelperText>
6!
1535
            </FormGroup>
6✔
1536
          </FormControl>
6✔
1537
        )
1538
      }}
6✔
1539
    </ConnectForm>
6✔
1540
  </Box>
6✔
1541
)
1542

1543
type FormArrayProps = {
1544
  object: FormObject
1545
  path: Array<string>
1546
  required: boolean
1547
}
1548

1549
const FormArrayTitle = styled(Paper, { shouldForwardProp: prop => prop !== "level" })<{
1✔
1550
  level: number
1551
}>(({ theme, level }) => ({
1✔
1552
  display: "flex",
8✔
1553
  flexDirection: "column",
8✔
1554
  justifyContent: "start",
8✔
1555
  alignItems: "start",
8✔
1556
  backgroundColor: level < 2 ? theme.palette.primary.light : theme.palette.common.white,
8!
1557
  height: "100%",
8✔
1558
  marginLeft: level < 2 ? "5rem" : 0,
8!
1559
  marginRight: "3rem",
8✔
1560
  padding: level === 1 ? "2rem" : 0,
8!
1561
}))
1✔
1562

1563
const FormArrayChildrenTitle = styled(Paper)(() => ({
1✔
1564
  width: "70%",
1✔
1565
  display: "inline-block",
1✔
1566
  marginBottom: "1rem",
1✔
1567
  paddingLeft: "1rem",
1✔
1568
  paddingTop: "1rem",
1✔
1569
}))
1✔
1570

1571
/*
1572
 * FormArray is rendered for arrays of objects. User is given option to choose how many objects to add to array.
1573
 */
1574
const FormArray = ({
1✔
1575
  object,
8✔
1576
  path,
8✔
1577
  required,
8✔
1578
  description,
8✔
1579
}: FormArrayProps & { description: string }) => {
8✔
1580
  const name = pathToName(path)
8✔
1581
  const [lastPathItem] = path.slice(-1)
8✔
1582
  const level = path.length
8✔
1583
  const label = object.title ?? lastPathItem
8!
1584

1585
  // Get currentObject and the values of current field
1586
  const currentObject = useAppSelector(state => state.currentObject) || {}
8!
1587
  const fileTypes = useAppSelector(state => state.fileTypes)
8✔
1588

1589
  const fieldValues = get(currentObject, name)
8✔
1590

1591
  const items = traverseValues(object.items) as FormObject
8✔
1592

1593
  const { control } = useForm()
8✔
1594

1595
  const {
8✔
1596
    unregister,
8✔
1597
    getValues,
8✔
1598
    setValue,
8✔
1599
    formState: { isSubmitted },
8✔
1600
    clearErrors,
8✔
1601
  } = useFormContext()
8✔
1602

1603
  const { fields, append, remove } = useFieldArray({ control, name })
8✔
1604

1605
  const [formFields, setFormFields] = React.useState<Record<"id", string>[] | null>(null)
8✔
1606
  const { t } = useTranslation()
8✔
1607

1608
  // Append the correct values to the equivalent fields when editing form
1609
  // This applies for the case: "fields" does not get the correct data (empty array) although there are values in the fields
1610
  // E.g. Study > StudyLinks or Experiment > Expected Base Call Table
1611
  // Append only once when form is populated
1612
  React.useEffect(() => {
8✔
1613
    if (
4✔
1614
      fieldValues?.length > 0 &&
4!
1615
      fields?.length === 0 &&
×
1616
      typeof fieldValues === "object" &&
×
1617
      !formFields
×
1618
    ) {
4!
1619
      const fieldsArray: Record<string, unknown>[] = []
×
1620
      for (let i = 0; i < fieldValues.length; i += 1) {
×
1621
        fieldsArray.push({ fieldValues: fieldValues[i] })
×
1622
      }
×
1623
      append(fieldsArray)
×
1624
    }
×
1625
    // Create initial fields when editing object
1626
    setFormFields(fields)
4✔
1627
  }, [fields])
8✔
1628

1629
  // Get unique fileTypes from submitted fileTypes
1630
  const uniqueFileTypes = uniq(
8✔
1631
    flatten(fileTypes?.map((obj: { fileTypes: string[] }) => obj.fileTypes))
8✔
1632
  )
8✔
1633

1634
  React.useEffect(() => {
8✔
1635
    // Append fileType to formats' field
1636
    if (name === "formats") {
3!
1637
      for (let i = 0; i < uniqueFileTypes.length; i += 1) {
×
1638
        append({ formats: uniqueFileTypes[i] })
×
1639
      }
×
1640
    }
×
1641
  }, [uniqueFileTypes.length])
8✔
1642

1643
  // Clear required field array error and append
1644
  const handleAppend = () => {
8✔
1645
    clearErrors([name])
1✔
1646
    append({})
1✔
1647
  }
1✔
1648

1649
  const handleRemove = (index: number) => {
8✔
1650
    // Unregister field if removing last item: empty array isn't flagged as missing or invalid
1651
    if (index === 0 && getValues(name)?.length <= 1) {
×
1652
      remove()
×
1653
      unregister(name)
×
1654
      return
×
1655
    }
×
1656
    // Set the correct values according to the name path when removing a field
1657
    const values = getValues(name)
×
1658
    const filteredValues = values?.filter((_val: unknown, ind: number) => ind !== index)
×
1659
    setValue(name, filteredValues)
×
1660
    setFormFields(filteredValues)
×
1661
    remove(index)
×
1662
  }
×
1663

1664
  return (
8✔
1665
    <Grid
8✔
1666
      container
8✔
1667
      key={`${name}-array`}
8✔
1668
      aria-labelledby={name}
8✔
1669
      data-testid={name}
8✔
1670
      direction={level < 2 ? "row" : "column"}
8!
1671
      sx={{ mb: level === 1 ? "3rem" : 0 }}
8!
1672
    >
1673
      <Grid size={{ xs: 12, md: 4 }}>
8✔
1674
        {
1675
          <FormArrayTitle square={true} elevation={0} level={level}>
8✔
1676
            <Typography
8✔
1677
              key={`${name}-header`}
8✔
1678
              variant={"subtitle1"}
8✔
1679
              data-testid={name}
8✔
1680
              role="heading"
8✔
1681
              color="secondary"
8✔
1682
            >
1683
              {label}
8✔
1684
              {required ? "*" : null}
8!
1685
              {required && formFields?.length === 0 && isSubmitted && (
8!
1686
                <span>
×
1687
                  <FormControl error>
×
1688
                    <FormHelperText>{t("errors.form.empty")}</FormHelperText>
×
1689
                  </FormControl>
×
1690
                </span>
×
1691
              )}
1692
              {description && (
8!
1693
                <FieldTooltip
×
1694
                  title={<DisplayDescription description={description} />}
×
1695
                  placement="top"
×
1696
                  arrow
×
1697
                  describeChild
×
1698
                >
1699
                  <TooltipIcon />
×
1700
                </FieldTooltip>
×
1701
              )}
1702
            </Typography>
8✔
1703
          </FormArrayTitle>
8✔
1704
        }
1705
      </Grid>
8✔
1706

1707
      <Grid size={{ xs: 12, md: 8 }}>
8✔
1708
        {formFields?.map((field, index) => {
8✔
1709
          const pathWithoutLastItem = path.slice(0, -1)
1✔
1710
          const lastPathItemWithIndex = `${lastPathItem}.${index}`
1✔
1711

1712
          if (items.oneOf) {
1✔
1713
            const pathForThisIndex = [...pathWithoutLastItem, lastPathItemWithIndex]
1✔
1714

1715
            return (
1✔
1716
              <Box
1✔
1717
                key={field.id || index}
1✔
1718
                data-testid={`${name}[${index}]`}
1✔
1719
                display="flex"
1✔
1720
                alignItems="center"
1✔
1721
              >
1722
                <FormArrayChildrenTitle elevation={2} square>
1✔
1723
                  <FormOneOfField
1✔
1724
                    key={field.id}
1✔
1725
                    nestedField={field as NestedField}
1✔
1726
                    path={pathForThisIndex}
1✔
1727
                    object={items}
1✔
1728
                  />
1729
                </FormArrayChildrenTitle>
1✔
1730
                <IconButton onClick={() => handleRemove(index)}>
1✔
1731
                  <RemoveIcon />
1✔
1732
                </IconButton>
1!
1733
              </Box>
1✔
1734
            )
1735
          }
1!
1736

1737
          const properties = object.items.properties
×
1738
          let requiredProperties =
×
1739
            index === 0 && object.contains?.allOf
×
1740
              ? object.contains?.allOf?.flatMap((item: FormObject) => item.required) // Case: DAC - Main Contact needs at least 1
×
1741
              : object.items?.required
×
1742

1743
          // Force first array item as required field if array is required but none of the items are required
1744
          if (required && !requiredProperties) requiredProperties = [Object.keys(items)[0]]
1!
1745

1746
          return (
×
1747
            <Box key={field.id || index} aria-labelledby={name} display="flex" alignItems="center">
×
1748
              <FormArrayChildrenTitle elevation={2} square>
×
1749
                {
1750
                  items
×
1751
                    ? Object.keys(items).map(item => {
×
1752
                        const pathForThisIndex = [
×
1753
                          ...pathWithoutLastItem,
×
1754
                          lastPathItemWithIndex,
×
1755
                          item,
×
1756
                        ]
1757
                        const requiredField = requiredProperties
×
1758
                          ? requiredProperties.filter((prop: string) => prop === item)
×
1759
                          : []
×
1760
                        return traverseFields(
×
1761
                          properties[item] as FormObject,
×
1762
                          pathForThisIndex,
×
1763
                          requiredField,
×
1764
                          false,
×
1765
                          field as NestedField
×
1766
                        )
×
1767
                      })
×
1768
                    : traverseFields(
×
1769
                        object.items,
×
1770
                        [...pathWithoutLastItem, lastPathItemWithIndex],
×
1771
                        [],
×
1772
                        false,
×
1773
                        field as NestedField
×
1774
                      ) // special case for doiSchema's "sizes" and "formats"
×
1775
                }
1776
              </FormArrayChildrenTitle>
1✔
1777
              <IconButton onClick={() => handleRemove(index)} size="large">
1✔
1778
                <RemoveIcon />
1✔
1779
              </IconButton>
1!
1780
            </Box>
1✔
1781
          )
1782
        })}
8✔
1783

1784
        <Button
8✔
1785
          variant="contained"
8✔
1786
          color="primary"
8✔
1787
          size="small"
8✔
1788
          startIcon={<AddIcon />}
8✔
1789
          onClick={() => handleAppend()}
8✔
1790
          sx={{ mb: "1rem" }}
8✔
1791
        >
1792
          Add new item
1793
        </Button>
8✔
1794
      </Grid>
8✔
1795
    </Grid>
8✔
1796
  )
1797
}
8✔
1798

1799
export default {
1✔
1800
  buildFields,
1✔
1801
  cleanUpFormValues,
1✔
1802
}
1✔
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

© 2026 Coveralls, Inc