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

CSCfi / metadata-submitter-frontend / 17324617246

29 Aug 2025 01:06PM UTC coverage: 58.026% (+0.09%) from 57.939%
17324617246

push

github

Hang Le
Input loss warning (merge commit)

Merge branch 'feature/warn-data-loss' into 'main'
* Accommodate the lack of default values in unsaved form check

* Restore form reset on navigation for hook-form

* Refactor unsaved input checks into a hook

* Add blur on form array element removal to force force input check

* Reset unsaved status on submission exit and new object submission

* Remove resetting of form on click to navigate away

* Add datafolder link confirmation dialog

* Track form state to alert of form data loss

Closes #1089 and #1068
See merge request https://gitlab.ci.csc.fi/sds-dev/sd-submit/metadata-submitter-frontend/-/merge_requests/1156

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

594 of 809 branches covered (73.42%)

Branch coverage included in aggregate %.

165 of 251 new or added lines in 12 files covered. (65.74%)

9 existing lines in 5 files now uncovered.

5331 of 9402 relevant lines covered (56.7%)

5.32 hits per line

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

66.03
/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 => {
12✔
94
    const property = data[key] as Record<string, unknown> | string | null
22✔
95

96
    if (typeof property === "object" && !Array.isArray(property)) {
22✔
97
      if (property !== null) {
7✔
98
        data[key] = traverseFormValuesForCleanUp(property)
7✔
99
        if (Object.keys(property).length === 0) delete data[key]
7✔
100
      }
7✔
101
    }
7✔
102
    if (property === "") {
22✔
103
      delete data[key]
10✔
104
    }
10✔
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) {
12✔
109
      data[key] = Number(data[key])
1✔
110
    }
1✔
111
  })
12✔
112
  return data
12✔
113
}
12✔
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()
236✔
131
  return children({ ...(methods as ConnectFormMethods) })
236✔
132
}
236✔
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 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!
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
798
      setValue(name, autocompleteField)
×
799
    } else if (prefilledValue === undefined && val) {
×
800
      // Remove values if autocompleteField is deleted
801
      setValue(name, "")
×
802
    }
×
803
  }, [autocompleteField, prefilledValue])
62✔
804

805
  // Remove values for Affiliations' <location of affiliation identifier> field if autocompleteField is deleted
806
  React.useEffect(() => {
62✔
807
    if (
28✔
808
      prefilledValue === undefined &&
28!
809
      val &&
×
810
      lastPathItem === prefilledHiddenFields[0] &&
×
811
      isDOIForm
×
812
    )
813
      setValue(name, "")
28!
814
  }, [prefilledValue])
62✔
815

816
  return (
62✔
817
    <ConnectForm>
62✔
818
      {({ control }: ConnectFormMethods) => {
62✔
819
        const multiLineRowIdentifiers = ["abstract", "description", "policy text"]
62✔
820

821
        return (
62✔
822
          <Controller
62✔
823
            render={({ field, fieldState: { error } }) => {
62✔
824
              const inputValue =
63✔
825
                (watchAutocompleteFieldName && typeof val !== "object" && val) ||
63!
826
                (typeof field.value !== "object" && field.value) ||
63✔
827
                ""
60✔
828

829
              const handleChange = (e: { target: { value: string | number } }) => {
63✔
830
                const { value } = e.target
2✔
831
                const parsedValue =
2✔
832
                  type === "string" && typeof value === "number" ? value.toString() : value
2!
833
                field.onChange(parsedValue) // Helps with Cypress change detection
2✔
834
                setValue(name, parsedValue) // Enables update of nested fields, eg. DAC contact
2✔
835
              }
2✔
836

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

883
/*
884
 * FormSelectField is rendered for selection from options where it's possible to choose many options
885
 */
886

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

951
/*
952
 * FormDatePicker used for selecting date or date rage in DOI form
953
 */
954

955
const StyledDatePicker = styled(DatePicker)(({ theme }) => ({
1✔
956
  "& .MuiIconButton-root": {
×
957
    color: theme.palette.primary.main,
×
958
    "&:hover": {
×
959
      backgroundColor: theme.palette.action.hover,
×
960
    },
×
961
  },
×
962
}))
1✔
963

964
const FormDatePicker = ({
1✔
965
  name,
×
966
  required,
×
967
  description,
×
968
}: FormFieldBaseProps & { description: string }) => {
×
969
  const { t } = useTranslation()
×
970
  const { getValues } = useFormContext()
×
971
  const defaultValue = getValues(name) || ""
×
972

973
  const getStartEndDates = (date: string) => {
×
974
    const [startInput, endInput] = date?.split("/")
×
975
    if (startInput && endInput) return [moment(startInput), moment(endInput)]
×
976
    else if (startInput) return [moment(startInput), null]
×
977
    else if (endInput) return [null, moment(endInput)]
×
978
    else return [null, null]
×
979
  }
×
980

981
  const [startDate, setStartDate] = React.useState<moment.Moment | null>(
×
982
    getStartEndDates(defaultValue)[0]
×
983
  )
×
984
  const [endDate, setEndDate] = React.useState<moment.Moment | null>(
×
985
    getStartEndDates(defaultValue)[1]
×
986
  )
×
987
  const [startError, setStartError] = React.useState<string | null>(null)
×
988
  const [endError, setEndError] = React.useState<string | null>(null)
×
989
  const clearForm = useAppSelector(state => state.clearForm)
×
990

991
  React.useEffect(() => {
×
992
    if (clearForm) {
×
993
      setStartDate(null)
×
994
      setEndDate(null)
×
995
    }
×
996
  }, [clearForm])
×
997

998
  const format = "YYYY-MM-DD"
×
999
  const formatDate = (date: moment.Moment) => moment(date).format(format)
×
1000

1001
  const makeValidDateString = (start: moment.Moment | null, end: moment.Moment | null) => {
×
1002
    let dateStr = ""
×
1003
    if (start && start?.isValid()) {
×
1004
      dateStr = formatDate(start)
×
1005
      if (end && end?.isValid() && formatDate(end) !== dateStr) {
×
1006
        dateStr += `/${formatDate(end)}`
×
1007
      }
×
1008
    }
×
1009
    return dateStr
×
1010
  }
×
1011

1012
  return (
×
1013
    <ConnectForm>
×
1014
      {({ setValue }: ConnectFormMethods) => {
×
1015
        const handleChangeStartDate = (newValue: moment.Moment | null) => {
×
1016
          setStartDate(newValue)
×
NEW
1017
          setValue(name, makeValidDateString(newValue, endDate), { shouldDirty: true })
×
1018
        }
×
1019

1020
        const handleChangeEndDate = (newValue: moment.Moment | null) => {
×
1021
          setEndDate(newValue)
×
NEW
1022
          setValue(name, makeValidDateString(startDate, newValue), { shouldDirty: true })
×
1023
        }
×
1024

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

1100
/*
1101
 * FormAutocompleteField uses ROR API to fetch organisations
1102
 */
1103
type RORItem = {
1104
  name: string
1105
  id: string
1106
}
1107
/*
1108
  More details of ROR data structure is here: https://ror.readme.io/docs/ror-data-structure
1109
*/
1110
type ROROrganization = Record<string, unknown> & {
1111
  id: string
1112
  names: { lang: string | null; types: string[]; value: string }[]
1113
}
1114

1115
const StyledAutocomplete = styled(Autocomplete)(() => ({
1✔
1116
  flex: "auto",
10✔
1117
  alignSelf: "flex-start",
10✔
1118
  "& + svg": {
10✔
1119
    marginTop: 1,
10✔
1120
  },
10✔
1121
})) as typeof Autocomplete
1✔
1122

1123
const FormAutocompleteField = ({
1✔
1124
  name,
10✔
1125
  label,
10✔
1126
  required,
10✔
1127
  description,
10✔
1128
}: FormFieldBaseProps & { description: string }) => {
10✔
1129
  const dispatch = useAppDispatch()
10✔
1130
  const { getValues } = useFormContext()
10✔
1131

1132
  const defaultValue = getValues(name) || ""
10✔
1133
  const [open, setOpen] = React.useState(false)
10✔
1134
  const [options, setOptions] = React.useState([])
10✔
1135
  const [inputValue, setInputValue] = React.useState("")
10✔
1136
  const [loading, setLoading] = React.useState(false)
10✔
1137

1138
  const fetchOrganisations = async (searchTerm: string) => {
10✔
1139
    // Check if searchTerm includes non-word char, for e.g. "(", ")", "-" because the api does not work with those chars
1140
    const isContainingNonWordChar = searchTerm.match(/\W/g)
1✔
1141
    const response =
1✔
1142
      isContainingNonWordChar === null ? await rorAPIService.getOrganisations(searchTerm) : null
1!
1143

1144
    if (response) setLoading(false)
1✔
1145

1146
    if (response?.ok) {
1✔
1147
      const mappedOrganisations = response.data.items.reduce(
1✔
1148
        (orgArr: RORItem[], org: ROROrganization) => {
1✔
1149
          const orgName = org.names.filter(name => name.types.includes("ror_display"))[0]?.value
1✔
1150
          if (orgName) {
1✔
1151
            orgArr.push({
1✔
1152
              name: orgName,
1✔
1153
              id: org.id,
1✔
1154
            })
1✔
1155
          }
1✔
1156
          return orgArr
1✔
1157
        },
1✔
1158
        []
1✔
1159
      )
1✔
1160

1161
      setOptions(mappedOrganisations)
1✔
1162
    }
1✔
1163
  }
1✔
1164

1165
  const debouncedSearch = debounce((newInput: string) => {
10✔
1166
    if (newInput.length > 0) fetchOrganisations(newInput)
1✔
1167
  }, 150)
10✔
1168

1169
  React.useEffect(() => {
10✔
1170
    let active = true
5✔
1171

1172
    if (inputValue === "") {
5✔
1173
      setOptions([])
3✔
1174
      return undefined
3✔
1175
    }
3✔
1176

1177
    if (active && open) {
5✔
1178
      setLoading(true)
1✔
1179
      debouncedSearch(inputValue)
1✔
1180
    }
1✔
1181

1182
    return () => {
2✔
1183
      active = false
2✔
1184
      setLoading(false)
2✔
1185
    }
2✔
1186
  }, [inputValue])
10✔
1187

1188
  return (
10✔
1189
    <ConnectForm>
10✔
1190
      {({ errors, control }: ConnectFormMethods) => {
10✔
1191
        const error = get(errors, name)
10✔
1192

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

1283
const ValidationTagField = styled(TextField)(({ theme }) => ({
1✔
1284
  "& .MuiOutlinedInput-root.MuiInputBase-root": { flexWrap: "wrap" },
×
1285
  "& input": { flex: 1, minWidth: "2rem" },
×
1286
  "& label": { color: theme.palette.primary.main },
×
1287
  "& .MuiOutlinedInput-notchedOutline, div:hover .MuiOutlinedInput-notchedOutline":
×
1288
    highlightStyle(theme),
×
1289
}))
1✔
1290

1291
const FormTagField = ({
1✔
1292
  name,
×
1293
  label,
×
1294
  required,
×
1295
  description,
×
1296
}: FormFieldBaseProps & { description: string }) => {
×
1297
  const savedValues = useWatch({ name })
×
1298
  const [inputValue, setInputValue] = React.useState("")
×
1299
  const [tags, setTags] = React.useState<Array<string>>([])
×
1300

1301
  React.useEffect(() => {
×
1302
    // update tags when value becomes available or changes
1303
    const updatedTags = savedValues ? savedValues.split(",") : []
×
1304
    setTags(updatedTags)
×
1305
  }, [savedValues])
×
1306

1307
  const handleInputChange = e => {
×
1308
    setInputValue(e.target.value)
×
1309
  }
×
1310

1311
  const clearForm = useAppSelector(state => state.clearForm)
×
1312

1313
  React.useEffect(() => {
×
1314
    if (clearForm) {
×
1315
      setTags([])
×
1316
      setInputValue("")
×
1317
    }
×
1318
  }, [clearForm])
×
1319

NEW
1320
  const inputRef = React.useRef<HTMLInputElement | null>(null)
×
1321

1322
  return (
×
1323
    <ConnectForm>
×
1324
      {({ control }: ConnectFormMethods) => {
×
1325
        return (
×
1326
          <Controller
×
1327
            name={name}
×
1328
            control={control}
×
NEW
1329
            defaultValue={""}
×
1330
            render={({ field }) => {
×
1331
              const handleKeywordAsTag = (keyword: string) => {
×
1332
                // newTags with unique values
1333
                const newTags = !tags.includes(keyword) ? [...tags, keyword] : tags
×
1334
                setInputValue("")
×
1335
                // Convert tags to string for hidden registered input's values
1336
                field.onChange(newTags.join(","))
×
1337
              }
×
1338

1339
              const handleKeyDown = e => {
×
1340
                const { key } = e
×
1341
                const trimmedInput = inputValue.trim()
×
1342
                // Convert to tags if users press "," OR "Enter"
1343
                if ((key === "," || key === "Enter") && trimmedInput.length > 0) {
×
1344
                  e.preventDefault()
×
1345
                  handleKeywordAsTag(trimmedInput)
×
1346
                }
×
1347
              }
×
1348

1349
              // Convert to tags when user clicks outside of input field
1350
              const handleOnBlur = () => {
×
1351
                const trimmedInput = inputValue.trim()
×
1352
                if (trimmedInput.length > 0) {
×
1353
                  handleKeywordAsTag(trimmedInput)
×
1354
                }
×
1355
              }
×
1356

1357
              const handleTagDelete = item => () => {
×
1358
                const newTags = tags.filter(tag => tag !== item)
×
1359
                field.onChange(newTags.join(","))
×
1360
                // manual focus to trigger blur event
NEW
1361
                inputRef.current?.focus()
×
UNCOV
1362
              }
×
1363

1364
              return (
×
1365
                <BaselineDiv>
×
1366
                  <input
×
1367
                    {...field}
×
1368
                    required={required}
×
1369
                    style={{ width: 0, opacity: 0, transform: "translate(8rem, 2rem)" }}
×
NEW
1370
                    ref={inputRef}
×
1371
                  />
1372
                  <ValidationTagField
×
1373
                    slotProps={{
×
1374
                      htmlInput: { "data-testid": name },
×
1375
                      input: {
×
1376
                        startAdornment:
×
1377
                          tags.length > 0
×
1378
                            ? tags.map(item => (
×
1379
                                <Chip
×
1380
                                  key={item}
×
1381
                                  tabIndex={-1}
×
1382
                                  label={item}
×
1383
                                  onDelete={handleTagDelete(item)}
×
1384
                                  color="primary"
×
1385
                                  deleteIcon={<ClearIcon fontSize="small" />}
×
1386
                                  data-testid={item}
×
1387
                                  sx={{ fontSize: "1.4rem", m: "0.5rem" }}
×
1388
                                />
1389
                              ))
×
1390
                            : null,
×
1391
                      },
×
1392
                    }}
×
1393
                    label={label}
×
1394
                    id={name}
×
1395
                    value={inputValue}
×
1396
                    onChange={handleInputChange}
×
1397
                    onKeyDown={handleKeyDown}
×
1398
                    onBlur={handleOnBlur}
×
1399
                  />
1400

1401
                  {description && (
×
1402
                    <FieldTooltip
×
1403
                      title={<DisplayDescription description={description} />}
×
1404
                      placement="right"
×
1405
                      arrow
×
1406
                      describeChild
×
1407
                    >
1408
                      <TooltipIcon />
×
1409
                    </FieldTooltip>
×
1410
                  )}
1411
                </BaselineDiv>
×
1412
              )
1413
            }}
×
1414
          />
1415
        )
1416
      }}
×
1417
    </ConnectForm>
×
1418
  )
1419
}
×
1420

1421
/*
1422
 * Highlight required Checkbox
1423
 */
1424
const ValidationFormControlLabel = styled(FormControlLabel)(({ theme }) => ({
1✔
1425
  label: {
6✔
1426
    "& span": { color: theme.palette.primary.main },
6✔
1427
  },
6✔
1428
}))
1✔
1429

1430
const FormBooleanField = ({
1✔
1431
  name,
6✔
1432
  label,
6✔
1433
  required,
6✔
1434
  description,
6✔
1435
}: FormFieldBaseProps & { description: string }) => {
6✔
1436
  return (
6✔
1437
    <ConnectForm>
6✔
1438
      {({ register, errors, getValues }: ConnectFormMethods) => {
6✔
1439
        const error = get(errors, name)
6✔
1440

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

1483
                <FormHelperText>{error?.message}</FormHelperText>
6!
1484
              </FormGroup>
6✔
1485
            </FormControl>
6✔
1486
          </Box>
6✔
1487
        )
1488
      }}
6✔
1489
    </ConnectForm>
6✔
1490
  )
1491
}
6✔
1492

1493
const FormCheckBoxArray = ({
1✔
1494
  name,
6✔
1495
  label,
6✔
1496
  required,
6✔
1497
  options,
6✔
1498
  description,
6✔
1499
}: FormSelectFieldProps & { description: string }) => (
6✔
1500
  <Box px={1}>
6✔
1501
    <p>{label}</p>
6✔
1502
    <ConnectForm>
6✔
1503
      {({ register, errors, getValues }: ConnectFormMethods) => {
6✔
1504
        const values = getValues()[name]
6✔
1505

1506
        const error = get(errors, name)
6✔
1507

1508
        const { ref, ...rest } = register(name)
6✔
1509

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

1554
type FormArrayProps = {
1555
  object: FormObject
1556
  path: Array<string>
1557
  required: boolean
1558
}
1559

1560
const FormArrayTitle = styled(Paper, { shouldForwardProp: prop => prop !== "level" })<{
1✔
1561
  level: number
1562
}>(({ theme, level }) => ({
1✔
1563
  display: "flex",
8✔
1564
  flexDirection: "column",
8✔
1565
  justifyContent: "start",
8✔
1566
  alignItems: "start",
8✔
1567
  backgroundColor: level < 2 ? theme.palette.primary.light : theme.palette.common.white,
8!
1568
  height: "100%",
8✔
1569
  marginLeft: level < 2 ? "5rem" : 0,
8!
1570
  marginRight: "3rem",
8✔
1571
  padding: level === 1 ? "2rem" : 0,
8!
1572
}))
1✔
1573

1574
const FormArrayChildrenTitle = styled(Paper)(() => ({
1✔
1575
  width: "70%",
1✔
1576
  display: "inline-block",
1✔
1577
  marginBottom: "1rem",
1✔
1578
  paddingLeft: "1rem",
1✔
1579
  paddingTop: "1rem",
1✔
1580
}))
1✔
1581

1582
/*
1583
 * FormArray is rendered for arrays of objects. User is given option to choose how many objects to add to array.
1584
 */
1585
const FormArray = ({
1✔
1586
  object,
8✔
1587
  path,
8✔
1588
  required,
8✔
1589
  description,
8✔
1590
}: FormArrayProps & { description: string }) => {
8✔
1591
  const name = pathToName(path)
8✔
1592
  const [lastPathItem] = path.slice(-1)
8✔
1593
  const level = path.length
8✔
1594
  const label = object.title ?? lastPathItem
8!
1595

1596
  // Get currentObject and the values of current field
1597
  const currentObject = useAppSelector(state => state.currentObject) || {}
8!
1598
  const fileTypes = useAppSelector(state => state.fileTypes)
8✔
1599

1600
  const fieldValues = get(currentObject, name)
8✔
1601

1602
  const items = traverseValues(object.items) as FormObject
8✔
1603

1604
  const { control } = useForm()
8✔
1605

1606
  const {
8✔
1607
    unregister,
8✔
1608
    getValues,
8✔
1609
    setValue,
8✔
1610
    formState: { isSubmitted },
8✔
1611
    clearErrors,
8✔
1612
  } = useFormContext()
8✔
1613

1614
  const { fields, append, remove } = useFieldArray({ control, name })
8✔
1615

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

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

1640
  // Get unique fileTypes from submitted fileTypes
1641
  const uniqueFileTypes = uniq(
8✔
1642
    flatten(fileTypes?.map((obj: { fileTypes: string[] }) => obj.fileTypes))
8✔
1643
  )
8✔
1644

1645
  React.useEffect(() => {
8✔
1646
    // Append fileType to formats' field
1647
    if (name === "formats") {
3!
1648
      for (let i = 0; i < uniqueFileTypes.length; i += 1) {
×
1649
        append({ formats: uniqueFileTypes[i] })
×
1650
      }
×
1651
    }
×
1652
  }, [uniqueFileTypes.length])
8✔
1653

1654
  // Clear required field array error and append
1655
  const handleAppend = () => {
8✔
1656
    clearErrors([name])
1✔
1657
    append({})
1✔
1658
  }
1✔
1659

1660
  const handleRemove = (index: number) => {
8✔
1661
    // Unregister field if removing last item: empty array isn't flagged as missing or invalid
1662
    if (index === 0 && getValues(name)?.length <= 1) {
×
1663
      remove()
×
1664
      unregister(name)
×
NEW
1665
    } else {
×
1666
      // Set the correct values according to the name path when removing a field
NEW
1667
      const values = getValues(name)
×
NEW
1668
      const filteredValues = values?.filter((_val: unknown, ind: number) => ind !== index)
×
NEW
1669
      setValue(name, filteredValues)
×
NEW
1670
      setFormFields(filteredValues)
×
NEW
1671
      remove(index)
×
NEW
1672
    }
×
NEW
1673
    if (document.activeElement instanceof HTMLElement) {
×
1674
      // force input check onBlur
NEW
1675
      document.activeElement.blur()
×
UNCOV
1676
    }
×
UNCOV
1677
  }
×
1678

1679
  return (
8✔
1680
    <Grid
8✔
1681
      container
8✔
1682
      key={`${name}-array`}
8✔
1683
      aria-labelledby={name}
8✔
1684
      data-testid={name}
8✔
1685
      direction={level < 2 ? "row" : "column"}
8!
1686
      sx={{ mb: level === 1 ? "3rem" : 0 }}
8!
1687
    >
1688
      <Grid size={{ xs: 12, md: 4 }}>
8✔
1689
        {
1690
          <FormArrayTitle square={true} elevation={0} level={level}>
8✔
1691
            <Typography
8✔
1692
              key={`${name}-header`}
8✔
1693
              variant={"subtitle1"}
8✔
1694
              data-testid={name}
8✔
1695
              role="heading"
8✔
1696
              color="secondary"
8✔
1697
            >
1698
              {label}
8✔
1699
              {required ? "*" : null}
8!
1700
              {required && formFields?.length === 0 && isSubmitted && (
8!
1701
                <span>
×
1702
                  <FormControl error>
×
1703
                    <FormHelperText>{t("errors.form.empty")}</FormHelperText>
×
1704
                  </FormControl>
×
1705
                </span>
×
1706
              )}
1707
              {description && (
8!
1708
                <FieldTooltip
×
1709
                  title={<DisplayDescription description={description} />}
×
1710
                  placement="top"
×
1711
                  arrow
×
1712
                  describeChild
×
1713
                >
1714
                  <TooltipIcon />
×
1715
                </FieldTooltip>
×
1716
              )}
1717
            </Typography>
8✔
1718
          </FormArrayTitle>
8✔
1719
        }
1720
      </Grid>
8✔
1721

1722
      <Grid size={{ xs: 12, md: 8 }}>
8✔
1723
        {formFields?.map((field, index) => {
8✔
1724
          const pathWithoutLastItem = path.slice(0, -1)
1✔
1725
          const lastPathItemWithIndex = `${lastPathItem}.${index}`
1✔
1726

1727
          if (items.oneOf) {
1✔
1728
            const pathForThisIndex = [...pathWithoutLastItem, lastPathItemWithIndex]
1✔
1729

1730
            return (
1✔
1731
              <Box
1✔
1732
                key={field.id || index}
1✔
1733
                data-testid={`${name}[${index}]`}
1✔
1734
                display="flex"
1✔
1735
                alignItems="center"
1✔
1736
              >
1737
                <FormArrayChildrenTitle elevation={2} square>
1✔
1738
                  <FormOneOfField
1✔
1739
                    key={field.id}
1✔
1740
                    nestedField={field as NestedField}
1✔
1741
                    path={pathForThisIndex}
1✔
1742
                    object={items}
1✔
1743
                  />
1744
                </FormArrayChildrenTitle>
1✔
1745
                <IconButton onClick={() => handleRemove(index)}>
1✔
1746
                  <RemoveIcon />
1✔
1747
                </IconButton>
1!
1748
              </Box>
1✔
1749
            )
1750
          }
1!
1751

1752
          const properties = object.items.properties
×
1753
          let requiredProperties =
×
1754
            index === 0 && object.contains?.allOf
×
1755
              ? object.contains?.allOf?.flatMap((item: FormObject) => item.required) // Case: DAC - Main Contact needs at least 1
×
1756
              : object.items?.required
×
1757

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

1761
          return (
×
1762
            <Box key={field.id || index} aria-labelledby={name} display="flex" alignItems="center">
×
1763
              <FormArrayChildrenTitle elevation={2} square>
×
1764
                {
1765
                  items
×
1766
                    ? Object.keys(items).map(item => {
×
1767
                        const pathForThisIndex = [
×
1768
                          ...pathWithoutLastItem,
×
1769
                          lastPathItemWithIndex,
×
1770
                          item,
×
1771
                        ]
1772
                        const requiredField = requiredProperties
×
1773
                          ? requiredProperties.filter((prop: string) => prop === item)
×
1774
                          : []
×
1775
                        return traverseFields(
×
1776
                          properties[item] as FormObject,
×
1777
                          pathForThisIndex,
×
1778
                          requiredField,
×
1779
                          false,
×
1780
                          field as NestedField
×
1781
                        )
×
1782
                      })
×
1783
                    : traverseFields(
×
1784
                        object.items,
×
1785
                        [...pathWithoutLastItem, lastPathItemWithIndex],
×
1786
                        [],
×
1787
                        false,
×
1788
                        field as NestedField
×
1789
                      ) // special case for doiSchema's "sizes" and "formats"
×
1790
                }
1791
              </FormArrayChildrenTitle>
1✔
1792
              <IconButton onClick={() => handleRemove(index)} size="large">
1✔
1793
                <RemoveIcon />
1✔
1794
              </IconButton>
1!
1795
            </Box>
1✔
1796
          )
1797
        })}
8✔
1798

1799
        <Button
8✔
1800
          variant="contained"
8✔
1801
          color="primary"
8✔
1802
          size="small"
8✔
1803
          startIcon={<AddIcon />}
8✔
1804
          onClick={() => handleAppend()}
8✔
1805
          sx={{ mb: "1rem" }}
8✔
1806
        >
1807
          {t("formActions.addItem")}
8✔
1808
        </Button>
8✔
1809
      </Grid>
8✔
1810
    </Grid>
8✔
1811
  )
1812
}
8✔
1813

1814
export default {
1✔
1815
  buildFields,
1✔
1816
  cleanUpFormValues,
1✔
1817
}
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