Commit 0b83e0ac authored by Ermolaev Timur's avatar Ermolaev Timur

Merge branch 'task-112-enhance/refactoring_and_optimize_code' into 'development'

Task 112 enhance/refactoring and optimize code

See merge request !90
parents 732725e6 6e0eadad
......@@ -71,15 +71,6 @@ const App = () => {
</ProtectedRoute>
} />
<Route path={"/week/:id"} element={
<ProtectedRoute
isAllowed={user}
redirectUrl={"/sign-in"}
>
<WeekCalendar />
</ProtectedRoute>
} />
<Route path={"/month"} element={
<ProtectedRoute
isAllowed={user}
......@@ -89,15 +80,6 @@ const App = () => {
</ProtectedRoute>
} />
<Route path={"/month/:id"} element={
<ProtectedRoute
isAllowed={user}
redirectUrl={"/sign-in"}
>
<MonthCalendar></MonthCalendar>
</ProtectedRoute>
} />
<Route path={"/my-tasks"} element={
<ProtectedRoute
isAllowed={user}
......
......@@ -2,26 +2,11 @@ import { Button, TextField } from "@mui/material";
import { memo } from "react";
import { priorities } from "../../../constants";
import CustomSelect from '../../UI/СustomSelect/СustomSelect'
import { isValidate } from "./Helpers";
function CalendarModalTaskContent({ title, onChangeCurrentTaskHandler, description, priority, sendNewTaskHandler, deleteTaskHandler, startHour, endHour, id }) {
const isValidate = () => {
if (title) {
const startHourInt = parseInt(startHour)
const endHourInt = parseInt(endHour)
if (startHourInt >= 8 && startHourInt <= 24) {
if (endHourInt >= 8 && endHourInt <= 24) {
if (startHourInt < endHourInt) {
return true
}
}
} else {
return false
}
}
}
return (<>
<TextField
id="task-description-title"
......@@ -72,7 +57,7 @@ function CalendarModalTaskContent({ title, onChangeCurrentTaskHandler, descripti
/>
</div>
<div style={{ display: 'flex', gap: '20px', margin: '10px 0' }}>
<Button id='test_button_save_task' onClick={sendNewTaskHandler} disabled={!isValidate()}>Сохранить</Button>
<Button id='test_button_save_task' onClick={sendNewTaskHandler} disabled={!isValidate(title, startHour, endHour)}>Сохранить</Button>
<Button onClick={deleteTaskHandler} disabled={!id}>Удалить</Button>
</div>
</>);
......
export const isValidate = (title, startHour, endHour) => {
if (title) {
const startHourInt = parseInt(startHour)
const endHourInt = parseInt(endHour)
if (startHourInt >= 8 && startHourInt <= 24) {
if (endHourInt >= 8 && endHourInt <= 24) {
if (startHourInt < endHourInt) {
return true
}
}
} else {
return false
}
}
}
\ No newline at end of file
import { Autocomplete, Button, TextField } from "@mui/material";
import { memo } from "react";
import CustomAutocomplete from "../../UI/CustomAutocomplete/CustomAutocomplete";
function CalendarModalWorkerContent({ allUserProjects, onChangeProjectHandler, onChangeWorkerHandler, workerInfo, workers, handleClose, onChangeCalendarUser}) {
function CalendarModalWorkerContent({ allUserProjects, onChangeProjectHandler, onChangeWorkerHandler, workerInfo, workers, handleClose, onChangeCalendarUser }) {
return (<>
<Autocomplete
id="choose-project"
freeSolo
<CustomAutocomplete
name={'project'}
label={'Проекты'}
options={allUserProjects}
getOptionLabel={(item) => item.title || ""}
onChange={onChangeProjectHandler}
name={"project"}
value={workerInfo.project}
renderInput={(params) => <TextField
style={{ marginBottom: "15px" }}
label={"Проект"}
state={workerInfo.project}
{...params} />}
getOptionLabel={(item) => item.title || ""}
style={{ marginBottom: '15px' }}
/>
{workerInfo.project ?
<>
<Autocomplete
id="choose-worker"
freeSolo
<CustomAutocomplete
name={'worker'}
label={'Участник'}
options={workers}
getOptionLabel={(item) => item?.user?.displayName || ""}
onChange={(e, value) => { onChangeWorkerHandler(e, value) }}
name={"worker"}
onChange={onChangeWorkerHandler}
value={workerInfo.worker}
renderInput={(params) => <TextField
label={"Участник"}
state={workerInfo.worker}
{...params} />}
getOptionLabel={(item) => item?.user?.displayName || ""}
style={{ marginBottom: '15px' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', margin: '10px 0' }}>
<Button onClick={()=>{onChangeCalendarUser()}} >Выбрать</Button>
<Button onClick={() => { onChangeCalendarUser() }} >Выбрать</Button>
<Button onClick={() => handleClose()}>Отмена</Button>
</div>
</>
......
import { FormControlLabel, Switch } from "@mui/material";
import { memo } from "react";
const HourFormatSwitch = ({ hourFormat, setHourFormat }) => {
return (<>
<FormControlLabel
control={<Switch color="primary" checked={hourFormat} onChange={() => { setHourFormat(() => !hourFormat) }} />}
label="1 час"
labelPlacement="end"
/>
</>)
};
export default memo(HourFormatSwitch);
\ No newline at end of file
import { Box, FormControlLabel, Switch } from "@mui/material";
import { useState } from "react";
import { useCallback, useState } from "react";
import CalendarRow from "../../CalendarRow/CalendarRow";
import CalendarSmallCell from "../../CalendarSmallCell/CalendarSmallCell";
import CalendarStandartCell from "../../CalendarStandartCell/CalendarStandartCell";
......@@ -12,7 +12,7 @@ function MonthCalendarBody({ month, year, tasks, createTaskInCellHandler, curren
const [currentLine, setCurrentLine] = useState('')
const [modal, setModal] = useState({ open: false, y: 0, x: 0, });
const handleOpen = (e) => {
const handleOpen = useCallback((e) => {
setModal({
open: true,
yClickСordinates: e.clientY,
......@@ -22,12 +22,12 @@ function MonthCalendarBody({ month, year, tasks, createTaskInCellHandler, curren
yDiv: e.target.offsetHeight,
xDiv: e.target.offsetWidth,
})
};
},[])
const handleClose = () => {
const handleClose = useCallback(() => {
setModal({ ...modal, open: false })
setCurrentTask({})
};
}, [modal, setCurrentTask])
return (
<Box style={{ marginBottom: '30px' }}>
......
......@@ -4,17 +4,19 @@ import CalendarStandartCell from "../../../CalendarStandartCell/CalendarStandart
import { useEffect, useRef, useState } from "react";
import { Grid } from "@mui/material";
import CalendarWeekTask from "./CalendarWeekTask/CalendarWeekTask";
import { getTasksWithInfoForPosition, getWidthLeftZIndex } from "./Helpers";
function CalendarColumnDayWeek({ hoursInDay, tasks, month, year, day, hourFormat, handleOpen, setCurrentTask, copyTask, createCopyTask, createTaskInCellHandler, modal }) {
const [columnDayHeight, setColumnDayHeight] = useState(0)
const [columnDaySize, setColumnDaySize] = useState({ width: 0, height: 0 })
const dayColumnRef = useRef('')
useEffect(() => {
setColumnDayHeight(prev => dayColumnRef.current.offsetHeight)
setColumnDaySize(prev => { return { height: dayColumnRef.current.offsetHeight, width: dayColumnRef.current.offsetWidth } })
}, [hourFormat])
const hours = useMemo(() => {
return getHoursInDayNumbers(hoursInDay)
}, [hoursInDay])
......@@ -23,6 +25,7 @@ function CalendarColumnDayWeek({ hoursInDay, tasks, month, year, day, hourFormat
return getAvailableTasks(tasks, year, month, day)
}, [tasks, month, year, day])
const sortedTasks = useMemo(() => {
return getSortedTasks(availableTasks)
}, [availableTasks])
......@@ -32,68 +35,17 @@ function CalendarColumnDayWeek({ hoursInDay, tasks, month, year, day, hourFormat
return getLinesInDay(availableTasks, sortedTasks, hoursInDay, hours, hourFormat)
}, [availableTasks, hourFormat, hours, hoursInDay, sortedTasks])
const getBoxesInLine = (line, hoursInDay, sortedTasks, linesInDay) => {
if (line) {
const boxes = []
for (let i = 0; i < line.length; i++) {
if (!isNaN(line[i])) {
} else {
const task = sortedTasks[line[i].split('-')[1]]
const taskIsThere = boxes.find((taskFind) => {
if (taskFind?.task?.id === task.id) return taskFind
return false
})
const step = columnDayHeight / hours.length
if (taskIsThere) {
taskIsThere.lastHour = i
taskIsThere.height += step
let tasksInHour = 0
for (let line of linesInDay) {
if (isNaN(line[i])) {
tasksInHour++
}
}
if (tasksInHour > taskIsThere.tasksInHour) {
taskIsThere.tasksInHour = tasksInHour
}
} else {
let tasksInHour = 0
for (let line of linesInDay) {
if (isNaN(line[i])) {
tasksInHour++
}
}
boxes.push({
tasksInHour: tasksInHour,
top: step * i,
height: step,
firstHour: i,
lastHour: i,
task: sortedTasks[line[i].split('-')[1]]
})
}
}
}
return boxes
}
}
return (<>
<Grid item xs={12 / 7} ref={dayColumnRef} sx={{ position: 'relative' }}>
{linesInDay?.map((line, i) => {
const boxes = getBoxesInLine(line, hoursInDay, sortedTasks, linesInDay)
const boxes = getTasksWithInfoForPosition(line, sortedTasks, linesInDay, columnDaySize.height, hours)
return (<>
{boxes.map((task, index) => {
const amount = task.tasksInHour
const oneTaskPrecentWidth = 100 / amount
const left = oneTaskPrecentWidth * dayColumnRef.current.offsetWidth / 100 * i
const zIndex = 10 + i
const oneTaskWidth = dayColumnRef.current.offsetWidth - (oneTaskPrecentWidth * dayColumnRef.current.offsetWidth / 100) * i
{boxes.map((task) => {
const { width, left, zIndex } = getWidthLeftZIndex(task, columnDaySize.width, i)
return (
<CalendarWeekTask
key={index}
width={oneTaskWidth}
key={task.task.id}
width={width}
height={task.height}
left={left}
task={task.task}
......@@ -103,10 +55,7 @@ function CalendarColumnDayWeek({ hoursInDay, tasks, month, year, day, hourFormat
setCurrentTask={setCurrentTask}
modal={modal}
>
</CalendarWeekTask>
)
})}
</>)
......
import { Box } from "@mui/material"
import { useEffect, useState } from "react"
import { useEffect, useState, memo, useCallback, useMemo } from "react"
import { getColorTaskByPriority } from "../../../../../../helpers/CalendarHelpers"
function CalendarWeekTask({ height, width, left, top, task, zIndex, handleOpen, setCurrentTask, modal}) {
function CalendarWeekTask({ height, width, left, top, task, zIndex, handleOpen, setCurrentTask, modal }) {
const [zIndexStyle, setZIndexStyle] = useState(10)
const [color, setColor] = useState('')
useEffect(() => {
if (task.priority) {
if (task.priority === 'A') setColor('rgb(32, 138, 250)')
if (task.priority === 'B') setColor('lightgreen')
if (task.priority === 'C') setColor('yellow')
} else {
setColor('rgb(171, 157, 157);')
}
setZIndexStyle(zIndex)
}, [task])
const color = useMemo(() => {
return getColorTaskByPriority(task.priority)
}, [task.priority])
useEffect(() => {
if (!modal) {
setZIndexStyle(zIndex)
}
}, [modal])
}, [modal, zIndex])
const onClickTaskHandler = (e, task) => {
const onClickTaskHandler = useCallback((e, task) => {
e.stopPropagation();
setCurrentTask((prevState) => {
return {
......@@ -35,7 +28,7 @@ function CalendarWeekTask({ height, width, left, top, task, zIndex, handleOpen,
});
setZIndexStyle(100)
handleOpen(e)
}
}, [handleOpen, setCurrentTask])
const styles = {
boxSizing: 'border-box',
......@@ -59,12 +52,12 @@ function CalendarWeekTask({ height, width, left, top, task, zIndex, handleOpen,
return (
<Box
onClick={(e)=>{onClickTaskHandler(e, task)}}
onClick={(e) => { onClickTaskHandler(e, task) }}
sx={styles}>
<span style={{textOverflow: 'ellipsis', padding: '5px 0 0 5px'}}>
{task.title}
</span>
<span style={{ textOverflow: 'ellipsis', padding: '5px 0 0 5px' }}>
{task.title}
</span>
</Box>);
}
export default CalendarWeekTask;
\ No newline at end of file
export default memo(CalendarWeekTask);
\ No newline at end of file
export const getTasksWithInfoForPosition = (line, sortedTasks, linesInDay, columnDayHeight, hours) => {
if (line) {
const boxes = []
for (let i = 0; i < line.length; i++) {
if (!isNaN(line[i])) {
} else {
const task = sortedTasks[line[i].split('-')[1]]
const taskIsThere = boxes.find((taskFind) => {
if (taskFind?.task?.id === task.id) return taskFind
return false
})
const step = columnDayHeight / hours.length
if (taskIsThere) {
taskIsThere.height += step
let tasksInHour = 0
for (let line of linesInDay) {
if (isNaN(line[i])) {
tasksInHour++
}
}
if (tasksInHour > taskIsThere.tasksInHour) {
taskIsThere.tasksInHour = tasksInHour
}
} else {
let tasksInHour = 0
for (let line of linesInDay) {
if (isNaN(line[i])) {
tasksInHour++
}
}
boxes.push({
tasksInHour: tasksInHour,
top: step * i,
height: step,
task: sortedTasks[line[i].split('-')[1]]
})
}
}
}
return boxes
}
}
export const getWidthLeftZIndex = (task, dayColumnWidth, i) => {
const amount = task.tasksInHour
const oneTaskPrecentWidth = 100 / amount
const left = oneTaskPrecentWidth * dayColumnWidth / 100 * i
const zIndex = 10 + i
const oneTaskWidth = dayColumnWidth - (oneTaskPrecentWidth * dayColumnWidth / 100) * i
return { width: oneTaskWidth, left: left, zIndex: zIndex }
}
\ No newline at end of file
......@@ -4,4 +4,19 @@ export const getCurrentWeekDayString = (dayNumber) => {
} else {
return null
}
}
export const getMonthToDayColumn = (week, weekDay, month) => {
if (week[0] > week[6]) {
if (weekDay < week[0]) {
if (month === 11) {
return 0
}
return month + 1
} else {
return month
}
} else {
return month
}
}
\ No newline at end of file
import { FormControlLabel, Grid, Switch } from "@mui/material";
import { Grid } from "@mui/material";
import { Box } from "@mui/system";
import { useState } from "react";
import { useCallback, useState } from "react";
import ModalTask from "../../../UI/ModalTask/ModalTask";
import MonthCalendarModalContent from "../../CalendarModalTaskContent/CalendarModalTaskContent";
import CalendarRow from "../../CalendarRow/CalendarRow";
import CalendarSmallCell from "../../CalendarSmallCell/CalendarSmallCell";
import CalendarStandartCell from "../../CalendarStandartCell/CalendarStandartCell";
import HourFormatSwitch from "../../HourFormatSwitch/HourFormatSwitch";
import CalendarColumnDayWeek from "./CalendarColumnDayWeek/CalendarColumnDayWeek";
import { getCurrentWeekDayString } from "./Helpers";
import { getCurrentWeekDayString, getMonthToDayColumn } from "./Helpers";
function WeekCalendarBody({ week, hoursInDay, hourFormat, setHourFormat, date, tasks, currentTask, setCurrentTask, onChangeCurrentTaskHandler, deleteTaskHandler, sendNewTaskHandler, createTaskInCellHandler }) {
const [modal, setModal] = useState({ open: false, y: 0, x: 0, });
const handleOpen = (e) => {
const handleOpen = useCallback((e) => {
setModal({
open: true,
yClickСordinates: e.clientY,
......@@ -21,12 +22,12 @@ function WeekCalendarBody({ week, hoursInDay, hourFormat, setHourFormat, date, t
yDiv: e.target.offsetHeight,
xDiv: e.target.offsetWidth,
})
};
}, []);
const handleClose = () => {
const handleClose = useCallback(() => {
setModal({ ...modal, open: false })
setCurrentTask({})
};
}, [setCurrentTask, modal]);
return (
<>
......@@ -35,10 +36,9 @@ function WeekCalendarBody({ week, hoursInDay, hourFormat, setHourFormat, date, t
<CalendarRow
>
<CalendarSmallCell xs={1}>
<FormControlLabel
control={<Switch color="primary" checked={hourFormat} onChange={() => { setHourFormat(() => !hourFormat) }} />}
label="1 час"
labelPlacement="end"
<HourFormatSwitch
hourFormat={hourFormat}
setHourFormat={setHourFormat}
/>
</CalendarSmallCell>
{week?.map((weekDay, i) => {
......@@ -71,7 +71,7 @@ function WeekCalendarBody({ week, hoursInDay, hourFormat, setHourFormat, date, t
key={i}
hoursInDay={hoursInDay}
tasks={tasks}
month={date.month}
month={getMonthToDayColumn(week, weekDay, date.month)}
year={date.year}
day={weekDay}
hourFormat={hourFormat}
......
import { AppBar, Toolbar } from '@mui/material';
import { Box } from '@mui/system';
import { memo } from 'react';
import WeekCalendarHeaderInfo from './WeekCalendarHeaderInfo/WeekCalendarHeaderInfo';
......@@ -26,4 +27,4 @@ function WeekCalendarHeader({ decrementWeek, incrementWeek, weekInfo }) {
);
}
export default WeekCalendarHeader;
\ No newline at end of file
export default memo(WeekCalendarHeader);
\ No newline at end of file
......@@ -2,6 +2,7 @@ import ArrowDecrementButton from '../../../../UI/ArrowDecrementButton/ArrowDecre
import ArrowIncrementButton from '../../../../UI/ArrowIncrementButton/ArrowIncrementButton';
import { Box } from '@mui/system';
import { Typography } from '@mui/material';
import { memo } from 'react';
......@@ -34,4 +35,4 @@ function WeekCalendarHeaderInfo({ decrementWeek, incrementWeek, weekInfo }) {
);
}
export default WeekCalendarHeaderInfo;
\ No newline at end of file
export default memo(WeekCalendarHeaderInfo);
\ No newline at end of file
import { Autocomplete, TextField } from "@mui/material";
import { memo } from "react";
function CustomAutocomplete({ options, onChange, value, name, label, style, getOptionLabel }) {
return (<>
<Autocomplete
id={name}
freeSolo
options={options}
getOptionLabel={getOptionLabel}
onChange={(e, value) => { onChange(e, value) }}
name={name}
value={value}
renderInput={(params) => <TextField
style={style}
label={label}
state={value}
{...params} />}
/>
</>);
}
export default memo(CustomAutocomplete);
\ No newline at end of file
import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useState } from 'react';
export default function ModalTask({modal, handleClose, children}) {
......
export const getCurrentWeekDayString = (dayNumber) => {
if (dayNumber <= 6 && dayNumber >= 0) {
return ["ПН","ВТ","СР","ЧТ","ПТ","СБ","ВС"][dayNumber];
} else {
return null
}
}
\ No newline at end of file
import { FormControlLabel, Grid, Switch } from "@mui/material";
import { Box } from "@mui/system";
import CalendarRow from "../../MonthCalendar/MonthCalendarBody/CalendarRow/CalendarRow";
import CalendarSmallCell from "../../MonthCalendar/MonthCalendarBody/CalendarSmallCell/CalendarSmallCell";
import CalendarStandartCell from "../../MonthCalendar/MonthCalendarBody/CalendarStandartCell.js/CalendarStandartCell";
import { getCurrentWeekDayString } from "./Helpers";
function WeekCalendarBody({week, hoursInDay, hourFormat, setHourFormat}) {
return (
<>
<Box style={{marginBottom: '30px'}}>
<Box style={{position: 'sticky', top: '0px', zIndex: '10', backgroundColor: 'lightgrey'}}>
<CalendarRow
>
<CalendarSmallCell xs={1}>
<FormControlLabel
control={<Switch color="primary" checked={hourFormat} onChange={()=>{setHourFormat(()=>!hourFormat)}}/>}
label="1 час"
labelPlacement="end"
/>
</CalendarSmallCell>
{week?.map((weekDay, i)=>{
return (
<CalendarStandartCell key={i} xs={11/week.length}>
<span style={{display: 'block', fontWeight: "600"}}>{weekDay}</span>
<span style={{marginBottom: '10px'}}>{getCurrentWeekDayString(i)}</span>
</CalendarStandartCell>
)
})}
</CalendarRow>
</Box>
<Grid container>
<CalendarRow week={true}>
<Grid item xs={0.995} flexDirection='column'>
{hoursInDay?.map((hour, i)=>{
return (
<CalendarSmallCell key={i} week={true}>
{hour}
</CalendarSmallCell>)
})}
</Grid>
<Grid item xs={11.005}>
<CalendarRow week={true}>
{week?.map((weekDay, i)=>{
return (
<Grid item key={i} xs={12/week.length}>
{hoursInDay?.map((hour, i)=>{
return (
<CalendarStandartCell key={i} week={true}>
</CalendarStandartCell>)
})}
</Grid>)
})}
</CalendarRow>
</Grid>
</CalendarRow>
</Grid>
</Box>
</>
);
}
export default WeekCalendarBody;
\ No newline at end of file
import { AppBar, Toolbar} from '@mui/material';
import { Box } from '@mui/system';
import WeekCalendarHeaderInfo from './WeekCalendarHeaderInfo/WeekCalendarHeaderInfo';
function WeekCalendarHeader({decrementWeek, incrementWeek, weekInfo}) {
return (
<>
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<WeekCalendarHeaderInfo
decrementWeek={decrementWeek}
incrementWeek={incrementWeek}
weekInfo={weekInfo}
/>
</Toolbar>
</AppBar>
</Box>
</>
);
}
export default WeekCalendarHeader;
\ No newline at end of file
import ArrowDecrementButton from '../../../UI/ArrowDecrementButton/ArrowDecrementButton';
import ArrowIncrementButton from '../../../UI/ArrowIncrementButton/ArrowIncrementButton';
import { Box } from '@mui/system';
import {Typography} from '@mui/material';
function WeekCalendarHeaderInfo({decrementWeek, incrementWeek, weekInfo}) {
return (
<>
<Box sx={{width: '40%', marginBottom: '15px'}}>
<h2>Цель недели: Наладить режим сна</h2>
<Box sx={{display: 'flex', alignItems: 'center'}}>
<ArrowDecrementButton
onClick={()=>{decrementWeek()}}
/>
<Typography
variant="h6"
sx={{
flexBasis: '250px',
display: 'flex',
justifyContent: 'center',
}}
>
{weekInfo}
</Typography>
<ArrowIncrementButton
onClick={()=>{incrementWeek()}}
/>
</Box>
</Box>
</>
);
}
export default WeekCalendarHeaderInfo;
\ No newline at end of file
import { useEffect, useCallback, useState, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import CalendarModalWorkerContent from '../../components/Calendars/CalendarModalWorkerContent/CalendarModalWorkerContent';
import MonthCalendarBody from '../../components/Calendars/MonthCalendar/MonthCalendarBody/MonthCalendarBody';
import MonthCalendarHeader from '../../components/Calendars/MonthCalendar/MonthCalendarHeader/MonthCalendarHeader';
......@@ -12,11 +12,10 @@ import { fetchCurrentCalendarDisplayName } from '../../store/actions/usersAction
function MonthCalendar() {
const dispatch = useDispatch();
const navigate = useNavigate()
const { calendarTasks } = useSelector(state => state.tasks);
const { user, currentCalendarDisplayName } = useSelector(state => state.users);
const { allUserProjects, project } = useSelector(state => state.projects)
const params = useParams()
const [hourFormat, setHourFormat] = useState(false);
const [dateNow, setDateNow] = useState({ month: '', year: '' })
......@@ -25,6 +24,7 @@ function MonthCalendar() {
const [copyTask, setCopyTask] = useState(null)
const [cellSizes, setCellSizes] = useState({})
const [userId, setUserId] = useState('')
const [userCalendarId, setUserCalendarId] = useState(null)
const [modal, setModal] = useState(false)
useEffect(() => {
......@@ -32,22 +32,25 @@ function MonthCalendar() {
month: new Date().getMonth(),
year: new Date().getFullYear(),
})
if (params.id) {
setUserId(params.id)
dispatch(fetchCalendarTasks(params.id))
dispatch(fetchCurrentCalendarDisplayName(params.id))
}, [dispatch])
useEffect(() => {
if (userCalendarId) {
setUserId(userCalendarId)
dispatch(fetchCalendarTasks(userCalendarId))
dispatch(fetchCurrentCalendarDisplayName(userCalendarId))
} else {
setUserId(user.id)
dispatch(fetchCalendarTasks(user.id))
dispatch(fetchCurrentCalendarDisplayName(user.id))
}
}, [dispatch])
}, [userCalendarId, dispatch, user.id])
useEffect(() => {
if (workerInfo.project) {
dispatch(fetchProject(workerInfo.project.id))
}
}, [workerInfo.project])
}, [workerInfo.project, dispatch])
const hoursInDay = useMemo(() => {
let arr
......@@ -120,7 +123,7 @@ function MonthCalendar() {
}
}, []);
const createTaskInCellHandler = (dayNumber, dayHour) => {
const createTaskInCellHandler = useCallback((dayNumber, dayHour) => {
let hour
if (!isNaN(dayHour)) {
hour = dayHour
......@@ -146,9 +149,9 @@ function MonthCalendar() {
}
}
setCurrentTask((newTask))
}
}, [dateNow.month, dateNow.year, hourFormat])
const dragTaskHandler = async (dayNumber, hour) => {
const dragTaskHandler = useCallback(async (dayNumber, hour) => {
const hourDiff = currentTask.infoForCell.endHour - currentTask.infoForCell.startHour
const lastHour = hoursInDay[hoursInDay.length - 1].split(':')[0]
let due
......@@ -168,9 +171,9 @@ function MonthCalendar() {
delete newTask.infoForCell
await dispatch(editCalendarTask(newTask, currentTask.id, userId))
setCurrentTask({})
}
}, [currentTask, dateNow.month, dateNow.year, dispatch, hoursInDay, userId])
const sendNewTaskHandler = async () => {
const sendNewTaskHandler = useCallback(async () => {
const timeEndHour = currentTask.infoForCell.endHour
const timeStartHour = currentTask.infoForCell.startHour
const day = currentTask.infoForCell.startDay
......@@ -198,9 +201,9 @@ function MonthCalendar() {
delete newTask.id
await dispatch(addCalendarTask(newTask, userId))
}
}
}, [currentTask, dateNow.month, dateNow.year, dispatch, user.id, userId])
const createCopyTask = async (dayNumber, hour) => {
const createCopyTask = useCallback(async (dayNumber, hour) => {
const hourDiff = copyTask.infoForCell.endHour - copyTask.infoForCell.startHour
const lastHour = hoursInDay[hoursInDay.length - 1].split(':')[0]
let due
......@@ -220,35 +223,31 @@ function MonthCalendar() {
delete newTask.id
await dispatch(addCopyCalendarTask(newTask, userId))
setCopyTask(null)
}
}, [copyTask, dateNow.month, dateNow.year, dispatch, hoursInDay, userId])
const deleteTaskHandler = async (taskId) => {
const deleteTaskHandler = useCallback(async (taskId) => {
dispatch(deleteCalendarTask(taskId, userId))
}
}, [dispatch, userId])
const handleClose = () => {
const handleClose = useCallback(() => {
setModal(false)
setWorkerInfo({ project: '', worker: '' })
}
const handleOpen = async () => {
}, [])
const handleOpen = useCallback(async () => {
if (user.id === userId) {
await dispatch(fetchAllUserProjects())
setModal(true)
} else {
navigate("/month")
setWorkerInfo({ project: '', worker: '' })
setUserId(user.id)
dispatch(fetchCalendarTasks(user.id))
dispatch(fetchCurrentCalendarDisplayName(user.id))
dispatch(setUserCalendarId(null))
}
}
const onChangeCalendarUser = () => {
navigate(`/month/${workerInfo.worker.user.id}`)
}, [dispatch, user.id, userId])
const onChangeCalendarUser = useCallback(() => {
setModal(false)
setUserId(workerInfo.worker.user.id)
dispatch(fetchCalendarTasks(workerInfo.worker.user.id))
dispatch(fetchCurrentCalendarDisplayName(workerInfo.worker.user.id))
}
dispatch(setUserCalendarId(workerInfo.worker.user.id))
setWorkerInfo({ project: '', worker: '' })
}, [dispatch, workerInfo?.worker?.user?.id])
return (
<>
......
......@@ -44,7 +44,7 @@ export default function EnhancedTable() {
if (tasks && tasks?.length > 0) {
setRecievedTasks(tasks);
}
}, [dispatch, tasks?.length]);
}, [dispatch, tasks]);
useEffect(() => {
dispatch(fetchAllTasks());
......
......@@ -2,7 +2,7 @@ import moment from 'moment';
import { useEffect, useState, useMemo, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import WeekCalendarBody from '../../components/Calendars/WeekCalendar/WeekCalendarBody/WeekCalendarBody';
import WeekCalendarHeader from '../../components/Calendars/WeekCalendar/WeekCalendarHeader/WeekCalendarHeader'
import WeekCalendarHeader from '../../components/Calendars/WeekCalendar/WeekCalendarHeader/WeekCalendarHeader';
import { getWeekInfoString, getWeekFromCurrentDate, dateToISOLikeButLocal } from '../../helpers/CalendarHelpers';
import { addCalendarTask, deleteCalendarTask, editCalendarTask, fetchCalendarTasks } from '../../store/actions/tasksActions';
......@@ -23,7 +23,7 @@ function WeekCalendar() {
setDateNow({ year: year, month: month, currentDay: currentDay })
dispatch(fetchCalendarTasks(user.id))
setUserId(user.id)
}, [])
}, [dispatch, user.id])
const hoursInDay = useMemo(() => {
let arr
......@@ -49,14 +49,12 @@ function WeekCalendar() {
return { year: newDate.getFullYear(), month: newDate.getMonth(), currentDay: moment(newDate).date() }
})
}, [])
const decrementWeek = useCallback(() => {
setDateNow((prevState) => {
const newDate = new Date(prevState.year, prevState.month, prevState.currentDay - 7)
return { year: newDate.getFullYear(), month: newDate.getMonth(), currentDay: moment(newDate).date() }
})
}, [])
const onChangeCurrentTaskHandler = useCallback((e) => {
const { name, value } = e.target;
if (name === 'startHour' || name === 'endHour') {
......@@ -79,7 +77,7 @@ function WeekCalendar() {
}
}, []);
const createTaskInCellHandler = (dayNumber, dayHour) => {
const createTaskInCellHandler = useCallback((dayNumber, dayHour) => {
let hour
if (!isNaN(dayHour)) {
hour = dayHour
......@@ -105,9 +103,9 @@ function WeekCalendar() {
}
}
setCurrentTask((newTask))
}
},[dateNow.month, dateNow.year, hourFormat])
const sendNewTaskHandler = async () => {
const sendNewTaskHandler = useCallback(async () => {
const timeEndHour = currentTask.infoForCell.endHour
const timeStartHour = currentTask.infoForCell.startHour
const day = currentTask.infoForCell.startDay
......@@ -135,11 +133,11 @@ function WeekCalendar() {
delete newTask.id
await dispatch(addCalendarTask(newTask, userId))
}
}
}, [currentTask, dateNow.month, dateNow.year, dispatch, user.id, userId])
const deleteTaskHandler = async (taskId) => {
const deleteTaskHandler = useCallback(async (taskId) => {
dispatch(deleteCalendarTask(taskId, userId))
}
},[dispatch, userId])
return (
<>
......
......@@ -183,4 +183,17 @@ export const getAvailableTasks = (tasks, year, month, dayNumber) => {
} else {return false}
})
return tasksInDay
}
export const getColorTaskByPriority = (priority) => {
switch(priority) {
case 'A':
return 'rgb(32, 138, 250)';
case 'B':
return 'lightgreen';
case 'C':
return 'orange';
default:
return 'rgb(171, 157, 157)';
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment