Skip to content

Commit

Permalink
feat(defaultCompletions): add tracker defaultCompletions
Browse files Browse the repository at this point in the history
  • Loading branch information
Clm-Roig committed Apr 16, 2022
1 parent 183cd48 commit 3f94e64
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 2 deletions.
139 changes: 139 additions & 0 deletions src/components/forms/DefaultCompletionsForm/DefaultCompletionsForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
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 { FC } from 'react';
import {
Control,
Controller,
FieldArrayWithId,
UseFieldArrayAppend,
UseFieldArrayRemove
} from 'react-hook-form';

import { useAppSelector } from '../../../app/hooks';
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);
border-radius: 4px;
padding: 8px;
`;

interface Props {
append: UseFieldArrayAppend<FormValues, 'defaultCompletions'>;
control: Control<FormValues, any> /* eslint-disable-line @typescript-eslint/no-explicit-any */;
fields: FieldArrayWithId<FormValues, 'defaultCompletions', 'id'>[];
gridProps?: GridProps;
remove: UseFieldArrayRemove;
}

/**
* This forms is used to create one or many defaultCompletions for a new tracker.
*
* @param {*} { append, control, fields, gridProps, remove }
* @return {*}
*/
const DefaultCompletionsForm: FC<Props> = ({ append, control, fields, gridProps, remove }) => {
const themeMode = useAppSelector(selectThemeMode);
const theme = useTheme();

const fieldsetSx = {
bgcolor: themeMode === ThemeMode.LIGHT ? theme.palette.grey[100] : theme.palette.grey[900],
mb: 1
};

return (
<Box>
{fields.map((field, index) => (
<FieldsetGrid columns={2} container key={field.id} sx={fieldsetSx} {...gridProps}>
<Grid item xs={2} sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
<Typography variant="subtitle1">Réalisation par défaut n°{index + 1}</Typography>
<IconButton onClick={() => remove(index)} sx={{ p: 0 }}>
<DeleteIcon color="error" />
</IconButton>
</Grid>
<Grid item xs={1}>
<Controller
control={control}
name={`defaultCompletions.${index}.quantity` as const}
rules={{
min: 0,
pattern: /^\d+$/,
required: true
}}
render={({ field: { onChange, value }, fieldState: { error } }) => {
let errorText = '';
if (error) {
switch (error.type) {
case 'min':
errorText = 'La quantité doit être supérieure à 0.';
break;

case 'pattern':
errorText = 'La quantité doit être un nombre.';
break;

case 'required':
errorText = 'La quantité est requise';
break;
}
}
return (
<CompletionQuantityTextField
error={!!error}
helperText={error && errorText}
label={'Quantité'}
onChange={onChange}
required
size="small"
inputProps={{
style: {
textAlign: 'right'
}
}}
sx={{ mb: 1 }}
style={{}}
value={value || ''}
/>
);
}}
/>
</Grid>
<Grid item xs={1}>
<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}
/>
)}
/>
</Grid>
</FieldsetGrid>
))}
<Button
onClick={() => append({})}
startIcon={<AddCircleOutlineIcon />}
sx={{ mb: 2 }}
variant="contained">
Réalisation par défaut
</Button>
</Box>
);
};

export default DefaultCompletionsForm;
22 changes: 20 additions & 2 deletions src/components/forms/TrackerForm/TrackerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import { v4 } from 'uuid';
import { useAppDispatch } from '../../../app/hooks';
import TrackerStatus from '../../../models/TrackerStatus';
import { createTracker } from '../../../store/trackers/trackersSlice';
import DefaultCompletionsForm from '../DefaultCompletionsForm/DefaultCompletionsForm';
import RequiredCompletionsForm from '../RequiredCompletionsForm/RequiredCompletionsForm';
import { FormValues } from './types';

const getDefaultValues = (): FormValues => ({
id: v4(),
beginDate: new Date().toString(),
duration: '',
defaultCompletions: [],
entries: [],
name: '',
requiredCompletions: [
Expand All @@ -33,10 +35,14 @@ const TrackerForm: FC<Props> = ({ hideForm }) => {
const { control, handleSubmit, reset } = useForm<FormValues>({
defaultValues: getDefaultValues()
});
const { fields, append, remove } = useFieldArray({
const requiredCompletionsFieldArray = useFieldArray({
control, // control props comes from useForm
name: 'requiredCompletions'
});
const defaultCompletionsFieldArray = useFieldArray({
control, // control props comes from useForm
name: 'defaultCompletions'
});

const dispatch = useAppDispatch();

Expand Down Expand Up @@ -139,7 +145,19 @@ const TrackerForm: FC<Props> = ({ hideForm }) => {
}}
/>

<RequiredCompletionsForm append={append} control={control} fields={fields} remove={remove} />
<RequiredCompletionsForm
append={requiredCompletionsFieldArray.append}
control={control}
fields={requiredCompletionsFieldArray.fields}
remove={requiredCompletionsFieldArray.remove}
/>

<DefaultCompletionsForm
append={defaultCompletionsFieldArray.append}
control={control}
fields={defaultCompletionsFieldArray.fields}
remove={defaultCompletionsFieldArray.remove}
/>

<Stack direction="row" justifyContent="center" spacing={1}>
<Button type="submit" onClick={handleSubmit(onSubmit)} variant={'outlined'}>
Expand Down
2 changes: 2 additions & 0 deletions src/models/Tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import TrackerStatus from './TrackerStatus';
* @member {string} id a v4 uuid
* @member {string} beginDate when the completions start (can be in the past or the future)
* @member {string?} dateHidden when not undefined, specify which day the tracker is ignored. The next day, it's automatically set to "undefined".
* @member {Completion[]} defaultCompletions default completions submitted when validating the tracker
* @member {number?} duration number of days the tracker is active since beginDate
* @member {string} endDate when the Tracker is over
* @member {TrackerEntry[]} entries TrackerEntries related to this Tracker
Expand All @@ -22,6 +23,7 @@ export default interface Tracker {
readonly id: string;
beginDate: string;
dateHidden?: string;
defaultCompletions?: Completion[];
duration?: number;
endDate?: string;
entries: TrackerEntry[];
Expand Down
16 changes: 16 additions & 0 deletions src/store/trackers/FAKE_DATA.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ export const testTracker1Id = '123e4567-e89b-12d3-a456-426614174000';
export const testTracker1: Tracker = {
id: testTracker1Id,
beginDate: subDays(new Date(), 3).toString(),
defaultCompletions: [
{
quantity: 10,
unit: 'push-ups'
},
{
quantity: 15,
unit: 'squats'
}
],
duration: 13,
name: 'Musculation',
remainingDays: 10,
Expand Down Expand Up @@ -46,6 +56,12 @@ export const testTracker3Id = '656e4567-e89b-12k3-b456-427614174000';
export const testTracker3: Tracker = {
id: testTracker2Id,
beginDate: new Date().toString(),
defaultCompletions: [
{
quantity: 0.5,
unit: 'L of water'
}
],
entries: [],
name: 'Drink',
requiredCompletions: [
Expand Down
1 change: 1 addition & 0 deletions src/utils/isATracker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ describe('isATracker helper', () => {
const basicTracker = {
id: '1234-5678',
beginDate: 'Thu Mar 17 2022 12:50:05 GMT+0100 (Central European Standard Time)',
defaultCompletions: [],
entries: [],
name: 'A basic tracker',
requiredCompletions: [],
Expand Down
1 change: 1 addition & 0 deletions src/utils/isATracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const isATracker = (tracker: any): NotATrackerResponse => {
{ key: 'id', types: ['string'] },
{ key: 'beginDate', types: ['string'] },
{ key: 'dateHidden', types: ['string', 'undefined'] },
{ key: 'defaultCompletions', types: ['array'] },
{ key: 'duration', types: ['number', 'undefined'] },
{ key: 'endDate', types: ['string', 'undefined'] },
{ key: 'entries', types: ['array'] },
Expand Down

0 comments on commit 3f94e64

Please sign in to comment.