`).join('');
}
function deleteSession(id) {
if (confirm('Are you sure you want to delete this session?')) {
studySessions = studySessions.filter(s => s.id !== id);
saveSessions();
renderHistory();
renderChart();
}
}
function renderChart() {
const last7Days = {};
for (let i = 6; i >= 0; i--) {
const d = new Date();
d.setDate(d.getDate() - i);
const key = d.toISOString().split('T')[0];
last7Days[key] = 0;
}
studySessions.forEach(session => {
if (last7Days.hasOwnProperty(session.date)) {
last7Days[session.date] += session.duration;
}
});
const chartData = {
labels: Object.keys(last7Days).map(d => new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })),
datasets: [{
label: 'Minutes Studied',
data: Object.values(last7Days),
backgroundColor: 'rgba(59, 130, 246, 0.5)',
borderColor: 'rgba(59, 130, 246, 1)',
borderWidth: 1,
borderRadius: 5,
}]
};
if (studyChart) {
studyChart.destroy();
}
studyChart = new Chart(chartCanvas, {
type: 'bar',
data: chartData,
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
title: { display: true, text: 'Minutes' }
}
},
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: (context) => `${context.parsed.y} minutes`
}
}
}
}
});
}
// --- PDF Generation ---
async function generatePdf() {
const chartImage = studyChart.toBase64Image();
const tableRows = studySessions.map(s => `
| ${new Date(s.date).toLocaleDateString()} |
${s.subject} |
${s.duration} |
${s.rating}/5 |
${s.notes || ''} |
`).join('');
pdfContentArea.innerHTML = `
Study Habit Report
Study Time (Last 7 Days)
Full Session Log
| Date |
Subject |
Duration (min) |
Focus |
Notes |
${tableRows}
`;
pdfContentArea.style.display = 'block';
pdfContentArea.style.position = 'absolute';
pdfContentArea.style.left = '-9999px';
pdfContentArea.style.width = '1000px';
try {
const canvas = await html2canvas(pdfContentArea, { scale: 2 });
const imgData = canvas.toDataURL('image/png');
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({ orientation: 'landscape', unit: 'px', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const imgHeight = canvas.height * pdfWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, imgHeight);
pdf.save(`Study-Habit-Report-${new Date().toISOString().split('T')[0]}.pdf`);
} catch (error) {
console.error("Failed to generate PDF:", error);
alert("Sorry, there was an error creating the PDF file.");
} finally {
pdfContentArea.style.display = 'none';
}
}
// --- Event Listeners ---
tabButtons.forEach(btn => btn.addEventListener('click', () => setActiveTab(btn.dataset.tab)));
logSessionBtn.addEventListener('click', logSession);
downloadPdfBtn.addEventListener('click', generatePdf);
historyLog.addEventListener('click', (e) => {
if (e.target.classList.contains('delete-btn')) {
const id = parseInt(e.target.dataset.id, 10);
deleteSession(id);
}
});
// --- Initial State ---
sessionDateInput.value = new Date().toISOString().split('T')[0];
setActiveTab('log');
});