-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
615 lines (527 loc) · 19.4 KB
/
Copy pathscript.js
File metadata and controls
615 lines (527 loc) · 19.4 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/* Shared script for startup, index (dashboard), study, routine, and goal pages */
console.log("script.js loaded");
window.addEventListener("load", () => {
try {
initApp();
} catch (err) {
console.error("initApp error:", err);
}
});
const dailyBtn = document.getElementById("dailyBtn");
if (dailyBtn) dailyBtn.onclick = () => window.location.href = "reminders.html";
/* ---------------- MAIN ROUTER ---------------- */
function initApp() {
const path = window.location.pathname.split("/").pop();
if (path === "" || path === "index.html") initIndex();
else if (path === "startup.html") initStartup();
else if (path === "study.html") initStudy();
else if (path === "routine.html") initRoutine();
else if (path === "goal.html") initGoal();
else initIndex();
}
/* ---------------- STARTUP ---------------- */
function initStartup() {
const subCountInput = document.getElementById("subCount");
const subjectInputs = document.getElementById("subjectInputs");
const saveBtn = document.getElementById("saveBtn");
const userNameInput = document.getElementById("userName");
if (!subCountInput || !subjectInputs || !saveBtn || !userNameInput) return;
subCountInput.addEventListener("input", () => {
const count = Math.max(0, parseInt(subCountInput.value) || 0);
subjectInputs.innerHTML = "";
for (let i = 0; i < count; i++) {
const box = document.createElement("input");
box.type = "text";
box.placeholder = "Subject " + (i + 1);
box.className = "subjectBox";
box.style.display = "block";
box.style.margin = "8px 0";
subjectInputs.appendChild(box);
}
});
saveBtn.addEventListener("click", () => {
const name = userNameInput.value.trim();
const count = Math.max(0, parseInt(subCountInput.value) || 0);
if (!name || count < 1) {
alert("Please enter your name and valid subject count.");
return;
}
const boxes = Array.from(document.querySelectorAll(".subjectBox"));
const subs = boxes.map(b => b.value.trim()).filter(v => v);
if (subs.length !== count) {
alert("Please fill all subject names.");
return;
}
localStorage.setItem("userName", name);
localStorage.setItem("subjects", JSON.stringify(subs));
const colors = {};
subs.forEach(s => colors[s] = randomColor());
localStorage.setItem("subjectColors", JSON.stringify(colors));
localStorage.setItem("firstTime", "false");
window.location.href = "index.html";
});
const existingSubjects = JSON.parse(localStorage.getItem("subjects") || "[]");
if (existingSubjects.length) {
subCountInput.value = existingSubjects.length;
subCountInput.dispatchEvent(new Event("input"));
const boxes = document.querySelectorAll(".subjectBox");
boxes.forEach((b, i) => b.value = existingSubjects[i] || "");
userNameInput.value = localStorage.getItem("userName") || "";
}
}
/* ---------------- INDEX / DASHBOARD ---------------- */
let currentChart = null;
function initIndex() {
const firstTime = localStorage.getItem("firstTime");
if (!firstTime || firstTime === "true") {
window.location.href = "startup.html";
return;
}
const goalBtn = document.getElementById("goalBtn");
if (goalBtn) goalBtn.onclick = () => window.location.href = "goal.html";
const routineBtn = document.getElementById("routineBtn");
if (routineBtn) routineBtn.onclick = () => window.location.href = "routine.html";
const welcomeUser = document.getElementById("welcomeUser");
const subjectButtons = document.getElementById("subjectButtons");
const canvas = document.getElementById("studyGraph");
if (!welcomeUser || !subjectButtons || !canvas) return;
welcomeUser.textContent = `Hello, ${localStorage.getItem("userName") || "Student"}!`;
// Subjects
const subjects = JSON.parse(localStorage.getItem("subjects") || "[]");
const colors = JSON.parse(localStorage.getItem("subjectColors") || "{}");
const allSubjects = Array.from(new Set([...subjects, "Personal Project"]));
if (!colors["Personal Project"]) colors["Personal Project"] = "#FF7F50";
localStorage.setItem("subjectColors", JSON.stringify(colors));
// Clear buttons first
subjectButtons.innerHTML = "";
// Create subject buttons dynamically
allSubjects.forEach(sub => {
const btn = document.createElement("button");
btn.className = "subject-btn";
btn.textContent = sub;
btn.style.margin = "6px";
btn.onclick = () => window.location.href = `study.html?subject=${encodeURIComponent(sub)}`;
subjectButtons.appendChild(btn);
});
// --- ADD NOTES BUTTON ---
const notesBtn = document.createElement("button");
notesBtn.className = "subject-btn";
notesBtn.textContent = "Notes";
notesBtn.style.margin = "6px";
notesBtn.onclick = () => window.location.href = "note.html";
subjectButtons.appendChild(notesBtn);
renderGraph();
renderDashboardReminders();
scheduleDashboardReminderUpdates();
}
/* ---------------- DASHBOARD REMINDERS ---------------- */
function renderDashboardReminders() {
const containerId = "dashboardReminders";
let container = document.getElementById(containerId);
if (!container) {
container = document.createElement("div");
container.id = containerId;
container.style.margin = "12px 0";
container.style.padding = "10px";
container.style.background = "#FFF3CD";
container.style.border = "1px solid #FFEEBA";
container.style.borderRadius = "8px";
const refEl = document.getElementById("subjectButtons") || document.body.firstChild;
document.body.insertBefore(container, refEl);
}
container.innerHTML = "";
const now = new Date();
const todayDay = now.toLocaleString("en-US", { weekday: "long" });
// Routine reminders
const routineData = JSON.parse(localStorage.getItem("routines") || "[]");
routineData.forEach(r => {
if (r.day !== todayDay) return;
const [h, m] = r.startTime.split(":").map(Number);
const start = new Date();
start.setHours(h, m, 0, 0);
const durationMs = r.duration * 60 * 1000;
const remaining = start.getTime() + durationMs - now.getTime();
if (remaining > 0 && remaining <= durationMs * 0.1) {
const div = document.createElement("div");
div.style.margin = "4px 0";
div.style.padding = "6px 10px";
div.style.background = "#FFF9C4";
div.style.borderRadius = "6px";
div.textContent = `⚠️ Almost time: Study ${r.subject} (${r.duration}min)`;
container.appendChild(div);
}
});
// Goal reminders (within 24h)
const goals = JSON.parse(localStorage.getItem("goals") || "[]");
goals.forEach(g => {
const deadline = new Date(g.deadline);
const remainingMs = deadline - now;
if (remainingMs > 0 && remainingMs <= 24 * 60 * 60 * 1000) {
const div = document.createElement("div");
div.style.margin = "4px 0";
div.style.padding = "6px 10px";
div.style.background = "#D1ECF1";
div.style.borderRadius = "6px";
div.textContent = `⚠️ Goal deadline soon: ${g.subject} - ${g.task}`;
container.appendChild(div);
}
});
container.style.display = container.hasChildNodes() ? "block" : "none";
}
// Update dashboard reminders every 5s
function scheduleDashboardReminderUpdates() {
setInterval(() => {
if (window.location.pathname.split("/").pop() === "index.html") {
renderDashboardReminders();
}
}, 5000);
}
/* ---------------- STUDY PAGE ---------------- */
// Worker (1s tick) for smooth updates
const workerCode = `
let interval = null;
self.onmessage = e => {
const { type } = e.data || {};
if (type === "START") {
if (interval) clearInterval(interval);
interval = setInterval(() => postMessage({ type: "TICK" }), 1000);
} else if (type === "STOP") {
if (interval) clearInterval(interval);
interval = null;
}
};
`;
const worker = new Worker(URL.createObjectURL(new Blob([workerCode], { type: "application/javascript" })));
// Prevent crashes if called (dashboard hook)
function onSessionComplete(subject, minutes) {
console.log(`Session complete: ${subject} — ${minutes} min`);
}
function initStudy() {
console.log("initStudy: starting");
// DOM
const sound = document.getElementById("alarmSound");
const studySubjectEl = document.getElementById("studySubject");
const startBtn = document.getElementById("startTimerBtn");
const stopBtn = document.getElementById("stopTimerBtn");
const timerInput = document.getElementById("timerInput");
const display = document.getElementById("timerDisplay");
const backBtn = document.getElementById("backBtn");
if (!startBtn || !stopBtn || !timerInput || !display || !studySubjectEl) {
console.error("initStudy: missing DOM elements");
return;
}
// Subject from URL
const params = new URLSearchParams(window.location.search);
const subject = params.get("subject") || "Personal Project";
studySubjectEl.textContent = `Studying: ${subject}`;
// State
let started = false;
let running = false;
let startTime = null;
let durationMs = null;
let setMinutes = 0;
let endTime = null;
let audioUnlocked = false;
// ---- Audio unlock for mobile autoplay policies ----
function unlockAlarmAudio() {
if (!sound || audioUnlocked) return;
try {
sound.load?.();
sound.muted = true;
sound.loop = false;
sound.currentTime = 0;
const p = sound.play();
if (p && typeof p.then === "function") {
p.then(() => {
sound.pause();
sound.muted = false;
audioUnlocked = true;
console.log("Alarm audio unlocked");
}).catch(() => {
sound.muted = false;
console.warn("Alarm audio unlock attempt failed");
});
} else {
sound.pause();
sound.muted = false;
audioUnlocked = true;
}
} catch (e) {
console.warn("Alarm audio unlock error", e);
}
}
// Alarm helpers
function stopAlarm() {
if (sound) {
sound.loop = false;
sound.pause();
setTimeout(() => { sound.currentTime = 0; }, 50);
}
const popup = document.getElementById("alarmPopup");
if (popup) popup.remove();
}
function notifyTimerEnd(subj) {
if (sound) {
sound.currentTime = 0;
sound.loop = true;
sound.play().catch(() => {
console.warn("Alarm play blocked; waiting for user gesture");
});
}
const existing = document.getElementById("alarmPopup");
if (existing) existing.remove();
const popup = document.createElement("div");
popup.id = "alarmPopup";
popup.innerHTML = `
<div style="position:fixed;top:30%;left:50%;transform:translateX(-50%);
background:#fff;padding:16px 20px;border:2px solid #000;border-radius:8px;z-index:9999;max-width:340px">
<p style="margin:0 0 12px">⏰ Time's up! Your ${subj} session has ended.</p>
<button id="closeAlarmBtn" style="padding:8px 12px;border:1px solid #000;background:#f5f5f5">Stop Alarm</button>
</div>`;
document.body.appendChild(popup);
document.getElementById("closeAlarmBtn").onclick = stopAlarm;
}
// Display update
function updateTimerDisplay() {
if (!running || !startTime || durationMs == null || !endTime) {
display.textContent = "00:00";
return;
}
const now = Date.now();
const remainingMs = endTime - now;
const remainingSec = Math.ceil(Math.max(0, remainingMs) / 1000);
if (remainingSec <= 0) {
running = false;
started = false;
startTime = null;
durationMs = null;
endTime = null;
display.textContent = "00:00";
worker.postMessage({ type: "STOP" });
onSessionComplete(subject, setMinutes);
notifyTimerEnd(subject);
startBtn.textContent = "Start";
startBtn.disabled = false;
stopBtn.textContent = "Stop";
stopBtn.disabled = true;
timerInput.disabled = false;
return;
}
const m = Math.floor(remainingSec / 60);
const s = remainingSec % 60;
display.textContent = `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}
// Button cycle
function startOrReset() {
if (started) {
running = false;
started = false;
startTime = null;
durationMs = null;
setMinutes = 0;
endTime = null;
worker.postMessage({ type: "STOP" });
stopAlarm();
display.textContent = "00:00";
startBtn.textContent = "Start";
startBtn.disabled = false;
stopBtn.textContent = "Stop";
stopBtn.disabled = true;
timerInput.disabled = false;
console.log("Timer reset");
return;
}
setMinutes = Math.max(1, parseInt(timerInput.value) || 30);
durationMs = setMinutes * 60 * 1000;
startTime = Date.now();
endTime = startTime + durationMs;
started = true;
running = true;
unlockAlarmAudio();
startBtn.textContent = "Reset";
stopBtn.textContent = "Stop";
stopBtn.disabled = false;
timerInput.disabled = true;
updateTimerDisplay();
worker.postMessage({ type: "START" });
console.log("Timer started", { setMinutes, durationMs });
}
function stopOrResume() {
if (!started) return;
if (running) {
const now = Date.now();
durationMs = Math.max(0, endTime - now);
running = false;
worker.postMessage({ type: "STOP" });
startBtn.textContent = "Reset";
stopBtn.textContent = "Resume";
stopBtn.disabled = false;
timerInput.disabled = true;
console.log("Timer paused, remainingMs =", durationMs);
} else {
startTime = Date.now();
endTime = startTime + durationMs;
running = true;
unlockAlarmAudio();
worker.postMessage({ type: "START" });
startBtn.textContent = "Reset";
stopBtn.textContent = "Stop";
stopBtn.disabled = false;
timerInput.disabled = true;
console.log("Timer resumed, remainingMs =", durationMs);
}
}
// Bind worker tick
worker.onmessage = (e) => {
if (e.data && e.data.type === "TICK") updateTimerDisplay();
};
// Visibility handler: catch up if tab was hidden
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
updateTimerDisplay();
}
});
// Bind buttons
startBtn.onclick = startOrReset;
stopBtn.onclick = stopOrResume;
if (backBtn) backBtn.onclick = () => (window.location.href = "index.html");
// Initial UI
display.textContent = "00:00";
startBtn.textContent = "Start";
startBtn.disabled = false;
stopBtn.textContent = "Stop";
stopBtn.disabled = true;
timerInput.disabled = false;
console.log("initStudy: ready");
}
/* ---------------- ROUTINE PAGE ---------------- */
function initRoutine() {
const form = document.getElementById("routineForm");
const list = document.getElementById("routineList");
if (!form || !list) return;
renderRoutineList();
form.onsubmit = (e) => {
e.preventDefault();
const day = document.getElementById("routineDay").value;
const time = document.getElementById("routineTime").value;
const subject = document.getElementById("routineSubject").value;
const routines = JSON.parse(localStorage.getItem("routines") || "[]");
routines.push({ day, startTime: time, duration: 60, subject });
localStorage.setItem("routines", JSON.stringify(routines));
renderRoutineList();
form.reset();
};
function renderRoutineList() {
const routines = JSON.parse(localStorage.getItem("routines") || "[]");
list.innerHTML = routines.length
? ""
: "<p>No routines added yet.</p>";
routines.forEach((r, i) => {
const div = document.createElement("div");
div.className = "goalCard";
div.innerHTML = `
<h3>${r.day} - ${r.subject}</h3>
<p>Time: ${r.startTime}</p>
<button onclick="deleteRoutine(${i})">Delete</button>
`;
list.appendChild(div);
});
}
window.deleteRoutine = function(i) {
const routines = JSON.parse(localStorage.getItem("routines") || "[]");
routines.splice(i, 1);
localStorage.setItem("routines", JSON.stringify(routines));
renderRoutineList();
};
}
/* ---------------- GOAL PAGE ---------------- */
function initGoal() {
const form = document.getElementById("goalForm");
const list = document.getElementById("goalList");
if (!form || !list) return;
renderGoalList();
form.onsubmit = (e) => {
e.preventDefault();
const subject = document.getElementById("goalSubject").value;
const task = document.getElementById("goalTask").value;
const deadline = document.getElementById("goalDeadline").value;
const goals = JSON.parse(localStorage.getItem("goals") || "[]");
goals.push({ subject, task, deadline });
localStorage.setItem("goals", JSON.stringify(goals));
renderGoalList();
form.reset();
};
function renderGoalList() {
const goals = JSON.parse(localStorage.getItem("goals") || "[]");
list.innerHTML = goals.length
? ""
: "<p>No goals added yet.</p>";
goals.forEach((g, i) => {
const div = document.createElement("div");
div.className = "goalCard";
div.innerHTML = `
<h3>${g.subject}</h3>
<p>${g.task}</p>
<p>Deadline: ${g.deadline}</p>
<button onclick="deleteGoal(${i})">Delete</button>
`;
list.appendChild(div);
});
}
window.deleteGoal = function(i) {
const goals = JSON.parse(localStorage.getItem("goals") || "[]");
goals.splice(i, 1);
localStorage.setItem("goals", JSON.stringify(goals));
renderGoalList();
};
}
/* ---------------- Helpers ---------------- */
function randomColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}
/* ---------------- STUDY SESSION RECORD ---------------- */
function onSessionComplete(subject, minutes) {
minutes = Math.max(1, Math.round(minutes));
const raw = localStorage.getItem("studyData");
const studyData = raw ? JSON.parse(raw) : {};
const today = new Date().toISOString().split("T")[0];
if (!studyData[today]) studyData[today] = {};
if (!studyData[today][subject]) studyData[today][subject] = 0;
studyData[today][subject] += minutes;
localStorage.setItem("studyData", JSON.stringify(studyData));
// Update index graph if on dashboard
if (window.location.pathname.split("/").pop() === "index.html") {
try { renderGraph(); } catch(e) { console.error(e); }
}
}
/* ---------------- RENDER GRAPH ---------------- */
function renderGraph() {
const canvas = document.getElementById("studyGraph");
const placeholder = document.getElementById("statsPlaceholder");
if (!canvas) return;
const studyData = JSON.parse(localStorage.getItem("studyData") || "{}");
const todayData = studyData[new Date().toISOString().split("T")[0]] || {};
const labels = Object.keys(todayData);
const values = Object.values(todayData);
if (!labels.length) {
if (placeholder) placeholder.style.display = "block";
canvas.style.display = "none";
if (currentChart) { try { currentChart.destroy(); } catch(e){} currentChart = null; }
return;
} else {
if (placeholder) placeholder.style.display = "none";
canvas.style.display = "block";
}
const colorsMap = JSON.parse(localStorage.getItem("subjectColors") || "{}");
const bg = labels.map(l => colorsMap[l] || randomColor());
if (currentChart) { try { currentChart.destroy(); } catch(e){} currentChart = null; }
if (typeof Chart === "undefined") {
console.error("Chart.js not found");
return;
}
currentChart = new Chart(canvas.getContext("2d"), {
type: "bar",
data: { labels, datasets: [{ label: "Minutes studied (today)", data: values, backgroundColor: bg }] },
options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } } }
});
}