-
Notifications
You must be signed in to change notification settings - Fork 2
/
RenderSurvey.tsx
112 lines (101 loc) · 3.3 KB
/
RenderSurvey.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* eslint-disable react/no-array-index-key */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Box, Button, Typography } from '@mui/material'
import LoadingButton from '@mui/lab/LoadingButton'
import { Locales, Question } from '@backend/types'
import { Control, UseFormWatch } from 'react-hook-form/dist/types'
import { useFormState } from 'react-hook-form'
import RenderQuestion from './RenderQuestion'
import SurveyButtons from '../Common/SurveyButtons'
import { useResultData } from '../../contexts/ResultDataContext'
import styles from '../../styles'
const RenderSurvey = ({
questions,
control,
watch,
isSubmitted,
submitButtonLoading,
}: {
control: Control<any>
watch: UseFormWatch<any>
questions: Question[]
isSubmitted: boolean
submitButtonLoading: boolean
}) => {
const { t, i18n } = useTranslation()
const { dirtyFields, defaultValues, errors } = useFormState({ control })
const { resultData } = useResultData()
const [showQuestions, setShowQuestions] = useState(Boolean(resultData))
if (!questions || !watch || !defaultValues) return null
const { cardStyles, formStyles } = styles
const { language } = i18n
const requiredFields = Object.keys(defaultValues).filter(
(value) => !['1', '2', '7', 'faculty'].includes(value)
)
return (
<Box sx={cardStyles.outerBox}>
<Box sx={cardStyles.card}>
{questions.map((question) => (
<Box key={question.id} sx={cardStyles.card}>
{showQuestions && question.parentId === null && (
<RenderQuestion
control={control}
watch={watch}
question={question}
questions={questions}
language={language}
/>
)}
</Box>
))}
{Object.values(errors).length !== 0 && (
<Box sx={{ p: 2 }}>
<Typography>
{t('questions:requiredQuestionsNeedAnswers')}
</Typography>
<ul>
{requiredFields
.filter((id) => !Object.keys(dirtyFields).includes(id))
.map((id) => (
<li key={id}>
<Typography color="red">
{
questions.find((q) => q.id.toString() === id)?.title[
language as keyof Locales
]
}
</Typography>
</li>
))}
</ul>
</Box>
)}
<Box sx={formStyles.stackBox}>
{!showQuestions ? (
<Button
data-cy="open-form-button"
onClick={() => setShowQuestions(true)}
>
{t('openForm')}
</Button>
) : (
<SurveyButtons>
<LoadingButton
sx={formStyles.stackButton}
type="submit"
data-cy="submit-form-button"
variant="contained"
loading={submitButtonLoading}
>
{isSubmitted ? t('updateSubmit') : t('submit')}
</LoadingButton>
</SurveyButtons>
)}
</Box>
</Box>
</Box>
)
}
export default RenderSurvey