Compare commits

...

9 Commits

9 changed files with 464 additions and 167 deletions

View File

@@ -1,7 +1,7 @@
import { cn } from "@/utils/class-merge";
import { ClockIcon } from "@heroicons/react/24/outline";
import { FunctionComponent } from "preact";
import { Dispatch, StateUpdater, useState } from "preact/hooks";
import { Dispatch, StateUpdater, useEffect, useState } from "preact/hooks";
import { Calendar, CalendarPassThroughMethodOptions } from "primereact/calendar";
import { FormEvent } from "primereact/ts-helpers";
import Button from "./ui/Button";
@@ -36,6 +36,13 @@ const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({
...rest
}) => {
const [showTime, setShowTime] = useState(false);
const [minDate, setMinDate] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setMinDate(new Date());
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<ModalWindow
{...rest}
@@ -53,6 +60,7 @@ const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({
onChange={onChange}
value={value}
hourFormat="24"
minDate={minDate}
showTime={showTime}
pt={{
root: ({ props }: CalendarPassThroughMethodOptions) => ({

View File

@@ -8,6 +8,7 @@ import ModalWindow, { ModalWindowProps } from "./ui/Modal";
export interface ITags {
first: string;
second: string;
overdue: boolean;
}
interface ModalTagsProps extends ModalWindowProps {

View File

@@ -4,8 +4,22 @@ import { FunctionComponent, h } from "preact";
import { useLocation } from "preact-iso";
import { tv } from "tailwind-variants";
import classes from "./menu.module.scss";
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
import { useEffect, useState } from "preact/hooks";
import apiClient from "@/services/api";
import { useAppContext } from "@/providers/AuthProvider";
interface UserProfile {
username: string;
email: string;
status: string;
avatar_url: string | null;
telegram_notifications: boolean;
telegram_chat_id: string;
}
interface UserSettings {
profile: UserProfile;
}
interface MenuItemProps {
title: string;
@@ -36,32 +50,27 @@ const MenuItem: FunctionComponent<MenuItemProps> = ({ title, link, icon }: MenuI
);
};
const Avatar: FunctionComponent = () => {
const [status, setStatus] = useState("");
const [username, setUsername] = useState("");
const { route, path } = useLocation();
const { isLoggedIn } = useAppContext();
useEffect(() => {
const updateStatus = () => {
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
const points = calculatePoints(completedTasks);
setStatus(getCurrentStatus(points));
};
// Initial update
updateStatus();
// Update when tasks change
const handleStorage = (e: StorageEvent) => {
if (e.key === "tasks") {
updateStatus();
const fetchUserData = async () => {
try {
const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
setUsername(response.profile.username);
setStatus(response.profile.status);
} catch (error) {
console.error("Failed to fetch user data:", error);
}
};
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, []);
if (isLoggedIn.value) {
fetchUserData();
}
}, [isLoggedIn.value]);
return (
<button
@@ -77,7 +86,7 @@ const Avatar: FunctionComponent = () => {
>
<div class="my-5 aspect-square h-full rounded-full bg-white"></div>
<div class="flex flex-col items-center justify-center">
<p class="text-3xl font-semibold">никнейм</p>
<p class="text-3xl font-semibold">{username}</p>
<div class="rounded-[1rem] bg-white px-5 leading-5 font-light italic">{status}</div>
</div>
</div>

View File

@@ -1,5 +1,5 @@
@reference "../index.scss";
.task {
@apply flex h-24 w-full cursor-pointer flex-row items-center justify-start gap-4 rounded-[3rem] bg-[rgba(251,194,199,0.53)] px-5 py-6 text-xl shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-transform hover:scale-[1.05] hover:bg-[rgba(251,194,199,0.7)] active:scale-[1.05] md:w-[500px];
@apply relative flex h-24 w-full cursor-pointer flex-row items-center justify-start gap-4 rounded-[3rem] bg-[rgba(251,194,199,0.53)] px-5 py-6 text-xl shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-transform hover:scale-[1.05] hover:bg-[rgba(251,194,199,0.7)] active:scale-[1.05] md:w-[500px];
}

View File

@@ -6,6 +6,7 @@ import classes from "./task.module.scss";
interface TaskProps {
name: string;
checked?: boolean;
overdue?: boolean;
onClick?: () => void;
onMarkClick?: MouseEventHandler<HTMLParagraphElement>;
}
@@ -30,7 +31,13 @@ const markStyle = tv({
},
});
const Task: FunctionComponent<TaskProps> = ({ name, checked = false, onClick = () => {}, onMarkClick = () => {} }) => {
const Task: FunctionComponent<TaskProps> = ({
name,
checked = false,
onClick = () => {},
onMarkClick = () => {},
overdue,
}) => {
return (
<div class="w-[95%]">
<div class={classes.task} onClick={onClick}>
@@ -44,6 +51,7 @@ const Task: FunctionComponent<TaskProps> = ({ name, checked = false, onClick = (
<p class={markStyle({ checked })}></p>
</div>
{name}
{overdue && <span class="absolute top-2 right-16 text-xs text-red-500">Просрочено</span>}
</div>
</div>
);

View File

@@ -1,26 +1,25 @@
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { FunctionComponent } from "preact";
import { useState, useEffect } from "preact/hooks";
import { Calendar, CalendarDateTemplateEvent } from "primereact/calendar";
import { cn } from "@/utils/class-merge";
import { ITask } from "./profile_tasks.dto";
import Task from "@/components/task";
import ModalWindow from "@/components/ui/Modal";
import ModalCalendar from "@/components/ModalCalendar";
import ModalTags, { ITags } from "@/components/ModalTags";
import { useForm } from "react-hook-form";
import { ITaskForm } from "./profile_tasks.dto";
import { Nullable } from "primereact/ts-helpers";
import Task from "@/components/task";
import Dialog from "@/components/ui/Dialog";
import ModalWindow from "@/components/ui/Modal";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { cn } from "@/utils/class-merge";
import {
PencilIcon,
InboxArrowDownIcon,
CalendarDaysIcon,
BookOpenIcon,
CalendarDaysIcon,
DocumentDuplicateIcon,
InboxArrowDownIcon,
PencilIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import Dialog from "@/components/ui/Dialog";
import { FunctionComponent } from "preact";
import { useEffect, useState } from "preact/hooks";
import { Calendar, CalendarDateTemplateEvent } from "primereact/calendar";
import { Nullable } from "primereact/ts-helpers";
import { useForm } from "react-hook-form";
import { ITask, ITaskForm } from "./profile_tasks.dto";
const example_tags: { first: string[]; second: string[] } = {
first: ["Программирование", "Информатика", "Физика", "Математика"],
@@ -58,10 +57,9 @@ const ProfileCalendar: FunctionComponent = () => {
const [isEditModal, setIsEditModal] = useState(false);
const [editContent, setEditContent] = useState<ITask | null>(null);
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>();
const [tags, setTags] = useState<ITags>({ first: "", second: "" });
const [tags, setTags] = useState<ITags>({ first: "", second: "", overdue: false });
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const {
handleSubmit,
register,
@@ -123,6 +121,15 @@ const ProfileCalendar: FunctionComponent = () => {
setEditContent(newEditContent);
}, [tags]);
const tasksCount = (date: CalendarDateTemplateEvent) => {
return tasks.filter((task) => {
const taskDate = task.date;
return (
taskDate.getDate() === date.day && taskDate.getMonth() === date.month && taskDate.getFullYear() === date.year
);
}).length;
};
const hasTasksOnDate = (date: CalendarDateTemplateEvent) => {
return tasks.some((task) => {
const taskDate = task.date;
@@ -134,6 +141,7 @@ const ProfileCalendar: FunctionComponent = () => {
const dateTemplate = (date: CalendarDateTemplateEvent) => {
const isHighlighted = hasTasksOnDate(date);
const countT = tasksCount(date);
const isSelected =
currentDate &&
currentDate.getDate() === date.day &&
@@ -143,7 +151,6 @@ const ProfileCalendar: FunctionComponent = () => {
new Date().getDate() === date.day &&
new Date().getMonth() === date.month &&
new Date().getFullYear() === date.year;
return (
<div
className={cn(
@@ -156,7 +163,14 @@ const ProfileCalendar: FunctionComponent = () => {
)}
>
<span>{date.day}</span>
{isHighlighted && <span className="absolute top-2 right-2 h-2 w-2 rounded-full bg-pink-400" />}
{isHighlighted && (
<div class="absolute top-2 right-2 flex h-fit w-2 flex-col items-center gap-1 md:h-2 md:w-fit md:flex-row">
{Array.from({ length: countT > 3 ? 3 : countT }).map((_, i) => (
<span key={i} className="size-2 rounded-full bg-pink-400" />
))}
{countT > 3 && <span className="text-xs font-bold text-pink-400 select-none">+</span>}
</div>
)}
</div>
);
};
@@ -192,7 +206,7 @@ const ProfileCalendar: FunctionComponent = () => {
};
setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
localStorage.setItem("tasks", JSON.stringify(tasks.map((task) => (task.id === eTask.id ? eTask : task))));
setTags({ first: "", second: "" });
setTags({ first: "", second: "", overdue: false });
};
const pt = {
@@ -222,7 +236,7 @@ const ProfileCalendar: FunctionComponent = () => {
tagsList={example_tags}
value={tags}
onClose={() => {
setTags({ first: "", second: "" });
setTags({ first: "", second: "", overdue: false });
}}
onChange={setTags}
/>
@@ -242,7 +256,7 @@ const ProfileCalendar: FunctionComponent = () => {
setIsEdit(false);
setEditContent(null);
setIsEditModal(false);
setTags({ first: "", second: "" });
setTags({ first: "", second: "", overdue: false });
setCalendarDate(null);
}}
>
@@ -345,7 +359,7 @@ const ProfileCalendar: FunctionComponent = () => {
})}
onClick={() => {
if (!isEditModal) return;
setTags({ first: editContent.tags[0], second: editContent.tags[1] });
setTags({ first: editContent.tags[0], second: editContent.tags[1], overdue: false });
setOpenModalTags(true);
}}
>

View File

@@ -4,44 +4,56 @@ import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { cn } from "@/utils/class-merge";
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import { useEffect, useState } from "preact/hooks";
import classes from "./profile_settings.module.scss";
interface UserProfile {
username: string;
email: string;
status: string;
avatar_url: string | null;
telegram_notifications: boolean;
telegram_chat_id: string;
}
interface UserSettings {
profile: UserProfile;
}
const ProfileSettings: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const { route } = useLocation();
const [status, setStatus] = useState(0);
const [userData, setUserData] = useState<UserProfile>({
username: "",
email: "",
status: "",
avatar_url: null,
telegram_notifications: false,
telegram_chat_id: "",
});
const maxStatus = 100;
useEffect(() => {
const updateStatus = () => {
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
const points = calculatePoints(completedTasks);
setStatus(points);
};
// Initial update
updateStatus();
// Update when tasks change
const handleStorage = (e: StorageEvent) => {
if (e.key === "tasks") {
updateStatus();
const fetchUserData = async () => {
try {
const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
setUserData(response.profile);
} catch (error) {
console.error("Failed to fetch user data:", error);
}
};
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, []);
if (isLoggedIn.value) {
fetchUserData();
}
}, [isLoggedIn.value]);
const handleLogout = async () => {
try {
await apiClient("/api/logout/", { method: "POST", needsCsrf: true }, isLoggedIn);
await apiClient("/api/settings/logout/", { method: "POST", needsCsrf: true }, isLoggedIn);
isLoggedIn.value = false;
localStorage.removeItem("loggedIn");
localStorage.removeItem("user");
@@ -54,18 +66,24 @@ const ProfileSettings: FunctionComponent = () => {
return (
<div class={classes.container}>
<div class="flex w-full flex-col items-center rounded-[4rem] bg-[linear-gradient(180.00deg,rgb(251,194,199),rgba(206,232,251,0.72)_100%)] px-7 py-5 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] md:flex-row">
<div id={classes.avatar}>Аватар</div>
<div id={classes.avatar}>
{userData.avatar_url ? (
<img src={userData.avatar_url} alt="User avatar" class="h-full w-full rounded-full object-cover" />
) : (
"Аватар"
)}
</div>
<div class={classes.header_block__name}>
<p class="text-4xl font-semibold">Никнейм</p>
<p class="text-2xl font-light">{getCurrentStatus(status)}</p>
<p class="text-4xl font-semibold">{userData.username}</p>
<p class="text-2xl font-light">{userData.status}</p>
<div class="h-1.5 w-full overflow-hidden rounded-2xl bg-white">
<div
class={cn("relative top-0 left-0 h-2 bg-black")}
style={{ width: `${(status / maxStatus) * 100}%` }}
style={{ width: `${userData.telegram_chat_id ? 100 : 0}%` }}
></div>
</div>
<div class="-mt-3 self-end text-sm font-light">
{status}/{maxStatus}
{userData.telegram_chat_id ? "100" : "0"}/{maxStatus}
</div>
</div>
</div>

View File

@@ -11,3 +11,83 @@ export interface ITask {
export interface ITaskForm extends Omit<ITask, "date"> {
date: string;
}
export interface IApiTask {
id: number;
title: string;
description: string;
isCompleted: boolean;
due_date: string;
subject: string;
task_type: string;
}
export interface IApiDay {
date: string;
name: string;
tasks: IApiTask[];
}
export interface IApiResponse {
profile: string;
days: IApiDay[];
subject_choices: Record<string, string>;
task_type_choices: Record<string, string>;
}
export interface ICreateTaskResponse {
success: boolean;
message: string;
profile: string;
task: {
id: number;
title: string;
description: string;
subject: string;
taskType: string;
dateTime_due: string;
isCompleted: boolean;
reminder?: {
remind_before_days: number;
repeat_interval: number;
reminder_time: string;
};
};
}
export interface ITaskDetails {
profile: string;
title: string;
description: string;
subject: string;
taskType: string;
dateTime_due: string;
remind_before_days: number;
repeat_reminder: number;
reminder_time: string;
}
export interface IDeleteTaskResponse {
success: boolean;
message: string;
}
export interface IEditTaskResponse {
success: boolean;
message: string;
profile: string;
task: {
id: number;
title: string;
description: string;
subject: string;
taskType: string;
dateTime_due: string;
isCompleted: boolean;
reminder?: {
remind_before_days: number;
repeat_interval: number;
reminder_time: string;
};
};
}

View File

@@ -24,16 +24,21 @@ import {
} from "@heroicons/react/24/outline";
import { FunctionComponent } from "preact";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Checkbox, CheckboxPassThroughMethodOptions } from "primereact/checkbox";
import { Nullable } from "primereact/ts-helpers";
import { SubmitHandler, useForm } from "react-hook-form";
import { v4 as uuid } from "uuid";
import { ITask, ITaskForm } from "./profile_tasks.dto";
import {
ITask,
ITaskForm,
IApiResponse,
ICreateTaskResponse,
ITaskDetails,
IDeleteTaskResponse,
IEditTaskResponse,
} from "./profile_tasks.dto";
import classes from "./profile_tasks.module.scss";
const example_tags: { first: string[]; second: string[] } = {
first: ["Программирование", "Информатика", "Физика", "Математика"],
second: ["Лабораторная работа", "Практическая работа", "Домашнее задание", "Экзамен"],
};
import apiClient from "@/services/api";
const ProfileTasks: FunctionComponent = () => {
const [openModal, setIsOpen] = useState(false); // Открыта модалка
@@ -46,10 +51,10 @@ const ProfileTasks: FunctionComponent = () => {
const [isCreating, setIsCreating] = useState(false); // Включено создание задачи
const [editContent, setEditContent] = useState<ITask | null>(null); // Содержимое редактируемой задачи
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>(); // Выбранная в календаре дата
const [tags, setTags] = useState<ITags>({ first: "", second: "" });
const [tags, setTags] = useState<ITags>({ first: "", second: "", overdue: false });
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [searchQuery, setSearchQuery] = useState(""); // Текст поиска
const [filterTags, setFilterTags] = useState<ITags>({ first: "", second: "" });
const [filterTags, setFilterTags] = useState<ITags>({ first: "", second: "", overdue: false });
const [openFirstList, setOpenFirstList] = useState(false);
const [openSecondList, setOpenSecondList] = useState(false);
const getDate = useMemo(() => {
@@ -57,17 +62,42 @@ const ProfileTasks: FunctionComponent = () => {
const formatter = new Intl.DateTimeFormat("ru-RU", { month: "long", day: "numeric" });
return formatter.format(date);
}, []);
const init_tasks: ITask[] = localStorage.getItem("tasks") ? JSON.parse(localStorage.getItem("tasks") as string) : [];
let clear = false;
init_tasks.forEach((task) => {
clear = clear || (task.new == undefined ? true : false);
if (!clear) task.new = true;
task.date = new Date(task.date);
});
const [tasks, setTasks] = useState<ITask[]>(clear ? [] : init_tasks);
const [tasks, setTasks] = useState<ITask[]>([]);
const [subjectChoices, setSubjectChoices] = useState<Record<string, string>>({});
const [taskTypeChoices, setTaskTypeChoices] = useState<Record<string, string>>({});
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
fetchTasks();
}, []);
const fetchTasks = async () => {
try {
setIsLoading(true);
const response = await apiClient<IApiResponse>("/api/tasks/view_tasks/");
setSubjectChoices(response.subject_choices);
setTaskTypeChoices(response.task_type_choices);
const convertedTasks: ITask[] = response.days.flatMap((day) =>
day.tasks.map((apiTask) => ({
id: apiTask.id.toString(),
name: apiTask.title,
checked: apiTask.isCompleted,
date: new Date(apiTask.due_date),
description: apiTask.description,
tags: [apiTask.subject, apiTask.task_type],
new: false,
}))
);
setTasks(convertedTasks);
} catch (error) {
console.error("Failed to fetch tasks:", error);
} finally {
setIsLoading(false);
}
};
const {
handleSubmit,
@@ -80,27 +110,81 @@ const ProfileTasks: FunctionComponent = () => {
tags: [],
},
});
const saveTask: SubmitHandler<ITaskForm> = (data) => {
const example_tags = useMemo(
() => ({
first: Object.keys(subjectChoices),
second: Object.keys(taskTypeChoices),
}),
[subjectChoices, taskTypeChoices]
);
const saveTask: SubmitHandler<ITaskForm> = async (data) => {
if (!calendarDate) {
setError("date", { message: "Выберите дату" });
return;
}
console.log(tags);
if ((!editContent?.tags[0] || !editContent.tags[1]) && (!tags.first || !tags.second)) {
setError("tags", { message: "Выберите теги" });
return;
}
const eTask: ITask = {
...data,
date: calendarDate,
tags: editContent?.tags.length ? editContent.tags : [tags.first, tags.second],
new: true,
};
if (isCreating) setTasks([...tasks, eTask]);
else setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
if (isCreating) setIsOpen(false);
setTags({ first: "", second: "" });
try {
const selectedSubject = editContent?.tags[0] || tags.first;
const selectedTaskType = editContent?.tags[1] || tags.second;
// Format date to DD-MM-YYYYTHH:MM
const formattedDate = calendarDate
.toLocaleString("en-GB", {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
})
.replace(",", "T")
.replace(/\//g, "-")
.replace("T ", "T");
const taskData = {
title: data.name,
description: data.description || "",
subject: selectedSubject,
taskType: selectedTaskType,
dateTime_due: formattedDate,
telegram_notifications: false,
};
if (isCreating) {
const response = await apiClient<ICreateTaskResponse>("/api/tasks/create_task/", {
method: "POST",
body: JSON.stringify(taskData),
});
if (!response.success) {
throw new Error(response.message);
}
} else {
const response = await apiClient<IEditTaskResponse>(`/api/tasks/edit_task/${editContent?.id}/`, {
method: "PUT",
body: JSON.stringify(taskData),
});
if (!response.success) {
throw new Error(response.message);
}
}
await fetchTasks();
if (isCreating) setIsOpen(false);
setTags({ first: "", second: "", overdue: false });
} catch (error) {
console.error("Failed to save task:", error);
}
};
useEffect(() => {
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
else reset();
@@ -173,17 +257,43 @@ const ProfileTasks: FunctionComponent = () => {
}).format(date);
};
const handleDeleteTask = () => {
const handleDeleteTask = async () => {
if (!editContent) return;
setTasks(tasks.filter((task) => task.id !== editContent.id));
setIsOpen(false);
setShowDeleteDialog(false);
try {
const response = await apiClient<IDeleteTaskResponse>(`/api/tasks/delete_task/${editContent.id}/`, {
method: "DELETE",
});
if (!response.success) {
throw new Error(response.message);
}
await fetchTasks();
setIsOpen(false);
setShowDeleteDialog(false);
} catch (error) {
console.error("Failed to delete task:", error);
}
};
const handleMarkTask = async (taskId: string, isCompleted: boolean) => {
try {
await apiClient(`/api/update_task/${taskId}/`, {
method: "PATCH",
body: JSON.stringify({ isCompleted }),
});
await fetchTasks();
} catch (error) {
console.error("Failed to mark task:", error);
}
};
const filteredTasks = useMemo(() => {
let filtered = tasks;
// Фильтрация по поиску
if (searchQuery) {
filtered = filtered.filter(
(task) =>
@@ -192,7 +302,6 @@ const ProfileTasks: FunctionComponent = () => {
);
}
// Фильтрация по тегам
if (filterTags.first || filterTags.second) {
filtered = filtered.filter(
(task) =>
@@ -201,6 +310,7 @@ const ProfileTasks: FunctionComponent = () => {
);
}
filtered = filtered.filter((task) => (filterTags.overdue ? task.date < new Date() : task.date >= new Date()));
return filtered;
}, [tasks, searchQuery, filterTags]);
@@ -209,19 +319,50 @@ const ProfileTasks: FunctionComponent = () => {
useEffect(() => {
if (searchInputRef.current && openSearchModal) searchInputRef.current.focus();
}, [searchInputRef, openSearchModal]);
const handleViewTask = async (taskId: string) => {
try {
const taskDetails = await apiClient<ITaskDetails>(`/api/tasks/view_task/${taskId}/`);
const task: ITask = {
id: taskId,
name: taskDetails.title,
checked: false,
date: new Date(taskDetails.dateTime_due),
description: taskDetails.description,
tags: [taskDetails.subject, taskDetails.taskType],
new: false,
};
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
setIsEditModal(false);
} catch (error) {
console.error("Failed to fetch task details:", error);
}
};
return (
<div class={classes.container}>
<ModalTags
zIndex={70}
isOpen={openModalTags}
setIsOpen={setOpenModalTags}
tagsList={example_tags}
value={tags}
onClose={() => {
if (!isCreating) setTags({ first: "", second: "" });
}}
onChange={setTags}
/>
{isLoading ? (
<div class="flex w-full flex-1 items-center justify-center">
<div class="text-2xl">Загрузка...</div>
</div>
) : (
<ModalTags
zIndex={70}
isOpen={openModalTags}
setIsOpen={setOpenModalTags}
tagsList={example_tags}
value={tags}
onClose={() => {
if (!isCreating) setTags({ first: "", second: "", overdue: false });
}}
onChange={setTags}
/>
)}
<ModalCalendar
zIndex={80}
isOpen={openModalCalendar}
@@ -241,7 +382,7 @@ const ProfileTasks: FunctionComponent = () => {
setEditContent(null);
setIsCreating(false);
setIsEditModal(false);
setTags({ first: "", second: "" });
setTags({ first: "", second: "", overdue: false });
setCalendarDate(null);
}}
>
@@ -257,7 +398,9 @@ const ProfileTasks: FunctionComponent = () => {
<div class="flex w-full flex-row items-start justify-between">
<div class="flex flex-1 flex-col gap-1 pe-2">
<input
class="w-full text-2xl outline-0"
class={cn("w-full p-2 text-2xl outline-0", {
"rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
})}
disabled={!isEditModal}
placeholder="Название"
{...register("name", {
@@ -266,7 +409,9 @@ const ProfileTasks: FunctionComponent = () => {
})}
/>
<textarea
class="h-[5rem] w-full resize-none outline-0"
class={cn("h-[5rem] w-full resize-none p-2 outline-0", {
"rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
})}
disabled={!isEditModal}
placeholder={isEditModal ? "Описание" : ""}
{...register("description", {
@@ -281,7 +426,7 @@ const ProfileTasks: FunctionComponent = () => {
/>
<input type="checkbox" hidden {...register("checked")} />
</div>
<div class="flex flex-row gap-4">
<div class="flex flex-col gap-4 md:flex-row">
<div
className="flex cursor-pointer flex-col items-center gap-3"
onClick={() => {
@@ -344,7 +489,7 @@ const ProfileTasks: FunctionComponent = () => {
})}
onClick={() => {
if (!isEditModal) return;
setTags({ first: editContent.tags[0], second: editContent.tags[1] });
setTags({ first: editContent.tags[0], second: editContent.tags[1], overdue: false });
setOpenModalTags(true);
}}
>
@@ -371,13 +516,13 @@ const ProfileTasks: FunctionComponent = () => {
<div class="flex w-full flex-1 flex-row items-start justify-between">
<div class="flex flex-1 flex-col gap-1 pe-2">
<input
class="w-full text-2xl outline-0"
class="w-full rounded-md bg-gray-400/30 p-2 text-2xl ring-1 ring-gray-400 outline-0"
maxLength={20}
placeholder="Название"
{...register("name", { required: "Заполните название" })}
/>
<textarea
class="h-[5rem] w-full resize-none outline-0"
class="h-[5rem] w-full resize-none rounded-md bg-gray-400/30 p-2 ring-1 ring-gray-400 outline-0"
placeholder="Описание"
maxLength={200}
{...register("description")}
@@ -390,7 +535,7 @@ const ProfileTasks: FunctionComponent = () => {
/>
<input type="checkbox" checked={false} hidden {...register("checked")} />
</div>
<div class="flex flex-row gap-3 self-start">
<div class="flex flex-col gap-3 self-start md:flex-row">
<CalendarDaysIcon
class="size-8 cursor-pointer"
onClick={() => {
@@ -429,7 +574,7 @@ const ProfileTasks: FunctionComponent = () => {
confirmText="Удалить"
cancelText="Отмена"
/>
{!searchQuery && !filterTags.first && !filterTags.second ? (
{!searchQuery && !filterTags.first && !filterTags.second && !filterTags.overdue ? (
filteredTasks.length > 0 ? (
<>
<div class={classes.header}>
@@ -467,15 +612,9 @@ const ProfileTasks: FunctionComponent = () => {
name={task.name}
key={task.id}
checked={task.checked}
onClick={() => {
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
}}
onMarkClick={() => {
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
}}
overdue={task.date < new Date()}
onClick={() => handleViewTask(task.id)}
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
/>
))}
</div>
@@ -490,15 +629,8 @@ const ProfileTasks: FunctionComponent = () => {
name={task.name}
key={task.id}
checked={task.checked}
onClick={() => {
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
}}
onMarkClick={() => {
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
}}
onClick={() => handleViewTask(task.id)}
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
/>
))}
</div>
@@ -511,15 +643,8 @@ const ProfileTasks: FunctionComponent = () => {
name={task.name}
key={task.id}
checked={task.checked}
onClick={() => {
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
}}
onMarkClick={() => {
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
}}
onClick={() => handleViewTask(task.id)}
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
/>
))}
</div>
@@ -564,15 +689,9 @@ const ProfileTasks: FunctionComponent = () => {
name={task.name}
key={task.id}
checked={task.checked}
onClick={() => {
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
}}
onMarkClick={() => {
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
}}
overdue={task.date < new Date()}
onClick={() => handleViewTask(task.id)}
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
/>
))
) : (
@@ -645,6 +764,46 @@ const ProfileTasks: FunctionComponent = () => {
<div class="flex flex-col gap-4">
<div class="text-center text-lg font-semibold">Фильтры</div>
<div class="flex flex-col gap-2">
<div class="flex flex-row gap-2">
<Checkbox
name="overdue"
checked={filterTags.overdue}
onChange={(e) => {
setFilterTags({ ...filterTags, overdue: e.target.checked! });
}}
pt={{
root: {
className: cn("cursor-pointer inline-flex relative select-none align-bottom", "w-6 h-6"),
},
input: {
className: cn(
"absolute appearance-none top-0 left-0 size-full p-0 m-0 opacity-0 z-10 outline-none cursor-pointer"
),
},
box: ({ props, context }: CheckboxPassThroughMethodOptions) => ({
className: cn(
"flex items-center justify-center",
"border-2 w-6 h-6 text-gray-600 rounded-lg transition-colors duration-200",
{
"border-gray-300 bg-white": !context.checked,
"border-blue-500 bg-blue-500": context.checked,
},
{
"hover:border-blue-500 focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(191,219,254,1)]":
!props.disabled,
"cursor-default opacity-60": props.disabled,
}
),
}),
icon: {
className: "w-4 h-4 transition-all duration-200 text-white text-base",
},
}}
></Checkbox>
<label htmlFor="overdue" class="cursor-pointer">
Просроченные
</label>
</div>
<div class="relative">
<div
class={cn(
@@ -729,11 +888,11 @@ const ProfileTasks: FunctionComponent = () => {
)}
</div>
{(filterTags.first || filterTags.second) && (
{(filterTags.first || filterTags.second || filterTags.overdue) && (
<button
class="mt-2 w-full rounded-lg bg-red-100 px-4 py-2 text-red-600 hover:bg-red-200"
onClick={() => {
setFilterTags({ first: "", second: "" });
setFilterTags({ first: "", second: "", overdue: false });
setOpenFirstList(false);
setOpenSecondList(false);
}}