diff --git a/src/app/(student)/questions/new/page.tsx b/src/app/(student)/questions/new/page.tsx index 40ed8b3..753a986 100644 --- a/src/app/(student)/questions/new/page.tsx +++ b/src/app/(student)/questions/new/page.tsx @@ -1,15 +1,56 @@ "use client"; -import { useState } from "react"; +import { useState, useRef } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; +interface FileAttachment { + name: string; + url: string; + size: number; +} + +function formatFileSize(bytes: number) { + if (bytes < 1024) return `${bytes} Б`; + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} КБ`; + return `${(bytes / 1024 / 1024).toFixed(1)} МБ`; +} + export default function NewQuestionPage() { const router = useRouter(); const [title, setTitle] = useState(""); const [text, setText] = useState(""); + const [files, setFiles] = useState([]); + const [uploading, setUploading] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); + const fileInputRef = useRef(null); + + async function handleFileSelect(e: React.ChangeEvent) { + const selected = Array.from(e.target.files ?? []); + if (!selected.length) return; + setUploading(true); + setError(""); + try { + const uploaded: FileAttachment[] = []; + for (const f of selected) { + const form = new FormData(); + form.append("file", f); + const res = await fetch("/api/student/question-upload", { method: "POST", body: form }); + if (!res.ok) { + const d = await res.json(); + throw new Error(d.error ?? "Ошибка загрузки файла"); + } + uploaded.push(await res.json()); + } + setFiles((prev) => [...prev, ...uploaded]); + } catch (err) { + setError(err instanceof Error ? err.message : "Ошибка загрузки"); + } finally { + setUploading(false); + if (fileInputRef.current) fileInputRef.current.value = ""; + } + } async function handleSubmit(e: React.FormEvent) { e.preventDefault(); @@ -21,7 +62,7 @@ export default function NewQuestionPage() { const res = await fetch("/api/questions", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ title, text }), + body: JSON.stringify({ title, text, files }), }); if (!res.ok) { const data = await res.json(); @@ -104,6 +145,54 @@ export default function NewQuestionPage() { /> + {/* File attachments */} +
+ + {files.length > 0 && ( +
+ {files.map((f, i) => ( +
+ 📎 {f.name} + · {formatFileSize(f.size)} + +
+ ))} +
+ )} +
+ + + jpg, png, pdf, md · до 10 МБ + +
+
+ {error && (

{error} @@ -113,13 +202,13 @@ export default function NewQuestionPage() {