feat: drag and drop for files, code redactor in task + competition session decomposed

This commit is contained in:
rngsurrounded
2025-03-01 22:52:51 +09:00
parent c79b3df909
commit 758d0de9ed
17 changed files with 784 additions and 132 deletions
@@ -0,0 +1,45 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Task } from "@/shared/types";
import { getTaskBgColor, getTaskTextColor } from '../../utils/utils';
interface CompetitionHeaderProps {
title: string;
tasks: Task[];
competitionId: string;
}
const CompetitionHeader: React.FC<CompetitionHeaderProps> = ({
title,
tasks,
competitionId
}) => {
return (
<header className="bg-white shadow-sm">
<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">
{tasks.map((task) => (
<Link
key={task.id}
to={`/competition/${competitionId}/tasks/${task.id}`}
className={`${getTaskBgColor(task.status)} ${getTaskTextColor(task.status)}
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}
</Link>
))}
</div>
</div>
</header>
);
};
export default CompetitionHeader;
@@ -0,0 +1,55 @@
import React from 'react';
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";
interface TaskContentProps {
task: Task;
}
const TaskContent: React.FC<TaskContentProps> = ({ task }) => {
const markdownContent = `
## Задача на числовую последовательность
Рассмотрим последовательность чисел:
\`2, 3, 5, 9, 17, 33, 65, 129, ...\`
Каждый член этой последовательности, **начиная с третьего**, равен сумме двух предыдущих членов:
- $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$
**В ответе укажите целое число.**
`;
return (
<div className="flex-1 bg-white rounded-lg p-6">
<h2 className="text-3xl font-semibold mb-6 font-hse-sans">
Задача {task.number}
</h2>
<div className="prose prose-lg max-w-none text-gray-700 font-hse-sans">
<ReactMarkdown
remarkPlugins={[remarkMath]}
rehypePlugins={[rehypeKatex]}
>
{markdownContent}
</ReactMarkdown>
</div>
</div>
);
};
export default TaskContent;
@@ -1,38 +1,24 @@
import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useState } from "react";
import { useParams, Navigate } from "react-router-dom";
import { Task } from "@/shared/types";
import { getTaskBgColor, getTaskTextColor } from "./utils/utils";
import { mockTasks } from "@/shared/mocks/mocks";
import { Button } from "@/components/ui/button";
import CompetitionHeader from "./components/CompetitionHeader";
import TaskContent from "./components/TaskContent";
import TaskSolution from "./modules/TaskSolution";
const CompetitionSessionPage = () => {
const { id, taskId } = useParams<{ id: string; taskId?: string }>();
const navigate = useNavigate();
const [competitionTitle, setCompetitionTitle] = useState("Олимпиада DANO 2025. Индивидуальный этап");
const [tasks] = useState<Task[]>(mockTasks);
const [selectedTaskId, setSelectedTaskId] = useState<string | null>(taskId || null);
const [answer, setAnswer] = useState("");
useEffect(() => {
if (taskId) {
setSelectedTaskId(taskId);
} else if (tasks.length > 0) {
navigate(`/competition/${id}/tasks/${tasks[0].id}`, { replace: true });
}
}, [taskId, tasks, id, navigate]);
const currentTask = tasks.find(t => t.id === taskId) || null;
const handleTaskClick = (taskId: string) => {
if (selectedTaskId !== taskId) {
setSelectedTaskId(taskId);
navigate(`/competition/${id}/tasks/${taskId}`);
}
};
if (!taskId && tasks.length > 0) {
return <Navigate to={`/competition/${id}/tasks/${tasks[0].id}`} replace />;
}
const currentTask = tasks.find(t => t.id === selectedTaskId);
const handleSubmit = () => {
console.log("Submitting answer:", answer);
// Submit logic here
};
const handleHistoryClick = () => {
@@ -40,100 +26,25 @@ const CompetitionSessionPage = () => {
};
return (
<>
<div className="sticky top-0 z-10 bg-white">
<div className="mx-auto max-w-6xl px-4">
<div className="py-3 text-center">
<h1 className="font-hse-sans text-lg font-semibold">
{competitionTitle}
</h1>
</div>
<div className="flex items-center justify-center gap-2 pb-3 overflow-x-auto no-scrollbar">
{tasks.map((task) => (
<div
key={task.id}
className={`${getTaskBgColor(task.status)} ${getTaskTextColor(task.status)}
rounded-lg px-3 py-1.5 font-medium text-sm font-hse-sans cursor-pointer
transition-all hover:brightness-95 flex-shrink-0
${selectedTaskId === task.id ? 'shadow-md transform scale-105' : ''}`}
onClick={() => handleTaskClick(task.id)}
>
{task.number}
</div>
))}
</div>
</div>
</div>
<div className="flex flex-col min-h-screen">
<CompetitionHeader
title="Олимпиада DANO 2025. Индивидуальный этап"
tasks={tasks}
competitionId={id || ""}
/>
<div className="bg-[#F8F8F8] min-h-screen pb-8">
<main className="flex-1 bg-[#F8F8F8] pb-8">
<div className="max-w-6xl mx-auto px-4 py-6">
{currentTask ? (
<div className="flex flex-col md:flex-row gap-6 font-hse-sans">
{/* Left Container - Task Description */}
<div className="flex-1 bg-white rounded-lg p-6">
<h2 className="text-xl font-medium mb-4">
Задача {currentTask.number}
</h2>
<div className="prose max-w-none text-gray-700">
<p>
Рассмотрим последовательность чисел 2, 3, 5, 9, 17, 33, 65, 129, ...
Каждый член этой последовательности, начиная с третьего, равен сумме двух предыдущих членов.
</p>
<p className="mt-4">
Найдите сумму первых 15 членов этой последовательности.
</p>
<p className="mt-4">
В ответе укажите целое число.
</p>
</div>
</div>
{/* Right Container - Solution Area */}
<div className="md:w-[350px] flex flex-col gap-4">
{/* Solution Status Card */}
<div className={`${getTaskBgColor(currentTask.status)} rounded-lg p-4 relative`}>
<div className="flex flex-col">
<span className={`${getTaskTextColor(currentTask.status)} font-medium`}>
Решение 12345
</span>
<span className={`${getTaskTextColor(currentTask.status)} mt-1`}>
Зачтено 5/10 баллов
</span>
</div>
<div className="absolute bottom-2 right-3 text-xs text-gray-600">
1 марта, 08:41
</div>
</div>
{/* Answer Input */}
<div className="bg-white rounded-lg p-4">
<textarea
className="w-full h-32 border border-gray-300 rounded-md p-3 font-hse-sans text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Введите ответ"
value={answer}
onChange={(e) => setAnswer(e.target.value)}
/>
</div>
{/* Action Buttons */}
<div className="flex gap-3 justify-between">
<Button
variant="outline"
className="font-hse-sans"
onClick={handleHistoryClick}
>
История
</Button>
<Button
className="bg-yellow-400 hover:bg-yellow-500 text-black font-hse-sans"
onClick={handleSubmit}
>
Отправить решение
</Button>
</div>
</div>
<TaskContent task={currentTask} />
<TaskSolution
task={currentTask}
answer={answer}
setAnswer={setAnswer}
onSubmit={handleSubmit}
onHistoryClick={handleHistoryClick}
/>
</div>
) : (
<div className="flex justify-center items-center h-40 bg-white rounded-lg">
@@ -143,9 +54,9 @@ const CompetitionSessionPage = () => {
</div>
)}
</div>
</div>
</>
</main>
</div>
);
};
export default CompetitionSessionPage;
export default CompetitionSessionPage;
@@ -0,0 +1,29 @@
import React from 'react';
import { Button } from "@/components/ui/button";
interface ActionButtonsProps {
onHistoryClick: () => void;
onSubmit: () => void;
}
const ActionButtons: React.FC<ActionButtonsProps> = ({ onHistoryClick, onSubmit }) => {
return (
<div className="flex gap-3 justify-between">
<Button
variant="ghost"
className="font-hse-sans bg-white hover:bg-gray-100"
onClick={onHistoryClick}
>
История
</Button>
<Button
onClick={onSubmit}
className="font-hse-sans"
>
Отправить решение
</Button>
</div>
);
};
export default ActionButtons;
@@ -0,0 +1,117 @@
import React, { useRef, useEffect, useState } from 'react';
import * as monaco from 'monaco-editor';
import { Copy, Check } from 'lucide-react'; // Import Lucide React icons
interface CodeSolutionProps {
answer: string;
setAnswer: (value: string) => void;
language?: string;
}
const CodeSolution: React.FC<CodeSolutionProps> = ({
answer,
setAnswer,
language = 'python'
}) => {
const editorContainerRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
const [copied, setCopied] = useState(false);
const languageDisplay = language === 'python' ? 'Python 3.11' : language;
const copyToClipboard = () => {
if (answer) {
navigator.clipboard.writeText(answer)
.then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
})
.catch(err => {
console.error('Failed to copy: ', err);
});
}
};
useEffect(() => {
if (editorContainerRef.current) {
editorRef.current = monaco.editor.create(editorContainerRef.current, {
value: answer,
language,
theme: 'vs-light',
automaticLayout: true,
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 14,
fontFamily: 'hse-sans, Menlo, Monaco, "Courier New", monospace',
lineNumbers: 'on',
lineNumbersMinChars: 3,
glyphMargin: false,
folding: false,
roundedSelection: false,
renderLineHighlight: 'none',
overviewRulerBorder: false,
overviewRulerLanes: 0,
hideCursorInOverviewRuler: true,
scrollbar: {
useShadows: false,
verticalHasArrows: false,
horizontalHasArrows: false,
vertical: 'hidden',
horizontal: 'auto',
verticalScrollbarSize: 0,
horizontalScrollbarSize: 8,
alwaysConsumeMouseWheel: false
},
});
editorRef.current.onDidChangeModelContent(() => {
if (editorRef.current) {
const value = editorRef.current.getValue();
setAnswer(value);
}
});
return () => {
if (editorRef.current) {
editorRef.current.dispose();
}
};
}
}, [language]);
useEffect(() => {
if (editorRef.current) {
const currentValue = editorRef.current.getValue();
if (currentValue !== answer) {
editorRef.current.setValue(answer);
}
}
}, [answer]);
return (
<div className="bg-white rounded-lg overflow-hidden border border-gray-200">
<div className="flex items-center justify-between bg-gray-50 px-4 py-2 border-b border-gray-200">
<div className="text-sm font-medium text-gray-600">{languageDisplay}</div>
<button
onClick={copyToClipboard}
className="flex items-center text-sm text-gray-500 hover:text-gray-700 transition-colors"
>
{copied ? (
<Check className="w-4 h-4 mr-1" />
) : (
<Copy className="w-4 h-4 mr-1" />
)}
</button>
</div>
<div className="p-4">
<div
ref={editorContainerRef}
className="w-full min-h-[300px] rounded bg-gray-50"
/>
</div>
</div>
);
};
export default CodeSolution;
@@ -0,0 +1,93 @@
import React from 'react';
import { FileIcon } from 'lucide-react';
import { Button } from "@/components/ui/button";
interface FileSolutionProps {
selectedFile: File | null;
setSelectedFile: (file: File | null) => void;
fileInputRef: React.RefObject<HTMLInputElement>;
}
const FileSolution: React.FC<FileSolutionProps> = ({
selectedFile,
setSelectedFile,
fileInputRef
}) => {
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files[0]) {
setSelectedFile(event.target.files[0]);
}
};
const handleFileUploadClick = () => {
fileInputRef.current?.click();
};
const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.currentTarget.classList.add('bg-gray-50');
};
const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.currentTarget.classList.remove('bg-gray-50');
};
const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.currentTarget.classList.remove('bg-gray-50');
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
setSelectedFile(e.dataTransfer.files[0]);
}
};
return (
<>
<input
type="file"
ref={fileInputRef}
className="hidden"
onChange={handleFileChange}
accept=".jpg,.jpeg,.png,.pptx,.docx,.pdf,.xlsx,.txt"
/>
{selectedFile ? (
<div className="bg-white rounded-lg p-6 flex flex-col items-center justify-center min-h-[180px]">
<div className="flex flex-col items-center">
<FileIcon size={28} className="text-black mb-2" />
<span className="text-sm text-gray-700 font-medium mb-1 font-hse-sans">{selectedFile.name}</span>
<span className="text-xs text-gray-500 font-hse-sans">{(selectedFile.size / 1024).toFixed(1)} KB</span>
<Button
variant="ghost"
className="text-blue-500 text-sm mt-2 p-0 h-auto hover:bg-transparent hover:text-blue-600 font-hse-sans"
onClick={() => setSelectedFile(null)}
>
Выбрать другой файл
</Button>
</div>
</div>
) : (
<div
className="bg-white rounded-lg p-6 flex flex-col items-center justify-center min-h-[180px] cursor-pointer transition-colors"
onClick={handleFileUploadClick}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<FileIcon size={28} className="text-black mb-3" />
<span
className="bg-[var(--color-yellow-standard)] text-black font-medium rounded-full px-4 py-1.5 text-sm mb-2 font-hse-sans inline-block"
>
Загрузить файл
</span>
<p className="text-xs text-gray-500 text-center font-hse-sans">
Доступные форматы: jpg, jpeg, png
</p>
</div>
)}
</>
);
};
export default FileSolution;
@@ -0,0 +1,22 @@
import React from 'react';
import { Input } from "@/components/ui/input";
interface InputSolutionProps {
answer: string;
setAnswer: (value: string) => void;
}
const InputSolution: React.FC<InputSolutionProps> = ({ answer, setAnswer }) => {
return (
<div className="bg-white rounded-lg p-4">
<Input
className="border-0 shadow-none focus-visible:ring-0 font-hse-sans text-sm h-9"
placeholder="Введите ответ"
value={answer}
onChange={(e) => setAnswer(e.target.value)}
/>
</div>
);
};
export default InputSolution;
@@ -0,0 +1,27 @@
import React from 'react';
import { Task } from "@/shared/types";
import { getTaskBgColor, getTaskTextColor } from '@/pages/CompetitionSession/utils/utils';
interface SolutionStatusProps {
task: Task;
}
const SolutionStatus: React.FC<SolutionStatusProps> = ({ task }) => {
return (
<div className={`${getTaskBgColor(task.status)} rounded-lg p-4 relative`}>
<div className="flex flex-col">
<span className={`${getTaskTextColor(task.status)} font-medium`}>
Решение 12345
</span>
<span className={`${getTaskTextColor(task.status)} mt-1`}>
Зачтено 5/10 баллов
</span>
</div>
<div className={`absolute bottom-2 right-3 text-xs ${getTaskTextColor(task.status)}`}>
1 марта, 08:41
</div>
</div>
);
};
export default SolutionStatus;
@@ -0,0 +1,52 @@
import React, { useState, useRef } from 'react';
import { Task } from "@/shared/types";
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';
interface TaskSolutionProps {
task: Task;
answer: string;
setAnswer: (value: string) => void;
onSubmit: () => void;
onHistoryClick: () => void;
}
const TaskSolution: React.FC<TaskSolutionProps> = ({
task,
answer,
setAnswer,
onSubmit,
onHistoryClick,
}) => {
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
return (
<div className="md:w-[500px] flex flex-col gap-4">
<SolutionStatus task={task} />
{task.solutionType === 'input' && (
<InputSolution answer={answer} setAnswer={setAnswer} />
)}
{task.solutionType === 'file' && (
<FileSolution
selectedFile={selectedFile}
setSelectedFile={setSelectedFile}
fileInputRef={fileInputRef}
/>
)}
{task.solutionType === 'code' && (
<CodeSolution answer={answer} setAnswer={setAnswer} />
)}
<ActionButtons onHistoryClick={onHistoryClick} onSubmit={onSubmit} />
</div>
);
};
export default TaskSolution;