Compare commits
1 Commits
dev
...
0055e09806
| Author | SHA1 | Date | |
|---|---|---|---|
| 0055e09806 |
@@ -1,7 +1,7 @@
|
|||||||
import { cn } from "@/utils/class-merge";
|
import { cn } from "@/utils/class-merge";
|
||||||
import { ClockIcon } from "@heroicons/react/24/outline";
|
import { ClockIcon } from "@heroicons/react/24/outline";
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { Dispatch, StateUpdater, useEffect, useState } from "preact/hooks";
|
import { Dispatch, StateUpdater, useState } from "preact/hooks";
|
||||||
import { Calendar, CalendarPassThroughMethodOptions } from "primereact/calendar";
|
import { Calendar, CalendarPassThroughMethodOptions } from "primereact/calendar";
|
||||||
import { FormEvent } from "primereact/ts-helpers";
|
import { FormEvent } from "primereact/ts-helpers";
|
||||||
import Button from "./ui/Button";
|
import Button from "./ui/Button";
|
||||||
@@ -36,13 +36,6 @@ const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({
|
|||||||
...rest
|
...rest
|
||||||
}) => {
|
}) => {
|
||||||
const [showTime, setShowTime] = useState(false);
|
const [showTime, setShowTime] = useState(false);
|
||||||
const [minDate, setMinDate] = useState(new Date());
|
|
||||||
useEffect(() => {
|
|
||||||
const interval = setInterval(() => {
|
|
||||||
setMinDate(new Date());
|
|
||||||
}, 1000);
|
|
||||||
return () => clearInterval(interval);
|
|
||||||
}, []);
|
|
||||||
return (
|
return (
|
||||||
<ModalWindow
|
<ModalWindow
|
||||||
{...rest}
|
{...rest}
|
||||||
@@ -60,7 +53,6 @@ const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({
|
|||||||
onChange={onChange}
|
onChange={onChange}
|
||||||
value={value}
|
value={value}
|
||||||
hourFormat="24"
|
hourFormat="24"
|
||||||
minDate={minDate}
|
|
||||||
showTime={showTime}
|
showTime={showTime}
|
||||||
pt={{
|
pt={{
|
||||||
root: ({ props }: CalendarPassThroughMethodOptions) => ({
|
root: ({ props }: CalendarPassThroughMethodOptions) => ({
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import ModalWindow, { ModalWindowProps } from "./ui/Modal";
|
|||||||
export interface ITags {
|
export interface ITags {
|
||||||
first: string;
|
first: string;
|
||||||
second: string;
|
second: string;
|
||||||
overdue: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ModalTagsProps extends ModalWindowProps {
|
interface ModalTagsProps extends ModalWindowProps {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
@reference "../index.scss";
|
@reference "../index.scss";
|
||||||
|
|
||||||
.task {
|
.task {
|
||||||
@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];
|
@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];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import classes from "./task.module.scss";
|
|||||||
interface TaskProps {
|
interface TaskProps {
|
||||||
name: string;
|
name: string;
|
||||||
checked?: boolean;
|
checked?: boolean;
|
||||||
overdue?: boolean;
|
|
||||||
onClick?: () => void;
|
onClick?: () => void;
|
||||||
onMarkClick?: MouseEventHandler<HTMLParagraphElement>;
|
onMarkClick?: MouseEventHandler<HTMLParagraphElement>;
|
||||||
}
|
}
|
||||||
@@ -31,13 +30,7 @@ const markStyle = tv({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const Task: FunctionComponent<TaskProps> = ({
|
const Task: FunctionComponent<TaskProps> = ({ name, checked = false, onClick = () => {}, onMarkClick = () => {} }) => {
|
||||||
name,
|
|
||||||
checked = false,
|
|
||||||
onClick = () => {},
|
|
||||||
onMarkClick = () => {},
|
|
||||||
overdue,
|
|
||||||
}) => {
|
|
||||||
return (
|
return (
|
||||||
<div class="w-[95%]">
|
<div class="w-[95%]">
|
||||||
<div class={classes.task} onClick={onClick}>
|
<div class={classes.task} onClick={onClick}>
|
||||||
@@ -51,7 +44,6 @@ const Task: FunctionComponent<TaskProps> = ({
|
|||||||
<p class={markStyle({ checked })}>✓</p>
|
<p class={markStyle({ checked })}>✓</p>
|
||||||
</div>
|
</div>
|
||||||
{name}
|
{name}
|
||||||
{overdue && <span class="absolute top-2 right-16 text-xs text-red-500">Просрочено</span>}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import Input from "@/components/ui/Input";
|
|||||||
import { withTitle } from "@/constructors/Component";
|
import { withTitle } from "@/constructors/Component";
|
||||||
import { UrlsTitle } from "@/enums/urls";
|
import { UrlsTitle } from "@/enums/urls";
|
||||||
import { useAppContext } from "@/providers/AuthProvider";
|
import { useAppContext } from "@/providers/AuthProvider";
|
||||||
|
import apiClient from "@/services/api";
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { useLocation } from "preact-iso";
|
import { useLocation } from "preact-iso";
|
||||||
import "preact/debug";
|
import "preact/debug";
|
||||||
@@ -10,10 +11,6 @@ import { Controller, SubmitHandler, useForm } from "react-hook-form";
|
|||||||
import { ILoginForm } from "./login.dto";
|
import { ILoginForm } from "./login.dto";
|
||||||
import classes from "./login.module.scss";
|
import classes from "./login.module.scss";
|
||||||
|
|
||||||
const testUser = {
|
|
||||||
login: "test",
|
|
||||||
password: "test",
|
|
||||||
};
|
|
||||||
const LoginPage: FunctionComponent = () => {
|
const LoginPage: FunctionComponent = () => {
|
||||||
const { isLoggedIn } = useAppContext();
|
const { isLoggedIn } = useAppContext();
|
||||||
const { route } = useLocation();
|
const { route } = useLocation();
|
||||||
@@ -25,15 +22,35 @@ const LoginPage: FunctionComponent = () => {
|
|||||||
mode: "onChange",
|
mode: "onChange",
|
||||||
});
|
});
|
||||||
const login: SubmitHandler<ILoginForm> = async (data) => {
|
const login: SubmitHandler<ILoginForm> = async (data) => {
|
||||||
console.log(data);
|
try {
|
||||||
if (data.login !== testUser.login || data.password !== testUser.password) {
|
const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
|
||||||
setError("login", { message: "Неверный логин или пароль" });
|
"/api/login/",
|
||||||
setError("password", { message: "Неверный логин или пароль" });
|
{
|
||||||
return;
|
method: "POST",
|
||||||
}
|
body: JSON.stringify({ username: data.login, password: data.password }),
|
||||||
|
needsCsrf: true,
|
||||||
|
},
|
||||||
|
isLoggedIn
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.success) {
|
||||||
isLoggedIn.value = true;
|
isLoggedIn.value = true;
|
||||||
localStorage.setItem("loggedIn", "true");
|
localStorage.setItem("loggedIn", "true");
|
||||||
route("/profile/tasks", true);
|
route("/profile/tasks", true);
|
||||||
|
} else {
|
||||||
|
const errorMessage = response.error || "Неверный логин или пароль";
|
||||||
|
setError("login", { message: errorMessage });
|
||||||
|
setError("password", { message: " " });
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Login failed:", error);
|
||||||
|
const errorMessage =
|
||||||
|
error.message.includes("Authentication failed") || error.message.includes("Invalid credentials")
|
||||||
|
? "Неверный логин или пароль"
|
||||||
|
: "Ошибка входа. Попробуйте позже.";
|
||||||
|
setError("login", { message: errorMessage });
|
||||||
|
setError("password", { message: " " });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
if (isLoggedIn.value) route("/profile/tasks", true);
|
if (isLoggedIn.value) route("/profile/tasks", true);
|
||||||
return !isLoggedIn.value ? (
|
return !isLoggedIn.value ? (
|
||||||
|
|||||||
@@ -6,8 +6,16 @@ import ids from "./profile.module.scss";
|
|||||||
|
|
||||||
const ProfilePage: FunctionComponent = () => {
|
const ProfilePage: FunctionComponent = () => {
|
||||||
const { route } = useLocation();
|
const { route } = useLocation();
|
||||||
const { isLoggedIn } = useAppContext();
|
const { isLoggedIn, isCheckingAuth } = useAppContext(); // Получаем новый сигнал
|
||||||
if (!isLoggedIn.value) route("/login", true);
|
|
||||||
|
if (isCheckingAuth.value) {
|
||||||
|
return <div class="flex h-screen items-center justify-center">Проверка авторизации...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isLoggedIn.value) {
|
||||||
|
route("/login", true);
|
||||||
|
return <p>Redirecting...</p>; // Заглушка на время редиректа
|
||||||
|
}
|
||||||
return isLoggedIn.value ? (
|
return isLoggedIn.value ? (
|
||||||
<div id={ids.main_container}>
|
<div id={ids.main_container}>
|
||||||
<div id={ids.router_container}>
|
<div id={ids.router_container}>
|
||||||
|
|||||||
@@ -1,25 +1,26 @@
|
|||||||
import ModalCalendar from "@/components/ModalCalendar";
|
|
||||||
import ModalTags, { ITags } from "@/components/ModalTags";
|
|
||||||
import Task from "@/components/task";
|
|
||||||
import Dialog from "@/components/ui/Dialog";
|
|
||||||
import ModalWindow from "@/components/ui/Modal";
|
|
||||||
import { withTitle } from "@/constructors/Component";
|
import { withTitle } from "@/constructors/Component";
|
||||||
import { UrlsTitle } from "@/enums/urls";
|
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 { 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 {
|
import {
|
||||||
BookOpenIcon,
|
|
||||||
CalendarDaysIcon,
|
|
||||||
DocumentDuplicateIcon,
|
|
||||||
InboxArrowDownIcon,
|
|
||||||
PencilIcon,
|
PencilIcon,
|
||||||
|
InboxArrowDownIcon,
|
||||||
|
CalendarDaysIcon,
|
||||||
|
BookOpenIcon,
|
||||||
|
DocumentDuplicateIcon,
|
||||||
TrashIcon,
|
TrashIcon,
|
||||||
} from "@heroicons/react/24/outline";
|
} from "@heroicons/react/24/outline";
|
||||||
import { FunctionComponent } from "preact";
|
import Dialog from "@/components/ui/Dialog";
|
||||||
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[] } = {
|
const example_tags: { first: string[]; second: string[] } = {
|
||||||
first: ["Программирование", "Информатика", "Физика", "Математика"],
|
first: ["Программирование", "Информатика", "Физика", "Математика"],
|
||||||
@@ -57,9 +58,10 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
const [isEditModal, setIsEditModal] = useState(false);
|
const [isEditModal, setIsEditModal] = useState(false);
|
||||||
const [editContent, setEditContent] = useState<ITask | null>(null);
|
const [editContent, setEditContent] = useState<ITask | null>(null);
|
||||||
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>();
|
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>();
|
||||||
const [tags, setTags] = useState<ITags>({ first: "", second: "", overdue: false });
|
const [tags, setTags] = useState<ITags>({ first: "", second: "" });
|
||||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||||
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
register,
|
register,
|
||||||
@@ -121,15 +123,6 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
setEditContent(newEditContent);
|
setEditContent(newEditContent);
|
||||||
}, [tags]);
|
}, [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) => {
|
const hasTasksOnDate = (date: CalendarDateTemplateEvent) => {
|
||||||
return tasks.some((task) => {
|
return tasks.some((task) => {
|
||||||
const taskDate = task.date;
|
const taskDate = task.date;
|
||||||
@@ -141,7 +134,6 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
|
|
||||||
const dateTemplate = (date: CalendarDateTemplateEvent) => {
|
const dateTemplate = (date: CalendarDateTemplateEvent) => {
|
||||||
const isHighlighted = hasTasksOnDate(date);
|
const isHighlighted = hasTasksOnDate(date);
|
||||||
const countT = tasksCount(date);
|
|
||||||
const isSelected =
|
const isSelected =
|
||||||
currentDate &&
|
currentDate &&
|
||||||
currentDate.getDate() === date.day &&
|
currentDate.getDate() === date.day &&
|
||||||
@@ -151,6 +143,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
new Date().getDate() === date.day &&
|
new Date().getDate() === date.day &&
|
||||||
new Date().getMonth() === date.month &&
|
new Date().getMonth() === date.month &&
|
||||||
new Date().getFullYear() === date.year;
|
new Date().getFullYear() === date.year;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -163,14 +156,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span>{date.day}</span>
|
<span>{date.day}</span>
|
||||||
{isHighlighted && (
|
{isHighlighted && <span className="absolute top-2 right-2 h-2 w-2 rounded-full bg-pink-400" />}
|
||||||
<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>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -206,7 +192,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
};
|
};
|
||||||
setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
||||||
localStorage.setItem("tasks", JSON.stringify(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: "", overdue: false });
|
setTags({ first: "", second: "" });
|
||||||
};
|
};
|
||||||
|
|
||||||
const pt = {
|
const pt = {
|
||||||
@@ -236,7 +222,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
tagsList={example_tags}
|
tagsList={example_tags}
|
||||||
value={tags}
|
value={tags}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setTags({ first: "", second: "", overdue: false });
|
setTags({ first: "", second: "" });
|
||||||
}}
|
}}
|
||||||
onChange={setTags}
|
onChange={setTags}
|
||||||
/>
|
/>
|
||||||
@@ -256,7 +242,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
setIsEdit(false);
|
setIsEdit(false);
|
||||||
setEditContent(null);
|
setEditContent(null);
|
||||||
setIsEditModal(false);
|
setIsEditModal(false);
|
||||||
setTags({ first: "", second: "", overdue: false });
|
setTags({ first: "", second: "" });
|
||||||
setCalendarDate(null);
|
setCalendarDate(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -359,7 +345,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
})}
|
})}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!isEditModal) return;
|
if (!isEditModal) return;
|
||||||
setTags({ first: editContent.tags[0], second: editContent.tags[1], overdue: false });
|
setTags({ first: editContent.tags[0], second: editContent.tags[1] });
|
||||||
setOpenModalTags(true);
|
setOpenModalTags(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import Button from "@/components/ui/Button";
|
|||||||
import { withTitle } from "@/constructors/Component";
|
import { withTitle } from "@/constructors/Component";
|
||||||
import { UrlsTitle } from "@/enums/urls";
|
import { UrlsTitle } from "@/enums/urls";
|
||||||
import { useAppContext } from "@/providers/AuthProvider";
|
import { useAppContext } from "@/providers/AuthProvider";
|
||||||
|
import apiClient from "@/services/api";
|
||||||
import { cn } from "@/utils/class-merge";
|
import { cn } from "@/utils/class-merge";
|
||||||
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
|
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
|
||||||
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
|
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
|
||||||
@@ -38,6 +39,18 @@ const ProfileSettings: FunctionComponent = () => {
|
|||||||
return () => window.removeEventListener("storage", handleStorage);
|
return () => window.removeEventListener("storage", handleStorage);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const handleLogout = async () => {
|
||||||
|
try {
|
||||||
|
await apiClient("/api/logout/", { method: "POST", needsCsrf: true }, isLoggedIn);
|
||||||
|
isLoggedIn.value = false;
|
||||||
|
localStorage.removeItem("loggedIn");
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
route("/login", true);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Logout failed:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class={classes.container}>
|
<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 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">
|
||||||
@@ -64,11 +77,7 @@ const ProfileSettings: FunctionComponent = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="flex flex-row items-center justify-center gap-2 bg-[linear-gradient(180.00deg,rgba(246,255,211,0.7),rgba(195,229,253,0.7)_100%)]"
|
className="flex flex-row items-center justify-center gap-2 bg-[linear-gradient(180.00deg,rgba(246,255,211,0.7),rgba(195,229,253,0.7)_100%)]"
|
||||||
onClick={() => {
|
onClick={handleLogout}
|
||||||
isLoggedIn.value = false;
|
|
||||||
localStorage.setItem("loggedIn", "false");
|
|
||||||
route("/login", true);
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
|
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ import {
|
|||||||
} from "@heroicons/react/24/outline";
|
} from "@heroicons/react/24/outline";
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
|
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
|
||||||
import { Checkbox, CheckboxPassThroughMethodOptions } from "primereact/checkbox";
|
|
||||||
import { Nullable } from "primereact/ts-helpers";
|
import { Nullable } from "primereact/ts-helpers";
|
||||||
import { SubmitHandler, useForm } from "react-hook-form";
|
import { SubmitHandler, useForm } from "react-hook-form";
|
||||||
import { v4 as uuid } from "uuid";
|
import { v4 as uuid } from "uuid";
|
||||||
@@ -47,10 +46,10 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
const [isCreating, setIsCreating] = useState(false); // Включено создание задачи
|
const [isCreating, setIsCreating] = useState(false); // Включено создание задачи
|
||||||
const [editContent, setEditContent] = useState<ITask | null>(null); // Содержимое редактируемой задачи
|
const [editContent, setEditContent] = useState<ITask | null>(null); // Содержимое редактируемой задачи
|
||||||
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>(); // Выбранная в календаре дата
|
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>(); // Выбранная в календаре дата
|
||||||
const [tags, setTags] = useState<ITags>({ first: "", second: "", overdue: false });
|
const [tags, setTags] = useState<ITags>({ first: "", second: "" });
|
||||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||||
const [searchQuery, setSearchQuery] = useState(""); // Текст поиска
|
const [searchQuery, setSearchQuery] = useState(""); // Текст поиска
|
||||||
const [filterTags, setFilterTags] = useState<ITags>({ first: "", second: "", overdue: false });
|
const [filterTags, setFilterTags] = useState<ITags>({ first: "", second: "" });
|
||||||
const [openFirstList, setOpenFirstList] = useState(false);
|
const [openFirstList, setOpenFirstList] = useState(false);
|
||||||
const [openSecondList, setOpenSecondList] = useState(false);
|
const [openSecondList, setOpenSecondList] = useState(false);
|
||||||
const getDate = useMemo(() => {
|
const getDate = useMemo(() => {
|
||||||
@@ -100,7 +99,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
if (isCreating) setTasks([...tasks, eTask]);
|
if (isCreating) setTasks([...tasks, eTask]);
|
||||||
else setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
else setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
||||||
if (isCreating) setIsOpen(false);
|
if (isCreating) setIsOpen(false);
|
||||||
setTags({ first: "", second: "", overdue: false });
|
setTags({ first: "", second: "" });
|
||||||
};
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
|
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
|
||||||
@@ -202,7 +201,6 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
filtered = filtered.filter((task) => (filterTags.overdue ? task.date < new Date() : task.date >= new Date()));
|
|
||||||
return filtered;
|
return filtered;
|
||||||
}, [tasks, searchQuery, filterTags]);
|
}, [tasks, searchQuery, filterTags]);
|
||||||
|
|
||||||
@@ -220,7 +218,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
tagsList={example_tags}
|
tagsList={example_tags}
|
||||||
value={tags}
|
value={tags}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
if (!isCreating) setTags({ first: "", second: "", overdue: false });
|
if (!isCreating) setTags({ first: "", second: "" });
|
||||||
}}
|
}}
|
||||||
onChange={setTags}
|
onChange={setTags}
|
||||||
/>
|
/>
|
||||||
@@ -243,7 +241,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
setEditContent(null);
|
setEditContent(null);
|
||||||
setIsCreating(false);
|
setIsCreating(false);
|
||||||
setIsEditModal(false);
|
setIsEditModal(false);
|
||||||
setTags({ first: "", second: "", overdue: false });
|
setTags({ first: "", second: "" });
|
||||||
setCalendarDate(null);
|
setCalendarDate(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -259,9 +257,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
<div class="flex w-full flex-row items-start justify-between">
|
<div class="flex w-full flex-row items-start justify-between">
|
||||||
<div class="flex flex-1 flex-col gap-1 pe-2">
|
<div class="flex flex-1 flex-col gap-1 pe-2">
|
||||||
<input
|
<input
|
||||||
class={cn("w-full p-2 text-2xl outline-0", {
|
class="w-full text-2xl outline-0"
|
||||||
"rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
|
|
||||||
})}
|
|
||||||
disabled={!isEditModal}
|
disabled={!isEditModal}
|
||||||
placeholder="Название"
|
placeholder="Название"
|
||||||
{...register("name", {
|
{...register("name", {
|
||||||
@@ -270,9 +266,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
})}
|
})}
|
||||||
/>
|
/>
|
||||||
<textarea
|
<textarea
|
||||||
class={cn("h-[5rem] w-full resize-none p-2 outline-0", {
|
class="h-[5rem] w-full resize-none outline-0"
|
||||||
"rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
|
|
||||||
})}
|
|
||||||
disabled={!isEditModal}
|
disabled={!isEditModal}
|
||||||
placeholder={isEditModal ? "Описание" : ""}
|
placeholder={isEditModal ? "Описание" : ""}
|
||||||
{...register("description", {
|
{...register("description", {
|
||||||
@@ -287,7 +281,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
/>
|
/>
|
||||||
<input type="checkbox" hidden {...register("checked")} />
|
<input type="checkbox" hidden {...register("checked")} />
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-4 md:flex-row">
|
<div class="flex flex-row gap-4">
|
||||||
<div
|
<div
|
||||||
className="flex cursor-pointer flex-col items-center gap-3"
|
className="flex cursor-pointer flex-col items-center gap-3"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -350,7 +344,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
})}
|
})}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!isEditModal) return;
|
if (!isEditModal) return;
|
||||||
setTags({ first: editContent.tags[0], second: editContent.tags[1], overdue: false });
|
setTags({ first: editContent.tags[0], second: editContent.tags[1] });
|
||||||
setOpenModalTags(true);
|
setOpenModalTags(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -377,13 +371,13 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
<div class="flex w-full flex-1 flex-row items-start justify-between">
|
<div class="flex w-full flex-1 flex-row items-start justify-between">
|
||||||
<div class="flex flex-1 flex-col gap-1 pe-2">
|
<div class="flex flex-1 flex-col gap-1 pe-2">
|
||||||
<input
|
<input
|
||||||
class="w-full rounded-md bg-gray-400/30 p-2 text-2xl ring-1 ring-gray-400 outline-0"
|
class="w-full text-2xl outline-0"
|
||||||
maxLength={20}
|
maxLength={20}
|
||||||
placeholder="Название"
|
placeholder="Название"
|
||||||
{...register("name", { required: "Заполните название" })}
|
{...register("name", { required: "Заполните название" })}
|
||||||
/>
|
/>
|
||||||
<textarea
|
<textarea
|
||||||
class="h-[5rem] w-full resize-none rounded-md bg-gray-400/30 p-2 ring-1 ring-gray-400 outline-0"
|
class="h-[5rem] w-full resize-none outline-0"
|
||||||
placeholder="Описание"
|
placeholder="Описание"
|
||||||
maxLength={200}
|
maxLength={200}
|
||||||
{...register("description")}
|
{...register("description")}
|
||||||
@@ -396,7 +390,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
/>
|
/>
|
||||||
<input type="checkbox" checked={false} hidden {...register("checked")} />
|
<input type="checkbox" checked={false} hidden {...register("checked")} />
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-3 self-start md:flex-row">
|
<div class="flex flex-row gap-3 self-start">
|
||||||
<CalendarDaysIcon
|
<CalendarDaysIcon
|
||||||
class="size-8 cursor-pointer"
|
class="size-8 cursor-pointer"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -435,7 +429,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
confirmText="Удалить"
|
confirmText="Удалить"
|
||||||
cancelText="Отмена"
|
cancelText="Отмена"
|
||||||
/>
|
/>
|
||||||
{!searchQuery && !filterTags.first && !filterTags.second && !filterTags.overdue ? (
|
{!searchQuery && !filterTags.first && !filterTags.second ? (
|
||||||
filteredTasks.length > 0 ? (
|
filteredTasks.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
<div class={classes.header}>
|
<div class={classes.header}>
|
||||||
@@ -473,7 +467,6 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
name={task.name}
|
name={task.name}
|
||||||
key={task.id}
|
key={task.id}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
overdue={task.date < new Date()}
|
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setIsOpen(true);
|
setIsOpen(true);
|
||||||
setIsEdit(true);
|
setIsEdit(true);
|
||||||
@@ -571,7 +564,6 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
name={task.name}
|
name={task.name}
|
||||||
key={task.id}
|
key={task.id}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
overdue={task.date < new Date()}
|
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setIsOpen(true);
|
setIsOpen(true);
|
||||||
setIsEdit(true);
|
setIsEdit(true);
|
||||||
@@ -653,46 +645,6 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
<div class="text-center text-lg font-semibold">Фильтры</div>
|
<div class="text-center text-lg font-semibold">Фильтры</div>
|
||||||
<div class="flex flex-col gap-2">
|
<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="relative">
|
||||||
<div
|
<div
|
||||||
class={cn(
|
class={cn(
|
||||||
@@ -777,11 +729,11 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(filterTags.first || filterTags.second || filterTags.overdue) && (
|
{(filterTags.first || filterTags.second) && (
|
||||||
<button
|
<button
|
||||||
class="mt-2 w-full rounded-lg bg-red-100 px-4 py-2 text-red-600 hover:bg-red-200"
|
class="mt-2 w-full rounded-lg bg-red-100 px-4 py-2 text-red-600 hover:bg-red-200"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setFilterTags({ first: "", second: "", overdue: false });
|
setFilterTags({ first: "", second: "" });
|
||||||
setOpenFirstList(false);
|
setOpenFirstList(false);
|
||||||
setOpenSecondList(false);
|
setOpenSecondList(false);
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,20 +1,75 @@
|
|||||||
import { stringToBoolean } from "@/utils/converter";
|
import apiClient from "@/services/api";
|
||||||
import { signal, Signal } from "@preact/signals";
|
import { signal, Signal } from "@preact/signals";
|
||||||
import { createContext, JSX } from "preact";
|
import { createContext, JSX } from "preact";
|
||||||
import { useContext } from "preact/hooks";
|
import { useContext, useEffect } from "preact/hooks";
|
||||||
|
|
||||||
|
interface UserData {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthStatusResponse {
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
user?: UserData;
|
||||||
|
}
|
||||||
|
|
||||||
interface AppContextValue {
|
interface AppContextValue {
|
||||||
isLoggedIn: Signal<boolean>;
|
isLoggedIn: Signal<boolean>;
|
||||||
|
isCheckingAuth: Signal<boolean>;
|
||||||
|
currentUser: Signal<UserData | null>;
|
||||||
|
checkAuth: () => Promise<void>;
|
||||||
}
|
}
|
||||||
const ininitialValue = stringToBoolean(localStorage.getItem("loggedIn"));
|
|
||||||
|
|
||||||
const AppContext = createContext<AppContextValue>({
|
const initialLoggedIn = localStorage.getItem("loggedIn") === "true";
|
||||||
isLoggedIn: signal(ininitialValue),
|
|
||||||
});
|
const AppContext = createContext<AppContextValue | null>(null);
|
||||||
|
|
||||||
const AppProvider = ({ children }: { children: JSX.Element }) => {
|
const AppProvider = ({ children }: { children: JSX.Element }) => {
|
||||||
|
const isLoggedIn = signal(initialLoggedIn);
|
||||||
|
const isCheckingAuth = signal(true);
|
||||||
|
const currentUser = signal<UserData | null>(null);
|
||||||
|
|
||||||
|
const checkAuth = async () => {
|
||||||
|
console.log("Checking auth status...");
|
||||||
|
isCheckingAuth.value = true;
|
||||||
|
try {
|
||||||
|
const response = await apiClient<AuthStatusResponse>("/api/auth/status/", {
|
||||||
|
method: "GET",
|
||||||
|
needsCsrf: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.isAuthenticated && response.user) {
|
||||||
|
console.log("User is authenticated:", response.user.username);
|
||||||
|
isLoggedIn.value = true;
|
||||||
|
currentUser.value = response.user;
|
||||||
|
localStorage.setItem("loggedIn", "true");
|
||||||
|
} else {
|
||||||
|
console.log("User is not authenticated.");
|
||||||
|
isLoggedIn.value = false;
|
||||||
|
currentUser.value = null;
|
||||||
|
localStorage.removeItem("loggedIn");
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Auth check failed:", error.message);
|
||||||
|
isLoggedIn.value = false;
|
||||||
|
currentUser.value = null;
|
||||||
|
localStorage.removeItem("loggedIn");
|
||||||
|
} finally {
|
||||||
|
isCheckingAuth.value = false;
|
||||||
|
console.log("Auth check finished. isLoggedIn:", isLoggedIn.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
checkAuth();
|
||||||
|
}, []);
|
||||||
|
|
||||||
const value: AppContextValue = {
|
const value: AppContextValue = {
|
||||||
isLoggedIn: signal(ininitialValue),
|
isLoggedIn,
|
||||||
|
isCheckingAuth,
|
||||||
|
currentUser,
|
||||||
|
checkAuth,
|
||||||
};
|
};
|
||||||
|
|
||||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||||
@@ -29,3 +84,4 @@ const useAppContext = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export { AppProvider, useAppContext };
|
export { AppProvider, useAppContext };
|
||||||
|
export type { UserData };
|
||||||
|
|||||||
99
src/services/api.ts
Normal file
99
src/services/api.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import { Signal } from "@preact/signals";
|
||||||
|
|
||||||
|
function getCookie(name: string): string | null {
|
||||||
|
let cookieValue = null;
|
||||||
|
if (document.cookie && document.cookie !== "") {
|
||||||
|
const cookies = document.cookie.split(";");
|
||||||
|
for (let i = 0; i < cookies.length; i++) {
|
||||||
|
const cookie = cookies[i].trim();
|
||||||
|
if (cookie.substring(0, name.length + 1) === name + "=") {
|
||||||
|
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cookieValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:8000";
|
||||||
|
|
||||||
|
interface RequestOptions extends RequestInit {
|
||||||
|
needsCsrf?: boolean;
|
||||||
|
isFormData?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiClient<T>(
|
||||||
|
endpoint: string,
|
||||||
|
options: RequestOptions = {},
|
||||||
|
isLoggedInSignal?: Signal<boolean>
|
||||||
|
): Promise<T> {
|
||||||
|
const url = `${API_BASE_URL}${endpoint}`;
|
||||||
|
const { needsCsrf = true, isFormData = false, ...fetchOptions } = options;
|
||||||
|
|
||||||
|
const headers: HeadersInit = {
|
||||||
|
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
||||||
|
Accept: "application/json",
|
||||||
|
...fetchOptions.headers,
|
||||||
|
};
|
||||||
|
|
||||||
|
const method = options.method?.toUpperCase() || "GET";
|
||||||
|
if (needsCsrf && ["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
|
||||||
|
const csrfToken = getCookie("csrftoken");
|
||||||
|
if (csrfToken) {
|
||||||
|
(headers as Record<string, string>)["X-CSRFToken"] = csrfToken;
|
||||||
|
} else {
|
||||||
|
console.warn("CSRF token not found in cookies.");
|
||||||
|
await fetchCsrfToken(); // Implement this function if needed
|
||||||
|
const newCsrfToken = getCookie("csrftoken");
|
||||||
|
if (newCsrfToken) {
|
||||||
|
(headers as Record<string, string>)["X-CSRFToken"] = newCsrfToken;
|
||||||
|
} else {
|
||||||
|
throw new Error("CSRF token is missing");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const config: RequestInit = {
|
||||||
|
...fetchOptions,
|
||||||
|
headers,
|
||||||
|
credentials: "include",
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, config);
|
||||||
|
|
||||||
|
if (response.status === 401 || response.status === 403) {
|
||||||
|
console.error("Authentication error:", response.status);
|
||||||
|
if (isLoggedInSignal) {
|
||||||
|
isLoggedInSignal.value = false;
|
||||||
|
localStorage.setItem("loggedIn", "false");
|
||||||
|
}
|
||||||
|
throw new Error(`Authentication failed: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json().catch(() => ({}));
|
||||||
|
console.error("API Error:", response.status, errorData);
|
||||||
|
throw new Error(`HTTP error ${response.status}: ${JSON.stringify(errorData) || response.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 204) {
|
||||||
|
return {} as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (await response.json()) as T;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Client Fetch Error:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchCsrfToken() {
|
||||||
|
try {
|
||||||
|
await apiClient("/api/get-csrf/", { method: "GET", needsCsrf: false });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch CSRF token:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default apiClient;
|
||||||
Reference in New Issue
Block a user