Add student questions list, new question form, and thread pages
Tasks 8–10: student-facing questions UI — list page with unread badges, new question form with client-side submission, and thread page with QuestionThread component for real-time reply + file attachment flow. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
|
||||
interface FileAttachment {
|
||||
name: string;
|
||||
url: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
authorId: string;
|
||||
text: string;
|
||||
files: FileAttachment[] | null;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
author: { id: string; name: string; role: string };
|
||||
}
|
||||
|
||||
interface QuestionThreadProps {
|
||||
questionId: string;
|
||||
questionStatus: "OPEN" | "CLOSED";
|
||||
currentUserId: string;
|
||||
initialMessages: Message[];
|
||||
}
|
||||
|
||||
function formatDate(iso: string) {
|
||||
return new Date(iso).toLocaleString("ru", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function QuestionThread({
|
||||
questionId,
|
||||
questionStatus,
|
||||
currentUserId,
|
||||
initialMessages,
|
||||
}: QuestionThreadProps) {
|
||||
const [messages, setMessages] = useState<Message[]>(initialMessages);
|
||||
const [text, setText] = useState("");
|
||||
const [files, setFiles] = useState<FileAttachment[]>([]);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
async function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
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 handleSend() {
|
||||
if (!text.trim() && files.length === 0) return;
|
||||
setSending(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/questions/${questionId}/messages`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ text: text.trim(), files }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const d = await res.json();
|
||||
throw new Error(d.error ?? "Ошибка отправки");
|
||||
}
|
||||
const msg = await res.json();
|
||||
setMessages((prev) => [...prev, msg]);
|
||||
setText("");
|
||||
setFiles([]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Ошибка");
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
{/* Messages */}
|
||||
<div className="flex flex-col gap-2 mb-4 max-h-96 overflow-y-auto pr-1">
|
||||
{messages.map((msg) => {
|
||||
const isMine = msg.authorId === currentUserId;
|
||||
const isNew = !msg.isRead && !isMine;
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="max-w-[88%] px-3 py-2 rounded-sm text-sm"
|
||||
style={{
|
||||
alignSelf: isMine ? "flex-start" : "flex-end",
|
||||
background: isMine ? "#E8E8E0" : "#F5F5F0",
|
||||
border: isMine ? "none" : `2px solid #E8F0D8`,
|
||||
borderLeft: !isMine && isNew ? "3px solid #323232" : undefined,
|
||||
}}
|
||||
>
|
||||
<p
|
||||
className="text-xs mb-1"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
{isMine ? "Ты" : msg.author.name} · {formatDate(msg.createdAt)}
|
||||
{isNew && (
|
||||
<strong style={{ color: "#323232" }}> · 🔵 новое</strong>
|
||||
)}
|
||||
</p>
|
||||
<p style={{ color: "var(--foreground)" }}>{msg.text}</p>
|
||||
{msg.files && msg.files.length > 0 && (
|
||||
<div className="flex flex-col gap-1 mt-2">
|
||||
{msg.files.map((f, i) => (
|
||||
<a
|
||||
key={i}
|
||||
href={f.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1.5 text-xs px-2 py-1 rounded-sm"
|
||||
style={{
|
||||
background: "#F5F5F0",
|
||||
border: "1px solid #AAAAAA",
|
||||
color: "var(--foreground)",
|
||||
width: "fit-content",
|
||||
}}
|
||||
>
|
||||
📎 <span>{f.name}</span>
|
||||
<span style={{ color: "#999" }}>· {formatFileSize(f.size)}</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Queued files preview */}
|
||||
{files.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-2">
|
||||
{files.map((f, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-center gap-1 text-xs px-2 py-1 rounded-sm"
|
||||
style={{ background: "var(--surface)", border: "1px solid var(--border)" }}
|
||||
>
|
||||
📎 {f.name}
|
||||
<button
|
||||
onClick={() => setFiles((prev) => prev.filter((_, j) => j !== i))}
|
||||
className="ml-1 text-xs"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Reply form */}
|
||||
<div
|
||||
className="rounded-sm p-2"
|
||||
style={{
|
||||
border: "2px solid #AAAAAA",
|
||||
background: "var(--surface)",
|
||||
opacity: questionStatus === "CLOSED" ? 0.5 : 1,
|
||||
pointerEvents: questionStatus === "CLOSED" ? "none" : "auto",
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={questionStatus === "CLOSED" ? "Вопрос закрыт" : "Написать сообщение..."}
|
||||
rows={3}
|
||||
disabled={questionStatus === "CLOSED"}
|
||||
className="w-full text-sm outline-none resize-none bg-transparent"
|
||||
style={{ border: "none", color: "var(--foreground)" }}
|
||||
/>
|
||||
<div
|
||||
className="flex items-center justify-between pt-2 mt-1"
|
||||
style={{ borderTop: "1px solid #E8E8E0" }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
accept=".jpg,.jpeg,.png,.pdf,.md,.txt"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="text-xs px-2 py-1 rounded-sm"
|
||||
style={{ background: "var(--surface)", border: "1px solid #AAAAAA" }}
|
||||
>
|
||||
{uploading ? "Загрузка..." : "📎 Прикрепить"}
|
||||
</button>
|
||||
<span className="text-xs" style={{ color: "#999" }}>
|
||||
jpg, png, pdf, md · до 10 МБ
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSend}
|
||||
disabled={sending || (!text.trim() && files.length === 0)}
|
||||
className="text-xs font-bold px-4 py-1.5 rounded-sm"
|
||||
style={{
|
||||
background: "var(--foreground)",
|
||||
color: "var(--background)",
|
||||
border: "none",
|
||||
opacity: sending ? 0.6 : 1,
|
||||
}}
|
||||
>
|
||||
{sending ? "..." : "Отправить →"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-xs mt-1" style={{ color: "#c00" }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user