Work Session Length Analyzer
Log Work Sessions
Analyze Session Data
Log New Work Session
☆☆☆☆☆
Recently Logged Sessions (Last 10)
Analysis Configuration
Analysis for Period:
Total Sessions Logged: 0
Total Productive Time: 0h 0m
Average Session Length: 0m
Average Focus Level: N/A
Overall Time Variance (Actual - Planned): 0h 0m
Distribution of Session Lengths
Avg. Focus by Session Length
Sessions by Hour of Day
Avg. Session Length by Day of Week
No data for this period.
'); return; } let totalDurationSum = 0; let totalFocusSum = 0; let focusRatedSessions = 0; let totalPlannedDurationSum = 0; let sessionsWithPlan = 0; const lengthBuckets = { "<30m": 0, "30-60m": 0, "61-90m": 0, "91-120m": 0, ">120m": 0 }; const focusByLength = { "<30m": {sum:0, count:0}, "30-60m": {sum:0, count:0}, "61-90m": {sum:0, count:0}, "91-120m": {sum:0, count:0}, ">120m": {sum:0, count:0} }; const sessionsByHour = Array(24).fill(0); const lengthByDayOfWeek = {0:{sum:0,count:0},1:{sum:0,count:0},2:{sum:0,count:0},3:{sum:0,count:0},4:{sum:0,count:0},5:{sum:0,count:0},6:{sum:0,count:0}}; // 0=Sun, 6=Sat filteredLogs.forEach(log => { totalDurationSum += log.durationMinutes; if (log.focusLevel && log.focusLevel > 0) { totalFocusSum += log.focusLevel; focusRatedSessions++; } if (log.plannedDurationMinutes !== null && log.plannedDurationMinutes > 0) { totalPlannedDurationSum += log.plannedDurationMinutes; sessionsWithPlan++; } // Length Distribution & Focus by Length let bucketKey; if (log.durationMinutes < 30) bucketKey = "<30m"; else if (log.durationMinutes <= 60) bucketKey = "30-60m"; else if (log.durationMinutes <= 90) bucketKey = "61-90m"; else if (log.durationMinutes <= 120) bucketKey = "91-120m"; else bucketKey = ">120m"; lengthBuckets[bucketKey]++; if (log.focusLevel && log.focusLevel > 0) { focusByLength[bucketKey].sum += log.focusLevel; focusByLength[bucketKey].count++; } // Sessions by Hour const startHour = parseInt(log.startTime.split(':')[0]); sessionsByHour[startHour]++; // Avg Length by Day of Week const dayOfWeek = new Date(log.date + "T00:00:00").getDay(); lengthByDayOfWeek[dayOfWeek].sum += log.durationMinutes; lengthByDayOfWeek[dayOfWeek].count++; }); totalSessionsSpan.textContent = filteredLogs.length; totalProductiveTimeSpan.textContent = formatDurationFromMinutes(totalDurationSum); avgSessionLengthSpan.textContent = formatDurationFromMinutes(filteredLogs.length > 0 ? totalDurationSum / filteredLogs.length : 0); avgFocusLevelSpan.textContent = focusRatedSessions > 0 ? (totalFocusSum / focusRatedSessions).toFixed(1) + "/5" : "N/A"; const timeVariance = sessionsWithPlan > 0 ? totalDurationSum - totalPlannedDurationSum : 0; overallTimeVarianceSpan.textContent = formatDurationFromMinutes(timeVariance); overallTimeVarianceSpan.style.color = timeVariance === 0 ? 'var(--dark-text)' : (timeVariance > 0 ? 'var(--danger-color)' : 'var(--accent-color)'); renderGenericBarChart(sessionLengthDistChartDiv, lengthBuckets, "Sessions"); const avgFocusData = {}; for(const key in focusByLength){ avgFocusData[key] = focusByLength[key].count > 0 ? (focusByLength[key].sum / focusByLength[key].count) : 0; } renderGenericBarChart(focusByLengthChartDiv, avgFocusData, "Avg Focus", 5); // Max value 5 for focus chart const sessionsByHourData = {}; sessionsByHour.forEach((count, hr) => { if(count > 0) sessionsByHourData[`${String(hr).padStart(2,'0')}:00`] = count; }); renderGenericBarChart(sessionsByHourChartDiv, sessionsByHourData, "Sessions"); const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const avgLengthByDayData = {}; dayNames.forEach((name, index) => { avgLengthByDayData[name] = lengthByDayOfWeek[index].count > 0 ? (lengthByDayOfWeek[index].sum / lengthByDayOfWeek[index].count) : 0; }); renderGenericBarChart(avgLengthByDayOfWeekChartDiv, avgLengthByDayData, "Avg Mins"); analysisOutputDiv.style.display = 'block'; }); function renderGenericBarChart(chartElement, data, valueSuffix = "", YAxisMaxValue = null) { chartElement.innerHTML = ''; const keys = Object.keys(data); if (keys.length === 0) { chartElement.innerHTML = `No data for this period.
`; return; } let maxValue = YAxisMaxValue !== null ? YAxisMaxValue : 0; if(YAxisMaxValue === null) { // Calculate max if not provided Object.values(data).forEach(val => { if (val > maxValue) maxValue = val; }); if (maxValue === 0) maxValue = 1; } keys.forEach((key, index) => { const value = data[key]; const barGroup = document.createElement('div'); barGroup.className = 'chart-bar-group'; const bar = document.createElement('div'); bar.className = 'chart-bar'; bar.style.height = `${(value / maxValue) * 100}%`; // Cycle through some predefined colors for variety const colors = [varToRGB('--info-color'), varToRGB('--accent-color'), varToRGB('--primary-color'), varToRGB('--warning-color', true), varToRGB('--danger-color', true)]; const barColor = colors[index % colors.length]; if(typeof barColor === 'string') bar.style.backgroundColor = barColor; //If it's already a var() string else bar.style.backgroundColor = `rgb(${barColor.r},${barColor.g},${barColor.b})`; bar.textContent = value.toFixed(valueSuffix === "Avg Focus" || valueSuffix === "Avg Mins" ? 1:0); bar.title = `${key}: ${value.toFixed(1)} ${valueSuffix}`; const label = document.createElement('div'); label.className = 'chart-label'; label.textContent = key; barGroup.appendChild(bar); barGroup.appendChild(label); chartElement.appendChild(barGroup); }); } // --- PDF Download --- downloadAnalysisReportPdfBtn.addEventListener('click', async () => { if (analysisOutputDiv.style.display === 'none') { alert('Please generate an analysis first.'); return; } const { jsPDF } = window.jspdf; const doc = new jsPDF('p', 'pt', 'a4'); const margin = 40; let yPos = margin; const pageWidth = doc.internal.pageSize.getWidth(); doc.setFontSize(18); doc.setTextColor(varToRGB('--primary-color').r, varToRGB('--primary-color').g, varToRGB('--primary-color').b); doc.text('Work Session Length Analysis', pageWidth / 2, yPos, { align: 'center' }); yPos += 20; doc.setFontSize(11); doc.setTextColor(100); doc.text(`Period: ${analysisPeriodDisplaySpan.textContent}`, pageWidth / 2, yPos, { align: 'center' }); yPos += 15; doc.text(`Generated: ${new Date().toLocaleString()}`, pageWidth / 2, yPos, { align: 'center' }); yPos += 25; const summaryPdfData = [ ['Total Sessions Logged:', totalSessionsSpan.textContent], ['Total Productive Time:', totalProductiveTimeSpan.textContent], ['Average Session Length:', avgSessionLengthSpan.textContent], ['Average Focus Level:', avgFocusLevelSpan.textContent], ['Overall Time Variance (Actual - Planned):', overallTimeVarianceSpan.textContent] ]; doc.autoTable({ startY: yPos, body: summaryPdfData, theme: 'plain', styles: {fontSize:10}, columnStyles: {0:{fontStyle:'bold', cellWidth:250}}}); yPos = doc.lastAutoTable.finalY + 15; async function addChartToPdf(chartContainerId, titleText, currentY) { const chartContainer = document.getElementById(chartContainerId); if (html2canvas && chartContainer && chartContainer.querySelector('.chart')?.children.length > 0) { if (currentY > doc.internal.pageSize.getHeight() - 200) { doc.addPage(); currentY = margin; } doc.setFontSize(12); doc.setTextColor(varToRGB('--primary-color').r, varToRGB('--primary-color').g, varToRGB('--primary-color').b); doc.text(titleText, margin, currentY); currentY += 15; try { const canvas = await html2canvas(chartContainer.querySelector('.chart'), { scale: 1.5, backgroundColor: getComputedStyle(document.documentElement).getPropertyValue('--light-bg').trim() }); const imgData = canvas.toDataURL('image/png'); const imgProps = doc.getImageProperties(imgData); const pdfImgWidth = pageWidth - 2 * margin; const pdfImgHeight = Math.min(180, (imgProps.height * pdfImgWidth) / imgProps.width); doc.addImage(imgData, 'PNG', margin, currentY, pdfImgWidth, pdfImgHeight); currentY += pdfImgHeight + 10; } catch (e) { console.error("Chart to PDF error:", e); doc.setTextColor(255,0,0).text("Chart could not be rendered.", margin, currentY); currentY+=15; } } return currentY; } yPos = await addChartToPdf('sessionLengthDistChartContainer', 'Distribution of Session Lengths', yPos); yPos = await addChartToPdf('focusByLengthChartContainer', 'Average Focus by Session Length', yPos); yPos = await addChartToPdf('sessionsByHourChartContainer', 'Sessions by Hour of Day', yPos); yPos = await addChartToPdf('avgLengthByDayOfWeekChartContainer', 'Average Session Length by Day of Week', yPos); // Detailed Log (optional, can be long) // For this version, PDF focus is on summary and charts. // If detailed log is needed, re-filter logs for period and add with autoTable. doc.save(`Work_Session_Analysis_${analysisPeriodDisplaySpan.textContent.replace(/\s-\s/g,'_to_')}.pdf`); }); function varToRGB(varName, asArray = false) { const colorHex = getComputedStyle(document.documentElement).getPropertyValue(varName).trim(); if (!colorHex.startsWith('#')) { // Fallback for non-hex values (e.g. 'purple') const namedColors = {"purple":"#800080", /* add more if needed */}; const hexFromName = namedColors[colorHex.toLowerCase()]; if(hexFromName) colorHex = hexFromName; else return asArray ? [0,0,0] : {r:0,g:0,b:0}; } const r = parseInt(colorHex.slice(1, 3), 16); const g = parseInt(colorHex.slice(3, 5), 16); const b = parseInt(colorHex.slice(5, 7), 16); return asArray ? [r,g,b] : {r,g,b}; } // --- Initializations --- renderRecentSessionsList(); setDefaultAnalysisDates(); // Optionally auto-run analysis on load for default period if logs exist: if (workSessionLogs.length > 0) { analyzeSessionsBtn.click(); } else { analysisOutputDiv.style.display = 'none'; // Ensure it's hidden if no logs } })();