Skip to content

Commit

Permalink
feat(trackerForm): populate defaultCompletions with required ones
Browse files Browse the repository at this point in the history
  • Loading branch information
Clm-Roig committed Apr 19, 2022
1 parent eb10f80 commit c06daef
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 32 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
import styled from '@emotion/styled';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import DeleteIcon from '@mui/icons-material/Delete';
import { Box, Button, Grid, GridProps, IconButton, Typography, useTheme } from '@mui/material';
import {
Box,
Button,
FormControl,
FormHelperText,
Grid,
GridProps,
IconButton,
InputLabel,
MenuItem,
Select,
Typography,
useTheme
} from '@mui/material';
import { FC } from 'react';
import {
Control,
Expand All @@ -12,11 +25,11 @@ import {
} from 'react-hook-form';

import { useAppSelector } from '../../../app/hooks';
import Completion from '../../../models/Completion';
import ThemeMode from '../../../models/ThemeMode';
import { selectThemeMode } from '../../../store/theme/theme.selectors';
import { FormValues } from '../TrackerForm/types';
import CompletionQuantityTextField from '../completions/CompletionQuantityTextField';
import CompletionUnitTextField from '../completions/CompletionUnitTextField';

export const FieldsetGrid = styled(Grid)`
border: 1px solid rgba(0, 0, 0, 0.23);
Expand All @@ -30,6 +43,7 @@ interface Props {
fields: FieldArrayWithId<FormValues, 'defaultCompletions', 'id'>[];
gridProps?: GridProps;
remove: UseFieldArrayRemove;
requiredCompletions: Completion[];
}

/**
Expand All @@ -38,7 +52,14 @@ interface Props {
* @param {*} { append, control, fields, gridProps, remove }
* @return {*}
*/
const DefaultCompletionsForm: FC<Props> = ({ append, control, fields, gridProps, remove }) => {
const DefaultCompletionsForm: FC<Props> = ({
append,
control,
fields,
gridProps,
remove,
requiredCompletions
}) => {
const themeMode = useAppSelector(selectThemeMode);
const theme = useTheme();

Expand Down Expand Up @@ -108,19 +129,39 @@ const DefaultCompletionsForm: FC<Props> = ({ append, control, fields, gridProps,
<Controller
control={control}
name={`defaultCompletions.${index}.unit` as const}
rules={{ required: true }}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<CompletionUnitTextField
error={!!error}
helperText={error ? 'Une unité est requise' : ''}
label={'Unité'}
onChange={onChange}
required
size="small"
sx={{ mb: 1 }}
value={value}
/>
)}
rules={{
required: true
}}
render={({ field: { onChange, value }, fieldState: { error } }) => {
let errorText = '';
if (error) {
switch (error.type) {
case 'required':
errorText = "L'unité est requise";
break;
}
}
return (
<FormControl fullWidth error={!!error} size="small">
<InputLabel>Unité</InputLabel>
<Select
required
value={(requiredCompletions.find((rc) => rc.unit === value) && value) || ''}
label="Unité"
onChange={onChange}
size="small">
{requiredCompletions
.filter((rc) => rc.unit && rc.unit !== '')
.map((rc) => (
<MenuItem key={rc.unit} value={rc.unit}>
{rc.unit}
</MenuItem>
))}
</Select>
<FormHelperText>{error ? errorText : ''}</FormHelperText>
</FormControl>
);
}}
/>
</Grid>
</FieldsetGrid>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from 'react-hook-form';

import { useAppSelector } from '../../../app/hooks';
import Completion from '../../../models/Completion';
import ThemeMode from '../../../models/ThemeMode';
import { selectThemeMode } from '../../../store/theme/theme.selectors';
import { FormValues } from '../TrackerForm/types';
Expand All @@ -28,8 +29,7 @@ interface Props {
append: UseFieldArrayAppend<FormValues, 'requiredCompletions'>;
control: Control<FormValues, any> /* eslint-disable-line @typescript-eslint/no-explicit-any */;
fields: FieldArrayWithId<FormValues, 'requiredCompletions', 'id'>[];
// eslint-disable-next-line @typescript-eslint/ban-types
getValues: (payload?: string | string[]) => FormValues;
requiredCompletions: Completion[];
gridProps?: GridProps;
remove: UseFieldArrayRemove;
}
Expand All @@ -44,7 +44,7 @@ const RequiredCompletionsForm: FC<Props> = ({
append,
control,
fields,
getValues,
requiredCompletions,
gridProps,
remove
}) => {
Expand All @@ -57,7 +57,6 @@ const RequiredCompletionsForm: FC<Props> = ({
};

const uniqueUnit = (v: string) => {
const requiredCompletions = getValues().requiredCompletions;
const nbCompletions = requiredCompletions.filter((v2) => v2.unit === v);
return nbCompletions.length < 2;
};
Expand Down
52 changes: 40 additions & 12 deletions src/components/forms/TrackerForm/TrackerForm.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Box, Button, Stack, TextField } from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { FC } from 'react';
import { Controller, useFieldArray, useForm } from 'react-hook-form';
import { Controller, useFieldArray, useForm, useWatch } from 'react-hook-form';
import { v4 } from 'uuid';

import { useAppDispatch } from '../../../app/hooks';
import Completion from '../../../models/Completion';
import TrackerStatus from '../../../models/TrackerStatus';
import { createTracker } from '../../../store/trackers/trackersSlice';
import DefaultCompletionsForm from '../DefaultCompletionsForm/DefaultCompletionsForm';
Expand All @@ -27,7 +28,8 @@ interface Props {
}

const TrackerForm: FC<Props> = ({ hideForm }) => {
const { control, getValues, handleSubmit, reset } = useForm<FormValues>({
const dispatch = useAppDispatch();
const { control, handleSubmit, reset } = useForm<FormValues>({
defaultValues: getDefaultValues()
});
const requiredCompletionsFieldArray = useFieldArray({
Expand All @@ -38,13 +40,23 @@ const TrackerForm: FC<Props> = ({ hideForm }) => {
control, // control props comes from useForm
name: 'defaultCompletions'
});

const dispatch = useAppDispatch();
const requiredCompletions = useWatch({
control,
name: 'requiredCompletions'
});

const resetToDefault = () => {
reset(getDefaultValues());
};

const removeRequiredCompletion = (index?: number | number[]) => {
// If it's the latest requiredCompletions, defaultCompletions should be emptied
if (requiredCompletions.length === 1) {
defaultCompletionsFieldArray.replace([]);
}
requiredCompletionsFieldArray.remove(index);
};

const onSubmit = (data: FormValues) => {
const { beginDate, duration, requiredCompletions } = data;
dispatch(
Expand Down Expand Up @@ -144,16 +156,32 @@ const TrackerForm: FC<Props> = ({ hideForm }) => {
append={requiredCompletionsFieldArray.append}
control={control}
fields={requiredCompletionsFieldArray.fields}
getValues={getValues}
remove={requiredCompletionsFieldArray.remove}
remove={removeRequiredCompletion}
requiredCompletions={requiredCompletions.map(
(rc) =>
({
...rc,
quantity: Number(rc.quantity)
} as Completion)
)}
/>

<DefaultCompletionsForm
append={defaultCompletionsFieldArray.append}
control={control}
fields={defaultCompletionsFieldArray.fields}
remove={defaultCompletionsFieldArray.remove}
/>
{requiredCompletions.length > 0 &&
requiredCompletions.some((rc) => rc.unit !== '' && rc.unit !== undefined) && (
<DefaultCompletionsForm
append={defaultCompletionsFieldArray.append}
control={control}
fields={defaultCompletionsFieldArray.fields}
remove={defaultCompletionsFieldArray.remove}
requiredCompletions={requiredCompletions.map(
(rc) =>
({
...rc,
quantity: Number(rc.quantity)
} as Completion)
)}
/>
)}

<Stack direction="row" justifyContent="center" spacing={1}>
<Button type="submit" onClick={handleSubmit(onSubmit)} variant={'outlined'}>
Expand Down

0 comments on commit c06daef

Please sign in to comment.