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
| // --- 配置 --- const FILE_PATH = "睡眠日记-2025.md"; // 确保此路径与你的日志文件完全一致! // --- 配置结束 ---
// --- 辅助函数与常量 --- const IS_IOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; const formatDurationFromMs = (ms) => { if (isNaN(ms) || ms < 0) return "无效时长"; const totalMinutes = Math.round(ms / (1000 * 60)); const hours = Math.floor(totalMinutes / 60); const minutes = totalMinutes % 60; return `${hours}时 ${minutes}分`; }; const formatAvgDurationHours = (ms) => { if (isNaN(ms) || ms < 0) return "无效"; return (ms / (1000 * 60 * 60)).toFixed(2); }; const groupBy = (data, keyFn) => { return data.reduce((acc, item) => { const key = keyFn(item); if (!acc[key]) acc[key] = []; acc[key].push(item); return acc; }, {}); }; const calculateAverages = (group) => { const total = group.length; if (total === 0) return null; const avgDurationMs = group.reduce((sum, r) => sum + r.durationMillis, 0) / total;
const calculateMeanTime = (times) => { if (times.length === 0) return null; const radians = times.map(t => (t / 24) * 2 * Math.PI); const sinSum = radians.reduce((sum, r) => sum + Math.sin(r), 0) / times.length; const cosSum = radians.reduce((sum, r) => sum + Math.cos(r), 0) / times.length; let meanAngle = Math.atan2(sinSum, cosSum); if (meanAngle < 0) meanAngle += 2 * Math.PI; let meanHours = (meanAngle / (2 * Math.PI)) * 24; const hours = Math.floor(meanHours); const minutes = Math.round((meanHours - hours) * 60); return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; };
return { "记录天数": total, "平均入睡": calculateMeanTime(group.filter(r => r.bedtimeHour !== undefined).map(r => r.bedtimeHour)), "平均起床": calculateMeanTime(group.filter(r => r.waketimeHour !== undefined).map(r => r.waketimeHour)), "平均时长": formatDurationFromMs(avgDurationMs), "avgDurationMs": avgDurationMs }; }; // --- 1. 数据解析模块 --- function parseSleepData(page) { if (!page || !page.file || !page.file.lists || page.file.lists.length === 0) { dv.paragraph("❌ **错误:** 找不到文件或文件中没有数据。"); return null; } return page.file.lists .where(item => item.date && (item.duration || (item.bed && item.wake))) .map(item => { try { const dateStr = item.date.toString().substring(0, 10); let durationMillis, bedtimeHour, waketimeHour;
if (item.duration) { const [hours, minutes] = item.duration.toString().split(':').map(Number); if (isNaN(hours) || isNaN(minutes)) return null; durationMillis = (hours * 60 + minutes) * 60 * 1000; } else { const bedtime = dv.date(`${dateStr}T${item.bed}`); let waketime = dv.date(`${dateStr}T${item.wake}`); if (!bedtime || !waketime) return null; if (waketime <= bedtime) waketime = waketime.plus({ days: 1 }); durationMillis = waketime.toMillis() - bedtime.toMillis(); }
if (item.bed) { const bedtime = dv.date(`${dateStr}T${item.bed}`); if (bedtime) bedtimeHour = bedtime.hour + bedtime.minute / 60; } if (item.wake) { const waketime = dv.date(`${dateStr}T${item.wake}`); if (waketime) waketimeHour = waketime.hour + waketime.minute / 60; }
return { date: dv.date(dateStr), durationMillis, bedtimeHour, waketimeHour }; } catch (e) { console.warn(`[DataviewJS Sleep Report] 解析数据失败,已跳过此行: ${item.text}`, e); return null; } }) .filter(item => item !== null && !isNaN(item.durationMillis)) .values; } // --- 2. 核心统计计算模块 --- function calculateAllStatistics(records) { const today = dv.date('now').startOf('day'); const sevenDaysAgo = today.minus({ days: 7 }); const thirtyDaysAgo = today.minus({ days: 30 });
const stats = { recent7DaysRecords: [], recent30DaysRecords: [], byMonth: {}, byYear: {}, totalRecords: records.length, };
for (const record of records) { const recordDate = record.date; if (recordDate.ts >= thirtyDaysAgo.ts && recordDate.ts <= today.ts) { stats.recent30DaysRecords.push(record); if (recordDate.ts >= sevenDaysAgo.ts) { stats.recent7DaysRecords.push(record); } } const monthKey = recordDate.toFormat("yyyy-'年' MM'-月'"); if (!stats.byMonth[monthKey]) stats.byMonth[monthKey] = []; stats.byMonth[monthKey].push(record);
const yearKey = recordDate.year; if (!stats.byYear[yearKey]) stats.byYear[yearKey] = []; stats.byYear[yearKey].push(record); }
stats.sevenDayAvg = calculateAverages(stats.recent7DaysRecords); stats.thirtyDayAvg = calculateAverages(stats.recent30DaysRecords); stats.recent7DaysGrouped = groupBy(stats.recent7DaysRecords, r => r.date.toFormat("MM-dd")); stats.recent30DaysGrouped = groupBy(stats.recent30DaysRecords, r => r.date.toFormat("MM-dd")); stats.limitedMonthlyData = Object.fromEntries(Object.entries(stats.byMonth).sort((a, b) => b.localeCompare(a)).slice(0, 12)); stats.limitedYearlyData = Object.fromEntries(Object.entries(stats.byYear).sort((a, b) => b.localeCompare(a)).slice(0, 12));
return stats; } // --- 3. 报告渲染模块 --- const calculateDistribution = (group, type) => { const hours = type === 'bedtime' ? group.map(r => r.bedtimeHour) : group.map(r => r.waketimeHour); const validHours = hours.filter(h => h !== undefined); const dist = {}; validHours.forEach(h => { const bucket = `${String(Math.floor(h)).padStart(2, '0')}:00`; dist[bucket] = (dist[bucket] || 0) + 1; }); return dist; }; const renderTable = (header, data) => { const rows = Object.keys(data).sort((a, b) => b.localeCompare(a)).map(key => { const avg = calculateAverages(data[key]); return [avg.平均时长, avg.平均入睡 || "无数据", avg.平均起床 || "无数据", key]; }); dv.table(["平均时长", "平均入睡", "平均起床", header], rows); }; const createChartCanvas = () => { const canvas = dv.el("canvas"); canvas.style.width = '100%'; canvas.style.height = '300px'; canvas.width = window.innerWidth * window.devicePixelRatio; canvas.height = 300 * window.devicePixelRatio; dv.container.appendChild(canvas); return canvas.getContext('2d'); }; const renderAvgChart = (data, title) => { const labels = Object.keys(data).sort((a, b) => a.localeCompare(b)); const chartValues = labels.map(key => (calculateAverages(data[key]).avgDurationMs / (1000 * 60 * 60)).toFixed(2)); const ctx = createChartCanvas(); new Chart(ctx, { type: 'bar', data: { labels, datasets: [{ label: `${title} 平均睡眠时长 (小时)`, data: chartValues, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, title: { display: true, text: '小时' } } }, animation: { duration: IS_IOS ? 0 : 1000 } } }); }; const renderTrendChart = (data, title, days) => { const labels = Object.keys(data).sort((a, b) => a.localeCompare(b)); const chartValues = labels.map(key => formatAvgDurationHours(calculateAverages(data[key]).avgDurationMs)); const ctx = createChartCanvas(); new Chart(ctx, { type: 'line', data: { labels, datasets: [{ label: `${title} 睡眠时长趋势 (小时)`, data: chartValues, backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 2, fill: false, tension: 0.3 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, title: { display: true, text: '小时' } } }, animation: { duration: IS_IOS ? 0 : 1000 } } }); }; const renderStackedDistChart = (data, title) => { const bedtimeDist = calculateDistribution(data, 'bedtime'); const waketimeDist = calculateDistribution(data, 'waketime'); const allLabels = [...new Set([...Object.keys(bedtimeDist), ...Object.keys(waketimeDist)])].sort(); const ctx = createChartCanvas(); new Chart(ctx, { type: 'bar', data: { labels: allLabels, datasets: [{ label: '入睡时间', data: allLabels.map(label => bedtimeDist[label] || 0), backgroundColor: 'rgba(54, 162, 235, 0.4)', stack: 'Stack 0' }, { label: '起床时间', data: allLabels.map(label => waketimeDist[label] || 0), backgroundColor: 'rgba(75, 192, 192, 0.4)', stack: 'Stack 0' }] }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { stacked: true }, y: { stacked: true } }, animation: { duration: IS_IOS ? 0 : 1000 } } }); }; function renderReport(stats) { if (stats.totalRecords === 0) { dv.paragraph("✅ 文件已找到,但未能解析出任何有效数据行。请检查数据格式。"); return; } dv.header(4, `近7天睡眠趋势 平均: ${stats.sevenDayAvg ? formatAvgDurationHours(stats.sevenDayAvg.avgDurationMs) : '无数据'}小时`); renderTrendChart(stats.recent7DaysGrouped, "近7天", 7); dv.header(4, `最近30天睡眠时长趋势 平均: ${stats.thirtyDayAvg ? formatAvgDurationHours(stats.thirtyDayAvg.avgDurationMs) : '无数据'}小时`); renderTrendChart(stats.recent30DaysGrouped, "最近30天", 30); dv.header(4, "最近30天入睡/起床时间分布"); renderStackedDistChart(stats.recent30DaysRecords, "最近30天"); dv.header(3, "按月统计"); renderTable("月份", stats.limitedMonthlyData); renderAvgChart(stats.limitedMonthlyData, "月"); dv.header(3, "按年统计"); renderTable("年份", stats.limitedYearlyData); renderAvgChart(stats.limitedYearlyData, "年"); dv.el('p', `🛌 睡眠记录共 ${stats.totalRecords} 条`, { cls: 'sleep-record-count' }); } // --- 主执行逻辑 --- const main = () => { const style = document.createElement('style'); style.textContent = ` .dataview.container { width: 100% !important; max-width: 100% !important; padding: 0 !important; margin: 0 !important; } canvas { width: 100% !important; max-height: 350px !important; } .sleep-record-count { font-size: 0.8em; color: var(--text-muted); text-align: left; margin-top: 15px; } @media (max-width: 600px) { canvas { max-height: 300px !important; } } `; document.head.appendChild(style); const page = dv.page(FILE_PATH); const records = parseSleepData(page); if (records) { const statistics = calculateAllStatistics(records); renderReport(statistics); } }; if (typeof Chart === 'undefined') { const script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js'; document.head.appendChild(script); script.onload = main; script.onerror = () => dv.paragraph("❌ 无法加载 Chart.js 库,图表无法显示。"); } else { main(); }
|