Compare commits
28 Commits
5693701aa5
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f83e31967b | |||
|
|
781945b358 | ||
| c55f7a972c | |||
|
|
0c41cc59b9 | ||
|
|
c761f337b1 | ||
|
|
47152a921e | ||
|
|
d1a46435c4 | ||
|
|
02de330034 | ||
|
|
14d2f5cbf1 | ||
|
|
6675bd871e | ||
|
|
4391114dc3 | ||
|
|
46e27616b2 | ||
|
|
284de59a16 | ||
|
|
4fcbde6a06 | ||
|
|
a4622cf8d2 | ||
|
|
fd34761745 | ||
|
|
358c7def78 | ||
|
|
8f337e6f7b | ||
|
|
95f7479375 | ||
|
|
2e5d4b2653 | ||
|
|
d6ab1cba4d | ||
|
|
ee0e44082a | ||
|
|
dae4584840 | ||
|
|
57a680fba8 | ||
|
|
390f1f52c8 | ||
|
|
abb7301c16 | ||
|
|
304c734169 | ||
|
|
e904297bb9 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -11,6 +11,7 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
*.tsbuildinfo
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
@@ -23,3 +24,4 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + React + TS</title>
|
||||
<title>LiquidCode</title>
|
||||
|
||||
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap" rel="stylesheet">
|
||||
|
||||
|
||||
13562
package-lock.json
generated
13562
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host",
|
||||
"build": "tsc && vite build",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
||||
5
public/logo.svg
Normal file
5
public/logo.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg width="62" height="56" viewBox="0 0 62 56" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M16.7765 44.9299V16.6675C16.7765 7.46416 9.26353 0 0 0V44.9299C0.00729412 45.9589 0.153177 50.4447 3.64706 53.626C4.92353 54.7927 6.27294 55.4377 7.29412 55.8H23.3412C22.4221 55.4377 21.2113 54.7927 20.0588 53.626C16.9151 50.4447 16.7838 45.9589 16.7765 44.9299Z" fill="#0C8092"/>
|
||||
<path d="M35.7412 44.9299V27.5377C35.7412 18.3343 28.2282 10.8701 18.9647 10.8701V44.9299C18.972 45.9589 19.1179 50.4447 22.6118 53.626C23.8882 54.7927 25.2376 55.4377 26.2588 55.8H42.3059C41.3868 55.4377 40.176 54.7927 39.0235 53.626C35.8798 50.4447 35.7485 45.9589 35.7412 44.9299Z" fill="#16A7C6"/>
|
||||
<path d="M58.3529 53.626C54.8591 50.4447 54.7132 45.9589 54.7059 44.9299V39.1325C54.7059 29.9291 47.1929 22.4649 37.9294 22.4649V44.9299C37.9367 45.9589 38.0826 50.4447 41.5765 53.626C42.8529 54.7927 44.2024 55.4377 45.2235 55.8H62C60.9788 55.4377 59.6294 54.7927 58.3529 53.626Z" fill="#00DBD9"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 993 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@@ -1,5 +1,6 @@
|
||||
import Cup from './cup.svg';
|
||||
import Home from './home.svg';
|
||||
import MessageChat from './message-chat.svg';
|
||||
import Logout from './logout.svg';
|
||||
|
||||
export { Cup, MessageChat, Home };
|
||||
export { Cup, MessageChat, Home, Logout };
|
||||
|
||||
3
src/assets/icons/group/logout.svg
Normal file
3
src/assets/icons/group/logout.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8.79562 4H5.1075C4.54856 4 4.01251 4.21071 3.61727 4.58579C3.22204 4.96086 3 5.46957 3 6V18C3 18.5304 3.22204 19.0391 3.61727 19.4142C4.01251 19.7893 4.54856 20 5.1075 20H8.79562M9.0575 12.0007L21 12.0007M21 12.0007L16.4368 7.42931M21 12.0007L16.4368 16.5722" stroke="#EDF6F7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 456 B |
@@ -5,4 +5,5 @@ import Edit from './edit.svg';
|
||||
import UserAdd from './user-profile-add.svg';
|
||||
import ChevroneDown from './chevron-down.svg';
|
||||
|
||||
|
||||
export { Book, Edit, EyeClosed, EyeOpen, UserAdd, ChevroneDown };
|
||||
|
||||
@@ -5,6 +5,8 @@ import upload from './upload.svg';
|
||||
import chevroneDropDownList from './chevron-drop-down.svg';
|
||||
import checkMark from './check-mark.svg';
|
||||
import Edit from './edit.svg';
|
||||
import Send from './send.svg';
|
||||
import Trash from './trash.svg';
|
||||
|
||||
export {
|
||||
Edit,
|
||||
@@ -14,4 +16,6 @@ export {
|
||||
upload,
|
||||
chevroneDropDownList,
|
||||
checkMark,
|
||||
Send,
|
||||
Trash,
|
||||
};
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 8.9 KiB |
3
src/assets/icons/input/send.svg
Normal file
3
src/assets/icons/input/send.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M21.4045 11.5763L6.32338 11.5763M5.06681 2.74198L20.8828 10.4103C21.8567 10.8826 21.8567 12.2701 20.8828 12.7423L5.06681 20.4107C3.98332 20.936 2.83166 19.8284 3.3143 18.7253L6.21474 12.0957C6.3596 11.7646 6.3596 11.388 6.21474 11.0569L3.3143 4.42737C2.83167 3.32419 3.98332 2.21665 5.06681 2.74198Z" stroke="#EDF6F7" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 472 B |
3
src/assets/icons/input/trash.svg
Normal file
3
src/assets/icons/input/trash.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M4 6.17647H20M9 3H15M10 16.7647V10.4118M14 16.7647V10.4118M15.5 21H8.5C7.39543 21 6.5 20.0519 6.5 18.8824L6.0434 7.27937C6.01973 6.67783 6.47392 6.17647 7.04253 6.17647H16.9575C17.5261 6.17647 17.9803 6.67783 17.9566 7.27937L17.5 18.8824C17.5 20.0519 16.6046 21 15.5 21Z" stroke="#EDF6F7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 467 B |
@@ -104,7 +104,8 @@ export const Checkbox: React.FC<CheckboxProps> = ({
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'group-hover:bg-default-100 group-active:scale-90 flex items-center justify-center bg-transparent hover:bg-default-100 box-border border-solid border-[1px] border-liquid-white z-10 relative transition-all duration-300',
|
||||
'group-hover:bg-default-100 group-active:scale-90 flex items-center justify-center bg-transparent hover:bg-default-100 box-border border-solid border-[1px] border-liquid-white z-10 relative transition-all duration-300',
|
||||
color == 'danger' && ' border-liquid-red',
|
||||
sizeVariants[size],
|
||||
radiusVraiants[radius],
|
||||
active && borderColorsVariants[color],
|
||||
|
||||
161
src/components/filters/TagFilter.tsx
Normal file
161
src/components/filters/TagFilter.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import React, { useState } from 'react';
|
||||
import { cn } from '../../lib/cn';
|
||||
import { useClickOutside } from '../../hooks/useClickOutside';
|
||||
import { iconFilter, iconFilterActive } from '../../assets/icons/filters';
|
||||
import { Input } from '../input/Input';
|
||||
import { PrimaryButton } from '../button/PrimaryButton';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
import { SecondaryButton } from '../button/SecondaryButton';
|
||||
|
||||
interface TagFilterProps {
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
onChange: (items: string[]) => void;
|
||||
}
|
||||
|
||||
export const TagFilter: React.FC<TagFilterProps> = ({
|
||||
disabled = false,
|
||||
className = '',
|
||||
onChange,
|
||||
}) => {
|
||||
const [active, setActive] = React.useState(false);
|
||||
|
||||
const [tagInput, setTagInput] = useState<string>('');
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
|
||||
// ==========================
|
||||
// Теги
|
||||
// ==========================
|
||||
const addTag = () => {
|
||||
if (tags.length > 30) {
|
||||
setTagInput('');
|
||||
toastError('Нельзя добавить больше 30 тегов');
|
||||
return;
|
||||
}
|
||||
const newTag = tagInput.trim();
|
||||
if (newTag && !tags.includes(newTag)) {
|
||||
setTags([...tags, newTag]);
|
||||
setTagInput('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeTag = (tagToRemove: string) => {
|
||||
setTags(tags.filter((tag) => tag !== tagToRemove));
|
||||
};
|
||||
|
||||
const resetTags = () => {
|
||||
setTags([]);
|
||||
};
|
||||
|
||||
const ref = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
useClickOutside(ref, () => {
|
||||
setActive(false);
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
onChange(tags);
|
||||
}, [tags]);
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)} ref={ref}>
|
||||
<div
|
||||
className={cn(
|
||||
'items-center h-[40px] rounded-full bg-liquid-lighter w-[40px] flex',
|
||||
'text-[18px] font-bold cursor-pointer select-none',
|
||||
'overflow-hidden',
|
||||
(active || tags.length > 0) &&
|
||||
'w-fit border-liquid-brightmain border-[1px] border-solid',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (!disabled) setActive(!active);
|
||||
}}
|
||||
>
|
||||
<div className="text-liquid-brightmain pl-[42px] pr-[16px] w-fit">
|
||||
{tags.length}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter icons */}
|
||||
<img
|
||||
src={iconFilter}
|
||||
className={cn(
|
||||
'absolute left-[8px] top-[8px] h-[24px] w-[24px] rotate-0 transition-all duration-300 pointer-events-none',
|
||||
)}
|
||||
/>
|
||||
<img
|
||||
src={iconFilterActive}
|
||||
className={cn(
|
||||
'absolute left-[8px] top-[8px] h-[24px] w-[24px] rotate-0 transition-all duration-300 pointer-events-none opacity-0',
|
||||
(active || tags.length > 0) && 'opacity-100',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Dropdown */}
|
||||
<div
|
||||
className={cn(
|
||||
'absolute rounded-[10px] bg-liquid-background w-[590px] left-0 top-[48px] z-50 transition-all duration-300',
|
||||
'grid overflow-hidden border-liquid-lighter border-[3px] border-solid',
|
||||
active
|
||||
? 'grid-rows-[1fr] opacity-100'
|
||||
: 'grid-rows-[0fr] opacity-0',
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden p-[8px]">
|
||||
<div className="overflow-y-scroll min-h-[130px] thin-scrollbar grid gap-[20px]">
|
||||
{/* Теги */}
|
||||
<div className="">
|
||||
<div className="grid grid-cols-[1fr,140px,130px] items-end gap-2">
|
||||
<Input
|
||||
name="articleTag"
|
||||
autocomplete="articleTag"
|
||||
className="max-w-[600px] "
|
||||
type="text"
|
||||
label="Теги"
|
||||
onChange={setTagInput}
|
||||
defaultState={tagInput}
|
||||
placeholder="arrays"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') addTag();
|
||||
}}
|
||||
/>
|
||||
<PrimaryButton
|
||||
onClick={addTag}
|
||||
text="Добавить"
|
||||
className="h-[40px] w-[140px]"
|
||||
/>
|
||||
<SecondaryButton
|
||||
onClick={resetTags}
|
||||
text="Сбросить"
|
||||
className="h-[40px] w-[130px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-[10px] mt-2 ">
|
||||
{tags.length == 0 ? (
|
||||
<div className="text-liquid-brightmain flex items-center justify-center w-full h-[50px]">
|
||||
Вы еще не добавили ни одного тега
|
||||
</div>
|
||||
) : (
|
||||
tags.map((tag) => (
|
||||
<div
|
||||
key={tag}
|
||||
className="flex items-center gap-1 bg-liquid-lighter px-3 py-1 rounded-full"
|
||||
>
|
||||
<span>{tag}</span>
|
||||
<button
|
||||
onClick={() => removeTag(tag)}
|
||||
className="text-liquid-red font-bold ml-[5px]"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
35
src/components/input/DateInput.tsx
Normal file
35
src/components/input/DateInput.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
// DateInput.tsx
|
||||
import React from 'react';
|
||||
|
||||
interface DateInputProps {
|
||||
label?: string;
|
||||
value?: string;
|
||||
defaultValue?: string;
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const DateInput: React.FC<DateInputProps> = ({
|
||||
label = 'Дата',
|
||||
value,
|
||||
defaultValue,
|
||||
onChange,
|
||||
className = '',
|
||||
}) => {
|
||||
return (
|
||||
<div className={`flex flex-col gap-1 ${className}`}>
|
||||
<label className="block text-sm font-medium text-liquid-white">
|
||||
{label}
|
||||
</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={value}
|
||||
defaultValue={defaultValue}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="mt-1 block w-full rounded-[10px] sm:text-sm outline-none p-[8px] text-liquid-white cursor-text bg-liquid-lighter"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DateInput;
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { cn } from '../../lib/cn';
|
||||
import { checkMark, chevroneDropDownList } from '../../assets/icons/input';
|
||||
import { useClickOutside } from '../../hooks/useClickOutside';
|
||||
@@ -14,6 +14,7 @@ interface DropDownListProps {
|
||||
onChange: (state: string) => void;
|
||||
defaultState?: DropDownListItem;
|
||||
items: DropDownListItem[];
|
||||
weight?: string;
|
||||
}
|
||||
|
||||
export const DropDownList: React.FC<DropDownListProps> = ({
|
||||
@@ -22,6 +23,7 @@ export const DropDownList: React.FC<DropDownListProps> = ({
|
||||
onChange,
|
||||
defaultState,
|
||||
items = [{ text: '', value: '' }],
|
||||
weight = 'w-[180px]',
|
||||
}) => {
|
||||
if (items.length == 0) items.push({ text: '', value: '' });
|
||||
|
||||
@@ -30,21 +32,24 @@ export const DropDownList: React.FC<DropDownListProps> = ({
|
||||
);
|
||||
const [active, setActive] = React.useState<boolean>(false);
|
||||
|
||||
React.useEffect(() => onChange(value.value), [value]);
|
||||
|
||||
const ref = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
useClickOutside(ref, () => {
|
||||
setActive(false);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setValue(defaultState != undefined ? defaultState : items[0]);
|
||||
}, [defaultState]);
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)} ref={ref}>
|
||||
<div
|
||||
className={cn(
|
||||
' flex items-center h-[40px] rounded-[10px] bg-liquid-lighter px-[16px] w-[180px]',
|
||||
' flex items-center h-[40px] rounded-[10px] bg-liquid-lighter px-[16px]',
|
||||
'text-[18px] font-bold cursor-pointer select-none',
|
||||
'transitin-all active:scale-95 duration-300',
|
||||
weight,
|
||||
)}
|
||||
onClick={() => {
|
||||
setActive(!active);
|
||||
@@ -56,21 +61,22 @@ export const DropDownList: React.FC<DropDownListProps> = ({
|
||||
<img
|
||||
src={chevroneDropDownList}
|
||||
className={cn(
|
||||
' absolute right-[16px] h-[24px] w-[24px] top-[8.5px] rotate-0 transition-all duration-300 pointer-events-none',
|
||||
' absolute right-[16px] h-[24px] w-[24px] top-[8.5px] rotate-0 transition-all duration-300 pointer-events-none select-none',
|
||||
active && ' rotate-180',
|
||||
)}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
' absolute rounded-[10px] bg-liquid-lighter w-[180px] left-0 top-[48px] z-50 transition-all duration-300',
|
||||
' absolute rounded-[10px] bg-liquid-lighter left-0 top-[48px] z-50 transition-all duration-300',
|
||||
'grid overflow-hidden',
|
||||
weight,
|
||||
active
|
||||
? 'grid-rows-[1fr] opacity-100'
|
||||
: 'grid-rows-[0fr] opacity-0',
|
||||
)}
|
||||
>
|
||||
<div className=" overflow-hidden p-[8px]">
|
||||
<div className=" overflow-hidden p-[8px] border-liquid-background border-solid border-[1px] rounded-[10px]">
|
||||
<div
|
||||
className={cn(
|
||||
' overflow-y-scroll max-h-[200px] thin-scrollbar pr-[8px] ',
|
||||
@@ -89,6 +95,7 @@ export const DropDownList: React.FC<DropDownListProps> = ({
|
||||
)}
|
||||
onClick={() => {
|
||||
setValue(v);
|
||||
onChange(v.value);
|
||||
setActive(false);
|
||||
}}
|
||||
>
|
||||
@@ -11,6 +11,7 @@ interface inputProps {
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
inputClassName?: string;
|
||||
onChange: (state: string) => void;
|
||||
defaultState?: string;
|
||||
autocomplete?: string;
|
||||
@@ -25,6 +26,7 @@ export const Input: React.FC<inputProps> = ({
|
||||
label = '',
|
||||
placeholder = '',
|
||||
className = '',
|
||||
inputClassName = '',
|
||||
onChange,
|
||||
defaultState = '',
|
||||
name = '',
|
||||
@@ -52,10 +54,11 @@ export const Input: React.FC<inputProps> = ({
|
||||
className={cn(
|
||||
'bg-liquid-lighter w-full rounded-[10px] outline-none pl-[16px] py-[8px] placeholder:text-liquid-light',
|
||||
type == 'password' ? 'h-[40px]' : 'h-[36px]',
|
||||
inputClassName,
|
||||
)}
|
||||
value={value}
|
||||
name={name}
|
||||
autoComplete={autocomplete}
|
||||
autoComplete={autocomplete || undefined}
|
||||
type={
|
||||
type == 'password'
|
||||
? visible
|
||||
@@ -84,7 +87,7 @@ export const Input: React.FC<inputProps> = ({
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'text-liquid-red text-[14px] h-[18px] text-right mt-[5px]',
|
||||
'text-liquid-red text-[14px] h-auto text-right mt-[5px] whitespace-pre-line ',
|
||||
error == '' && 'h-0 mt-0',
|
||||
)}
|
||||
>
|
||||
|
||||
73
src/components/input/NumberInput.tsx
Normal file
73
src/components/input/NumberInput.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import React from 'react';
|
||||
import { cn } from '../../lib/cn';
|
||||
|
||||
interface NumberInputProps {
|
||||
name?: string;
|
||||
error?: string;
|
||||
disabled?: boolean;
|
||||
required?: boolean;
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
minValue?: number;
|
||||
maxValue?: number;
|
||||
onChange: (state: number) => void;
|
||||
defaultState?: number;
|
||||
}
|
||||
|
||||
export const NumberInput: React.FC<NumberInputProps> = ({
|
||||
error = '',
|
||||
// disabled = false,
|
||||
// required = false,
|
||||
label = '',
|
||||
placeholder = '',
|
||||
className = '',
|
||||
onChange,
|
||||
defaultState = 0,
|
||||
minValue = 0,
|
||||
maxValue = 365 * 24,
|
||||
name = '',
|
||||
}) => {
|
||||
const [value, setValue] = React.useState<number>(defaultState);
|
||||
|
||||
React.useEffect(() => onChange(value), [value]);
|
||||
React.useEffect(() => setValue(defaultState), [defaultState]);
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<div
|
||||
className={cn(
|
||||
'text-[18px] text-liquid-white font-medium h-[23px] mb-[10px] transition-all',
|
||||
label == '' && 'h-0 mb-0',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</div>
|
||||
<div className="relative pr-[5px]">
|
||||
<input
|
||||
className={cn(
|
||||
'bg-liquid-lighter w-full rounded-[10px] outline-none pl-[16px] pr-[8px] py-[8px] placeholder:text-liquid-light',
|
||||
)}
|
||||
value={value}
|
||||
name={name}
|
||||
type={'number'}
|
||||
min={minValue}
|
||||
max={maxValue}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => {
|
||||
setValue(Number(e.target.value));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'text-liquid-red text-[14px] h-auto text-right mt-[5px] whitespace-pre-line ',
|
||||
error == '' && 'h-0 mt-0',
|
||||
)}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
62
src/components/modal/ConfirmModal.tsx
Normal file
62
src/components/modal/ConfirmModal.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { FC } from 'react';
|
||||
import { Modal } from './Modal';
|
||||
import { PrimaryButton } from '../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../components/button/SecondaryButton';
|
||||
import { cn } from '../../lib/cn';
|
||||
|
||||
interface ConfirmModalProps {
|
||||
active: boolean;
|
||||
setActive: (value: boolean) => void;
|
||||
onConfirmClick: () => void;
|
||||
title?: string;
|
||||
message?: string;
|
||||
confirmColor?: 'primary' | 'secondary' | 'error' | 'warning' | 'success';
|
||||
confirmText?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const ConfirmModal: FC<ConfirmModalProps> = ({
|
||||
active,
|
||||
setActive,
|
||||
onConfirmClick,
|
||||
title,
|
||||
message,
|
||||
confirmColor = 'secondary',
|
||||
confirmText = 'Ок',
|
||||
className,
|
||||
}) => {
|
||||
return (
|
||||
<Modal
|
||||
className={cn(
|
||||
'bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white',
|
||||
className,
|
||||
)}
|
||||
onOpenChange={setActive}
|
||||
open={active}
|
||||
backdrop="blur"
|
||||
>
|
||||
<div className="w-[500px]">
|
||||
<div className="font-bold text-[30px]">{title}</div>
|
||||
<div className="font-bold text-[20px] mt-[20px]">{message}</div>
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
onConfirmClick();
|
||||
setActive(false);
|
||||
}}
|
||||
text={confirmText}
|
||||
color={confirmColor}
|
||||
/>
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
setActive(false);
|
||||
}}
|
||||
text="Отмена"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConfirmModal;
|
||||
@@ -47,7 +47,7 @@ export const Modal: React.FC<ModalProps> = ({
|
||||
exit={modalbgVariants.closed}
|
||||
transition={{ duration: 0.15 }}
|
||||
className={cn(
|
||||
' fixed top-0 left-0 h-svh w-svw backdrop-filter transition-all z-50',
|
||||
' fixed top-0 left-0 h-svh w-svw backdrop-filter transition-[background-color,backdrop-filter,opacity] z-50',
|
||||
backdrop == 'blur' && open && 'backdrop-blur-sm',
|
||||
backdrop == 'opaque' &&
|
||||
open &&
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from '../redux/slices/articles';
|
||||
import { useQuery } from '../hooks/useQuery';
|
||||
import { ReverseButton } from '../components/button/ReverseButton';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const ArticleEditor = () => {
|
||||
const navigate = useNavigate();
|
||||
@@ -24,6 +25,7 @@ const ArticleEditor = () => {
|
||||
const back = query.get('back') ?? undefined;
|
||||
const articleId = Number(query.get('articleId') ?? undefined);
|
||||
const refactor = articleId && !isNaN(articleId);
|
||||
const [clickSubmit, setClickSubmit] = useState<boolean>(false);
|
||||
|
||||
// Достаём данные из redux
|
||||
const article = useAppSelector(
|
||||
@@ -61,7 +63,6 @@ const ArticleEditor = () => {
|
||||
const removeTag = (tagToRemove: string) => {
|
||||
setTags(tags.filter((tag) => tag !== tagToRemove));
|
||||
};
|
||||
|
||||
// ==========================
|
||||
// Эффекты по статусам
|
||||
// ==========================
|
||||
@@ -96,6 +97,7 @@ const ArticleEditor = () => {
|
||||
// Получение статьи
|
||||
// ==========================
|
||||
useEffect(() => {
|
||||
setClickSubmit(false);
|
||||
if (articleId) {
|
||||
dispatch(fetchArticleById(articleId));
|
||||
}
|
||||
@@ -110,6 +112,18 @@ const ArticleEditor = () => {
|
||||
}
|
||||
}, [article]);
|
||||
|
||||
const getNameErrorMessage = (): string => {
|
||||
if (!clickSubmit) return '';
|
||||
if (name == '') return 'Поле не может быть пустым';
|
||||
return '';
|
||||
};
|
||||
|
||||
const getContentErrorMessage = (): string => {
|
||||
if (!clickSubmit) return '';
|
||||
if (code == '') return 'Поле не может быть пустым';
|
||||
return '';
|
||||
};
|
||||
|
||||
// ==========================
|
||||
// Рендер
|
||||
// ==========================
|
||||
@@ -137,6 +151,7 @@ const ArticleEditor = () => {
|
||||
<div className="flex gap-[20px]">
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
setClickSubmit(true);
|
||||
dispatch(
|
||||
updateArticle({
|
||||
articleId,
|
||||
@@ -163,6 +178,7 @@ const ArticleEditor = () => {
|
||||
) : (
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
setClickSubmit(true);
|
||||
dispatch(
|
||||
createArticle({
|
||||
name,
|
||||
@@ -188,6 +204,7 @@ const ArticleEditor = () => {
|
||||
label="Название"
|
||||
onChange={setName}
|
||||
placeholder="Новая статья"
|
||||
error={getNameErrorMessage()}
|
||||
/>
|
||||
|
||||
{/* Теги */}
|
||||
@@ -236,6 +253,14 @@ const ArticleEditor = () => {
|
||||
text="Редактировать текст"
|
||||
className="mt-[20px]"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'text-liquid-red text-[14px] h-auto mt-[5px] whitespace-pre-line ',
|
||||
getContentErrorMessage() == '' && 'h-0 mt-0',
|
||||
)}
|
||||
>
|
||||
{getContentErrorMessage()}
|
||||
</div>
|
||||
<MarkdownPreview
|
||||
content={code}
|
||||
className="bg-transparent border-liquid-lighter border-[3px] rounded-[20px] mt-[20px]"
|
||||
|
||||
@@ -10,17 +10,82 @@ import {
|
||||
setContestStatus,
|
||||
updateContest,
|
||||
} from '../redux/slices/contests';
|
||||
import DateRangeInput from '../components/input/DateRangeInput';
|
||||
import { useQuery } from '../hooks/useQuery';
|
||||
import { Navigate, useNavigate } from 'react-router-dom';
|
||||
import { fetchMissionById } from '../redux/slices/missions';
|
||||
import { fetchMissionById, fetchMissions } from '../redux/slices/missions';
|
||||
import { ReverseButton } from '../components/button/ReverseButton';
|
||||
import {
|
||||
DropDownList,
|
||||
DropDownListItem,
|
||||
} from '../components/input/DropDownList';
|
||||
import { NumberInput } from '../components/input/NumberInput';
|
||||
import { cn } from '../lib/cn';
|
||||
import DateInput from '../components/input/DateInput';
|
||||
import { fetchMyGroups } from '../redux/slices/groups';
|
||||
|
||||
interface Mission {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const highlightZ = (name: string, filter: string) => {
|
||||
if (!filter) return name;
|
||||
|
||||
const s = filter.toLowerCase();
|
||||
const t = name.toLowerCase();
|
||||
const n = t.length;
|
||||
const m = s.length;
|
||||
|
||||
const mark = Array(n).fill(false);
|
||||
|
||||
// Проходимся с конца и ставим отметки
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
if (i + m <= n && t.slice(i, i + m) === s) {
|
||||
for (let j = i; j < i + m; j++) {
|
||||
if (mark[j]) break;
|
||||
mark[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Формируем единые жёлтые блоки ===
|
||||
const result: any[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < n) {
|
||||
if (!mark[i]) {
|
||||
// обычный символ
|
||||
result.push(name[i]);
|
||||
i++;
|
||||
} else {
|
||||
// начинаем жёлтый блок
|
||||
let j = i;
|
||||
while (j < n && mark[j]) j++;
|
||||
|
||||
const chunk = name.slice(i, j);
|
||||
result.push(
|
||||
<span key={i} className="bg-yellow-400 text-black rounded px-1">
|
||||
{chunk}
|
||||
</span>,
|
||||
);
|
||||
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
function toUtc(localDateTime?: string): string {
|
||||
if (!localDateTime) return '';
|
||||
|
||||
// Создаём дату (она автоматически считается как локальная)
|
||||
const date = new Date(localDateTime);
|
||||
|
||||
// Возвращаем ISO-строку с 'Z' (всегда в UTC)
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Страница создания / редактирования контеста
|
||||
*/
|
||||
@@ -41,22 +106,42 @@ const ContestEditor = () => {
|
||||
(state) => state.contests.createContest.status,
|
||||
);
|
||||
|
||||
const [missionIdInput, setMissionIdInput] = useState<string>('');
|
||||
const [missionFindInput, setMissionFindInput] = useState<string>('');
|
||||
|
||||
const now = new Date();
|
||||
const plus60 = new Date(now.getTime() + 60 * 60 * 1000);
|
||||
|
||||
const toLocal = (d: Date) => {
|
||||
const off = d.getTimezoneOffset();
|
||||
const local = new Date(d.getTime() - off * 60000);
|
||||
return local.toISOString().slice(0, 16);
|
||||
};
|
||||
|
||||
const visibilityItems: DropDownListItem[] = [
|
||||
{ value: 'Public', text: 'Публичный' },
|
||||
{ value: 'GroupPrivate', text: 'Для группы' },
|
||||
];
|
||||
|
||||
const scheduleTypeItems: DropDownListItem[] = [
|
||||
{ value: 'AlwaysOpen', text: 'Всегда открыт' },
|
||||
{ value: 'FixedWindow', text: 'Фиксированое окно' },
|
||||
{ value: 'RollingWindow', text: 'Скользящее окно' },
|
||||
];
|
||||
|
||||
const [contest, setContest] = useState<CreateContestBody>({
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
startsAt: toLocal(now),
|
||||
endsAt: toLocal(plus60),
|
||||
attemptDurationMinutes: 60,
|
||||
maxAttempts: 1,
|
||||
allowEarlyFinish: true,
|
||||
allowEarlyFinish: false,
|
||||
missionIds: [],
|
||||
articleIds: [],
|
||||
});
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
const [missions, setMissions] = useState<Mission[]>([]);
|
||||
|
||||
const statusDelete = useAppSelector(
|
||||
@@ -69,6 +154,30 @@ const ContestEditor = () => {
|
||||
const { contest: contestById, status: contestByIdstatus } = useAppSelector(
|
||||
(state) => state.contests.fetchContestById,
|
||||
);
|
||||
|
||||
const globalMissions = useAppSelector((state) => state.missions.missions);
|
||||
|
||||
const myGroups = useAppSelector(
|
||||
(state) => state.groups.fetchMyGroups.groups,
|
||||
).filter((group) =>
|
||||
group.members.some(
|
||||
(member) =>
|
||||
member.username === myname &&
|
||||
member.role.includes('Administrator'),
|
||||
),
|
||||
);
|
||||
|
||||
function toLocalInputValue(utcString: string) {
|
||||
const d = new Date(utcString);
|
||||
|
||||
const pad = (n: number) => n.toString().padStart(2, '0');
|
||||
|
||||
return (
|
||||
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
|
||||
`T${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (status === 'successful') {
|
||||
}
|
||||
@@ -79,7 +188,14 @@ const ContestEditor = () => {
|
||||
};
|
||||
|
||||
const handleUpdateContest = () => {
|
||||
dispatch(updateContest({ ...contest, contestId }));
|
||||
dispatch(
|
||||
updateContest({
|
||||
...contest,
|
||||
endsAt: toUtc(contest.endsAt),
|
||||
startsAt: toUtc(contest.startsAt),
|
||||
contestId,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const handleDeleteContest = () => {
|
||||
@@ -87,7 +203,15 @@ const ContestEditor = () => {
|
||||
};
|
||||
|
||||
const addMission = () => {
|
||||
const id = Number(missionIdInput.trim());
|
||||
const mission = globalMissions
|
||||
.filter((v) => !contest?.missionIds?.includes(v.id))
|
||||
.filter((v) =>
|
||||
(v.id + ' ' + v.name)
|
||||
.toLocaleLowerCase()
|
||||
.includes(missionFindInput.toLocaleLowerCase()),
|
||||
)[0];
|
||||
if (!mission) return;
|
||||
const id = mission.id;
|
||||
if (!id || contest.missionIds?.includes(id)) return;
|
||||
dispatch(fetchMissionById(id))
|
||||
.unwrap()
|
||||
@@ -97,9 +221,11 @@ const ContestEditor = () => {
|
||||
...prev,
|
||||
missionIds: [...(prev.missionIds ?? []), id],
|
||||
}));
|
||||
setMissionIdInput('');
|
||||
setMissionFindInput('');
|
||||
})
|
||||
.catch((err) => {});
|
||||
.catch((err) => {
|
||||
err;
|
||||
});
|
||||
};
|
||||
|
||||
const removeMission = (removeId: number) => {
|
||||
@@ -131,6 +257,8 @@ const ContestEditor = () => {
|
||||
useEffect(() => {
|
||||
if (refactor) {
|
||||
dispatch(fetchContestById(contestId));
|
||||
dispatch(fetchMyGroups());
|
||||
dispatch(fetchMissions({}));
|
||||
}
|
||||
}, [refactor]);
|
||||
|
||||
@@ -143,13 +271,32 @@ const ContestEditor = () => {
|
||||
articleIds: contestById.articles?.map(
|
||||
(article) => article.articleId,
|
||||
),
|
||||
visibility: 'Public',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
});
|
||||
setMissions(contestById.missions ?? []);
|
||||
}
|
||||
}, [contestById]);
|
||||
|
||||
const visibilityDefaultState =
|
||||
visibilityItems.find(
|
||||
(i) => contest && i.value === contest.visibility,
|
||||
) ?? visibilityItems[0];
|
||||
|
||||
const scheduleTypeDefaultState =
|
||||
scheduleTypeItems.find(
|
||||
(i) => contest && i.value === contest.scheduleType,
|
||||
) ?? scheduleTypeItems[0];
|
||||
|
||||
const groupItems = myGroups.map((v) => {
|
||||
return {
|
||||
value: '' + v.id,
|
||||
text: v.name,
|
||||
};
|
||||
});
|
||||
const groupIdDefaultState =
|
||||
myGroups.find((g) => g.id == contest?.groupId) ??
|
||||
myGroups[0] ??
|
||||
undefined;
|
||||
|
||||
return (
|
||||
<div className="h-screen grid grid-rows-[60px,1fr] text-liquid-white">
|
||||
<Header backClick={() => navigate(back || '/home/contests')} />
|
||||
@@ -190,73 +337,134 @@ const ContestEditor = () => {
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<div>
|
||||
<label className="block text-sm mb-1">
|
||||
Тип расписания
|
||||
Тип контеста
|
||||
</label>
|
||||
<select
|
||||
className="w-full p-2 rounded-md bg-liquid-darker border border-liquid-lighter"
|
||||
value={contest.scheduleType}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'scheduleType',
|
||||
e.target
|
||||
.value as CreateContestBody['scheduleType'],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="AlwaysOpen">
|
||||
Всегда открыт
|
||||
</option>
|
||||
<option value="FixedWindow">
|
||||
Фиксированные даты
|
||||
</option>
|
||||
<option value="RollingWindow">
|
||||
Скользящее окно
|
||||
</option>
|
||||
</select>
|
||||
|
||||
<DropDownList
|
||||
items={scheduleTypeItems}
|
||||
defaultState={scheduleTypeDefaultState}
|
||||
onChange={(v) => {
|
||||
handleChange('scheduleType', v);
|
||||
}}
|
||||
weight="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm mb-1">
|
||||
Видимость
|
||||
</label>
|
||||
<select
|
||||
className="w-full p-2 rounded-md bg-liquid-darker border border-liquid-lighter"
|
||||
value={contest.visibility}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'visibility',
|
||||
e.target
|
||||
.value as CreateContestBody['visibility'],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="Public">
|
||||
Публичный
|
||||
</option>
|
||||
<option value="GroupPrivate">
|
||||
Групповой
|
||||
</option>
|
||||
</select>
|
||||
<DropDownList
|
||||
items={visibilityItems}
|
||||
onChange={(v) => {
|
||||
handleChange('visibility', v);
|
||||
}}
|
||||
defaultState={visibilityDefaultState}
|
||||
weight="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Даты начала и конца */}
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<DateRangeInput
|
||||
startValue={contest.startsAt || ''}
|
||||
endValue={contest.endsAt || ''}
|
||||
onChange={handleChange}
|
||||
className="mt-[10px]"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
' grid grid-flow-row grid-rows-[0fr] opacity-0 transition-all duration-200 mb-[10px]',
|
||||
contest.visibility == 'GroupPrivate' &&
|
||||
'grid-rows-[1fr] opacity-100',
|
||||
)}
|
||||
>
|
||||
{groupIdDefaultState ? (
|
||||
<div
|
||||
className={cn(
|
||||
contest.visibility !=
|
||||
'GroupPrivate' &&
|
||||
'overflow-hidden',
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
<label className="block text-sm mb-2 mt-[10px]">
|
||||
Группа для привязки
|
||||
</label>
|
||||
|
||||
<DropDownList
|
||||
items={groupItems}
|
||||
defaultState={{
|
||||
value:
|
||||
'' +
|
||||
groupIdDefaultState.id,
|
||||
text: groupIdDefaultState.name,
|
||||
}}
|
||||
onChange={(v) => {
|
||||
handleChange(
|
||||
'groupId',
|
||||
Number(v),
|
||||
);
|
||||
}}
|
||||
weight="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-hidden">
|
||||
<div className="text-liquid-red my-[20px]">
|
||||
У вас нет группы вкоторой вы
|
||||
являетесь Администратором!
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Даты */}
|
||||
<div
|
||||
className={cn(
|
||||
' grid grid-flow-row grid-rows-[0fr] opacity-0 transition-all duration-200',
|
||||
contest.scheduleType != 'AlwaysOpen' &&
|
||||
'grid-rows-[1fr] opacity-100',
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<DateInput
|
||||
label="Дата начала"
|
||||
value={
|
||||
contest.startsAt
|
||||
? toLocalInputValue(
|
||||
contest.startsAt,
|
||||
)
|
||||
: ''
|
||||
}
|
||||
onChange={(v) =>
|
||||
handleChange('startsAt', v)
|
||||
}
|
||||
/>
|
||||
|
||||
<DateInput
|
||||
label="Дата окончания"
|
||||
value={
|
||||
contest.endsAt
|
||||
? toLocalInputValue(
|
||||
contest.endsAt,
|
||||
)
|
||||
: ''
|
||||
}
|
||||
onChange={(v) =>
|
||||
handleChange('endsAt', v)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Продолжительность и лимиты */}
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<Input
|
||||
<NumberInput
|
||||
defaultState={
|
||||
contest.attemptDurationMinutes
|
||||
}
|
||||
name="attemptDurationMinutes"
|
||||
type="number"
|
||||
label="Длительность попытки (мин)"
|
||||
placeholder="Например: 60"
|
||||
minValue={1}
|
||||
maxValue={365 * 24 * 60}
|
||||
onChange={(v) =>
|
||||
handleChange(
|
||||
'attemptDurationMinutes',
|
||||
@@ -264,35 +472,19 @@ const ContestEditor = () => {
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
<NumberInput
|
||||
defaultState={contest.maxAttempts}
|
||||
name="maxAttempts"
|
||||
type="number"
|
||||
label="Макс. попыток"
|
||||
placeholder="Например: 3"
|
||||
minValue={1}
|
||||
maxValue={100}
|
||||
onChange={(v) =>
|
||||
handleChange('maxAttempts', Number(v))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Разрешить раннее завершение */}
|
||||
<div className="flex items-center gap-[10px] mt-[15px]">
|
||||
<input
|
||||
id="allowEarlyFinish"
|
||||
type="checkbox"
|
||||
checked={!!contest.allowEarlyFinish}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'allowEarlyFinish',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label htmlFor="allowEarlyFinish">
|
||||
Разрешить раннее завершение
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Кнопки */}
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
<PrimaryButton
|
||||
@@ -312,24 +504,22 @@ const ContestEditor = () => {
|
||||
</div>
|
||||
|
||||
{/* Правая панель */}
|
||||
<div className="overflow-y-auto min-h-0 overflow-hidden">
|
||||
<div className="min-h-0 ">
|
||||
<div className="p-4 border-r border-gray-700 flex flex-col h-full">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-100"></h2>
|
||||
|
||||
{/* Блок для тегов */}
|
||||
<div className="mt-[20px] max-w-[600px]">
|
||||
<div className="mt-[20px] max-w-[600px] relative">
|
||||
<div className="grid grid-cols-[1fr,140px] items-end gap-2">
|
||||
<Input
|
||||
name="missionId"
|
||||
autocomplete="missionId"
|
||||
className="mt-[20px] max-w-[600px]"
|
||||
type="number"
|
||||
label="ID миссии"
|
||||
label="Введите название или ID миссии"
|
||||
type="text"
|
||||
onChange={(v) => {
|
||||
setMissionIdInput(v);
|
||||
setMissionFindInput(v);
|
||||
}}
|
||||
defaultState={missionIdInput}
|
||||
placeholder="458"
|
||||
defaultState={missionFindInput}
|
||||
placeholder={`Наприме: \"458\" или \"Поиск наименьшего\"`}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key == 'Enter') addMission();
|
||||
}}
|
||||
@@ -339,18 +529,70 @@ const ContestEditor = () => {
|
||||
text="Добавить"
|
||||
className="h-[40px] w-[140px]"
|
||||
/>
|
||||
|
||||
{/* Выпадающие задачи */}
|
||||
<div
|
||||
className={cn(
|
||||
'absolute rounded-[10px] bg-liquid-background w-[590px] left-0 top-[100px] z-50 transition-all duration-300',
|
||||
'grid overflow-hidden border-liquid-lighter border-[3px] border-solid',
|
||||
missionFindInput
|
||||
? 'grid-rows-[1fr] opacity-100'
|
||||
: 'grid-rows-[0fr] opacity-0 pointer-events-none',
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden p-[8px]">
|
||||
<div className="overflow-y-scroll max-h-[250px] thin-scrollbar grid gap-[20px]">
|
||||
{globalMissions
|
||||
.filter(
|
||||
(v) =>
|
||||
!contest?.missionIds?.includes(
|
||||
v.id,
|
||||
),
|
||||
)
|
||||
.filter((v) =>
|
||||
(v.id + ' ' + v.name)
|
||||
.toLocaleLowerCase()
|
||||
.includes(
|
||||
missionFindInput.toLocaleLowerCase(),
|
||||
),
|
||||
)
|
||||
.map((v, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="hover:bg-liquid-lighter rounded-[10px] px-[12px] py-[4px] transition-colors duration-300 cursor-pointer"
|
||||
onClick={() => {
|
||||
setMissionFindInput(
|
||||
v.id +
|
||||
' ' +
|
||||
v.name,
|
||||
);
|
||||
addMission();
|
||||
}}
|
||||
>
|
||||
{highlightZ(
|
||||
'#' +
|
||||
v.id +
|
||||
' ' +
|
||||
v.name,
|
||||
missionFindInput,
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-[10px] mt-2">
|
||||
<div className="gap-[10px] mt-[20px]">
|
||||
{missions.map((v, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-center gap-1 bg-liquid-lighter px-3 py-1 rounded-full"
|
||||
className="grid grid-cols-[60px,1fr,24px] gap-1 bg-liquid-lighter px-[16px] py-[8px] rounded-[10px] relative mb-[10px] items-center"
|
||||
>
|
||||
<span>{v.id}</span>
|
||||
<span>{v.name}</span>
|
||||
<div>{'#' + v.id}</div>
|
||||
<div>{v.name}</div>
|
||||
<button
|
||||
onClick={() => removeMission(v.id)}
|
||||
className="text-liquid-red font-bold ml-[5px]"
|
||||
className="text-liquid-red font-bold ml-[5px] absolute right-[16px]"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
|
||||
@@ -1,32 +1,25 @@
|
||||
// src/pages/Home.tsx
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
import Login from '../views/home/auth/Login';
|
||||
import Register from '../views/home/auth/Register';
|
||||
import Menu from '../views/home/menu/Menu';
|
||||
import { useAppDispatch, useAppSelector } from '../redux/hooks';
|
||||
import { useEffect } from 'react';
|
||||
import { fetchWhoAmI, logout } from '../redux/slices/auth';
|
||||
import { fetchWhoAmI } from '../redux/slices/auth';
|
||||
import Missions from '../views/home/missions/Missions';
|
||||
import Articles from '../views/home/articles/Articles';
|
||||
import Groups from '../views/home/groups/Groups';
|
||||
import Contests from '../views/home/contests/Contests';
|
||||
import { PrimaryButton } from '../components/button/PrimaryButton';
|
||||
import Group from '../views/home/group/Group';
|
||||
import Contest from '../views/home/contest/Contest';
|
||||
import Account from '../views/home/account/Account';
|
||||
import ProtectedRoute from '../components/router/ProtectedRoute';
|
||||
import { MissionsRightPanel } from '../views/home/rightpanel/Missions';
|
||||
import { ArticlesRightPanel } from '../views/home/rightpanel/Articles';
|
||||
import { GroupRightPanel } from '../views/home/rightpanel/Group';
|
||||
import { GroupRightPanel } from '../views/home/rightpanel/group/Group';
|
||||
import GroupInvite from '../views/home/groupinviter/GroupInvite';
|
||||
import {
|
||||
toastError,
|
||||
toastSuccess,
|
||||
toastWarning,
|
||||
} from '../lib/toastNotification';
|
||||
|
||||
const Home = () => {
|
||||
const name = useAppSelector((state) => state.auth.username);
|
||||
const jwt = useAppSelector((state) => state.auth.jwt);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
@@ -59,53 +52,7 @@ const Home = () => {
|
||||
<Route path="contest/:contestId/*" element={<Contest />} />
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
<p>{jwt}</p>
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
if (jwt) {
|
||||
navigator.clipboard.writeText(jwt);
|
||||
alert(jwt);
|
||||
}
|
||||
}}
|
||||
text="скопировать токен"
|
||||
className="pt-[20px]"
|
||||
/>
|
||||
<p className="py-[20px]">{name}</p>
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
dispatch(logout());
|
||||
}}
|
||||
>
|
||||
выйти
|
||||
</PrimaryButton>
|
||||
|
||||
<div className="flex mt-[20px] gap-[20px]">
|
||||
<PrimaryButton
|
||||
color="success"
|
||||
text="Toast"
|
||||
onClick={() => {
|
||||
toastSuccess('Success');
|
||||
}}
|
||||
/>
|
||||
<PrimaryButton
|
||||
color="warning"
|
||||
text="Toast"
|
||||
onClick={() => {
|
||||
toastWarning('Warning');
|
||||
}}
|
||||
/>
|
||||
<PrimaryButton
|
||||
color="error"
|
||||
text="Toast"
|
||||
onClick={() => {
|
||||
toastError('Error');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
element={<Navigate to="/home/account" replace />}
|
||||
/>
|
||||
</Routes>
|
||||
</div>
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
import { useParams, Navigate } from 'react-router-dom';
|
||||
import { useParams, Navigate, useNavigate } from 'react-router-dom';
|
||||
import CodeEditor from '../views/mission/codeeditor/CodeEditor';
|
||||
import Statement from '../views/mission/statement/Statement';
|
||||
import { PrimaryButton } from '../components/button/PrimaryButton';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../redux/hooks';
|
||||
import { fetchMySubmitsByMission, submitMission } from '../redux/slices/submit';
|
||||
import { fetchMissionById } from '../redux/slices/missions';
|
||||
import { fetchMissionById, setMissionsStatus } from '../redux/slices/missions';
|
||||
import Header from '../views/mission/statement/Header';
|
||||
import MissionSubmissions from '../views/mission/statement/MissionSubmissions';
|
||||
import { useQuery } from '../hooks/useQuery';
|
||||
import { fetchMyAttemptsInContest } from '../redux/slices/contests';
|
||||
|
||||
const Mission = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Получаем параметры из URL
|
||||
const { missionId } = useParams<{ missionId: string }>();
|
||||
const mission = useAppSelector((state) => state.missions.currentMission);
|
||||
const missionStatus = useAppSelector(
|
||||
(state) => state.missions.statuses.fetchById,
|
||||
);
|
||||
const attempt = useAppSelector(
|
||||
(state) => state.contests.fetchMyAttemptsInContest.attempts[0],
|
||||
);
|
||||
|
||||
const missionIdNumber = Number(missionId);
|
||||
|
||||
const query = useQuery();
|
||||
@@ -40,6 +49,9 @@ const Mission = () => {
|
||||
if (pollingRef.current) return;
|
||||
|
||||
pollingRef.current = setInterval(async () => {
|
||||
if (contestId) {
|
||||
dispatch(fetchMyAttemptsInContest(contestId));
|
||||
}
|
||||
dispatch(fetchMySubmitsByMission(missionIdNumber));
|
||||
|
||||
const hasWaiting = submissionsRef.current.some(
|
||||
@@ -59,6 +71,12 @@ const Mission = () => {
|
||||
}, 5000); // 10 секунд
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (contestId) {
|
||||
dispatch(fetchMyAttemptsInContest(contestId));
|
||||
}
|
||||
}, [contestId]);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchMissionById(missionIdNumber));
|
||||
dispatch(fetchMySubmitsByMission(missionIdNumber));
|
||||
@@ -74,6 +92,12 @@ const Mission = () => {
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (missionStatus == 'failed') {
|
||||
setMissionsStatus({ key: 'fetchById', status: 'idle' });
|
||||
navigate(back ?? '/home/missions');
|
||||
}
|
||||
}, [missionStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
submissionsRef.current = submissions;
|
||||
@@ -184,7 +208,8 @@ const Mission = () => {
|
||||
language: language,
|
||||
languageVersion: 'latest',
|
||||
sourceCode: code,
|
||||
contestId: contestId,
|
||||
contestAttemptId:
|
||||
attempt?.attemptId,
|
||||
}),
|
||||
).unwrap();
|
||||
dispatch(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
// =====================
|
||||
// Типы
|
||||
@@ -33,6 +34,12 @@ interface ArticlesState {
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
fetchNewArticles: {
|
||||
articles: Article[];
|
||||
hasNextPage: boolean;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
fetchArticleById: {
|
||||
article?: Article;
|
||||
status: Status;
|
||||
@@ -66,6 +73,12 @@ const initialState: ArticlesState = {
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
fetchNewArticles: {
|
||||
articles: [],
|
||||
hasNextPage: false,
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
fetchArticleById: {
|
||||
article: undefined,
|
||||
status: 'idle',
|
||||
@@ -96,13 +109,13 @@ const initialState: ArticlesState = {
|
||||
// Async Thunks
|
||||
// =====================
|
||||
|
||||
// Все статьи
|
||||
export const fetchArticles = createAsyncThunk(
|
||||
'articles/fetchArticles',
|
||||
// Новые статьи
|
||||
export const fetchNewArticles = createAsyncThunk(
|
||||
'articles/fetchNewArticles',
|
||||
async (
|
||||
{
|
||||
page = 0,
|
||||
pageSize = 10,
|
||||
pageSize = 5,
|
||||
tags,
|
||||
}: { page?: number; pageSize?: number; tags?: string[] } = {},
|
||||
{ rejectWithValue },
|
||||
@@ -110,14 +123,46 @@ export const fetchArticles = createAsyncThunk(
|
||||
try {
|
||||
const params: any = { page, pageSize };
|
||||
if (tags && tags.length > 0) params.tags = tags;
|
||||
|
||||
const response = await axios.get<ArticlesResponse>('/articles', {
|
||||
params,
|
||||
paramsSerializer: {
|
||||
indexes: null,
|
||||
},
|
||||
});
|
||||
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при получении статей',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Все статьи
|
||||
export const fetchArticles = createAsyncThunk(
|
||||
'articles/fetchArticles',
|
||||
async (
|
||||
{
|
||||
page = 0,
|
||||
pageSize = 100,
|
||||
tags,
|
||||
}: { page?: number; pageSize?: number; tags?: string[] } = {},
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const params: any = { page, pageSize };
|
||||
if (tags && tags.length > 0) params.tags = tags;
|
||||
|
||||
const response = await axios.get<ArticlesResponse>('/articles', {
|
||||
params,
|
||||
paramsSerializer: {
|
||||
indexes: null,
|
||||
},
|
||||
});
|
||||
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -130,10 +175,7 @@ export const fetchMyArticles = createAsyncThunk(
|
||||
const response = await axios.get<Article[]>('/articles/my');
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message ||
|
||||
'Ошибка при получении моих статей',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -146,9 +188,7 @@ export const fetchArticleById = createAsyncThunk(
|
||||
const response = await axios.get<Article>(`/articles/${articleId}`);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при получении статьи',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -172,9 +212,7 @@ export const createArticle = createAsyncThunk(
|
||||
});
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при создании статьи',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -202,9 +240,7 @@ export const updateArticle = createAsyncThunk(
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при обновлении статьи',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -217,9 +253,7 @@ export const deleteArticle = createAsyncThunk(
|
||||
await axios.delete(`/articles/${articleId}`);
|
||||
return articleId;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при удалении статьи',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -258,7 +292,35 @@ const articlesSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchArticles.rejected, (state, action: any) => {
|
||||
state.fetchArticles.status = 'failed';
|
||||
state.fetchArticles.error = action.payload;
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchNewArticles
|
||||
builder.addCase(fetchNewArticles.pending, (state) => {
|
||||
state.fetchNewArticles.status = 'loading';
|
||||
state.fetchNewArticles.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchNewArticles.fulfilled,
|
||||
(state, action: PayloadAction<ArticlesResponse>) => {
|
||||
state.fetchNewArticles.status = 'successful';
|
||||
state.fetchNewArticles.articles = action.payload.articles;
|
||||
state.fetchNewArticles.hasNextPage = action.payload.hasNextPage;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchNewArticles.rejected, (state, action: any) => {
|
||||
state.fetchNewArticles.status = 'failed';
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchMyArticles
|
||||
@@ -275,7 +337,12 @@ const articlesSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchMyArticles.rejected, (state, action: any) => {
|
||||
state.fetchMyArticles.status = 'failed';
|
||||
state.fetchMyArticles.error = action.payload;
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchArticleById
|
||||
@@ -292,7 +359,12 @@ const articlesSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchArticleById.rejected, (state, action: any) => {
|
||||
state.fetchArticleById.status = 'failed';
|
||||
state.fetchArticleById.error = action.payload;
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// createArticle
|
||||
@@ -309,7 +381,14 @@ const articlesSlice = createSlice({
|
||||
);
|
||||
builder.addCase(createArticle.rejected, (state, action: any) => {
|
||||
state.createArticle.status = 'failed';
|
||||
state.createArticle.error = action.payload;
|
||||
state.createArticle.error = action.payload.title;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// updateArticle
|
||||
@@ -326,7 +405,14 @@ const articlesSlice = createSlice({
|
||||
);
|
||||
builder.addCase(updateArticle.rejected, (state, action: any) => {
|
||||
state.updateArticle.status = 'failed';
|
||||
state.updateArticle.error = action.payload;
|
||||
state.createArticle.error = action.payload.title;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// deleteArticle
|
||||
@@ -350,7 +436,12 @@ const articlesSlice = createSlice({
|
||||
);
|
||||
builder.addCase(deleteArticle.rejected, (state, action: any) => {
|
||||
state.deleteArticle.status = 'failed';
|
||||
state.deleteArticle.error = action.payload;
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
type Status = 'idle' | 'loading' | 'successful' | 'failed';
|
||||
|
||||
// 🔹 Декодирование JWT
|
||||
function decodeJwt(token: string) {
|
||||
@@ -15,8 +18,12 @@ interface AuthState {
|
||||
username: string | null;
|
||||
email: string | null;
|
||||
id: string | null;
|
||||
status: 'idle' | 'loading' | 'successful' | 'failed';
|
||||
status: Status;
|
||||
error: string | null;
|
||||
register: {
|
||||
errors?: Record<string, string[]>;
|
||||
status: Status;
|
||||
};
|
||||
}
|
||||
|
||||
// 🔹 Инициализация состояния с синхронной загрузкой из localStorage
|
||||
@@ -31,6 +38,9 @@ const initialState: AuthState = {
|
||||
id: null,
|
||||
status: 'idle',
|
||||
error: null,
|
||||
register: {
|
||||
status: 'idle',
|
||||
},
|
||||
};
|
||||
|
||||
// Если токен есть, подставляем в axios и декодируем
|
||||
@@ -76,9 +86,7 @@ export const registerUser = createAsyncThunk(
|
||||
});
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Registration failed',
|
||||
);
|
||||
return rejectWithValue(err.response?.data?.errors ? err.response?.data?.errors : {"error" : [err.response?.data]});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -165,6 +173,15 @@ const authSlice = createSlice({
|
||||
localStorage.removeItem('refreshToken');
|
||||
delete axios.defaults.headers.common['Authorization'];
|
||||
},
|
||||
setAuthStatus: (
|
||||
state,
|
||||
action: PayloadAction<{ key: keyof AuthState; status: Status }>,
|
||||
) => {
|
||||
const { key, status } = action.payload;
|
||||
if (state[key]) {
|
||||
(state[key] as any).status = status;
|
||||
}
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
// ----------------- Register -----------------
|
||||
@@ -199,7 +216,12 @@ const authSlice = createSlice({
|
||||
});
|
||||
builder.addCase(registerUser.rejected, (state, action) => {
|
||||
state.status = 'failed';
|
||||
state.error = action.payload as string;
|
||||
state.register.errors = action.payload as Record<string, string[]>;
|
||||
Object.values(state.register.errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ----------------- Login -----------------
|
||||
@@ -304,5 +326,5 @@ const authSlice = createSlice({
|
||||
},
|
||||
});
|
||||
|
||||
export const { logout } = authSlice.actions;
|
||||
export const { logout, setAuthStatus } = authSlice.actions;
|
||||
export const authReducer = authSlice.reducer;
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
// =====================
|
||||
// Типы
|
||||
// =====================
|
||||
|
||||
// =====================
|
||||
// Типы для посылок
|
||||
// =====================
|
||||
|
||||
export interface Solution {
|
||||
id: number;
|
||||
missionId: number;
|
||||
@@ -73,11 +70,26 @@ export interface Contest {
|
||||
members?: Member[];
|
||||
}
|
||||
|
||||
export interface Attempt {
|
||||
attemptId: number;
|
||||
contestId: number;
|
||||
startedAt: string;
|
||||
expiresAt: string;
|
||||
finished: boolean;
|
||||
submissions?: Submission[];
|
||||
results?: any[];
|
||||
}
|
||||
|
||||
interface ContestsResponse {
|
||||
hasNextPage: boolean;
|
||||
contests: Contest[];
|
||||
}
|
||||
|
||||
interface MembersPage {
|
||||
members: Member[];
|
||||
hasNextPage: boolean;
|
||||
}
|
||||
|
||||
export interface CreateContestBody {
|
||||
name: string;
|
||||
description?: string;
|
||||
@@ -142,94 +154,106 @@ interface ContestsState {
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
// NEW:
|
||||
fetchContestMembers: {
|
||||
members: Member[];
|
||||
hasNextPage: boolean;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
addOrUpdateMember: {
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
deleteContestMember: {
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
startAttempt: {
|
||||
attempt?: Attempt;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
fetchMyAttemptsInContest: {
|
||||
attempts: Attempt[];
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
fetchMyAllAttempts: {
|
||||
attempts: Attempt[];
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
fetchMyActiveAttempt: {
|
||||
attempt?: Attempt | null;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
checkRegistration: {
|
||||
registered: boolean;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
fetchUpcomingEligible: {
|
||||
contests: Contest[];
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
fetchParticipating: {
|
||||
contests: Contest[];
|
||||
hasNextPage: boolean;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const emptyContest: Contest = {
|
||||
id: 0,
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
attemptDurationMinutes: 0,
|
||||
maxAttempts: 0,
|
||||
allowEarlyFinish: false,
|
||||
missions: [],
|
||||
articles: [],
|
||||
members: [],
|
||||
};
|
||||
|
||||
const initialState: ContestsState = {
|
||||
fetchContests: {
|
||||
fetchContests: { contests: [], hasNextPage: false, status: 'idle' },
|
||||
fetchContestById: { contest: emptyContest, status: 'idle' },
|
||||
createContest: { contest: emptyContest, status: 'idle' },
|
||||
fetchMySubmissions: { submissions: [], status: 'idle' },
|
||||
updateContest: { contest: emptyContest, status: 'idle' },
|
||||
deleteContest: { status: 'idle' },
|
||||
fetchMyContests: { contests: [], status: 'idle' },
|
||||
fetchRegisteredContests: {
|
||||
contests: [],
|
||||
hasNextPage: false,
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
fetchContestById: {
|
||||
contest: {
|
||||
id: 0,
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
attemptDurationMinutes: 0,
|
||||
maxAttempts: 0,
|
||||
allowEarlyFinish: false,
|
||||
groupId: undefined,
|
||||
groupName: undefined,
|
||||
missions: [],
|
||||
articles: [],
|
||||
members: [],
|
||||
},
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
fetchMySubmissions: {
|
||||
submissions: [],
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
|
||||
createContest: {
|
||||
contest: {
|
||||
id: 0,
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
attemptDurationMinutes: 0,
|
||||
maxAttempts: 0,
|
||||
allowEarlyFinish: false,
|
||||
groupId: undefined,
|
||||
groupName: undefined,
|
||||
missions: [],
|
||||
articles: [],
|
||||
members: [],
|
||||
},
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
updateContest: {
|
||||
contest: {
|
||||
id: 0,
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
attemptDurationMinutes: 0,
|
||||
maxAttempts: 0,
|
||||
allowEarlyFinish: false,
|
||||
groupId: undefined,
|
||||
groupName: undefined,
|
||||
missions: [],
|
||||
articles: [],
|
||||
members: [],
|
||||
},
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
deleteContest: {
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
fetchMyContests: {
|
||||
contests: [],
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
fetchRegisteredContests: {
|
||||
fetchContestMembers: { members: [], hasNextPage: false, status: 'idle' },
|
||||
addOrUpdateMember: { status: 'idle' },
|
||||
deleteContestMember: { status: 'idle' },
|
||||
|
||||
startAttempt: { status: 'idle' },
|
||||
fetchMyAttemptsInContest: { attempts: [], status: 'idle' },
|
||||
fetchMyAllAttempts: { attempts: [], status: 'idle' },
|
||||
fetchMyActiveAttempt: { attempt: null, status: 'idle' },
|
||||
|
||||
checkRegistration: { registered: false, status: 'idle' },
|
||||
fetchUpcomingEligible: { contests: [], status: 'idle' },
|
||||
fetchParticipating: {
|
||||
contests: [],
|
||||
hasNextPage: false,
|
||||
status: 'idle',
|
||||
@@ -241,7 +265,27 @@ const initialState: ContestsState = {
|
||||
// Async Thunks
|
||||
// =====================
|
||||
|
||||
// Мои посылки в контесте
|
||||
// Existing ----------------------------
|
||||
|
||||
export const fetchParticipatingContests = createAsyncThunk(
|
||||
'contests/fetchParticipating',
|
||||
async (
|
||||
params: { page?: number; pageSize?: number } = {},
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const { page = 0, pageSize = 100 } = params;
|
||||
const response = await axios.get<ContestsResponse>(
|
||||
'/contests/participating',
|
||||
{ params: { page, pageSize } },
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const fetchMySubmissions = createAsyncThunk(
|
||||
'contests/fetchMySubmissions',
|
||||
async (contestId: number, { rejectWithValue }) => {
|
||||
@@ -251,14 +295,11 @@ export const fetchMySubmissions = createAsyncThunk(
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to fetch my submissions',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Все контесты
|
||||
export const fetchContests = createAsyncThunk(
|
||||
'contests/fetchAll',
|
||||
async (
|
||||
@@ -270,20 +311,17 @@ export const fetchContests = createAsyncThunk(
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const { page = 0, pageSize = 10, groupId } = params;
|
||||
const { page = 0, pageSize = 100, groupId } = params;
|
||||
const response = await axios.get<ContestsResponse>('/contests', {
|
||||
params: { page, pageSize, groupId },
|
||||
});
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to fetch contests',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Контест по ID
|
||||
export const fetchContestById = createAsyncThunk(
|
||||
'contests/fetchById',
|
||||
async (id: number, { rejectWithValue }) => {
|
||||
@@ -291,14 +329,11 @@ export const fetchContestById = createAsyncThunk(
|
||||
const response = await axios.get<Contest>(`/contests/${id}`);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to fetch contest',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Создание контеста
|
||||
export const createContest = createAsyncThunk(
|
||||
'contests/create',
|
||||
async (contestData: CreateContestBody, { rejectWithValue }) => {
|
||||
@@ -309,14 +344,11 @@ export const createContest = createAsyncThunk(
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to create contest',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 🆕 Обновление контеста
|
||||
export const updateContest = createAsyncThunk(
|
||||
'contests/update',
|
||||
async (
|
||||
@@ -333,14 +365,11 @@ export const updateContest = createAsyncThunk(
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to update contest',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 🆕 Удаление контеста
|
||||
export const deleteContest = createAsyncThunk(
|
||||
'contests/delete',
|
||||
async (contestId: number, { rejectWithValue }) => {
|
||||
@@ -348,14 +377,11 @@ export const deleteContest = createAsyncThunk(
|
||||
await axios.delete(`/contests/${contestId}`);
|
||||
return contestId;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to delete contest',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Контесты, созданные мной
|
||||
export const fetchMyContests = createAsyncThunk(
|
||||
'contests/fetchMyContests',
|
||||
async (_, { rejectWithValue }) => {
|
||||
@@ -363,14 +389,11 @@ export const fetchMyContests = createAsyncThunk(
|
||||
const response = await axios.get<Contest[]>('/contests/my');
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Failed to fetch my contests',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Контесты, где я зарегистрирован
|
||||
export const fetchRegisteredContests = createAsyncThunk(
|
||||
'contests/fetchRegisteredContests',
|
||||
async (
|
||||
@@ -378,17 +401,167 @@ export const fetchRegisteredContests = createAsyncThunk(
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const { page = 0, pageSize = 10 } = params;
|
||||
const { page = 0, pageSize = 100 } = params;
|
||||
const response = await axios.get<ContestsResponse>(
|
||||
'/contests/registered',
|
||||
{ params: { page, pageSize } },
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message ||
|
||||
'Failed to fetch registered contests',
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// NEW -----------------------------------
|
||||
|
||||
// Add or update member
|
||||
export const addOrUpdateContestMember = createAsyncThunk(
|
||||
'contests/addOrUpdateMember',
|
||||
async (
|
||||
{
|
||||
contestId,
|
||||
member,
|
||||
}: { contestId: number; member: { userId: number; role: string } },
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const response = await axios.post<Member[]>(
|
||||
`/contests/${contestId}/members`,
|
||||
member,
|
||||
);
|
||||
return { contestId, members: response.data };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Delete member
|
||||
export const deleteContestMember = createAsyncThunk(
|
||||
'contests/deleteContestMember',
|
||||
async (
|
||||
{ contestId, memberId }: { contestId: number; memberId: number },
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
await axios.delete(`/contests/${contestId}/members/${memberId}`);
|
||||
return { contestId, memberId };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Start attempt
|
||||
export const startContestAttempt = createAsyncThunk(
|
||||
'contests/startContestAttempt',
|
||||
async (contestId: number, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.post<Attempt>(
|
||||
`/contests/${contestId}/attempts`,
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// My attempts in contest
|
||||
export const fetchMyAttemptsInContest = createAsyncThunk(
|
||||
'contests/fetchMyAttemptsInContest',
|
||||
async (contestId: number, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.get<Attempt[]>(
|
||||
`/contests/${contestId}/attempts/my`,
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Members with pagination
|
||||
export const fetchContestMembers = createAsyncThunk(
|
||||
'contests/fetchContestMembers',
|
||||
async (
|
||||
{
|
||||
contestId,
|
||||
page = 0,
|
||||
pageSize = 100,
|
||||
}: { contestId: number; page?: number; pageSize?: number },
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const response = await axios.get<MembersPage>(
|
||||
`/contests/${contestId}/members`,
|
||||
{ params: { page, pageSize } },
|
||||
);
|
||||
return { contestId, ...response.data };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Check registration
|
||||
export const checkContestRegistration = createAsyncThunk(
|
||||
'contests/checkRegistration',
|
||||
async (contestId: number, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.get<{ registered: boolean }>(
|
||||
`/contests/${contestId}/registered`,
|
||||
);
|
||||
return { contestId, registered: response.data.registered };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Upcoming eligible contests
|
||||
export const fetchUpcomingEligibleContests = createAsyncThunk(
|
||||
'contests/fetchUpcomingEligible',
|
||||
async (_, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.get<Contest[]>(
|
||||
'/contests/upcoming/eligible',
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// All my attempts
|
||||
export const fetchMyAllAttempts = createAsyncThunk(
|
||||
'contests/fetchMyAllAttempts',
|
||||
async (_, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.get<Attempt[]>(
|
||||
'/contests/attempts/my',
|
||||
);
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Active attempt
|
||||
export const fetchMyActiveAttempt = createAsyncThunk(
|
||||
'contests/fetchMyActiveAttempt',
|
||||
async (contestId: number, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.get<Attempt | null>(
|
||||
`/contests/${contestId}/attempts/my/active`,
|
||||
);
|
||||
return { contestId, attempt: response.data };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -401,7 +574,6 @@ const contestsSlice = createSlice({
|
||||
name: 'contests',
|
||||
initialState,
|
||||
reducers: {
|
||||
// 🆕 Сброс статусов
|
||||
setContestStatus: (
|
||||
state,
|
||||
action: PayloadAction<{ key: keyof ContestsState; status: Status }>,
|
||||
@@ -413,7 +585,8 @@ const contestsSlice = createSlice({
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
// 🆕 fetchMySubmissions
|
||||
// ——— YOUR EXISTING HANDLERS (unchanged) ———
|
||||
|
||||
builder.addCase(fetchMySubmissions.pending, (state) => {
|
||||
state.fetchMySubmissions.status = 'loading';
|
||||
state.fetchMySubmissions.error = undefined;
|
||||
@@ -427,13 +600,17 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchMySubmissions.rejected, (state, action: any) => {
|
||||
state.fetchMySubmissions.status = 'failed';
|
||||
state.fetchMySubmissions.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchContests
|
||||
builder.addCase(fetchContests.pending, (state) => {
|
||||
state.fetchContests.status = 'loading';
|
||||
state.fetchContests.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchContests.fulfilled,
|
||||
@@ -445,13 +622,17 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchContests.rejected, (state, action: any) => {
|
||||
state.fetchContests.status = 'failed';
|
||||
state.fetchContests.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchContestById
|
||||
builder.addCase(fetchContestById.pending, (state) => {
|
||||
state.fetchContestById.status = 'loading';
|
||||
state.fetchContestById.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchContestById.fulfilled,
|
||||
@@ -462,13 +643,17 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchContestById.rejected, (state, action: any) => {
|
||||
state.fetchContestById.status = 'failed';
|
||||
state.fetchContestById.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// createContest
|
||||
builder.addCase(createContest.pending, (state) => {
|
||||
state.createContest.status = 'loading';
|
||||
state.createContest.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
createContest.fulfilled,
|
||||
@@ -479,13 +664,17 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(createContest.rejected, (state, action: any) => {
|
||||
state.createContest.status = 'failed';
|
||||
state.createContest.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 🆕 updateContest
|
||||
builder.addCase(updateContest.pending, (state) => {
|
||||
state.updateContest.status = 'loading';
|
||||
state.updateContest.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
updateContest.fulfilled,
|
||||
@@ -496,19 +685,22 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(updateContest.rejected, (state, action: any) => {
|
||||
state.updateContest.status = 'failed';
|
||||
state.updateContest.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 🆕 deleteContest
|
||||
builder.addCase(deleteContest.pending, (state) => {
|
||||
state.deleteContest.status = 'loading';
|
||||
state.deleteContest.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
deleteContest.fulfilled,
|
||||
(state, action: PayloadAction<number>) => {
|
||||
state.deleteContest.status = 'successful';
|
||||
// Удалим контест из списков
|
||||
state.fetchContests.contests =
|
||||
state.fetchContests.contests.filter(
|
||||
(c) => c.id !== action.payload,
|
||||
@@ -521,13 +713,17 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(deleteContest.rejected, (state, action: any) => {
|
||||
state.deleteContest.status = 'failed';
|
||||
state.deleteContest.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchMyContests
|
||||
builder.addCase(fetchMyContests.pending, (state) => {
|
||||
state.fetchMyContests.status = 'loading';
|
||||
state.fetchMyContests.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchMyContests.fulfilled,
|
||||
@@ -538,13 +734,17 @@ const contestsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchMyContests.rejected, (state, action: any) => {
|
||||
state.fetchMyContests.status = 'failed';
|
||||
state.fetchMyContests.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchRegisteredContests
|
||||
builder.addCase(fetchRegisteredContests.pending, (state) => {
|
||||
state.fetchRegisteredContests.status = 'loading';
|
||||
state.fetchRegisteredContests.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchRegisteredContests.fulfilled,
|
||||
@@ -560,7 +760,269 @@ const contestsSlice = createSlice({
|
||||
fetchRegisteredContests.rejected,
|
||||
(state, action: any) => {
|
||||
state.fetchRegisteredContests.status = 'failed';
|
||||
state.fetchRegisteredContests.error = action.payload;
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// NEW HANDLERS
|
||||
|
||||
builder.addCase(fetchContestMembers.pending, (state) => {
|
||||
state.fetchContestMembers.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
fetchContestMembers.fulfilled,
|
||||
(
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
contestId: number;
|
||||
members: Member[];
|
||||
hasNextPage: boolean;
|
||||
}>,
|
||||
) => {
|
||||
state.fetchContestMembers.status = 'successful';
|
||||
state.fetchContestMembers.members = action.payload.members;
|
||||
state.fetchContestMembers.hasNextPage =
|
||||
action.payload.hasNextPage;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchContestMembers.rejected, (state, action: any) => {
|
||||
state.fetchContestMembers.status = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
builder.addCase(addOrUpdateContestMember.pending, (state) => {
|
||||
state.addOrUpdateMember.status = 'loading';
|
||||
});
|
||||
builder.addCase(addOrUpdateContestMember.fulfilled, (state) => {
|
||||
state.addOrUpdateMember.status = 'successful';
|
||||
});
|
||||
builder.addCase(
|
||||
addOrUpdateContestMember.rejected,
|
||||
(state, action: any) => {
|
||||
state.addOrUpdateMember.status = 'failed';
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(deleteContestMember.pending, (state) => {
|
||||
state.deleteContestMember.status = 'loading';
|
||||
});
|
||||
builder.addCase(deleteContestMember.fulfilled, (state) => {
|
||||
state.deleteContestMember.status = 'successful';
|
||||
});
|
||||
builder.addCase(deleteContestMember.rejected, (state, action: any) => {
|
||||
state.deleteContestMember.status = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
builder.addCase(startContestAttempt.pending, (state) => {
|
||||
state.startAttempt.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
startContestAttempt.fulfilled,
|
||||
(state, action: PayloadAction<Attempt>) => {
|
||||
state.startAttempt.status = 'successful';
|
||||
state.startAttempt.attempt = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(startContestAttempt.rejected, (state, action: any) => {
|
||||
state.startAttempt.status = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
builder.addCase(fetchMyAttemptsInContest.pending, (state) => {
|
||||
state.fetchMyAttemptsInContest.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
fetchMyAttemptsInContest.fulfilled,
|
||||
(state, action: PayloadAction<Attempt[]>) => {
|
||||
state.fetchMyAttemptsInContest.status = 'successful';
|
||||
state.fetchMyAttemptsInContest.attempts = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(
|
||||
fetchMyAttemptsInContest.rejected,
|
||||
(state, action: any) => {
|
||||
state.fetchMyAttemptsInContest.status = 'failed';
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(fetchMyAllAttempts.pending, (state) => {
|
||||
state.fetchMyAllAttempts.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
fetchMyAllAttempts.fulfilled,
|
||||
(state, action: PayloadAction<Attempt[]>) => {
|
||||
state.fetchMyAllAttempts.status = 'successful';
|
||||
state.fetchMyAllAttempts.attempts = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchMyAllAttempts.rejected, (state, action: any) => {
|
||||
state.fetchMyAllAttempts.status = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
builder.addCase(fetchMyActiveAttempt.pending, (state) => {
|
||||
state.fetchMyActiveAttempt.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
fetchMyActiveAttempt.fulfilled,
|
||||
(
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
contestId: number;
|
||||
attempt: Attempt | null;
|
||||
}>,
|
||||
) => {
|
||||
state.fetchMyActiveAttempt.status = 'successful';
|
||||
state.fetchMyActiveAttempt.attempt = action.payload.attempt;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchMyActiveAttempt.rejected, (state, action: any) => {
|
||||
state.fetchMyActiveAttempt.status = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
builder.addCase(checkContestRegistration.pending, (state) => {
|
||||
state.checkRegistration.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
checkContestRegistration.fulfilled,
|
||||
(
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
contestId: number;
|
||||
registered: boolean;
|
||||
}>,
|
||||
) => {
|
||||
state.checkRegistration.status = 'successful';
|
||||
state.checkRegistration.registered = action.payload.registered;
|
||||
},
|
||||
);
|
||||
builder.addCase(
|
||||
checkContestRegistration.rejected,
|
||||
(state, action: any) => {
|
||||
state.checkRegistration.status = 'failed';
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(fetchUpcomingEligibleContests.pending, (state) => {
|
||||
state.fetchUpcomingEligible.status = 'loading';
|
||||
});
|
||||
builder.addCase(
|
||||
fetchUpcomingEligibleContests.fulfilled,
|
||||
(state, action: PayloadAction<Contest[]>) => {
|
||||
state.fetchUpcomingEligible.status = 'successful';
|
||||
state.fetchUpcomingEligible.contests = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(
|
||||
fetchUpcomingEligibleContests.rejected,
|
||||
(state, action: any) => {
|
||||
state.fetchUpcomingEligible.status = 'failed';
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(fetchParticipatingContests.pending, (state) => {
|
||||
state.fetchParticipating.status = 'loading';
|
||||
});
|
||||
|
||||
builder.addCase(
|
||||
fetchParticipatingContests.fulfilled,
|
||||
(state, action: PayloadAction<ContestsResponse>) => {
|
||||
state.fetchParticipating.status = 'successful';
|
||||
state.fetchParticipating.contests = action.payload.contests;
|
||||
state.fetchParticipating.hasNextPage =
|
||||
action.payload.hasNextPage;
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(
|
||||
fetchParticipatingContests.rejected,
|
||||
(state, action: any) => {
|
||||
state.fetchParticipating.status = 'failed';
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
203
src/redux/slices/groupChat.ts
Normal file
203
src/redux/slices/groupChat.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
// =========================================
|
||||
// Типы
|
||||
// =========================================
|
||||
|
||||
export type Status = 'idle' | 'loading' | 'successful' | 'failed';
|
||||
|
||||
export interface ChatMessage {
|
||||
id: number;
|
||||
groupId: number;
|
||||
authorId: number;
|
||||
authorUsername: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface FetchMessagesParams {
|
||||
groupId: number;
|
||||
limit?: number;
|
||||
afterMessageId?: number;
|
||||
timeoutSeconds?: number;
|
||||
}
|
||||
|
||||
interface SendMessageParams {
|
||||
groupId: number;
|
||||
content: string;
|
||||
}
|
||||
|
||||
// =========================================
|
||||
// State
|
||||
// =========================================
|
||||
|
||||
interface GroupChatState {
|
||||
messages: Record<number, ChatMessage[]>; // по группам
|
||||
lastMessage: Record<number, number>;
|
||||
|
||||
fetchMessages: {
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
sendMessage: {
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const initialState: GroupChatState = {
|
||||
messages: {},
|
||||
lastMessage: {},
|
||||
fetchMessages: {
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
sendMessage: {
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
// =========================================
|
||||
// Thunks
|
||||
// =========================================
|
||||
|
||||
// Получение сообщений
|
||||
export const fetchGroupMessages = createAsyncThunk(
|
||||
'groupChat/fetchGroupMessages',
|
||||
async (params: FetchMessagesParams, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.get(`/groups/${params.groupId}/chat`, {
|
||||
params: {
|
||||
limit: params.limit,
|
||||
afterMessageId: params.afterMessageId,
|
||||
timeoutSeconds: params.timeoutSeconds,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
groupId: params.groupId,
|
||||
messages: response.data as ChatMessage[],
|
||||
};
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Отправка
|
||||
export const sendGroupMessage = createAsyncThunk(
|
||||
'groupChat/sendGroupMessage',
|
||||
async ({ groupId, content }: SendMessageParams, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await axios.post(`/groups/${groupId}/chat`, {
|
||||
content,
|
||||
});
|
||||
return response.data as ChatMessage;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// =========================================
|
||||
// Slice
|
||||
// =========================================
|
||||
|
||||
const groupChatSlice = createSlice({
|
||||
name: 'groupChat',
|
||||
initialState,
|
||||
reducers: {
|
||||
clearChat(state, action: PayloadAction<number>) {
|
||||
delete state.messages[action.payload];
|
||||
},
|
||||
setGroupChatStatus: (
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
key: keyof GroupChatState;
|
||||
status: Status;
|
||||
}>,
|
||||
) => {
|
||||
const { key, status } = action.payload;
|
||||
if (state[key]) {
|
||||
(state[key] as any).status = status;
|
||||
}
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
// fetch messages
|
||||
builder.addCase(fetchGroupMessages.pending, (state) => {
|
||||
state.fetchMessages.status = 'loading';
|
||||
});
|
||||
|
||||
builder.addCase(
|
||||
fetchGroupMessages.fulfilled,
|
||||
(
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
groupId: number;
|
||||
messages: ChatMessage[];
|
||||
}>,
|
||||
) => {
|
||||
const { groupId, messages } = action.payload;
|
||||
const existing = state.messages[groupId] || [];
|
||||
|
||||
const ids = new Set(existing.map((m) => m.id));
|
||||
const filtered = messages.filter((m) => !ids.has(m.id));
|
||||
|
||||
state.messages[groupId] = [...existing, ...filtered].sort(
|
||||
(a, b) => a.id - b.id,
|
||||
);
|
||||
if (state.messages[groupId].length) {
|
||||
state.lastMessage[groupId] =
|
||||
state.messages[groupId][
|
||||
state.messages[groupId].length - 1
|
||||
].id;
|
||||
}
|
||||
|
||||
state.fetchMessages.status = 'successful';
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(fetchGroupMessages.rejected, (state, action: any) => {
|
||||
state.fetchMessages.status = 'failed';
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// send message
|
||||
builder.addCase(sendGroupMessage.pending, (state) => {
|
||||
state.sendMessage.status = 'loading';
|
||||
});
|
||||
|
||||
builder.addCase(
|
||||
sendGroupMessage.fulfilled,
|
||||
(state, action: PayloadAction<ChatMessage>) => {
|
||||
const msg = action.payload;
|
||||
if (!state.messages[msg.groupId])
|
||||
state.messages[msg.groupId] = [];
|
||||
state.messages[msg.groupId].push(msg);
|
||||
state.sendMessage.status = 'successful';
|
||||
},
|
||||
);
|
||||
|
||||
builder.addCase(sendGroupMessage.rejected, (state, action: any) => {
|
||||
state.sendMessage.status = 'failed';
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const { clearChat, setGroupChatStatus } = groupChatSlice.actions;
|
||||
export const groupChatReducer = groupChatSlice.reducer;
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
// =====================
|
||||
// Типы
|
||||
@@ -94,7 +95,7 @@ export const fetchGroupPosts = createAsyncThunk(
|
||||
{
|
||||
groupId,
|
||||
page = 0,
|
||||
pageSize = 20,
|
||||
pageSize = 100,
|
||||
}: { groupId: number; page?: number; pageSize?: number },
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
@@ -104,9 +105,7 @@ export const fetchGroupPosts = createAsyncThunk(
|
||||
);
|
||||
return { page, data: response.data as PostsPage };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка загрузки постов',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -124,9 +123,7 @@ export const fetchPostById = createAsyncThunk(
|
||||
);
|
||||
return response.data as Post;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка загрузки поста',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -149,9 +146,7 @@ export const createPost = createAsyncThunk(
|
||||
});
|
||||
return response.data as Post;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка создания поста',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -183,9 +178,7 @@ export const updatePost = createAsyncThunk(
|
||||
);
|
||||
return response.data as Post;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка обновления поста',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -201,9 +194,7 @@ export const deletePost = createAsyncThunk(
|
||||
await axios.delete(`/groups/${groupId}/feed/${postId}`);
|
||||
return postId;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка удаления поста',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -244,7 +235,13 @@ const postsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchGroupPosts.rejected, (state, action: any) => {
|
||||
state.fetchPosts.status = 'failed';
|
||||
state.fetchPosts.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchPostById
|
||||
@@ -260,7 +257,13 @@ const postsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchPostById.rejected, (state, action: any) => {
|
||||
state.fetchPostById.status = 'failed';
|
||||
state.fetchPostById.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// createPost
|
||||
@@ -281,7 +284,13 @@ const postsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(createPost.rejected, (state, action: any) => {
|
||||
state.createPost.status = 'failed';
|
||||
state.createPost.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// updatePost
|
||||
@@ -310,7 +319,13 @@ const postsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(updatePost.rejected, (state, action: any) => {
|
||||
state.updatePost.status = 'failed';
|
||||
state.updatePost.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// deletePost
|
||||
@@ -338,7 +353,13 @@ const postsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(deletePost.rejected, (state, action: any) => {
|
||||
state.deletePost.status = 'failed';
|
||||
state.deletePost.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
// =====================
|
||||
// Типы
|
||||
@@ -131,9 +132,7 @@ export const createGroup = createAsyncThunk(
|
||||
const response = await axios.post('/groups', { name, description });
|
||||
return response.data as Group;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при создании группы',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -155,9 +154,7 @@ export const updateGroup = createAsyncThunk(
|
||||
});
|
||||
return response.data as Group;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при обновлении группы',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -169,9 +166,7 @@ export const deleteGroup = createAsyncThunk(
|
||||
await axios.delete(`/groups/${groupId}`);
|
||||
return groupId;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при удалении группы',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -183,9 +178,7 @@ export const fetchMyGroups = createAsyncThunk(
|
||||
const response = await axios.get('/groups/my');
|
||||
return response.data.groups as Group[];
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при получении групп',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -197,9 +190,7 @@ export const fetchGroupById = createAsyncThunk(
|
||||
const response = await axios.get(`/groups/${groupId}`);
|
||||
return response.data as Group;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при получении группы',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -221,10 +212,7 @@ export const addGroupMember = createAsyncThunk(
|
||||
});
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message ||
|
||||
'Ошибка при добавлении участника',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -239,9 +227,7 @@ export const removeGroupMember = createAsyncThunk(
|
||||
await axios.delete(`/groups/${groupId}/members/${memberId}`);
|
||||
return { groupId, memberId };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при удалении участника',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -258,10 +244,7 @@ export const fetchGroupJoinLink = createAsyncThunk(
|
||||
const response = await axios.get(`/groups/${groupId}/join-link`);
|
||||
return response.data as { token: string; expiresAt: string };
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message ||
|
||||
'Ошибка при получении ссылки для присоединения',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -274,10 +257,7 @@ export const joinGroupByToken = createAsyncThunk(
|
||||
const response = await axios.post(`/groups/join/${token}`);
|
||||
return response.data as Group;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message ||
|
||||
'Ошибка при присоединении к группе по ссылке',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -314,7 +294,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchMyGroups.rejected, (state, action: any) => {
|
||||
state.fetchMyGroups.status = 'failed';
|
||||
state.fetchMyGroups.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchGroupById
|
||||
@@ -330,7 +316,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchGroupById.rejected, (state, action: any) => {
|
||||
state.fetchGroupById.status = 'failed';
|
||||
state.fetchGroupById.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// createGroup
|
||||
@@ -347,7 +339,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(createGroup.rejected, (state, action: any) => {
|
||||
state.createGroup.status = 'failed';
|
||||
state.createGroup.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// updateGroup
|
||||
@@ -370,7 +368,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(updateGroup.rejected, (state, action: any) => {
|
||||
state.updateGroup.status = 'failed';
|
||||
state.updateGroup.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// deleteGroup
|
||||
@@ -391,7 +395,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(deleteGroup.rejected, (state, action: any) => {
|
||||
state.deleteGroup.status = 'failed';
|
||||
state.deleteGroup.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// addGroupMember
|
||||
@@ -403,7 +413,13 @@ const groupsSlice = createSlice({
|
||||
});
|
||||
builder.addCase(addGroupMember.rejected, (state, action: any) => {
|
||||
state.addGroupMember.status = 'failed';
|
||||
state.addGroupMember.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// removeGroupMember
|
||||
@@ -430,7 +446,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(removeGroupMember.rejected, (state, action: any) => {
|
||||
state.removeGroupMember.status = 'failed';
|
||||
state.removeGroupMember.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// fetchGroupJoinLink
|
||||
@@ -449,7 +471,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(fetchGroupJoinLink.rejected, (state, action: any) => {
|
||||
state.fetchGroupJoinLink.status = 'failed';
|
||||
state.fetchGroupJoinLink.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// joinGroupByToken
|
||||
@@ -466,7 +494,13 @@ const groupsSlice = createSlice({
|
||||
);
|
||||
builder.addCase(joinGroupByToken.rejected, (state, action: any) => {
|
||||
state.joinGroupByToken.status = 'failed';
|
||||
state.joinGroupByToken.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<string, string[]>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
import { toastError } from '../../lib/toastNotification';
|
||||
|
||||
// ─── Типы ────────────────────────────────────────────
|
||||
|
||||
@@ -27,13 +28,18 @@ export interface Mission {
|
||||
|
||||
interface MissionsState {
|
||||
missions: Mission[];
|
||||
newMissions: Mission[];
|
||||
currentMission: Mission | null;
|
||||
hasNextPage: boolean;
|
||||
create: {
|
||||
errors?: Record<string, string[]>;
|
||||
};
|
||||
statuses: {
|
||||
fetchList: Status;
|
||||
fetchById: Status;
|
||||
upload: Status;
|
||||
fetchMy: Status;
|
||||
delete: Status;
|
||||
};
|
||||
error: string | null;
|
||||
}
|
||||
@@ -42,13 +48,16 @@ interface MissionsState {
|
||||
|
||||
const initialState: MissionsState = {
|
||||
missions: [],
|
||||
newMissions: [],
|
||||
currentMission: null,
|
||||
hasNextPage: false,
|
||||
create: {},
|
||||
statuses: {
|
||||
fetchList: 'idle',
|
||||
fetchById: 'idle',
|
||||
upload: 'idle',
|
||||
fetchMy: 'idle',
|
||||
delete: 'idle',
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
@@ -58,6 +67,33 @@ const initialState: MissionsState = {
|
||||
// GET /missions
|
||||
export const fetchMissions = createAsyncThunk(
|
||||
'missions/fetchMissions',
|
||||
async (
|
||||
{
|
||||
page = 0,
|
||||
pageSize = 100,
|
||||
tags = [],
|
||||
}: { page?: number; pageSize?: number; tags?: string[] },
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const params: any = { page, pageSize };
|
||||
if (tags.length) params.tags = tags;
|
||||
const response = await axios.get('/missions', {
|
||||
params,
|
||||
paramsSerializer: {
|
||||
indexes: null,
|
||||
},
|
||||
});
|
||||
return response.data; // { missions, hasNextPage }
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// GET /missions
|
||||
export const fetchNewMissions = createAsyncThunk(
|
||||
'missions/fetchNewMissions',
|
||||
async (
|
||||
{
|
||||
page = 0,
|
||||
@@ -69,12 +105,15 @@ export const fetchMissions = createAsyncThunk(
|
||||
try {
|
||||
const params: any = { page, pageSize };
|
||||
if (tags.length) params.tags = tags;
|
||||
const response = await axios.get('/missions', { params });
|
||||
const response = await axios.get('/missions', {
|
||||
params,
|
||||
paramsSerializer: {
|
||||
indexes: null,
|
||||
},
|
||||
});
|
||||
return response.data; // { missions, hasNextPage }
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при получении миссий',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -87,9 +126,7 @@ export const fetchMissionById = createAsyncThunk(
|
||||
const response = await axios.get(`/missions/${id}`);
|
||||
return response.data; // Mission
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при получении миссии',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -102,10 +139,7 @@ export const fetchMyMissions = createAsyncThunk(
|
||||
const response = await axios.get('/missions/my');
|
||||
return response.data as Mission[]; // массив миссий пользователя
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message ||
|
||||
'Ошибка при получении моих миссий',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -134,9 +168,20 @@ export const uploadMission = createAsyncThunk(
|
||||
});
|
||||
return response.data; // Mission
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка при загрузке миссии',
|
||||
);
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /missions/{id}
|
||||
export const deleteMission = createAsyncThunk(
|
||||
'missions/deleteMission',
|
||||
async (id: number, { rejectWithValue }) => {
|
||||
try {
|
||||
await axios.delete(`/missions/${id}`);
|
||||
return id; // возвращаем id удалённой миссии
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(err.response?.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -182,7 +227,52 @@ const missionsSlice = createSlice({
|
||||
fetchMissions.rejected,
|
||||
(state, action: PayloadAction<any>) => {
|
||||
state.statuses.fetchList = 'failed';
|
||||
state.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// ─── FETCH NEW MISSIONS ───
|
||||
builder.addCase(fetchNewMissions.pending, (state) => {
|
||||
state.statuses.fetchList = 'loading';
|
||||
state.error = null;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchNewMissions.fulfilled,
|
||||
(
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
missions: Mission[];
|
||||
hasNextPage: boolean;
|
||||
}>,
|
||||
) => {
|
||||
state.statuses.fetchList = 'successful';
|
||||
state.newMissions = action.payload.missions;
|
||||
state.hasNextPage = action.payload.hasNextPage;
|
||||
},
|
||||
);
|
||||
builder.addCase(
|
||||
fetchNewMissions.rejected,
|
||||
(state, action: PayloadAction<any>) => {
|
||||
state.statuses.fetchList = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -202,7 +292,16 @@ const missionsSlice = createSlice({
|
||||
fetchMissionById.rejected,
|
||||
(state, action: PayloadAction<any>) => {
|
||||
state.statuses.fetchById = 'failed';
|
||||
state.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -222,7 +321,16 @@ const missionsSlice = createSlice({
|
||||
fetchMyMissions.rejected,
|
||||
(state, action: PayloadAction<any>) => {
|
||||
state.statuses.fetchMy = 'failed';
|
||||
state.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -242,7 +350,53 @@ const missionsSlice = createSlice({
|
||||
uploadMission.rejected,
|
||||
(state, action: PayloadAction<any>) => {
|
||||
state.statuses.upload = 'failed';
|
||||
state.error = action.payload;
|
||||
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
|
||||
state.create.errors = errors;
|
||||
},
|
||||
);
|
||||
|
||||
// ─── DELETE MISSION ───
|
||||
builder.addCase(deleteMission.pending, (state) => {
|
||||
state.statuses.delete = 'loading';
|
||||
state.error = null;
|
||||
});
|
||||
builder.addCase(
|
||||
deleteMission.fulfilled,
|
||||
(state, action: PayloadAction<number>) => {
|
||||
state.statuses.delete = 'successful';
|
||||
state.missions = state.missions.filter(
|
||||
(m) => m.id !== action.payload,
|
||||
);
|
||||
|
||||
if (state.currentMission?.id === action.payload) {
|
||||
state.currentMission = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
builder.addCase(
|
||||
deleteMission.rejected,
|
||||
(state, action: PayloadAction<any>) => {
|
||||
state.statuses.delete = 'failed';
|
||||
|
||||
const errors = action.payload.errors as Record<
|
||||
string,
|
||||
string[]
|
||||
>;
|
||||
Object.values(errors).forEach((messages) => {
|
||||
messages.forEach((msg) => {
|
||||
toastError(msg);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
395
src/redux/slices/profile.ts
Normal file
395
src/redux/slices/profile.ts
Normal file
@@ -0,0 +1,395 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
|
||||
// =====================
|
||||
// Типы
|
||||
// =====================
|
||||
|
||||
type Status = 'idle' | 'loading' | 'successful' | 'failed';
|
||||
|
||||
// Основной профиль
|
||||
export interface ProfileIdentity {
|
||||
userId: number;
|
||||
username: string;
|
||||
email: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface ProfileSolutions {
|
||||
totalSolved: number;
|
||||
solvedLast7Days: number;
|
||||
}
|
||||
|
||||
export interface ProfileContestsInfo {
|
||||
totalParticipations: number;
|
||||
participationsLast7Days: number;
|
||||
}
|
||||
|
||||
export interface ProfileCreationStats {
|
||||
missions: { total: number; last7Days: number };
|
||||
contests: { total: number; last7Days: number };
|
||||
articles: { total: number; last7Days: number };
|
||||
}
|
||||
|
||||
export interface ProfileResponse {
|
||||
identity: ProfileIdentity;
|
||||
solutions: ProfileSolutions;
|
||||
contests: ProfileContestsInfo;
|
||||
creation: ProfileCreationStats;
|
||||
}
|
||||
|
||||
// Missions
|
||||
export interface MissionsBucket {
|
||||
key: string;
|
||||
label: string;
|
||||
solved: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface MissionItem {
|
||||
missionId: number;
|
||||
missionName: string;
|
||||
difficultyLabel: string;
|
||||
difficultyValue: number;
|
||||
createdAt: string;
|
||||
timeLimitMilliseconds: number;
|
||||
memoryLimitBytes: number;
|
||||
}
|
||||
|
||||
export interface MissionsResponse {
|
||||
summary: {
|
||||
total: MissionsBucket;
|
||||
buckets: MissionsBucket[];
|
||||
};
|
||||
recent: {
|
||||
items: MissionItem[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNextPage: boolean;
|
||||
};
|
||||
authored: {
|
||||
items: MissionItem[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNextPage: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
// Articles
|
||||
export interface ProfileArticleItem {
|
||||
articleId: number;
|
||||
title: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
export interface ProfileArticlesResponse {
|
||||
articles: {
|
||||
items: ProfileArticleItem[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNextPage: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
// Contests
|
||||
export interface ContestItem {
|
||||
contestId: number;
|
||||
name: string;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
visibility: string;
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
role: 'None' | 'Participant' | 'Organizer';
|
||||
}
|
||||
|
||||
export interface ContestsList {
|
||||
items: ContestItem[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNextPage: boolean;
|
||||
}
|
||||
|
||||
export interface ProfileContestsResponse {
|
||||
upcoming: ContestsList;
|
||||
past: ContestsList;
|
||||
mine: ContestsList;
|
||||
}
|
||||
|
||||
// =====================
|
||||
// Состояние
|
||||
// =====================
|
||||
|
||||
interface ProfileState {
|
||||
profile: {
|
||||
data?: ProfileResponse;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
missions: {
|
||||
data?: MissionsResponse;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
articles: {
|
||||
data?: ProfileArticlesResponse;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
contests: {
|
||||
data?: ProfileContestsResponse;
|
||||
status: Status;
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const initialState: ProfileState = {
|
||||
profile: {
|
||||
data: undefined,
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
missions: {
|
||||
data: undefined,
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
articles: {
|
||||
data: undefined,
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
contests: {
|
||||
data: undefined,
|
||||
status: 'idle',
|
||||
error: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
// =====================
|
||||
// Async Thunks
|
||||
// =====================
|
||||
|
||||
// Основной профиль
|
||||
export const fetchProfile = createAsyncThunk(
|
||||
'profile/fetch',
|
||||
async (username: string, { rejectWithValue }) => {
|
||||
try {
|
||||
const res = await axios.get<ProfileResponse>(
|
||||
`/profile/${username}`,
|
||||
);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка загрузки профиля',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Missions
|
||||
export const fetchProfileMissions = createAsyncThunk(
|
||||
'profile/fetchMissions',
|
||||
async (
|
||||
{
|
||||
username,
|
||||
recentPage = 0,
|
||||
recentPageSize = 100,
|
||||
authoredPage = 0,
|
||||
authoredPageSize = 100,
|
||||
}: {
|
||||
username: string;
|
||||
recentPage?: number;
|
||||
recentPageSize?: number;
|
||||
authoredPage?: number;
|
||||
authoredPageSize?: number;
|
||||
},
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const res = await axios.get<MissionsResponse>(
|
||||
`/profile/${username}/missions`,
|
||||
{
|
||||
params: {
|
||||
recentPage,
|
||||
recentPageSize,
|
||||
authoredPage,
|
||||
authoredPageSize,
|
||||
},
|
||||
},
|
||||
);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка загрузки задач',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Articles
|
||||
export const fetchProfileArticles = createAsyncThunk(
|
||||
'profile/fetchArticles',
|
||||
async (
|
||||
{
|
||||
username,
|
||||
page = 0,
|
||||
pageSize = 100,
|
||||
}: { username: string; page?: number; pageSize?: number },
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const res = await axios.get<ProfileArticlesResponse>(
|
||||
`/profile/${username}/articles`,
|
||||
{ params: { page, pageSize } },
|
||||
);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка загрузки статей',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Contests
|
||||
export const fetchProfileContests = createAsyncThunk(
|
||||
'profile/fetchContests',
|
||||
async (
|
||||
{
|
||||
username,
|
||||
upcomingPage = 0,
|
||||
upcomingPageSize = 100,
|
||||
pastPage = 0,
|
||||
pastPageSize = 100,
|
||||
minePage = 0,
|
||||
minePageSize = 100,
|
||||
}: {
|
||||
username: string;
|
||||
upcomingPage?: number;
|
||||
upcomingPageSize?: number;
|
||||
pastPage?: number;
|
||||
pastPageSize?: number;
|
||||
minePage?: number;
|
||||
minePageSize?: number;
|
||||
},
|
||||
{ rejectWithValue },
|
||||
) => {
|
||||
try {
|
||||
const res = await axios.get<ProfileContestsResponse>(
|
||||
`/profile/${username}/contests`,
|
||||
{
|
||||
params: {
|
||||
upcomingPage,
|
||||
upcomingPageSize,
|
||||
pastPage,
|
||||
pastPageSize,
|
||||
minePage,
|
||||
minePageSize,
|
||||
},
|
||||
},
|
||||
);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Ошибка загрузки контестов',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// =====================
|
||||
// Slice
|
||||
// =====================
|
||||
|
||||
const profileSlice = createSlice({
|
||||
name: 'profile',
|
||||
initialState,
|
||||
reducers: {
|
||||
setProfileStatus: (
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
key: keyof ProfileState;
|
||||
status: Status;
|
||||
}>,
|
||||
) => {
|
||||
state[action.payload.key].status = action.payload.status;
|
||||
},
|
||||
},
|
||||
|
||||
extraReducers: (builder) => {
|
||||
// PROFILE
|
||||
builder.addCase(fetchProfile.pending, (state) => {
|
||||
state.profile.status = 'loading';
|
||||
state.profile.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchProfile.fulfilled,
|
||||
(state, action: PayloadAction<ProfileResponse>) => {
|
||||
state.profile.status = 'successful';
|
||||
state.profile.data = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchProfile.rejected, (state, action: any) => {
|
||||
state.profile.status = 'failed';
|
||||
state.profile.error = action.payload;
|
||||
});
|
||||
|
||||
// MISSIONS
|
||||
builder.addCase(fetchProfileMissions.pending, (state) => {
|
||||
state.missions.status = 'loading';
|
||||
state.missions.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchProfileMissions.fulfilled,
|
||||
(state, action: PayloadAction<MissionsResponse>) => {
|
||||
state.missions.status = 'successful';
|
||||
state.missions.data = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchProfileMissions.rejected, (state, action: any) => {
|
||||
state.missions.status = 'failed';
|
||||
state.missions.error = action.payload;
|
||||
});
|
||||
|
||||
// ARTICLES
|
||||
builder.addCase(fetchProfileArticles.pending, (state) => {
|
||||
state.articles.status = 'loading';
|
||||
state.articles.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchProfileArticles.fulfilled,
|
||||
(state, action: PayloadAction<ProfileArticlesResponse>) => {
|
||||
state.articles.status = 'successful';
|
||||
state.articles.data = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchProfileArticles.rejected, (state, action: any) => {
|
||||
state.articles.status = 'failed';
|
||||
state.articles.error = action.payload;
|
||||
});
|
||||
|
||||
// CONTESTS
|
||||
builder.addCase(fetchProfileContests.pending, (state) => {
|
||||
state.contests.status = 'loading';
|
||||
state.contests.error = undefined;
|
||||
});
|
||||
builder.addCase(
|
||||
fetchProfileContests.fulfilled,
|
||||
(state, action: PayloadAction<ProfileContestsResponse>) => {
|
||||
state.contests.status = 'successful';
|
||||
state.contests.data = action.payload;
|
||||
},
|
||||
);
|
||||
builder.addCase(fetchProfileContests.rejected, (state, action: any) => {
|
||||
state.contests.status = 'failed';
|
||||
state.contests.error = action.payload;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const { setProfileStatus } = profileSlice.actions;
|
||||
export const profileReducer = profileSlice.reducer;
|
||||
@@ -7,6 +7,21 @@ interface StorState {
|
||||
activeProfilePage: string;
|
||||
activeGroupPage: string;
|
||||
};
|
||||
group: {
|
||||
groupFilter: string;
|
||||
};
|
||||
articles: {
|
||||
articleTagFilter: string[];
|
||||
filterName: string;
|
||||
};
|
||||
contests: {
|
||||
contestsTagFilter: string[];
|
||||
filterName: string;
|
||||
};
|
||||
missions: {
|
||||
missionsTagFilter: string[];
|
||||
filterName: string;
|
||||
};
|
||||
}
|
||||
|
||||
// Инициализация состояния
|
||||
@@ -16,6 +31,21 @@ const initialState: StorState = {
|
||||
activeProfilePage: '',
|
||||
activeGroupPage: '',
|
||||
},
|
||||
group: {
|
||||
groupFilter: '',
|
||||
},
|
||||
articles: {
|
||||
articleTagFilter: [],
|
||||
filterName: '',
|
||||
},
|
||||
contests: {
|
||||
contestsTagFilter: [],
|
||||
filterName: '',
|
||||
},
|
||||
missions: {
|
||||
missionsTagFilter: [],
|
||||
filterName: '',
|
||||
},
|
||||
};
|
||||
|
||||
// Slice
|
||||
@@ -23,28 +53,63 @@ const storeSlice = createSlice({
|
||||
name: 'store',
|
||||
initialState,
|
||||
reducers: {
|
||||
setMenuActivePage: (state, activePage: PayloadAction<string>) => {
|
||||
state.menu.activePage = activePage.payload;
|
||||
setMenuActivePage: (state, action: PayloadAction<string>) => {
|
||||
state.menu.activePage = action.payload;
|
||||
},
|
||||
setMenuActiveProfilePage: (
|
||||
state,
|
||||
activeProfilePage: PayloadAction<string>,
|
||||
) => {
|
||||
state.menu.activeProfilePage = activeProfilePage.payload;
|
||||
setMenuActiveProfilePage: (state, action: PayloadAction<string>) => {
|
||||
state.menu.activeProfilePage = action.payload;
|
||||
},
|
||||
setMenuActiveGroupPage: (
|
||||
state,
|
||||
activeGroupPage: PayloadAction<string>,
|
||||
) => {
|
||||
state.menu.activeGroupPage = activeGroupPage.payload;
|
||||
setMenuActiveGroupPage: (state, action: PayloadAction<string>) => {
|
||||
state.menu.activeGroupPage = action.payload;
|
||||
},
|
||||
setGroupFilter: (state, action: PayloadAction<string>) => {
|
||||
state.group.groupFilter = action.payload;
|
||||
},
|
||||
|
||||
// ---------- ARTICLES ----------
|
||||
setArticlesTagFilter: (state, action: PayloadAction<string[]>) => {
|
||||
state.articles.articleTagFilter = action.payload;
|
||||
},
|
||||
setArticlesNameFilter: (state, action: PayloadAction<string>) => {
|
||||
state.articles.filterName = action.payload;
|
||||
},
|
||||
|
||||
// ---------- CONTESTS ----------
|
||||
setContestsTagFilter: (state, action: PayloadAction<string[]>) => {
|
||||
state.contests.contestsTagFilter = action.payload;
|
||||
},
|
||||
setContestsNameFilter: (state, action: PayloadAction<string>) => {
|
||||
state.contests.filterName = action.payload;
|
||||
},
|
||||
|
||||
// ---------- MISSIONS ----------
|
||||
setMissionsTagFilter: (state, action: PayloadAction<string[]>) => {
|
||||
state.missions.missionsTagFilter = action.payload;
|
||||
},
|
||||
setMissionsNameFilter: (state, action: PayloadAction<string>) => {
|
||||
state.missions.filterName = action.payload;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const {
|
||||
// menu
|
||||
setMenuActivePage,
|
||||
setMenuActiveProfilePage,
|
||||
setMenuActiveGroupPage,
|
||||
setGroupFilter,
|
||||
|
||||
// articles
|
||||
setArticlesTagFilter,
|
||||
setArticlesNameFilter,
|
||||
|
||||
// contests
|
||||
setContestsTagFilter,
|
||||
setContestsNameFilter,
|
||||
|
||||
// missions
|
||||
setMissionsTagFilter,
|
||||
setMissionsNameFilter,
|
||||
} = storeSlice.actions;
|
||||
|
||||
export const storeReducer = storeSlice.reducer;
|
||||
|
||||
@@ -8,7 +8,7 @@ export interface Submit {
|
||||
language: string;
|
||||
languageVersion: string;
|
||||
sourceCode: string;
|
||||
contestId?: number;
|
||||
contestAttemptId?: number;
|
||||
}
|
||||
|
||||
export interface Solution {
|
||||
|
||||
@@ -7,6 +7,8 @@ import { contestsReducer } from './slices/contests';
|
||||
import { groupsReducer } from './slices/groups';
|
||||
import { articlesReducer } from './slices/articles';
|
||||
import { groupFeedReducer } from './slices/groupfeed';
|
||||
import { groupChatReducer } from './slices/groupChat';
|
||||
import { profileReducer } from './slices/profile';
|
||||
|
||||
// использование
|
||||
// import { useAppDispatch, useAppSelector } from '../redux/hooks';
|
||||
@@ -27,6 +29,8 @@ export const store = configureStore({
|
||||
groups: groupsReducer,
|
||||
articles: articlesReducer,
|
||||
groupfeed: groupFeedReducer,
|
||||
groupchat: groupChatReducer,
|
||||
profile: profileReducer,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -68,14 +68,14 @@ function greet(user: User) {
|
||||
return \`Привет, \${user.name}! 👋 Роль: \${user.role}\`;
|
||||
}
|
||||
|
||||
console.log(greet({ name: "Ты", role: "Разработчик" }));
|
||||
consol.log(greet({ name: "Ты", role: "Разработчик" }));
|
||||
\`\`\`
|
||||
|
||||
Пример **JavaScript**:
|
||||
|
||||
\`\`\`js
|
||||
const sum = (a, b) => a + b;
|
||||
console.log(sum(2, 3)); // 5
|
||||
consol.log(sum(2, 3)); // 5
|
||||
\`\`\`
|
||||
|
||||
Пример **Python**:
|
||||
@@ -256,9 +256,7 @@ const MarkdownEditor: FC<MarkdownEditorProps> = ({
|
||||
markdown.slice(cursorPos);
|
||||
|
||||
setMarkdown(newText);
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки изображения:', err);
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,19 +4,51 @@ import RightPanel from './RightPanel';
|
||||
import Missions from './missions/Missions';
|
||||
import Contests from './contests/Contests';
|
||||
import ArticlesBlock from './articles/ArticlesBlock';
|
||||
import { useAppDispatch } from '../../../redux/hooks';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { useEffect } from 'react';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import { useQuery } from '../../../hooks/useQuery';
|
||||
import {
|
||||
fetchProfile,
|
||||
fetchProfileArticles,
|
||||
fetchProfileContests,
|
||||
fetchProfileMissions,
|
||||
} from '../../../redux/slices/profile';
|
||||
|
||||
const Account = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActivePage('account'));
|
||||
}, []);
|
||||
if (username == myname) {
|
||||
dispatch(setMenuActivePage('account'));
|
||||
} else {
|
||||
dispatch(setMenuActivePage(''));
|
||||
}
|
||||
dispatch(
|
||||
fetchProfileMissions({
|
||||
username: username,
|
||||
recentPageSize: 1,
|
||||
authoredPageSize: 100,
|
||||
}),
|
||||
);
|
||||
dispatch(fetchProfileArticles({ username: username, pageSize: 100 }));
|
||||
dispatch(
|
||||
fetchProfileContests({
|
||||
username: username,
|
||||
pastPageSize: 100,
|
||||
minePageSize: 100,
|
||||
upcomingPageSize: 100,
|
||||
}),
|
||||
);
|
||||
dispatch(fetchProfile(username));
|
||||
}, [username]);
|
||||
|
||||
return (
|
||||
<div className="h-full w-[calc(100%+250px)] box-border grid grid-cols-[1fr,520px] relative divide-x-[1px] divide-liquid-lighter">
|
||||
<div className="h-full w-[calc(100%+250px)] box-border grid grid-cols-[1fr,430px] relative divide-x-[1px] divide-liquid-lighter">
|
||||
<div className=" h-full min-h-0 flex flex-col">
|
||||
<div className=" h-full grid grid-rows-[80px,1fr] ">
|
||||
<div className="h-full w-full">
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { PrimaryButton } from '../../../components/button/PrimaryButton';
|
||||
import { ReverseButton } from '../../../components/button/ReverseButton';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { logout } from '../../../redux/slices/auth';
|
||||
import { OpenBook, Clipboard, Cup } from '../../../assets/icons/account';
|
||||
import { FC } from 'react';
|
||||
import { useQuery } from '../../../hooks/useQuery';
|
||||
|
||||
interface StatisticItemProps {
|
||||
icon: string;
|
||||
@@ -34,32 +34,55 @@ const StatisticItem: FC<StatisticItemProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
export const formatDate = (isoDate?: string): string => {
|
||||
if (!isoDate) return '';
|
||||
const date = new Date(isoDate);
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
return `${day}.${month}.${year}`;
|
||||
};
|
||||
|
||||
const RightPanel = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const name = useAppSelector((state) => state.auth.username);
|
||||
const email = useAppSelector((state) => state.auth.email);
|
||||
|
||||
const { data: profileData } = useAppSelector(
|
||||
(state) => state.profile.profile,
|
||||
);
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
return (
|
||||
<div className="h-full w-full relative flex flex-col p-[20px] pt-[35px] gap-[20px]">
|
||||
<div className="grid grid-cols-[150px,1fr] h-[150px] gap-[20px]">
|
||||
<div className="-hfull w-full bg-[#B8B8B8] rounded-[10px]"></div>
|
||||
<div className=" relative">
|
||||
<div className="text-liquid-white text-[24px] leading-[30px] font-bold">
|
||||
{name}
|
||||
{profileData?.identity.username}
|
||||
</div>
|
||||
<div className="text-liquid-light text-[18px] leading-[23px] font-medium">
|
||||
{email}
|
||||
</div>
|
||||
<div className=" absolute bottom-0 text-liquid-light text-[24px] leading-[30px] font-bold">
|
||||
Топ 50%
|
||||
{profileData?.identity.email}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PrimaryButton
|
||||
onClick={() => {}}
|
||||
text="Редактировать"
|
||||
className="w-full"
|
||||
/>
|
||||
<div className=" text-liquid-light text-[18px] leading-[30px] font-bold">
|
||||
{`Зарегистрирован ${formatDate(
|
||||
profileData?.identity.createdAt,
|
||||
)}`}
|
||||
</div>
|
||||
|
||||
{/* {username == myname && (
|
||||
<PrimaryButton
|
||||
onClick={() => {}}
|
||||
text="Редактировать"
|
||||
className="w-full"
|
||||
/>
|
||||
)} */}
|
||||
|
||||
<div className="h-[1px] w-full bg-liquid-lighter"></div>
|
||||
|
||||
@@ -70,14 +93,14 @@ const RightPanel = () => {
|
||||
<StatisticItem
|
||||
icon={Clipboard}
|
||||
title={'Задачи'}
|
||||
count={14}
|
||||
countLastWeek={5}
|
||||
count={profileData?.solutions.totalSolved}
|
||||
countLastWeek={profileData?.solutions.solvedLast7Days}
|
||||
/>
|
||||
<StatisticItem
|
||||
icon={Cup}
|
||||
title={'Контесты'}
|
||||
count={8}
|
||||
countLastWeek={2}
|
||||
count={profileData?.contests.totalParticipations}
|
||||
countLastWeek={profileData?.contests.participationsLast7Days}
|
||||
/>
|
||||
|
||||
<div className="text-liquid-white text-[24px] leading-[30px] font-bold">
|
||||
@@ -87,30 +110,32 @@ const RightPanel = () => {
|
||||
<StatisticItem
|
||||
icon={Clipboard}
|
||||
title={'Задачи'}
|
||||
count={4}
|
||||
countLastWeek={2}
|
||||
count={profileData?.creation.missions.total}
|
||||
countLastWeek={profileData?.creation.missions.last7Days}
|
||||
/>
|
||||
<StatisticItem
|
||||
icon={OpenBook}
|
||||
title={'Статьи'}
|
||||
count={12}
|
||||
countLastWeek={4}
|
||||
count={profileData?.creation.articles.total}
|
||||
countLastWeek={profileData?.creation.articles.last7Days}
|
||||
/>
|
||||
<StatisticItem
|
||||
icon={Cup}
|
||||
title={'Контесты'}
|
||||
count={2}
|
||||
countLastWeek={0}
|
||||
count={profileData?.creation.contests.total}
|
||||
countLastWeek={profileData?.creation.contests.last7Days}
|
||||
/>
|
||||
|
||||
<ReverseButton
|
||||
className="absolute bottom-[20px] right-[20px]"
|
||||
onClick={() => {
|
||||
dispatch(logout());
|
||||
}}
|
||||
text="Выход"
|
||||
color="error"
|
||||
/>
|
||||
{username == myname && (
|
||||
<ReverseButton
|
||||
className="absolute bottom-[20px] right-[20px]"
|
||||
onClick={() => {
|
||||
dispatch(logout());
|
||||
}}
|
||||
text="Выход"
|
||||
color="error"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,16 +3,25 @@ import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { setMenuActiveProfilePage } from '../../../../redux/slices/store';
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { ChevroneDown, Edit } from '../../../../assets/icons/groups';
|
||||
import { fetchMyArticles } from '../../../../redux/slices/articles';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export interface ArticleItemProps {
|
||||
id: number;
|
||||
name: string;
|
||||
tags: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const ArticleItem: FC<ArticleItemProps> = ({ id, name, tags }) => {
|
||||
export const formatDate = (isoDate?: string): string => {
|
||||
if (!isoDate) return '';
|
||||
const date = new Date(isoDate);
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
return `${day}.${month}.${year}`;
|
||||
};
|
||||
|
||||
const ArticleItem: FC<ArticleItemProps> = ({ id, name, createdAt }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
@@ -35,18 +44,8 @@ const ArticleItem: FC<ArticleItemProps> = ({ id, name, tags }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-[14px] flex text-liquid-light gap-[10px] mt-[10px]">
|
||||
{tags.map((v, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'rounded-full px-[16px] py-[8px] bg-liquid-lighter',
|
||||
v === 'Sertificated' && 'text-liquid-green',
|
||||
)}
|
||||
>
|
||||
{v}
|
||||
</div>
|
||||
))}
|
||||
<div className="text-[18px] flex text-liquid-light gap-[10px] mt-[20px]">
|
||||
{`Опубликована ${formatDate(createdAt)}`}
|
||||
</div>
|
||||
|
||||
<img
|
||||
@@ -72,20 +71,12 @@ const ArticlesBlock: FC<ArticlesBlockProps> = ({ className = '' }) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const [active, setActive] = useState<boolean>(true);
|
||||
|
||||
// ✅ Берём только "мои статьи"
|
||||
const articles = useAppSelector(
|
||||
(state) => state.articles.fetchMyArticles.articles,
|
||||
);
|
||||
const status = useAppSelector(
|
||||
(state) => state.articles.fetchMyArticles.status,
|
||||
);
|
||||
const error = useAppSelector(
|
||||
(state) => state.articles.fetchMyArticles.error,
|
||||
const { data: articleData } = useAppSelector(
|
||||
(state) => state.profile.articles,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActiveProfilePage('articles'));
|
||||
dispatch(fetchMyArticles());
|
||||
}, [dispatch]);
|
||||
|
||||
return (
|
||||
@@ -130,19 +121,21 @@ const ArticlesBlock: FC<ArticlesBlockProps> = ({ className = '' }) => {
|
||||
</div>
|
||||
)}
|
||||
{status === 'failed' && (
|
||||
<div className="text-liquid-red">
|
||||
Ошибка:{' '}
|
||||
{error || 'Не удалось загрузить статьи'}
|
||||
</div>
|
||||
<div className="text-liquid-red">Ошибка: </div>
|
||||
)}
|
||||
{status === 'successful' &&
|
||||
articles.length === 0 && (
|
||||
articleData?.articles.items.length === 0 && (
|
||||
<div className="text-liquid-light">
|
||||
У вас пока нет статей
|
||||
</div>
|
||||
)}
|
||||
{articles.map((v) => (
|
||||
<ArticleItem key={v.id} {...v} />
|
||||
{articleData?.articles.items.map((v, i) => (
|
||||
<ArticleItem
|
||||
key={i}
|
||||
id={v.articleId}
|
||||
name={v.title}
|
||||
createdAt={v.createdAt}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,25 +1,18 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { setMenuActiveProfilePage } from '../../../../redux/slices/store';
|
||||
import {
|
||||
fetchMyContests,
|
||||
fetchRegisteredContests,
|
||||
} from '../../../../redux/slices/contests';
|
||||
import ContestsBlock from './ContestsBlock';
|
||||
|
||||
const Contests = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
// Redux-состояния
|
||||
const myContestsState = useAppSelector(
|
||||
(state) => state.contests.fetchMyContests,
|
||||
const { data: constestData } = useAppSelector(
|
||||
(state) => state.profile.contests,
|
||||
);
|
||||
|
||||
// При загрузке страницы — выставляем вкладку и подгружаем контесты
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActiveProfilePage('contests'));
|
||||
dispatch(fetchMyContests());
|
||||
dispatch(fetchRegisteredContests({}));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -29,30 +22,38 @@ const Contests = () => {
|
||||
<ContestsBlock
|
||||
className="mb-[20px]"
|
||||
title="Предстоящие контесты"
|
||||
type="reg"
|
||||
// contests={regContestsState.contests}
|
||||
contests={[]}
|
||||
type="upcoming"
|
||||
contests={constestData?.upcoming.items
|
||||
.filter((v) => v.role != 'Organizer')
|
||||
.filter((v) => v.scheduleType != 'AlwaysOpen')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<ContestsBlock
|
||||
className="mb-[20px]"
|
||||
title="Прошедшие контесты"
|
||||
type="past"
|
||||
contests={[
|
||||
...(constestData?.past.items.filter(
|
||||
(v) => v.role != 'Organizer',
|
||||
) ?? []),
|
||||
...(constestData?.upcoming.items
|
||||
.filter((v) => v.role != 'Organizer')
|
||||
.filter((v) => v.scheduleType == 'AlwaysOpen') ??
|
||||
[]),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Контесты, которые я создал */}
|
||||
<div>
|
||||
{myContestsState.status === 'loading' ? (
|
||||
<div className="text-liquid-white p-4 text-[24px]">
|
||||
Загрузка ваших контестов...
|
||||
</div>
|
||||
) : myContestsState.error ? (
|
||||
<div className="text-red-500 p-4 text-[24px]">
|
||||
Ошибка: {myContestsState.error}
|
||||
</div>
|
||||
) : (
|
||||
<ContestsBlock
|
||||
className="mb-[20px]"
|
||||
title="Мои контесты"
|
||||
type="my"
|
||||
contests={myContestsState.contests}
|
||||
/>
|
||||
)}
|
||||
<ContestsBlock
|
||||
className="mb-[20px]"
|
||||
title="Созданные контесты"
|
||||
type="edit"
|
||||
contests={constestData?.mine.items}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { useState, FC } from 'react';
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { ChevroneDown } from '../../../../assets/icons/groups';
|
||||
import MyContestItem from './MyContestItem';
|
||||
import RegisterContestItem from './RegisterContestItem';
|
||||
import { Contest } from '../../../../redux/slices/contests';
|
||||
import { ContestItem } from '../../../../redux/slices/profile';
|
||||
import PastContestItem from './PastContestItem';
|
||||
import UpcoingContestItem from './UpcomingContestItem';
|
||||
import EditContestItem from './EditContestItem';
|
||||
|
||||
interface ContestsBlockProps {
|
||||
contests: Contest[];
|
||||
contests?: ContestItem[];
|
||||
title: string;
|
||||
className?: string;
|
||||
type?: 'my' | 'reg';
|
||||
type?: 'edit' | 'upcoming' | 'past';
|
||||
}
|
||||
|
||||
const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
contests,
|
||||
title,
|
||||
className,
|
||||
type = 'my',
|
||||
type = 'edit',
|
||||
}) => {
|
||||
const [active, setActive] = useState<boolean>(title != 'Скрытые');
|
||||
|
||||
@@ -36,11 +37,11 @@ const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
setActive(!active);
|
||||
}}
|
||||
>
|
||||
<span>{title}</span>
|
||||
<span className=" select-none">{title}</span>
|
||||
<img
|
||||
src={ChevroneDown}
|
||||
className={cn(
|
||||
'transition-all duration-300',
|
||||
'transition-all duration-300 select-none',
|
||||
active && 'rotate-180',
|
||||
)}
|
||||
/>
|
||||
@@ -53,35 +54,38 @@ const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="pb-[10px] pt-[20px]">
|
||||
{contests.map((v, i) => {
|
||||
return type == 'my' ? (
|
||||
<MyContestItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
name={v.name}
|
||||
startAt={v.startsAt ?? ''}
|
||||
duration={
|
||||
new Date(v.endsAt ?? '').getTime() -
|
||||
new Date(v.startsAt ?? '').getTime()
|
||||
}
|
||||
members={(v.members??[]).length}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
) : (
|
||||
<RegisterContestItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
name={v.name}
|
||||
startAt={v.startsAt ?? ''}
|
||||
statusRegister={'reg'}
|
||||
duration={
|
||||
new Date(v.endsAt ?? '').getTime() -
|
||||
new Date(v.startsAt ?? '').getTime()
|
||||
}
|
||||
members={(v.members??[]).length}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
{contests?.map((v, i) => {
|
||||
if (type == 'past') {
|
||||
return (
|
||||
<PastContestItem
|
||||
key={i}
|
||||
{...v}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type == 'upcoming') {
|
||||
return (
|
||||
<UpcoingContestItem
|
||||
key={i}
|
||||
{...v}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type == 'edit') {
|
||||
return (
|
||||
<EditContestItem
|
||||
key={i}
|
||||
{...v}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <></>;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
146
src/views/home/account/contests/EditContestItem.tsx
Normal file
146
src/views/home/account/contests/EditContestItem.tsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppSelector } from '../../../../redux/hooks';
|
||||
import { useQuery } from '../../../../hooks/useQuery';
|
||||
import { toastWarning } from '../../../../lib/toastNotification';
|
||||
import { Edit } from '../../../../assets/icons/input';
|
||||
|
||||
export interface EditContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
visibility: string;
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
role: string;
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const EditContestItem: React.FC<EditContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
const started = new Date(startsAt) <= new Date();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
username == myname
|
||||
? 'grid-cols-[1fr,150px,190px,110px,130px,24px]'
|
||||
: 'grid-cols-[1fr,150px,190px,110px,130px]',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (!started && username != myname) {
|
||||
toastWarning('Контест еще не начался');
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/account/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-center text-liquid-brightmain font-normal">
|
||||
{new Date() < new Date(startsAt) ? (
|
||||
<>{'Не начался'}</>
|
||||
) : (
|
||||
<>
|
||||
{scheduleType == 'AlwaysOpen'
|
||||
? 'Открыт'
|
||||
: new Date() < new Date(endsAt)
|
||||
? 'Идет'
|
||||
: 'Завершен'}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{username == myname && (
|
||||
<img
|
||||
className=" h-[24px] w-[24px] hover:bg-liquid-light rounded-[5px] transition-all duration-300"
|
||||
src={Edit}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate(
|
||||
`/contest/create?back=/home/account/contests&contestId=${contestId}`,
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditContestItem;
|
||||
@@ -1,98 +0,0 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { Account } from '../../../../assets/icons/auth';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Edit } from '../../../../assets/icons/input';
|
||||
|
||||
export interface ContestItemProps {
|
||||
id: number;
|
||||
name: string;
|
||||
startAt: string;
|
||||
duration: number;
|
||||
members: number;
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatWaitTime(ms: number): string {
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const ContestItem: React.FC<ContestItemProps> = ({
|
||||
id,
|
||||
name,
|
||||
startAt,
|
||||
duration,
|
||||
members,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[10px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid grid-cols-[1fr,1fr,110px,110px,110px,24px] items-center font-bold',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
navigate(`/contest/${id}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal ">
|
||||
{/* {authors.map((v, i) => <p key={i}>{v}</p>)} */}
|
||||
valavshonok
|
||||
</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startAt)}
|
||||
</div>
|
||||
<div className="text-center">{formatWaitTime(duration)}</div>
|
||||
<div className="items-center justify-center flex gap-[10px] flex-row w-full">
|
||||
<div>{members}</div>
|
||||
<img src={Account} className="h-[24px] w-[24px]" />
|
||||
</div>
|
||||
|
||||
<img
|
||||
className=" h-[24px] w-[24px] hover:bg-liquid-light rounded-[5px] transition-all duration-300"
|
||||
src={Edit}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate(
|
||||
`/contest/create?back=/home/account/contests&contestId=${id}`,
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContestItem;
|
||||
112
src/views/home/account/contests/PastContestItem.tsx
Normal file
112
src/views/home/account/contests/PastContestItem.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppSelector } from '../../../../redux/hooks';
|
||||
import { useQuery } from '../../../../hooks/useQuery';
|
||||
|
||||
export interface PastContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
visibility: string;
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
role: string;
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const PastContestItem: React.FC<PastContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid grid-cols-[1fr,150px,190px,120px,150px] items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/account/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-center text-liquid-brightmain font-normal">
|
||||
{scheduleType == 'AlwaysOpen' ? 'Открыт' : 'Завершен'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PastContestItem;
|
||||
@@ -1,114 +0,0 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { Account } from '../../../../assets/icons/auth';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { ReverseButton } from '../../../../components/button/ReverseButton';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export interface ContestItemProps {
|
||||
id: number;
|
||||
name: string;
|
||||
startAt: string;
|
||||
duration: number;
|
||||
members: number;
|
||||
statusRegister: 'reg' | 'nonreg';
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatWaitTime(ms: number): string {
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const ContestItem: React.FC<ContestItemProps> = ({
|
||||
id,
|
||||
name,
|
||||
startAt,
|
||||
duration,
|
||||
members,
|
||||
statusRegister,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const now = new Date();
|
||||
|
||||
const waitTime = new Date(startAt).getTime() - now.getTime();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[10px] text-liquid-white text-[16px] leading-[20px] cursor-pointer',
|
||||
waitTime <= 0 ? 'grid grid-cols-6' : 'grid grid-cols-7',
|
||||
'items-center font-bold text-liquid-white',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
navigate(`/contest/${id}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal ">
|
||||
{/* {authors.map((v, i) => <p key={i}>{v}</p>)} */}
|
||||
valavshonok
|
||||
</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startAt)}
|
||||
</div>
|
||||
<div className="text-center">{formatWaitTime(duration)}</div>
|
||||
{waitTime > 0 && (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До начала\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
)}
|
||||
<div className="items-center justify-center flex gap-[10px] flex-row w-full">
|
||||
<div>{members}</div>
|
||||
<img src={Account} className="h-[24px] w-[24px]" />
|
||||
</div>
|
||||
<div className="flex items-center justify-end">
|
||||
{statusRegister == 'reg' ? (
|
||||
<>
|
||||
{' '}
|
||||
<PrimaryButton onClick={() => {}} text="Регистрация" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{' '}
|
||||
<ReverseButton onClick={() => {}} text="Вы записаны" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContestItem;
|
||||
160
src/views/home/account/contests/UpcomingContestItem.tsx
Normal file
160
src/views/home/account/contests/UpcomingContestItem.tsx
Normal file
@@ -0,0 +1,160 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppSelector } from '../../../../redux/hooks';
|
||||
import { useQuery } from '../../../../hooks/useQuery';
|
||||
import { toastWarning } from '../../../../lib/toastNotification';
|
||||
|
||||
export interface UpcoingContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
visibility: string;
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
role: string;
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
function formatWaitTime(ms: number): string {
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const UpcoingContestItem: React.FC<UpcoingContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
const started = new Date(startsAt) <= new Date();
|
||||
const finished = new Date(endsAt) <= new Date();
|
||||
const waitTime = !started
|
||||
? new Date(startsAt).getTime() - new Date().getTime()
|
||||
: new Date(endsAt).getTime() - new Date().getTime();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid grid-cols-[1fr,150px,190px,110px,110px,130px] items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (!started) {
|
||||
toastWarning('Контест еще не начался');
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/account/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
{!started ? (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До начала\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
) : (
|
||||
!finished && (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До конца\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-center text-liquid-brightmain font-normal">
|
||||
{new Date() < new Date(startsAt) ? (
|
||||
<>{'Не начался'}</>
|
||||
) : (
|
||||
<>{scheduleType == 'AlwaysOpen' ? 'Открыт' : 'Идет'}</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpcoingContestItem;
|
||||
@@ -1,12 +1,15 @@
|
||||
import { FC, useEffect } from 'react';
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { setMenuActiveProfilePage } from '../../../../redux/slices/store';
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import MissionsBlock from './MissionsBlock';
|
||||
import {
|
||||
fetchMyMissions,
|
||||
deleteMission,
|
||||
setMissionsStatus,
|
||||
} from '../../../../redux/slices/missions';
|
||||
import ConfirmModal from '../../../../components/modal/ConfirmModal';
|
||||
import { fetchProfileMissions } from '../../../../redux/slices/profile';
|
||||
import { useQuery } from '../../../../hooks/useQuery';
|
||||
|
||||
interface ItemProps {
|
||||
count: number;
|
||||
@@ -41,12 +44,20 @@ const Item: FC<ItemProps> = ({
|
||||
|
||||
const Missions = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const missions = useAppSelector((state) => state.missions.missions);
|
||||
const status = useAppSelector((state) => state.missions.statuses.fetchMy);
|
||||
|
||||
const [modalDeleteTask, setModalDeleteTask] = useState<boolean>(false);
|
||||
const [taskdeleteId, setTaskDeleteId] = useState<number>(0);
|
||||
|
||||
const { data: missionData } = useAppSelector(
|
||||
(state) => state.profile.missions,
|
||||
);
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActiveProfilePage('missions'));
|
||||
dispatch(fetchMyMissions());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -62,46 +73,67 @@ const Missions = () => {
|
||||
</div>
|
||||
<div className="flex flex-row justify-between items-start">
|
||||
<div className="flex gap-[10px]">
|
||||
<Item count={14} totalCount={123} title="Задачи" />
|
||||
<Item
|
||||
count={missionData?.summary?.total?.solved ?? 0}
|
||||
totalCount={
|
||||
missionData?.summary?.total?.total ?? 0
|
||||
}
|
||||
title={
|
||||
missionData?.summary?.total?.label ??
|
||||
'Задачи'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-[20px]">
|
||||
<Item
|
||||
count={14}
|
||||
totalCount={123}
|
||||
title="Easy"
|
||||
color="green"
|
||||
/>
|
||||
<Item
|
||||
count={14}
|
||||
totalCount={123}
|
||||
title="Medium"
|
||||
color="orange"
|
||||
/>
|
||||
<Item
|
||||
count={14}
|
||||
totalCount={123}
|
||||
title="Hard"
|
||||
color="red"
|
||||
/>
|
||||
{missionData?.summary?.buckets?.map((bucket) => (
|
||||
<Item
|
||||
key={bucket.key}
|
||||
count={bucket.solved}
|
||||
totalCount={bucket.total}
|
||||
title={bucket.label}
|
||||
color={
|
||||
bucket.key === 'easy'
|
||||
? 'green'
|
||||
: bucket.key === 'medium'
|
||||
? 'orange'
|
||||
: 'red'
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-[24px] font-bold text-liquid-white">
|
||||
Компетенции
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-[10px]">
|
||||
<Item count={14} totalCount={123} title="Массивы" />
|
||||
<Item count={14} totalCount={123} title="Списки" />
|
||||
<Item count={14} totalCount={123} title="Стэк" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-[20px]">
|
||||
<MissionsBlock
|
||||
missions={missions ?? []}
|
||||
missions={missionData?.authored.items ?? []}
|
||||
title="Мои миссии"
|
||||
setTastDeleteId={setTaskDeleteId}
|
||||
setDeleteModalActive={setModalDeleteTask}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
active={modalDeleteTask}
|
||||
setActive={setModalDeleteTask}
|
||||
title="Подтвердите действия"
|
||||
message={`Вы действительно хотите удалить задачу #${taskdeleteId}?`}
|
||||
confirmColor="error"
|
||||
confirmText="Удалить"
|
||||
onConfirmClick={() => {
|
||||
dispatch(deleteMission(taskdeleteId))
|
||||
.unwrap()
|
||||
.then(() => {
|
||||
dispatch(
|
||||
fetchProfileMissions({
|
||||
username: username,
|
||||
recentPageSize: 1,
|
||||
authoredPageSize: 100,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,18 +2,23 @@ import { useState, FC } from 'react';
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { ChevroneDown } from '../../../../assets/icons/groups';
|
||||
import MyMissionItem from './MyMissionItem';
|
||||
import { Mission } from '../../../../redux/slices/missions';
|
||||
import { MissionItem } from '../../../../redux/slices/profile';
|
||||
|
||||
interface MissionsBlockProps {
|
||||
missions: Mission[];
|
||||
missions: MissionItem[];
|
||||
title: string;
|
||||
className?: string;
|
||||
setTastDeleteId: (v: number) => void;
|
||||
setDeleteModalActive: (v: boolean) => void;
|
||||
}
|
||||
|
||||
const MissionsBlock: FC<MissionsBlockProps> = ({
|
||||
missions,
|
||||
title,
|
||||
className,
|
||||
|
||||
setTastDeleteId,
|
||||
setDeleteModalActive,
|
||||
}) => {
|
||||
const [active, setActive] = useState<boolean>(true);
|
||||
|
||||
@@ -53,12 +58,14 @@ const MissionsBlock: FC<MissionsBlockProps> = ({
|
||||
{missions.map((v, i) => (
|
||||
<MyMissionItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
name={v.name}
|
||||
timeLimit={v.timeLimit}
|
||||
memoryLimit={v.memoryLimit}
|
||||
difficulty={v.difficulty}
|
||||
id={v.missionId}
|
||||
name={v.missionName}
|
||||
timeLimit={v.timeLimitMilliseconds}
|
||||
memoryLimit={v.memoryLimitBytes}
|
||||
difficulty={v.difficultyValue}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
setTastDeleteId={setTastDeleteId}
|
||||
setDeleteModalActive={setDeleteModalActive}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Edit } from '../../../../assets/icons/input';
|
||||
import { Trash } from '../../../../assets/icons/input';
|
||||
import { useAppSelector } from '../../../../redux/hooks';
|
||||
|
||||
export interface MissionItemProps {
|
||||
id: number;
|
||||
@@ -14,6 +15,8 @@ export interface MissionItemProps {
|
||||
updatedAt?: string;
|
||||
type?: 'first' | 'second';
|
||||
status?: 'empty' | 'success' | 'error';
|
||||
setTastDeleteId: (v: number) => void;
|
||||
setDeleteModalActive: (v: boolean) => void;
|
||||
}
|
||||
|
||||
export function formatMilliseconds(ms: number): string {
|
||||
@@ -35,11 +38,19 @@ const MissionItem: React.FC<MissionItemProps> = ({
|
||||
memoryLimit = 256 * 1024 * 1024,
|
||||
type,
|
||||
status,
|
||||
setTastDeleteId,
|
||||
setDeleteModalActive,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const difficultyItems = ['Easy', 'Medium', 'Hard'];
|
||||
const difficultyString =
|
||||
difficultyItems[Math.min(Math.max(0, difficulty - 1), 2)];
|
||||
const calcDifficulty = (d: number) => {
|
||||
if (d <= 1200) return 'Easy';
|
||||
if (d <= 2000) return 'Medium';
|
||||
return 'Hard';
|
||||
};
|
||||
const difficultyString = calcDifficulty(difficulty);
|
||||
const deleteStatus = useAppSelector(
|
||||
(state) => state.missions.statuses.delete,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -75,10 +86,18 @@ const MissionItem: React.FC<MissionItemProps> = ({
|
||||
</div>
|
||||
<div className="h-[24px] w-[24px]">
|
||||
<img
|
||||
src={Edit}
|
||||
className="hover:bg-liquid-light rounded-[8px] transition-all duration-300"
|
||||
src={Trash}
|
||||
className={cn(
|
||||
'hover:bg-liquid-light rounded-[8px] transition-all duration-300',
|
||||
deleteStatus == 'loading' &&
|
||||
'cursor-default pointer-events-none hover:bg-transparent opacity-35',
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (deleteStatus != 'loading') {
|
||||
setTastDeleteId(id);
|
||||
setDeleteModalActive(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { useAppSelector } from '../../../redux/hooks';
|
||||
|
||||
export interface ArticleItemProps {
|
||||
id: number;
|
||||
@@ -9,6 +10,65 @@ export interface ArticleItemProps {
|
||||
|
||||
const ArticleItem: React.FC<ArticleItemProps> = ({ id, name, tags }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const filterTags = useAppSelector(
|
||||
(state) => state.store.articles.articleTagFilter,
|
||||
);
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.articles.filterName,
|
||||
);
|
||||
|
||||
const highlightZ = (name: string, filter: string) => {
|
||||
if (!filter) return name;
|
||||
|
||||
const s = filter.toLowerCase();
|
||||
const t = name.toLowerCase();
|
||||
const n = t.length;
|
||||
const m = s.length;
|
||||
|
||||
const mark = Array(n).fill(false);
|
||||
|
||||
// Проходимся с конца и ставим отметки
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
if (i + m <= n && t.slice(i, i + m) === s) {
|
||||
for (let j = i; j < i + m; j++) {
|
||||
if (mark[j]) break;
|
||||
mark[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Формируем единые жёлтые блоки ===
|
||||
const result: any[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < n) {
|
||||
if (!mark[i]) {
|
||||
// обычный символ
|
||||
result.push(name[i]);
|
||||
i++;
|
||||
} else {
|
||||
// начинаем жёлтый блок
|
||||
let j = i;
|
||||
while (j < n && mark[j]) j++;
|
||||
|
||||
const chunk = name.slice(i, j);
|
||||
result.push(
|
||||
<span
|
||||
key={i}
|
||||
className="bg-yellow-400 text-black rounded px-1"
|
||||
>
|
||||
{chunk}
|
||||
</span>,
|
||||
);
|
||||
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -26,7 +86,7 @@ const ArticleItem: React.FC<ArticleItemProps> = ({ id, name, tags }) => {
|
||||
#{id}
|
||||
</div>
|
||||
<div className="text-[18px] font-bold flex items-center bg-red-400r">
|
||||
{name}
|
||||
{highlightZ(name, nameFilter)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-[14px] flex text-liquid-light gap-[10px] mt-[10px]">
|
||||
@@ -36,6 +96,8 @@ const ArticleItem: React.FC<ArticleItemProps> = ({ id, name, tags }) => {
|
||||
className={cn(
|
||||
'rounded-full px-[16px] py-[8px] bg-liquid-lighter',
|
||||
v == 'Sertificated' && 'text-liquid-green',
|
||||
filterTags.includes(v) &&
|
||||
'border-liquid-brightmain border-[1px] border-solid text-liquid-brightmain',
|
||||
)}
|
||||
>
|
||||
{v}
|
||||
|
||||
@@ -2,7 +2,11 @@ import { useEffect } from 'react';
|
||||
import { SecondaryButton } from '../../../components/button/SecondaryButton';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import ArticleItem from './ArticleItem';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import {
|
||||
setArticlesNameFilter,
|
||||
setArticlesTagFilter,
|
||||
setMenuActivePage,
|
||||
} from '../../../redux/slices/store';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { fetchArticles } from '../../../redux/slices/articles';
|
||||
import Filters from './Filter';
|
||||
@@ -15,39 +19,22 @@ const Articles = () => {
|
||||
const articles = useAppSelector(
|
||||
(state) => state.articles.fetchArticles.articles,
|
||||
);
|
||||
const status = useAppSelector(
|
||||
(state) => state.articles.fetchArticles.status,
|
||||
const tagsFilter = useAppSelector(
|
||||
(state) => state.store.articles.articleTagFilter,
|
||||
);
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.articles.filterName,
|
||||
);
|
||||
const error = useAppSelector((state) => state.articles.fetchArticles.error);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActivePage('articles'));
|
||||
dispatch(fetchArticles({}));
|
||||
}, [dispatch]);
|
||||
dispatch(fetchArticles({ tags: tagsFilter }));
|
||||
}, []);
|
||||
|
||||
// ========================
|
||||
// Состояния загрузки / ошибки
|
||||
// ========================
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<div className="h-full w-full flex items-center justify-center text-liquid-light text-[18px]">
|
||||
Загрузка статей...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
return (
|
||||
<div className="h-full w-full flex flex-col items-center justify-center text-liquid-red text-[18px]">
|
||||
Ошибка при загрузке статей
|
||||
{error && (
|
||||
<div className="text-liquid-light text-[14px] mt-2">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const filterTagsHandler = (value: string[]) => {
|
||||
dispatch(setArticlesTagFilter(value));
|
||||
dispatch(fetchArticles({ tags: value }));
|
||||
};
|
||||
|
||||
// ========================
|
||||
// Основной контент
|
||||
@@ -68,7 +55,14 @@ const Articles = () => {
|
||||
</div>
|
||||
|
||||
{/* Фильтры */}
|
||||
<Filters />
|
||||
<Filters
|
||||
onChangeTags={(value: string[]) => {
|
||||
filterTagsHandler(value);
|
||||
}}
|
||||
onChangeName={(value: string) => {
|
||||
dispatch(setArticlesNameFilter(value));
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Список статей */}
|
||||
<div className="mt-[20px]">
|
||||
@@ -77,14 +71,15 @@ const Articles = () => {
|
||||
Пока нет статей
|
||||
</div>
|
||||
) : (
|
||||
articles.map((v) => <ArticleItem key={v.id} {...v} />)
|
||||
articles
|
||||
.filter((v) =>
|
||||
v.name
|
||||
.toLocaleLowerCase()
|
||||
.includes(nameFilter.toLocaleLowerCase()),
|
||||
)
|
||||
.map((v) => <ArticleItem key={v.id} {...v} />)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Пагинация (пока заглушка) */}
|
||||
<div className="mt-[20px] text-liquid-light text-[14px]">
|
||||
pages
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,48 +1,25 @@
|
||||
import {
|
||||
FilterDropDown,
|
||||
FilterItem,
|
||||
} from '../../../components/drop-down-list/Filter';
|
||||
import { SorterDropDown } from '../../../components/drop-down-list/Sorter';
|
||||
import { FC } from 'react';
|
||||
import { TagFilter } from '../../../components/filters/TagFilter';
|
||||
import { SearchInput } from '../../../components/input/SearchInput';
|
||||
|
||||
const Filters = () => {
|
||||
const items: FilterItem[] = [
|
||||
{ text: 'React', value: 'react' },
|
||||
{ text: 'Vue', value: 'vue' },
|
||||
{ text: 'Angular', value: 'angular' },
|
||||
{ text: 'Svelte', value: 'svelte' },
|
||||
{ text: 'Next.js', value: 'next' },
|
||||
{ text: 'Nuxt', value: 'nuxt' },
|
||||
{ text: 'Solid', value: 'solid' },
|
||||
{ text: 'Qwik', value: 'qwik' },
|
||||
];
|
||||
interface ArticleFiltersProps {
|
||||
onChangeTags: (value: string[]) => void;
|
||||
onChangeName: (value: string) => void;
|
||||
}
|
||||
|
||||
const Filters: FC<ArticleFiltersProps> = ({ onChangeTags, onChangeName }) => {
|
||||
return (
|
||||
<div className=" h-[50px] mb-[20px] flex gap-[20px] items-center">
|
||||
<SearchInput onChange={() => {}} placeholder="Поиск задачи" />
|
||||
|
||||
<SorterDropDown
|
||||
items={[
|
||||
{
|
||||
value: '1',
|
||||
text: 'Сложность',
|
||||
},
|
||||
{
|
||||
value: '2',
|
||||
text: 'Дата создания',
|
||||
},
|
||||
{
|
||||
value: '3',
|
||||
text: 'ID',
|
||||
},
|
||||
]}
|
||||
onChange={(v) => {}}
|
||||
<SearchInput
|
||||
onChange={(value: string) => {
|
||||
onChangeName(value);
|
||||
}}
|
||||
placeholder="Поиск статьи"
|
||||
/>
|
||||
|
||||
<FilterDropDown
|
||||
items={items}
|
||||
defaultState={[]}
|
||||
onChange={(values) => {}}
|
||||
<TagFilter
|
||||
onChange={(value: string[]) => {
|
||||
onChangeTags(value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -8,8 +8,6 @@ import { loginUser } from '../../../redux/slices/auth';
|
||||
// import { cn } from "../../../lib/cn";
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import { Balloon } from '../../../assets/icons/auth';
|
||||
import { SecondaryButton } from '../../../components/button/SecondaryButton';
|
||||
import { googleLogo } from '../../../assets/icons/input';
|
||||
|
||||
const Login = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
@@ -27,7 +25,6 @@ const Login = () => {
|
||||
// После успешного логина
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActivePage('account'));
|
||||
submitClicked;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -47,6 +44,21 @@ const Login = () => {
|
||||
dispatch(loginUser({ username, password }));
|
||||
};
|
||||
|
||||
const getErrorLoginMessage = (): string => {
|
||||
if (!submitClicked) return '';
|
||||
if (username == '') return 'Поле не может быть пустым';
|
||||
if (password == '') return '';
|
||||
if (status === 'failed')
|
||||
return 'Неверное имя пользователя и/или пароль';
|
||||
return '';
|
||||
};
|
||||
|
||||
const getErrorPasswordMessage = (): string => {
|
||||
if (!submitClicked) return '';
|
||||
if (password == '') return 'Поле не может быть пустым';
|
||||
return '';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-svh w-svw fixed pointer-events-none top-0 left-0 flex items-center justify-center">
|
||||
<div className="grid gap-[80px] grid-cols-[400px,384px] box-border relative ">
|
||||
@@ -55,7 +67,7 @@ const Login = () => {
|
||||
</div>
|
||||
<div className=" relative pointer-events-auto">
|
||||
<div>
|
||||
<div className="text-[40px] text-liquid-white font-bold h-[50px]">
|
||||
<div className="text-[35px] text-liquid-white font-bold h-[50px]">
|
||||
С возвращением
|
||||
</div>
|
||||
<div className="text-[18px] text-liquid-light font-bold h-[23px]">
|
||||
@@ -73,6 +85,7 @@ const Login = () => {
|
||||
setUsername(v);
|
||||
}}
|
||||
placeholder="login"
|
||||
error={getErrorLoginMessage()}
|
||||
/>
|
||||
<Input
|
||||
name="password"
|
||||
@@ -84,17 +97,11 @@ const Login = () => {
|
||||
setPassword(v);
|
||||
}}
|
||||
placeholder="abCD1234"
|
||||
error={getErrorPasswordMessage()}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end mt-[10px]">
|
||||
<Link
|
||||
to={''}
|
||||
className={
|
||||
'text-liquid-brightmain text-[16px] h-[20px] transition-all hover:underline '
|
||||
}
|
||||
>
|
||||
Забыли пароль?
|
||||
</Link>
|
||||
<div className="flex justify-end mt-[10px] h-[20px]">
|
||||
|
||||
</div>
|
||||
|
||||
<div className="mt-[10px]">
|
||||
@@ -104,15 +111,6 @@ const Login = () => {
|
||||
text={status === 'loading' ? 'Вход...' : 'Вход'}
|
||||
disabled={status === 'loading'}
|
||||
/>
|
||||
<SecondaryButton className="w-full" onClick={() => {}}>
|
||||
<div className="flex items-center">
|
||||
<img
|
||||
src={googleLogo}
|
||||
className="h-[24px] w-[24px] mr-[15px]"
|
||||
/>
|
||||
Вход с Google
|
||||
</div>
|
||||
</SecondaryButton>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center mt-[10px]">
|
||||
|
||||
@@ -9,9 +9,38 @@ import { registerUser } from '../../../redux/slices/auth';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import { Balloon } from '../../../assets/icons/auth';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { SecondaryButton } from '../../../components/button/SecondaryButton';
|
||||
import { Checkbox } from '../../../components/checkbox/Checkbox';
|
||||
import { googleLogo } from '../../../assets/icons/input';
|
||||
// import { Checkbox } from '../../../components/checkbox/Checkbox';
|
||||
|
||||
function isValidEmail(email: string): boolean {
|
||||
const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
|
||||
return pattern.test(email);
|
||||
}
|
||||
|
||||
function isValidLogin(login: string): boolean {
|
||||
return login.length >= 4 && login.length <= 128;
|
||||
}
|
||||
|
||||
function isValidatePassword(password: string): string {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (password.length < 8 || password.length > 255) {
|
||||
errors.push('Пароль должен содержать от 8 до 255 символов');
|
||||
}
|
||||
|
||||
if (!/[A-Z]/.test(password)) {
|
||||
errors.push('Пароль должен содержать хотя бы одну заглавную букву');
|
||||
}
|
||||
|
||||
if (!/[a-z]/.test(password)) {
|
||||
errors.push('Пароль должен содержать хотя бы одну строчную букву');
|
||||
}
|
||||
|
||||
if (!/[0-9]/.test(password)) {
|
||||
errors.push('Пароль должен содержать хотя бы одну цифру');
|
||||
}
|
||||
|
||||
return errors.join('\n');
|
||||
}
|
||||
|
||||
const Register = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
@@ -23,12 +52,13 @@ const Register = () => {
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [confirmPassword, setConfirmPassword] = useState<string>('');
|
||||
const [submitClicked, setSubmitClicked] = useState<boolean>(false);
|
||||
const [politicChecked, setPoliticChecked] = useState<boolean>(true);
|
||||
|
||||
const { status, jwt } = useAppSelector((state) => state.auth);
|
||||
|
||||
// После успешной регистрации — переход в систему
|
||||
// const { errors } = useAppSelector((state) => state.auth.register);
|
||||
|
||||
useEffect(() => {
|
||||
setPoliticChecked(true);
|
||||
dispatch(setMenuActivePage('account'));
|
||||
}, []);
|
||||
|
||||
@@ -38,18 +68,73 @@ const Register = () => {
|
||||
const path = from ? from.pathname + from.search : '/home/account';
|
||||
navigate(path, { replace: true });
|
||||
}
|
||||
submitClicked;
|
||||
}, [jwt]);
|
||||
|
||||
const handleRegister = () => {
|
||||
setSubmitClicked(true);
|
||||
|
||||
if (!politicChecked) return;
|
||||
if (!username || !email || !password || !confirmPassword) return;
|
||||
if (password !== confirmPassword) return;
|
||||
if (
|
||||
!isValidEmail(email) ||
|
||||
!isValidLogin(username) ||
|
||||
isValidatePassword(password) != ''
|
||||
)
|
||||
return;
|
||||
|
||||
dispatch(registerUser({ username, email, password }));
|
||||
};
|
||||
|
||||
const getErrorEmailMessage = (): string => {
|
||||
if (!submitClicked) return '';
|
||||
if (email == '') return 'Поле не может быть пустым';
|
||||
if (!isValidEmail(email)) return 'Почта не валидна';
|
||||
if (!username || !email || !password || !confirmPassword) return '';
|
||||
if (password !== confirmPassword) return '';
|
||||
// if (errors?.Email) {
|
||||
// return errors.Email.join('\n');
|
||||
// }
|
||||
return '';
|
||||
};
|
||||
|
||||
const getErrorLoginMessage = (): string => {
|
||||
if (!submitClicked) return '';
|
||||
if (username == '') return 'Поле не может быть пустым';
|
||||
if (!isValidLogin(username))
|
||||
return 'Логин дложен быть длиной от 4 до 128 символов';
|
||||
if (!username || !email || !password || !confirmPassword) return '';
|
||||
if (password !== confirmPassword) return '';
|
||||
// if (errors?.Username) {
|
||||
// return errors.Username.join('\n');
|
||||
// }
|
||||
return '';
|
||||
};
|
||||
|
||||
const getErrorPasswordMessage = (): string => {
|
||||
if (!submitClicked) return '';
|
||||
if (password == '') return 'Поле не может быть пустым';
|
||||
const val = isValidatePassword(password);
|
||||
if (val != '') return val;
|
||||
if (confirmPassword != password) return 'Пароли не совпадают';
|
||||
if (!username || !email || !password || !confirmPassword) return '';
|
||||
// if (errors?.Password) {
|
||||
// return errors.Password.join('\n');
|
||||
// }
|
||||
return '';
|
||||
};
|
||||
|
||||
const getErrorConfirmPasswordMessage = (): string => {
|
||||
if (!submitClicked) return '';
|
||||
if (confirmPassword == '') return 'Поле не может быть пустым';
|
||||
const val = isValidatePassword(confirmPassword);
|
||||
if (val != '') return val;
|
||||
if (confirmPassword != password) return 'Пароли не совпадают';
|
||||
if (!username || !email || !password || !confirmPassword) return '';
|
||||
|
||||
return '';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-svh w-svw fixed pointer-events-none top-0 left-0 flex items-center justify-center">
|
||||
<div className="grid gap-[80px] grid-cols-[400px,384px] box-border relative ">
|
||||
@@ -58,7 +143,7 @@ const Register = () => {
|
||||
</div>
|
||||
<div className=" relative pointer-events-auto">
|
||||
<div>
|
||||
<div className="text-[40px] text-liquid-white font-bold h-[50px]">
|
||||
<div className="text-[35px] text-liquid-white font-bold h-[50px]">
|
||||
Добро пожаловать
|
||||
</div>
|
||||
<div className="text-[18px] text-liquid-light font-bold h-[23px]">
|
||||
@@ -76,6 +161,7 @@ const Register = () => {
|
||||
setEmail(v);
|
||||
}}
|
||||
placeholder="example@gmail.com"
|
||||
error={getErrorEmailMessage()}
|
||||
/>
|
||||
<Input
|
||||
name="login"
|
||||
@@ -87,6 +173,7 @@ const Register = () => {
|
||||
setUsername(v);
|
||||
}}
|
||||
placeholder="login"
|
||||
error={getErrorLoginMessage()}
|
||||
/>
|
||||
<Input
|
||||
name="password"
|
||||
@@ -98,6 +185,7 @@ const Register = () => {
|
||||
setPassword(v);
|
||||
}}
|
||||
placeholder="abCD1234"
|
||||
error={getErrorPasswordMessage()}
|
||||
/>
|
||||
<Input
|
||||
name="confirm-password"
|
||||
@@ -109,16 +197,21 @@ const Register = () => {
|
||||
setConfirmPassword(v);
|
||||
}}
|
||||
placeholder="abCD1234"
|
||||
error={getErrorConfirmPasswordMessage()}
|
||||
/>
|
||||
|
||||
<div className=" flex items-center mt-[10px] h-[24px]">
|
||||
<Checkbox
|
||||
{/* <Checkbox
|
||||
onChange={(value: boolean) => {
|
||||
value;
|
||||
setPoliticChecked(value);
|
||||
}}
|
||||
className="p-0 w-fit m-[2.75px]"
|
||||
size="md"
|
||||
color="secondary"
|
||||
color={
|
||||
politicChecked || !submitClicked
|
||||
? 'secondary'
|
||||
: 'danger'
|
||||
}
|
||||
variant="default"
|
||||
/>
|
||||
<span className="text-[14px] font-medium text-liquid-light h-[18px] ml-[10px]">
|
||||
@@ -126,7 +219,10 @@ const Register = () => {
|
||||
<Link to={'/home'} className={' underline'}>
|
||||
политику конфиденциальности
|
||||
</Link>
|
||||
</span>
|
||||
<span className={' underline cursor-pointer'}>
|
||||
политику конфиденциальности
|
||||
</span>
|
||||
</span> */}
|
||||
</div>
|
||||
|
||||
<div className="mt-[10px]">
|
||||
@@ -140,15 +236,6 @@ const Register = () => {
|
||||
}
|
||||
disabled={status === 'loading'}
|
||||
/>
|
||||
<SecondaryButton className="w-full" onClick={() => {}}>
|
||||
<div className="flex items-center">
|
||||
<img
|
||||
src={googleLogo}
|
||||
className="h-[24px] w-[24px] mr-[15px]"
|
||||
/>
|
||||
Регистрация с Google
|
||||
</div>
|
||||
</SecondaryButton>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center mt-[10px]">
|
||||
|
||||
@@ -2,7 +2,10 @@ import { useEffect } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import { Navigate, Route, Routes, useParams } from 'react-router-dom';
|
||||
import { fetchContestById } from '../../../redux/slices/contests';
|
||||
import {
|
||||
fetchContestById,
|
||||
fetchMyAttemptsInContest,
|
||||
} from '../../../redux/slices/contests';
|
||||
import ContestMissions from './Missions';
|
||||
import Submissions from './Submissions';
|
||||
|
||||
@@ -30,6 +33,7 @@ const Contest = () => {
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchContestById(contestIdNumber));
|
||||
dispatch(fetchMyAttemptsInContest(contestIdNumber));
|
||||
}, [contestIdNumber]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -2,6 +2,7 @@ import { cn } from '../../../lib/cn';
|
||||
import { IconError, IconSuccess } from '../../../assets/icons/missions';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { toastWarning } from '../../../lib/toastNotification';
|
||||
|
||||
export interface MissionItemProps {
|
||||
contestId: number;
|
||||
@@ -11,6 +12,7 @@ export interface MissionItemProps {
|
||||
memoryLimit?: number;
|
||||
type?: 'first' | 'second';
|
||||
status?: 'success' | 'error';
|
||||
attemptsStarted?: boolean;
|
||||
}
|
||||
|
||||
export function formatMilliseconds(ms: number): string {
|
||||
@@ -32,6 +34,7 @@ const MissionItem: React.FC<MissionItemProps> = ({
|
||||
memoryLimit = 256 * 1024 * 1024,
|
||||
type,
|
||||
status,
|
||||
attemptsStarted,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
@@ -50,7 +53,12 @@ const MissionItem: React.FC<MissionItemProps> = ({
|
||||
'cursor-pointer brightness-100 hover:brightness-125 transition-all duration-300',
|
||||
)}
|
||||
onClick={() => {
|
||||
navigate(`/mission/${id}?back=${path}&contestId=${contestId}`);
|
||||
if (attemptsStarted){
|
||||
navigate(`/mission/${id}?back=${path}&contestId=${contestId}`);
|
||||
}
|
||||
else{
|
||||
toastWarning("Нужно начать попытку")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="text-[18px] font-bold">#{id}</div>
|
||||
|
||||
@@ -1,124 +1,215 @@
|
||||
import { FC, useEffect } from "react";
|
||||
import MissionItem from "./MissionItem";
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import MissionItem from './MissionItem';
|
||||
import {
|
||||
Contest,
|
||||
fetchMySubmissions,
|
||||
setContestStatus,
|
||||
} from "../../../redux/slices/contests";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { PrimaryButton } from "../../../components/button/PrimaryButton";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { arrowLeft } from "../../../assets/icons/header";
|
||||
Contest,
|
||||
fetchMyAttemptsInContest,
|
||||
fetchMySubmissions,
|
||||
setContestStatus,
|
||||
startContestAttempt,
|
||||
} from '../../../redux/slices/contests';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { PrimaryButton } from '../../../components/button/PrimaryButton';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { arrowLeft } from '../../../assets/icons/header';
|
||||
import { useQuery } from '../../../hooks/useQuery';
|
||||
|
||||
export interface Article {
|
||||
id: number;
|
||||
name: string;
|
||||
tags: string[];
|
||||
id: number;
|
||||
name: string;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
interface ContestMissionsProps {
|
||||
contest?: Contest;
|
||||
contest?: Contest;
|
||||
}
|
||||
|
||||
const ContestMissions: FC<ContestMissionsProps> = ({ contest }) => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
const { submissions, status } = useAppSelector(
|
||||
(state) => state.contests.fetchMySubmissions
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
useEffect(() => {
|
||||
if (contest) dispatch(fetchMySubmissions(contest.id));
|
||||
}, [contest]);
|
||||
const query = useQuery();
|
||||
const url = query.get('back') ?? '/home/contests';
|
||||
|
||||
useEffect(() => {
|
||||
if (status == "successful") {
|
||||
dispatch(setContestStatus({ key: "fetchMySubmissions", status: "idle" }));
|
||||
const { status } = useAppSelector(
|
||||
(state) => state.contests.fetchMySubmissions,
|
||||
);
|
||||
|
||||
const attempts = useAppSelector(
|
||||
(state) => state.contests.fetchMyAttemptsInContest.attempts,
|
||||
);
|
||||
const submissions = useAppSelector(
|
||||
(state) =>
|
||||
state.contests.fetchMyAttemptsInContest.attempts[0]?.submissions,
|
||||
);
|
||||
|
||||
const [attemptsStarted, setAttemptsStarted] = useState<boolean>(false);
|
||||
|
||||
const [time, setTime] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const calc = (time: string) => {
|
||||
return time != '' && new Date() <= new Date(time);
|
||||
};
|
||||
if (attempts.length && calc(attempts[0].expiresAt)) {
|
||||
setAttemptsStarted(true);
|
||||
|
||||
const diffMs =
|
||||
new Date(attempts[0].expiresAt).getTime() -
|
||||
new Date().getTime();
|
||||
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
|
||||
setTime(seconds);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setTime((t) => {
|
||||
if (t <= 1) {
|
||||
clearInterval(interval); // остановка таймера
|
||||
setAttemptsStarted(false); // можно закрыть попытку или уведомить пользователя
|
||||
return 0;
|
||||
}
|
||||
return t - 1;
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
} else setAttemptsStarted(false);
|
||||
}, [attempts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (contest) dispatch(fetchMySubmissions(contest.id));
|
||||
}, [contest]);
|
||||
|
||||
useEffect(() => {
|
||||
if (status == 'successful') {
|
||||
dispatch(
|
||||
setContestStatus({ key: 'fetchMySubmissions', status: 'idle' }),
|
||||
);
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
if (!contest) {
|
||||
return <></>;
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
if (!contest) {
|
||||
return <></>;
|
||||
}
|
||||
const solvedCount = (contest.missions ?? []).filter((mission) =>
|
||||
submissions?.some(
|
||||
(s) =>
|
||||
s.solution.missionId === mission.id &&
|
||||
s.solution.status === 'Accepted: All tests passed',
|
||||
),
|
||||
).length;
|
||||
|
||||
const solvedCount = (contest.missions ?? []).filter((mission) =>
|
||||
submissions.some(
|
||||
(s) =>
|
||||
s.solution.missionId === mission.id &&
|
||||
s.solution.status === "Accepted: All tests passed"
|
||||
)
|
||||
).length;
|
||||
const totalCount = contest.missions?.length ?? 0;
|
||||
|
||||
const totalCount = contest.missions?.length ?? 0;
|
||||
// форматирование: mm:ss
|
||||
const minutes = String(Math.floor(time / 60)).padStart(2, '0');
|
||||
const seconds = String(time % 60).padStart(2, '0');
|
||||
|
||||
return (
|
||||
<div className=" h-screen grid grid-rows-[74px,40px,1fr] p-[20px] gap-[20px]">
|
||||
<div className="">
|
||||
<div className="h-[50px] text-[40px] text-liquid-white font-bold">
|
||||
{contest.name}
|
||||
return (
|
||||
<div className=" h-screen grid grid-rows-[74px,40px,1fr] p-[20px] gap-[20px]">
|
||||
<div className="">
|
||||
<div className="h-[50px] text-[40px] text-liquid-white font-bold">
|
||||
{contest.name}
|
||||
</div>
|
||||
<div className="flex justify-between h-[24px] items-center gap-[10px]">
|
||||
<div className="flex items-center">
|
||||
<img
|
||||
src={arrowLeft}
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
navigate(url);
|
||||
}}
|
||||
/>
|
||||
<span className="text-liquid-light font-bold text-[18px]">
|
||||
Контест #{contest.id}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-liquid-light font-bold text-[18px]">
|
||||
{attemptsStarted
|
||||
? `${minutes}:${seconds}`
|
||||
: `Длительность попытки: ${
|
||||
contest.attemptDurationMinutes ?? 0
|
||||
} минут. Осталось попыток ${
|
||||
(contest.maxAttempts ?? 0) -
|
||||
(attempts?.length ?? 0)
|
||||
}/${contest.maxAttempts ?? 0}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-liquid-white text-[16px] font-bold">{`${solvedCount}/${totalCount} Решено`}</div>
|
||||
<div className="flex gap-[20px]">
|
||||
{attempts.length == 0 || !attemptsStarted ? (
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
dispatch(startContestAttempt(contest.id))
|
||||
.unwrap()
|
||||
.then(() => {
|
||||
dispatch(
|
||||
fetchMyAttemptsInContest(
|
||||
contest.id,
|
||||
),
|
||||
);
|
||||
});
|
||||
}}
|
||||
text="Начать попытку"
|
||||
disabled={
|
||||
(contest.maxAttempts ?? 0) -
|
||||
(attempts?.length ?? 0) <=
|
||||
0
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}{' '}
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
navigate(`/contest/${contest.id}/submissions`);
|
||||
}}
|
||||
text="Мои посылки"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-full min-h-0 overflow-y-scroll medium-scrollbar flex flex-col gap-[20px]">
|
||||
<div className="w-full">
|
||||
{(contest.missions ?? []).map((v, i) => {
|
||||
const missionSubmissions = submissions?.filter(
|
||||
(s) => s.solution.missionId === v.id,
|
||||
);
|
||||
|
||||
const hasSuccess = missionSubmissions?.some(
|
||||
(s) =>
|
||||
s.solution.status ==
|
||||
'Accepted: All tests passed',
|
||||
);
|
||||
|
||||
const status = hasSuccess
|
||||
? 'success'
|
||||
: missionSubmissions?.length &&
|
||||
missionSubmissions.length > 0
|
||||
? 'error'
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<MissionItem
|
||||
attemptsStarted={attemptsStarted}
|
||||
contestId={contest.id}
|
||||
key={i}
|
||||
id={v.id}
|
||||
name={v.name}
|
||||
timeLimit={v.timeLimitMilliseconds}
|
||||
memoryLimit={v.memoryLimitBytes}
|
||||
status={status}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between h-[24px] items-center gap-[10px]">
|
||||
<div className="flex items-center">
|
||||
<img
|
||||
src={arrowLeft}
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
navigate(`/home/contests`);
|
||||
}}
|
||||
/>
|
||||
<span className="text-liquid-light font-bold text-[18px]">
|
||||
Контест #{contest.id}
|
||||
</span>
|
||||
</div>
|
||||
<div>{contest.attemptDurationMinutes ?? 0} минут</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-liquid-white text-[16px] font-bold">{`${solvedCount}/${totalCount} Решено`}</div>
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
navigate(`/contest/${contest.id}/submissions`);
|
||||
}}
|
||||
text="Мои посылки"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-full min-h-0 overflow-y-scroll medium-scrollbar flex flex-col gap-[20px]">
|
||||
<div className="w-full">
|
||||
{(contest.missions ?? []).map((v, i) => {
|
||||
const missionSubmissions = submissions.filter(
|
||||
(s) => s.solution.missionId === v.id
|
||||
);
|
||||
|
||||
const hasSuccess = missionSubmissions.some(
|
||||
(s) => s.solution.status == "Accepted: All tests passed"
|
||||
);
|
||||
|
||||
console.log(missionSubmissions);
|
||||
|
||||
const status = hasSuccess
|
||||
? "success"
|
||||
: missionSubmissions.length > 0
|
||||
? "error"
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<MissionItem
|
||||
contestId={contest.id}
|
||||
key={i}
|
||||
id={v.id}
|
||||
name={v.name}
|
||||
timeLimit={v.timeLimitMilliseconds}
|
||||
memoryLimit={v.memoryLimitBytes}
|
||||
status={status}
|
||||
type={i % 2 ? "second" : "first"}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
||||
export default ContestMissions;
|
||||
|
||||
@@ -1,129 +1,81 @@
|
||||
import SubmissionItem from "./SubmissionItem";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { FC, useEffect } from "react";
|
||||
import {
|
||||
Contest,
|
||||
fetchMySubmissions,
|
||||
setContestStatus,
|
||||
} from "../../../redux/slices/contests";
|
||||
import { arrowLeft } from "../../../assets/icons/header";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { FC, useEffect } from 'react';
|
||||
import { Contest, fetchMySubmissions } from '../../../redux/slices/contests';
|
||||
import { arrowLeft } from '../../../assets/icons/header';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import SubmissionsBlock from './SubmissionsBlock';
|
||||
|
||||
export interface Mission {
|
||||
id: number;
|
||||
authorId: number;
|
||||
name: string;
|
||||
difficulty: "Easy" | "Medium" | "Hard";
|
||||
tags: string[];
|
||||
timeLimit: number;
|
||||
memoryLimit: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
id: number;
|
||||
authorId: number;
|
||||
name: string;
|
||||
difficulty: 'Easy' | 'Medium' | 'Hard';
|
||||
tags: string[];
|
||||
timeLimit: number;
|
||||
memoryLimit: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface SubmissionsProps {
|
||||
contest: Contest;
|
||||
contest: Contest;
|
||||
}
|
||||
|
||||
const Submissions: FC<SubmissionsProps> = ({ contest }) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { submissions, status } = useAppSelector(
|
||||
(state) => state.contests.fetchMySubmissions
|
||||
);
|
||||
const attempts = useAppSelector(
|
||||
(state) => state.contests.fetchMyAttemptsInContest.attempts,
|
||||
);
|
||||
const submissions = useAppSelector(
|
||||
(state) =>
|
||||
state.contests.fetchMyAttemptsInContest.attempts[0]?.submissions,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (contest && contest.id) dispatch(fetchMySubmissions(contest.id));
|
||||
}, [contest]);
|
||||
useEffect(() => {
|
||||
if (contest && contest.id) dispatch(fetchMySubmissions(contest.id));
|
||||
}, [contest]);
|
||||
|
||||
useEffect(() => {
|
||||
if (status == "successful") {
|
||||
dispatch(setContestStatus({ key: "fetchMySubmissions", status: "idle" }));
|
||||
}
|
||||
}, [status]);
|
||||
const solvedCount = (contest.missions ?? []).filter((mission) =>
|
||||
submissions?.some(
|
||||
(s) =>
|
||||
s.solution.missionId === mission.id &&
|
||||
s.solution.status === 'Accepted: All tests passed',
|
||||
),
|
||||
).length;
|
||||
|
||||
const checkStatus = (status: string) => {
|
||||
if (status == "IncorrectAnswer") return "wronganswer";
|
||||
if (status == "TimeLimitError") return "timelimit";
|
||||
return undefined;
|
||||
};
|
||||
const totalCount = contest.missions?.length ?? 0;
|
||||
|
||||
const solvedCount = (contest.missions ?? []).filter((mission) =>
|
||||
submissions.some(
|
||||
(s) =>
|
||||
s.solution.missionId === mission.id &&
|
||||
s.solution.status === "Accepted: All tests passed"
|
||||
)
|
||||
).length;
|
||||
|
||||
const totalCount = contest.missions?.length ?? 0;
|
||||
|
||||
return (
|
||||
<div className="h-full w-[calc(100%+250px)] box-border overflow-y-scroll overflow-x-hidden thin-scrollbar p-[20px] flex flex-col gap-[20px]">
|
||||
<div className="">
|
||||
<div className="h-[50px] text-[40px] text-liquid-white font-bold">
|
||||
{contest.name}
|
||||
return (
|
||||
<div className="h-full w-[calc(100%+250px)] box-border overflow-y-scroll overflow-x-hidden thin-scrollbar p-[20px] flex flex-col gap-[20px]">
|
||||
<div className="">
|
||||
<div className="h-[50px] text-[40px] text-liquid-white font-bold">
|
||||
{contest.name}
|
||||
</div>
|
||||
<div className="flex justify-between h-[24px] items-center gap-[10px]">
|
||||
<div className="flex items-center">
|
||||
<img
|
||||
src={arrowLeft}
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
navigate(`/contest/${contest.id}`);
|
||||
}}
|
||||
/>
|
||||
<span className="text-liquid-light font-bold text-[18px]">
|
||||
Контест #{contest.id}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-liquid-white text-[16px] font-bold">{`${solvedCount}/${totalCount} Решено`}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-full overflow-y-scroll medium-scrollbar pr-[20px]">
|
||||
{attempts?.map((v, i) => (
|
||||
<SubmissionsBlock key={i} attempt={v} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between h-[24px] items-center gap-[10px]">
|
||||
<div className="flex items-center">
|
||||
<img
|
||||
src={arrowLeft}
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
navigate(`/contest/${contest.id}`);
|
||||
}}
|
||||
/>
|
||||
<span className="text-liquid-light font-bold text-[18px]">
|
||||
Контест #{contest.id}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-liquid-white text-[16px] font-bold">{`${solvedCount}/${totalCount} Решено`}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="grid grid-cols-7 text-center items-center h-[43px] mb-[10px] text-[16px] font-bold text-liquid-white">
|
||||
<div>Посылка</div>
|
||||
<div>Когда</div>
|
||||
<div>Задача</div>
|
||||
<div>Язык</div>
|
||||
<div>Вердикт</div>
|
||||
<div>Время</div>
|
||||
<div>Память</div>
|
||||
</div>
|
||||
|
||||
{!submissions || submissions.length == 0 ? (
|
||||
<div className="text-liquid-brightmain text-[16px] font-medium text-center mt-[50px]">Вы еще ничего не отсылали</div>
|
||||
) : (
|
||||
<>
|
||||
{submissions.map((v, i) => (
|
||||
<SubmissionItem
|
||||
key={i}
|
||||
id={v.id ?? 0}
|
||||
datetime={v.solution.time}
|
||||
missionId={v.solution.missionId}
|
||||
language={v.solution.language}
|
||||
verdict={
|
||||
v.solution.testerMessage?.includes("Compilation failed")
|
||||
? "Compilation failed"
|
||||
: v.solution.testerMessage
|
||||
}
|
||||
duration={1000}
|
||||
memory={256 * 1024 * 1024}
|
||||
type={i % 2 ? "second" : "first"}
|
||||
status={
|
||||
v.solution.testerMessage == "All tests passed"
|
||||
? "success"
|
||||
: checkStatus(v.solution.testerErrorCode)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
||||
export default Submissions;
|
||||
|
||||
75
src/views/home/contest/SubmissionsBlock.tsx
Normal file
75
src/views/home/contest/SubmissionsBlock.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import SubmissionItem from './SubmissionItem';
|
||||
import { FC } from 'react';
|
||||
import { Attempt } from '../../../redux/slices/contests';
|
||||
|
||||
interface SubmissionsBlockProps {
|
||||
attempt: Attempt;
|
||||
}
|
||||
|
||||
const SubmissionsBlock: FC<SubmissionsBlockProps> = ({ attempt }) => {
|
||||
const submissions = attempt?.submissions;
|
||||
const isFinished = new Date(attempt.expiresAt) < new Date();
|
||||
|
||||
const checkStatus = (status: string) => {
|
||||
if (status == 'IncorrectAnswer') return 'wronganswer';
|
||||
if (status == 'TimeLimitError') return 'timelimit';
|
||||
return undefined;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-[50px]">
|
||||
<div className="flex items-center justify-center text-liquid-white font-bold text-[20px]">{`Попытка #${attempt.attemptId}`}</div>
|
||||
{!submissions || submissions.length == 0 ? (
|
||||
<></>
|
||||
) : (
|
||||
<div className="grid grid-cols-7 text-center items-center h-[43px] mb-[10px] text-[16px] font-bold text-liquid-white">
|
||||
<div>Посылка</div>
|
||||
<div>Когда</div>
|
||||
<div>Задача</div>
|
||||
<div>Язык</div>
|
||||
<div>Вердикт</div>
|
||||
<div>Время</div>
|
||||
<div>Память</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!submissions || submissions.length == 0 ? (
|
||||
<div className="text-liquid-brightmain text-[16px] font-medium text-center">
|
||||
{isFinished
|
||||
? 'Вы ничего не посылали в этот сеанс'
|
||||
: 'Вы еще ничего не отсылали'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{submissions.map((v, i) => (
|
||||
<SubmissionItem
|
||||
key={i}
|
||||
id={v.id ?? 0}
|
||||
datetime={v.solution.time}
|
||||
missionId={v.solution.missionId}
|
||||
language={v.solution.language}
|
||||
verdict={
|
||||
v.solution.testerMessage?.includes(
|
||||
'Compilation failed',
|
||||
)
|
||||
? 'Compilation failed'
|
||||
: v.solution.testerMessage
|
||||
}
|
||||
duration={1000}
|
||||
memory={256 * 1024 * 1024}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
status={
|
||||
v.solution.testerMessage == 'All tests passed'
|
||||
? 'success'
|
||||
: checkStatus(v.solution.testerErrorCode)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<div className="h-[1px] bg-liquid-lighter mt-[50px]"></div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SubmissionsBlock;
|
||||
@@ -1,114 +0,0 @@
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { Account } from '../../../assets/icons/auth';
|
||||
import { PrimaryButton } from '../../../components/button/PrimaryButton';
|
||||
import { ReverseButton } from '../../../components/button/ReverseButton';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export interface ContestItemProps {
|
||||
id: number;
|
||||
name: string;
|
||||
startAt: string;
|
||||
duration: number;
|
||||
members: number;
|
||||
statusRegister: 'reg' | 'nonreg';
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatWaitTime(ms: number): string {
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const ContestItem: React.FC<ContestItemProps> = ({
|
||||
id,
|
||||
name,
|
||||
startAt,
|
||||
duration,
|
||||
members,
|
||||
statusRegister,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const now = new Date();
|
||||
|
||||
const waitTime = new Date(startAt).getTime() - now.getTime();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[10px] text-liquid-white text-[16px] leading-[20px] cursor-pointer',
|
||||
waitTime <= 0 ? 'grid grid-cols-6' : 'grid grid-cols-7',
|
||||
'items-center font-bold text-liquid-white',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
navigate(`/contest/${id}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal ">
|
||||
{/* {authors.map((v, i) => <p key={i}>{v}</p>)} */}
|
||||
valavshonok
|
||||
</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startAt)}
|
||||
</div>
|
||||
<div className="text-center">{formatWaitTime(duration)}</div>
|
||||
{waitTime > 0 && (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До начала\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
)}
|
||||
<div className="items-center justify-center flex gap-[10px] flex-row w-full">
|
||||
<div>{members}</div>
|
||||
<img src={Account} className="h-[24px] w-[24px]" />
|
||||
</div>
|
||||
<div className="flex items-center justify-end">
|
||||
{statusRegister == 'reg' ? (
|
||||
<>
|
||||
{' '}
|
||||
<PrimaryButton onClick={() => {}} text="Регистрация" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{' '}
|
||||
<ReverseButton onClick={() => {}} text="Вы записаны" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContestItem;
|
||||
@@ -3,30 +3,40 @@ import { SecondaryButton } from '../../../components/button/SecondaryButton';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import ContestsBlock from './ContestsBlock';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import { fetchContests } from '../../../redux/slices/contests';
|
||||
import {
|
||||
setContestsNameFilter,
|
||||
setMenuActivePage,
|
||||
} from '../../../redux/slices/store';
|
||||
import {
|
||||
fetchContests,
|
||||
fetchMyContests,
|
||||
fetchParticipatingContests,
|
||||
} from '../../../redux/slices/contests';
|
||||
import ModalCreateContest from './ModalCreate';
|
||||
import Filters from './Filter';
|
||||
import { toastWarning } from '../../../lib/toastNotification';
|
||||
|
||||
const Contests = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const now = new Date();
|
||||
|
||||
const [modalActive, setModalActive] = useState<boolean>(false);
|
||||
|
||||
// Берём данные из Redux
|
||||
const contests = useAppSelector(
|
||||
(state) => state.contests.fetchContests.contests,
|
||||
const jwt = useAppSelector((state) => state.auth.jwt);
|
||||
|
||||
const { contests, status } = useAppSelector(
|
||||
(state) => state.contests.fetchContests,
|
||||
);
|
||||
const status = useAppSelector(
|
||||
(state) => state.contests.fetchContests.status,
|
||||
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.contests.filterName,
|
||||
);
|
||||
const error = useAppSelector((state) => state.contests.fetchContests.error);
|
||||
|
||||
// При загрузке страницы — выставляем активную вкладку и подгружаем контесты
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActivePage('contests'));
|
||||
dispatch(fetchContests({}));
|
||||
dispatch(fetchParticipatingContests({ pageSize: 100 }));
|
||||
dispatch(fetchMyContests());
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -42,6 +52,10 @@ const Contests = () => {
|
||||
</div>
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
if (!jwt){
|
||||
toastWarning("Для создания контеста необходимо авторизоваться")
|
||||
return;
|
||||
}
|
||||
setModalActive(true);
|
||||
}}
|
||||
text="Создать контест"
|
||||
@@ -49,37 +63,46 @@ const Contests = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Filters />
|
||||
<Filters
|
||||
onChangeName={(v: string) => {
|
||||
dispatch(setContestsNameFilter(v));
|
||||
}}
|
||||
/>
|
||||
{status == 'loading' && (
|
||||
<div className="text-liquid-white p-4">
|
||||
Загрузка контестов...
|
||||
</div>
|
||||
)}
|
||||
{status == 'failed' && (
|
||||
<div className="text-red-500 p-4">Ошибка: {error}</div>
|
||||
)}
|
||||
{status == 'successful' && (
|
||||
<>
|
||||
<ContestsBlock
|
||||
className="mb-[20px]"
|
||||
title="Текущие"
|
||||
contests={contests.filter((contest) => {
|
||||
const endTime = new Date(
|
||||
contest.endsAt ?? new Date().toDateString(),
|
||||
).getTime();
|
||||
return endTime >= now.getTime();
|
||||
})}
|
||||
contests={contests
|
||||
.filter((v) =>
|
||||
v.name
|
||||
.toLocaleLowerCase()
|
||||
.includes(
|
||||
nameFilter.toLocaleLowerCase(),
|
||||
),
|
||||
)
|
||||
.filter((c) => c.scheduleType != 'AlwaysOpen')}
|
||||
type="upcoming"
|
||||
/>
|
||||
|
||||
<ContestsBlock
|
||||
className="mb-[20px]"
|
||||
title="Прошедшие"
|
||||
contests={contests.filter((contest) => {
|
||||
const endTime = new Date(
|
||||
contest.endsAt ?? new Date().toDateString(),
|
||||
).getTime();
|
||||
return endTime < now.getTime();
|
||||
})}
|
||||
title="Постоянные"
|
||||
contests={contests
|
||||
.filter((v) =>
|
||||
v.name
|
||||
.toLocaleLowerCase()
|
||||
.includes(
|
||||
nameFilter.toLocaleLowerCase(),
|
||||
),
|
||||
)
|
||||
.filter((c) => c.scheduleType == 'AlwaysOpen')}
|
||||
type="past"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
import { useState, FC } from 'react';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { ChevroneDown } from '../../../assets/icons/groups';
|
||||
import ContestItem from './ContestItem';
|
||||
import { Contest } from '../../../redux/slices/contests';
|
||||
import PastContestItem from './PastContestItem';
|
||||
import UpcoingContestItem from './UpcomingContestItem';
|
||||
|
||||
interface ContestsBlockProps {
|
||||
contests: Contest[];
|
||||
title: string;
|
||||
className?: string;
|
||||
type: 'upcoming' | 'past';
|
||||
}
|
||||
|
||||
const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
contests,
|
||||
title,
|
||||
className,
|
||||
type,
|
||||
}) => {
|
||||
const [active, setActive] = useState<boolean>(title != 'Скрытые');
|
||||
|
||||
@@ -33,11 +36,11 @@ const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
setActive(!active);
|
||||
}}
|
||||
>
|
||||
<span>{title}</span>
|
||||
<span className=" select-none">{title}</span>
|
||||
<img
|
||||
src={ChevroneDown}
|
||||
className={cn(
|
||||
'transition-all duration-300',
|
||||
'transition-all duration-300 select-none',
|
||||
active && 'rotate-180',
|
||||
)}
|
||||
/>
|
||||
@@ -50,21 +53,51 @@ const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="pb-[10px] pt-[20px]">
|
||||
{contests.map((v, i) => (
|
||||
<ContestItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
name={v.name}
|
||||
startAt={v.startsAt ?? new Date().toString()}
|
||||
statusRegister={'reg'}
|
||||
duration={
|
||||
new Date(v.endsAt ?? new Date().toString()).getTime() -
|
||||
new Date(v.startsAt ?? new Date().toString()).getTime()
|
||||
}
|
||||
members={v.members?.length ?? 0}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
))}
|
||||
{contests.map((v, i) => {
|
||||
if (type == 'past') {
|
||||
return (
|
||||
<PastContestItem
|
||||
key={i}
|
||||
contestId={v.id}
|
||||
scheduleType={v.scheduleType}
|
||||
name={v.name}
|
||||
startsAt={
|
||||
v.startsAt ?? new Date().toString()
|
||||
}
|
||||
endsAt={
|
||||
v.endsAt ?? new Date().toString()
|
||||
}
|
||||
attemptDurationMinutes={
|
||||
v.attemptDurationMinutes ?? 0
|
||||
}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type == 'upcoming') {
|
||||
return (
|
||||
<UpcoingContestItem
|
||||
key={i}
|
||||
contestId={v.id}
|
||||
scheduleType={v.scheduleType}
|
||||
name={v.name}
|
||||
startsAt={
|
||||
v.startsAt ?? new Date().toString()
|
||||
}
|
||||
endsAt={
|
||||
v.endsAt ?? new Date().toString()
|
||||
}
|
||||
attemptDurationMinutes={
|
||||
v.attemptDurationMinutes ?? 0
|
||||
}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <></>;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,48 +1,18 @@
|
||||
import {
|
||||
FilterDropDown,
|
||||
FilterItem,
|
||||
} from '../../../components/drop-down-list/Filter';
|
||||
import { SorterDropDown } from '../../../components/drop-down-list/Sorter';
|
||||
import { FC } from 'react';
|
||||
import { SearchInput } from '../../../components/input/SearchInput';
|
||||
|
||||
const Filters = () => {
|
||||
const items: FilterItem[] = [
|
||||
{ text: 'React', value: 'react' },
|
||||
{ text: 'Vue', value: 'vue' },
|
||||
{ text: 'Angular', value: 'angular' },
|
||||
{ text: 'Svelte', value: 'svelte' },
|
||||
{ text: 'Next.js', value: 'next' },
|
||||
{ text: 'Nuxt', value: 'nuxt' },
|
||||
{ text: 'Solid', value: 'solid' },
|
||||
{ text: 'Qwik', value: 'qwik' },
|
||||
];
|
||||
interface ContestFiltersProps {
|
||||
onChangeName: (value: string) => void;
|
||||
}
|
||||
|
||||
const Filters: FC<ContestFiltersProps> = ({ onChangeName }) => {
|
||||
return (
|
||||
<div className=" h-[50px] mb-[20px] flex gap-[20px] items-center">
|
||||
<SearchInput onChange={() => {}} placeholder="Поиск задачи" />
|
||||
|
||||
<SorterDropDown
|
||||
items={[
|
||||
{
|
||||
value: '1',
|
||||
text: 'Сложность',
|
||||
},
|
||||
{
|
||||
value: '2',
|
||||
text: 'Дата создания',
|
||||
},
|
||||
{
|
||||
value: '3',
|
||||
text: 'ID',
|
||||
},
|
||||
]}
|
||||
onChange={(v) => console.log(v)}
|
||||
/>
|
||||
|
||||
<FilterDropDown
|
||||
items={items}
|
||||
defaultState={[]}
|
||||
onChange={(values) => console.log(values)}
|
||||
<SearchInput
|
||||
onChange={(value: string) => {
|
||||
onChangeName(value);
|
||||
}}
|
||||
placeholder="Поиск контеста"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -9,8 +9,25 @@ import {
|
||||
setContestStatus,
|
||||
} from '../../../redux/slices/contests';
|
||||
import { CreateContestBody } from '../../../redux/slices/contests';
|
||||
import DateRangeInput from '../../../components/input/DateRangeInput';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { NumberInput } from '../../../components/input/NumberInput';
|
||||
import {
|
||||
DropDownList,
|
||||
DropDownListItem,
|
||||
} from '../../../components/input/DropDownList';
|
||||
import DateInput from '../../../components/input/DateInput';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { fetchMyGroups } from '../../../redux/slices/groups';
|
||||
|
||||
function toUtc(localDateTime?: string): string {
|
||||
if (!localDateTime) return '';
|
||||
|
||||
// Создаём дату (она автоматически считается как локальная)
|
||||
const date = new Date(localDateTime);
|
||||
|
||||
// Возвращаем ISO-строку с 'Z' (всегда в UTC)
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
interface ModalCreateContestProps {
|
||||
active: boolean;
|
||||
@@ -27,15 +44,35 @@ const ModalCreateContest: FC<ModalCreateContestProps> = ({
|
||||
(state) => state.contests.createContest.status,
|
||||
);
|
||||
|
||||
const visibilityItems: DropDownListItem[] = [
|
||||
{ value: 'Public', text: 'Публичный' },
|
||||
{ value: 'GroupPrivate', text: 'Для группы' },
|
||||
];
|
||||
|
||||
const scheduleTypeItems: DropDownListItem[] = [
|
||||
{ value: 'AlwaysOpen', text: 'Всегда открыт' },
|
||||
{ value: 'FixedWindow', text: 'Фиксированое окно' },
|
||||
{ value: 'RollingWindow', text: 'Скользящее окно' },
|
||||
];
|
||||
|
||||
const now = new Date();
|
||||
const plus60 = new Date(now.getTime() + 60 * 60 * 1000);
|
||||
|
||||
const toLocal = (d: Date) => {
|
||||
const off = d.getTimezoneOffset();
|
||||
const local = new Date(d.getTime() - off * 60000);
|
||||
return local.toISOString().slice(0, 16);
|
||||
};
|
||||
|
||||
const [form, setForm] = useState<CreateContestBody>({
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
attemptDurationMinutes: 0,
|
||||
maxAttempts: 0,
|
||||
startsAt: toLocal(now),
|
||||
endsAt: toLocal(plus60),
|
||||
attemptDurationMinutes: 60,
|
||||
maxAttempts: 1,
|
||||
allowEarlyFinish: false,
|
||||
missionIds: [],
|
||||
articleIds: [],
|
||||
@@ -44,6 +81,16 @@ const ModalCreateContest: FC<ModalCreateContestProps> = ({
|
||||
const contest = useAppSelector(
|
||||
(state) => state.contests.createContest.contest,
|
||||
);
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
const myGroups = useAppSelector(
|
||||
(state) => state.groups.fetchMyGroups.groups,
|
||||
).filter((group) =>
|
||||
group.members.some(
|
||||
(member) =>
|
||||
member.username === myname &&
|
||||
member.role.includes('Administrator'),
|
||||
),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === 'successful') {
|
||||
@@ -56,14 +103,35 @@ const ModalCreateContest: FC<ModalCreateContestProps> = ({
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (active) {
|
||||
dispatch(fetchMyGroups());
|
||||
}
|
||||
}, [active]);
|
||||
|
||||
const handleChange = (key: keyof CreateContestBody, value: any) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
dispatch(createContest(form));
|
||||
dispatch(
|
||||
createContest({
|
||||
...form,
|
||||
endsAt: toUtc(form.endsAt),
|
||||
startsAt: toUtc(form.startsAt),
|
||||
}),
|
||||
);
|
||||
};
|
||||
const groupItems = myGroups.map((v) => {
|
||||
return {
|
||||
value: '' + v.id,
|
||||
text: v.name,
|
||||
};
|
||||
});
|
||||
const groupIdDefaultState =
|
||||
myGroups.find((g) => g.id == form?.groupId) ?? myGroups[0] ?? undefined;
|
||||
|
||||
console.log(groupItems, myGroups, groupIdDefaultState);
|
||||
return (
|
||||
<Modal
|
||||
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
||||
@@ -97,80 +165,123 @@ const ModalCreateContest: FC<ModalCreateContestProps> = ({
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<div>
|
||||
<label className="block text-sm mb-1">
|
||||
Тип расписания
|
||||
Тип контеста
|
||||
</label>
|
||||
<select
|
||||
className="w-full p-2 rounded-md bg-liquid-darker border border-liquid-lighter"
|
||||
value={form.scheduleType}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'scheduleType',
|
||||
e.target
|
||||
.value as CreateContestBody['scheduleType'],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="AlwaysOpen">Всегда открыт</option>
|
||||
<option value="FixedWindow">
|
||||
Фиксированные даты
|
||||
</option>
|
||||
<option value="RollingWindow">
|
||||
Скользящее окно
|
||||
</option>
|
||||
</select>
|
||||
|
||||
<DropDownList
|
||||
items={scheduleTypeItems}
|
||||
onChange={(v) => {
|
||||
handleChange('scheduleType', v);
|
||||
}}
|
||||
weight="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm mb-1">Видимость</label>
|
||||
<select
|
||||
className="w-full p-2 rounded-md bg-liquid-darker border border-liquid-lighter"
|
||||
value={form.visibility}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'visibility',
|
||||
e.target
|
||||
.value as CreateContestBody['visibility'],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="Public">Публичный</option>
|
||||
<option value="GroupPrivate">Групповой</option>
|
||||
</select>
|
||||
<DropDownList
|
||||
items={visibilityItems}
|
||||
onChange={(v) => {
|
||||
handleChange('visibility', v);
|
||||
}}
|
||||
weight="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Даты начала и конца */}
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<DateRangeInput
|
||||
startValue={form.startsAt || ''}
|
||||
endValue={form.endsAt || ''}
|
||||
onChange={handleChange}
|
||||
className="mt-[10px]"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
' grid grid-flow-row grid-rows-[0fr] opacity-0 transition-all duration-200 mb-[10px]',
|
||||
form.visibility == 'GroupPrivate' &&
|
||||
'grid-rows-[1fr] opacity-100',
|
||||
)}
|
||||
>
|
||||
{groupIdDefaultState ? (
|
||||
<div
|
||||
className={cn(
|
||||
form.visibility != 'GroupPrivate' &&
|
||||
'overflow-hidden',
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
<label className="block text-sm mb-2 mt-[10px]">
|
||||
Группа для привязки
|
||||
</label>
|
||||
|
||||
<DropDownList
|
||||
items={groupItems}
|
||||
defaultState={{
|
||||
value: '' + groupIdDefaultState.id,
|
||||
text: groupIdDefaultState.name,
|
||||
}}
|
||||
onChange={(v) => {
|
||||
handleChange('groupId', Number(v));
|
||||
}}
|
||||
weight="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-hidden">
|
||||
<div className="text-liquid-red my-[20px]">
|
||||
У вас нет группы вкоторой вы являетесь
|
||||
Администратором!
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Даты */}
|
||||
<div
|
||||
className={cn(
|
||||
' grid grid-flow-row grid-rows-[0fr] opacity-0 transition-all duration-200',
|
||||
form.scheduleType != 'AlwaysOpen' &&
|
||||
'grid-rows-[1fr] opacity-100',
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<DateInput
|
||||
label="Дата начала"
|
||||
value={form.startsAt}
|
||||
onChange={(v) => handleChange('startsAt', v)}
|
||||
/>
|
||||
|
||||
<DateInput
|
||||
label="Дата окончания"
|
||||
value={form.endsAt}
|
||||
onChange={(v) => handleChange('endsAt', v)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Продолжительность и лимиты */}
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<Input
|
||||
<NumberInput
|
||||
defaultState={form.attemptDurationMinutes}
|
||||
name="attemptDurationMinutes"
|
||||
type="number"
|
||||
label="Длительность попытки (мин)"
|
||||
placeholder="Например: 60"
|
||||
minValue={1}
|
||||
maxValue={365 * 24 * 60}
|
||||
onChange={(v) =>
|
||||
handleChange('attemptDurationMinutes', Number(v))
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
<NumberInput
|
||||
defaultState={form.maxAttempts}
|
||||
name="maxAttempts"
|
||||
type="number"
|
||||
label="Макс. попыток"
|
||||
placeholder="Например: 3"
|
||||
minValue={1}
|
||||
maxValue={100}
|
||||
onChange={(v) => handleChange('maxAttempts', Number(v))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Разрешить раннее завершение */}
|
||||
<div className="flex items-center gap-[10px] mt-[15px]">
|
||||
{/* <div className="flex items-center gap-[10px] mt-[15px]">
|
||||
<input
|
||||
id="allowEarlyFinish"
|
||||
type="checkbox"
|
||||
@@ -182,7 +293,7 @@ const ModalCreateContest: FC<ModalCreateContestProps> = ({
|
||||
<label htmlFor="allowEarlyFinish">
|
||||
Разрешить раннее завершение
|
||||
</label>
|
||||
</div>
|
||||
</div> */}
|
||||
|
||||
{/* Кнопки */}
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
|
||||
246
src/views/home/contests/PastContestItem.tsx
Normal file
246
src/views/home/contests/PastContestItem.tsx
Normal file
@@ -0,0 +1,246 @@
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { useQuery } from '../../../hooks/useQuery';
|
||||
import { ReverseButton } from '../../../components/button/ReverseButton';
|
||||
import { PrimaryButton } from '../../../components/button/PrimaryButton';
|
||||
import { toastWarning } from '../../../lib/toastNotification';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
addOrUpdateContestMember,
|
||||
fetchParticipatingContests,
|
||||
} from '../../../redux/slices/contests';
|
||||
|
||||
export interface PastContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
type Role = 'None' | 'Participant' | 'Organizer';
|
||||
|
||||
const PastContestItem: React.FC<PastContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [role, setRole] = useState<Role>('None');
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const userId = useAppSelector((state) => state.auth.id);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
const { contests: myContests } = useAppSelector(
|
||||
(state) => state.contests.fetchMyContests,
|
||||
);
|
||||
const { contests: participantContests } = useAppSelector(
|
||||
(state) => state.contests.fetchParticipating,
|
||||
);
|
||||
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.contests.filterName,
|
||||
);
|
||||
|
||||
const highlightZ = (name: string, filter: string) => {
|
||||
if (!filter) return name;
|
||||
|
||||
const s = filter.toLowerCase();
|
||||
const t = name.toLowerCase();
|
||||
const n = t.length;
|
||||
const m = s.length;
|
||||
|
||||
const mark = Array(n).fill(false);
|
||||
|
||||
// Проходимся с конца и ставим отметки
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
if (i + m <= n && t.slice(i, i + m) === s) {
|
||||
for (let j = i; j < i + m; j++) {
|
||||
if (mark[j]) break;
|
||||
mark[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Формируем единые жёлтые блоки ===
|
||||
const result: any[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < n) {
|
||||
if (!mark[i]) {
|
||||
// обычный символ
|
||||
result.push(name[i]);
|
||||
i++;
|
||||
} else {
|
||||
// начинаем жёлтый блок
|
||||
let j = i;
|
||||
while (j < n && mark[j]) j++;
|
||||
|
||||
const chunk = name.slice(i, j);
|
||||
result.push(
|
||||
<span
|
||||
key={i}
|
||||
className="bg-yellow-400 text-black rounded px-1"
|
||||
>
|
||||
{chunk}
|
||||
</span>,
|
||||
);
|
||||
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setRole(
|
||||
(() => {
|
||||
if (myContests?.some((c) => c.id === contestId)) {
|
||||
return 'Organizer';
|
||||
}
|
||||
if (participantContests?.some((c) => c.id === contestId)) {
|
||||
return 'Participant';
|
||||
}
|
||||
return 'None';
|
||||
})(),
|
||||
);
|
||||
}, [myContests, participantContests]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300',
|
||||
userId
|
||||
? 'grid-cols-[1fr,150px,190px,120px,150px,150px]'
|
||||
: 'grid-cols-[1fr,150px,190px,120px,150px]',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (role == 'None') {
|
||||
toastWarning('Нужно зарегистрироваться на контест');
|
||||
return;
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">
|
||||
{highlightZ(name, nameFilter)}
|
||||
</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-center text-liquid-brightmain font-normal">
|
||||
{scheduleType == 'AlwaysOpen' ? 'Открыт' : 'Завершен'}
|
||||
</div>
|
||||
{userId && (
|
||||
<div className="flex items-center justify-center">
|
||||
{role == 'Organizer' || role == 'Participant' ? (
|
||||
<ReverseButton
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
text="Войти"
|
||||
/>
|
||||
) : (
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
addOrUpdateContestMember({
|
||||
contestId: contestId,
|
||||
member: {
|
||||
userId: Number(userId),
|
||||
role: 'Participant',
|
||||
},
|
||||
}),
|
||||
)
|
||||
.unwrap()
|
||||
.then(() =>
|
||||
dispatch(
|
||||
fetchParticipatingContests({}),
|
||||
),
|
||||
);
|
||||
}}
|
||||
text="Регистрация"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PastContestItem;
|
||||
290
src/views/home/contests/UpcomingContestItem.tsx
Normal file
290
src/views/home/contests/UpcomingContestItem.tsx
Normal file
@@ -0,0 +1,290 @@
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { useQuery } from '../../../hooks/useQuery';
|
||||
import { toastWarning } from '../../../lib/toastNotification';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ReverseButton } from '../../../components/button/ReverseButton';
|
||||
import { PrimaryButton } from '../../../components/button/PrimaryButton';
|
||||
import {
|
||||
addOrUpdateContestMember,
|
||||
fetchParticipatingContests,
|
||||
} from '../../../redux/slices/contests';
|
||||
|
||||
type Role = 'None' | 'Participant' | 'Organizer';
|
||||
|
||||
export interface UpcoingContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
type: 'first' | 'second';
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
function formatWaitTime(ms: number): string {
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const UpcoingContestItem: React.FC<UpcoingContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [role, setRole] = useState<Role>('None');
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const { contests: myContests } = useAppSelector(
|
||||
(state) => state.contests.fetchMyContests,
|
||||
);
|
||||
const { contests: participantContests } = useAppSelector(
|
||||
(state) => state.contests.fetchParticipating,
|
||||
);
|
||||
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.contests.filterName,
|
||||
);
|
||||
|
||||
const highlightZ = (name: string, filter: string) => {
|
||||
if (!filter) return name;
|
||||
|
||||
const s = filter.toLowerCase();
|
||||
const t = name.toLowerCase();
|
||||
const n = t.length;
|
||||
const m = s.length;
|
||||
|
||||
const mark = Array(n).fill(false);
|
||||
|
||||
// Проходимся с конца и ставим отметки
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
if (i + m <= n && t.slice(i, i + m) === s) {
|
||||
for (let j = i; j < i + m; j++) {
|
||||
if (mark[j]) break;
|
||||
mark[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Формируем единые жёлтые блоки ===
|
||||
const result: any[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < n) {
|
||||
if (!mark[i]) {
|
||||
// обычный символ
|
||||
result.push(name[i]);
|
||||
i++;
|
||||
} else {
|
||||
// начинаем жёлтый блок
|
||||
let j = i;
|
||||
while (j < n && mark[j]) j++;
|
||||
|
||||
const chunk = name.slice(i, j);
|
||||
result.push(
|
||||
<span
|
||||
key={i}
|
||||
className="bg-yellow-400 text-black rounded px-1"
|
||||
>
|
||||
{chunk}
|
||||
</span>,
|
||||
);
|
||||
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
const userId = useAppSelector((state) => state.auth.id);
|
||||
|
||||
const started = new Date(startsAt) <= new Date();
|
||||
const finished = new Date(endsAt) <= new Date();
|
||||
const waitTime = !started
|
||||
? new Date(startsAt).getTime() - new Date().getTime()
|
||||
: new Date(endsAt).getTime() - new Date().getTime();
|
||||
|
||||
useEffect(() => {
|
||||
setRole(
|
||||
(() => {
|
||||
if (myContests?.some((c) => c.id === contestId)) {
|
||||
return 'Organizer';
|
||||
}
|
||||
if (participantContests?.some((c) => c.id === contestId)) {
|
||||
return 'Participant';
|
||||
}
|
||||
return 'None';
|
||||
})(),
|
||||
);
|
||||
}, [myContests, participantContests]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300',
|
||||
userId
|
||||
? 'grid-cols-[1fr,1fr,220px,130px,130px,140px,150px]'
|
||||
: 'grid-cols-[1fr,1fr,220px,130px,130px,130px]',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (!started) {
|
||||
toastWarning('Контест еще не начался');
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">
|
||||
{highlightZ(name, nameFilter)}
|
||||
</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
{!started ? (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До начала\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
) : (
|
||||
!finished && (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До конца\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-center text-liquid-brightmain font-normal">
|
||||
{new Date() < new Date(startsAt) ? (
|
||||
<>{'Не начался'}</>
|
||||
) : (
|
||||
<>{scheduleType == 'AlwaysOpen' ? 'Открыт' : 'Идет'}</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{userId && (
|
||||
<div className="flex items-center justify-center">
|
||||
{role == 'Organizer' || role == 'Participant' ? (
|
||||
<ReverseButton
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams({
|
||||
back: '/home/contests',
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
text="Войти"
|
||||
/>
|
||||
) : (
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
addOrUpdateContestMember({
|
||||
contestId: contestId,
|
||||
member: {
|
||||
userId: Number(userId),
|
||||
role: 'Participant',
|
||||
},
|
||||
}),
|
||||
)
|
||||
.unwrap()
|
||||
.then(() =>
|
||||
dispatch(
|
||||
fetchParticipatingContests({}),
|
||||
),
|
||||
);
|
||||
}}
|
||||
text="Регистрация"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpcoingContestItem;
|
||||
@@ -5,9 +5,9 @@ import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { fetchGroupById } from '../../../redux/slices/groups';
|
||||
import GroupMenu from './GroupMenu';
|
||||
import { Posts } from './posts/Posts';
|
||||
import { SearchInput } from '../../../components/input/SearchInput';
|
||||
import { Chat } from './chat/Chat';
|
||||
import { Contests } from './contests/Contests';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
|
||||
interface GroupsBlockProps {}
|
||||
|
||||
@@ -21,11 +21,10 @@ const Group: FC<GroupsBlockProps> = () => {
|
||||
const group = useAppSelector((state) => state.groups.fetchGroupById.group);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActivePage('groups'));
|
||||
dispatch(fetchGroupById(groupId));
|
||||
}, [groupId]);
|
||||
|
||||
console.log(group);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -38,8 +37,11 @@ const Group: FC<GroupsBlockProps> = () => {
|
||||
|
||||
<Routes>
|
||||
<Route path="home" element={<Posts groupId={groupId} />} />
|
||||
<Route path="chat" element={<Chat />} />
|
||||
<Route path="contests" element={<Contests />} />
|
||||
<Route path="chat" element={<Chat groupId={groupId} />} />
|
||||
<Route
|
||||
path="contests"
|
||||
element={<Contests groupId={groupId} />}
|
||||
/>
|
||||
<Route
|
||||
path="*"
|
||||
element={<Navigate to={`/group/${groupId}/home`} />}
|
||||
|
||||
@@ -1,12 +1,212 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useAppDispatch } from '../../../../redux/hooks';
|
||||
import { FC, useEffect, useRef, useState } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { setMenuActiveGroupPage } from '../../../../redux/slices/store';
|
||||
import {
|
||||
fetchGroupMessages,
|
||||
sendGroupMessage,
|
||||
setGroupChatStatus,
|
||||
} from '../../../../redux/slices/groupChat';
|
||||
import { MessageItem } from './MessageItem';
|
||||
import { Send } from '../../../../assets/icons/input';
|
||||
|
||||
export const Chat = () => {
|
||||
interface GroupChatProps {
|
||||
groupId: number;
|
||||
}
|
||||
|
||||
const CHUNK_SIZE = 10;
|
||||
|
||||
export const Chat: FC<GroupChatProps> = ({ groupId }) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const messages = useAppSelector((s) => s.groupchat.messages[groupId] || []);
|
||||
const messagesState = useAppSelector(
|
||||
(state) => state.groupchat.fetchMessages.status,
|
||||
);
|
||||
const lastMessageId = useAppSelector(
|
||||
(state) => state.groupchat.lastMessage[groupId] || 0,
|
||||
);
|
||||
const user = useAppSelector((state) => state.auth);
|
||||
|
||||
const [text, setText] = useState<string>('');
|
||||
const [firstMessagesFetch, setFirctMessagesFetch] = useState<boolean>(true);
|
||||
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// добавлено: ref для хранения предыдущей высоты
|
||||
const prevHeightRef = useRef(0);
|
||||
|
||||
// активируем таб
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActiveGroupPage('chat'));
|
||||
}, []);
|
||||
return <></>;
|
||||
|
||||
// первичная загрузка
|
||||
useEffect(() => {
|
||||
dispatch(
|
||||
fetchGroupMessages({
|
||||
groupId,
|
||||
limit: CHUNK_SIZE,
|
||||
}),
|
||||
);
|
||||
}, [groupId]);
|
||||
|
||||
// автоскролл вниз после начальной загрузки (но не при догрузке)
|
||||
useEffect(() => {
|
||||
const div = scrollRef.current;
|
||||
if (!div) return;
|
||||
|
||||
// если prevHeightRef == 0 — значит это не догрузка, а обычная загрузка
|
||||
if (prevHeightRef.current === 0) {
|
||||
div.scrollTop = div.scrollHeight;
|
||||
}
|
||||
}, [messages.length]);
|
||||
|
||||
// добавлено: компенсирование скролла при догрузке
|
||||
useEffect(() => {
|
||||
const div = scrollRef.current;
|
||||
if (!div) return;
|
||||
|
||||
if (prevHeightRef.current > 0) {
|
||||
const diff = div.scrollHeight - prevHeightRef.current;
|
||||
div.scrollTop = diff; // компенсируем смещение
|
||||
|
||||
prevHeightRef.current = 0; // сбрасываем
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (messagesState == 'successful') {
|
||||
dispatch(
|
||||
setGroupChatStatus({ key: 'fetchMessages', status: 'idle' }),
|
||||
);
|
||||
}
|
||||
if (messagesState == 'failed') {
|
||||
dispatch(
|
||||
setGroupChatStatus({ key: 'fetchMessages', status: 'idle' }),
|
||||
);
|
||||
}
|
||||
}, [messagesState]);
|
||||
|
||||
const lastMessageIdRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
lastMessageIdRef.current = lastMessageId;
|
||||
if (lastMessageId && firstMessagesFetch) {
|
||||
setFirctMessagesFetch(false);
|
||||
dispatch(
|
||||
fetchGroupMessages({
|
||||
groupId,
|
||||
afterMessageId: lastMessageIdRef.current,
|
||||
timeoutSeconds: 10,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (lastMessageIdRef.current === null) return;
|
||||
|
||||
dispatch(
|
||||
fetchGroupMessages({
|
||||
groupId,
|
||||
afterMessageId: lastMessageIdRef.current,
|
||||
timeoutSeconds: 10,
|
||||
}),
|
||||
);
|
||||
}, 10000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [groupId]);
|
||||
|
||||
const handleSend = () => {
|
||||
if (!text.trim()) return;
|
||||
|
||||
dispatch(
|
||||
sendGroupMessage({
|
||||
groupId,
|
||||
content: text.trim(),
|
||||
}),
|
||||
).then(() => {
|
||||
setText('');
|
||||
setTimeout(() => {
|
||||
const div = scrollRef.current;
|
||||
if (div) div.scrollTop = div.scrollHeight;
|
||||
}, 0);
|
||||
});
|
||||
};
|
||||
|
||||
const handleEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
// догрузка старых сообщений при скролле вверх
|
||||
const handleScroll = () => {
|
||||
const div = scrollRef.current;
|
||||
if (!div) return;
|
||||
|
||||
// если скролл в верхней точке
|
||||
if (div.scrollTop === 0) {
|
||||
prevHeightRef.current = div.scrollHeight; // запоминаем высоту до загрузки
|
||||
|
||||
const first = messages[0];
|
||||
if (!first || first.id == 1) return;
|
||||
|
||||
const beforeId = first.id - CHUNK_SIZE;
|
||||
|
||||
dispatch(
|
||||
fetchGroupMessages({
|
||||
groupId,
|
||||
limit: CHUNK_SIZE,
|
||||
afterMessageId: beforeId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full relative">
|
||||
<div className="grid grid-rows-[1fr,40px] h-full relative min-h-0 gap-[20px]">
|
||||
<div
|
||||
className="min-h-0 overflow-y-scroll thin-dark-scrollbar"
|
||||
ref={scrollRef}
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
<div className="flex flex-col gap-[20px] min-h-0 h-0 px-[16px]">
|
||||
{messages.map((msg, i) => (
|
||||
<MessageItem
|
||||
key={i}
|
||||
message={msg.content}
|
||||
createdAt={msg.createdAt}
|
||||
id={msg.id}
|
||||
groupId={msg.groupId}
|
||||
authorId={msg.authorId}
|
||||
authorUsername={msg.authorUsername}
|
||||
myMessage={msg.authorId == Number(user.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="bg-liquid-lighter rounded-[10px] cursor-text flex items-center px-[16px]">
|
||||
<input
|
||||
className="w-[calc(100%-50px)] outline-none bg-transparent placeholder:text-[16px] placeholder:text-liquid-light placeholder:font-medium"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={handleEnter}
|
||||
placeholder="Введите сообщение"
|
||||
/>
|
||||
<img
|
||||
src={Send}
|
||||
className=" absolute cursor-pointer right-[16px] active:scale-90 transition-all duration-300"
|
||||
onClick={() => {
|
||||
handleSend();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
81
src/views/home/group/chat/MessageItem.tsx
Normal file
81
src/views/home/group/chat/MessageItem.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
import { FC } from 'react';
|
||||
import { useAppSelector } from '../../../../redux/hooks';
|
||||
|
||||
function convertDate(isoString: string) {
|
||||
const date = new Date(isoString);
|
||||
|
||||
const dd = String(date.getUTCDate()).padStart(2, '0');
|
||||
const mm = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const yyyy = date.getUTCFullYear();
|
||||
|
||||
const hh = String(date.getUTCHours()).padStart(2, '0');
|
||||
const min = String(date.getUTCMinutes()).padStart(2, '0');
|
||||
|
||||
return `${dd}.${mm}.${yyyy} ${hh}:${min}`;
|
||||
}
|
||||
|
||||
interface MessageItemProps {
|
||||
id: number;
|
||||
groupId: number;
|
||||
authorId: number;
|
||||
authorUsername: string;
|
||||
createdAt: string;
|
||||
message: string;
|
||||
myMessage: boolean;
|
||||
}
|
||||
|
||||
export const MessageItem: FC<MessageItemProps> = ({
|
||||
authorId,
|
||||
authorUsername,
|
||||
createdAt,
|
||||
message,
|
||||
myMessage,
|
||||
}) => {
|
||||
const members = useAppSelector(
|
||||
(state) => state.groups.fetchGroupById.group?.members,
|
||||
);
|
||||
const member = members?.find((m) => m.userId === authorId);
|
||||
|
||||
return myMessage ? (
|
||||
<div className="flex flex-col gap-[20px] items-end leading-[20px] text-[16px]">
|
||||
<div className="w-[50%] flex flex-col gap-[10px]">
|
||||
<div className="h-[20px] w-full flex gap-[10px] relative justify-end ">
|
||||
<div className="font-bold text-liquid-light">
|
||||
{convertDate(createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<div className="bg-liquid-lighter w-fit max-w-full break-words px-[16px] py-[8px] rounded-[10px] ">
|
||||
{message}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-[20px] ">
|
||||
<div className="w-[50%] flex flex-col gap-[10px]">
|
||||
<div className="h-[40px] w-full flex gap-[10px] relative ">
|
||||
<div className="h-[40px] w-[40px] bg-[#D9D9D9] rounded-[10px]"></div>
|
||||
<div className=" leading-[20px] font-bold text-[16px] ">
|
||||
<div>{authorUsername} </div>
|
||||
<div className="text-liquid-light">
|
||||
{member ? member.role : 'роль не найдена'}
|
||||
</div>
|
||||
</div>
|
||||
<div className=" leading-[20px] font-bold text-[16px] ">
|
||||
<div className="text-liquid-light">
|
||||
{convertDate(createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex">
|
||||
<div className="bg-liquid-lighter w-fit max-w-full break-words px-[16px] py-[8px] rounded-[10px] ">
|
||||
{message}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,12 +1,75 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useAppDispatch } from '../../../../redux/hooks';
|
||||
import { FC, useEffect } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import ContestsBlock from './ContestsBlock';
|
||||
import { setMenuActiveGroupPage } from '../../../../redux/slices/store';
|
||||
import {
|
||||
fetchContests,
|
||||
fetchMyContests,
|
||||
fetchParticipatingContests,
|
||||
} from '../../../../redux/slices/contests';
|
||||
|
||||
export const Contests = () => {
|
||||
interface ContestsProps {
|
||||
groupId: number;
|
||||
}
|
||||
|
||||
export const Contests: FC<ContestsProps> = ({ groupId }) => {
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const { contests, status } = useAppSelector(
|
||||
(state) => state.contests.fetchContests,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActiveGroupPage('contests'));
|
||||
dispatch(fetchContests({ groupId }));
|
||||
dispatch(fetchParticipatingContests({ pageSize: 100 }));
|
||||
dispatch(fetchMyContests());
|
||||
}, []);
|
||||
return <></>;
|
||||
|
||||
return (
|
||||
<div className="h-full relative">
|
||||
<div className="grid grid-rows-[1fr] h-full relative min-h-0 gap-[20px]">
|
||||
<div className="min-h-0 overflow-y-scroll thin-dark-scrollbar pr-[20px]">
|
||||
{status == 'loading' && (
|
||||
<div className="text-liquid-white p-4">
|
||||
Загрузка контестов...
|
||||
</div>
|
||||
)}
|
||||
{status == 'successful' && (
|
||||
<div className="flex flex-col gap-[20px] min-h-0 h-0 px-[16px]">
|
||||
<ContestsBlock
|
||||
groupId={groupId}
|
||||
className="mb-[20px]"
|
||||
title="Текущие"
|
||||
contests={contests
|
||||
.filter(
|
||||
(c) => c.scheduleType != 'AlwaysOpen',
|
||||
)
|
||||
.filter((c) =>
|
||||
c.endsAt
|
||||
? new Date() < new Date(c.endsAt)
|
||||
: false,
|
||||
)}
|
||||
type="upcoming"
|
||||
/>
|
||||
|
||||
<ContestsBlock
|
||||
groupId={groupId}
|
||||
className="mb-[20px]"
|
||||
title="Прошедшие"
|
||||
contests={contests.filter(
|
||||
(c) =>
|
||||
c.scheduleType == 'AlwaysOpen' ||
|
||||
!(c.endsAt
|
||||
? new Date() < new Date(c.endsAt)
|
||||
: false),
|
||||
)}
|
||||
type="past"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
112
src/views/home/group/contests/ContestsBlock.tsx
Normal file
112
src/views/home/group/contests/ContestsBlock.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { useState, FC } from 'react';
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { ChevroneDown } from '../../../../assets/icons/groups';
|
||||
import { Contest } from '../../../../redux/slices/contests';
|
||||
import PastContestItem from './PastContestItem';
|
||||
import UpcoingContestItem from './UpcomingContestItem';
|
||||
|
||||
interface ContestsBlockProps {
|
||||
contests: Contest[];
|
||||
title: string;
|
||||
className?: string;
|
||||
type: 'upcoming' | 'past';
|
||||
groupId: number;
|
||||
}
|
||||
|
||||
const ContestsBlock: FC<ContestsBlockProps> = ({
|
||||
contests,
|
||||
title,
|
||||
className,
|
||||
type,
|
||||
groupId,
|
||||
}) => {
|
||||
const [active, setActive] = useState<boolean>(title != 'Скрытые');
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
' border-b-[1px] border-b-liquid-lighter rounded-[10px]',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
' h-[40px] text-[24px] font-bold flex gap-[10px] items-center cursor-pointer border-b-[1px] border-b-transparent transition-all duration-300',
|
||||
active && 'border-b-liquid-lighter',
|
||||
)}
|
||||
onClick={() => {
|
||||
setActive(!active);
|
||||
}}
|
||||
>
|
||||
<span className=" select-none">{title}</span>
|
||||
<img
|
||||
src={ChevroneDown}
|
||||
className={cn(
|
||||
'transition-all duration-300 select-none',
|
||||
active && 'rotate-180',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
' grid grid-flow-row grid-rows-[0fr] opacity-0 transition-all duration-300',
|
||||
active && 'grid-rows-[1fr] opacity-100',
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="pb-[10px] pt-[20px]">
|
||||
{contests.map((v, i) => {
|
||||
if (type == 'past') {
|
||||
return (
|
||||
<PastContestItem
|
||||
groupId={groupId}
|
||||
key={i}
|
||||
contestId={v.id}
|
||||
scheduleType={v.scheduleType}
|
||||
name={v.name}
|
||||
startsAt={
|
||||
v.startsAt ?? new Date().toString()
|
||||
}
|
||||
endsAt={
|
||||
v.endsAt ?? new Date().toString()
|
||||
}
|
||||
attemptDurationMinutes={
|
||||
v.attemptDurationMinutes ?? 0
|
||||
}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type == 'upcoming') {
|
||||
return (
|
||||
<UpcoingContestItem
|
||||
groupId={groupId}
|
||||
key={i}
|
||||
contestId={v.id}
|
||||
scheduleType={v.scheduleType}
|
||||
name={v.name}
|
||||
startsAt={
|
||||
v.startsAt ?? new Date().toString()
|
||||
}
|
||||
endsAt={
|
||||
v.endsAt ?? new Date().toString()
|
||||
}
|
||||
attemptDurationMinutes={
|
||||
v.attemptDurationMinutes ?? 0
|
||||
}
|
||||
type={i % 2 ? 'second' : 'first'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <></>;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContestsBlock;
|
||||
222
src/views/home/group/contests/ModalCreate.tsx
Normal file
222
src/views/home/group/contests/ModalCreate.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { Modal } from '../../../../components/modal/Modal';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
|
||||
import { Input } from '../../../../components/input/Input';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import {
|
||||
createContest,
|
||||
setContestStatus,
|
||||
} from '../../../../redux/slices/contests';
|
||||
import { CreateContestBody } from '../../../../redux/slices/contests';
|
||||
import DateRangeInput from '../../../../components/input/DateRangeInput';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
function toUtc(localDateTime?: string): string {
|
||||
if (!localDateTime) return '';
|
||||
|
||||
// Создаём дату (она автоматически считается как локальная)
|
||||
const date = new Date(localDateTime);
|
||||
|
||||
// Возвращаем ISO-строку с 'Z' (всегда в UTC)
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
interface ModalCreateContestProps {
|
||||
active: boolean;
|
||||
setActive: (value: boolean) => void;
|
||||
}
|
||||
|
||||
const ModalCreateContest: FC<ModalCreateContestProps> = ({
|
||||
active,
|
||||
setActive,
|
||||
}) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
const status = useAppSelector(
|
||||
(state) => state.contests.createContest.status,
|
||||
);
|
||||
|
||||
const [form, setForm] = useState<CreateContestBody>({
|
||||
name: '',
|
||||
description: '',
|
||||
scheduleType: 'AlwaysOpen',
|
||||
visibility: 'Public',
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
attemptDurationMinutes: 0,
|
||||
maxAttempts: 0,
|
||||
allowEarlyFinish: false,
|
||||
missionIds: [],
|
||||
articleIds: [],
|
||||
});
|
||||
|
||||
const contest = useAppSelector(
|
||||
(state) => state.contests.createContest.contest,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === 'successful') {
|
||||
dispatch(
|
||||
setContestStatus({ key: 'createContest', status: 'idle' }),
|
||||
);
|
||||
navigate(
|
||||
`/contest/create?back=/home/account/contests&contestId=${contest.id}`,
|
||||
);
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
const handleChange = (key: keyof CreateContestBody, value: any) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
dispatch(
|
||||
createContest({
|
||||
...form,
|
||||
endsAt: toUtc(form.endsAt),
|
||||
startsAt: toUtc(form.startsAt),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
||||
onOpenChange={setActive}
|
||||
open={active}
|
||||
backdrop="blur"
|
||||
>
|
||||
<div className="w-[550px]">
|
||||
<div className="font-bold text-[30px] mb-[10px]">
|
||||
Создать контест
|
||||
</div>
|
||||
|
||||
<Input
|
||||
name="name"
|
||||
type="text"
|
||||
label="Название"
|
||||
className="mt-[10px]"
|
||||
placeholder="Введите название"
|
||||
onChange={(v) => handleChange('name', v)}
|
||||
/>
|
||||
|
||||
<Input
|
||||
name="description"
|
||||
type="text"
|
||||
label="Описание"
|
||||
className="mt-[10px]"
|
||||
placeholder="Введите описание"
|
||||
onChange={(v) => handleChange('description', v)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<div>
|
||||
<label className="block text-sm mb-1">
|
||||
Тип расписания
|
||||
</label>
|
||||
<select
|
||||
className="w-full p-2 rounded-md bg-liquid-darker border border-liquid-lighter"
|
||||
value={form.scheduleType}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'scheduleType',
|
||||
e.target
|
||||
.value as CreateContestBody['scheduleType'],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="AlwaysOpen">Всегда открыт</option>
|
||||
<option value="FixedWindow">
|
||||
Фиксированные даты
|
||||
</option>
|
||||
<option value="RollingWindow">
|
||||
Скользящее окно
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm mb-1">Видимость</label>
|
||||
<select
|
||||
className="w-full p-2 rounded-md bg-liquid-darker border border-liquid-lighter"
|
||||
value={form.visibility}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
'visibility',
|
||||
e.target
|
||||
.value as CreateContestBody['visibility'],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="Public">Публичный</option>
|
||||
<option value="GroupPrivate">Групповой</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Даты начала и конца */}
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<DateRangeInput
|
||||
startValue={form.startsAt || ''}
|
||||
endValue={form.endsAt || ''}
|
||||
onChange={handleChange}
|
||||
className="mt-[10px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Продолжительность и лимиты */}
|
||||
<div className="grid grid-cols-2 gap-[10px] mt-[10px]">
|
||||
<Input
|
||||
name="attemptDurationMinutes"
|
||||
type="number"
|
||||
label="Длительность попытки (мин)"
|
||||
placeholder="Например: 60"
|
||||
onChange={(v) =>
|
||||
handleChange('attemptDurationMinutes', Number(v))
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
name="maxAttempts"
|
||||
type="number"
|
||||
label="Макс. попыток"
|
||||
placeholder="Например: 3"
|
||||
onChange={(v) => handleChange('maxAttempts', Number(v))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Разрешить раннее завершение */}
|
||||
<div className="flex items-center gap-[10px] mt-[15px]">
|
||||
<input
|
||||
id="allowEarlyFinish"
|
||||
type="checkbox"
|
||||
checked={!!form.allowEarlyFinish}
|
||||
onChange={(e) =>
|
||||
handleChange('allowEarlyFinish', e.target.checked)
|
||||
}
|
||||
/>
|
||||
<label htmlFor="allowEarlyFinish">
|
||||
Разрешить раннее завершение
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Кнопки */}
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
handleSubmit();
|
||||
}}
|
||||
text="Создать"
|
||||
disabled={status === 'loading'}
|
||||
/>
|
||||
<SecondaryButton
|
||||
onClick={() => setActive(false)}
|
||||
text="Отмена"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModalCreateContest;
|
||||
191
src/views/home/group/contests/PastContestItem.tsx
Normal file
191
src/views/home/group/contests/PastContestItem.tsx
Normal file
@@ -0,0 +1,191 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { useQuery } from '../../../../hooks/useQuery';
|
||||
import { ReverseButton } from '../../../../components/button/ReverseButton';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { toastWarning } from '../../../../lib/toastNotification';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
addOrUpdateContestMember,
|
||||
fetchParticipatingContests,
|
||||
} from '../../../../redux/slices/contests';
|
||||
|
||||
export interface PastContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
type: 'first' | 'second';
|
||||
groupId: number;
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
type Role = 'None' | 'Participant' | 'Organizer';
|
||||
|
||||
const PastContestItem: React.FC<PastContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
groupId,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [role, setRole] = useState<Role>('None');
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const userId = useAppSelector((state) => state.auth.id);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
const { contests: myContests } = useAppSelector(
|
||||
(state) => state.contests.fetchMyContests,
|
||||
);
|
||||
const { contests: participantContests } = useAppSelector(
|
||||
(state) => state.contests.fetchParticipating,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setRole(
|
||||
(() => {
|
||||
if (myContests?.some((c) => c.id === contestId)) {
|
||||
return 'Organizer';
|
||||
}
|
||||
if (participantContests?.some((c) => c.id === contestId)) {
|
||||
return 'Participant';
|
||||
}
|
||||
return 'None';
|
||||
})(),
|
||||
);
|
||||
}, [myContests, participantContests]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer grid items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300',
|
||||
userId
|
||||
? 'grid-cols-[1fr,150px,190px,120px,150px,150px]'
|
||||
: 'grid-cols-[1fr,150px,190px,120px,150px]',
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (role == 'None') {
|
||||
toastWarning('Нужно зарегистрироваться на контест');
|
||||
return;
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
back: `/group/${groupId}/contests`,
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-center text-liquid-brightmain font-normal">
|
||||
{scheduleType == 'AlwaysOpen' ? 'Открыт' : 'Завершен'}
|
||||
</div>
|
||||
{userId && (
|
||||
<div className="flex items-center justify-center">
|
||||
{role == 'Organizer' || role == 'Participant' ? (
|
||||
<ReverseButton
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams({
|
||||
back: `/group/${groupId}/contests`,
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
text="Войти"
|
||||
/>
|
||||
) : (
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
addOrUpdateContestMember({
|
||||
contestId: contestId,
|
||||
member: {
|
||||
userId: Number(userId),
|
||||
role: 'Participant',
|
||||
},
|
||||
}),
|
||||
)
|
||||
.unwrap()
|
||||
.then(() =>
|
||||
dispatch(
|
||||
fetchParticipatingContests({}),
|
||||
),
|
||||
);
|
||||
}}
|
||||
text="Регистрация"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PastContestItem;
|
||||
228
src/views/home/group/contests/UpcomingContestItem.tsx
Normal file
228
src/views/home/group/contests/UpcomingContestItem.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
import { cn } from '../../../../lib/cn';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { useQuery } from '../../../../hooks/useQuery';
|
||||
import { toastWarning } from '../../../../lib/toastNotification';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ReverseButton } from '../../../../components/button/ReverseButton';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import {
|
||||
addOrUpdateContestMember,
|
||||
fetchParticipatingContests,
|
||||
} from '../../../../redux/slices/contests';
|
||||
|
||||
type Role = 'None' | 'Participant' | 'Organizer';
|
||||
|
||||
export interface UpcoingContestItemProps {
|
||||
name: string;
|
||||
contestId: number;
|
||||
scheduleType: 'AlwaysOpen' | 'FixedWindow' | 'RollingWindow';
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
attemptDurationMinutes: number;
|
||||
type: 'first' | 'second';
|
||||
groupId: number;
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
|
||||
const day = date.getDate().toString().padStart(2, '0');
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
return `${day}/${month}/${year}\n${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function formatDurationTime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
function formatWaitTime(ms: number): string {
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
const remainder = days % 10;
|
||||
let suffix = 'дней';
|
||||
if (remainder === 1 && days !== 11) suffix = 'день';
|
||||
else if (remainder >= 2 && remainder <= 4 && (days < 10 || days > 20))
|
||||
suffix = 'дня';
|
||||
return `${days} ${suffix}`;
|
||||
} else if (hours > 0) {
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours} ч ${mins} мин` : `${hours} ч`;
|
||||
} else {
|
||||
return `${minutes} мин`;
|
||||
}
|
||||
}
|
||||
|
||||
const UpcoingContestItem: React.FC<UpcoingContestItemProps> = ({
|
||||
name,
|
||||
contestId,
|
||||
scheduleType,
|
||||
startsAt,
|
||||
endsAt,
|
||||
attemptDurationMinutes,
|
||||
type,
|
||||
groupId,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [role, setRole] = useState<Role>('None');
|
||||
|
||||
const myname = useAppSelector((state) => state.auth.username);
|
||||
|
||||
const { contests: myContests } = useAppSelector(
|
||||
(state) => state.contests.fetchMyContests,
|
||||
);
|
||||
const { contests: participantContests } = useAppSelector(
|
||||
(state) => state.contests.fetchParticipating,
|
||||
);
|
||||
|
||||
const query = useQuery();
|
||||
const username = query.get('username') ?? myname ?? '';
|
||||
|
||||
const userId = useAppSelector((state) => state.auth.id);
|
||||
|
||||
const started = new Date(startsAt) <= new Date();
|
||||
const finished = new Date(endsAt) <= new Date();
|
||||
const waitTime = !started
|
||||
? new Date(startsAt).getTime() - new Date().getTime()
|
||||
: new Date(endsAt).getTime() - new Date().getTime();
|
||||
|
||||
useEffect(() => {
|
||||
setRole(
|
||||
(() => {
|
||||
if (myContests?.some((c) => c.id === contestId)) {
|
||||
return 'Organizer';
|
||||
}
|
||||
if (participantContests?.some((c) => c.id === contestId)) {
|
||||
return 'Participant';
|
||||
}
|
||||
return 'None';
|
||||
})(),
|
||||
);
|
||||
}, [myContests, participantContests]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full box-border relative rounded-[10px] px-[20px] py-[14px] text-liquid-white text-[16px] leading-[20px] cursor-pointer items-center font-bold border-transparent hover:border-liquid-darkmain border-solid border-[1px] transition-all duration-300 grid grid-flow-col',
|
||||
userId
|
||||
? 'grid-cols-[1fr,1fr,190px,130px,130px,150px]'
|
||||
: 'grid-cols-[1fr,1fr,190px,130px,130px]',
|
||||
|
||||
type == 'first'
|
||||
? ' bg-liquid-lighter'
|
||||
: ' bg-liquid-background',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (!started) {
|
||||
toastWarning('Контест еще не начался');
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
back: `/group/${groupId}/contests`,
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
>
|
||||
<div className="text-left font-bold text-[18px]">{name}</div>
|
||||
<div className="text-center text-liquid-brightmain font-normal flex items-center justify-center">
|
||||
{username}
|
||||
</div>
|
||||
{scheduleType == 'AlwaysOpen' ? (
|
||||
<div className="text-center text-nowrap whitespace-pre-line text-[14px]">
|
||||
Всегда открыт
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-[5px] text-[14px]">
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(startsAt)}
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="text-center text-nowrap whitespace-pre-line">
|
||||
{formatDate(endsAt)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center">
|
||||
{formatDurationTime(attemptDurationMinutes)}
|
||||
</div>
|
||||
|
||||
{!started ? (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До начала\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
) : (
|
||||
!finished && (
|
||||
<div className="text-center whitespace-pre-line ">
|
||||
{'До конца\n' + formatWaitTime(waitTime)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{userId && (
|
||||
<div className="flex items-center justify-center">
|
||||
{role == 'Organizer' || role == 'Participant' ? (
|
||||
<ReverseButton
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams({
|
||||
back: `/group/${groupId}/contests`,
|
||||
});
|
||||
navigate(`/contest/${contestId}?${params}`);
|
||||
}}
|
||||
text="Войти"
|
||||
/>
|
||||
) : (
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
addOrUpdateContestMember({
|
||||
contestId: contestId,
|
||||
member: {
|
||||
userId: Number(userId),
|
||||
role: 'Participant',
|
||||
},
|
||||
}),
|
||||
)
|
||||
.unwrap()
|
||||
.then(() =>
|
||||
dispatch(
|
||||
fetchParticipatingContests({}),
|
||||
),
|
||||
);
|
||||
}}
|
||||
text="Регистрация"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpcoingContestItem;
|
||||
@@ -2,9 +2,7 @@ import { FC, useEffect, useState } from 'react';
|
||||
import { Modal } from '../../../../components/modal/Modal';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
|
||||
import { Input } from '../../../../components/input/Input';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { createGroup } from '../../../../redux/slices/groups';
|
||||
import MarkdownEditor from '../../../articleeditor/Editor';
|
||||
import {
|
||||
createPost,
|
||||
|
||||
@@ -2,12 +2,9 @@ import { FC, useEffect, useState } from 'react';
|
||||
import { Modal } from '../../../../components/modal/Modal';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
|
||||
import { Input } from '../../../../components/input/Input';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { createGroup } from '../../../../redux/slices/groups';
|
||||
import MarkdownEditor, { MarkDownPattern } from '../../../articleeditor/Editor';
|
||||
import {
|
||||
createPost,
|
||||
deletePost,
|
||||
fetchPostById,
|
||||
setGroupFeedStatus,
|
||||
@@ -55,7 +52,7 @@ const ModalUpdate: FC<ModalUpdateProps> = ({
|
||||
}, [statusDelete]);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchPostById({ groupId, postId }));
|
||||
if (postId) dispatch(fetchPostById({ groupId, postId }));
|
||||
}, [postId]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -32,13 +32,10 @@ interface PostItemProps {
|
||||
|
||||
export const PostItem: FC<PostItemProps> = ({
|
||||
id,
|
||||
groupId,
|
||||
authorId,
|
||||
authorUsername,
|
||||
name,
|
||||
content,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
isAdmin,
|
||||
setModalUpdateActive,
|
||||
setUpdatePostId,
|
||||
|
||||
@@ -2,7 +2,6 @@ import { FC, useEffect, useState } from 'react';
|
||||
|
||||
import { useAppSelector, useAppDispatch } from '../../../../redux/hooks';
|
||||
import { fetchGroupPosts } from '../../../../redux/slices/groupfeed';
|
||||
import { SearchInput } from '../../../../components/input/SearchInput';
|
||||
import { setMenuActiveGroupPage } from '../../../../redux/slices/store';
|
||||
import { fetchGroupById } from '../../../../redux/slices/groups';
|
||||
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
|
||||
@@ -54,45 +53,48 @@ export const Posts: FC<PostsProps> = ({ groupId }) => {
|
||||
const page0 = pages[0];
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-scroll thin-dark-scrollbar">
|
||||
<div className="h-[40px] mb-[20px] relative">
|
||||
<SearchInput
|
||||
className="w-[216px]"
|
||||
onChange={(v) => {}}
|
||||
placeholder="Поиск сообщений"
|
||||
/>
|
||||
{isAdmin && (
|
||||
<div className=" h-[40px] w-[180px] absolute top-0 right-0 flex items-center">
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
setModalCreateActive(true);
|
||||
}}
|
||||
text="Создать пост"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{status === 'loading' && <div>Загрузка...</div>}
|
||||
{status === 'failed' && <div>Ошибка загрузки постов</div>}
|
||||
|
||||
{status == 'successful' &&
|
||||
page0?.items &&
|
||||
page0.items.length > 0 ? (
|
||||
<div className="flex flex-col gap-[20px]">
|
||||
{page0.items.map((post, i) => (
|
||||
<PostItem
|
||||
{...post}
|
||||
key={i}
|
||||
isAdmin={isAdmin}
|
||||
setModalUpdateActive={setModalUpdateActive}
|
||||
setUpdatePostId={setUpdatePostId}
|
||||
/>
|
||||
))}
|
||||
<div className="h-full relative">
|
||||
<div className="grid grid-rows-[40px,1fr,40px] h-full relative min-h-0 gap-[20px]">
|
||||
<div className="h-[40px] mb-[20px] relative">
|
||||
{isAdmin && (
|
||||
<div className=" h-[40px] w-[180px] absolute top-0 right-0 flex items-center">
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
setModalCreateActive(true);
|
||||
}}
|
||||
text="Создать пост"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : status === 'successful' ? (
|
||||
<div>Постов пока нет</div>
|
||||
) : null}
|
||||
|
||||
<>
|
||||
{status === 'loading' && <div>Загрузка...</div>}
|
||||
{status === 'failed' && <div>Ошибка загрузки постов</div>}
|
||||
|
||||
{status == 'successful' &&
|
||||
page0?.items &&
|
||||
page0.items.length > 0 ? (
|
||||
<div className="min-h-0 overflow-y-scroll thin-dark-scrollbar">
|
||||
<div className="flex flex-col gap-[20px] min-h-0 h-0 px-[16px]">
|
||||
{page0.items.map((post, i) => (
|
||||
<PostItem
|
||||
{...post}
|
||||
key={i}
|
||||
isAdmin={isAdmin}
|
||||
setModalUpdateActive={
|
||||
setModalUpdateActive
|
||||
}
|
||||
setUpdatePostId={setUpdatePostId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : status === 'successful' ? (
|
||||
<div>Постов пока нет</div>
|
||||
) : null}
|
||||
</>
|
||||
</div>
|
||||
|
||||
<ModalCreate
|
||||
active={modalCreateActive}
|
||||
|
||||
@@ -1,48 +1,16 @@
|
||||
import {
|
||||
FilterDropDown,
|
||||
FilterItem,
|
||||
} from '../../../components/drop-down-list/Filter';
|
||||
import { SorterDropDown } from '../../../components/drop-down-list/Sorter';
|
||||
import { SearchInput } from '../../../components/input/SearchInput';
|
||||
import { useAppDispatch } from '../../../redux/hooks';
|
||||
import { setGroupFilter } from '../../../redux/slices/store';
|
||||
|
||||
const Filters = () => {
|
||||
const items: FilterItem[] = [
|
||||
{ text: 'React', value: 'react' },
|
||||
{ text: 'Vue', value: 'vue' },
|
||||
{ text: 'Angular', value: 'angular' },
|
||||
{ text: 'Svelte', value: 'svelte' },
|
||||
{ text: 'Next.js', value: 'next' },
|
||||
{ text: 'Nuxt', value: 'nuxt' },
|
||||
{ text: 'Solid', value: 'solid' },
|
||||
{ text: 'Qwik', value: 'qwik' },
|
||||
];
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
return (
|
||||
<div className=" h-[50px] mb-[20px] flex gap-[20px] items-center">
|
||||
<SearchInput onChange={() => {}} placeholder="Поиск задачи" />
|
||||
|
||||
<SorterDropDown
|
||||
items={[
|
||||
{
|
||||
value: '1',
|
||||
text: 'Сложность',
|
||||
},
|
||||
{
|
||||
value: '2',
|
||||
text: 'Дата создания',
|
||||
},
|
||||
{
|
||||
value: '3',
|
||||
text: 'ID',
|
||||
},
|
||||
]}
|
||||
onChange={(v) => {}}
|
||||
/>
|
||||
|
||||
<FilterDropDown
|
||||
items={items}
|
||||
defaultState={[]}
|
||||
onChange={(values) => {}}
|
||||
<SearchInput
|
||||
onChange={(v: string) => {
|
||||
dispatch(setGroupFilter(v));
|
||||
}}
|
||||
placeholder="Поиск группы"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
import { cn } from '../../../lib/cn';
|
||||
import {
|
||||
Book,
|
||||
UserAdd,
|
||||
Edit,
|
||||
EyeClosed,
|
||||
EyeOpen,
|
||||
} from '../../../assets/icons/groups';
|
||||
import { Book, UserAdd, Edit } from '../../../assets/icons/groups';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { GroupInvite, GroupUpdate } from './Groups';
|
||||
import { useAppSelector } from '../../../redux/hooks';
|
||||
|
||||
export interface GroupItemProps {
|
||||
id: number;
|
||||
role: 'menager' | 'member' | 'owner' | 'viewer';
|
||||
visible: boolean;
|
||||
name: string;
|
||||
description: string;
|
||||
setUpdateActive: (value: any) => void;
|
||||
@@ -43,8 +37,6 @@ const IconComponent: React.FC<IconComponentProps> = ({ src, onClick }) => {
|
||||
const GroupItem: React.FC<GroupItemProps> = ({
|
||||
id,
|
||||
name,
|
||||
visible,
|
||||
role,
|
||||
description,
|
||||
setUpdateGroup,
|
||||
setUpdateActive,
|
||||
@@ -54,6 +46,61 @@ const GroupItem: React.FC<GroupItemProps> = ({
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const filter = useAppSelector(
|
||||
(state) => state.store.group.groupFilter,
|
||||
).toLowerCase();
|
||||
|
||||
const highlightZ = (name: string, filter: string) => {
|
||||
if (!filter) return name;
|
||||
|
||||
const s = filter.toLowerCase();
|
||||
const t = name.toLowerCase();
|
||||
const n = t.length;
|
||||
const m = s.length;
|
||||
|
||||
const mark = Array(n).fill(false);
|
||||
|
||||
// Проходимся с конца и ставим отметки
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
if (i + m <= n && t.slice(i, i + m) === s) {
|
||||
for (let j = i; j < i + m; j++) {
|
||||
if (mark[j]) break;
|
||||
mark[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Формируем единые жёлтые блоки ===
|
||||
const result: any[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < n) {
|
||||
if (!mark[i]) {
|
||||
// обычный символ
|
||||
result.push(name[i]);
|
||||
i++;
|
||||
} else {
|
||||
// начинаем жёлтый блок
|
||||
let j = i;
|
||||
while (j < n && mark[j]) j++;
|
||||
|
||||
const chunk = name.slice(i, j);
|
||||
result.push(
|
||||
<span
|
||||
key={i}
|
||||
className="bg-yellow-400 text-black rounded px-1"
|
||||
>
|
||||
{chunk}
|
||||
</span>,
|
||||
);
|
||||
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -67,7 +114,10 @@ const GroupItem: React.FC<GroupItemProps> = ({
|
||||
className="bg-liquid-brightmain rounded-[10px]"
|
||||
/>
|
||||
<div className="grid grid-flow-row grid-rows-[1fr,24px]">
|
||||
<div className="text-[18px] font-bold">{name}</div>
|
||||
<div className="text-[18px] font-bold">
|
||||
{highlightZ(name, filter)}
|
||||
</div>
|
||||
|
||||
<div className=" flex gap-[10px]">
|
||||
{type == 'manage' && (
|
||||
<IconComponent
|
||||
@@ -87,8 +137,6 @@ const GroupItem: React.FC<GroupItemProps> = ({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{visible == false && <IconComponent src={EyeOpen} />}
|
||||
{visible == true && <IconComponent src={EyeClosed} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { cn } from '../../../lib/cn';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import GroupsBlock from './GroupsBlock';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import { fetchMyGroups } from '../../../redux/slices/groups';
|
||||
import { fetchMyGroups, Group } from '../../../redux/slices/groups';
|
||||
import ModalCreate from './ModalCreate';
|
||||
import ModalUpdate from './ModalUpdate';
|
||||
import Filters from './Filter';
|
||||
@@ -45,6 +45,7 @@ const Groups = () => {
|
||||
const groupsError = useAppSelector(
|
||||
(store) => store.groups.fetchMyGroups.error,
|
||||
);
|
||||
const filter = useAppSelector((state) => state.store.group.groupFilter);
|
||||
|
||||
// Берём текущего пользователя
|
||||
const currentUserName = useAppSelector((store) => store.auth.username);
|
||||
@@ -54,17 +55,21 @@ const Groups = () => {
|
||||
dispatch(fetchMyGroups());
|
||||
}, [dispatch]);
|
||||
|
||||
// Разделяем группы
|
||||
const { managedGroups, currentGroups, hiddenGroups } = useMemo(() => {
|
||||
const applyFilter = (groups: Group[], filter: string) => {
|
||||
if (!filter || filter.trim() === '') return groups;
|
||||
const normalized = filter.toLowerCase();
|
||||
|
||||
return groups.filter((g) => g.name.toLowerCase().includes(normalized));
|
||||
};
|
||||
const { managedGroups, currentGroups } = useMemo(() => {
|
||||
if (!groups || !currentUserName) {
|
||||
return { managedGroups: [], currentGroups: [], hiddenGroups: [] };
|
||||
return { managedGroups: [], currentGroups: [] };
|
||||
}
|
||||
|
||||
const managed: typeof groups = [];
|
||||
const current: typeof groups = [];
|
||||
const hidden: typeof groups = []; // пока пустые, без логики
|
||||
|
||||
groups.forEach((group) => {
|
||||
applyFilter(groups, filter).forEach((group) => {
|
||||
const me = group.members.find(
|
||||
(m) => m.username === currentUserName,
|
||||
);
|
||||
@@ -80,9 +85,8 @@ const Groups = () => {
|
||||
return {
|
||||
managedGroups: managed,
|
||||
currentGroups: current,
|
||||
hiddenGroups: hidden,
|
||||
};
|
||||
}, [groups, currentUserName]);
|
||||
}, [groups, currentUserName, filter]);
|
||||
|
||||
return (
|
||||
<div className="h-full w-[calc(100%+250px)] box-border p-[20px] pt-[20px]">
|
||||
@@ -137,16 +141,6 @@ const Groups = () => {
|
||||
setInviteGroup={setInviteGroup}
|
||||
type="member"
|
||||
/>
|
||||
<GroupsBlock
|
||||
className="mb-[20px]"
|
||||
title="Скрытые"
|
||||
groups={hiddenGroups} // пока пусто
|
||||
setUpdateActive={setModalUpdateActive}
|
||||
setUpdateGroup={setUpdateGroup}
|
||||
setInviteActive={setModalInviteActive}
|
||||
setInviteGroup={setInviteGroup}
|
||||
type="member"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -65,7 +65,6 @@ const GroupsBlock: FC<GroupsBlockProps> = ({
|
||||
<GroupItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
visible={true}
|
||||
description={v.description}
|
||||
setUpdateActive={setUpdateActive}
|
||||
setUpdateGroup={setUpdateGroup}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { fetchGroupJoinLink } from '../../../redux/slices/groups';
|
||||
import { Modal } from '../../../components/modal/Modal';
|
||||
import { PrimaryButton } from '../../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../../components/button/SecondaryButton';
|
||||
import { Input } from '../../../components/input/Input';
|
||||
import { toastSuccess } from '../../../lib/toastNotification';
|
||||
|
||||
interface ModalInviteProps {
|
||||
active: boolean;
|
||||
@@ -51,10 +51,9 @@ const ModalInvite: FC<ModalInviteProps> = ({
|
||||
if (!inviteLink) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(inviteLink);
|
||||
toastSuccess('Приглашение скопировано в буфер обмена!');
|
||||
setActive(false);
|
||||
} catch (err) {
|
||||
console.error('Не удалось скопировать ссылку:', err);
|
||||
}
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
Account,
|
||||
Clipboard,
|
||||
Cup,
|
||||
Home,
|
||||
Openbook,
|
||||
Users,
|
||||
} from '../../../assets/icons/menu';
|
||||
@@ -12,7 +11,6 @@ import { useAppSelector } from '../../../redux/hooks';
|
||||
|
||||
const Menu = () => {
|
||||
const menuItems = [
|
||||
{ text: 'Главная', href: '/home', icon: Home, page: 'home' },
|
||||
{
|
||||
text: 'Задачи',
|
||||
href: '/home/missions',
|
||||
|
||||
@@ -1,48 +1,25 @@
|
||||
import {
|
||||
FilterDropDown,
|
||||
FilterItem,
|
||||
} from '../../../components/drop-down-list/Filter';
|
||||
import { SorterDropDown } from '../../../components/drop-down-list/Sorter';
|
||||
import { FC } from 'react';
|
||||
import { TagFilter } from '../../../components/filters/TagFilter';
|
||||
import { SearchInput } from '../../../components/input/SearchInput';
|
||||
|
||||
const Filters = () => {
|
||||
const items: FilterItem[] = [
|
||||
{ text: 'React', value: 'react' },
|
||||
{ text: 'Vue', value: 'vue' },
|
||||
{ text: 'Angular', value: 'angular' },
|
||||
{ text: 'Svelte', value: 'svelte' },
|
||||
{ text: 'Next.js', value: 'next' },
|
||||
{ text: 'Nuxt', value: 'nuxt' },
|
||||
{ text: 'Solid', value: 'solid' },
|
||||
{ text: 'Qwik', value: 'qwik' },
|
||||
];
|
||||
interface MissionFiltersProps {
|
||||
onChangeTags: (value: string[]) => void;
|
||||
onChangeName: (value: string) => void;
|
||||
}
|
||||
|
||||
const Filters: FC<MissionFiltersProps> = ({ onChangeTags, onChangeName }) => {
|
||||
return (
|
||||
<div className=" h-[50px] mb-[20px] flex gap-[20px] items-center">
|
||||
<SearchInput onChange={() => {}} placeholder="Поиск задачи" />
|
||||
|
||||
<SorterDropDown
|
||||
items={[
|
||||
{
|
||||
value: '1',
|
||||
text: 'Сложность',
|
||||
},
|
||||
{
|
||||
value: '2',
|
||||
text: 'Дата создания',
|
||||
},
|
||||
{
|
||||
value: '3',
|
||||
text: 'ID',
|
||||
},
|
||||
]}
|
||||
onChange={(v) => console.log(v)}
|
||||
<SearchInput
|
||||
onChange={(value: string) => {
|
||||
onChangeName(value);
|
||||
}}
|
||||
placeholder="Поиск задачи"
|
||||
/>
|
||||
|
||||
<FilterDropDown
|
||||
items={items}
|
||||
defaultState={[]}
|
||||
onChange={(values) => console.log(values)}
|
||||
<TagFilter
|
||||
onChange={(value: string[]) => {
|
||||
onChangeTags(value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { IconError, IconSuccess } from '../../../assets/icons/missions';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppSelector } from '../../../redux/hooks';
|
||||
|
||||
export interface MissionItemProps {
|
||||
id: number;
|
||||
@@ -38,6 +39,61 @@ const MissionItem: React.FC<MissionItemProps> = ({
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.missions.filterName,
|
||||
);
|
||||
|
||||
const highlightZ = (name: string, filter: string) => {
|
||||
if (!filter) return name;
|
||||
|
||||
const s = filter.toLowerCase();
|
||||
const t = name.toLowerCase();
|
||||
const n = t.length;
|
||||
const m = s.length;
|
||||
|
||||
const mark = Array(n).fill(false);
|
||||
|
||||
// Проходимся с конца и ставим отметки
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
if (i + m <= n && t.slice(i, i + m) === s) {
|
||||
for (let j = i; j < i + m; j++) {
|
||||
if (mark[j]) break;
|
||||
mark[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Формируем единые жёлтые блоки ===
|
||||
const result: any[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < n) {
|
||||
if (!mark[i]) {
|
||||
// обычный символ
|
||||
result.push(name[i]);
|
||||
i++;
|
||||
} else {
|
||||
// начинаем жёлтый блок
|
||||
let j = i;
|
||||
while (j < n && mark[j]) j++;
|
||||
|
||||
const chunk = name.slice(i, j);
|
||||
result.push(
|
||||
<span
|
||||
key={i}
|
||||
className="bg-yellow-400 text-black rounded px-1"
|
||||
>
|
||||
{chunk}
|
||||
</span>,
|
||||
);
|
||||
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -55,7 +111,9 @@ const MissionItem: React.FC<MissionItemProps> = ({
|
||||
}}
|
||||
>
|
||||
<div className="text-[18px] font-bold">#{id}</div>
|
||||
<div className="text-[18px] font-bold">{name}</div>
|
||||
<div className="text-[18px] font-bold">
|
||||
{highlightZ(name, nameFilter)}
|
||||
</div>
|
||||
<div className="text-[12px] text-right">
|
||||
стандартный ввод/вывод {formatMilliseconds(timeLimit)},{' '}
|
||||
{formatBytesToMB(memoryLimit)}
|
||||
|
||||
@@ -2,10 +2,15 @@ import MissionItem from './MissionItem';
|
||||
import { SecondaryButton } from '../../../components/button/SecondaryButton';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { setMenuActivePage } from '../../../redux/slices/store';
|
||||
import {
|
||||
setMenuActivePage,
|
||||
setMissionsNameFilter,
|
||||
setMissionsTagFilter,
|
||||
} from '../../../redux/slices/store';
|
||||
import { fetchMissions } from '../../../redux/slices/missions';
|
||||
import ModalCreate from './ModalCreate';
|
||||
import Filters from './Filter';
|
||||
import { toastWarning } from '../../../lib/toastNotification';
|
||||
|
||||
export interface Mission {
|
||||
id: number;
|
||||
@@ -25,10 +30,28 @@ const Missions = () => {
|
||||
|
||||
const missions = useAppSelector((state) => state.missions.missions);
|
||||
|
||||
const jwt = useAppSelector((state) => state.auth.jwt);
|
||||
const nameFilter = useAppSelector(
|
||||
(state) => state.store.missions.filterName,
|
||||
);
|
||||
const tagsFilter = useAppSelector(
|
||||
(state) => state.store.articles.articleTagFilter,
|
||||
);
|
||||
|
||||
const calcDifficulty = (d: number) => {
|
||||
if (d <= 1200) return 'Easy';
|
||||
if (d <= 2000) return 'Medium';
|
||||
return 'Hard';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setMenuActivePage('missions'));
|
||||
dispatch(fetchMissions({}));
|
||||
dispatch(fetchMissions({ tags: tagsFilter }));
|
||||
}, []);
|
||||
const filterTagsHandler = (value: string[]) => {
|
||||
dispatch(setMissionsTagFilter(value));
|
||||
dispatch(fetchMissions({ tags: value }));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className=" h-full w-full box-border p-[20px] pt-[20px]">
|
||||
@@ -39,6 +62,11 @@ const Missions = () => {
|
||||
</div>
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
|
||||
if (!jwt){
|
||||
toastWarning("Для загрузки задачи необходимо авторизоваться")
|
||||
return;
|
||||
}
|
||||
setModalActive(true);
|
||||
}}
|
||||
text="Добавить задачу"
|
||||
@@ -46,34 +74,39 @@ const Missions = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Filters />
|
||||
<Filters
|
||||
onChangeTags={(value: string[]) => {
|
||||
filterTagsHandler(value);
|
||||
}}
|
||||
onChangeName={(value: string) => {
|
||||
dispatch(setMissionsNameFilter(value));
|
||||
}}
|
||||
/>
|
||||
|
||||
<div>
|
||||
{missions.map((v, i) => (
|
||||
<MissionItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
authorId={v.authorId}
|
||||
name={v.name}
|
||||
difficulty={'Easy'}
|
||||
tags={v.tags}
|
||||
timeLimit={1000}
|
||||
memoryLimit={256 * 1024 * 1024}
|
||||
createdAt={v.createdAt}
|
||||
updatedAt={v.updatedAt}
|
||||
type={i % 2 == 0 ? 'first' : 'second'}
|
||||
status={
|
||||
i == 0 || i == 3 || i == 7
|
||||
? 'success'
|
||||
: i == 2 || i == 4 || i == 9
|
||||
? 'error'
|
||||
: 'empty'
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{missions
|
||||
.filter((v) =>
|
||||
v.name
|
||||
.toLowerCase()
|
||||
.includes(nameFilter.toLocaleLowerCase()),
|
||||
)
|
||||
.map((v, i) => (
|
||||
<MissionItem
|
||||
key={i}
|
||||
id={v.id}
|
||||
authorId={v.authorId}
|
||||
name={v.name}
|
||||
difficulty={calcDifficulty(v.difficulty)}
|
||||
tags={v.tags}
|
||||
timeLimit={1000}
|
||||
memoryLimit={256 * 1024 * 1024}
|
||||
createdAt={v.createdAt}
|
||||
updatedAt={v.updatedAt}
|
||||
type={i % 2 == 0 ? 'first' : 'second'}
|
||||
status={'empty'}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>pages</div>
|
||||
</div>
|
||||
|
||||
<ModalCreate setActive={setModalActive} active={modalActive} />
|
||||
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
setMissionsStatus,
|
||||
uploadMission,
|
||||
} from '../../../redux/slices/missions';
|
||||
import { toastSuccess } from '../../../lib/toastNotification';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { NumberInput } from '../../../components/input/NumberInput';
|
||||
|
||||
interface ModalCreateProps {
|
||||
active: boolean;
|
||||
@@ -24,6 +28,8 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
const status = useAppSelector((state) => state.missions.statuses.upload);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [clickSubmit, setClickSubmit] = useState<boolean>(false);
|
||||
|
||||
const addTag = () => {
|
||||
const newTag = tagInput.trim();
|
||||
if (newTag && !tags.includes(newTag)) {
|
||||
@@ -43,13 +49,14 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!file) return alert('Выберите файл миссии!');
|
||||
setClickSubmit(true);
|
||||
if (!file) return;
|
||||
dispatch(uploadMission({ file, name, difficulty, tags }));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (status === 'successful') {
|
||||
alert('Миссия успешно загружена!');
|
||||
toastSuccess('Миссия создана!');
|
||||
setName('');
|
||||
setDifficulty(1);
|
||||
setTags([]);
|
||||
@@ -60,9 +67,18 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (active == true) {
|
||||
setClickSubmit(false);
|
||||
}
|
||||
dispatch(setMissionsStatus({ key: 'upload', status: 'idle' }));
|
||||
}, [active]);
|
||||
|
||||
const getNameErrorMessage = (): string => {
|
||||
if (!clickSubmit) return '';
|
||||
if (name == '') return 'Поле не может быть пустым';
|
||||
return '';
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
||||
@@ -82,16 +98,17 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
defaultState={name}
|
||||
onChange={setName}
|
||||
placeholder="В яблочко"
|
||||
error={getNameErrorMessage()}
|
||||
/>
|
||||
|
||||
<Input
|
||||
<NumberInput
|
||||
name="difficulty"
|
||||
autocomplete="difficulty"
|
||||
className="mt-[10px]"
|
||||
type="number"
|
||||
label="Сложность"
|
||||
defaultState={'' + difficulty}
|
||||
onChange={(v) => setDifficulty(Number(v))}
|
||||
defaultState={difficulty}
|
||||
minValue={1}
|
||||
maxValue={3500}
|
||||
onChange={(v) => setDifficulty(v)}
|
||||
placeholder="1"
|
||||
/>
|
||||
|
||||
@@ -106,6 +123,16 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
{
|
||||
<div
|
||||
className={cn(
|
||||
'text-liquid-red text-[14px] h-auto text-left mt-[5px] whitespace-pre-line overflow-hidden ',
|
||||
(!clickSubmit || file) && 'h-0 mt-0',
|
||||
)}
|
||||
>
|
||||
Необходимо выбрать файл задачи
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
{/* Теги */}
|
||||
@@ -148,6 +175,17 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Создать пакет задачи можно на платформе{' '}
|
||||
<Link
|
||||
to={'https://polygon.codeforces.com'}
|
||||
target="_blank"
|
||||
className="text-[#7489ff] hover:text-[#8c9dfd] transition-color duration-300"
|
||||
>
|
||||
polygon
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
<PrimaryButton
|
||||
onClick={handleSubmit}
|
||||
@@ -159,8 +197,6 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||
text="Отмена"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{status == 'failed' && <div>error</div>}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
@@ -1,40 +1,63 @@
|
||||
import { FC } from 'react';
|
||||
import { FC, Fragment, useEffect } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { fetchNewArticles } from '../../../redux/slices/articles';
|
||||
|
||||
export const ArticlesRightPanel: FC = () => {
|
||||
const items = [
|
||||
{
|
||||
name: 'Энтузиаст создал карточки с NFC-метками для знакомства ребёнка с музыкой',
|
||||
},
|
||||
{
|
||||
name: 'Алгоритм Древа Силы, Космический Сортировщик',
|
||||
},
|
||||
{
|
||||
name: 'Космический Сортировщик',
|
||||
},
|
||||
{
|
||||
name: 'Зеркала Многомерности',
|
||||
},
|
||||
];
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const articles = useAppSelector(
|
||||
(state) => state.articles.fetchNewArticles.articles,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchNewArticles({ pageSize: 10 }));
|
||||
}, []);
|
||||
|
||||
const getDaysAgo = (dateString: string) => {
|
||||
const updatedDate = new Date(dateString);
|
||||
const today = new Date();
|
||||
// Сбрасываем время для точного сравнения по дням
|
||||
updatedDate.setHours(0, 0, 0, 0);
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const diffTime = today.getTime() - updatedDate.getTime();
|
||||
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffDays === 0) return 'Сегодня';
|
||||
if (diffDays === 1) return '1 день назад';
|
||||
return `${diffDays} дня назад`;
|
||||
};
|
||||
return (
|
||||
<div className="h-screen w-full overflow-y-scroll thin-dark-scrollbar p-[20px] gap-[10px] flex flex-col">
|
||||
<div className="text-liquid-white font-bold text-[18px]">
|
||||
Попоулярные статьи
|
||||
<div className="text-liquid-white font-bold text-[24px] mb-[10px]">
|
||||
Новые статьи
|
||||
</div>
|
||||
|
||||
{items.map((v, i) => {
|
||||
return (
|
||||
<>
|
||||
{
|
||||
<div className="font-bold text-liquid-light text-[16px]">
|
||||
{v.name}
|
||||
</div>
|
||||
}
|
||||
{i + 1 != items.length && (
|
||||
<div className="h-[1px] w-full bg-liquid-lighter"></div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})}
|
||||
{articles &&
|
||||
articles
|
||||
.filter((v) => {
|
||||
const updatedDate = new Date(v.updatedAt);
|
||||
const threeDaysAgo = new Date();
|
||||
threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
|
||||
return updatedDate >= threeDaysAgo;
|
||||
})
|
||||
.map((v, i) => {
|
||||
return (
|
||||
<Fragment key={i}>
|
||||
{
|
||||
<div className="font-bold text-liquid-white text-[16px]">
|
||||
{v.name}
|
||||
<div className="text-sm text-liquid-light">
|
||||
{getDaysAgo(v.updatedAt)}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{i + 1 != articles.length && (
|
||||
<div className="h-[1px] w-full bg-liquid-lighter"></div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { FC } from 'react';
|
||||
|
||||
export const GroupRightPanel: FC = () => {
|
||||
const items = [
|
||||
{
|
||||
name: 'Игнат Герасименко',
|
||||
role: 'Администратор',
|
||||
},
|
||||
{
|
||||
name: 'Алиса Макаренко',
|
||||
role: 'Модератор',
|
||||
},
|
||||
{
|
||||
name: 'Федор Картман',
|
||||
role: 'Модератор',
|
||||
},
|
||||
{
|
||||
name: 'Карина Механаджанович',
|
||||
role: 'Участник',
|
||||
},
|
||||
{
|
||||
name: 'Михаил Ангрский',
|
||||
role: 'Участник',
|
||||
},
|
||||
{
|
||||
name: 'newuser',
|
||||
role: 'Участник (Вы)',
|
||||
},
|
||||
];
|
||||
return (
|
||||
<div className="h-screen w-full overflow-y-scroll thin-dark-scrollbar p-[20px] gap-[5px] flex flex-col">
|
||||
<div className="text-liquid-white font-bold text-[18px]">
|
||||
Пользователи
|
||||
</div>
|
||||
|
||||
{items.map((v, i) => {
|
||||
return (
|
||||
<>
|
||||
{
|
||||
<div className="text-liquid-light text-[16px] grid grid-cols-[40px,1fr] gap-[10px] items-center cursor-pointer hover:bg-liquid-lighter transition-all duration-300 rounded-[10px] p-[5px]">
|
||||
<div className="h-[40px] w-[40px] rounded-[10px] bg-[#D9D9D9]"></div>
|
||||
<div className="flex flex-col">
|
||||
<div className="text-liquid-white font-bold text-[16px] leading-5">
|
||||
{v.name}
|
||||
</div>
|
||||
<div className="text-liquid-light font-normal text-[16px] leading-5">
|
||||
{v.role}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{i + 1 != items.length && (
|
||||
<div className="h-[1px] w-full bg-liquid-lighter"></div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
import { FC } from 'react';
|
||||
import { FC, Fragment, useEffect } from 'react';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { fetchNewMissions } from '../../../redux/slices/missions';
|
||||
|
||||
export const MissionsRightPanel: FC = () => {
|
||||
const items = [
|
||||
@@ -24,30 +26,61 @@ export const MissionsRightPanel: FC = () => {
|
||||
tags: ['matrix', 'geometry', 'simulation'],
|
||||
},
|
||||
];
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const missions = useAppSelector((state) => state.missions.newMissions);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchNewMissions({ pageSize: 10 }));
|
||||
}, []);
|
||||
|
||||
const getDaysAgo = (dateString: string) => {
|
||||
const updatedDate = new Date(dateString);
|
||||
const today = new Date();
|
||||
// Сбрасываем время для точного сравнения по дням
|
||||
updatedDate.setHours(0, 0, 0, 0);
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const diffTime = today.getTime() - updatedDate.getTime();
|
||||
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffDays === 0) return 'Сегодня';
|
||||
if (diffDays === 1) return '1 день назад';
|
||||
return `${diffDays} дня назад`;
|
||||
};
|
||||
|
||||
const calcDifficulty = (d: number) => {
|
||||
if (d <= 1200) return 'Easy';
|
||||
if (d <= 2000) return 'Medium';
|
||||
return 'Hard';
|
||||
};
|
||||
return (
|
||||
<div className="h-screen w-full overflow-y-scroll thin-dark-scrollbar p-[20px] gap-[10px] flex flex-col">
|
||||
<div className="text-liquid-white font-bold text-[18px]">
|
||||
Новые задачи
|
||||
</div>
|
||||
|
||||
{items.map((v, i) => {
|
||||
{missions.map((v, i) => {
|
||||
return (
|
||||
<>
|
||||
<Fragment key={i}>
|
||||
{
|
||||
<div className="text-liquid-light text-[16px]">
|
||||
<div className="font-bold ">{v.name}</div>
|
||||
<div className="font-bold text-liquid-white">
|
||||
{v.name}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'',
|
||||
v.difficulty == 'Hard' &&
|
||||
'text-liquid-red',
|
||||
v.difficulty == 'Medium' &&
|
||||
'text-liquid-orange',
|
||||
v.difficulty == 'Easy' &&
|
||||
'text-liquid-green',
|
||||
calcDifficulty(v.difficulty) ==
|
||||
'Hard' && 'text-liquid-red',
|
||||
calcDifficulty(v.difficulty) ==
|
||||
'Medium' && 'text-liquid-orange',
|
||||
calcDifficulty(v.difficulty) ==
|
||||
'Easy' && 'text-liquid-green',
|
||||
)}
|
||||
>
|
||||
{v.difficulty}
|
||||
{calcDifficulty(v.difficulty)}
|
||||
</div>
|
||||
<div className="flex gap-[10px] overflow-hidden">
|
||||
{v.tags.slice(0, 2).map((v, i) => (
|
||||
@@ -55,12 +88,15 @@ export const MissionsRightPanel: FC = () => {
|
||||
))}
|
||||
{v.tags.length > 2 && '...'}
|
||||
</div>
|
||||
<div className="text-sm text-liquid-light">
|
||||
{getDaysAgo(v.updatedAt)}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{i + 1 != items.length && (
|
||||
<div className="h-[1px] w-full bg-liquid-lighter"></div>
|
||||
)}
|
||||
</>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
135
src/views/home/rightpanel/group/Group.tsx
Normal file
135
src/views/home/rightpanel/group/Group.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { FC, Fragment, useEffect, useState } from 'react';
|
||||
import { Navigate, useNavigate, useParams } from 'react-router-dom';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import { fetchGroupById, GroupMember } from '../../../../redux/slices/groups';
|
||||
import { Edit } from '../../../../assets/icons/input';
|
||||
import { Logout } from '../../../../assets/icons/group';
|
||||
import ModalLeave from './ModalLeave';
|
||||
import ModalUpdate from './ModalUpdate';
|
||||
|
||||
export const GroupRightPanel: FC = () => {
|
||||
const groupId = Number(useParams<{ groupId: string }>().groupId);
|
||||
if (!groupId) {
|
||||
return <Navigate to="/home/groups" replace />;
|
||||
}
|
||||
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [user, setUser] = useState<GroupMember | undefined>();
|
||||
const [myUser, setMyUser] = useState<GroupMember | undefined>();
|
||||
const [isAdmin, setIsAdmin] = useState<boolean>(false);
|
||||
const [modalLeaveActive, setModalLeaveActive] = useState<boolean>(false);
|
||||
const [modalUpdateActive, setModalUpdateActive] = useState<boolean>(false);
|
||||
const { id: userId } = useAppSelector((state) => state.auth);
|
||||
|
||||
const { group } = useAppSelector((state) => state.groups.fetchGroupById);
|
||||
useEffect(() => {
|
||||
dispatch(fetchGroupById(groupId));
|
||||
}, [groupId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!group) return;
|
||||
|
||||
const isUserAdmin =
|
||||
group.members?.some(
|
||||
(m) =>
|
||||
Number(m.userId) === Number(userId) &&
|
||||
m.role.includes('Administrator'),
|
||||
) || false;
|
||||
|
||||
setIsAdmin(isUserAdmin);
|
||||
|
||||
const member = group.members?.find(
|
||||
(m) => Number(m.userId) === Number(userId),
|
||||
);
|
||||
|
||||
setMyUser(member);
|
||||
}, [group, userId]);
|
||||
|
||||
return (
|
||||
<div className="h-screen w-full overflow-y-scroll thin-dark-scrollbar p-[20px] gap-[5px] flex flex-col">
|
||||
<div className="text-liquid-white font-bold text-[18px]">
|
||||
Пользователи
|
||||
</div>
|
||||
|
||||
{group?.members.map((v, i) => {
|
||||
return (
|
||||
<Fragment key={i}>
|
||||
{
|
||||
<div
|
||||
className="text-liquid-light text-[16px] grid grid-cols-[40px,1fr] gap-[10px] items-center cursor-pointer hover:bg-liquid-lighter transition-all duration-300 rounded-[10px] p-[5px] group"
|
||||
onClick={() => {
|
||||
navigate(
|
||||
`/home/account/missions?username=${v.username}`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="h-[40px] w-[40px] rounded-[10px] bg-[#D9D9D9]"></div>
|
||||
<div className="flex flex-col">
|
||||
<div className="text-liquid-white font-bold text-[16px] leading-5">
|
||||
{v.username}
|
||||
</div>
|
||||
<div className="text-liquid-light font-normal text-[16px] leading-5">
|
||||
{v.role +
|
||||
(Number(userId) == v.userId
|
||||
? ' (Вы)'
|
||||
: '')}
|
||||
</div>
|
||||
</div>
|
||||
{(isAdmin || Number(userId) == v.userId) &&
|
||||
!v.role.includes('Creator') && (
|
||||
<div
|
||||
className="h-[34px] w-[34px] absolute right-[34px] opacity-0 group-hover:opacity-100 transition-all duration-300 hover:bg-liquid-light rounded-[10px] p-[5px] active:scale-90"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (
|
||||
Number(userId) == v.userId
|
||||
) {
|
||||
setModalLeaveActive(true);
|
||||
return;
|
||||
}
|
||||
if (isAdmin) {
|
||||
setUser(v);
|
||||
setModalUpdateActive(true);
|
||||
return;
|
||||
}
|
||||
}}
|
||||
>
|
||||
{Number(userId) == v.userId ? (
|
||||
<img src={Logout} />
|
||||
) : isAdmin ? (
|
||||
<img src={Edit} />
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
{i + 1 != group?.members.length && (
|
||||
<div className="h-[1px] w-full bg-liquid-lighter"></div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
|
||||
<ModalLeave
|
||||
groupId={groupId}
|
||||
groupName={group?.name}
|
||||
userId={Number(userId)}
|
||||
active={modalLeaveActive}
|
||||
setActive={setModalLeaveActive}
|
||||
/>
|
||||
<ModalUpdate
|
||||
groupId={groupId}
|
||||
groupName={group?.name}
|
||||
userId={Number(userId)}
|
||||
user={user}
|
||||
adminUser={myUser}
|
||||
active={modalUpdateActive}
|
||||
setActive={setModalUpdateActive}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
105
src/views/home/rightpanel/group/ModalLeave.tsx
Normal file
105
src/views/home/rightpanel/group/ModalLeave.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { Modal } from '../../../../components/modal/Modal';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import {
|
||||
removeGroupMember,
|
||||
setGroupsStatus,
|
||||
} from '../../../../redux/slices/groups';
|
||||
import ConfirmModal from '../../../../components/modal/ConfirmModal';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
interface ModalLeaveProps {
|
||||
active: boolean;
|
||||
setActive: (value: boolean) => void;
|
||||
groupId: number;
|
||||
groupName?: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
const ModalLeave: FC<ModalLeaveProps> = ({
|
||||
active,
|
||||
setActive,
|
||||
groupName,
|
||||
groupId,
|
||||
userId,
|
||||
}) => {
|
||||
const statusLeave = useAppSelector(
|
||||
(state) => state.groups.removeGroupMember.status,
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [modalConfirmActive, setModalConfirmActive] =
|
||||
useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (statusLeave == 'successful') {
|
||||
dispatch(
|
||||
setGroupsStatus({ key: 'removeGroupMember', status: 'idle' }),
|
||||
);
|
||||
setActive(false);
|
||||
navigate('/home/groups');
|
||||
}
|
||||
}, [statusLeave]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
||||
onOpenChange={setActive}
|
||||
open={active}
|
||||
backdrop="blur"
|
||||
>
|
||||
<div className="w-[500px]">
|
||||
<div className="font-bold text-[30px]">
|
||||
Вы действительно хотите покинуть группу:
|
||||
</div>
|
||||
<div className="font-bold text-[20px] mt-[20px]">
|
||||
"{groupName}" #{groupId}?
|
||||
</div>
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
setModalConfirmActive(true);
|
||||
}}
|
||||
text={
|
||||
statusLeave == 'loading'
|
||||
? 'Покинуть...'
|
||||
: 'Покинуть'
|
||||
}
|
||||
disabled={statusLeave == 'loading'}
|
||||
color="error"
|
||||
/>
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
setActive(false);
|
||||
}}
|
||||
text="Отмена"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ConfirmModal
|
||||
className=" fixed top-0 left-0"
|
||||
active={modalConfirmActive}
|
||||
setActive={setModalConfirmActive}
|
||||
title="Подтвердите действия"
|
||||
message="Вы действительно хотите покинуть группу?"
|
||||
confirmColor="error"
|
||||
confirmText="Покинуть"
|
||||
onConfirmClick={() => {
|
||||
dispatch(
|
||||
removeGroupMember({
|
||||
groupId,
|
||||
memberId: userId,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModalLeave;
|
||||
223
src/views/home/rightpanel/group/ModalUpdate.tsx
Normal file
223
src/views/home/rightpanel/group/ModalUpdate.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { Modal } from '../../../../components/modal/Modal';
|
||||
import { PrimaryButton } from '../../../../components/button/PrimaryButton';
|
||||
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
|
||||
import { useAppDispatch, useAppSelector } from '../../../../redux/hooks';
|
||||
import {
|
||||
addGroupMember,
|
||||
fetchGroupById,
|
||||
GroupMember,
|
||||
removeGroupMember,
|
||||
setGroupsStatus,
|
||||
} from '../../../../redux/slices/groups';
|
||||
import ConfirmModal from '../../../../components/modal/ConfirmModal';
|
||||
import {
|
||||
DropDownList,
|
||||
DropDownListItem,
|
||||
} from '../../../../components/input/DropDownList';
|
||||
import { ReverseButton } from '../../../../components/button/ReverseButton';
|
||||
|
||||
interface ModalUpdateProps {
|
||||
active: boolean;
|
||||
setActive: (value: boolean) => void;
|
||||
groupId: number;
|
||||
userId: number;
|
||||
user?: GroupMember;
|
||||
adminUser?: GroupMember;
|
||||
groupName?: string;
|
||||
}
|
||||
|
||||
const ModalUpdate: FC<ModalUpdateProps> = ({
|
||||
active,
|
||||
setActive,
|
||||
groupId,
|
||||
user,
|
||||
adminUser,
|
||||
groupName,
|
||||
}) => {
|
||||
const statusLeave = useAppSelector(
|
||||
(state) => state.groups.removeGroupMember.status,
|
||||
);
|
||||
const statusUpdate = useAppSelector(
|
||||
(state) => state.groups.addGroupMember.status,
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [modalConfirmDeleteUser, setModalConfirmDeleteUser] =
|
||||
useState<boolean>(false);
|
||||
const [modalConfirmRoleActive, setModalConfirmRoleActive] =
|
||||
useState<boolean>(false);
|
||||
const [userRole, setUserRole] = useState<string>('');
|
||||
|
||||
useEffect(() => {
|
||||
if (active) {
|
||||
}
|
||||
}, [active]);
|
||||
|
||||
useEffect(() => {
|
||||
if (statusLeave == 'successful') {
|
||||
dispatch(
|
||||
setGroupsStatus({ key: 'removeGroupMember', status: 'idle' }),
|
||||
);
|
||||
dispatch(fetchGroupById(groupId));
|
||||
setActive(false);
|
||||
}
|
||||
}, [statusLeave]);
|
||||
|
||||
useEffect(() => {
|
||||
if (statusUpdate == 'successful') {
|
||||
dispatch(
|
||||
setGroupsStatus({ key: 'addGroupMember', status: 'idle' }),
|
||||
);
|
||||
dispatch(fetchGroupById(groupId));
|
||||
setActive(false);
|
||||
}
|
||||
}, [statusUpdate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setUserRole(
|
||||
user?.role.includes('Creator') ? 'Creator' : user?.role,
|
||||
);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const roles: DropDownListItem[] = [
|
||||
{ value: 'Member', text: 'Участник' },
|
||||
{ value: 'Administrator', text: 'Администратор' },
|
||||
];
|
||||
if (adminUser?.role.includes('Creator')) {
|
||||
roles.push({ value: 'Creator', text: 'Владелец' });
|
||||
}
|
||||
|
||||
const casrtRoleMap: Record<'Member' | 'Administrator' | 'Creator', string> =
|
||||
{
|
||||
Member: 'Участник',
|
||||
Administrator: 'Администратор',
|
||||
Creator: 'Владелец',
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
||||
onOpenChange={setActive}
|
||||
open={active}
|
||||
backdrop="blur"
|
||||
>
|
||||
<div className="w-[500px]">
|
||||
<div className="font-bold text-[30px]">
|
||||
Управление участниками группы:
|
||||
</div>
|
||||
<div className="font-bold text-[20px]">
|
||||
"{groupName}" #{groupId}
|
||||
</div>
|
||||
<div className="my-[5px]">Пользователь: {user?.username}</div>
|
||||
<div>
|
||||
Текущая роль:{' '}
|
||||
{casrtRoleMap[user?.role as keyof typeof casrtRoleMap]}
|
||||
</div>
|
||||
<div className="flex flex-row w-full items-center justify-between mt-[20px] gap-[20px]">
|
||||
<div>
|
||||
<DropDownList
|
||||
defaultState={{
|
||||
value: userRole,
|
||||
text: casrtRoleMap[
|
||||
userRole as keyof typeof casrtRoleMap
|
||||
],
|
||||
}}
|
||||
weight="w-[230px]"
|
||||
items={roles}
|
||||
onChange={(v) => {
|
||||
setUserRole(v);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<PrimaryButton
|
||||
onClick={() => {
|
||||
setModalConfirmRoleActive(true);
|
||||
}}
|
||||
text={
|
||||
statusUpdate == 'loading'
|
||||
? 'Назначить...'
|
||||
: 'Назначить'
|
||||
}
|
||||
disabled={statusUpdate == 'loading'}
|
||||
color="secondary"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row w-full items-center justify-between mt-[20px] gap-[20px]">
|
||||
<div className="font-bold text-[24px]">
|
||||
Исключить пользователя?
|
||||
</div>
|
||||
<ReverseButton
|
||||
onClick={() => {
|
||||
setModalConfirmDeleteUser(true);
|
||||
}}
|
||||
text={
|
||||
statusLeave == 'loading'
|
||||
? 'Исключить...'
|
||||
: 'Исключить'
|
||||
}
|
||||
disabled={statusLeave == 'loading'}
|
||||
color="error"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row w-full items-center justify-end mt-[20px] gap-[20px]">
|
||||
<SecondaryButton
|
||||
onClick={() => {
|
||||
setActive(false);
|
||||
}}
|
||||
text="Отмена"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
className=" fixed top-0 left-0"
|
||||
active={modalConfirmDeleteUser}
|
||||
setActive={setModalConfirmDeleteUser}
|
||||
title="Подтвердите действия"
|
||||
message={`Вы действительно хотите исключить пользователя ${user?.username}?`}
|
||||
confirmColor="error"
|
||||
confirmText="Исключить"
|
||||
onConfirmClick={() => {
|
||||
if (user) {
|
||||
dispatch(
|
||||
removeGroupMember({
|
||||
groupId,
|
||||
memberId: user.userId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
className=" fixed top-0 left-0"
|
||||
active={modalConfirmRoleActive}
|
||||
setActive={setModalConfirmRoleActive}
|
||||
title="Подтвердите действия"
|
||||
message={`Вы действительно хотите назначить пользователя ${user?.username} в качестве ${userRole}?`}
|
||||
confirmText="Назначить"
|
||||
onConfirmClick={() => {
|
||||
if (user) {
|
||||
dispatch(
|
||||
addGroupMember({
|
||||
groupId,
|
||||
userId: user.userId,
|
||||
role:
|
||||
userRole == 'Creator'
|
||||
? 'Administrator, Creator'
|
||||
: userRole,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModalUpdate;
|
||||
@@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
|
||||
import Editor from '@monaco-editor/react';
|
||||
import { upload } from '../../../assets/icons/input';
|
||||
import { cn } from '../../../lib/cn';
|
||||
import { DropDownList } from '../../../components/drop-down-list/DropDownList';
|
||||
import { DropDownList } from '../../../components/input/DropDownList';
|
||||
|
||||
const languageMap: Record<string, string> = {
|
||||
c: 'cpp',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
chevroneLeft,
|
||||
chevroneRight,
|
||||
@@ -6,6 +6,9 @@ import {
|
||||
} from '../../../assets/icons/header';
|
||||
import { Logo } from '../../../assets/logos';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
|
||||
import { useQuery } from '../../../hooks/useQuery';
|
||||
import { fetchMyAttemptsInContest } from '../../../redux/slices/contests';
|
||||
|
||||
interface HeaderProps {
|
||||
missionId: number;
|
||||
@@ -14,6 +17,57 @@ interface HeaderProps {
|
||||
|
||||
const Header: React.FC<HeaderProps> = ({ missionId, back }) => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const query = useQuery();
|
||||
const contestId = Number(query.get('contestId') ?? undefined);
|
||||
|
||||
const attempt = useAppSelector(
|
||||
(state) => state.contests.fetchMyAttemptsInContest.attempts[0],
|
||||
);
|
||||
|
||||
const [time, setTime] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!contestId) return;
|
||||
const calc = (time: string) => {
|
||||
return time != '' && new Date() <= new Date(time);
|
||||
};
|
||||
if (attempt) {
|
||||
if (!calc(attempt.expiresAt)) {
|
||||
navigate('/home/contests');
|
||||
}
|
||||
const diffMs =
|
||||
new Date(attempt.expiresAt).getTime() - new Date().getTime();
|
||||
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
|
||||
setTime(seconds);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setTime((t) => {
|
||||
if (t <= 1) {
|
||||
clearInterval(interval);
|
||||
navigate('/home/contests');
|
||||
return 0;
|
||||
}
|
||||
return t - 1;
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [attempt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (contestId) {
|
||||
dispatch(fetchMyAttemptsInContest(contestId));
|
||||
}
|
||||
}, [contestId]);
|
||||
|
||||
const minutes = String(Math.floor(time / 60)).padStart(2, '0');
|
||||
const seconds = String(time % 60).padStart(2, '0');
|
||||
|
||||
return (
|
||||
<header className="w-full h-[60px] flex items-center px-4 gap-[20px]">
|
||||
<img
|
||||
@@ -59,6 +113,9 @@ const Header: React.FC<HeaderProps> = ({ missionId, back }) => {
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{!!contestId && !!attempt && (
|
||||
<div className="">{`${minutes}:${seconds}`}</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -19,9 +19,16 @@ interface MissionSubmissionsProps {
|
||||
contestId?: number;
|
||||
}
|
||||
|
||||
const MissionSubmissions: FC<MissionSubmissionsProps> = ({ missionId, contestId }) => {
|
||||
const MissionSubmissions: FC<MissionSubmissionsProps> = ({
|
||||
missionId,
|
||||
contestId,
|
||||
}) => {
|
||||
const submissions = useAppSelector(
|
||||
(state) => state.submin.submitsById[missionId] || []
|
||||
(state) => state.submin.submitsById[missionId] || [],
|
||||
);
|
||||
|
||||
const attempt = useAppSelector(
|
||||
(state) => state.contests.fetchMyAttemptsInContest.attempts[0],
|
||||
);
|
||||
|
||||
const checkStatus = (status: string) => {
|
||||
@@ -32,7 +39,9 @@ const MissionSubmissions: FC<MissionSubmissionsProps> = ({ missionId, contestId
|
||||
|
||||
// Если contestId передан, фильтруем по нему, иначе показываем все
|
||||
const filteredSubmissions = contestId
|
||||
? submissions.filter((v) => v.contestId === contestId)
|
||||
? attempt?.submissions?.filter(
|
||||
(v) => v.solution.missionId == missionId,
|
||||
) ?? []
|
||||
: submissions;
|
||||
|
||||
return (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user