Repository navigation
Expand file tree
/
Copy pathscripts.js
More file actions
723 lines (613 loc) · 25.4 KB
/
Copy pathscripts.js
File metadata and controls
723 lines (613 loc) · 25.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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
// --- Content registry for recommendation (Smart Personal Website) ---
const CONTENT_REGISTRY = [
{ id: "home", title: "Home", url: "index.html", tags: ["about"], category: "home" },
{ id: "projects", title: "Projects", url: "projects.html", tags: ["ml", "systems", "fullstack", "embedded", "hardware"], category: "projects" },
{ id: "coursework", title: "Coursework", url: "coursework.html", tags: ["courses", "eecs"], category: "academic" },
{ id: "heatmaps", title: "Heatmaps", url: "heatmaps.html", tags: ["activity", "github"], category: "tools" },
{ id: "messages", title: "Messages", url: "messages.html", tags: ["contact"], category: "contact" },
{ id: "smart-website", title: "Smart Personal Website", url: "project-smart-website.html", tags: ["ml", "systems", "fullstack"], category: "projects" }
];
function getRecommendations(currentPageId, limit) {
const limitNum = Math.min(limit || 3, CONTENT_REGISTRY.length - 1);
const others = CONTENT_REGISTRY.filter(function (c) { return c.id !== currentPageId; });
if (others.length <= limitNum) return others;
try {
const raw = localStorage.getItem("smart_website_recent_views");
const recent = raw ? JSON.parse(raw) : [];
const viewedIds = recent.map(function (r) { return r.page_id; });
const byTag = {};
viewedIds.forEach(function (id) {
const c = CONTENT_REGISTRY.find(function (x) { return x.id === id; });
if (c && c.tags) c.tags.forEach(function (t) { byTag[t] = (byTag[t] || 0) + 1; });
});
const scored = others.map(function (c) {
let s = 0;
if (c.tags) c.tags.forEach(function (t) { s += byTag[t] || 0; });
return { item: c, score: s };
});
scored.sort(function (a, b) { return b.score - a.score; });
const top = scored.slice(0, limitNum).map(function (x) { return x.item; });
while (top.length < limitNum) {
const next = others.find(function (c) { return top.indexOf(c) < 0; });
if (!next) break;
top.push(next);
}
return top;
} catch (_) {
return others.slice(0, limitNum);
}
}
function renderRecommendations(containerId) {
const el = document.getElementById(containerId);
if (!el) return;
const pageId = (function () {
const path = window.location.pathname.replace(/^\//, "").replace(/\.html$/, "") || "index";
return path === "index" ? "home" : path === "project-smart-website" ? "smart-website" : path;
})();
const recs = getRecommendations(pageId, 3);
el.innerHTML = recs.map(function (c) {
return '<a href="' + c.url + '" class="recommendation-card"><span class="rec-title">' + c.title + '</span><span class="rec-meta">' + (c.category || "") + '</span></a>';
}).join("");
}
// Theme Toggling
function toggleTheme() {
const html = document.documentElement;
const currentTheme = html.getAttribute('data-theme') || 'light';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
const themeButton = document.querySelector('.theme-switch');
if (newTheme === 'dark') {
themeButton.textContent = '☀️ Light Mode';
} else {
themeButton.textContent = '🌙 Dark Mode';
}
}
// Check for saved theme preference
document.addEventListener('DOMContentLoaded', function() {
const savedTheme = localStorage.getItem('theme') || 'light';
const html = document.documentElement;
html.setAttribute('data-theme', savedTheme);
const themeButton = document.querySelector('.theme-switch');
if (savedTheme === 'dark') {
themeButton.textContent = '☀️ Light Mode';
} else {
themeButton.textContent = '🌙 Dark Mode';
}
// Adding blinking cursor animation
setInterval(() => {
const cursors = document.querySelectorAll('.cursor-blink');
cursors.forEach(cursor => {
cursor.style.visibility = cursor.style.visibility === 'hidden' ? 'visible' : 'hidden';
});
}, 500);
// Add typing effect to terminal titles
addTypingEffect();
// Initialize habit heatmaps
initHabitTrackers();
// Load habit data from localStorage
loadHabitData();
});
// Message system functionality
function showMessageDialog() {
document.getElementById('messageDialog').style.display = 'flex';
}
function hideMessageDialog() {
document.getElementById('messageDialog').style.display = 'none';
document.getElementById('messageArea').style.display = 'none';
document.getElementById('clearAllBtn').style.display = 'none';
document.getElementById('password').value = '';
}
// Close dialog when clicking outside
window.addEventListener('click', function(event) {
const dialog = document.getElementById('messageDialog');
if (event.target === dialog) {
hideMessageDialog();
}
});
// Password verification for viewing messages
function checkPassword() {
const password = document.getElementById('password').value;
// Simple password check - in a real app, use secure authentication
if (password === 'admin123') {
loadMessages();
document.getElementById('messageArea').style.display = 'block';
document.getElementById('clearAllBtn').style.display = 'block';
} else {
alert('Authentication failed. Access denied.');
}
}
// Load messages from Firebase
function loadMessages() {
if (typeof firebase !== 'undefined') {
const messagesRef = firebase.database().ref('messages');
const messageArea = document.getElementById('messageArea');
messageArea.innerHTML = '<h3>Messages:</h3>';
messagesRef.once('value', function(snapshot) {
const messages = snapshot.val();
if (messages) {
Object.keys(messages).forEach(key => {
const message = messages[key];
const messageElement = document.createElement('div');
messageElement.className = 'message-item';
messageElement.innerHTML = `
<p><strong>${message.author}</strong>: ${message.text}</p>
<p class="message-date">${new Date(message.timestamp).toLocaleString()}</p>
<button onclick="deleteMessage('${key}')">Delete</button>
`;
messageArea.appendChild(messageElement);
});
} else {
messageArea.innerHTML += '<p>No messages yet.</p>';
}
});
}
}
// Send a new message
function sendMessage() {
const authorInput = document.getElementById('messageAuthor');
const textInput = document.getElementById('messageText');
const author = authorInput.value.trim();
const text = textInput.value.trim();
if (!author || !text) {
alert('Please enter your name and message.');
return;
}
if (typeof firebase !== 'undefined') {
const messagesRef = firebase.database().ref('messages');
const newMessage = {
author: author,
text: text,
timestamp: Date.now()
};
messagesRef.push(newMessage)
.then(() => {
authorInput.value = '';
textInput.value = '';
alert('Message sent successfully!');
})
.catch(error => {
console.error('Error sending message:', error);
alert('Error sending message. Please try again.');
});
}
}
// Delete a specific message
function deleteMessage(messageId) {
if (typeof firebase !== 'undefined') {
const messageRef = firebase.database().ref('messages/' + messageId);
messageRef.remove()
.then(() => {
loadMessages();
})
.catch(error => {
console.error('Error deleting message:', error);
alert('Error deleting message. Please try again.');
});
}
}
// Clear all messages
function clearAllMessages() {
if (typeof firebase !== 'undefined') {
const messagesRef = firebase.database().ref('messages');
if (confirm('Are you sure you want to delete ALL messages?')) {
messagesRef.remove()
.then(() => {
document.getElementById('messageArea').innerHTML = '<h3>Messages:</h3><p>No messages yet.</p>';
})
.catch(error => {
console.error('Error clearing messages:', error);
alert('Error clearing messages. Please try again.');
});
}
}
}
// Add terminal typing effect
function addTypingEffect() {
const terminalTitles = document.querySelectorAll('.terminal-title');
terminalTitles.forEach(title => {
const text = title.textContent;
title.textContent = '';
let i = 0;
const typing = setInterval(() => {
if (i < text.length) {
title.textContent += text.charAt(i);
i++;
} else {
clearInterval(typing);
}
}, 50);
});
}
// Habit tracking functionality
// Initialize habit tracker
function initHabitTrackers() {
const habits = ['meditation', 'exercise', 'reading'];
const today = new Date();
habits.forEach(habit => {
const heatmapEl = document.getElementById(`${habit}-heatmap`);
if (!heatmapEl) return;
// Clear existing content
heatmapEl.innerHTML = '';
// 创建GitHub风格的日历布局
const calendarEl = document.createElement('div');
calendarEl.className = 'habit-calendar';
// 计算一年需要多少周(52周)
const totalWeeks = 52;
// 添加周行用于网格布局(52周 = 一年)
const weeks = [];
for (let w = 0; w < totalWeeks; w++) {
const weekEl = document.createElement('div');
weekEl.className = 'calendar-week';
weeks.push(weekEl);
calendarEl.appendChild(weekEl);
}
// 生成过去一年的单元格
const oneYearAgo = new Date();
oneYearAgo.setFullYear(today.getFullYear() - 1);
oneYearAgo.setDate(today.getDate() + 1);
// 计算天数
const daysBetween = Math.floor((today.getTime() - oneYearAgo.getTime()) / (1000 * 3600 * 24));
// 从一年前开始生成日期
for (let i = 0; i <= daysBetween; i++) {
const date = new Date(oneYearAgo);
date.setDate(oneYearAgo.getDate() + i);
const dayEl = document.createElement('div');
dayEl.className = 'habit-day level-0';
dayEl.title = formatDate(date);
dayEl.dataset.date = formatDate(date, 'yyyy-MM-dd');
dayEl.dataset.habit = habit;
// 确定这一天属于哪一周
// 将一年的天数平均分配到52周
const weekIndex = Math.floor(i * totalWeeks / daysBetween);
// 添加点击事件以手动切换状态
dayEl.addEventListener('click', function() {
toggleHabitDay(this);
});
// 添加到适当的周
if (weeks[weekIndex]) {
weeks[weekIndex].appendChild(dayEl);
}
}
heatmapEl.appendChild(calendarEl);
// 添加调试信息
console.log(`初始化 ${habit} 热图,创建了 ${daysBetween} 天的数据`);
});
}
// Load habit data
function loadHabitData() {
const habits = ['meditation', 'exercise', 'reading'];
habits.forEach(habit => {
// Get saved data from localStorage
let data = localStorage.getItem(`habit_${habit}`);
if (data) {
data = JSON.parse(data);
// Update heatmap UI (work with both old and new class names)
Object.keys(data.days).forEach(dateStr => {
// Try both selectors to handle both old and new layouts
const dayEl = document.querySelector(`.calendar-day.habit-day[data-date="${dateStr}"][data-habit="${habit}"]`) ||
document.querySelector(`.habit-day[data-date="${dateStr}"][data-habit="${habit}"]`);
if (dayEl) {
const level = getActivityLevel(data.days[dateStr].minutes);
// Update classes for both old and new layouts
if (dayEl.classList.contains('calendar-day')) {
dayEl.className = `calendar-day habit-day level-${level}`;
} else {
dayEl.className = `habit-day level-${level}`;
}
// Add tooltip data
dayEl.dataset.count = data.days[dateStr].minutes;
dayEl.title = `${data.days[dateStr].minutes} minutes on ${formatDate(new Date(dateStr))}`;
// Add journal entry if available
if (data.days[dateStr].journal) {
dayEl.dataset.journal = data.days[dateStr].journal;
}
}
});
// Update streak and stats
updateStreaks(data);
updateHabitStats(habit, data);
}
});
}
// Log habit with modal interface
function logHabit(habit) {
// Create modal overlay
const modal = document.createElement('div');
modal.className = 'habit-modal';
// Format date for display
const today = new Date();
const dateValue = formatDate(today, 'yyyy-MM-dd');
// Create modal content
modal.innerHTML = `
<div class="habit-modal-content">
<div class="habit-modal-header">
<h3>${getHabitName(habit)}</h3>
<button class="habit-modal-close">esc</button>
</div>
<div class="habit-modal-body">
<div class="habit-modal-row">
<label>Date:</label>
<input type="date" id="habit-date" value="${dateValue}">
</div>
<div class="habit-modal-row">
<label>Minutes:</label>
<input type="number" id="habit-minutes" value="30" min="1">
</div>
<div class="habit-modal-row">
<label>Journal entry:</label>
<textarea id="habit-journal" placeholder="Write about your ${getHabitName(habit).toLowerCase()} session..."></textarea>
</div>
<button class="habit-modal-save">Save</button>
</div>
</div>
`;
// Add modal to the page
document.body.appendChild(modal);
// Focus on minutes input
setTimeout(() => document.getElementById('habit-minutes').focus(), 100);
// Add event listeners
const closeBtn = modal.querySelector('.habit-modal-close');
closeBtn.addEventListener('click', () => {
document.body.removeChild(modal);
});
// Close when clicking outside
modal.addEventListener('click', (e) => {
if (e.target === modal) {
document.body.removeChild(modal);
}
});
// Handle save button
const saveBtn = modal.querySelector('.habit-modal-save');
saveBtn.addEventListener('click', () => {
const dateInput = document.getElementById('habit-date');
const minutesInput = document.getElementById('habit-minutes');
const journalInput = document.getElementById('habit-journal');
const date = dateInput.value;
const minutes = parseInt(minutesInput.value);
const journal = journalInput.value.trim();
if (isNaN(minutes) || minutes <= 0) {
alert('Please enter a valid number of minutes');
return;
}
// Get current habit data
const habitData = JSON.parse(localStorage.getItem(`habit_${habit}`)) || {
days: {},
streak: 0,
longestStreak: 0,
totalCount: 0,
totalMinutes: 0
};
// Check if this date already exists
if (habitData.days[date]) {
// Subtract previous minutes
habitData.totalMinutes -= habitData.days[date].minutes;
}
// Update record for selected date
habitData.days[date] = {
minutes: minutes,
timestamp: new Date().toISOString(),
journal: journal
};
// Calculate streak
updateStreaks(habitData);
// Update total data
habitData.totalCount = Object.keys(habitData.days).length;
habitData.totalMinutes += minutes;
// Save to localStorage
localStorage.setItem(`habit_${habit}`, JSON.stringify(habitData));
// Update UI
updateHabitStats(habit, habitData);
// Update heatmap
const level = getActivityLevel(minutes);
const dayEl = document.querySelector(`.habit-day[data-date="${date}"][data-habit="${habit}"]`);
if (dayEl) {
dayEl.className = `habit-day level-${level}`;
}
// Close modal
document.body.removeChild(modal);
});
// Handle keyboard events
document.addEventListener('keydown', function escHandler(e) {
if (e.key === 'Escape') {
document.body.removeChild(modal);
document.removeEventListener('keydown', escHandler);
}
});
}
// Toggle habit day status using modal interface
function toggleHabitDay(dayEl) {
const habit = dayEl.dataset.habit;
const date = dayEl.dataset.date;
// Get current habit data
const habitData = JSON.parse(localStorage.getItem(`habit_${habit}`)) || {
days: {},
streak: 0,
longestStreak: 0,
totalCount: 0,
totalMinutes: 0
};
// If the date already exists, delete it
if (habitData.days[date]) {
if (confirm(`Remove ${getHabitName(habit)} entry for ${formatDate(new Date(date))}?`)) {
habitData.totalMinutes -= habitData.days[date].minutes;
delete habitData.days[date];
dayEl.className = 'habit-day level-0';
// Update statistics
habitData.totalCount = Object.keys(habitData.days).length;
updateStreaks(habitData);
// Save to localStorage
localStorage.setItem(`habit_${habit}`, JSON.stringify(habitData));
// Update UI
updateHabitStats(habit, habitData);
}
return;
}
// Otherwise show the logging modal with the selected date
// Create modal overlay
const modal = document.createElement('div');
modal.className = 'habit-modal';
// Parse date for the modal
const selectedDate = new Date(date);
const formattedDate = formatDate(selectedDate, 'MMM dd, yyyy');
// Create modal content
modal.innerHTML = `
<div class="habit-modal-content">
<div class="habit-modal-header">
<h3>${getHabitName(habit)}</h3>
<button class="habit-modal-close">esc</button>
</div>
<div class="habit-modal-body">
<div class="habit-modal-row">
<label>Date:</label>
<input type="date" id="habit-date" value="${date}" readonly>
</div>
<div class="habit-modal-row">
<label>Minutes:</label>
<input type="number" id="habit-minutes" value="30" min="1">
</div>
<div class="habit-modal-row">
<label>Journal entry:</label>
<textarea id="habit-journal" placeholder="Write about your ${getHabitName(habit).toLowerCase()} session..."></textarea>
</div>
<button class="habit-modal-save">Save</button>
</div>
</div>
`;
// Add modal to the page
document.body.appendChild(modal);
// Focus on minutes input
setTimeout(() => document.getElementById('habit-minutes').focus(), 100);
// Add event listeners
const closeBtn = modal.querySelector('.habit-modal-close');
closeBtn.addEventListener('click', () => {
document.body.removeChild(modal);
});
// Close when clicking outside
modal.addEventListener('click', (e) => {
if (e.target === modal) {
document.body.removeChild(modal);
}
});
// Handle save button
const saveBtn = modal.querySelector('.habit-modal-save');
saveBtn.addEventListener('click', () => {
const dateInput = document.getElementById('habit-date');
const minutesInput = document.getElementById('habit-minutes');
const journalInput = document.getElementById('habit-journal');
const entryDate = dateInput.value;
const minutes = parseInt(minutesInput.value);
const journal = journalInput.value.trim();
if (isNaN(minutes) || minutes <= 0) {
alert('Please enter a valid number of minutes');
return;
}
// Update record for selected date
habitData.days[entryDate] = {
minutes: minutes,
timestamp: new Date().toISOString(),
journal: journal
};
// Update total data
habitData.totalCount = Object.keys(habitData.days).length;
habitData.totalMinutes += minutes;
// Calculate streak
updateStreaks(habitData);
// Save to localStorage
localStorage.setItem(`habit_${habit}`, JSON.stringify(habitData));
// Update UI
updateHabitStats(habit, habitData);
// Update heatmap
const level = getActivityLevel(minutes);
dayEl.className = `habit-day level-${level}`;
// Close modal
document.body.removeChild(modal);
});
// Handle keyboard events
document.addEventListener('keydown', function escHandler(e) {
if (e.key === 'Escape') {
document.body.removeChild(modal);
document.removeEventListener('keydown', escHandler);
}
});
}
// Update habit statistics
function updateHabitStats(habit, data) {
const streakEl = document.getElementById(`${habit}-streak`);
const currentEl = document.getElementById(`${habit}-current`);
const totalEl = document.getElementById(`${habit}-total`);
const avgEl = document.getElementById(`${habit}-avg`);
// Only update if elements exist
if (streakEl) streakEl.textContent = data.longestStreak || 0;
if (currentEl) currentEl.textContent = data.currentStreak || 0;
if (totalEl) totalEl.textContent = data.count || 0;
if (avgEl) avgEl.textContent = data.avgMinutes ? data.avgMinutes.toFixed(2) : '0.00';
}
// Calculate consecutive days
function updateStreaks(habitData) {
const dates = Object.keys(habitData.days).sort();
if (dates.length === 0) {
habitData.streak = 0;
habitData.longestStreak = 0;
return;
}
// Calculate current streak
let currentStreak = 1;
const today = formatDate(new Date(), 'yyyy-MM-dd');
const yesterday = formatDate(new Date(Date.now() - 86400000), 'yyyy-MM-dd');
// Check if there's a record for today or yesterday, if not the streak is 0
if (!habitData.days[today] && !habitData.days[yesterday]) {
habitData.streak = 0;
} else {
// If there's a record for today, start counting from today
// If no record for today but there's one for yesterday, start from yesterday
const startDate = habitData.days[today] ? today : yesterday;
const startIdx = dates.indexOf(startDate);
if (startIdx >= 0) {
for (let i = startIdx; i > 0; i--) {
const currentDate = new Date(dates[i]);
const prevDate = new Date(dates[i-1]);
// Check if the dates are consecutive
const diffDays = Math.round((currentDate - prevDate) / (1000 * 60 * 60 * 24));
if (diffDays === 1) {
currentStreak++;
} else {
break;
}
}
}
habitData.streak = currentStreak;
}
// Update longest streak
if (currentStreak > habitData.longestStreak) {
habitData.longestStreak = currentStreak;
}
}
// Get activity level based on duration
function getActivityLevel(minutes) {
if (minutes < 15) return 1;
if (minutes < 30) return 2;
if (minutes < 60) return 3;
return 4;
}
// Get habit name in English
function getHabitName(habit) {
const names = {
'meditation': 'Meditation',
'exercise': 'Exercise',
'reading': 'Reading'
};
return names[habit] || habit;
}
// Format date in English
function formatDate(date, format = 'MMM dd, yyyy') {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
if (format === 'yyyy-MM-dd') {
return `${year}-${month}-${day}`;
}
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const monthName = months[date.getMonth()];
return `${monthName} ${day}, ${year}`;
}