Merge branch 'master' of gitlab.prodcontest.ru:team-15/project

This commit is contained in:
moolcoov
2025-03-02 17:53:28 +03:00
75 changed files with 1596 additions and 965 deletions
@@ -2,38 +2,56 @@ import { useParams, Link, useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { ArrowLeft } from "lucide-react";
import ReactMarkdown from "react-markdown";
import { mockTasks } from "@/shared/mocks/mocks";
import { useQuery } from "@tanstack/react-query";
import { getCompetition } from "@/shared/api/competitions";
import { useQuery, useMutation } from "@tanstack/react-query";
import { getCompetition, startCompetition } from "@/shared/api/competitions";
import { getCompetitionTasks } from "@/shared/api/session";
import { Loading } from "@/components/ui/loading";
const CompetitionPage = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const competitionId = id || "";
const { data: competition, isLoading } = useQuery({
queryKey: ["competition", id],
queryFn: async () => getCompetition(id || ""),
const competitionQuery = useQuery({
queryKey: ["competition", competitionId],
queryFn: () => getCompetition(competitionId),
enabled: !!competitionId,
});
if (isLoading) {
const startMutation = useMutation({
mutationFn: () => startCompetition(competitionId),
onSuccess: async () => {
try {
const tasks = await getCompetitionTasks(competitionId);
if (tasks && tasks.length > 0) {
navigate(`/competition/${competitionId}/tasks/${tasks[0].id}`);
} else {
navigate(`/competition/${competitionId}/tasks`);
}
} catch (error) {
console.error("Failed to fetch tasks:", error);
navigate(`/competition/${competitionId}/tasks`);
}
},
onError: (error) => {
console.error("Failed to start competition:", error);
}
});
const handleStart = () => {
startMutation.mutate();
};
if (competitionQuery.isLoading) {
return <Loading />;
}
if (!id || !competition) {
if (!competitionId || !competitionQuery.data) {
return <></>;
}
const handleContinue = () => {
if (competition?.id) {
if (mockTasks && mockTasks.length > 0) {
const firstTaskId = mockTasks[0].id;
navigate(`/competition/${competition.id}/tasks/${firstTaskId}`);
} else {
navigate(`/competition/${competition.id}/tasks`);
}
}
};
const competition = competitionQuery.data;
return (
<div className="flex flex-col gap-4">
@@ -46,15 +64,13 @@ const CompetitionPage = () => {
</Link>
<div className="flex flex-col gap-6">
{competition.image_url && (
<div className="aspect-2 h-auto w-full overflow-hidden rounded-xl">
<img
src={competition.image_url}
alt={competition.title}
className="h-full w-full object-cover object-center"
/>
</div>
)}
<div className="aspect-2 h-auto w-full overflow-hidden rounded-xl">
<img
src={competition.image_url ? competition.image_url : '/DANO.png'}
alt={competition.title}
className="h-full w-full object-cover object-center"
/>
</div>
<div className="flex flex-col-reverse gap-8 md:flex-row">
<div className="flex flex-1 flex-col gap-5">
@@ -66,8 +82,12 @@ const CompetitionPage = () => {
</div>
</div>
<div className="w-full *:w-full md:w-96">
<Button size={"lg"} onClick={handleContinue}>
Продолжить
<Button
size={"lg"}
onClick={handleStart}
disabled={startMutation.isPending}
>
{startMutation.isPending ? "Загрузка..." : "Приступить к выполнению"}
</Button>
</div>
</div>
@@ -76,4 +96,4 @@ const CompetitionPage = () => {
);
};
export default CompetitionPage;
export default CompetitionPage;
@@ -1,63 +0,0 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Task } from "@/shared/types";
import { Settings, Plus } from 'lucide-react';
import { Button } from "@/components/ui/button";
interface ConstructorHeaderProps {
title: string;
tasks: Task[];
competitionId: string;
onAddTaskClick: () => void;
}
const ConstructorHeader: React.FC<ConstructorHeaderProps> = ({
title,
tasks,
competitionId,
onAddTaskClick
}) => {
return (
<header className="bg-white shadow-sm sticky top-0 z-30 w-full">
<div className="mx-auto max-w-6xl px-4">
<div className="py-4 text-center">
<h1 className="font-hse-sans text-xl font-semibold">
{title}
</h1>
</div>
<div className="flex items-center justify-center gap-4 pb-4 overflow-x-auto no-scrollbar">
<Link
to={`/constructor/${competitionId}/tasks/settings`}
className="bg-gray-100 text-gray-700 rounded-lg px-3 py-1.5 font-medium text-sm font-hse-sans cursor-pointer
transition-all hover:bg-gray-200 flex-shrink-0 flex items-center"
>
<Settings size={16} className="mr-1" />
</Link>
{tasks.map((task) => (
<Link
key={task.id}
to={`/constructor/${competitionId}/tasks/${task.id}`}
className="bg-blue-100 text-blue-700 rounded-lg px-3 py-1.5 font-medium text-sm font-hse-sans cursor-pointer
transition-all hover:bg-blue-200 flex-shrink-0"
>
{task.number}
</Link>
))}
<Button
variant="ghost"
size="sm"
className="rounded-lg flex items-center px-2 h-8"
onClick={onAddTaskClick}
>
<Plus size={18} />
</Button>
</div>
</div>
</header>
);
};
export default ConstructorHeader;
@@ -1,89 +0,0 @@
import { useState } from "react";
import { useParams, Navigate, useNavigate } from "react-router-dom";
import { Task, TaskStatus } from "@/shared/types";
import ConstructorHeader from "./components/ConstructorHeader";
import TaskCreationModal from "./modules/TaskCreationModal";
const CompetitionConstructor = () => {
const { id, taskId } = useParams<{ id: string; taskId?: string }>();
const navigate = useNavigate();
const [competitionTitle, setCompetitionTitle] = useState("Новая олимпиада");
const [tasks, setTasks] = useState<Task[]>([]);
const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
const isSettings = taskId === "settings";
const handleOpenTaskModal = () => {
setIsTaskModalOpen(true);
};
const handleCloseTaskModal = () => {
setIsTaskModalOpen(false);
};
const handleCreateTask = (taskData: Partial<Task>) => {
const newTask: Task = {
id: `task-${Date.now()}`,
number: taskData.number || `${tasks.length + 1}`,
status: TaskStatus.Uncleared,
solutionType: taskData.solutionType || "input",
description: taskData.description || "",
requirements: taskData.requirements,
attachments: taskData.attachments || []
};
setTasks([...tasks, newTask]);
setIsTaskModalOpen(false);
navigate(`/constructor/${id}/tasks/${newTask.id}`);
};
if (!taskId) {
if (tasks.length > 0) {
return <Navigate to={`/constructor/${id}/tasks/${tasks[0].id}`} replace />;
} else {
return <Navigate to={`/constructor/${id}/tasks/settings`} replace />;
}
}
return (
<div className="flex flex-col min-h-screen">
<ConstructorHeader
title={competitionTitle}
tasks={tasks}
competitionId={id || ""}
onAddTaskClick={handleOpenTaskModal}
/>
<TaskCreationModal
isOpen={isTaskModalOpen}
onClose={handleCloseTaskModal}
onCreateTask={handleCreateTask}
taskCount={tasks.length}
/>
<main className="flex-1 bg-[#F8F8F8] pb-8">
<div className="max-w-6xl mx-auto px-4 py-6">
{isSettings ? (
<div className="bg-white rounded-lg p-6 shadow-sm">
<h2 className="text-2xl font-semibold mb-6 font-hse-sans">Настройки олимпиады</h2>
<p className="text-gray-500 font-hse-sans">
Здесь будет форма настроек олимпиады
</p>
</div>
) : (
<div className="bg-white rounded-lg p-6 shadow-sm">
<h2 className="text-2xl font-semibold mb-6 font-hse-sans">
{`Редактирование задачи ${tasks.find(t => t.id === taskId)?.number || ""}`}
</h2>
<p className="text-gray-500 font-hse-sans">
Здесь будет форма редактирования задачи
</p>
</div>
)}
</div>
</main>
</div>
);
};
export default CompetitionConstructor;
@@ -1,27 +0,0 @@
import React from 'react';
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
interface TaskDescriptionFieldProps {
description: string;
onChange: (value: string) => void;
}
const TaskDescriptionField: React.FC<TaskDescriptionFieldProps> = ({ description, onChange }) => {
return (
<div className="grid grid-cols-4 items-start gap-4">
<Label htmlFor="description" className="text-right pt-2">
Описание
</Label>
<Textarea
id="description"
value={description}
onChange={(e) => onChange(e.target.value)}
className="col-span-3 min-h-[100px]"
placeholder="Введите описание задачи"
/>
</div>
);
};
export default TaskDescriptionField;
@@ -1,92 +0,0 @@
import React from 'react';
import { FileIcon, X, Upload } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
interface TaskFileAttachmentsProps {
files: File[];
onChange: (files: File[]) => void;
}
const TaskFileAttachments: React.FC<TaskFileAttachmentsProps> = ({ files, onChange }) => {
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
const newFiles = Array.from(e.target.files);
onChange([...files, ...newFiles]);
}
};
const removeFile = (index: number) => {
onChange(files.filter((_, i) => i !== index));
};
return (
<div className="grid grid-cols-4 items-start gap-4">
<Label className="text-right pt-2">
Файлы
</Label>
<div className="col-span-3">
<div className="flex flex-col gap-2">
{files.map((file, index) => (
<FileListItem
key={index}
file={file}
onRemove={() => removeFile(index)}
/>
))}
<FileUploadButton onChange={handleFileChange} />
</div>
</div>
</div>
);
};
interface FileListItemProps {
file: File;
onRemove: () => void;
}
const FileListItem: React.FC<FileListItemProps> = ({ file, onRemove }) => {
return (
<div className="flex items-center justify-between p-2 border rounded-md">
<div className="flex items-center">
<FileIcon size={16} className="mr-2 text-gray-500" />
<span className="text-sm">{file.name}</span>
<span className="text-xs text-gray-500 ml-2">
({Math.round(file.size / 1024)} KB)
</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={onRemove}
>
<X size={16} />
</Button>
</div>
);
};
interface FileUploadButtonProps {
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
const FileUploadButton: React.FC<FileUploadButtonProps> = ({ onChange }) => {
return (
<label className="cursor-pointer">
<div className="flex items-center gap-2 p-2 border border-dashed rounded-md hover:bg-gray-50 transition-colors">
<Upload size={16} className="text-gray-500" />
<span className="text-sm text-gray-700">Добавить файлы</span>
</div>
<input
type="file"
className="hidden"
onChange={onChange}
multiple
/>
</label>
);
};
export default TaskFileAttachments;
@@ -1,26 +0,0 @@
import React from 'react';
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface TaskNumberFieldProps {
number: string;
onChange: (value: string) => void;
}
const TaskNumberField: React.FC<TaskNumberFieldProps> = ({ number, onChange }) => {
return (
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="task-number" className="text-right">
Номер задачи
</Label>
<Input
id="task-number"
value={number}
onChange={(e) => onChange(e.target.value)}
className="col-span-3"
/>
</div>
);
};
export default TaskNumberField;
@@ -1,27 +0,0 @@
import React from 'react';
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
interface TaskRequirementsFieldProps {
requirements: string;
onChange: (value: string) => void;
}
const TaskRequirementsField: React.FC<TaskRequirementsFieldProps> = ({ requirements, onChange }) => {
return (
<div className="grid grid-cols-4 items-start gap-4">
<Label htmlFor="requirements" className="text-right pt-2">
Требования
</Label>
<Textarea
id="requirements"
value={requirements}
onChange={(e) => onChange(e.target.value)}
className="col-span-3"
placeholder="Введите требования к решению (необязательно)"
/>
</div>
);
};
export default TaskRequirementsField;
@@ -1,41 +0,0 @@
import React from 'react';
import {
RadioGroup,
RadioGroupItem
} from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
interface TaskSolutionTypeSelectorProps {
solutionType: 'input' | 'file' | 'code';
onChange: (value: 'input' | 'file' | 'code') => void;
}
const TaskSolutionTypeSelector: React.FC<TaskSolutionTypeSelectorProps> = ({ solutionType, onChange }) => {
return (
<div className="grid grid-cols-4 items-start gap-4">
<Label className="text-right pt-2">
Тип решения
</Label>
<RadioGroup
className="col-span-3"
value={solutionType}
onValueChange={(value) => onChange(value as 'input' | 'file' | 'code')}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="input" id="input" />
<Label htmlFor="input">Ввод ответа</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="file" id="file" />
<Label htmlFor="file">Загрузка файла</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="code" id="code" />
<Label htmlFor="code">Программный код</Label>
</div>
</RadioGroup>
</div>
);
};
export default TaskSolutionTypeSelector;
@@ -1,101 +0,0 @@
import React, { useState } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Task } from "@/shared/types";
import TaskNumberField from './components/TaskNumberField';
import TaskDescriptionField from './components/TaskDescriptionField';
import TaskRequirementsField from './components/TaskRequirementsField';
import TaskSolutionTypeSelector from './components/TaskSolutionTypeSelector';
import TaskFileAttachments from './components/TaskFileAttachments';
interface TaskCreationModalProps {
isOpen: boolean;
onClose: () => void;
onCreateTask: (task: Partial<Task>) => void;
taskCount: number;
}
const TaskCreationModal: React.FC<TaskCreationModalProps> = ({
isOpen,
onClose,
onCreateTask,
taskCount
}) => {
const [number, setNumber] = useState(`${taskCount + 1}`);
const [description, setDescription] = useState('');
const [requirements, setRequirements] = useState('');
const [solutionType, setSolutionType] = useState<'input' | 'file' | 'code'>('input');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const handleSubmit = () => {
const newTask: Partial<Task> = {
number,
description,
requirements: requirements || undefined,
solutionType,
attachments: attachedFiles.map(file => file.name)
};
onCreateTask(newTask);
setNumber(`${taskCount + 1}`);
setDescription('');
setRequirements('');
setSolutionType('input');
setAttachedFiles([]);
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[600px] font-hse-sans">
<DialogHeader>
<DialogTitle className="text-xl">Создание новой задачи</DialogTitle>
</DialogHeader>
<div className="grid gap-4 py-4">
<TaskNumberField
number={number}
onChange={setNumber}
/>
<TaskDescriptionField
description={description}
onChange={setDescription}
/>
<TaskRequirementsField
requirements={requirements}
onChange={setRequirements}
/>
<TaskSolutionTypeSelector
solutionType={solutionType}
onChange={setSolutionType}
/>
<TaskFileAttachments
files={attachedFiles}
onChange={setAttachedFiles}
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Отмена
</Button>
<Button type="button" onClick={handleSubmit}>
Создать задачу
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export default TaskCreationModal;
@@ -1,7 +1,6 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Task } from "@/shared/types";
import { getTaskBgColor, getTaskTextColor } from '../../utils/utils';
import { Task } from '@/shared/types/task';
interface CompetitionHeaderProps {
title: string;
@@ -28,12 +27,12 @@ const CompetitionHeader: React.FC<CompetitionHeaderProps> = ({
<Link
key={task.id}
to={`/competition/${competitionId}/tasks/${task.id}`}
className={`${getTaskBgColor(task.status)} ${getTaskTextColor(task.status)}
className={`text-[var(--color-task-text-uncleared)] bg-[var(--color-task-uncleared)]
rounded-lg px-3 py-1.5 font-medium text-sm font-hse-sans cursor-pointer
transition-all hover:brightness-95 flex-shrink-0
`}
>
{task.number}
{task.in_competition_position}
</Link>
))}
</div>
@@ -3,53 +3,78 @@ import ReactMarkdown from 'react-markdown';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import 'katex/dist/katex.min.css';
import { Task } from "@/shared/types";
import { Task } from '@/shared/types/task';
import { useQuery } from '@tanstack/react-query';
import { getTaskAttachments } from '@/shared/api/session';
import { FileIcon, Loader2 } from 'lucide-react';
import { useParams } from 'react-router-dom';
interface TaskContentProps {
task: Task;
}
const TaskContent: React.FC<TaskContentProps> = ({ task }) => {
const markdownContent = `
## Задача на числовую последовательность
const { id: competitionId } = useParams<{ id: string }>();
Рассмотрим последовательность чисел:
\`2, 3, 5, 9, 17, 33, 65, 129, ...\`
const attachmentsQuery = useQuery({
queryKey: ['taskAttachments', competitionId, task.id],
queryFn: () => getTaskAttachments(competitionId || '', task.id),
enabled: !!(competitionId && task.id),
});
Каждый член этой последовательности, **начиная с третьего**, равен сумме двух предыдущих членов:
- $a_1 = 2$
- $a_2 = 3$
- $a_n = a_{n-1} + a_{n-2}$ для всех $n ≥ 3$
### Задание:
Найдите сумму первых 15 членов этой последовательности.
*Примечание:* Для решения задачи вам может быть полезно записать несколько первых членов последовательности:
1. $a_1 = 2$
2. $a_2 = 3$
3. $a_3 = 3 + 2 = 5$
4. $a_4 = 5 + 3 = 8$
5. $a_5 = 8 + 5 = 13$
**В ответе укажите целое число.**
`;
const attachments = attachmentsQuery.data || [];
return (
<div className="flex-1 bg-white rounded-lg p-6">
<h2 className="text-3xl font-semibold mb-6 font-hse-sans">
Задача {task.number}
Задача {task.in_competition_position}
</h2>
<div className="prose prose-lg max-w-none text-gray-700 font-hse-sans">
<div className="prose prose-lg max-w-none text-gray-700 font-hse-sans mb-6">
<ReactMarkdown
remarkPlugins={[remarkMath]}
rehypePlugins={[rehypeKatex]}
>
{markdownContent}
{task.description}
</ReactMarkdown>
</div>
{attachmentsQuery.isLoading ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-gray-400 mr-2" />
<span className="text-gray-500 font-hse-sans">Загрузка файлов...</span>
</div>
) : attachments.length > 0 ? (
<div className="mt-6">
<h3 className="text-lg font-semibold mb-3 font-hse-sans">Прикрепленные файлы</h3>
<div className="flex flex-col gap-2">
{attachments.map((attachment) => (
<a
key={attachment.id}
href={attachment.file}
download
className="flex items-center p-3 border rounded-md hover:bg-gray-50 transition-colors"
>
<FileIcon size={18} className="text-blue-500 mr-2" />
<span className="font-hse-sans">
{getFileNameFromUrl(attachment.file)}
</span>
</a>
))}
</div>
</div>
) : null}
</div>
);
};
export default TaskContent;
const getFileNameFromUrl = (url: string): string => {
try {
const parts = url.split('/');
return parts[parts.length - 1];
} catch (e) {
return 'Файл';
}
};
export default TaskContent;
@@ -1,45 +1,41 @@
import { useState, useEffect } from "react";
import { useState } from "react";
import { useParams, Navigate } from "react-router-dom";
import { Task, TaskStatus } from "@/shared/types";
import { mockSolutions } from "@/shared/mocks/mocks"; // Keep mocks for solutions for now
import CompetitionHeader from "./components/CompetitionHeader";
import TaskContent from "./components/TaskContent";
import TaskSolution from "./modules/TaskSolution";
import { getCompetitionTasks } from "@/shared/api/session";
import { getCompetitionTasks, submitTaskSolution } from "@/shared/api/session";
import { Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
const CompetitionSession = () => {
const { id, taskId } = useParams<{ id: string; taskId?: string }>();
const [tasks, setTasks] = useState<Task[]>([]);
const [answer, setAnswer] = useState("");
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const competitionId = id || "";
const queryClient = useQueryClient();
useEffect(() => {
const fetchTasks = async () => {
try {
setLoading(true);
const fetchedTasks = await getCompetitionTasks(competitionId);
setTasks(fetchedTasks);
setError(null);
} catch (err) {
console.error("Failed to fetch tasks:", err);
setError("Не удалось загрузить задания. Пожалуйста, попробуйте позже.");
} finally {
setLoading(false);
}
};
const tasksQuery = useQuery({
queryKey: ["competitionTasks", competitionId],
queryFn: () => getCompetitionTasks(competitionId),
enabled: !!competitionId,
});
if (competitionId) {
fetchTasks();
const submitMutation = useMutation({
mutationFn: () => submitTaskSolution(competitionId, taskId || "", answer),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['submissionHistory', competitionId, taskId]
});
setAnswer("");
}
}, [competitionId]);
});
const tasks = tasksQuery.data || [];
const isLoading = tasksQuery.isLoading;
const error = tasksQuery.error ? "Не удалось загрузить задания. Пожалуйста, попробуйте позже." : null;
const currentTask = tasks.find((t) => t.id === taskId) || null;
if (!taskId && tasks.length > 0 && !loading) {
if (!taskId && tasks.length > 0 && !isLoading) {
return (
<Navigate
to={`/competition/${competitionId}/tasks/${tasks[0].id}`}
@@ -48,14 +44,10 @@ const CompetitionSession = () => {
);
}
const handleSubmit = async () => {
if (!currentTask || !competitionId) return;
try {
console.log("Solution submitted successfully");
} catch (err) {
console.error("Failed to submit solution:", err);
}
const handleSubmit = () => {
console.log(currentTask, competitionId, answer)
if (!currentTask || !competitionId || !answer.trim()) return;
submitMutation.mutate();
};
return (
@@ -68,7 +60,7 @@ const CompetitionSession = () => {
<main className="flex-1 bg-[#F8F8F8] pb-8">
<div className="mx-auto max-w-6xl px-4 py-6">
{loading ? (
{isLoading ? (
<div className="flex h-40 flex-col items-center justify-center rounded-lg bg-white">
<Loader2 className="mb-2 h-8 w-8 animate-spin text-gray-400" />
<p className="font-hse-sans text-gray-500">Загрузка заданий...</p>
@@ -82,7 +74,7 @@ const CompetitionSession = () => {
<TaskContent task={currentTask} />
<TaskSolution
task={currentTask}
solutions={mockSolutions} // Still using mock solutions
solutions={[]}
answer={answer}
setAnswer={setAnswer}
onSubmit={handleSubmit}
@@ -99,4 +91,4 @@ const CompetitionSession = () => {
);
};
export default CompetitionSession;
export default CompetitionSession;
@@ -1,48 +1,31 @@
import React, { useState } from 'react';
import React from 'react';
import { Button } from "@/components/ui/button";
import SolutionHistorySheet from '../SolutionHistorySheet';
import { Solution } from "@/shared/types";
import { mockSolutions } from '@/shared/mocks/mocks';
interface ActionButtonsProps {
onSubmit: () => void;
solutionHistory?: Solution[];
onHistoryClick: () => void;
}
const ActionButtons: React.FC<ActionButtonsProps> = ({
onSubmit,
solutionHistory = mockSolutions
onHistoryClick
}) => {
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
const handleHistoryClick = () => {
setIsHistoryOpen(true);
};
return (
<>
<div className="flex gap-8">
<Button
variant="ghost"
className="font-hse-sans bg-white hover:bg-gray-100"
onClick={handleHistoryClick}
>
История
</Button>
<Button
onClick={onSubmit}
className="font-hse-sans flex-grow"
>
Отправить решение
</Button>
</div>
{/* чуть-чуть рак */}
<SolutionHistorySheet
isOpen={isHistoryOpen}
onOpenChange={setIsHistoryOpen}
solutions={solutionHistory}
/>
</>
<div className="flex gap-8">
<Button
variant="ghost"
className="font-hse-sans bg-white hover:bg-gray-100"
onClick={onHistoryClick}
>
История
</Button>
<Button
onClick={onSubmit}
className="font-hse-sans flex-grow"
>
Отправить решение
</Button>
</div>
);
};
@@ -3,18 +3,20 @@ import { Sheet, SheetClose, SheetContent, SheetHeader, SheetTitle } from "@/comp
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import SolutionStatus from '../SolutionStatus';
import { Solution } from "@/shared/types";
import { Solution } from '@/shared/types/task';
interface SolutionHistorySheetProps {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
solutions: Solution[];
maxPoints: number
}
const SolutionHistorySheet: React.FC<SolutionHistorySheetProps> = ({
isOpen,
onOpenChange,
solutions
solutions,
maxPoints
}) => {
return (
<Sheet open={isOpen} onOpenChange={onOpenChange}>
@@ -34,7 +36,7 @@ const SolutionHistorySheet: React.FC<SolutionHistorySheetProps> = ({
{solutions.length > 0 ? (
solutions.map((solution, index) => (
<div key={index} className="w-full">
<SolutionStatus solution={solution} />
<SolutionStatus solution={solution} maxPoints={maxPoints} />
</div>
))
) : (
@@ -1,41 +1,26 @@
import React from 'react';
import { Solution, TaskStatus } from "@/shared/types";
import { getTaskBgColor, getTaskTextColor } from '@/pages/CompetitionSession/utils/utils';
import { Solution } from '@/shared/types/task';
import { getSolutionBgColor, getSolutionTextColor, getStatusText } from '@/pages/CompetitionSession/utils/utils';
interface SolutionStatusProps {
solution: Solution;
maxPoints: number;
}
const SolutionStatus: React.FC<SolutionStatusProps> = ({ solution }) => {
const getStatusText = (status: TaskStatus, score?: number, maxScore?: number) => {
switch (status) {
case TaskStatus.Checking:
return 'На проверке';
case TaskStatus.Wrong:
return 'Неверный ответ';
case TaskStatus.Correct:
return `Зачтено ${maxScore}/${maxScore} баллов`;
case TaskStatus.Partial:
return `Зачтено ${score}/${maxScore} баллов`;
case TaskStatus.Uncleared:
return 'Не решено';
default:
return '';
}
};
const SolutionStatus: React.FC<SolutionStatusProps> = ({ solution, maxPoints }) => {
return (
<div className={`${getTaskBgColor(solution.status)} rounded-lg p-4 relative`}>
<div className={`${getSolutionBgColor(solution.status, solution.earned_points, maxPoints)} rounded-lg p-4 relative`}>
<div className="flex flex-col">
<span className={`${getTaskTextColor(solution.status)} font-medium`}>
<span className={`${getSolutionTextColor(solution.status, solution.earned_points, maxPoints)} font-medium`}>
Решение {solution.id}
</span>
<span className={`${getTaskTextColor(solution.status)} mt-1`}>
{getStatusText(solution.status, solution.score, solution.maxScore)}
<span className={`${getSolutionTextColor(solution.status, solution.earned_points, maxPoints)} mt-1`}>
{getStatusText(solution.status, solution.earned_points, maxPoints)}
</span>
</div>
<div className={`absolute bottom-2 right-3 text-xs ${getTaskTextColor(solution.status)}`}>
{solution.date}
<div className={`absolute bottom-2 right-3 text-xs ${getSolutionTextColor(solution.status, solution.earned_points, maxPoints)}`}>
{solution.timestamp}
</div>
</div>
);
@@ -1,10 +1,14 @@
import React, { useState, useRef } from 'react';
import { Solution, Task } from "@/shared/types";
import { useParams } from 'react-router-dom';
import { Task, TaskType, Solution } from '@/shared/types/task';
import { useQuery } from '@tanstack/react-query';
import { getTaskSolutionHistory } from '@/shared/api/session';
import SolutionStatus from './components/SolutionStatus';
import InputSolution from './components/InputSolution';
import FileSolution from './components/FileSolution';
import CodeSolution from './components/CodeSolution';
import ActionButtons from './components/ActionButtons';
import SolutionHistorySheet from './components/SolutionHistorySheet';
interface TaskSolutionProps {
task: Task;
@@ -12,28 +16,49 @@ interface TaskSolutionProps {
answer: string;
setAnswer: (value: string) => void;
onSubmit: () => void;
}
const TaskSolution: React.FC<TaskSolutionProps> = ({
task,
solutions,
solutions = [],
answer,
setAnswer,
onSubmit,
}) => {
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
const { id: competitionId } = useParams<{ id: string }>();
const solutionsQuery = useQuery({
queryKey: ['solutionHistory', competitionId, task.id],
queryFn: () => getTaskSolutionHistory(competitionId || '', task.id),
enabled: !!(competitionId && task.id),
});
const solutionHistory = solutionsQuery.data || [];
const handleOpenHistory = () => {
setIsHistoryOpen(true);
};
const latestSolution = solutions && solutions.length > 0 ? solutions[0] : null;
return (
<div className="md:w-[500px] flex flex-col gap-4">
<SolutionStatus solution={solutions[0]} />
{latestSolution ? (
<SolutionStatus solution={latestSolution} maxPoints={task.points}/>
) : (
<div className="bg-gray-100 rounded-lg p-4 text-gray-600 font-hse-sans">
Решение еще не отправлено
</div>
)}
{task.solutionType === 'input' && (
{task.type === TaskType.INPUT && (
<InputSolution answer={answer} setAnswer={setAnswer} />
)}
{task.solutionType === 'file' && (
{task.type === TaskType.FILE && (
<FileSolution
selectedFile={selectedFile}
setSelectedFile={setSelectedFile}
@@ -41,11 +66,21 @@ const TaskSolution: React.FC<TaskSolutionProps> = ({
/>
)}
{task.solutionType === 'code' && (
{task.type === TaskType.CODE && (
<CodeSolution answer={answer} setAnswer={setAnswer} />
)}
<ActionButtons onSubmit={onSubmit} />
<ActionButtons
onSubmit={onSubmit}
onHistoryClick={handleOpenHistory}
/>
<SolutionHistorySheet
isOpen={isHistoryOpen}
onOpenChange={setIsHistoryOpen}
solutions={solutionHistory}
maxPoints={task.points}
/>
</div>
);
};
@@ -1,4 +1,5 @@
import { TaskStatus } from "@/shared/types";
import { SolutionStatus } from "@/shared/types/task";
const getTaskBgColor = (status: TaskStatus): string => {
switch (status) {
case TaskStatus.Uncleared: return "bg-[var(--color-task-uncleared)]";
@@ -19,4 +20,39 @@ const getTaskTextColor = (status: TaskStatus): string => {
}
};
export {getTaskBgColor, getTaskTextColor}
const getSolutionBgColor = (status: SolutionStatus, earned_points: number, maxPoints: number): string => {
switch (status) {
case SolutionStatus.SENT: return "text-[var(--color-task-uncleared)]";
case SolutionStatus.CHECKING: return "text-[var(--color-task-checking)]";
case SolutionStatus.CHECKED: {
if (earned_points === 0) return "text-[var(--color-task-wrong)]";
else if (earned_points === maxPoints) "text-[var(--color-task-correct)]";
return "text-[var(--color-task-partial)]";
}
}
}
const getSolutionTextColor = (status: SolutionStatus, earned_points: number, maxPoints: number): string => {
switch (status) {
case SolutionStatus.SENT: return "text-[var(--color-task-text-uncleared)]";
case SolutionStatus.CHECKING: return "text-[var(--color-task-text-checking)]";
case SolutionStatus.CHECKED: {
if (earned_points === 0) return "text-[var(--color-task-text-wrong)]";
else if (earned_points === maxPoints) "text-[var(--color-task-text-correct)]";
return "text-[var(--color-task-text-partial)]";
}
}
}
const getStatusText = (status: SolutionStatus, earned_points: number, maxPoints: number): string => {
switch (status) {
case SolutionStatus.SENT: return "Решение отправлено";
case SolutionStatus.CHECKING: return "Решение проверяется";
case SolutionStatus.CHECKED: {
if (earned_points === 0) return "Неверный ответ";
else if (earned_points === maxPoints) `Зачтено ${maxPoints}/${maxPoints} баллов`;
return `Зачтено ${earned_points}/${maxPoints} баллов`;
}
}
}
export {getTaskBgColor, getTaskTextColor, getSolutionBgColor, getSolutionTextColor, getStatusText}
@@ -20,13 +20,11 @@ export function CompetitionCard({
className={cn("aspect-square h-full w-auto overflow-hidden", className)}
>
<div className="relative h-full overflow-hidden">
{competition.image_url && (
<img
src={competition.image_url}
alt={competition.title}
className="h-full w-full object-cover object-center"
/>
)}
<img
src={competition.image_url ? competition.image_url : '/DANO.png'}
alt={competition.title}
className="h-full w-full object-cover object-center"
/>
</div>
<CardContent>
@@ -112,4 +112,5 @@ const SectionTitle = ({ children }: { children: React.ReactNode }) => {
return <h1 className="w-full text-3xl font-semibold">{children}</h1>;
};
export default CompetitionsPage;
export default CompetitionsPage;