BilimWay / src /components /LessonNotesSidebar.tsx
musabek77's picture
Deploy to Hugging Face Spaces with corrected permissions
99ddd4c
Raw History Blame Contribute Delete
11 kB
import React, { useState, useEffect, useRef } from "react";
import { doc, getDoc, setDoc } from "firebase/firestore";
import { db, auth } from "../firebase";
import { FileText, Save, Check, RefreshCw, AlertTriangle, ChevronRight, ChevronLeft, Sparkles, BookOpen } from "lucide-react";
interface LessonNotesSidebarProps {
lesson: {
docId?: string;
id: string | number;
title: string;
};
playBeep?: (type: string) => void;
}
export const LessonNotesSidebar: React.FC<LessonNotesSidebarProps> = ({ lesson, playBeep }) => {
const [content, setContent] = useState<string>("");
const [notesId, setNotesId] = useState<string>("");
const [isCollapsed, setIsCollapsed] = useState<boolean>(false);
// Status states
const [loading, setLoading] = useState<boolean>(false);
const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle");
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [lastSavedTime, setLastSavedTime] = useState<string | null>(null);
const user = auth.currentUser;
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
// Generate unique notes document ID for Firebase: userId + lessonId
const getNoteDocId = () => {
if (!user) return "";
const cleanLessonId = String(lesson.docId || lesson.id).replace(/[^a-zA-Z0-9_\-]/g, "");
return `${user.uid}_${cleanLessonId}`;
};
// Load existing note on mount or when user/lesson changes
useEffect(() => {
if (!user) {
setContent("");
setSaveStatus("idle");
return;
}
const docId = getNoteDocId();
setNotesId(docId);
setLoading(true);
setSaveStatus("idle");
setErrorMsg(null);
const fetchNote = async () => {
try {
const noteRef = doc(db, "lesson_notes", docId);
const noteDoc = await getDoc(noteRef);
if (noteDoc.exists()) {
const data = noteDoc.data();
setContent(data.content || "");
if (data.updatedAt) {
const date = new Date(data.updatedAt);
setLastSavedTime(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }));
setSaveStatus("saved");
}
} else {
setContent("");
setLastSavedTime(null);
}
} catch (err: any) {
console.error("Eslatmani yuklashda xatolik:", err);
setErrorMsg("Eslatmani yuklab bo'lmadi.");
setSaveStatus("error");
} finally {
setLoading(false);
}
};
fetchNote();
}, [lesson.id, lesson.docId, user?.uid]);
// Handle manual saving
const handleSave = async (textToSave = content) => {
if (!user) {
setErrorMsg("Eslatmalarni saqlash uchun tizimga kirishingiz lozim.");
setSaveStatus("error");
if (playBeep) playBeep("error");
return;
}
const docId = getNoteDocId() || notesId;
if (!docId) return;
setSaveStatus("saving");
setErrorMsg(null);
try {
const noteRef = doc(db, "lesson_notes", docId);
const now = Date.now();
await setDoc(noteRef, {
id: docId,
userId: user.uid,
lessonId: String(lesson.docId || lesson.id),
lessonTitle: lesson.title,
content: textToSave,
updatedAt: now
}, { merge: true });
const date = new Date(now);
setLastSavedTime(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }));
setSaveStatus("saved");
if (playBeep) playBeep("levelUp");
} catch (err: any) {
console.error("Eslatmani saqlashda xatolik:", err);
setErrorMsg("Internet ulanishi yoki ruxsat yo'q.");
setSaveStatus("error");
if (playBeep) playBeep("error");
}
};
// Debounced auto-save on typing if logged in
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const text = e.target.value;
setContent(text);
setSaveStatus("idle");
if (!user) return;
// Clear previous timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Set new timeout for auto-saving after 1.5s of idle typing
timeoutRef.current = setTimeout(() => {
handleSave(text);
}, 1500);
};
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
const charCount = content.length;
const wordCount = content.trim() ? content.trim().split(/\s+/).length : 0;
// Render Collapsed trigger vertical tab
if (isCollapsed) {
return (
<button
onClick={() => {
setIsCollapsed(false);
if (playBeep) playBeep("move");
}}
className="bg-slate-900 hover:bg-slate-850 border-t lg:border-t-0 lg:border-l border-slate-800 text-slate-350 hover:text-white px-3 py-6 flex flex-row lg:flex-col items-center justify-between gap-3 cursor-pointer transition-all duration-300 focus:outline-none relative select-none w-full lg:w-16 h-12 lg:h-full z-[100000]"
title="Eslatma oynasini ochish"
>
<div className="flex items-center gap-2 lg:flex-col">
<ChevronLeft className="w-4 h-4 hidden lg:block text-violet-400 animate-pulse" />
<FileText className="w-5 h-5 text-emerald-400" />
<span className="text-[10px] font-bold uppercase tracking-widest font-sans lg:[writing-mode:vertical-lr] lg:scale-110">
Eslatmalar
</span>
</div>
<div className="flex items-center gap-2">
{content && <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />}
<span className="text-[10px] font-mono font-bold bg-slate-950 px-1.5 py-0.5 rounded border border-slate-850">
{wordCount} s.
</span>
</div>
</button>
);
}
return (
<div className="w-full lg:w-96 h-[260px] lg:h-full bg-slate-950 border-t lg:border-t-0 lg:border-l border-slate-850 flex flex-col relative z-[100000] select-text transition-all duration-350">
{/* Drawer Header */}
<div className="p-3 bg-slate-900 border-b border-slate-850 flex items-center justify-between gap-2.5">
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-lg bg-violet-950 border border-violet-850 flex items-center justify-center">
<BookOpen className="w-4 h-4 text-violet-400" />
</div>
<div>
<h3 className="text-xs font-bold text-white tracking-wide font-sans">
Dars eslatmasi
</h3>
<p className="text-[9.5px] text-slate-400 truncate max-w-[200px]">
Shaxsiy konspektlaringiz
</p>
</div>
</div>
<div className="flex items-center gap-1.5">
<button
onClick={() => {
setIsCollapsed(true);
if (playBeep) playBeep("move");
}}
className="hover:bg-slate-800 text-slate-400 hover:text-white rounded-lg p-1.5 transition cursor-pointer"
title="Eslatmani yashirish"
>
<ChevronRight className="w-4 h-4" />
</button>
</div>
</div>
{/* Editor Body */}
<div className="flex-1 p-3 flex flex-col justify-between gap-2.5 overflow-hidden">
{/* Loading Indicator Overlay */}
{loading ? (
<div className="flex-1 flex flex-col items-center justify-center text-slate-400 gap-2">
<RefreshCw className="w-6 h-6 animate-spin text-violet-500" />
<span className="text-[10px] font-mono">Eslatmalarni yuklanmoqda...</span>
</div>
) : (
<div className="flex-1 flex flex-col relative min-h-0">
<textarea
value={content}
onChange={handleTextChange}
placeholder="Dars bo'yicha muhim dars qoidalari, yangi so'zlar yoki savollaringizni shu yerga yozib boring..."
className="flex-1 w-full p-2.5 bg-slate-900/60 rounded-xl text-slate-100 placeholder-slate-500 text-xs focus:outline-none focus:ring-1 focus:ring-violet-500/70 border border-slate-850 resize-none font-sans leading-relaxed transition-all focus:bg-slate-900"
spellCheck={false}
/>
{!user && (
<div className="absolute inset-0 bg-slate-950/85 backdrop-blur-sm flex flex-col items-center justify-center p-4 text-center rounded-xl border border-dashed border-slate-800">
<AlertTriangle className="w-6 h-6 text-amber-500 mb-2" />
<h4 className="text-[11px] font-bold text-white mb-1">Tizimga kirmagansiz</h4>
<p className="text-[10px] text-slate-400 leading-normal max-w-[200px] mb-3">
Eslatmalarni asrab qolish va saqlash uchun darslikka hisobingiz orqali kiring.
</p>
</div>
)}
</div>
)}
{/* Status bar and metadata */}
<div className="bg-slate-900/80 border border-slate-850/80 p-2.5 rounded-xl flex items-center justify-between text-[9.5px]">
<div className="flex flex-col gap-0.5">
{saveStatus === "saving" && (
<span className="text-amber-400 font-mono font-bold flex items-center gap-1 animate-pulse">
<RefreshCw className="w-3 h-3 animate-spin" /> Saqlanmoqda...
</span>
)}
{saveStatus === "saved" && (
<span className="text-emerald-400 font-mono font-bold flex items-center gap-1">
<Check className="w-3 h-3" /> Sinxronlandi
</span>
)}
{saveStatus === "error" && (
<span className="text-red-400 font-mono font-bold flex items-center gap-1">
<AlertTriangle className="w-3 h-3 text-red-400" /> Xatolik yuz berdi
</span>
)}
{saveStatus === "idle" && (
<span className="text-slate-400 font-mono">
{content ? "Sinxronlanmagan" : "Bo'sh varoq"}
</span>
)}
{lastSavedTime && (
<span className="text-[8.5px] text-slate-500">
Oxirgi: {lastSavedTime}
</span>
)}
</div>
<div className="flex items-center gap-2">
<span className="text-[9px] text-slate-500 font-mono">
{wordCount} so'z / {charCount} harf
</span>
{user && content && (
<button
onClick={() => handleSave()}
className="bg-violet-600 hover:bg-violet-500 text-white p-1 rounded transition cursor-pointer flex items-center"
title="Sinxronlash"
>
<Save className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
</div>
</div>
);
};