36 Commits

Author SHA1 Message Date
f6b19767f2 feat: calendar circle colors 2025-05-15 16:36:15 +03:00
049e6dd912 feat: fixed tags 2025-05-12 19:50:02 +03:00
c72ce9baa4 feat: avatars 2025-05-12 16:16:26 +03:00
ac1b7338f8 feat: nice isLoading view 2025-05-12 15:59:16 +03:00
ae1e0ad0c0 feat: priority select in calendar 2025-05-12 15:39:50 +03:00
2d2d5699a3 feat: tg bot link 2025-05-12 02:36:20 +03:00
d0cb13a7f1 fix: removed console logs 2025-05-12 01:51:34 +03:00
4ad7a00535 feat: small text fix 2025-05-12 01:46:34 +03:00
19ce2bf278 feat: tag delete 2025-05-12 01:43:10 +03:00
95a264f5a4 feat: creating tasks 2025-05-12 01:04:33 +03:00
dca682ac1e feat: tasks priorities 2025-05-12 00:02:22 +03:00
d61b1ccffe feat: added if empty pic 2025-05-12 00:00:54 +03:00
32984642e5 feat: new tag system 2025-05-11 22:53:52 +03:00
3addff881b fix: overdue filter 2025-05-10 15:38:37 +03:00
f7870e5e00 feat: overdue 2025-05-10 15:27:58 +03:00
b5c67c6173 feat: profile settings 2025-05-10 14:20:10 +03:00
e342da34c0 feat: register page 2025-05-10 14:19:41 +03:00
cc7307a655 feat: get tasks from api in calendar 2025-05-09 15:37:05 +03:00
cb9e1bd266 feat: mark task change 2025-05-07 11:57:35 +03:00
1f289e8545 feat: CRUD tasks 2025-05-07 11:24:08 +03:00
ce694f0be8 feat: show tasks and creating them 2025-05-07 11:14:17 +03:00
852ac9ad0d feat: real login and logout 2025-05-07 10:42:23 +03:00
9ab2a1cb08 feat: input colors and some improvements 2025-05-07 10:26:57 +03:00
19a6d435b2 hotfix: icon classname in checkbox 2025-05-07 10:26:57 +03:00
5b5082df38 feat: fix styles in filters 2025-05-07 10:26:57 +03:00
2c11c3b21a feat: overdue tasks 2025-05-07 10:26:57 +03:00
f510c8c415 feat: cannot set previous dates 2025-05-07 10:26:57 +03:00
a2c1fd16c9 feat: calendar markers on task count 2025-05-07 10:26:57 +03:00
0055e09806 feat: api client and natural login and logoff 2025-05-05 16:53:18 +03:00
db73f498f6 feat: style improvements 2025-05-05 15:15:25 +03:00
be7a58b93f upd: tailwind package 2025-05-05 15:15:16 +03:00
4db7276166 feat: removed btn, added icons and gradient in settings 2025-05-05 14:24:43 +03:00
ae9eef1131 fix: mobile icons in create modal 2025-05-05 14:24:23 +03:00
0b068f7232 feat: close search on x 2025-05-05 11:48:34 +03:00
5ece8ca7eb feat: search and filter 2025-04-30 16:03:05 +03:00
23c0f43526 feat: removed trash 2025-04-30 14:54:15 +03:00
35 changed files with 2168 additions and 1198 deletions

3
.gitignore vendored
View File

@@ -23,3 +23,6 @@ dist-ssr
*.njsproj
*.sln
*.sw?
# My
repomix-output.*

View File

@@ -8,5 +8,7 @@
"([\"'`][^\"'`]*.*?[\"'`])",
"[\"'`]([^\"'`]*).*?[\"'`]"
]
]
],
"editor.formatOnSave": true,
"editor.tabSize": 2
}

View File

@@ -18,7 +18,7 @@
"react-hook-form": "^7.56.1",
"tailwind-merge": "^3.0.2",
"tailwind-variants": "^1.0.0",
"tailwindcss": "^4.0.17",
"tailwindcss": "^4.1.5",
"uuid": "^11.1.0",
},
"devDependencies": {
@@ -713,7 +713,7 @@
"tailwind-variants": ["tailwind-variants@1.0.0", "", { "dependencies": { "tailwind-merge": "3.0.2" }, "peerDependencies": { "tailwindcss": "*" } }, "sha512-2WSbv4ulEEyuBKomOunut65D8UZwxrHoRfYnxGcQNnHqlSCp2+B7Yz2W+yrNDrxRodOXtGD/1oCcKGNBnUqMqA=="],
"tailwindcss": ["tailwindcss@4.0.17", "", {}, "sha512-OErSiGzRa6rLiOvaipsDZvLMSpsBZ4ysB4f0VKGXUrjw2jfkJRd6kjRKV2+ZmTCNvwtvgdDam5D7w6WXsdLJZw=="],
"tailwindcss": ["tailwindcss@4.1.5", "", {}, "sha512-nYtSPfWGDiWgCkwQG/m+aX83XCwf62sBgg3bIlNiiOcggnS1x3uVRDAuyelBFL+vJdOPPCGElxv9DjHJjRHiVA=="],
"tapable": ["tapable@2.2.1", "", {}, "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ=="],
@@ -767,6 +767,12 @@
"@humanfs/node/@humanwhocodes/retry": ["@humanwhocodes/retry@0.3.1", "", {}, "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA=="],
"@tailwindcss/node/tailwindcss": ["tailwindcss@4.0.17", "", {}, "sha512-OErSiGzRa6rLiOvaipsDZvLMSpsBZ4ysB4f0VKGXUrjw2jfkJRd6kjRKV2+ZmTCNvwtvgdDam5D7w6WXsdLJZw=="],
"@tailwindcss/postcss/tailwindcss": ["tailwindcss@4.0.17", "", {}, "sha512-OErSiGzRa6rLiOvaipsDZvLMSpsBZ4ysB4f0VKGXUrjw2jfkJRd6kjRKV2+ZmTCNvwtvgdDam5D7w6WXsdLJZw=="],
"@tailwindcss/vite/tailwindcss": ["tailwindcss@4.0.17", "", {}, "sha512-OErSiGzRa6rLiOvaipsDZvLMSpsBZ4ysB4f0VKGXUrjw2jfkJRd6kjRKV2+ZmTCNvwtvgdDam5D7w6WXsdLJZw=="],
"@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
"@typescript-eslint/typescript-estree/semver": ["semver@7.7.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA=="],

View File

@@ -2,7 +2,7 @@
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Антихвост</title>
</head>

View File

@@ -23,7 +23,7 @@
"react-hook-form": "^7.56.1",
"tailwind-merge": "^3.0.2",
"tailwind-variants": "^1.0.0",
"tailwindcss": "^4.0.17",
"tailwindcss": "^4.1.5",
"uuid": "^11.1.0"
},
"devDependencies": {

View File

@@ -1,678 +0,0 @@
This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: bun.lock, node_modules/, .vscode/
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
<additional_info>
</additional_info>
</file_summary>
<directory_structure>
public/
vite.svg
src/
assets/
preact.svg
components/
ui/
Button.module.scss
Button.tsx
Input.module.scss
Input.tsx
layout.tsx
menu.module.scss
menu.tsx
pages/
login.module.scss
login.tsx
profile.module.scss
profile.tsx
providers/
AuthProvider.tsx
utils/
class-merge.ts
app.module.scss
app.tsx
index.scss
main.tsx
vite-env.d.ts
.gitattributes
.gitignore
.prettierrc
eslint.config.mjs
index.html
package.json
postcss.config.mts
tsconfig.app.json
tsconfig.json
tsconfig.node.json
vite.config.ts
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path="src/providers/AuthProvider.tsx">
import { signal, Signal } from "@preact/signals";
import { createContext, JSX } from "preact";
import { useContext } from "preact/hooks";
interface AppContextValue {
isLoggedIn: Signal<boolean>;
}
const AppContext = createContext<AppContextValue>({
isLoggedIn: signal(false),
});
const AppProvider = ({ children }: { children: JSX.Element }) => {
const value: AppContextValue = {
isLoggedIn: signal(false),
};
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};
const useAppContext = () => {
const context = useContext(AppContext);
if (!context) {
throw new Error("useAppContext must be used within AppProvider");
}
return context;
};
export { AppProvider, useAppContext };
</file>
<file path="public/vite.svg">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
</file>
<file path="src/assets/preact.svg">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="27.68" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 296"><path fill="#673AB8" d="m128 0l128 73.9v147.8l-128 73.9L0 221.7V73.9z"></path><path fill="#FFF" d="M34.865 220.478c17.016 21.78 71.095 5.185 122.15-34.704c51.055-39.888 80.24-88.345 63.224-110.126c-17.017-21.78-71.095-5.184-122.15 34.704c-51.055 39.89-80.24 88.346-63.224 110.126Zm7.27-5.68c-5.644-7.222-3.178-21.402 7.573-39.253c11.322-18.797 30.541-39.548 54.06-57.923c23.52-18.375 48.303-32.004 69.281-38.442c19.922-6.113 34.277-5.075 39.92 2.148c5.644 7.223 3.178 21.403-7.573 39.254c-11.322 18.797-30.541 39.547-54.06 57.923c-23.52 18.375-48.304 32.004-69.281 38.441c-19.922 6.114-34.277 5.076-39.92-2.147Z"></path><path fill="#FFF" d="M220.239 220.478c17.017-21.78-12.169-70.237-63.224-110.126C105.96 70.464 51.88 53.868 34.865 75.648c-17.017 21.78 12.169 70.238 63.224 110.126c51.055 39.889 105.133 56.485 122.15 34.704Zm-7.27-5.68c-5.643 7.224-19.998 8.262-39.92 2.148c-20.978-6.437-45.761-20.066-69.28-38.441c-23.52-18.376-42.74-39.126-54.06-57.923c-10.752-17.851-13.218-32.03-7.575-39.254c5.644-7.223 19.999-8.261 39.92-2.148c20.978 6.438 45.762 20.067 69.281 38.442c23.52 18.375 42.739 39.126 54.06 57.923c10.752 17.85 13.218 32.03 7.574 39.254Z"></path><path fill="#FFF" d="M127.552 167.667c10.827 0 19.603-8.777 19.603-19.604c0-10.826-8.776-19.603-19.603-19.603c-10.827 0-19.604 8.777-19.604 19.603c0 10.827 8.777 19.604 19.604 19.604Z"></path></svg>
</file>
<file path="src/components/layout.tsx">
import { useAppContext } from "@/providers/AuthProvider";
import { FunctionComponent } from "preact";
import { Route, Router, useLocation } from "preact-iso";
import { useEffect } from "preact/hooks";
import Menu from "./menu";
const Layout: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const location = useLocation();
useEffect(() => {
console.log(isLoggedIn.value);
}, [isLoggedIn]);
return (
<div class="flex min-w-screen flex-row justify-between">
<div class="w-full overflow-x-auto">
<Router>
<Route
path="/"
component={() => {
// location.route("/settings");
return <h1>Home</h1>;
}}
/>
<Route path="/settings" component={() => <h1>Test</h1>} />
<Route path="/tasks" component={() => <h1>Test2</h1>} />
<Route default component={() => <h1>404</h1>} />
</Router>
</div>
<Menu />
</div>
);
};
export default Layout;
</file>
<file path="src/pages/profile.module.scss">
@reference "../index.scss";
</file>
<file path="src/pages/profile.tsx">
import Layout from "@/components/layout";
import { FunctionComponent } from "preact";
const ProfilePage: FunctionComponent = () => {
return <Layout />;
};
export default ProfilePage;
</file>
<file path="src/utils/class-merge.ts">
import { ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(...inputs));
}
</file>
<file path="src/app.module.scss">
@reference "./index.scss";
.text {
@apply text-9xl text-red-500;
}
</file>
<file path="src/main.tsx">
import { render } from "preact";
import { App } from "./app.tsx";
import "./index.scss";
render(<App />, document.getElementById("app")!);
</file>
<file path="src/vite-env.d.ts">
/// <reference types="vite/client" />
</file>
<file path=".gitattributes">
* text=auto
bun.lock binary
</file>
<file path=".gitignore">
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
</file>
<file path="eslint.config.mjs">
// @ts-check
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config({
extends: [eslint.configs.recommended, tseslint.configs.recommended],
ignores: ["*.d.ts"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
parserOptions: { ecmaFeatures: { jsx: true } },
},
settings: {
env: {
browser: true,
es6: true,
},
},
});
</file>
<file path="postcss.config.mts">
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};
</file>
<file path="tsconfig.app.json">
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"paths": {
"react": [
"./node_modules/preact/compat/"
],
"react-dom": [
"./node_modules/preact/compat/"
],
"@/*": [
"./src/*"
]
},
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"jsxImportSource": "preact",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": [
"src"
]
}
</file>
<file path="tsconfig.json">
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
</file>
<file path="tsconfig.node.json">
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
</file>
<file path="vite.config.ts">
import preact from '@preact/preset-vite';
import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite';
import tsConfigPaths from 'vite-tsconfig-paths';
// https://vite.dev/config/
export default defineConfig({
plugins: [preact(), tailwindcss(), tsConfigPaths()],
});
</file>
<file path="src/components/ui/Button.module.scss">
@reference '../../index.scss';
.button {
@apply rounded-2xl border-2 py-3 font-semibold text-white transition-colors hover:cursor-pointer;
}
</file>
<file path="src/components/ui/Button.tsx">
import { FunctionComponent } from "preact";
import { tv } from "tailwind-variants";
import classes from "./Button.module.scss";
const button = tv({
base: classes.button,
variants: {
color: {
primary: "bg-blue-400 hover:bg-blue-500",
secondary: "bg-red-400 hover:bg-red-500",
},
},
});
const Button: FunctionComponent<{ onClick: () => void }> = (props) => {
return (
<button type="button" class={button({ color: "primary" })} onClick={props.onClick}>
{props.children}
</button>
);
};
export default Button;
</file>
<file path="src/components/ui/Input.tsx">
import { FunctionComponent } from "preact";
import { tv } from "tailwind-variants";
import classes from "./Input.module.scss";
const input = tv({
base: classes.input_field,
variants: {
"text-align": {
center: "text-center",
left: "text-left",
},
},
defaultVariants: {
"text-align": "left",
},
});
interface InputProps {
isPassword?: boolean;
placeholder?: string;
textAlign?: "center" | "left";
}
const Input: FunctionComponent<InputProps> = ({ isPassword = false, placeholder = "", textAlign }: InputProps) => {
return (
<input
type={isPassword ? "password" : "text"}
class={input({ "text-align": textAlign })}
placeholder={placeholder}
/>
);
};
export default Input;
</file>
<file path="src/components/menu.module.scss">
@reference "../index.scss";
.menu_container {
@apply flex min-h-8 min-w-screen flex-col items-center gap-4 border-l border-l-gray-500 px-5 pt-5 md:min-h-screen md:min-w-[300px];
}
.menu_item {
@apply w-full cursor-pointer rounded-md px-6 py-2 text-center hover:bg-gray-200;
}
</file>
<file path="src/components/menu.tsx">
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import { tv } from "tailwind-variants";
import classes from "./menu.module.scss";
interface MenuItemProps {
title: string;
link: string;
}
const MenuItem: FunctionComponent<MenuItemProps> = ({ title, link }: MenuItemProps) => {
const location = useLocation();
const active = location.path === link;
const menuItemClasses = tv({
base: classes.menu_item,
variants: {
activity: {
active: "bg-gray-200",
inactive: "bg-gray-100",
},
},
defaultVariants: {
activity: "inactive",
},
});
return (
<div class={menuItemClasses({ activity: active ? "active" : "inactive" })} onClick={() => location.route(link)}>
{title}
</div>
);
};
interface MenuItems {
title: string;
link: string;
}
const Menu: FunctionComponent = () => {
const menu_items: MenuItems[] = [
{
title: "Профиль",
link: "/profile",
},
{
title: "Задачи",
link: "/tasks",
},
{
title: "Календарь",
link: "/calendar",
},
];
return (
<div class={classes.menu_container}>
{menu_items.map(({ title, link }) => (
<MenuItem title={title} link={link} />
))}
</div>
);
};
export default Menu;
</file>
<file path="src/pages/login.module.scss">
@reference "../index.scss";
.login_container {
@apply flex min-h-screen flex-col items-center justify-center;
}
.login_card {
@apply flex w-[95%] min-w-[300px] flex-col justify-center gap-2 rounded-md border-gray-400 p-5 shadow-md md:w-[350px];
}
</file>
<file path="src/pages/login.tsx">
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { useAppContext } from "@/providers/AuthProvider";
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import classes from "./login.module.scss";
const LoginPage: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const location = useLocation();
return (
<div class={classes.login_container}>
<div class={classes.login_card}>
<Input placeholder="Login" textAlign="center" />
<Input isPassword placeholder="Password" textAlign="center" />
<Button
onClick={() => {
isLoggedIn.value = true;
location.route("/profile/settings");
}}
>
Login
</Button>
</div>
</div>
);
};
export default LoginPage;
</file>
<file path="src/index.scss">
@import "tailwindcss";
@import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap");
:root {
font-family: "Montserrat", sans-serif;
}
</file>
<file path="index.html">
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Антихвост</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
</file>
<file path="src/components/ui/Input.module.scss">
@reference "../../index.scss";
.input_field {
@apply rounded-md border border-gray-300 p-2 placeholder:transition focus:outline-0 focus:placeholder:opacity-25;
}
</file>
<file path="src/app.tsx">
import { FunctionComponent } from "preact";
import { ErrorBoundary, lazy, LocationProvider, Route, Router, useLocation } from "preact-iso";
import "preact/debug";
import LoginPage from "./pages/login";
import { AppProvider } from "./providers/AuthProvider";
const HomePage: FunctionComponent = () => {
const location = useLocation();
location.route("/login");
return <div>Redirecting to login...</div>;
};
export function App() {
return (
<AppProvider>
<LocationProvider>
<ErrorBoundary>
<Router>
<Route path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/profile/*" component={lazy(() => import("./pages/profile"))} />
</Router>
</ErrorBoundary>
</LocationProvider>
</AppProvider>
);
}
</file>
<file path=".prettierrc">
{
"tabWidth": 2,
"printWidth": 120,
"arrowParens": "always",
"singleQuote": false,
"trailingComma": "es5",
"useTabs": false,
"semi": true,
"bracketSpacing": true,
"plugins": ["prettier-plugin-tailwindcss"],
"tailwindFunctions": ["tv"]
}
</file>
<file path="package.json">
{
"name": "anti-hvost",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@preact/signals": "^2.0.2",
"@tailwindcss/postcss": "^4.0.17",
"@tailwindcss/vite": "^4.0.17",
"clsx": "^2.1.1",
"postcss": "^8.5.3",
"preact": "^10.26.2",
"preact-iso": "^2.9.1",
"tailwind-merge": "^3.0.2",
"tailwind-variants": "^1.0.0",
"tailwindcss": "^4.0.17"
},
"devDependencies": {
"@eslint/js": "^9.23.0",
"@preact/preset-vite": "^2.10.1",
"@typescript-eslint/parser": "^8.28.0",
"eslint": "^9.23.0",
"eslint-config-prettier": "^10.1.1",
"prettier": "^3.5.3",
"prettier-eslint": "^16.3.0",
"prettier-plugin-tailwindcss": "^0.6.11",
"sass-embedded": "^1.86.0",
"typescript": "~5.7.2",
"typescript-eslint": "^8.28.0",
"vite": "^6.2.0",
"vite-tsconfig-paths": "^5.1.4"
}
}
</file>
</files>

View File

@@ -5,6 +5,7 @@ import { addLocale, locale, PrimeReactProvider } from "primereact/api";
import { useMountEffect } from "primereact/hooks";
import Page404 from "./pages/404";
import LoginPage from "./pages/login";
import RegisterPage from "./pages/register";
import { AppProvider, useAppContext } from "./providers/AuthProvider";
const HomePage: FunctionComponent = () => {
@@ -32,6 +33,7 @@ export function App() {
<Router>
<Route path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<Route path="/profile/*" component={lazy(() => import("./pages/profile"))} />
<Route default component={() => <Page404 />} />
</Router>

12
src/assets/main.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 2.3 MiB

BIN
src/assets/status/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1012 KiB

BIN
src/assets/status/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

BIN
src/assets/status/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 970 KiB

BIN
src/assets/status/4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

BIN
src/assets/status/5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 973 KiB

View File

@@ -1,13 +1,13 @@
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";
import ModalWindow from "./ui/Modal";
import ModalWindow, { ModalWindowProps } from "./ui/Modal";
interface ModalCalendarProps {
interface ModalCalendarProps extends ModalWindowProps {
isOpen?: boolean;
setIsOpen?: Dispatch<StateUpdater<boolean>>;
onClose?: () => void;
@@ -27,10 +27,25 @@ const TRANSITIONS = {
},
};
const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({ isOpen, setIsOpen, onClose, onChange, value }) => {
const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({
isOpen,
setIsOpen,
onClose,
onChange,
value,
...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}
isOpen={isOpen}
setIsOpen={setIsOpen}
onClose={() => {
@@ -38,7 +53,6 @@ const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({ isOpen, setIsOpe
setShowTime(false);
}}
className="md:h-[40rem] md:w-[30rem]"
zIndex={60}
>
<div class="w-full flex-1 self-start">
<Calendar
@@ -46,6 +60,7 @@ const ModalCalendar: FunctionComponent<ModalCalendarProps> = ({ isOpen, setIsOpe
onChange={onChange}
value={value}
hourFormat="24"
minDate={minDate}
showTime={showTime}
pt={{
root: ({ props }: CalendarPassThroughMethodOptions) => ({

View File

@@ -0,0 +1,208 @@
import apiClient from "@/services/api";
import { cn } from "@/utils/class-merge";
import { EyeIcon, EyeSlashIcon, XCircleIcon } from "@heroicons/react/24/outline";
import { FunctionComponent } from "preact";
import { useEffect, useState } from "preact/hooks";
import {
InputSwitch,
InputSwitchPassThroughMethodOptions,
InputSwitchPassThroughOptions,
} from "primereact/inputswitch";
import { SubmitHandler, useForm } from "react-hook-form";
import Button from "./ui/Button";
import ModalWindow, { ModalWindowProps } from "./ui/Modal";
interface ISettings {
login: string;
oldPassword: string;
newPassword: string;
tgId: string;
}
export interface IAPIResponse {
profile: IAPIProfile;
}
export interface IAPIProfile {
username: string;
email: string;
status: string;
avatar_url: string;
telegram_notifications: boolean;
telegram_chat_id: string;
}
export interface IAPIUpdateSettingsResponse {
success: boolean;
username: string;
email: string;
avatar_url: string;
password_changed: boolean;
}
const SwitchStyles: InputSwitchPassThroughOptions = {
root: ({ props }: InputSwitchPassThroughMethodOptions) => ({
className: cn("inline-block relative", "w-12 h-7", {
"opacity-60 select-none pointer-events-none cursor-default": props.disabled,
}),
}),
input: {
className: cn("absolute appearance-none top-0 left-0 size-full p-0 m-0 opacity-0 z-10 outline-none cursor-pointer"),
},
slider: ({ props }: InputSwitchPassThroughMethodOptions) => ({
className: cn(
"absolute cursor-pointer top-0 left-0 right-0 bottom-0 border border-transparent",
"transition-colors duration-200 rounded-2xl",
"focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(191,219,254,1)] ",
"before:absolute before:content-'' before:top-1/2 before:bg-white before:w-5 before:h-5 before:left-1 before:-mt-2.5 before:rounded-full before:transition-duration-200",
{
"bg-gray-200 hover:bg-gray-300": !props.checked,
"bg-[rgba(251,194,199,0.53)] before:transform before:translate-x-5": props.checked,
}
),
}),
};
const ModalSettings: FunctionComponent<ModalWindowProps> = ({ isOpen, setIsOpen, onClose, ...rest }) => {
const { handleSubmit, register, setValue, reset } = useForm<ISettings>({
defaultValues: {
login: "",
oldPassword: "",
newPassword: "",
},
mode: "onChange",
});
const changeSettings: SubmitHandler<ISettings> = async (data: ISettings) => {
interface IReq {
username?: string;
current_password?: string;
password?: string;
}
const req: IReq = {
username: data.login || undefined,
current_password: data.oldPassword || undefined,
password: data.newPassword || undefined,
};
const response = await apiClient<IAPIUpdateSettingsResponse>("/api/settings/edit_profile/", {
method: "PATCH",
body: JSON.stringify(req),
});
if (!response.success) console.error("Error changing settings");
if (enableNotification && data.tgId) {
await apiClient("/api/settings/save_chat_id/", {
method: "PATCH",
body: JSON.stringify({ telegram_chat_id: data.tgId }),
});
if (oldEnabledNotif !== enableNotification) {
await apiClient("/api/settings/toggle_telegram_notifications/", { method: "PATCH" });
}
}
handleClose();
};
const [enableNotification, setEnableNotification] = useState(false);
const [login, setLogin] = useState("");
const [showOldPassword, setShowOldPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const [oldEnabledNotif, setOldEnabledNotif] = useState(false);
const [tgId, setTgId] = useState("");
useEffect(() => {
const getSettings = async () => {
const response = await apiClient<IAPIResponse>("/api/settings/view_settings/", { method: "GET" });
setEnableNotification(response.profile.telegram_notifications);
setOldEnabledNotif(response.profile.telegram_notifications);
setLogin(response.profile.username);
setTgId(response.profile.telegram_chat_id);
};
if (isOpen) getSettings();
}, [isOpen]);
const handleClose = () => {
setIsOpen!(false);
setEnableNotification(false);
reset();
if (onClose) onClose();
};
return (
<ModalWindow setIsOpen={setIsOpen} isOpen={isOpen} onClose={handleClose} {...rest} className="h-fit! md:w-[40%]!">
<form onSubmit={handleSubmit(changeSettings)} class="flex w-full flex-col gap-4">
<div class="flex flex-col items-start gap-2">
<span class="ms-5 text-sm">Имя</span>
<div class="flex w-full flex-row items-center rounded-[4rem] bg-[rgba(251,194,199,0.53)] px-5 py-3 leading-8">
<input class="flex-1 outline-0" {...register("login")} placeholder={login} />
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("login", "")} />
</div>
</div>
<div class="flex flex-col items-start gap-2">
<span class="ms-5 text-sm">Старый пароль</span>
<div class="flex w-full flex-row items-center gap-1 rounded-[4rem] bg-[rgba(251,194,199,0.53)] px-5 py-3 leading-8">
<input
class="flex-1 outline-0"
{...register("oldPassword")}
placeholder="Старый пароль"
type={showOldPassword ? "text" : "password"}
/>
{showOldPassword ? (
<EyeIcon class="size-6 cursor-pointer" onClick={() => setShowOldPassword(false)} />
) : (
<EyeSlashIcon class="size-6 cursor-pointer" onClick={() => setShowOldPassword(true)} />
)}
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("oldPassword", "")} />
</div>
</div>
<div class="flex flex-col items-start gap-2">
<span class="ms-5 text-sm">Новый пароль</span>
<div class="flex w-full flex-row items-center gap-1 rounded-[4rem] bg-[rgba(251,194,199,0.53)] px-5 py-3 leading-8">
<input
class="flex-1 outline-0"
{...register("newPassword", {
minLength: { value: 8, message: "Пароль должен быть не менее 8 символов" },
})}
placeholder="Новый пароль"
type={showNewPassword ? "text" : "password"}
/>
{showNewPassword ? (
<EyeIcon class="size-6 cursor-pointer" onClick={() => setShowNewPassword(false)} />
) : (
<EyeSlashIcon class="size-6 cursor-pointer" onClick={() => setShowNewPassword(true)} />
)}
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("newPassword", "")} />
</div>
</div>
<div class="flex flex-row items-center justify-between rounded-[4rem] px-5 py-4 ring-3 ring-[rgba(251,194,199,0.53)]">
<span>Уведомления</span>
<InputSwitch
pt={SwitchStyles}
checked={enableNotification}
onChange={(e) => setEnableNotification(e.value)}
/>
</div>
<div class={cn({ hidden: !enableNotification })}>
<div class="flex flex-col items-start gap-2">
<span class="ms-5 text-sm">
Telegram ID. Для работы перейдите в бота{" "}
<a href="https://t.me/antihvost_notif_bot" class="font-medium text-blue-600 hover:underline">
@antihvost_notif_bot
</a>
</span>
<div class="flex w-full flex-row items-center rounded-[4rem] px-5 py-3 leading-8 ring-2 ring-[rgba(206,232,251,0.7)]">
<input class="flex-1 outline-0" {...register("tgId")} placeholder={tgId} />
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("tgId", "")} />
</div>
</div>
</div>
<Button type="submit">Сохранить</Button>
</form>
</ModalWindow>
);
};
ModalSettings.displayName = "ModalSettings";
export default ModalSettings;

View File

@@ -1,44 +1,133 @@
import { IAPITag, IViewTagsResponse } from "@/pages/profile_tasks.dto";
import apiClient from "@/services/api";
import { cn } from "@/utils/class-merge";
import { BookOpenIcon, DocumentDuplicateIcon } from "@heroicons/react/24/outline";
import { BookOpenIcon, CheckIcon, DocumentDuplicateIcon, PlusCircleIcon } from "@heroicons/react/24/outline";
import { XMarkIcon } from "@heroicons/react/24/solid";
import { FunctionComponent } from "preact";
import { Dispatch, StateUpdater, useEffect, useState } from "preact/hooks";
import { Dispatch, StateUpdater, useEffect, useRef, useState } from "preact/hooks";
import Button from "./ui/Button";
import ModalWindow from "./ui/Modal";
import Dialog from "./ui/Dialog";
import ModalWindow, { ModalWindowProps } from "./ui/Modal";
export interface ITags {
first: string;
second: string;
first: number;
second: number;
overdue: boolean;
}
interface ModalTagsProps {
interface ModalTagsProps extends ModalWindowProps {
isOpen?: boolean;
setIsOpen?: Dispatch<StateUpdater<boolean>>;
onClose?: () => void;
value?: ITags;
onChange?: Dispatch<StateUpdater<ITags>>;
tagsList?: {
first: string[];
second: string[];
first: IAPITag[];
second: IAPITag[];
};
refreshTags: () => Promise<IViewTagsResponse | void>;
}
const ModalTags: FunctionComponent<ModalTagsProps> = ({ isOpen, setIsOpen, onClose, onChange, value, tagsList }) => {
const ModalTags: FunctionComponent<ModalTagsProps> = ({
isOpen,
setIsOpen,
onClose,
onChange,
value,
tagsList,
refreshTags,
...rest
}) => {
const [showFirstTags, setShowFirstTags] = useState(false);
const [showSecondTags, setShowSecondTags] = useState(false);
const [showAddFirstTag, setShowAddFirstTag] = useState(false);
const [showAddSecondTag, setShowAddSecondTag] = useState(false);
const [showErrorDialog, setShowErrorDialog] = useState(false);
const [errorMessage, setErrorMessage] = useState<string[]>([]);
const addFirstTagRef = useRef<HTMLInputElement>(null);
const addSecondTagRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (showFirstTags && showSecondTags) setShowFirstTags(false);
}, [showSecondTags]);
useEffect(() => {
if (showFirstTags && showSecondTags) setShowSecondTags(false);
}, [showFirstTags]);
const handleCreateTag = async () => {
if (!addFirstTagRef.current?.value && !addSecondTagRef.current?.value) return;
const data: { subject_name?: string; taskType_name?: string } = {};
if (addFirstTagRef.current && addFirstTagRef.current.value) data.subject_name = addFirstTagRef.current.value;
if (addSecondTagRef.current && addSecondTagRef.current.value) data.taskType_name = addSecondTagRef.current.value;
const response = await apiClient<{ success: boolean; subject?: IAPITag; taskType?: IAPITag }>(
"/api/tags/create_tags/",
{ method: "POST", body: JSON.stringify(data) }
);
if (response.success) {
await refreshTags();
if (showAddFirstTag) {
const new_subject_id = response.subject!.id;
onChange!((prev) => ({ ...prev, first: new_subject_id }));
setShowAddFirstTag(false);
}
if (showAddSecondTag) {
const new_taskType_id = response.taskType!.id;
onChange!((prev) => ({ ...prev, second: new_taskType_id }));
setShowAddSecondTag(false);
}
}
if (addFirstTagRef.current) addFirstTagRef.current.value = "";
if (addSecondTagRef.current) addSecondTagRef.current.value = "";
};
const handleDeleteTag = async (id: number) => {
const data: { subject_id?: number; taskType_id?: number } = {};
if (showFirstTags) data.subject_id = id;
if (showSecondTags) data.taskType_id = id;
const response = await apiClient<{ error?: string }>(`/api/tags/delete_tag/`, {
method: "DELETE",
body: JSON.stringify(data),
});
if (!response.error) {
await refreshTags();
} else {
setShowErrorDialog(true);
const match = response.error?.match(/\[(.+)\]/);
if (match) setErrorMessage(match[1].split(", ").map((s) => s.trim().replace(/'/g, "")));
}
};
return (
<>
<Dialog
isOpen={showErrorDialog}
setIsOpen={setShowErrorDialog}
title="Ошибка!"
confirmation={false}
cancelText="Ок"
>
<div class="flex flex-col items-start gap-1">
<p class="mb-6 text-sm sm:text-[1rem]">
Данный тег есть в других задачах. Поменяйте теги в них и повторите операцию.
</p>
<p class="text-sm sm:text-[1rem]">Задачи с этим тегом:</p>
<ul class="ms-6 list-disc">
{errorMessage.map((s, i) => (
<li key={i}>{s}</li>
))}
</ul>
</div>
</Dialog>
<ModalWindow
isOpen={isOpen}
{...rest}
setIsOpen={setIsOpen}
onClose={() => {
onClose!();
setShowFirstTags(false);
setShowSecondTags(false);
setShowAddFirstTag(false);
setShowAddSecondTag(false);
}}
className="relative h-[14rem] justify-between py-4 md:h-[14rem] md:w-[25rem]"
zIndex={70}
@@ -47,27 +136,37 @@ const ModalTags: FunctionComponent<ModalTagsProps> = ({ isOpen, setIsOpen, onClo
<div class="flex w-[85%] flex-col gap-2 md:w-full">
<Button
className="flex w-full flex-row items-center justify-center gap-1 text-[1rem]!"
onClick={() => setShowFirstTags(!showFirstTags)}
onClick={() => {
setShowFirstTags(!showFirstTags);
setShowSecondTags(false);
setShowAddFirstTag(false);
setShowAddSecondTag(false);
}}
>
<BookOpenIcon class="size-6" />
{value?.first || "Предмет"}
{tagsList?.first?.find((tag) => tag.id === value?.first)?.name || "Предмет"}
</Button>
<Button
className="flex w-full flex-row items-center justify-center gap-1 text-[1rem]! break-words"
onClick={() => setShowSecondTags(!showSecondTags)}
onClick={() => {
setShowSecondTags(!showSecondTags);
setShowFirstTags(false);
setShowAddFirstTag(false);
setShowAddSecondTag(false);
}}
>
<DocumentDuplicateIcon class="size-6" />
{value?.second || "Тема"}
{tagsList?.second?.find((tag) => tag.id === value?.second)?.name || "Тема"}
</Button>
{showFirstTags && (
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center rounded-[4rem] bg-white px-8 py-4 text-xs md:top-0 md:left-full md:mt-0 md:ml-5">
<div class="flex h-fit max-h-[45vh] w-full flex-col gap-3 overflow-y-auto">
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center gap-3 md:top-0 md:left-full md:mt-0 md:ml-5">
<div class="flex h-fit max-h-[15rem] w-full flex-col gap-3 overflow-y-auto rounded-[4rem] bg-white px-8 py-4 text-xs">
{tagsList?.first.map((tag) => (
<div
class="flex cursor-pointer flex-row gap-2"
class="flex cursor-pointer flex-row items-center gap-2"
onClick={() =>
onChange?.((prev) => {
return { ...prev, first: tag };
return { ...prev, first: tag.id };
})
}
>
@@ -75,27 +174,50 @@ const ModalTags: FunctionComponent<ModalTagsProps> = ({ isOpen, setIsOpen, onClo
class={cn(
"pointer-events-none flex aspect-square size-4 flex-col items-center justify-center rounded-full border-1 border-black text-white select-none",
{
"bg-black": value?.first === tag,
"bg-black": value?.first === tag.id,
}
)}
>
</div>
<p>{tag}</p>
<p class="flex-1">{tag.name}</p>
<XMarkIcon
class="size-4 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
handleDeleteTag(tag.id);
}}
/>
</div>
))}
<button
class="mt-2 flex w-full cursor-pointer flex-row items-center gap-2"
onClick={() => {
setShowAddFirstTag(!showAddFirstTag);
setTimeout(() => addFirstTagRef.current?.focus(), 100);
}}
>
<PlusCircleIcon class="size-5" />
<span>Добавить</span>
</button>
</div>
{showAddFirstTag && (
<div class="flex w-full flex-row items-center rounded-[4rem] bg-white px-8 py-4 text-xs">
<input placeholder="Введите текст" class="flex-1 outline-0" ref={addFirstTagRef} />
<CheckIcon class="size-6 cursor-pointer" onClick={handleCreateTag} />
</div>
)}
</div>
)}
{showSecondTags && (
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center rounded-[4rem] bg-white px-8 py-4 text-xs md:top-0 md:left-full md:mt-0 md:ml-5">
<div class="flex h-fit max-h-[45vh] w-full flex-col gap-3 overflow-y-auto">
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center gap-3 md:top-0 md:left-full md:mt-0 md:ml-5">
<div class="flex h-fit max-h-[15rem] w-full flex-col gap-3 overflow-y-auto rounded-[4rem] bg-white px-8 py-4 text-xs">
{tagsList?.second.map((tag) => (
<div
class="flex cursor-pointer flex-row gap-2"
onClick={() =>
onChange?.((prev) => {
return { ...prev, second: tag };
return { ...prev, second: tag.id };
})
}
>
@@ -103,20 +225,44 @@ const ModalTags: FunctionComponent<ModalTagsProps> = ({ isOpen, setIsOpen, onClo
class={cn(
"pointer-events-none flex aspect-square size-4 flex-col items-center justify-center rounded-full border-1 border-black text-white select-none",
{
"bg-black": value?.second === tag,
"bg-black": value?.second === tag.id,
}
)}
>
</div>
<p>{tag}</p>
<p class="flex-1">{tag.name}</p>
<XMarkIcon
class="size-4 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
handleDeleteTag(tag.id);
}}
/>
</div>
))}
<button
class="mt-2 flex w-full cursor-pointer flex-row items-center gap-2"
onClick={() => {
setShowAddSecondTag(!showAddSecondTag);
setTimeout(() => addSecondTagRef.current?.focus(), 100);
}}
>
<PlusCircleIcon class="size-5" />
<span>Добавить</span>
</button>
</div>
{showAddSecondTag && (
<div class="flex w-full flex-row items-center rounded-[4rem] bg-white px-8 py-4 text-xs">
<input placeholder="Введите текст" class="flex-1 outline-0" ref={addSecondTagRef} />
<CheckIcon class="size-6 cursor-pointer" onClick={handleCreateTag} />
</div>
)}
</div>
)}
</div>
</ModalWindow>
</>
);
};

View File

@@ -1,11 +1,26 @@
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { getAvatarPicUrl } from "@/services/avatar-pic";
import { cn } from "@/utils/class-merge";
import { CalendarDaysIcon, ListBulletIcon, UserIcon } from "@heroicons/react/24/solid";
import { FunctionComponent, h } from "preact";
import { useLocation } from "preact-iso";
import { useEffect, useState } from "preact/hooks";
import { tv } from "tailwind-variants";
import classes from "./menu.module.scss";
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
import { useEffect, useState } from "preact/hooks";
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,34 +51,29 @@ 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 (
return username ? (
<button
onClick={() => route("/profile/settings")}
class={cn("hidden h-32 w-full cursor-pointer overflow-hidden opacity-100 transition-[height,opacity] md:block", {
@@ -75,14 +85,16 @@ const Avatar: FunctionComponent = () => {
"h-full flex-row items-center justify-around rounded-[3rem] bg-[linear-gradient(180.00deg,rgba(249,134,143,0.5)_3.053%,rgb(228,242,252)_96.183%)] px-5 py-5 md:flex"
)}
>
<div class="my-5 aspect-square h-full rounded-full bg-white"></div>
<div class="my-5 aspect-square h-full rounded-full">
<img class="size-full rounded-full" src={getAvatarPicUrl(status)} alt="avatar" />
</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>
</button>
);
) : null;
};
interface MenuItems {

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] px-5 py-6 text-xl shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-transform hover:scale-[1.05] active:scale-[1.05] md:w-[500px];
}

View File

@@ -1,3 +1,4 @@
import { cn } from "@/utils/class-merge";
import { FunctionComponent } from "preact";
import { MouseEventHandler } from "preact/compat";
import { tv } from "tailwind-variants";
@@ -5,7 +6,9 @@ import classes from "./task.module.scss";
interface TaskProps {
name: string;
priority?: number;
checked?: boolean;
overdue?: boolean;
onClick?: () => void;
onMarkClick?: MouseEventHandler<HTMLParagraphElement>;
}
@@ -30,10 +33,26 @@ const markStyle = tv({
},
});
const Task: FunctionComponent<TaskProps> = ({ name, checked = false, onClick = () => {}, onMarkClick = () => {} }) => {
const Task: FunctionComponent<TaskProps> = ({
name,
checked = false,
onClick = () => {},
onMarkClick = () => {},
priority = 4,
overdue,
}) => {
return (
<div class="w-[95%]">
<div class={classes.task} onClick={onClick}>
<div
class={cn(
classes.task,
{ "bg-[linear-gradient(90.00deg,rgba(18,26,230,0.29),rgba(251,194,199,0.34)_100%)]": priority == 1 },
{ "bg-[linear-gradient(90.00deg,rgba(97,200,232,0.6),rgba(251,194,199,0.42)_100%)]": priority == 2 },
{ "bg-[linear-gradient(90.00deg,rgba(247,220,52,0.61),rgba(251,194,199,0.38)_97.71%)]": priority == 3 },
{ "bg-[rgba(251,194,199,0.53)] hover:bg-[rgba(251,194,199,0.7)]": priority == 4 }
)}
onClick={onClick}
>
<div
class={taskStyle({ checked })}
onClick={(e) => {
@@ -44,6 +63,7 @@ const Task: FunctionComponent<TaskProps> = ({ name, checked = false, onClick = (
<p class={markStyle({ checked })}></p>
</div>
{name}
{overdue && !checked && <span class="absolute top-2 right-16 text-xs text-red-500">Просрочено</span>}
</div>
</div>
);

View File

@@ -5,33 +5,33 @@ interface DialogProps {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
title: string;
content: string;
onConfirm: () => void;
onConfirm?: () => void;
confirmText?: string;
cancelText?: string;
confirmation?: boolean;
}
const Dialog: FunctionComponent<DialogProps> = ({
isOpen,
setIsOpen,
title,
content,
onConfirm,
children,
onConfirm = () => {},
confirmText = "Подтвердить",
cancelText = "Отмена",
confirmation = true,
}) => {
if (!isOpen) return null;
return (
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div class="fixed inset-0 z-150 flex items-center justify-center bg-black/50">
<div class="w-full max-w-md rounded-[4rem] bg-white p-6 shadow-lg">
<h2 class="mb-4 text-xl font-semibold">{title}</h2>
<p class="mb-6">{content}</p>
{children}
<div class="flex justify-end gap-4">
<Button
onClick={() => setIsOpen(false)}
className="bg-gray-200 text-gray-800 hover:bg-gray-300"
>
{confirmation ? (
<>
<Button onClick={() => setIsOpen(false)} className="bg-gray-200 text-gray-800 hover:bg-gray-300">
{cancelText}
</Button>
<Button
@@ -43,6 +43,12 @@ const Dialog: FunctionComponent<DialogProps> = ({
>
{confirmText}
</Button>
</>
) : (
<Button onClick={() => setIsOpen(false)} className="bg-gray-200 text-gray-800 hover:bg-gray-300">
{cancelText}
</Button>
)}
</div>
</div>
</div>

View File

@@ -2,7 +2,7 @@ import { cn } from "@/utils/class-merge";
import { FunctionComponent } from "preact";
import { Dispatch, StateUpdater, useEffect } from "preact/hooks";
interface ModalWindowProps {
export interface ModalWindowProps {
isOpen?: boolean;
setIsOpen?: Dispatch<StateUpdater<boolean>>;
onClose?: () => void;

View File

@@ -4,4 +4,5 @@ export enum UrlsTitle {
TASKS = "Задачи",
CALENDAR = "Календарь",
PAGE404 = "404",
REGISTER = "Регистрация",
}

View File

@@ -3,6 +3,7 @@ import Input from "@/components/ui/Input";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import "preact/debug";
@@ -10,10 +11,6 @@ import { Controller, SubmitHandler, useForm } from "react-hook-form";
import { ILoginForm } from "./login.dto";
import classes from "./login.module.scss";
const testUser = {
login: "test",
password: "test",
};
const LoginPage: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const { route } = useLocation();
@@ -25,15 +22,37 @@ const LoginPage: FunctionComponent = () => {
mode: "onChange",
});
const login: SubmitHandler<ILoginForm> = async (data) => {
console.log(data);
if (data.login !== testUser.login || data.password !== testUser.password) {
setError("login", { message: "Неверный логин или пароль" });
setError("password", { message: "Неверный логин или пароль" });
return;
}
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
"/api/login/",
{
method: "POST",
body: JSON.stringify({ username: data.login, password: data.password }),
needsCsrf: true,
},
isLoggedIn
);
if (response.success) {
isLoggedIn.value = true;
localStorage.setItem("loggedIn", "true");
route("/profile/tasks", true);
} else {
const errorMessage = response.error || "Неверный логин или пароль";
setError("login", { message: errorMessage });
setError("password", { message: " " });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} 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);
return !isLoggedIn.value ? (
@@ -71,6 +90,17 @@ const LoginPage: FunctionComponent = () => {
Войти
</Button>
</form>
<span class="mt-5 text-center text-xs">
Еще нет аккаунта?{" "}
<button
class="cursor-pointer text-blue-500 underline"
onClick={() => {
route("/register", true);
}}
>
Зарегистрироваться
</button>
</span>
</div>
</div>
) : (

View File

@@ -6,8 +6,16 @@ import ids from "./profile.module.scss";
const ProfilePage: FunctionComponent = () => {
const { route } = useLocation();
const { isLoggedIn } = useAppContext();
if (!isLoggedIn.value) route("/login", true);
const { isLoggedIn, isCheckingAuth } = useAppContext(); // Получаем новый сигнал
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 ? (
<div id={ids.main_container}>
<div id={ids.router_container}>

View File

@@ -1,31 +1,39 @@
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 apiClient from "@/services/api";
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";
const example_tags: { first: string[]; second: string[] } = {
first: ["Программирование", "Информатика", "Физика", "Математика"],
second: ["Лабораторная работа", "Практическая работа", "Домашнее задание", "Экзамен"],
};
import { FunctionComponent } from "preact";
import { useEffect, useMemo, useState } from "preact/hooks";
import { Calendar, CalendarDateTemplateEvent } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { Nullable } from "primereact/ts-helpers";
import { SubmitHandler, useForm } from "react-hook-form";
import { priorities } from "./profile_tasks";
import {
IApiResponse,
IAPITag,
ICreateTaskResponse,
IDeleteTaskResponse,
IEditTaskResponse,
ITask,
ITaskDetails,
ITaskForm,
IViewTagsResponse,
} from "./profile_tasks.dto";
import { DropdownStyles, selectedPriorityTemplate } from "./profile_tasks.prime.styles";
const calendarStyles = {
root: "inline-flex w-full relative",
@@ -58,9 +66,12 @@ 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: 0, second: 0, overdue: false });
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [subjectChoices, setSubjectChoices] = useState<IAPITag[]>([]);
const [taskTypeChoices, setTaskTypeChoices] = useState<IAPITag[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedPriority, setSelectedPriority] = useState(4);
const {
handleSubmit,
@@ -69,27 +80,191 @@ const ProfileCalendar: FunctionComponent = () => {
setError,
formState: { errors },
} = useForm<ITaskForm>({
defaultValues: {
tags: [],
},
defaultValues: {},
});
useEffect(() => {
const storedTasks = localStorage.getItem("tasks");
if (storedTasks) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const parsedTasks: ITask[] = JSON.parse(storedTasks).map((task: any) => ({
...task,
date: new Date(task.date),
}));
setTasks(parsedTasks);
}
fetchTasks();
fetchTags();
}, []);
const handleDeleteTask = () => {
const fetchTags = async () => {
try {
const response = await apiClient<IViewTagsResponse>("/api/tags/view_tags/");
setSubjectChoices(response.subjects);
setTaskTypeChoices(response.taskTypes);
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
const fetchTasks = async () => {
try {
setIsLoading(true);
const response = await apiClient<IApiResponse>("/api/tasks/view_tasks/");
const convertedTasks: ITask[] = response.tasks.map((apiTask) => ({
id: apiTask.id.toString(),
name: apiTask.title,
checked: apiTask.isCompleted,
date: new Date(apiTask.due_date),
description: apiTask.description,
priority: apiTask.priority,
subject: apiTask.subject,
taskType: apiTask.taskType,
new: false,
}));
setTasks(convertedTasks);
} catch (error) {
console.error("Failed to fetch tasks:", error);
} finally {
setIsLoading(false);
}
};
const example_tags = useMemo(
() => ({
first: subjectChoices,
second: taskTypeChoices,
}),
[subjectChoices, taskTypeChoices]
);
const saveTask: SubmitHandler<ITaskForm> = async (data) => {
if (!calendarDate) {
setError("date", { message: "Выберите дату" });
return;
}
if ((!editContent?.subject.id || !editContent.taskType.id) && (!tags.first || !tags.second)) {
setError("date", { message: "Выберите теги" });
return;
}
try {
const selectedSubject = tags.first || editContent?.subject.id;
const selectedTaskType = tags.second || editContent?.taskType.id;
// 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_id: selectedSubject,
taskType_id: selectedTaskType,
dateTime_due: formattedDate,
telegram_notifications: false,
priority: selectedPriority,
};
if (!editContent) {
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);
} else if (isEdit)
setEditContent({
name: response.task.title,
id: response.task.id.toString(),
description: response.task.description,
priority: response.task.priority,
checked: response.task.isCompleted,
subject: response.task.subject,
taskType: response.task.task_type,
date: new Date(response.task.dateTime_due),
});
}
await fetchTasks();
setIsOpen(false);
setTags({ first: 0, second: 0, overdue: false });
} catch (error) {
console.error("Failed to save task:", error);
}
};
const handleDeleteTask = async () => {
if (!editContent) return;
setTasks(tasks.filter((task) => task.id !== editContent.id));
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 handleTaskCheck = async (taskId: string) => {
try {
await apiClient(`/api/tasks/toggle_complete_task/${taskId}/`, {
method: "PATCH",
});
setTasks((prevTasks) =>
prevTasks.map((task) => (task.id === taskId ? { ...task, checked: !task.checked } : task))
);
} catch (error) {
console.error("Failed to mark task:", error);
}
};
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,
subject: taskDetails.subject,
taskType: taskDetails.task_type,
priority: taskDetails.priority,
};
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
setSelectedPriority(task.priority);
setIsEditModal(false);
} catch (error) {
console.error("Failed to fetch task details:", error);
}
};
useEffect(() => {
@@ -111,18 +286,41 @@ const ProfileCalendar: FunctionComponent = () => {
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
else reset();
}, [editContent]);
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
useEffect(() => {
if (!editContent) return;
const newEditContent = editContent;
if (tags.first) newEditContent.tags = [tags.first, newEditContent.tags[1]];
if (tags.second) newEditContent.tags = [newEditContent.tags[0], tags.second];
if (tags.first) newEditContent.subject = subjectChoices.find((tag) => tag.id === tags.first)!;
if (tags.second) newEditContent.taskType = taskTypeChoices.find((tag) => tag.id === tags.second)!;
setEditContent(newEditContent);
}, [tags]);
const tasksCount = (date: CalendarDateTemplateEvent) => {
const filterTasks = tasks.filter((task) => {
const taskDate = task.date;
return (
taskDate.getDate() === date.day && taskDate.getMonth() === date.month && taskDate.getFullYear() === date.year
);
});
return {
length: filterTasks.length,
colors: filterTasks.map((task) => {
switch (task.priority) {
case 1:
return "bg-[rgba(18,26,230,1)]";
case 2:
return "bg-[rgba(97,200,232,1)]";
case 3:
return "bg-[rgba(247,220,52,1)]";
case 4:
return "bg-[rgba(251,194,199,1)]";
default:
return "bg-[rgba(251,194,199,1)]";
}
}),
};
};
const hasTasksOnDate = (date: CalendarDateTemplateEvent) => {
return tasks.some((task) => {
const taskDate = task.date;
@@ -134,6 +332,8 @@ const ProfileCalendar: FunctionComponent = () => {
const dateTemplate = (date: CalendarDateTemplateEvent) => {
const isHighlighted = hasTasksOnDate(date);
const taskInfo = tasksCount(date);
if (taskInfo.length) console.log(taskInfo);
const isSelected =
currentDate &&
currentDate.getDate() === date.day &&
@@ -143,7 +343,6 @@ const ProfileCalendar: FunctionComponent = () => {
new Date().getDate() === date.day &&
new Date().getMonth() === date.month &&
new Date().getFullYear() === date.year;
return (
<div
className={cn(
@@ -156,17 +355,18 @@ 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: taskInfo.length > 3 ? 3 : taskInfo.length }).map((_, i) => (
<span key={i} className={cn("size-2 rounded-full", taskInfo.colors[i])} />
))}
{taskInfo.length > 3 && <span className="text-xs font-bold text-pink-400 select-none">+</span>}
</div>
)}
</div>
);
};
const handleTaskCheck = (taskId: string) => {
const updatedTasks = tasks.map((task) => (task.id === taskId ? { ...task, checked: !task.checked } : task));
setTasks(updatedTasks);
localStorage.setItem("tasks", JSON.stringify(updatedTasks));
};
const formatDate = (date: Date) => {
return new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
@@ -175,26 +375,6 @@ const ProfileCalendar: FunctionComponent = () => {
}).format(date);
};
const saveTask = (data: ITaskForm) => {
if (!calendarDate) {
setError("date", { message: "Выберите дату" });
return;
}
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,
};
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: "" });
};
const pt = {
root: { className: calendarStyles.root },
input: { root: { className: calendarStyles.input } },
@@ -216,33 +396,15 @@ const ProfileCalendar: FunctionComponent = () => {
return (
<div class="flex w-full flex-col items-center">
<ModalTags
isOpen={openModalTags}
setIsOpen={setOpenModalTags}
tagsList={example_tags}
value={tags}
onClose={() => {
setTags({ first: "", second: "" });
}}
onChange={setTags}
/>
<ModalCalendar
isOpen={openModalCalendar}
setIsOpen={setOpenModalCalendar}
onClose={() => {
if (isEdit && !isEditModal) setCalendarDate(null);
}}
onChange={(e) => isEditModal && setCalendarDate(e.value)}
value={calendarDate!}
/>
<ModalWindow
isOpen={openModal}
setIsOpen={setIsOpen}
onClose={() => {
setIsEdit(false);
setEditContent(null);
setSelectedPriority(4);
setIsEditModal(false);
setTags({ first: "", second: "" });
setTags({ first: 0, second: 0, overdue: false });
setCalendarDate(null);
}}
>
@@ -258,7 +420,9 @@ const ProfileCalendar: 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", {
@@ -267,7 +431,9 @@ const ProfileCalendar: 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", {
@@ -316,7 +482,6 @@ const ProfileCalendar: FunctionComponent = () => {
{errors.name && <p class="text-red-500">{errors.name.message}</p>}
{errors.description && <p class="text-red-500">{errors.description.message}</p>}
{errors.date && <p class="text-red-500">{errors.date.message}</p>}
{errors.tags && <p class="text-red-500">{errors.tags.message}</p>}
<div class="flex flex-col items-center gap-6 self-center md:flex-row md:justify-start md:self-start">
<div
class={cn("flex h-full flex-row items-center gap-1 rounded-2xl bg-[rgba(251,194,199,0.38)] px-2 py-1", {
@@ -345,32 +510,66 @@ const ProfileCalendar: FunctionComponent = () => {
})}
onClick={() => {
if (!isEditModal) return;
setTags({ first: editContent.tags[0], second: editContent.tags[1] });
setTags({ first: editContent.subject.id, second: editContent.taskType.id, overdue: false });
setOpenModalTags(true);
}}
>
<p class="flex flex-row gap-2">
<BookOpenIcon class="size-5" />
{editContent.tags[0]}
{editContent.subject.name}
</p>
<p class="flex flex-row gap-2">
<DocumentDuplicateIcon class="size-5" />
{editContent.tags[1]}
{editContent.taskType.name}
</p>
</div>
<Dropdown
disabled={!isEditModal}
pt={DropdownStyles}
options={priorities}
value={selectedPriority}
onChange={(e) => setSelectedPriority(e.value)}
itemTemplate={selectedPriorityTemplate}
valueTemplate={selectedPriorityTemplate}
/>
</div>
</form>
)}
</ModalWindow>
{isLoading ? (
<div class="flex w-full flex-1 items-center justify-center">Загрузка...</div>
) : (
<>
<ModalTags
refreshTags={fetchTags}
isOpen={openModalTags}
setIsOpen={setOpenModalTags}
tagsList={example_tags}
value={tags}
onClose={() => {
setTags({ first: 0, second: 0, overdue: false });
}}
onChange={setTags}
/>
<ModalCalendar
isOpen={openModalCalendar}
setIsOpen={setOpenModalCalendar}
onClose={() => {
if (isEdit && !isEditModal) setCalendarDate(null);
}}
onChange={(e) => isEditModal && setCalendarDate(e.value)}
value={calendarDate!}
/>
<Dialog
isOpen={showDeleteDialog}
setIsOpen={setShowDeleteDialog}
title="Удаление задачи"
content="Вы уверены, что хотите удалить эту задачу?"
onConfirm={handleDeleteTask}
confirmText="Удалить"
cancelText="Отмена"
/>
>
<p class="mb-6 text-sm sm:text-[1rem]">"Вы уверены, что хотите удалить эту задачу?"</p>
</Dialog>
<Calendar
value={currentDate}
onChange={(e) => setCurrentDate(e ? e.value! : new Date())}
@@ -389,12 +588,9 @@ const ProfileCalendar: FunctionComponent = () => {
key={task.id}
name={task.name}
checked={task.checked}
onClick={() => {
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
}}
priority={task.priority}
overdue={task.date < new Date()}
onClick={() => handleViewTask(task.id)}
onMarkClick={() => handleTaskCheck(task.id)}
/>
))}
@@ -403,6 +599,8 @@ const ProfileCalendar: FunctionComponent = () => {
<div class="rounded-lg bg-[rgba(251,194,199,0.2)] p-4 text-center">На этот день задач нет</div>
)}
</div>
</>
)}
</div>
);
};

View File

@@ -5,7 +5,7 @@
}
#avatar {
@apply flex aspect-square h-[7rem] flex-col items-center justify-center rounded-full bg-white;
@apply flex aspect-square h-[7rem] flex-col items-center justify-center rounded-full;
}
.profile_container {

View File

@@ -1,74 +1,106 @@
import ModalSettings from "@/components/ModalSettings";
import Button from "@/components/ui/Button";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { getAvatarPicUrl } from "@/services/avatar-pic";
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;
status: string;
telegram_notifications: boolean;
telegram_chat_id: string | null;
current_xp: string;
xp_for_next_status: string;
}
interface UserSettings {
profile: UserProfile;
}
const ProfileSettings: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const { route } = useLocation();
const [status, setStatus] = useState(0);
const maxStatus = 100;
const [userData, setUserData] = useState<UserProfile>({
username: "",
status: "",
current_xp: "",
xp_for_next_status: "",
telegram_notifications: false,
telegram_chat_id: "",
});
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
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);
}
};
useEffect(() => {
if (isLoggedIn.value) {
fetchUserData();
}
}, [isLoggedIn.value]);
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, []);
const handleLogout = async () => {
try {
await apiClient("/api/settings/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);
}
};
if (!userData.username)
return (
<div class="flex h-full w-full flex-1 flex-col items-center justify-center">
<div class="flex w-full flex-1 items-center justify-center">Загрузка...</div>;
</div>
);
return (
<div class={classes.container}>
<ModalSettings isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} onClose={fetchUserData} />
<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}>
<img class="size-28 rounded-full" src={getAvatarPicUrl(userData.status)} alt="avatar" />
</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.current_xp / +userData.xp_for_next_status) * 100}%` }}
></div>
</div>
<div class="-mt-3 self-end text-sm font-light">
{status}/{maxStatus}
{userData.current_xp}/{userData.xp_for_next_status}
</div>
</div>
</div>
<div class={classes.profile_container}>
<div class={classes.settings_block}>
<div class={classes.settings_block__buttons}>
<Button>Сменить тему</Button>
<Button>Настройки</Button>
<Button className="flex flex-row items-center justify-center gap-2" onClick={() => setIsSettingsOpen(true)}>
<Cog8ToothIcon class="size-8" /> Настройки
</Button>
<Button
color="secondary"
onClick={() => {
isLoggedIn.value = false;
localStorage.setItem("loggedIn", "false");
route("/login", true);
}}
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={handleLogout}
>
Выйти
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
</Button>
</div>
</div>
@@ -77,4 +109,6 @@ const ProfileSettings: FunctionComponent = () => {
);
};
ProfileSettings.displayName = "ProfileSettings";
export default withTitle(UrlsTitle.PROFILE, ProfileSettings);

View File

@@ -1,13 +1,95 @@
export interface IAPITag {
name: string;
id: number;
}
export interface ITask {
id: string;
name: string;
checked: boolean;
priority: number;
date: Date;
description: string;
tags: string[];
new?: boolean;
subject: IAPITag;
taskType: IAPITag;
}
export interface ITaskForm extends Omit<ITask, "date"> {
export interface ITaskView extends Omit<ITask, "taskType"> {
task_type: IAPITag;
}
export interface ITaskForm extends Omit<ITask, "date" | "subject" | "taskType"> {
date: string;
}
export interface IApiTask {
id: number;
title: string;
description: string;
priority: number;
isCompleted: boolean;
due_date: string;
subject: IAPITag;
taskType: IAPITag;
}
export interface IApiResponse {
profile: string;
tasks: IApiTask[];
}
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: IAPITag;
task_type: IAPITag;
priority: number;
dateTime_due: 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: IAPITag;
task_type: IAPITag;
dateTime_due: string;
isCompleted: boolean;
priority: number;
};
}
export interface IViewTagsResponse {
profile: string;
subjects: IAPITag[];
taskTypes: IAPITag[];
}

View File

@@ -5,7 +5,7 @@
}
.header {
@apply mb-3 w-full text-3xl font-semibold md:mb-12 md:text-5xl;
@apply mb-3 flex w-full flex-row items-center justify-between text-xl font-semibold sm:text-3xl md:mb-12 md:text-5xl;
}
.tasks_container {

View File

@@ -0,0 +1,86 @@
import { cn } from "@/utils/class-merge";
import { FlagIcon as FlagIconSolid } from "@heroicons/react/20/solid";
import { DropdownPassThroughMethodOptions, DropdownPassThroughOptions } from "primereact/dropdown";
export const DropdownStyles: DropdownPassThroughOptions = {
root: ({ props }: DropdownPassThroughMethodOptions) => ({
className: cn(
"cursor-pointer inline-flex relative select-none mb-2",
"bg-white border border-gray-400 transition-colors duration-200 ease-in-out rounded-md",
"w-full md:w-56",
"hover:border-[rgba(251,194,199,0.7)] focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(251,194,199,1)] ",
{ "opacity-60 select-none pointer-events-none cursor-default": props.disabled }
),
}),
input: ({ props }: DropdownPassThroughMethodOptions) => ({
className: cn(
"cursor-pointer flex flex-auto overflow-hidden overflow-ellipsis whitespace-nowrap relative",
"bg-transparent border-0 text-gray-800",
"p-3 transition duration-200 bg-transparent rounded appearance-none font-sans text-base",
"focus:outline-none focus:shadow-none",
{ "pr-7": props.showClear }
),
}),
trigger: {
className: cn(
"flex items-center justify-center shrink-0",
"bg-transparent text-gray-500 w-12 rounded-tr-lg rounded-br-lg"
),
},
wrapper: {
className: cn("max-h-[200px] overflow-auto", "bg-white text-gray-700 border-0 rounded-md shadow-lg", " "),
},
list: { className: "py-3 list-none m-0" },
item: ({ context }: DropdownPassThroughMethodOptions) => ({
className: cn(
"cursor-pointer font-normal overflow-hidden relative whitespace-nowrap",
"m-0 p-3 border-0 transition-shadow duration-200 rounded-none",
"hover:text-gray-700 hover:bg-gray-200",
{
"text-gray-700": !context.focused && !context.selected,
"bg-gray-300 text-gray-700 ": context.focused && !context.selected,
"bg-[rgba(251,194,199,0.7)] text-black ": context.focused && context.selected,
"bg-blue-50 text-gray-700": !context.focused && context.selected,
"opacity-60 select-none pointer-events-none cursor-default": context.disabled,
}
),
}),
itemGroup: {
className: cn("m-0 p-3 text-gray-800 bg-white font-bold", " ", "cursor-auto"),
},
header: {
className: cn("p-3 border-b border-gray-300 text-gray-700 bg-gray-100 mt-0 rounded-tl-lg rounded-tr-lg"),
},
filterContainer: {
className: "relative",
},
filterInput: {
className: cn(
"pr-7 -mr-7",
"w-full",
"font-sans text-base text-gray-700 bg-white py-3 px-3 border border-gray-300 transition duration-200 rounded-lg appearance-none",
"hover:border-[rgba(251,194,199,0.7)] focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(251,194,199,1)] "
),
},
filterIcon: { className: "-mt-2 absolute top-1/2" },
clearIcon: { className: "text-gray-500 right-12 -mt-2 absolute top-1/2" },
};
export const selectedPriorityTemplate = (option: { label: string; value: number }) => {
return (
<div class="flex items-center">
<FlagIconSolid
className={cn(
"mr-2 size-4",
{ "text-[rgba(18,26,230,0.29)]": option.value == 1 },
{ "text-[rgba(97,200,232,0.6)]": option.value == 2 },
{
"text-[rgba(247,220,52,0.61)]": option.value == 3,
},
{ "text-[rgba(251,194,199,0.53)]": option.value == 4 }
)}
/>
<span>{option.label}</span>
</div>
);
};

View File

@@ -1,5 +1,7 @@
//! Файл большой, потому что было лень делить на компоненты
import Task from "@/components/task";
import MainSvg from "@/assets/main.svg";
import ModalCalendar from "@/components/ModalCalendar";
import ModalTags, { ITags } from "@/components/ModalTags";
import Button from "@/components/ui/Button";
@@ -7,6 +9,7 @@ import Dialog from "@/components/ui/Dialog";
import ModalWindow from "@/components/ui/Modal";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import apiClient from "@/services/api";
import { cn } from "@/utils/class-merge";
import { PlusIcon } from "@heroicons/react/20/solid";
import {
@@ -19,47 +22,102 @@ import {
MagnifyingGlassIcon,
PencilIcon,
TrashIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { FunctionComponent } from "preact";
import { useEffect, useMemo, useState } from "preact/hooks";
import "preact/debug";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Checkbox, CheckboxPassThroughMethodOptions } from "primereact/checkbox";
import { Dropdown } from "primereact/dropdown";
import { SelectItem } from "primereact/selectitem";
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 {
IApiResponse,
IAPITag,
ICreateTaskResponse,
IDeleteTaskResponse,
IEditTaskResponse,
ITask,
ITaskDetails,
ITaskForm,
IViewTagsResponse,
} from "./profile_tasks.dto";
import classes from "./profile_tasks.module.scss";
import { DropdownStyles, selectedPriorityTemplate } from "./profile_tasks.prime.styles";
const example_tags: { first: string[]; second: string[] } = {
first: ["Программирование", "Информатика", "Физика", "Математика"],
second: ["Лабораторная работа", "Практическая работа", "Домашнее задание", "Экзамен"],
};
export const priorities: SelectItem[] = [
{ label: "Приоритет 1", value: 1 },
{ label: "Приоритет 2", value: 2 },
{ label: "Приоритет 3", value: 3 },
{ label: "Приоритет 4", value: 4 },
];
const ProfileTasks: FunctionComponent = () => {
const [openModal, setIsOpen] = useState(false); // Открыта модалка
const [openModalCalendar, setOpenModalCalendar] = useState(false); // Открыта модалка календаря
const [openModalTags, setOpenModalTags] = useState(false); // Открыта модалка тегов
const [openSearchModal, setOpenSearchModal] = useState(false); // Открыто окно поиска
const [openFilterModal, setOpenFilterModal] = useState(false);
const [isEdit, setIsEdit] = useState(false); // Открыта задача
const [isEditModal, setIsEditModal] = useState(false); // Включено редактирование задачи
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: 0, second: 0, overdue: false });
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [searchQuery, setSearchQuery] = useState(""); // Текст поиска
const [filterTags, setFilterTags] = useState<ITags>({ first: 0, second: 0, overdue: false });
const [openFirstList, setOpenFirstList] = useState(false);
const [openSecondList, setOpenSecondList] = useState(false);
const [selectedPriority, setSelectedPriority] = useState(4);
const getDate = useMemo(() => {
const date = new Date();
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<IAPITag[]>([]);
const [taskTypeChoices, setTaskTypeChoices] = useState<IAPITag[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
fetchTasks();
fetchTags();
}, []);
const fetchTags = async (): Promise<IViewTagsResponse | void> => {
try {
const response = await apiClient<IViewTagsResponse>("/api/tags/view_tags/");
setSubjectChoices(response.subjects);
setTaskTypeChoices(response.taskTypes);
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
const fetchTasks = async () => {
try {
setIsLoading(true);
const response = await apiClient<IApiResponse>("/api/tasks/view_tasks/");
const convertedTasks: ITask[] = response.tasks.map((apiTask) => ({
id: apiTask.id.toString(),
name: apiTask.title,
priority: apiTask.priority,
checked: apiTask.isCompleted,
date: new Date(apiTask.due_date),
description: apiTask.description,
subject: apiTask.subject,
taskType: apiTask.taskType,
}));
setTasks(convertedTasks);
} catch (error) {
console.error("Failed to fetch tasks:", error);
} finally {
setIsLoading(false);
}
};
const {
handleSubmit,
@@ -67,32 +125,92 @@ const ProfileTasks: FunctionComponent = () => {
reset,
setError,
formState: { errors },
} = useForm<ITaskForm>({
defaultValues: {
tags: [],
},
});
const saveTask: SubmitHandler<ITaskForm> = (data) => {
} = useForm<ITaskForm>({});
const example_tags = useMemo(
() => ({
first: subjectChoices,
second: 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: "Выберите теги" });
if ((!editContent?.subject.id || !editContent.taskType.id) && (!tags.first || !tags.second)) {
setError("date", { message: "Выберите теги" });
return;
}
const eTask: ITask = {
...data,
date: calendarDate,
tags: editContent?.tags.length ? editContent.tags : [tags.first, tags.second],
new: true,
try {
const selectedSubject = editContent?.subject.id || tags.first;
const selectedTaskType = editContent?.taskType.id || 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_id: selectedSubject,
taskType_id: selectedTaskType,
dateTime_due: formattedDate,
priority: selectedPriority,
telegram_notifications: true,
};
if (isCreating) setTasks([...tasks, eTask]);
else setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
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);
} else if (isEdit)
setEditContent({
name: response.task.title,
id: response.task.id.toString(),
description: response.task.description,
priority: response.task.priority,
checked: response.task.isCompleted,
subject: response.task.subject,
taskType: response.task.task_type,
date: new Date(response.task.dateTime_due),
});
}
await fetchTasks();
if (isCreating) setIsOpen(false);
setTags({ first: "", second: "" });
setTags({ first: 0, second: 0, 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();
@@ -102,15 +220,16 @@ const ProfileTasks: FunctionComponent = () => {
name: "",
description: "",
date: "",
tags: [],
priority: 4,
checked: false,
});
setSelectedPriority(4);
}, [isCreating]);
useEffect(() => {
if (!editContent) return;
const newEditContent = editContent;
if (tags.first) newEditContent.tags = [tags.first, newEditContent.tags[1]];
if (tags.second) newEditContent.tags = [newEditContent.tags[0], tags.second];
if (tags.first) newEditContent.subject = subjectChoices.find((choice) => choice.id === tags.first)!;
if (tags.second) newEditContent.taskType = taskTypeChoices.find((choice) => choice.id === tags.second)!;
setEditContent(newEditContent);
}, [tags]);
@@ -165,35 +284,100 @@ const ProfileTasks: FunctionComponent = () => {
}).format(date);
};
const handleDeleteTask = () => {
const handleDeleteTask = async () => {
if (!editContent) return;
setTasks(tasks.filter((task) => task.id !== editContent.id));
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) => {
try {
await apiClient(`/api/tasks/toggle_complete_task/${taskId}/`, {
method: "PATCH",
});
setTasks((prevTasks) =>
prevTasks.map((task) => (task.id === taskId ? { ...task, checked: !task.checked } : task))
);
} catch (error) {
console.error("Failed to mark task:", error);
}
};
const filteredTasks = useMemo(() => {
let filtered = tasks;
if (searchQuery) {
filtered = filtered.filter(
(task) =>
task.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
task.description?.toLowerCase().includes(searchQuery.toLowerCase())
);
}
if (filterTags.first || filterTags.second) {
filtered = filtered.filter(
(task) =>
(!filterTags.first || task.subject.id === filterTags.first) &&
(!filterTags.second || task.taskType.id === filterTags.second)
);
}
filtered = filtered.filter((task) => (filterTags.overdue && !task.checked ? task.date < new Date() : 1));
return filtered;
}, [tasks, searchQuery, filterTags]);
const searchInputRef = useRef<HTMLInputElement>(null);
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,
priority: taskDetails.priority,
checked: false,
date: new Date(taskDetails.dateTime_due),
description: taskDetails.description,
subject: taskDetails.subject,
taskType: taskDetails.task_type,
};
setIsOpen(true);
setIsEdit(true);
setEditContent(task);
setCalendarDate(task.date);
setIsEditModal(false);
setSelectedPriority(task.priority);
} catch (error) {
console.error("Failed to fetch task details:", error);
}
};
return (
<div class={classes.container}>
<ModalTags
isOpen={openModalTags}
setIsOpen={setOpenModalTags}
tagsList={example_tags}
value={tags}
onClose={() => {
if (!isCreating) setTags({ first: "", second: "" });
}}
onChange={setTags}
/>
<ModalCalendar
isOpen={openModalCalendar}
setIsOpen={setOpenModalCalendar}
onClose={() => {
if (isEdit && !isEditModal) setCalendarDate(null);
}}
onChange={(e) => (isCreating || isEditModal) && setCalendarDate(e.value)}
value={calendarDate!}
/>
<ModalWindow
zIndex={60}
isOpen={openModal}
setIsOpen={setIsOpen}
onClose={() => {
@@ -201,7 +385,7 @@ const ProfileTasks: FunctionComponent = () => {
setEditContent(null);
setIsCreating(false);
setIsEditModal(false);
setTags({ first: "", second: "" });
setTags({ first: 0, second: 0, overdue: false });
setCalendarDate(null);
}}
>
@@ -217,7 +401,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", {
@@ -226,13 +412,16 @@ 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", {
maxLength: { value: 200, message: "Максимум 200 символов в описании" },
})}
/>
<input
type="datetime-local"
value={calendarDate ? calendarDate.toISOString().slice(0, 16) : ""}
@@ -241,7 +430,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={() => {
@@ -275,7 +464,6 @@ const ProfileTasks: FunctionComponent = () => {
{errors.name && <p class="text-red-500">{errors.name.message}</p>}
{errors.description && <p class="text-red-500">{errors.description.message}</p>}
{errors.date && <p class="text-red-500">{errors.date.message}</p>}
{errors.tags && <p class="text-red-500">{errors.tags.message}</p>}
<div class="flex flex-col items-center gap-6 self-center md:flex-row md:justify-start md:self-start">
<div
class={cn("flex h-full flex-row items-center gap-1 rounded-2xl bg-[rgba(251,194,199,0.38)] px-2 py-1", {
@@ -295,7 +483,7 @@ const ProfileTasks: FunctionComponent = () => {
year: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(calendarDate!)}
}).format(calendarDate ?? editContent.date)}
</p>
</div>
<div
@@ -304,19 +492,28 @@ const ProfileTasks: FunctionComponent = () => {
})}
onClick={() => {
if (!isEditModal) return;
setTags({ first: editContent.tags[0], second: editContent.tags[1] });
setTags({ first: editContent.subject.id, second: editContent.taskType.id, overdue: false });
setOpenModalTags(true);
}}
>
<p class="flex flex-row gap-2">
<BookOpenIcon class="size-5" />
{editContent.tags[0]}
{editContent.subject.name}
</p>
<p class="flex flex-row gap-2">
<DocumentDuplicateIcon class="size-5" />
{editContent.tags[1]}
{editContent.taskType.name}
</p>
</div>
<Dropdown
disabled={!isEditModal}
pt={DropdownStyles}
options={priorities}
value={selectedPriority}
onChange={(e) => setSelectedPriority(e.value)}
itemTemplate={selectedPriorityTemplate}
valueTemplate={selectedPriorityTemplate}
/>
</div>
</form>
)}
@@ -325,19 +522,19 @@ const ProfileTasks: FunctionComponent = () => {
class="flex h-full w-full flex-col items-start justify-between"
onSubmit={(e) => {
e.preventDefault();
handleSubmit((data) => saveTask({ ...data, id: uuid() }))();
handleSubmit((data) => saveTask(data))();
}}
>
<div class="flex w-full flex-1 flex-row items-start justify-between">
<div class="me-4 flex h-full flex-1 flex-col gap-1">
<div class="flex flex-1 flex-col gap-1 pe-2">
<input
class="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="mb-10 w-full flex-1 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")}
@@ -348,22 +545,29 @@ const ProfileTasks: FunctionComponent = () => {
hidden
{...register("date")}
/>
<Dropdown
pt={DropdownStyles}
options={priorities}
value={selectedPriority}
onChange={(e) => setSelectedPriority(e.value)}
itemTemplate={selectedPriorityTemplate}
valueTemplate={selectedPriorityTemplate}
/>
<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-10 cursor-pointer"
class="size-8 cursor-pointer"
onClick={() => {
setOpenModalCalendar(true);
setCalendarDate(calendarDate ?? new Date());
}}
/>
<BookmarkIcon class="ms-4 size-10 cursor-pointer" onClick={() => setOpenModalTags(true)} />
<BookmarkIcon class="size-8 cursor-pointer" onClick={() => setOpenModalTags(true)} />
</div>
</div>
{errors.name && <p class="text-red-500">{errors.name.message}</p>}
{errors.date && <p class="text-red-500">{errors.date.message}</p>}
{errors.tags && <p class="text-red-500">{errors.tags.message}</p>}
<div className="mb-8 flex h-16 flex-col items-center gap-6 self-center md:mb-0 md:flex-row md:self-start">
<Button
className="text-sm"
@@ -380,18 +584,72 @@ const ProfileTasks: FunctionComponent = () => {
</form>
)}
</ModalWindow>
{isLoading ? (
<div class="flex w-full flex-1 items-center justify-center">Загрузка...</div>
) : (
<>
<ModalTags
refreshTags={fetchTags}
zIndex={70}
isOpen={openModalTags}
setIsOpen={setOpenModalTags}
tagsList={example_tags}
value={tags}
onClose={() => {
if (!isCreating) setTags({ first: 0, second: 0, overdue: false });
}}
onChange={setTags}
/>
<ModalCalendar
zIndex={80}
isOpen={openModalCalendar}
setIsOpen={setOpenModalCalendar}
onClose={() => {
if (isEdit && !isEditModal) setCalendarDate(null);
}}
onChange={(e) => (isCreating || isEditModal) && setCalendarDate(e.value)}
value={calendarDate!}
/>
<Dialog
isOpen={showDeleteDialog}
setIsOpen={setShowDeleteDialog}
title="Удаление задачи"
content="Вы уверены, что хотите удалить эту задачу?"
onConfirm={handleDeleteTask}
confirmText="Удалить"
cancelText="Отмена"
/>
{tasks.length > 0 ? (
>
<p class="mb-6 text-sm sm:text-[1rem]">"Вы уверены, что хотите удалить эту задачу?"</p>
</Dialog>
{!searchQuery && !filterTags.first && !filterTags.second && !filterTags.overdue ? (
filteredTasks.length > 0 ? (
<>
<div class={classes.header}>Сегодня: {getDate}</div>
<div class={classes.header}>
Сегодня: {getDate}
<div class="flex flex-row items-center gap-2 md:hidden">
{!openSearchModal && (
<div
class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]"
onClick={(e) => {
e.stopPropagation();
if (!openSearchModal) setOpenFilterModal(false);
setOpenSearchModal(!openSearchModal);
}}
>
<MagnifyingGlassIcon class="size-6" />
</div>
)}
<div class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]">
<FunnelIcon
class="size-6"
onClick={(e) => {
e.stopPropagation();
if (!openFilterModal) setOpenSearchModal(false);
setOpenFilterModal(!openFilterModal);
}}
/>
</div>
</div>
</div>
<div class={classes.tasks_container}>
{groupTasksByDate.today.length > 0 ? (
<div class="w-full">
@@ -399,16 +657,11 @@ const ProfileTasks: FunctionComponent = () => {
<Task
name={task.name}
key={task.id}
priority={task.priority}
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)}
/>
))}
</div>
@@ -421,17 +674,11 @@ const ProfileTasks: FunctionComponent = () => {
{groupTasksByDate.tomorrow.map((task) => (
<Task
name={task.name}
priority={task.priority}
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)}
/>
))}
</div>
@@ -442,22 +689,71 @@ const ProfileTasks: FunctionComponent = () => {
{group.tasks.map((task) => (
<Task
name={task.name}
priority={task.priority}
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)}
/>
))}
</div>
))}
</div>
</>
) : (
<div class="my-auto flex h-full w-full flex-col items-center justify-start">
<img src={MainSvg} />
<div class="flex w-full flex-1 flex-col items-center justify-center text-2xl">Начни уже сегодня!</div>
</div>
)
) : (
<div class={classes.tasks_container}>
<div class="mb-8 flex w-full flex-row items-center justify-between text-xl font-semibold sm:text-3xl md:text-5xl">
{searchQuery ? "Результаты поиска" : "Результаты фильтрации"}
<div class="flex flex-row items-center gap-2 md:hidden">
{!openSearchModal && (
<div
class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]"
onClick={(e) => {
e.stopPropagation();
if (!openSearchModal) setOpenFilterModal(false);
setOpenSearchModal(!openSearchModal);
}}
>
<MagnifyingGlassIcon class="size-6" />
</div>
)}
<div class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]">
<FunnelIcon
class="size-6"
onClick={(e) => {
e.stopPropagation();
if (!openFilterModal) setOpenSearchModal(false);
setOpenFilterModal(!openFilterModal);
}}
/>
</div>
</div>
</div>
{filteredTasks.length > 0 ? (
filteredTasks.map((task) => (
<Task
name={task.name}
priority={task.priority}
key={task.id}
checked={task.checked}
overdue={task.date < new Date()}
onClick={() => handleViewTask(task.id)}
onMarkClick={() => handleMarkTask(task.id)}
/>
))
) : (
<div class="w-full text-center text-xl">
{searchQuery ? "Ничего не найдено" : "Нет задач с выбранными фильтрами"}
</div>
)}
</div>
)}
<div class="group fixed right-1 bottom-16 flex flex-row items-center justify-start space-x-3 overflow-x-hidden py-2 md:right-[22rem] md:bottom-4">
<div
class="flex aspect-square h-20 cursor-pointer items-center justify-center rounded-full bg-[rgb(251,194,199,0.53)] text-9xl text-white shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-all duration-300 ease-out group-hover:ml-[12rem] hover:bg-[rgb(251,194,199,0.7)]"
@@ -468,30 +764,203 @@ const ProfileTasks: FunctionComponent = () => {
>
<PlusIcon />
</div>
{tasks.length > 0 && (
<div class="absolute left-0 my-auto hidden flex-row space-x-3 opacity-0 transition-opacity duration-100 group-hover:opacity-100 md:flex">
<div class="pointer-events-none flex aspect-square h-20 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] group-hover:pointer-events-auto hover:bg-[rgba(206,232,251,0.9)]">
<div
class="pointer-events-none flex aspect-square h-20 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] group-hover:pointer-events-auto hover:bg-[rgba(206,232,251,0.9)]"
onClick={(e) => {
e.stopPropagation();
if (!openSearchModal) setOpenFilterModal(false);
setOpenSearchModal(!openSearchModal);
}}
>
<MagnifyingGlassIcon class="size-12" />
</div>
<div class="pointer-events-none flex aspect-square h-20 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] group-hover:pointer-events-auto hover:bg-[rgba(206,232,251,0.9)]">
<FunnelIcon class="size-12" />
<FunnelIcon
class="size-12"
onClick={(e) => {
e.stopPropagation();
if (!openFilterModal) setOpenSearchModal(false);
setOpenFilterModal(!openFilterModal);
}}
/>
</div>
</div>
)}
</div>
</>
) : (
<>
<div class="flex w-full flex-1 flex-col items-center justify-center text-2xl">Начни уже сегодня!</div>
<div class="group fixed right-1 bottom-16 flex flex-row items-center justify-start space-x-3 overflow-x-hidden py-2 md:right-[22rem] md:bottom-4">
<div
class="flex aspect-square h-20 cursor-pointer items-center justify-center rounded-full bg-[rgb(251,194,199,0.53)] text-9xl text-white shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-all duration-300 ease-out hover:bg-[rgb(251,194,199,0.7)]"
{openSearchModal && (
<div class="fixed bottom-28 z-50 w-full rounded-lg bg-white p-4 shadow-lg md:absolute md:right-[24rem] md:mx-0 md:w-80">
{/* Пофиксить разфокус при вводе */}
<div class="flex items-center gap-2">
<MagnifyingGlassIcon class="size-6 text-gray-400" />
<input
type="text"
class="w-full rounded-lg border-0 px-4 py-2 outline-none"
placeholder="Поиск"
ref={searchInputRef}
value={searchQuery}
onInput={(e) => {
setSearchQuery((e.target as HTMLInputElement).value);
}}
/>
<XMarkIcon
class="size-5 cursor-pointer text-gray-400 hover:text-gray-600"
onClick={() => {
setIsCreating(true);
setIsOpen(true);
setSearchQuery("");
setOpenSearchModal(false);
}}
/>
</div>
</div>
)}
{openFilterModal && (
<div class="fixed top-[50%] z-50 w-full rounded-[2rem] bg-white p-4 shadow-lg md:absolute md:top-auto md:right-[24rem] md:bottom-28 md:w-80">
<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(
"flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-[rgba(206,232,251,0.7)] px-4 py-2",
{
"bg-[rgba(206,232,251,0.9)]": filterTags.first,
}
)}
onClick={() => {
setOpenFirstList(!openFirstList);
setOpenSecondList(false);
}}
>
<PlusIcon />
<BookOpenIcon class="size-5" />
<span>{subjectChoices.find((s) => s.id === filterTags.first)?.name || "Предмет"}</span>
</div>
{openFirstList && (
<div class="absolute top-full right-0 z-50 max-h-[15rem] w-64 overflow-y-auto rounded-lg bg-white p-2 shadow-lg md:top-0 md:right-full md:mr-2">
{example_tags.first.map((tag) => {
return (
<div
key={`subject_${tag.id}`}
class="group flex cursor-pointer items-center gap-2 rounded-lg px-4 py-2 hover:bg-[rgba(206,232,251,0.3)]"
onClick={() => {
setFilterTags({ ...filterTags, first: tag.id });
setOpenFirstList(false);
}}
>
<div
class={cn("flex h-5 w-5 items-center justify-center rounded-full border-2", {
"border-[#FBC2C7] bg-[#FBC2C7]": filterTags.first === tag.id,
"border-[#D4D4D4]": filterTags.first !== tag.id,
})}
>
{filterTags.first === tag.id && <div class="h-2.5 w-2.5 rounded-full bg-white" />}
</div>
<span class="text-sm font-medium text-[#404040]">{tag.name}</span>
</div>
);
})}
</div>
)}
</div>
<div class="relative">
<div
class={cn(
"flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-[rgba(206,232,251,0.7)] px-4 py-2",
{
"bg-[rgba(206,232,251,0.9)]": filterTags.second,
}
)}
onClick={() => {
setOpenSecondList(!openSecondList);
setOpenFirstList(false);
}}
>
<DocumentDuplicateIcon class="size-5" />
<span>{taskTypeChoices.find((s) => s.id === filterTags.second)?.name || "Задача"}</span>
</div>
{openSecondList && (
<div class="absolute top-full right-0 z-50 max-h-[15rem] w-64 overflow-y-auto rounded-lg bg-white p-2 shadow-lg md:top-0 md:right-full md:mr-2">
{example_tags.second.map((tag) => (
<div
key={`taskType_${tag.id}`}
class="group flex cursor-pointer items-center gap-2 rounded-lg px-4 py-2 hover:bg-[rgba(206,232,251,0.3)]"
onClick={() => {
setFilterTags({ ...filterTags, second: tag.id });
setOpenSecondList(false);
}}
>
<div
class={cn("flex h-5 w-5 items-center justify-center rounded-full border-2", {
"border-[#FBC2C7] bg-[#FBC2C7]": filterTags.second === tag.id,
"border-[#D4D4D4]": filterTags.second !== tag.id,
})}
>
{filterTags.second === tag.id && <div class="h-2.5 w-2.5 rounded-full bg-white" />}
</div>
<span class="text-sm font-medium text-[#404040]">{tag.name}</span>
</div>
))}
</div>
)}
</div>
{(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: 0, second: 0, overdue: false });
setOpenFirstList(false);
setOpenSecondList(false);
}}
>
Сбросить фильтры
</button>
)}
</div>
</div>
</div>
)}
</>
)}
</div>

132
src/pages/register.tsx Normal file
View File

@@ -0,0 +1,132 @@
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import "preact/debug";
import { Controller, SubmitHandler, useForm } from "react-hook-form";
import { ILoginForm } from "./login.dto";
import classes from "./login.module.scss";
interface IRegisterForm extends ILoginForm {
confirmPassword: string;
}
const RegisterPage: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const { route } = useLocation();
const { control, handleSubmit, formState, setError } = useForm({
defaultValues: {
login: "",
password: "",
confirmPassword: "",
},
mode: "onChange",
});
const register: SubmitHandler<IRegisterForm> = async (data) => {
if (data.password !== data.confirmPassword) {
setError("confirmPassword", { message: "Пароли не совпадают" });
return;
}
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response = await apiClient<{ success: boolean; user?: any; error?: string }>("/api/register/", {
method: "POST",
body: JSON.stringify({ username: data.login, password: data.password }),
needsCsrf: true,
});
if (response.success) {
route("/login", true);
} else {
const errorMessage = response.error || "Неверный логин или пароль";
setError("login", { message: errorMessage });
setError("password", { message: " " });
setError("confirmPassword", { message: " " });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
console.error("Register failed:", error);
const errorMessage = "Ошибка входа. Попробуйте позже.";
setError("login", { message: errorMessage });
setError("password", { message: " " });
setError("confirmPassword", { message: " " });
}
};
if (isLoggedIn.value) route("/profile/tasks", true);
return !isLoggedIn.value ? (
<div class={classes.login_container}>
<div class={classes.login_card}>
<p class={classes.login_card_name}>Антихвост</p>
<form onSubmit={handleSubmit(register)}>
<Controller
name="login"
control={control}
rules={{
required: "Введите логин",
minLength: { value: 3, message: "Логин должен быть не менее 3 символов" },
}}
render={({ field }) => (
<Input placeholder="Логин" textAlign="center" error={formState.errors.login?.message} {...field} />
)}
/>
<Controller
name="password"
control={control}
rules={{
required: "Введите пароль",
minLength: { value: 8, message: "Пароль должен быть не менее 8 символов" },
}}
render={({ field }) => (
<Input
placeholder="Пароль"
textAlign="center"
type="password"
error={formState.errors.password?.message}
{...field}
/>
)}
/>
<Controller
name="confirmPassword"
control={control}
rules={{
required: "Введите пароль",
minLength: { value: 8, message: "Пароль должен быть не менее 8 символов" },
}}
render={({ field }) => (
<Input
placeholder="Повторите пароль"
textAlign="center"
type="password"
error={formState.errors.confirmPassword?.message}
{...field}
/>
)}
/>
<Button type="submit" color="secondary" className="w-full">
Зарегистрироваться
</Button>
</form>
<span class="mt-5 text-center text-xs">
Уже есть аккаунт?{" "}
<button
class="cursor-pointer text-blue-500 underline"
onClick={() => {
route("/login", true);
}}
>
Войти
</button>
</span>
</div>
</div>
) : (
<p>Redirecting...</p>
);
};
export default withTitle(UrlsTitle.REGISTER, RegisterPage);

View File

@@ -1,20 +1,75 @@
import { stringToBoolean } from "@/utils/converter";
import apiClient from "@/services/api";
import { signal, Signal } from "@preact/signals";
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 {
isLoggedIn: Signal<boolean>;
isCheckingAuth: Signal<boolean>;
currentUser: Signal<UserData | null>;
checkAuth: () => Promise<void>;
}
const ininitialValue = stringToBoolean(localStorage.getItem("loggedIn"));
const AppContext = createContext<AppContextValue>({
isLoggedIn: signal(ininitialValue),
});
const initialLoggedIn = localStorage.getItem("loggedIn") === "true";
const AppContext = createContext<AppContextValue | null>(null);
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 = {
isLoggedIn: signal(ininitialValue),
isLoggedIn,
isCheckingAuth,
currentUser,
checkAuth,
};
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
@@ -29,3 +84,4 @@ const useAppContext = () => {
};
export { AppProvider, useAppContext };
export type { UserData };

99
src/services/api.ts Normal file
View 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;

View File

@@ -0,0 +1,21 @@
import Status1 from "@/assets/status/1.png";
import Status2 from "@/assets/status/2.png";
import Status3 from "@/assets/status/3.png";
import Status4 from "@/assets/status/4.png";
import Status5 from "@/assets/status/5.png";
export const getAvatarPicUrl = (status: string) => {
switch (true) {
case status.includes("точно"):
return Status1;
case status.includes("плана нет"):
return Status2;
case status.includes("прокрастинации"):
return Status3;
case status.includes("3000"):
return Status4;
case status.includes("планирования"):
return Status5;
default:
return Status1;
}
};