Spaces:
Running
Running
File size: 15,535 Bytes
41eab66 | 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 | // Mock data for 30 days - Bangkok office worker marathon runner
const mockData = {
days: Array.from({ length: 30 }, (_, i) => {
const dayOffset = 29 - i;
const date = new Date();
date.setDate(date.getDate() - dayOffset);
// Simulate realistic patterns
const isWeekend = date.getDay() === 0 || date.getDay() === 6;
const isHotDay = date.getMonth() >= 2 && date.getMonth() <= 5; // March-May hot season
const pollutionLevel = Math.random() > 0.7 ? 'high' : 'normal';
return {
date: date.toISOString().split('T')[0],
recoveryScore: Math.max(20, Math.min(100, Math.floor(
70 + (isWeekend ? 10 : 0) - (pollutionLevel === 'high' ? 15 : 0) - (isHotDay ? 5 : 0) + Math.random() * 20 - 10
))),
hrv: Math.floor(40 + Math.random() * 60 + (isWeekend ? 15 : 0) - (pollutionLevel === 'high' ? 10 : 0)),
rhr: Math.floor(55 + Math.random() * 15 + (pollutionLevel === 'high' ? 5 : 0)),
sleepScore: Math.floor(65 + Math.random() * 25 + (isWeekend ? 8 : 0)),
respiratoryRate: Math.floor(14 + Math.random() * 4 + (Math.random() > 0.9 ? 3 : 0)),
tempDelta: (Math.random() * 1 - 0.5).toFixed(2),
aqi_pm25: pollutionLevel === 'high' ? Math.floor(100 + Math.random() * 150) : Math.floor(20 + Math.random() * 50),
ambientTemp: isHotDay ? Math.floor(35 + Math.random() * 5) : Math.floor(28 + Math.random() * 5),
trafficIndex: Math.floor(2 + Math.random() * 6 + (isWeekend ? -3 : 0)),
spicyIntake: Math.floor(Math.random() * 4),
sugarIntake: Math.floor(Math.random() * 6),
sodiumIntake: Math.floor(Math.random() * 6),
sleepDebt: Math.floor(Math.random() * 3 - (isWeekend ? 2 : 0)),
perceivedStress: Math.floor(3 + Math.random() * 5 + (pollutionLevel === 'high' ? 2 : 0))
};
})
};
// Current day data
const todayData = mockData.days[mockData.days.length - 1];
// Utility functions
function getScoreColor(score) {
if (score >= 80) return '#10b981'; // Green
if (score >= 60) return '#f59e0b'; // Yellow
return '#ef4444'; // Red
}
function getScoreText(score) {
if (score >= 80) return { text: 'พร้อมรบ', color: 'text-green-500' };
if (score >= 60) return { text: 'ปานกลาง', color: 'text-yellow-500' };
return { text: 'ต้องพัก', color: 'text-red-500' };
}
function formatDateThai(dateString) {
const date = new Date(dateString);
const options = { year: 'numeric', month: 'long', day: 'numeric', locale: 'th-TH' };
return date.toLocaleDateString('th-TH', options);
}
function calculateTrend(values) {
const recent = values.slice(-7);
const previous = values.slice(-14, -7);
const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length;
const prevAvg = previous.reduce((a, b) => a + b, 0) / previous.length;
return recentAvg - prevAvg;
}
// Initialize app
document.addEventListener('DOMContentLoaded', function() {
// Set last update time
document.getElementById('lastUpdate').textContent = formatDateThai(new Date().toISOString());
// Load environmental warnings
loadEnvironmentalWarnings();
// Load daily suggestions
loadDailySuggestions();
// Initialize HRV chart
initHRVChart();
// Load sleep data
loadSleepData();
// Load nutrition matrix
loadNutritionMatrix();
// Load seasonal report
loadSeasonalReport();
// Initialize journal form data
initJournalForm();
});
// Tab navigation
function showSection(sectionName) {
// Hide all sections
document.querySelectorAll('.content-section').forEach(section => {
section.classList.add('hidden');
});
// Show selected section
document.getElementById(`${sectionName}-section`).classList.remove('hidden');
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active', 'bg-secondary');
btn.classList.add('bg-cardBg');
});
event.target.closest('.tab-btn').classList.add('active', 'bg-secondary');
event.target.closest('.tab-btn').classList.remove('bg-cardBg');
// Trigger chart resize if needed
if (sectionName === 'trends' && window.trendsChartInstance) {
setTimeout(() => window.trendsChartInstance.resize(), 100);
}
}
// Environmental warnings
function loadEnvironmentalWarnings() {
const warningsContainer = document.getElementById('environmental-warnings');
const warnings = [];
if (todayData.aqi_pm25 > 100) {
warnings.push(`🌫️ ค่า PM 2.5 สูง (${todayData.aqi_pm25} μg/m³) อาจลด HRV ของคุณได้`);
}
if (todayData.ambientTemp > 35) {
warnings.push(`🌡️ อุณหภูมิสูง (${todayData.ambientTemp}°C) เพิ่มความเครียดในการออกกำลังกาย`);
}
if (todayData.trafficIndex > 7) {
warnings.push(`🚗 รถติดหนัก (ระดับ ${todayData.trafficIndex}/10) เพิ่มความเครียดทางอารมณ์`);
}
warningsContainer.innerHTML = warnings.length > 0
? warnings.map(w => `<div class="flex items-start"><span class="mr-2">•</span><span>${w}</span></div>`).join('')
: '<div class="text-green-500">✅ สภาพแวดล้อมอยู่ในเกณฑ์ดี</div>';
}
// Daily suggestions
function loadDailySuggestions() {
const suggestionsContainer = document.getElementById('daily-suggestions');
const suggestions = [];
if (todayData.recoveryScore < 60) {
suggestions.push(`⚠️ ควรลดความตึงเครียดวันนี้ไม่เกิน 12.5 จุด`);
suggestions.push(`💤 แนะนำให้นอนกลางวัน 20-30 นาที`);
} else if (todayData.recoveryScore < 80) {
suggestions.push(`💪 สามารถฝึกกลางได้ตามปกติ แต่ควรหลีกเลี่ยงช่วงเที่ยง`);
suggestions.push(`🥤 เพิ่มการดื่มน้ำ 2 เท่า จากภาวะอากาศร้อน`);
} else {
suggestions.push(`🔥 พร้อมสำหรับการฝึกซ้อมหนักวันนี้!`);
suggestions.push(`🏃♂️ เหมาะสำหรับการวิ่งระยะไกล`);
}
if (todayData.spicyIntake > 2) {
suggestions.push(`🌶️ ระวังอาหารเผ็ดอาจทำให้ RHR สูงขึ้นตอนนอน`);
}
suggestionsContainer.innerHTML = suggestions.map(s =>
`<div class="flex items-start"><span class="mr-2">•</span><span>${s}</span></div>`
).join('');
}
// HRV Chart
function initHRVChart() {
const ctx = document.getElementById('hrvChart').getContext('2d');
const last7Days = mockData.days.slice(-7);
new Chart(ctx, {
type: 'line',
data: {
labels: last7Days.map(d => formatDateThai(d.date).split(' ')[0]),
datasets: [{
label: 'HRV (ms)',
data: last7Days.map(d => d.hrv),
borderColor: '#14b8a6',
backgroundColor: 'rgba(20, 184, 166, 0.1)',
tension: 0.4,
yAxisID: 'y'
}, {
label: 'ความเครียด',
data: last7Days.map(d => d.perceivedStress),
borderColor: '#f97316',
backgroundColor: 'rgba(249, 115, 22, 0.1)',
tension: 0.4,
yAxisID: 'y1'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'index',
intersect: false
},
plugins: {
legend: {
labels: {
color: '#9ca3af'
}
}
},
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
title: {
display: true,
text: 'HRV (ms)',
color: '#9ca3af'
},
grid: {
color: 'rgba(156, 163, 175, 0.1)'
},
ticks: {
color: '#9ca3af'
}
},
y1: {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: 'ระดับความเครียด (1-10)',
color: '#9ca3af'
},
grid: {
drawOnChartArea: false
},
ticks: {
color: '#9ca3af'
}
},
x: {
ticks: {
color: '#9ca3af'
},
grid: {
color: 'rgba(156, 163, 175, 0.1)'
}
}
}
}
});
}
// Sleep data
function loadSleepData() {
// Respiratory status
const respiratoryContainer = document.getElementById('respiratory-status');
const baselineRR = 16;
const currentRR = todayData.respiratoryRate;
const diff = currentRR - baselineRR;
let status = 'good';
let message = 'อัตราการหายใจปกติ';
if (diff > 3) {
status = 'danger';
message = '⚠️ อัตราการหายใจสูงผิดปกติ อาจมีอาการป่วยเริ่มต้น';
} else if (diff > 1) {
status = 'warning';
message = 'อัตราการหายใจสูงกว่าปกติเล็กน้อย';
}
respiratoryContainer.innerHTML = `
<div class="flex justify-between items-center mb-2">
<span class="text-textSecondary">ปัจจุบัน</span>
<span class="text-2xl font-bold ${status === 'danger' ? 'text-red-500' : status === 'warning' ? 'text-yellow-500' : 'text-green-500'}">${currentRR}</span>
</div>
<div class="flex justify-between items-center mb-4">
<span class="text-textSecondary">Baseline</span>
<span class="text-xl font-medium">${baselineRR}</span>
</div>
<div class="p-3 rounded-lg bg-darkBg text-sm">
${message}
</div>
`;
// Food impact on sleep
const foodContainer = document.getElementById('food-impact-sleep');
const foodImpacts = [];
if (todayData.spicyIntake > 2) {
foodImpacts.push(`🌶️ อาหารเผ็ดมาก ทำให้ RHR สูงขึ้น ${Math.floor(Math.random() * 5 + 3)} bpm ตอนเริ่มนอน`);
}
if (todayData.sodiumIntake > 3) {
foodImpacts.push(`🧂 โซเดียมสูง อาจทำให้คุณภาพการนอนลดลง 15%`);
}
if (todayData.sugarIntake > 4) {
foodImpacts.push(`🍬 น้ำตาลสูง ทำให้ Sleep Latency เพิ่มขึ้น 20 นาที`);
}
foodContainer.innerHTML = foodImpacts.length > 0
? foodImpacts.map(i => `<div class="p-3 rounded-lg bg-darkBg text-sm">${i}</div>`).join('')
: '<div class="text-green-500">✅ อาหารวันนี้ไม่มีผลกระทบต่อการนอน</div>';
}
// Nutrition matrix
function loadNutritionMatrix() {
const container = document.getElementById('nutrition-matrix');
// Calculate average RHR on high sodium days vs normal days
const highSodiumDays = mockData.days.filter(d => d.sodiumIntake >= 4);
const normalSodiumDays = mockData.days.filter(d => d.sodiumIntake < 3);
const avgRHR_highSodium = highSodiumDays.length > 0
? highSodiumDays.reduce((sum, d) => sum + d.rhr, 0) / highSodiumDays.length
: 0;
const avgRHR_normal = normalSodiumDays.length > 0
? normalSodiumDays.reduce((sum, d) => sum + d.rhr, 0) / normalSodiumDays.length
: 0;
const diff = Math.abs(avgRHR_highSodium - avgRHR_normal).toFixed(1);
container.innerHTML = `
<div class="space-y-4">
<div class="flex justify-between items-center p-3 rounded-lg bg-darkBg">
<span>วันที่กินเค็มมาก</span>
<span class="font-bold text-red-500">${avgRHR_highSodium.toFixed(1)} bpm</span>
</div>
<div class="flex justify-between items-center p-3 rounded-lg bg-darkBg">
<span>วันที่กินปกติ</span>
<span class="font-bold text-green-500">${avgRHR_normal.toFixed(1)} bpm</span>
</div>
<div class="p-3 rounded-lg border border-primary bg-primary bg-opacity-10 text-sm">
🔍 วันที่มีโซเดียมสูงเฉลี่ย RHR สูงกว่า <strong>${diff} bpm</strong>
</div>
</div>
`;
}
// Seasonal report
function loadSeasonalReport() {
const container = document.getElementById('seasonal-report');
const hotSeasonData = mockData.days.filter(d => {
const month = new Date(d.date).getMonth();
return month >= 2 && month <= 5; // March-May
});
const avgRecoveryHotSeason = hotSeasonData.length > 0
? hotSeasonData.reduce((sum, d) => sum + d.recoveryScore, 0) / hotSeasonData.length
: 70;
container.innerHTML = `
<div class="space-y-3">
<p>📊 ช่วงเดือนมีนาคมถึงพฤษภาคม เป็นฤดูร้อนที่เครียดที่สุด</p>
<p class="p-3 rounded-lg bg-darkBg">
⚠️ ค่าเฉลี่ยพลังกายพร้อมรบในฤดูร้อน: <strong>${avgRecoveryHotSeason.toFixed(1)}</strong>
</p>
<p class="text-green-400">
💡 แนะนำ: เน้นการฟื้นตัวแบบความเย็น ลดการออกกำลังกายกลางแจ้งในช่วง 10:00-16:00
</p>
<p class="text-blue-400">
🧊 เพิ่มการดื่มน้ำเกลือแร่ อาบน้ำเย็น และใช้ห้องแอร์ 24-26°C
</p>
</div>
`;
}
// Initialize journal form data
function initJournalForm() {
const journalForm = document.querySelector('journal-form');
if (journalForm) {
journalForm.setTodayData(todayData);
}
} |