File size: 10,963 Bytes
99ddd4c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | 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>
);
};
|